body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm working on a vue.js / nuxt.js project, applying the <a href="http://bradfrost.com/blog/post/atomic-web-design/" rel="nofollow noreferrer">Atomic Design</a> methodology, I need to do one to set the grid layout and using <a href="https://www.w3schools.com/css/css_grid.asp" rel="nofollow noreferrer">CSS Grid Layout</a>.</p> <p>I already did the component, but I think I did not do it the best way ... the code is great and not very smart, lots of manual work, I would like your opinion and help to make this component better</p> <p><code>GridLayout.vue</code></p> <pre><code>&lt;template&gt; &lt;div class="grid"&gt; &lt;style&gt; {{ css }} &lt;/style&gt; &lt;slot /&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { props: { columns: String, rows: String, areas: String, gap: String, columnGap: String, rowGap: String, // breakpoints small: Object, medium: Object, large: Object }, computed: { css () { let large = '' let finalStyle = '' // generic let generic = '' if (this.columns) generic += `grid-template-columns: ${this.columns};` if (this.rows) generic += `grid-template-rows: ${this.rows};` if (this.areas) generic += `grid-template-areas: "${this.areas}";` if (this.gap) generic += `grid-gap: ${this.gap};` if (this.columnGap) generic += `grid-column-gap: ${this.columnGap};` if (this.rowGap) generic += `grid-row-gap: ${this.rowGap};` finalStyle += ` .grid { ${generic} }` // small let small = '' if (this.small) { if (this.small.columns) small += `grid-template-columns: ${this.small.columns};` if (this.small.rows) small += `grid-template-rows: ${this.small.rows};` if (this.small.areas) small += `grid-template-areas: "${this.small.areas}";` if (this.small.gap) small += `grid-gap: ${this.small.gap};` if (this.small.columnGap) small += `grid-column-gap: ${this.small.columnGap};` if (this.small.rowGap) small += `grid-row-gap: ${this.small.rowGap};` finalStyle += `@media (max-width: 600px) { .grid { ${small} } } ` } // medium let medium = '' if (this.medium) { if (this.medium.columns) medium += `grid-template-columns: ${this.medium.columns};` if (this.medium.rows) medium += `grid-template-rows: ${this.medium.rows};` if (this.medium.areas) medium += `grid-template-areas: "${this.medium.areas}";` if (this.medium.gap) medium += `grid-gap: ${this.medium.gap};` if (this.medium.columnGap) medium += `grid-column-gap: ${this.medium.columnGap};` if (this.medium.rowGap) medium += `grid-row-gap: ${this.medium.rowGap};` finalStyle += `@media (min-width: 600px) and (max-width: 992px) { .grid { ${medium} } } ` } return finalStyle }, }, } &lt;/script&gt; &lt;style lang="scss" scoped&gt; .grid { display: grid; } &lt;/style&gt; </code></pre> <p>using component on any page.vue</p> <pre><code>&lt;template&gt; &lt;GridLayout columns="1fr 1fr 1fr 1fr" rows="auto" gap="10px" :medium="{ columns: '1fr 1fr', rows:'auto auto' }" :small="{ columns: '1fr', rows: 'auto auto auto auto', }" &gt; &lt;h1&gt;1&lt;/h1&gt; &lt;h1&gt;2&lt;/h1&gt; &lt;h1&gt;3&lt;/h1&gt; &lt;h1&gt;3&lt;/h1&gt; &lt;/GridLayout&gt; &lt;/template&gt; &lt;script&gt; import { GridLayout } from '@/components/bosons' export default { components: { GridLayout } } &lt;/script&gt; </code></pre> <p>problems</p> <blockquote> <p>1 - the style tag <code>&lt;style&gt;</code> inside ` needs to be scoped, applying only in the component itself</p> <p>2 - whenever I want new properties for the GridLayout, for example, '' child align '', I will have to add everywhere in computed, that is, <code>generic</code>, <code>small</code>, <code>medium</code>, <code>large</code></p> </blockquote> <p>Anyway, I honestly did not like what I did, I would like your opinion and help you guys.</p>
[]
[ { "body": "<p>Never heard of Atomic design till today.Read the blog and a few chapters of the book. Nothing really new, just another analogy (re-branding) for the standard modular design methods.</p>\n\n<p>To your code. </p>\n\n<p>Its not at all DRY but the various settings are consistent and can easily be changed so that you minimize the repeated code and literals.</p>\n\n<p>The following example reduces the repeated code but without knowing more about how these properties change per client/instance I cant add add anything regarding the design methods.</p>\n\n<pre><code>css() {\n const rules = {\n columns: \"grid-template-columns: ##SET##;\",\n rows: \"grid-template-rows: ##SET##;\",\n areas: \"grid-template-areas: \\\"##SET##\\\";\",\n gap: \"grid-gap: ##SET##;\",\n columnGap: \"grid-column-gap: ##SET##;\",\n rowGap: \"grid-row-gap: ##SET##;\",\n };\n const sizes = {\n default:\" .grid { ##STYLE## }\",\n small: \"@media (max-width: 600px) { .grid { ##STYLE## } } \",\n medium: \"@media (min-width: 600px) and (max-width: 992px) { .grid { ##STYLE## } } \",\n };\n var src, css = \"\";\n const rule = name =&gt; src[name] ? rules[name].replace(\"##SET##\", src[name]) : \"\";\n for (const size of Object.keys(sizes)) {\n src = size === \"default\" : this : this[size];\n if (src) {\n css += sizes[size].replace(\"##STYLE##\", Object.keys(rules).map(rule).join(\"\"));\n }\n }\n return css;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T04:49:01.780", "Id": "224193", "ParentId": "224179", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T22:49:35.837", "Id": "224179", "Score": "4", "Tags": [ "javascript", "layout", "vue.js" ], "Title": "Grid layout component for VueJS" }
224179
<p>I am trying to create a program to download a long list of websites using Python 3.7. By using multiprocessing for each request, my code runs much faster than when it's run synchronously. </p> <p>I've added a timer to my script so I can know the execution time for the script. The one I wrote below takes on average approximately <strong>3.5 seconds</strong> to run. However, when I use this script for my long list of URL's, it takes approximately 8 minutes to execute.</p> <p>I am wondering: is it taking this long because my internet is slow? Or is my script just bad? </p> <p>My internet speed is pretty low (3 mb/s download, 1 mb/s upload). If anyone has faster internet, could you post your execution time for this script along with your internet speed? This way, I can see if the bottleneck is internet speed or not.</p> <p>If the bottleneck isn't internet speed, but simply that my script is bad, can anyone offer any suggestions for improving the script so that the execution time is better? Thanks coders!</p> <pre><code>from urllib.request import Request, urlopen from multiprocessing.dummy import Pool as ThreadPool import datetime import time import requests start_time = time.time() urls = [ 'https://en.wikipedia.org/wiki/Python_(programming_language)', 'https://www.python.org/', 'https://stackoverflow.com/questions/tagged/python', 'https://github.com/python', 'https://realpython.com/python-beginner-tips/', 'https://pythonprogramming.net/introduction-to-python-programming/', ] mylist = [] def my_function(url_to_parse): req = Request(url_to_parse, headers={'User-Agent': 'Mozilla/5.0'}) resp = urlopen(req).read() mylist.append(resp) #------------------------------------------------------------------------------------------ pool = ThreadPool(8) results = pool.map(my_function, urls) pool.close() pool.join() print("--- %s seconds --- REQUESTS" % (time.time() - start_time)) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T23:40:32.130", "Id": "434788", "Score": "0", "body": "Welcome to CR! How many cores do you have on your machine and how long is your long list?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T00:11:45.707", "Id": "434789", "Score": "0", "body": "@ggorlen Thanks! I have 4 cores on my PC (and 8 processors, at 3.4 GHz). There are about 500 URL's on my list." } ]
[ { "body": "<h1>serializing</h1>\n<p>You are serializing <em>all</em> HTML text and sending it back to the parent.\nThat can be time consuming.</p>\n<p>Consider having the child (<code>my_function()</code>) write HTML text to a file in <code>/tmp</code>,\nand pass back the temporary filename to the parent.\nBetter, also pass back some timestamps: <code>(start, end, filename)</code></p>\n<h1>stragglers</h1>\n<p>If you can predict that a page will be &quot;big&quot; or a site will be &quot;slow&quot;,\nsort those to the front of your list of 500 URLs.\nThat way you won't have a handful of sluggish stragglers\nimpacting your overall time,\nwhile most cores are idle and waiting for them to complete.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T00:53:33.803", "Id": "434796", "Score": "0", "body": "Hi, thanks for the reply! Regarding stragglers, almost all of the sites are about the same size, so I think it's more simple to not take this into account. However, for serializing, do you know how I can do this? I just looked it up but I'm a beginner to Python so I'm having trouble understanding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T02:08:16.977", "Id": "434799", "Score": "0", "body": "I advised you not to serialize many kilobytes of HTML text coming back to a single-threaded parent. Instead, prefer to serialize the HTML text out to the filesystem in each of N children, and pass just a tiny filename back to the parent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T07:06:23.473", "Id": "434826", "Score": "0", "body": "I might remember wrongly, but isn't writing to a file subject to the global interpreter lock, meaning that you would lose out anyway, especially as writing to a file can be expensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T15:40:36.650", "Id": "434890", "Score": "0", "body": "That's not relevant here. It could be, in a threaded setting, but this is `multiprocessing`. Each child is its own process, running its own copy of the python interpreter. So for N children we have N non-interfering GILs." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T00:43:41.663", "Id": "224186", "ParentId": "224181", "Score": "2" } }, { "body": "<p>The main thing that tends to take time in acting over the net is the wait time between sending a request and getting a response, as opposed to the actual computations you have to do during the processing. It is therefore much more important to have a highly concurrent implementation than optimizing for parralel processing. In your case I would either increase the amount of threads in the pool to be the same length as as the number of pages to load, or use a concurrency library instead of a paralization library, especially if the thread library starts to have some kind of problems with such a high amount of threads (as they might have higher overhead).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T07:09:43.770", "Id": "224198", "ParentId": "224181", "Score": "1" } }, { "body": "<p>Firstly, it's a good idea to pythonize your code before we begin.</p>\n\n<p>When I ran your code, I saw the time to run calculation as the first thing. Looking into your code, I found that line at the end, then had search your entire program before I understood where <code>start_time</code> was defined.\nAn important thing with programming is - other programmers shouldn't have to do any hunting to understand your code. They will get frustrated if they have to keep searching through spaghetti to find what they're looking for.</p>\n\n<p>So, to fix that, and because we're writing in Python, it's important to have the standard entry point in your code. There are two reasons for this - first it tells your readers where your code starts \"here\", and second - if your code employs automated documentors, like Sphinx, it instantiates all the objects in your code before performing reflection to document your code. As is, your code would be executed immediately, which would break that intended functionality.</p>\n\n<pre><code>if __name__ == \"__main__\":\n start_time = time.time()\n mylist = []\n pool = ThreadPool(8)\n results = pool.map(my_function, urls())\n pool.close()\n pool.join()\n print_results() \n</code></pre>\n\n<p>Also, all your program flow is in one place. I can read this, and know what your code does without having to read all the different functions. I moved the print results into it's own function - as you will likely make changes to the print function as time progresses. If you make a change, and you create an error, the trace-back will point clearly to this function as being the error, instead of the main routine as being the error. This makes it easier and faster to fix bugs when you code. Keep everything in it's own function, this is the Single Responsibility Principle (<strong>S</strong>OLID).</p>\n\n<pre><code>def print_results():\n print(\"--- %s seconds --- REQUESTS\" % (time.time() - start_time))\n</code></pre>\n\n<p>You will notice I've changed <code>results = pool.map(my_function, urls())</code> - it's important to reduce variables into what they are - as your url variable returns a list of URLs, why not make it a simple function so it is called in one place without the overhead of maintaining memory space? (<code>...</code> for display)</p>\n\n<pre><code>def urls():\n return [\n 'https://en.wikipedia.org/wiki/Python_(programming_language)',\n ... \n 'https://pythonprogramming.net/introduction-to-python-programming/',\n ]\n</code></pre>\n\n<p>Another comment with that - as time goes on, you'll add and remove URLs, won't you? Every time you open your code up to make a change, there's a chance you'll inadvertently change the behavior of the code or accidentally break the code. We call this the Open Close Principle (S<strong>O</strong>LID) - your code should be open for enhancement, but closed for modification. To complete the point - it's best you export your URL list into a text/ini file, and when you need to add/remove URLs, you make the changes there, without the code being modified. </p>\n\n<p>Furthermore, think if your module was part of a large compiled program. If you changed a URL inside the code, it would need to be recompiled. Anything that used that library would need to be recompiled too, making your simple change quite laborious. See the point?</p>\n\n<p>Looking further into your code, we can see that <code>mylist[]</code> is created, but you don't really use it - because everything comes back from the <code>pool.map</code> into <code>results</code>. So let's change your code a little to improve that (<code>...</code> for display):</p>\n\n<pre><code>def fetch_url(url_to_parse):\n req = Request(url_to_parse, headers={'User-Agent': 'Mozilla/5.0'})\n resp = urlopen(req).read()\n return resp\n\ndef print_results(results):\n print(f\"--- {time.time() - start_time} Requests: {len(results)}\")\n\nif __name__ == \"__main__\":\n ...\n print_results(results)\n</code></pre>\n\n<p>Notice I renamed <code>my_function</code> to <code>fetch_url</code> - my_function doesn't mean anything, but fetch_url does. Make sure you name your functions to match what they do, otherwise other programmers need to read the entire function to understand what it does first.\nI've also used f-strings (Python 3.6+) which make print statements much cleaner. Take some time to learn them, they're good.</p>\n\n<p>Now that we've fixed your code, here it is:</p>\n\n<pre><code>from urllib.request import Request, urlopen\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport time\n\n\ndef urls():\n return [\n 'https://en.wikipedia.org/wiki/Python_(programming_language)',\n 'https://www.python.org/',\n 'https://stackoverflow.com/questions/tagged/python',\n 'https://github.com/python',\n 'https://realpython.com/python-beginner-tips/',\n 'https://pythonprogramming.net/introduction-to-python-programming/',\n ]\n\n\ndef read_url(url_to_parse):\n req = Request(url_to_parse, headers={'User-Agent': 'Mozilla/5.0'})\n return urlopen(req).read()\n\n\ndef print_results(results):\n print(f\"--- {time.time() - start_time} Requests: {len(results)}\")\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n pool = ThreadPool(8)\n results = pool.map(read_url, urls())\n pool.close()\n pool.join()\n print_results(results)\n</code></pre>\n\n<p>If you want to make your code faster, it's clear the fetching is the slow part. I notice you're mixing threading concepts and multiprocessor concepts, you should spend some time on understanding the differences. Finally, now that your code is modular, it's easy to drop-in a replacement for the fetch_url function. Here is an example which I tested with your code:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3472515/python-urllib2-urlopen-is-slow-need-a-better-way-to-read-several-urls\">https://stackoverflow.com/questions/3472515/python-urllib2-urlopen-is-slow-need-a-better-way-to-read-several-urls</a></p>\n\n<p>Hope this helps, Good Luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T07:44:39.183", "Id": "224201", "ParentId": "224181", "Score": "1" } } ]
{ "AcceptedAnswerId": "224201", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T23:33:43.123", "Id": "224181", "Score": "4", "Tags": [ "python", "web-scraping" ], "Title": "Why is my Python web scraper taking so long?" }
224181
<p>Problem statement:</p> <blockquote> <p>The following iterative sequence is defined for the set of positive integers:</p> <p>n → n/2 (n is even)<br> n → 3n + 1 (n is odd)</p> <p>Using the rule above and starting with 13, we generate the following sequence:</p> <p>13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1</p> <p>It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.</p> <p>Which starting number, under one million, produces the longest chain?</p> </blockquote> <p>NOTE: Once the chain starts the terms are allowed to go above one million. Here is my implementation written in Python, awaiting your feedback.</p> <pre><code>from time import time from operator import itemgetter def collatz_count(n, count={1: 1}): """uses cache (count) to speed up the search, returns sequence length for the given number""" try: return count[n] except KeyError: if n % 2 == 0: count[n] = collatz_count(n / 2) + 1 else: count[n] = collatz_count(n * 3 + 1) + 1 return count[n] def run_test(): """uses the previous function, returns number that generates the largest sequence""" time1 = time() items = sorted([(x, collatz_count(x)) for x in range(1, 1000000)], key=itemgetter(1), reverse=True) maximum = items[0] print(f' Starting number: {maximum[0]} \n Sequence length: {maximum[1]} \n ' f'Calculated in: {time() - time1} seconds.') if __name__ == '__main__': run_test() </code></pre>
[]
[ { "body": "<h2>Integer Division</h2>\n\n<p>In Python, <code>10 / 2</code> is equal to <code>5.0</code>, not <code>5</code>. Python has the integer division operator (<code>//</code>) which produces an integral value after division, instead of a floating point value. To prevent storing both <code>int</code> and <code>float</code> keys in the <code>count</code> dictionary, you should use:</p>\n\n<pre><code> count[n] = collatz_count(n // 2) + 1\n</code></pre>\n\n<h2>Cache</h2>\n\n<p>Your <code>count</code> cache works nicely. But you don’t have to implement it yourself. Python comes with <a href=\"https://docs.python.org/3/library/functools.html?highlight=lru_cache#functools.lru_cache\" rel=\"noreferrer\">caching built-in</a>. You just have to request it.</p>\n\n<pre><code>import functools\n\n@functools.lru_cache(None)\ndef collatz_count(n):\n if n == 1:\n return 1\n elif n % 2 == 0:\n return collatz_count(n // 2) + 1\n else\n return collatz_count(n * 3 + 1) + 1\n</code></pre>\n\n<p>The first time <code>collatz_count(n)</code> is called with any particular value of <code>n</code>, the function is called and the returned value is memorized in the cache. Any subsequent call with that argument retrieves the value from the cache. (The <code>None</code> value indicates that the cache size is unlimited.)</p>\n\n<h2>Sorting to find the maximum</h2>\n\n<p>Sorting, in order to find the maximum value, is an <span class=\"math-container\">\\$O(n \\log n)\\$</span> in time, and since you need to remember all the values, <span class=\"math-container\">\\$O(n)\\$</span> in space.</p>\n\n<p>There is no need to sort the list; instead, just maintain the largest value encountered so far, and the input which generated that value. This is <span class=\"math-container\">\\$O(n)\\$</span> in time, so much faster, and <span class=\"math-container\">\\$O(1)\\$</span> in space.</p>\n\n<p>And again, it is built-in to Python:</p>\n\n<pre><code>longest_start_number = max(range(1, 1000000), key=collatz_count)\nlength = collatz_count(longest_start_number)\n</code></pre>\n\n<h2>Docstrings</h2>\n\n<p>You are using the docstrings incorrectly.</p>\n\n<p>You shouldn’t say <code>\"\"\"uses the previous function ... \"\"\"</code> in a docstring, because if a user types <code>help(run_test)</code>, they will not know what function the previous function is. Even if they type <code>help(module_name)</code> and get help for all the functions in the module, the order the functions get listed in the resulting help output is not necessarily the order of the functions in the module’s source, so again “the previous function” is confusing.</p>\n\n<p>Similarly, saying <code>\"\"\"uses cache (count) to speed up ...\"\"\"</code> is useless, because a user typing <code>help(collatz_count)</code> is expecting to find help on how to use the function, such as what legal values can be given for <code>n</code>, what the return value is, and whether or not the user is expected to pass in a value for <code>count</code>; they don’t need implementation details about how the function was written.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T03:58:03.287", "Id": "434803", "Score": "1", "body": "thank you so much, this is really helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T03:35:59.620", "Id": "224189", "ParentId": "224182", "Score": "7" } }, { "body": "<blockquote>\n<pre><code>def collatz_count(n, count={1: 1}):\n \"\"\"uses cache (count) to speed up the search, returns sequence \n length for the given number\"\"\"\n</code></pre>\n</blockquote>\n\n<p>Are you sure it speeds it up? It certainly looks completely useless, because neither the looped top call</p>\n\n<blockquote>\n<pre><code>[(x, collatz_count(x)) for x in range(1, 1000000)]\n</code></pre>\n</blockquote>\n\n<p>nor the recursive calls reuse the cache.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T19:59:31.293", "Id": "435047", "Score": "0", "body": "Yes, it does speed it up. See the \"Valid uses for mutable defaults\" section in [Default Parameter Values in Python](http://www.effbot.org/zone/default-values.htm). The dictionary created in the parameter `count={1: 1}` is a global object that gets stored in `collatz_count.__defaults__`, and each time `n` is not found in the `count` dictionary, the `except KeyError:` block will store the computed value there. It is more of a side effect of using a mutable object as a parameter default, which normally results in disaster, but in this case actually is useful. `@functools.lru_cache` is better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T22:08:53.400", "Id": "435056", "Score": "1", "body": "Ugh. That's the kind of trick which is \"clever\" enough to need commenting every single time it's used." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:05:16.763", "Id": "224204", "ParentId": "224182", "Score": "2" } }, { "body": "<h1>time: O(n)</h1>\n\n<h1>memory: O(1)</h1>\n\n<h1>collatz_count()</h1>\n\n<p>To start, your <code>collatz_count()</code> function could be simpler and easier to read. The recursion in your <code>collatz_count()</code> function is confusing and too long.</p>\n\n<p>Also, do use integer division (<code>//</code>) to cut down on memory (floats take more space than integers).</p>\n\n<pre><code>def collatz_count(n):\n length = 0\n while n != 1: \n if n &amp; 1: # if n is odd\n n = 3 * n + 1\n else: # if n is even\n n = n // 2\n length += 1\n return length\n</code></pre>\n\n<h1>don’t sort, just remember</h1>\n\n<p>As another user mentioned, sorting to find the maximum is computationally complex (<span class=\"math-container\">\\$O(n \\log n)\\$</span>). An alternative is to just remember which starting number gave you the longest path.</p>\n\n<p>One user suggested this:</p>\n\n<pre><code>longest_start_number = max(range(1, 1000000), key=collatz_count)\nlength = collatz_count(longest_start_number)\n</code></pre>\n\n<p>That works and is better than what you currently have, but it’s more readable and faster to do this:</p>\n\n<pre><code>longest_start_number = 1\nlength = 1\nfor i in range(2, 1000000):\n if collatz_count(i) &gt; length:\n longest_start_number = i\n length = collatz_count(i)\n</code></pre>\n\n<h1>print from run_test()</h1>\n\n<p>You should generally not print from inside of a function. Instead of returning or printing a custom string, just return the values and leave the printing to the caller:</p>\n\n<pre><code>def run_test():\n # ... code ...\n return longest_start_number, length, time\n\nif __name__ == '__main__':\n longest_start_number, length, time = run_test()\n print(f' Starting number: {longest_start_number} \\n Sequence length: {length} \\n '\n f'Calculated in: {time} seconds.'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:07:19.030", "Id": "434927", "Score": "0", "body": "time taken by collatz_count without recursion using max(range(... 20.505295991897583 seconds.\n\n time taken by collatz_count without recursion using for loop... 21.560354948043823 seconds\n\n Starting number: 837799 \n Sequence length: 525 \n Calculated in: 2.5901660919189453 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:09:10.280", "Id": "434928", "Score": "0", "body": "I already a previous version without caching/recursion and it executed in the same time your function executed (almost 20 secs), after caching and use of recursion, it dropped to 2.5 secs, that's why I prefer the other version" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:44:04.280", "Id": "434930", "Score": "0", "body": "@emadboctor, that makes perfect sense. I was actually translating the most efficient alg from Mathematica to Python (Mathematica does t have cache, I’m pretty sure). Thanks for the feedback" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:09:32.670", "Id": "224239", "ParentId": "224182", "Score": "1" } } ]
{ "AcceptedAnswerId": "224189", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T23:52:30.990", "Id": "224182", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge", "dynamic-programming" ], "Title": "Project Euler #14: Longest Collatz Sequence starting point" }
224182
<p><a href="https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup" rel="noreferrer">Problem Statement</a>:</p> <blockquote> <p>Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, or a downhill, step. Gary's hikes start and end at sea level and each step up or down represents a unit change in altitude. We define the following terms:</p> <p>A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.</p> <p>For example, if Gary's path is, he first enters a valley units deep. Then he climbs out an up onto a mountain units high. Finally, he returns to sea level and ends his hike.</p> <h3>Function Description</h3> <p>Complete the <code>countingValleys</code> function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.</p> <p><code>countingValleys</code> has the following parameter(s):</p> <ul> <li><code>n</code>: the number of steps Gary takes</li> <li><code>s</code>: a string describing his path</li> </ul> <h3>Input Format</h3> <p>The first line contains an integer, the number of steps in Gary's hike. The second line contains a single string, of characters that describe his path.</p> <h3>Output Format</h3> <p>Print a single integer that denotes the number of valleys Gary walked through during his hike.</p> </blockquote> <p>My solution goes like this : </p> <pre><code>def countingValleys(n: Int, s: String): Int = { def rec(path: List[Char], counter: Int, valleys: Int): Int = { path match { case Nil =&gt; valleys case x::xs if (x == 'U') &amp;&amp; ((counter + 1) == 0) =&gt; rec(xs, counter+1, valleys+1 ) case x::xs if x == 'U' =&gt; rec(xs, counter +1, valleys) case x::xs if x == 'D' =&gt; rec(xs, counter -1, valleys) } } rec(s.toList, 0, 0) } </code></pre> <p>Sample Input: </p> <pre><code>8 UDDDUDUU </code></pre> <p>Sample Output:</p> <pre><code>1 </code></pre> <p>I wonder if there is a more idiomatic solution in functional programming style.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T19:10:10.933", "Id": "434792", "Score": "0", "body": "Side question about the problem - is the number of steps (`n`) redundant information? Won't that always be `s.length`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T05:10:12.393", "Id": "434813", "Score": "0", "body": "Yes, you are absolutely correct. Function was provided this way. I will report the question on Hacker-Rank." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T10:08:05.620", "Id": "435000", "Score": "0", "body": "@Sandio adding `n` as an additional information is necessary for languages like C++ that don't perform the same level of behind-the-scenes memory management as other languages" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T21:02:06.037", "Id": "435050", "Score": "0", "body": "Oh. That makes sense. @Vogel612 Thank you for the information." } ]
[ { "body": "<p>There's nothing wrong with or \"not functional\" about your approach. This might be opinion territory, but personally I would consider using <code>foldLeft</code> as it might be more readable and you can potentially eliminate some of the complexity of your cases.</p>\n\n<p>(also I got rid of <code>n</code> here as it is completely irrelevant, I know it's a problem from a website so you have to follow the format they gave you)</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>def countingValleys (steps: String): Int = steps\n .foldLeft((0, 0)) {\n case ((valleys, elevation), 'D') =&gt; (valleys, elevation - 1)\n case ((valleys, -1), 'U') =&gt; (valleys + 1, 0)\n case ((valleys, elevation), _) =&gt; (valleys, elevation + 1)\n }\n ._1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T07:29:56.543", "Id": "434830", "Score": "0", "body": "Thank you for your solution. It is helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T05:40:24.737", "Id": "434984", "Score": "0", "body": "Note that the original code's `counter` is what you call `depth`. That's a bit confusing, since positive `depth` represents higher elevation. Also, the original code's `valleys` is what you call `counter`. I think `valleys` was a clearer name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T12:13:59.337", "Id": "435002", "Score": "0", "body": "@200_success good point on the naming, updated." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T20:08:53.407", "Id": "224184", "ParentId": "224183", "Score": "2" } }, { "body": "<p>Your <code>counter</code> is a cumulative sum of elevation changes; <code>elevation</code> would be a more precise name for it.</p>\n\n<p>Ultimately, the goal is to count the number of times the elevation changes from -1 to 0. To do that:</p>\n\n<ol>\n<li>Translate the <code>'U'</code> and <code>'D'</code> steps into <code>+1</code> and <code>-1</code>, respectively.</li>\n<li>Obtain a sequence representing the elevation profile of the hike using <a href=\"https://www.scala-lang.org/api/current/scala/collection/Seq.html#scan[B&gt;:A](z:B)(op:(B,B)=&gt;B):CC[B]\" rel=\"nofollow noreferrer\"><code>Seq.scan</code></a>.</li>\n<li>Count the number of times -1 is followed by 0 in the elevation profile, using <a href=\"https://www.scala-lang.org/api/current/scala/collection/Seq.html#sliding(size:Int):Iterator[C]\" rel=\"nofollow noreferrer\"><code>Seq.sliding(2)</code></a> and <a href=\"https://www.scala-lang.org/api/current/scala/collection/Iterator.html#count(p:A=&gt;Boolean):Int\" rel=\"nofollow noreferrer\"><code>Iterator.count</code></a>.</li>\n</ol>\n\n\n\n<pre><code>def countingValleys(n: Int, s: String): Int = s\n .map(_ match {case 'U' =&gt; +1; case 'D' =&gt; -1})\n .scan(0)(_+_)\n .sliding(2)\n .count(_ == Vector(-1, 0))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T07:27:12.860", "Id": "434829", "Score": "0", "body": "This is so out of the box. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T04:19:29.617", "Id": "224190", "ParentId": "224183", "Score": "2" } } ]
{ "AcceptedAnswerId": "224190", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T17:01:37.057", "Id": "224183", "Score": "5", "Tags": [ "programming-challenge", "functional-programming", "scala", "immutability" ], "Title": "Counting valleys traversed below sea level, given elevation changes" }
224183
<h2>Preamble</h2> <p>I want to be able to test methods which communicate over a simple exclusively asynchronous two-way stream-like interface which may underneath use any of a number of communication methods (e.g. sockets, named pipe. In order to test these, I need a memory-backed implementation, where I can read and write stuff leisurely. In order to implement this, I need a one-way memory-backed channel.</p> <p>The main purpose is to facilitate throwing chunks of <code>byte</code>s around, but I decided it would be fun and possibly useful to make it generic. Correctness is very important, since I'll be using this type to test other types. The motivation for the implementation is that (for a sufficiently large buffer) everything should be nice and fast, with lots of synchronous writes, but that it will cope with the reader falling behind without trying to guzzle memory.</p> <p>I can't help but think this nightmarish mess might be over complicated, so I thought I'd ask here. In my defence, it does pass all its tests, and most of the code is just devoted to throwing exceptions (my favourite kind of code).</p> <h2>Specification</h2> <p>A class implementing a circular buffer which provides asynchronous read and write capabilities for any generic type such that:</p> <ul> <li>Can read or write an arbitrarily large amount of data</li> <li>Reads and Writes never fail (excepting manual cancellation or disposal)</li> <li>A Read or Write only finishes once all data has been read or written <ul> <li>Reads will wait for data if it is yet to be written</li> <li>Writes will wait for space in the buffer to be freed by reads</li> </ul></li> <li>Uses an essentially constant (predictable) amount of memory</li> <li>The instance may be disposed</li> <li>Reads may be cancelled: doing so must dispose the instance</li> <li>Reads and Writes must not block on a disposed instance</li> <li>Must support clearing read data from the buffer (e.g. so that references are not held)</li> </ul> <h3>Goals:</h3> <ul> <li>Simple API</li> <li>Well tested and Documented</li> <li>Allow arbitrary backing memory</li> <li>Attempt to detect 'concurrent' Read/Write</li> </ul> <h3>Non-goals:</h3> <ul> <li>Thread safe simultaneous reads and writes (this doesn't make sense at this layer) <ul> <li>Should try to throw if this is attempted</li> </ul></li> <li>Ludicrous performance <ul> <li>Speed is a concern, because it will be hammered by a bunch of tests (probably run in parallel...), but so long as it can pass 1GB around in under a minute on my old i7 I'm sure I'll cope</li> <li>Not eating all the memory on my machine is more important</li> <li>Any optimisation should be in favour of the non-waiting case</li> </ul></li> </ul> <h2>Notes:</h2> <ul> <li><p><code>ValueTask</code> is used to be consistent with parts of an external API. I don't think I gain anything by using <code>ValueTask</code> here, but I'm not too worried by performance, and some informal benchmarking suggests it doesn't make much difference. I'd be interested on comments, but I probably won't be changing this.</p></li> <li><p>The <code>EagerSignallingThreshold</code> is used to avoid the situation where, say, a <code>Read</code> wants 1000 bytes, but there are only 900 available: if the amount available is large relative to the total buffer size, then we signal the reader that it might as well get started, which hopefully maximises CPU utilisation, and means that the space freed by the reader will be available sooner to be written. Informal testing suggests this doesn't make much difference, but the capability is there if I find a situation which might be useful in the future.</p></li> <li><p>Three different concurrency methods are used for three different things:</p> <ul> <li>A <code>lock</code> (on <code>AvailabilityLock</code>) is used to ensure correctness of <code>ReadAvailable</code>, <code>ReadRequest</code>, <code>WriteAvailable</code>, and <code>WriteRequest</code>: these are the fields used to communicate between the Read and Write mechanisms.</li> <li>Semaphores to allow readers to wait for something to be written, and writers to wait for space to become available.</li> <li>CAS to perform mutual exclusion in <code>DisposeInternal</code>, <code>ReadAsync</code>, and <code>WriteAsync</code>.</li> </ul></li> <li><p>The <code>Disposed</code> event is provided so that, for example, a wrapper which manages simultaneous reads and writes has a dedicated way of detecting a failure. It also means there is a direct mechanism to allow releasing of unmanaged backing memory.</p></li> <li><p>I have tried to break the <code>ReadAsync</code> and <code>WriteAsync</code> methods down into meaningful parts. This has the downside of making everything a little more confusing, but the upside of enforcing structure, and does mean the code is slightly more flexible. It is still the case, for example, that <code>CompleteRead</code> must be called after <code>PerformRead</code>, and that you <em>must</em> release the <code>Writers</code> is <code>CompleteRead</code> tells you to (because it has already started that process), but atleast I can't get excited and shuffle the code between them, and if I feel like snapping <code>PerformRead</code> in two (so that someone else can do the 'overrun' check), that will be easier.</p></li> <li><p>I have no intention of doing anything along the lines of realising that I have a writer sitting around waiting to write, and reader waiting to read lots, and passing data directly from the writer to the reader. That could be a lot of fun as well, but it is not the idea here (I don't want writers blocking longer than they have to within the memory constraints, and I don't want the additional complexity of detecting and performing this efficiently here).</p></li> </ul> <h2>Description of operation</h2> <p>The Read and Write mechanism are almost completely symmetric, and have 'symmetric' properties to go with them. (I have considered coercing them into a single set of methods, but that would probably only create more confusion.) Reading has two added complexities, so I will describe only the <code>Read</code> mechanism here:</p> <p>A call to <code>ReadAsync</code> starts by ensuring we haven't been disposed, and that a read is not already in progress (both are cause for an exception), setting <code>ReadState = ResourceInUse</code> in the process.</p> <p>If this does not fail, it determines the <code>requested</code> number of values. It proceeds in a loop attempting to read as much memory as it can at that particular moment. It does so by requesting as much as could possibly copy (i.e. the size of the backing memory), which involves the call to <code>RequestRead</code> and associated <code>await</code>ing of the <code>ReadAvailableSemaphore</code>.</p> <p>If there are any values available (<code>ReadAvailable &gt; 0</code>), <code>RequestRead</code> returns true, and <code>required</code> is clamped to this value, before performing the read itself and remembering how much we have read so far before we start the loop again. We make no attempt to wait for 'more' values to become available (e.g. with a timeout) if there are any available in that moment.</p> <p>If there were no values available, then <code>RequestRead</code> returns false, and we <code>await</code> the <code>ReadAvailableSemaphore</code>, which will be signaled by the write mechanism when there are values available again. Reads can be cancelled (writes cannot): if the read is cancelled, we dispose ourselves and throw. Once the semaphore is released, we again decide how many values are available, and proceed to perform the actual read on the next slice of the buffer.</p> <p><code>PerformRead</code> starts by again checking we have not been disposed, caches a copy of the <code>MemoryBuffer</code>, and performs some internal checks to ensure we are not trying to do something stupid.</p> <p>Next, it decides whether the read needs to be cut into two because it extends beyond the buffer, and copies lots of memory about. At this point, if <code>ClearOnRead</code> is set, it will fill the buffer with <code>default</code> values. Finally it updates <code>ReadPosition</code>.</p> <p><code>CompleteRead</code> then locks <code>AvailabilityLock</code>. Within the lock it updates <code>ReadAvailable</code> and <code>WriteAvailable</code>, and decides whether it should signal a waiting, clearing <code>WriteRequest</code> if it decides that it will, and returning true (otherwise false).</p> <p>The loop in <code>ReadAsync</code> concludes by signalling the reader if <code>CompleteRead</code> instructed it to, and tallying how much is left to be read to the target buffer.</p> <p>When the whole buffer has been filled, the <code>ReadState</code> is reset so that <code>ReadAsync</code> can be called again.</p> <h2>Code</h2> <h3>Example Usage</h3> <pre class="lang-cs prettyprint-override"><code>using System; using System.Threading.Tasks; using Comm; namespace CommExamples { static class Program { static async Task Main(string[] args) { using (CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(capacity: 1024, clearOnRead: false)) { var write = WriteString(cm, "Hello, miserable world."); var read = ReadString(cm); Console.WriteLine(await read); await write; } Console.ReadKey(true); } /// &lt;summary&gt; /// Writes a length-prefix (Pascal) string to the given &lt;see cref="CommMemory{byte}"/&gt;. /// &lt;/summary&gt; /// &lt;param name="cm"&gt;The &lt;see cref="CommMemory{byte}"/&gt; to which to write.&lt;/param&gt; /// &lt;param name="str"&gt;The &lt;see cref="string"/&gt; to write to the &lt;see cref="CommMemory{byte}"/&gt;&lt;/param&gt; private static async ValueTask WriteString(CommMemory&lt;byte&gt; cm, string str) { // NOTE: this is example code: use a reusable string writer for performance var stringBuffer = System.Text.UTF8Encoding.UTF8.GetBytes(str); var intBuffer = System.BitConverter.GetBytes(stringBuffer.Length); await cm.WriteAsync(intBuffer); await cm.WriteAsync(stringBuffer); } /// &lt;summary&gt; /// Reads a length-prefixed (Pascal) string from the given &lt;see cref="CommMemory{byte}"/&gt;. /// &lt;/summary&gt; /// &lt;param name="cm"&gt;The &lt;see cref="CommMemory{byte}"/&gt; to which to write.&lt;/param&gt; /// &lt;returns&gt;The string read from the given &lt;see cref="CommMemory{byte}"/&gt;.&lt;/returns&gt; private static async ValueTask&lt;string&gt; ReadString(CommMemory&lt;byte&gt; cm) { // NOTE: this is example code: use a reusable string reader for performance var intBuffer = new byte[4]; await cm.ReadAsync(intBuffer); var length = System.BitConverter.ToInt32(intBuffer); var stringBuffer = new byte[length]; await cm.ReadAsync(stringBuffer); return System.Text.UTF8Encoding.UTF8.GetString(stringBuffer); } } } </code></pre> <h3><code>CommMemory.cs</code> (Implementation)</h3> <pre class="lang-cs prettyprint-override"><code>using System; using System.Threading; using System.Threading.Tasks; namespace Comm { /// &lt;summary&gt; /// Exception indicating that the &lt;see cref="CommMemory{TValue}"/&gt; instance consulted was Disposed and can no longer be used. /// &lt;/summary&gt; public class CommMemoryDisposedException : Exception { public CommMemoryDisposedException(string message) : base(message) { // nix } public CommMemoryDisposedException(string message, Exception innerException) : base(message, innerException) { // nix } } /// &lt;summary&gt; /// Callback for when a &lt;see cref="CommMemory{TValue}"/&gt; instance is disposed. /// &lt;/summary&gt; /// &lt;param name="disposedInstance"&gt;The &lt;see cref="CommMemory{TValue}"/&gt; instance disposed&lt;/param&gt; /// &lt;typeparam name="TValue"&gt;The type of the values handled by the &lt;see cref="CommMemory{TValue}"/&gt;.&lt;/typeparam&gt; public delegate void CommMemoryDisposed&lt;TValue&gt;(CommMemory&lt;TValue&gt; disposedInstance); /// &lt;summary&gt; /// Provides Asyncronous Read/Write into a cyclic memory buffer. /// &lt;see cref="ReadAsync(ArraySegment{TValue}, CancellationToken)"/&gt; and &lt;see cref="WriteAsync(ArraySegment{TValue})"/&gt; Tasks only complete when all data has been read, /// or the &lt;see cref="CommMemory{TValue}"/&gt; is Disposed by successfully cancelling a call to &lt;see cref="ReadAsync(ArraySegment{TValue}, CancellationToken)"/&gt; or calling &lt;see cref="Dispose"/&gt;. /// Thread-safe for single simulataneous Read and Write. /// Not thread-safe for multiple simulataneous Reads or Writes. /// &lt;/summary&gt; /// &lt;typeparam name="TValue"&gt;The type of Data handled by the &lt;see cref="CommMemory{TValue}"/&gt;.&lt;/typeparam&gt; public class CommMemory&lt;TValue&gt; : IDisposable { /// &lt;summary&gt; /// Checks the capacity is valid, and returns it. /// Throws if the capacity is not valid. /// &lt;/summary&gt; private static int CheckCapacity(int capacity) { if (capacity &lt;= 0) throw new ArgumentOutOfRangeException("Capacity must be non-negative (greater than 0)"); return capacity; } /// &lt;summary&gt; /// Creates a &lt;see cref="CommMemory{TValue}"/&gt; instance backed by an Array with the given capacity. /// &lt;/summary&gt; /// &lt;param name="capacity"&gt;The capcity of the &lt;see cref="CommMemory{TValue}"/&gt; instance; the length of the Array created.&lt;/param&gt; public CommMemory(int capacity, bool clearOnRead) : this(new Memory&lt;TValue&gt;(new TValue[CheckCapacity(capacity)]), clearOnRead) { // nix } public CommMemory(Memory&lt;TValue&gt; buffer, bool clearOnRead) { if (buffer.Length == 0) throw new ArgumentException("Cannot use a buffer of length 0 for CommMemory"); MemoryBuffer = buffer; ClearOnRead = clearOnRead; Capacity = MemoryBuffer.Length; ReadPosition = 0; ReadAvailable = 0; WritePosition = 0; WriteAvailable = Capacity; EagerSignallingThreshold = Capacity / 2; } /// &lt;summary&gt; /// The threshold, beyond which to signal early even if the requested number of values is not available. /// Must be no more than Capacity. /// &lt;/summary&gt; private readonly int EagerSignallingThreshold; /// &lt;summary&gt; /// The index from which to read. /// May only be modifier by a reader. /// &lt;/summary&gt; private int ReadPosition; /// &lt;summary&gt; /// The number of values available to be read. /// May only be increased by a Writer, and while AvailabilityLock is held. /// May only be decreased by Reader, and while AvailabilityLock is held. /// &lt;/summary&gt; private int ReadAvailable; /// &lt;summary&gt; /// The index to which to write. /// May only be modified by a writer. /// &lt;/summary&gt; private int WritePosition; /// &lt;summary&gt; /// The number of values free to be written. /// May only be increased by Reader, and while AvailabilityLock is held. /// May only be decreased by a Writer, and while AvailabilityLock is held. /// &lt;/summary&gt; private int WriteAvailable; /// &lt;summary&gt; /// The Memory used as the cyclic buffer. /// &lt;/summary&gt; private Memory&lt;TValue&gt; MemoryBuffer; /// &lt;summary&gt; /// The total capacity of this CommMemory object when it is alive. /// &lt;/summary&gt; public readonly int Capacity; /// &lt;summary&gt; /// Availablility lock to be held whenever Request or Available values are modified. /// Any time a decision is made based on Available, Request must be set within the same lock. /// &lt;/summary&gt; private readonly object AvailabilityLock = new object(); /// &lt;summary&gt; /// The number of values waiting to be read. /// Positive only if a reader is going to wait ReadAvailableSemaphore /// (must set ReadRequest before waiting on ReadAvailableSemaphore). /// Can only be set positive by a reader, and while AvailabilityLock is held. /// Can only be set to 0 by a writer, and while AvailabilityLock is held. /// &lt;/summary&gt; private int ReadRequest = 0; /// &lt;summary&gt; /// The number of values waiting to be written. /// Positive only if a writer is going to wait WriteAvailableSemaphore /// (must set WriteRequest before waiting on WriteAvailableSemaphore) /// Can only be set positive by a writer, and while AvailabilityLock is held. /// Can only be set to 0 by a reader, and while AvailabilityLock is held. /// &lt;/summary&gt; private int WriteRequest = 0; /// &lt;summary&gt; /// Signals when a Reader should try reading again because ReadAvailable has increased. /// &lt;/summary&gt; private readonly SemaphoreSlim ReadAvailableSemaphore = new SemaphoreSlim(0); /// &lt;summary&gt; /// Signals when a Writer should try writing again because WriterAvailable has increased. /// &lt;/summary&gt; private readonly SemaphoreSlim WriteAvailableSemaphore = new SemaphoreSlim(0); /// &lt;summary&gt; /// Indicidates whether this &lt;see cref="CommMemory{TValue}"/&gt; instance has become invalid. /// &lt;/summary&gt; public bool IsDisposed =&gt; State == DisposedState || MemoryBuffer.Length == 0; /// &lt;summary&gt; /// Indicates whether this &lt;see cref="CommMemory{TValue}"/&gt; clears values that have been read. /// &lt;/summary&gt; public bool ClearOnRead { get; } /// &lt;summary&gt; /// Throws if the CommMemory instance is dead. /// &lt;/summary&gt; private void EnsureAlive() { if (IsDisposed) throw new CommMemoryDisposedException("The CommMemory instance is disposed."); } /// &lt;summary&gt; /// Returns a useable copy of the MemoryBuffer. /// Throws if the instance is dead. /// &lt;/summary&gt; private Memory&lt;TValue&gt; EnsureAliveAcquire() { var memory = MemoryBuffer; // must check our own copy of memory if (State == DisposedState || memory.Length == 0) throw new CommMemoryDisposedException("The CommMemory instance is disposed."); return memory; } /// &lt;summary&gt; /// Called exactly once when the &lt;see cref="CommMemory{TValue}"/&gt; instance is disposed. /// Will only be called once. /// &lt;/summary&gt; public event CommMemoryDisposed&lt;TValue&gt; Disposed; /// &lt;summary&gt; /// Indicates the &lt;see cref="CommMemory{TValue}"/&gt; is alive. /// &lt;/summary&gt; private const int AliveState = 0; /// &lt;summary&gt; /// Indicates the &lt;see cref="CommMemory{TValue}"/&gt; is disposed, /// or in the process of being Disposed. /// &lt;/summary&gt; private const int DisposedState = 1; /// &lt;summary&gt; /// The state of the &lt;see cref="CommMemory{TValue}"/&gt; instance. /// Provides a Mutex for &lt;see cref="DisposeInternal"/&gt; ensuring it is only run once. /// &lt;/summary&gt; private int State = AliveState; /// &lt;summary&gt; /// Indicates that a given resource is free. /// &lt;/summary&gt; private const int ResourceFree = 0; /// &lt;summary&gt; /// Indicates that a given resource is in use. /// &lt;/summary&gt; private const int ResourceInUse = 1; /// &lt;summary&gt; /// Mutex for &lt;see cref="ReadAsync(Memory{TValue}, CancellationToken)"/&gt;. /// Has value &lt;see cref="ResourceFree"/&gt; when no read is pending. /// Takes value &lt;see cref="ResourceInUse"/&gt; when a read is pending. /// &lt;/summary&gt; private int ReadState = ResourceFree; /// &lt;summary&gt; /// Mutex for &lt;see cref="WriteAsync(ReadOnlyMemory{TValue})"/&gt;. /// Has value &lt;see cref="ResourceFree"/&gt; when no write is pending. /// Takes value &lt;see cref="ResourceInUse"/&gt; when a write is pending. /// &lt;/summary&gt; private int WriteState = ResourceFree; /// &lt;summary&gt; /// Kills the instance. /// 'Clears' the MemoryBuffer. /// Releasing (and disposes) all semaphors. /// Invokes &lt;see cref="Disposed"/&gt;. /// &lt;/summary&gt; private void DisposeInternal() { // only dispose once; tolerate multiple calls if (System.Threading.Interlocked.CompareExchange(ref State, DisposedState, AliveState) != AliveState) return; MemoryBuffer = Memory&lt;TValue&gt;.Empty; ReadAvailableSemaphore.Release(); ReadAvailableSemaphore.Dispose(); WriteAvailableSemaphore.Release(); WriteAvailableSemaphore.Dispose(); Disposed?.Invoke(this); } /// &lt;summary&gt; /// Asynchronously writes all the values from the given source &lt;see cref="ReadOnlyMemory{T}"/&gt;. /// Only one write may be in progress at a time. /// &lt;/summary&gt; /// &lt;param name="buffer"&gt;The buffer containing the values to be written.&lt;/param&gt; public async ValueTask WriteAsync(ReadOnlyMemory&lt;TValue&gt; source) { EnsureAlive(); if (System.Threading.Interlocked.CompareExchange(ref WriteState, ResourceInUse, ResourceFree) != ResourceFree) { // double-check we are still alive: if we have been disposed, then we are probably just an unreleased Mutex EnsureAlive(); throw new InvalidOperationException("A Write operation is still pending"); } int requested = source.Length; int writtenSoFar = 0; while (requested &gt; 0) { // only try to write as much as could fit in memory at a time int required = Math.Min(requested, Capacity); // check if values are available if (!RequestWrite(required)) { // wait for requested values to become available await WriteAvailableSemaphore.WaitAsync(); EnsureAlive(); } // take as much as we can required = Math.Min(required, WriteAvailable); // moves data around PerformWrite(source.Slice(writtenSoFar, required)); // communicate state to Readers if (CompleteWrite(required)) { ReadAvailableSemaphore.Release(); } writtenSoFar += required; requested -= required; } // we only clear WriteState on a successful write WriteState = ResourceFree; } /// &lt;summary&gt; /// Returns true if there are values available for writing; /// otherwise, sets &lt;see cref="WriteRequest"/&gt; and returns false. /// You must await &lt;see cref="WriteAvailableSemaphore"/&gt; if this method returns false. /// &lt;/summary&gt; private bool RequestWrite(int requested) { // preliminary check to avoid unnecessary locking if (WriteAvailable == 0) { // check we still need to wait, and set WriteRequested if need to wait lock (AvailabilityLock) { if (WriteAvailable == 0) { WriteRequest = requested; return false; } } } return true; } /// &lt;summary&gt; /// Writes the given source &lt;see cref="ReadOnlyMemory{T}"/&gt; to the MemoryBuffer at the WritePosition, updating the WritePosition. /// &lt;/summary&gt; private void PerformWrite(ReadOnlyMemory&lt;TValue&gt; source) { // acquire a copy of MemoryBuffer so that it can't change beneath us var memory = EnsureAliveAcquire(); int required = source.Length; // check we have enough space to actually perform the write (should be verified by callers) if (required &gt; WriteAvailable) { DisposeInternal(); throw new Exception("Internal error in CommMemory: attempted to perform a write with insufficient space available."); } if (required == 0) { DisposeInternal(); throw new Exception("Internal error in CommMemory: attempted to write into a buffer of length 0."); } // determine whether we need to cut the write in two if (WritePosition + required &gt; Capacity) { int headLength = Capacity - WritePosition; // length of the first write int tailLength = required - headLength; // length of the second write var s0 = source.Slice(0, headLength); var m0 = memory.Slice(WritePosition, headLength); s0.CopyTo(m0); var s1 = source.Slice(headLength, tailLength); var m1 = memory.Slice(0, tailLength); s1.CopyTo(m1); WritePosition = tailLength; } else { Memory&lt;TValue&gt; m = memory.Slice(WritePosition, required); source.CopyTo(m); WritePosition += required; if (WritePosition == Capacity) WritePosition = 0; } } /// &lt;summary&gt; /// Finishes the write by transfering the given space from WriteAvailable to ReadAvailable. /// Returns true if there is a waiting reader that should be signalled; clears ReadRequest accordingly. /// &lt;/summary&gt; /// &lt;param name="consumed"&gt;The number of values consumed&lt;/param&gt; private bool CompleteWrite(int consumed) { lock (AvailabilityLock) { // update availables WriteAvailable -= consumed; ReadAvailable += consumed; // check if a reader is waiting if (ReadRequest &gt; 0) { // signal reader if there are enough values availale to be read, and clear the ReadRequest if (ReadAvailable &gt;= ReadRequest || ReadAvailable &gt;= EagerSignallingThreshold) { ReadRequest = 0; return true; } } } return false; } /// &lt;summary&gt; /// Asynchronously reads values into the given destination &lt;see cref="Memory{T}"/&gt;. /// Cancelling a read will cause the CommMemory instance to be Disposed, and any pending write to fail. /// Only one read may be in progress at a time. /// &lt;/summary&gt; /// &lt;param name="ct"&gt;A cancellation token.&lt;/param&gt; public async ValueTask ReadAsync(Memory&lt;TValue&gt; destination, CancellationToken ct = default) { EnsureAlive(); if (System.Threading.Interlocked.CompareExchange(ref ReadState, ResourceInUse, ResourceFree) != ResourceFree) { // double-check we are still alive: if we have been disposed, then we are probably just an unreleased Mutex EnsureAlive(); throw new InvalidOperationException("A Read operation is still pending"); } int requested = destination.Length; int readSoFar = 0; while (requested &gt; 0) { // only try to write as much as could fit in memory at a time int required = Math.Min(requested, Capacity); if (!RequestRead(required)) { try { // wait for requested values to become available await ReadAvailableSemaphore.WaitAsync(ct); } catch (OperationCanceledException ocex) { // task cancelled: invalidate everything DisposeInternal(); throw new CommMemoryDisposedException("Invalided by Read cancellation.", ocex); } } // take as much as we can required = Math.Min(required, ReadAvailable); PerformRead(destination.Slice(readSoFar, required)); if (CompleteRead(required)) { WriteAvailableSemaphore.Release(); } readSoFar += required; requested -= required; } // Only clear ReadState on a successful read ReadState = ResourceFree; } /// &lt;summary&gt; /// Returns true if there are values available for reading; /// otherwise, sets &lt;see cref="ReadRequest"/&gt; and returns false. /// You must await &lt;see cref="ReadAvailableSemaphore"/&gt; if this method returns false. /// &lt;/summary&gt; private bool RequestRead(int requested) { // preliminary check to avoid unnecessary locking if (ReadAvailable == 0) { // check we still need to wait, and set ReadRequested if need to wait lock (AvailabilityLock) { if (ReadAvailable == 0) { ReadRequest = requested; return false; } } } return true; } /// &lt;summary&gt; /// Reads to the given destination &lt;see cref="Memory{T}"/&gt; from the MemoryBuffer at the ReadPosition, updating the ReadPosition. /// &lt;/summary&gt; private void PerformRead(Memory&lt;TValue&gt; destination) { // acquire a copy of MemoryBuffer so that it can't change beneath us var memory = EnsureAliveAcquire(); int required = destination.Length; // check we have enough space to actually perform the read if (required &gt; ReadAvailable) { DisposeInternal(); throw new Exception("Internal error in CommMemory: attempted to perform a read with insufficient space available."); } if (required == 0) { DisposeInternal(); throw new Exception("Internal error in CommMemory: attempted to read into a buffer of length 0."); } // determine whether we need to cut the read in two if (ReadPosition + required &gt; Capacity) { int headLength = Capacity - ReadPosition; // length of the first read int tailLength = required - headLength; // length of the second read var d0 = destination.Slice(0, headLength); var m0 = memory.Slice(ReadPosition, headLength); m0.CopyTo(d0); var d1 = destination.Slice(headLength, tailLength); var m1 = memory.Slice(0, tailLength); m1.CopyTo(d1); if (ClearOnRead) { m0.Span.Fill(default(TValue)); m1.Span.Fill(default(TValue)); } ReadPosition = tailLength; } else { var m = memory.Slice(ReadPosition, required); m.CopyTo(destination); if (ClearOnRead) { m.Span.Fill(default(TValue)); } ReadPosition += required; if (ReadPosition == Capacity) ReadPosition = 0; } } /// &lt;summary&gt; /// Finishes the read by transfering the given space from ReadAvailable to WriteAvailable. /// Returns true if there is a waiting writer that must be signalled; clears WriteRequest accordingly. /// &lt;/summary&gt; /// &lt;param name="consumed"&gt;The number of values consumed&lt;/param&gt; private bool CompleteRead(int consumed) { lock (AvailabilityLock) { // update availables ReadAvailable -= consumed; WriteAvailable += consumed; // check if a write is waiting if (WriteRequest &gt; 0) { // signal write if there is enough space, and clear the WriteRequest if (WriteAvailable &gt;= WriteRequest || WriteAvailable &gt;= EagerSignallingThreshold) { WriteRequest = 0; return true; } } } return false; } /// &lt;summary&gt; /// Disposes the &lt;see cref="CommMemory{TValue}"/&gt; instances. /// Terminating any pending Read or Write. /// &lt;/summary&gt; public void Dispose() { DisposeInternal(); } } } </code></pre> <h3><code>CommMemoryTests.cs</code> (Tests)</h3> <pre class="lang-cs prettyprint-override"><code>using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Comm.Tests { /// &lt;summary&gt; /// Wraps a &lt;see cref="CommMemory{byte}"/&gt; for Read/Write testing. /// &lt;/summary&gt; public struct ReadWriteCommMemoryByteWrapper : IAsyncByteReader, IAsyncByteWriter { public ReadWriteCommMemoryByteWrapper(CommMemory&lt;byte&gt; commMemory) { CommMemory = commMemory ?? throw new ArgumentNullException(nameof(commMemory)); } public CommMemory&lt;byte&gt; CommMemory { get; } public ValueTask ReadAsync(ArraySegment&lt;byte&gt; buffer, CancellationToken ct) { return CommMemory.ReadAsync(buffer, ct); } public ValueTask WriteAsync(ArraySegment&lt;byte&gt; buffer) { return CommMemory.WriteAsync(buffer); } } [TestClass] public class CommMemoryTests { /// &lt;summary&gt; /// Check that repeated calls to &lt;see cref="CommMemory{TValue}.Dispose"/&gt; are tolerated, /// and that &lt;see cref="CommMemory{TValue}.IsDisposed"/&gt; is only called once. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TolerateRepeatedDisposalTest() { int count = 0; using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(0, false); cm.Disposed += _cm =&gt; count++; for (int i = 0; i &lt; 10; i++) cm.Dispose(); Assert.AreEqual(1, count, "Disposal should only run once"); } /// &lt;summary&gt; /// Check that a capcity of zero is reject with an &lt;see cref="ArgumentOutOfRangeException"/&gt;. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void InvalidBufferSize0Test() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(0, false); } /// &lt;summary&gt; /// Check that a negative capcity is reject with an &lt;see cref="ArgumentOutOfRangeException"/&gt;. /// &lt;/summary&gt; /// &lt;summary&gt; [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void InvalidBufferSizeNegativeTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(-10, false); } /// &lt;summary&gt; /// Check that an empty buffer is rejected with an &lt;see cref="ArgumentException"/&gt;. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(ArgumentException))] public void InvalidBufferEmptyTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(new byte[0], false); } /// &lt;summary&gt; /// Check that a null buffer is rejected with an &lt;see cref="ArgumentException"/&gt;. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(ArgumentException))] public void InvalidBufferNullTest() { // NOTE: we would prefer this failed statically, but it performs an implict cast from byte[] using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(null, false); } /// &lt;summary&gt; /// Check that the backing buffer is cleared on read is &lt;see cref="CommMemory{TValue}.ClearOnRead"/&gt; is true. /// &lt;/summary&gt; [TestMethod] public async Task ClearOnReadTest() { // tests the ClearOnTrue property when set to true // no attempt is made to test when ClearOnTrue is false string str = "TestString"; int backingArraySize = 10; int dataSize = 6; var backingArray = new string[backingArraySize]; using CommMemory&lt;string&gt; cm = new CommMemory&lt;string&gt;(backingArray, true); var data = new string[dataSize]; data.AsSpan().Fill(str); await cm.WriteAsync(data); // data should appear in the array, otherwise our test is wrong Assert.AreEqual(dataSize, backingArray.Where(s =&gt; s == str).Count(), $"Backing array should contain {dataSize} copies of the string: test is broken"); Assert.AreEqual(backingArraySize - dataSize, backingArray.Where(s =&gt; s == null).Count(), $"Backing array should contain {backingArraySize - dataSize} nulls: test is broken"); await cm.ReadAsync(data); // data should not appear in the array, otherwise the implementation is wrong Assert.AreEqual(0, backingArray.Where(s =&gt; s == str).Count(), $"Backing array should contain 0 copies of the string"); Assert.AreEqual(backingArraySize, backingArray.Where(s =&gt; s == null).Count(), $"Backing array should contain {backingArraySize} nulls"); } } [TestClass] public class CommMemoryByteTestsNoClearOnRead : CommMemoryByteTests { protected override bool ClearOnRead =&gt; false; } [TestClass] public class CommMemoryByteTestsClearOnRead : CommMemoryByteTests { protected override bool ClearOnRead =&gt; true; } public abstract class CommMemoryByteTests { protected abstract bool ClearOnRead { get; } [TestMethod] public async Task SimpleLargeBufferTest() { await SimpleTest(10000, ClearOnRead); } [TestMethod] public async Task SimpleSmallBufferTest() { await SimpleTest(10, ClearOnRead); } [TestMethod] public async Task SimpleTinyBufferTest() { await SimpleTest(1, ClearOnRead); } /// &lt;summary&gt; /// Check that a &lt;see cref="CommMemoryDisposedException"/&gt; is thrown when a Read is cancelled. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(CommMemoryDisposedException))] public async Task CancelledReadExceptionTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); var cts = new System.Threading.CancellationTokenSource(100); await cm.ReadAsync(new byte[10], cts.Token); } /// &lt;summary&gt; /// Check that &lt;see cref="CommMemory{TValue}.IsDisposed"/&gt; is set when a Read is cancelled. /// &lt;/summary&gt; [TestMethod] public async Task CancelledReadStateTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); try { var cts = new System.Threading.CancellationTokenSource(500); await cm.ReadAsync(new byte[10], cts.Token); Assert.Fail("ReadAsync should have failed"); } catch { } Assert.IsTrue(cm.IsDisposed, "CommMemory should be Disposed"); } /// &lt;summary&gt; /// Check that a waiting Write throws a &lt;see cref="CommMemoryDisposedException"/&gt; if a waiting pending read is cancelled. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(CommMemoryDisposedException))] public async Task CancelledAwaitingWriteTest() { // set up a writer which will block // then kill a reader while the writer is still blocked // then await the writer, so we find out how (if) it died using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); await cm.WriteAsync(new byte[5]); var blockedWriter = cm.WriteAsync(new byte[20]); try { var cts = new System.Threading.CancellationTokenSource(); cts.Cancel(); await cm.ReadAsync(new byte[15], cts.Token); Assert.Fail("ReadAsync should have failed"); } catch { } // this should throw CommMemoryDisposedException, NOT InvalidOperationException await blockedWriter; } /// &lt;summary&gt; /// Check that attempting to Read from a Disposed &lt;see cref="CommMemory{TValue}"/&gt; results in a &lt;see cref="CommMemoryDisposedException"/&gt;. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(CommMemoryDisposedException))] public async Task DeadReadTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); try { var cts = new System.Threading.CancellationTokenSource(); cts.Cancel(); await cm.ReadAsync(new byte[15], cts.Token); Assert.Fail("ReadAsync should have failed"); } catch { } // this should throw await cm.ReadAsync(new byte[5]); } /// &lt;summary&gt; /// Check that attempting to Write to a Disposed &lt;see cref="CommMemory{TValue}"/&gt; results in a &lt;see cref="CommMemoryDisposedException"/&gt;. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(CommMemoryDisposedException))] public async Task DeadWriteTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); try { var cts = new System.Threading.CancellationTokenSource(); cts.Cancel(); await cm.ReadAsync(new byte[15], cts.Token); Assert.Fail("ReadAsync should have failed"); } catch { } // this should throw await cm.WriteAsync(new byte[5]); } /// &lt;summary&gt; /// Check that &lt;see cref="CommMemory{TValue}.Disposed"/&gt; is called when we cancel a read. /// &lt;/summary&gt; [TestMethod] public async Task DisposedCallbackOnReadCancellationTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); bool disposed = false; cm.Disposed += _cm =&gt; disposed = true; try { var cts = new System.Threading.CancellationTokenSource(); cts.Cancel(); await cm.ReadAsync(new byte[15], cts.Token); Assert.Fail("ReadAsync should have failed"); } catch { } Assert.IsTrue(disposed); } /// &lt;summary&gt; /// Check that &lt;see cref="CommMemory{TValue}.Disposed"/&gt; is called when we call &lt;see cref="CommMemory{TValue}.Dispose"/&gt;. /// &lt;/summary&gt; [TestMethod] public void DisposedCallbackOnDisposeTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); bool disposed = false; cm.Disposed += _cm =&gt; disposed = true; cm.Dispose(); Assert.IsTrue(disposed); } /// &lt;summary&gt; /// Check that &lt;see cref="CommMemory{TValue}.Disposed"/&gt; is called with the correct instance. /// &lt;/summary&gt; [TestMethod] public void DisposedCallbackIsntanceOnDisposeTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); CommMemory&lt;byte&gt; disposed = null; cm.Disposed += _cm =&gt; disposed = _cm; cm.Dispose(); Assert.AreEqual(cm, disposed); } /// &lt;summary&gt; /// Check that a waiting Read throws a &lt;see cref="CommMemoryDisposedException"/&gt; if the &lt;see cref="CommMemory{TValue}"/&gt; is manually Disposed. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(CommMemoryDisposedException))] public async Task ReadReleasedOnDispose() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); var read = cm.ReadAsync(new byte[15]); cm.Dispose(); await read; } /// &lt;summary&gt; /// Check that a waiting Write throws a &lt;see cref="CommMemoryDisposedException"/&gt; if the &lt;see cref="CommMemory{TValue}"/&gt; is manually Disposed. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(CommMemoryDisposedException))] public async Task WriteReleasedOnDispose() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); var read = cm.WriteAsync(new byte[15]); cm.Dispose(); await read; } /// &lt;summary&gt; /// Check that we get an &lt;see cref="InvalidOperationException"/&gt; if we try to Read multiple times at once. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public async Task DetectConcurrentReadTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(10, ClearOnRead); var buffer = new byte[10]; var r0 = cm.ReadAsync(buffer); var r1 = cm.ReadAsync(buffer); try { await r1; } catch { throw; } finally { try { cm.Dispose(); await r0; } catch { } } } /// &lt;summary&gt; /// Check that we get an &lt;see cref="InvalidOperationException"/&gt; if we try to Write multiple times at once. /// &lt;/summary&gt; [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public async Task DetectConcurrentWriteTest() { using CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(5, ClearOnRead); var buffer = new byte[10]; // data larger than buffer so that first write waits var w0 = cm.WriteAsync(buffer); var w1 = cm.WriteAsync(buffer); try { await w1; } catch { throw; } finally { try { cm.Dispose(); await w0; } catch { } } } /// &lt;summary&gt; /// Performs basic tests concerning data-integrety and blocking&lt;see cref="CommMemory{TValue}"/&gt; state. /// &lt;/summary&gt; /// &lt;param name="capacity"&gt;The capacity of the &lt;see cref="CommMemory{TValue}"/&gt; to use.&lt;/param&gt; /// &lt;param name="clearOnRead"&gt;The value to provide for &lt;see cref="CommMemory{TValue}.ClearOnRead"/&gt;.&lt;/param&gt; private static async Task SimpleTest(int capacity, bool clearOnRead) { using var cm = new CommMemory&lt;byte&gt;(capacity, clearOnRead); Assert.AreEqual(capacity, cm.Capacity); await SimpleTest(cm); Assert.AreEqual(capacity, cm.Capacity); } private static async Task SimpleTest(CommMemory&lt;byte&gt; cm) { // check basic read/write with signal works var sstr = "Hello, miserable world."; string rstr; bool disposeEventCalled = false; cm.Disposed += _cm =&gt; disposeEventCalled = true; var sbytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sstr); var rbytes = new byte[sbytes.Length]; // writer first var strWriter = cm.WriteAsync(sbytes); await Task.Delay(100); // give it a moment to sink in await cm.ReadAsync(rbytes); await strWriter; rstr = System.Text.ASCIIEncoding.ASCII.GetString(rbytes); Assert.AreEqual(sstr, rstr, "Data integrity not preserved"); Assert.IsFalse(cm.IsDisposed, "CommMemory should not be dead"); Assert.IsFalse(disposeEventCalled, "CommMemory.Disposed should not have been called"); // reader first var strReader = cm.ReadAsync(rbytes); await Task.Delay(100); // give it a moment to sink in await cm.WriteAsync(sbytes); await strReader; rstr = System.Text.ASCIIEncoding.ASCII.GetString(rbytes); Assert.AreEqual(sstr, rstr, "Data integrity not preserved"); Assert.IsFalse(cm.IsDisposed, "CommMemory should not be dead"); Assert.IsFalse(disposeEventCalled, "CommMemory.Disposed should not have been called"); } /// &lt;summary&gt; /// Checks that Reading and Writing many times with different buffer sizes produces consistent results. /// Non-deterministic: specificity is ~255/256 /// &lt;/summary&gt; [TestMethod] public async Task StressTest() { int bufferSize = 1000; int amount = 10000000; // 10million -&gt; ~2seconds per test int maxChunk = 10000; Assert.IsTrue(maxChunk &gt; bufferSize, "Test should include the situation where the maxChunk is greater than the buffer size: test is broken"); CommMemory&lt;byte&gt; cm = new CommMemory&lt;byte&gt;(bufferSize, ClearOnRead); var wrapper = new ReadWriteCommMemoryByteWrapper(cm); await Utilities.StressReadWriteTest(wrapper, wrapper, amount, maxChunk); } } } </code></pre> <h3><code>Utilities.cs</code> (Test utilities)</h3> <pre class="lang-cs prettyprint-override"><code>using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Threading; using System.Threading.Tasks; namespace Comm.Tests { /// &lt;summary&gt; /// Test interface /// &lt;/summary&gt; public interface IAsyncByteWriter { ValueTask WriteAsync(ArraySegment&lt;byte&gt; buffer); } /// &lt;summary&gt; /// Test interface /// &lt;/summary&gt; public interface IAsyncByteReader { ValueTask ReadAsync(ArraySegment&lt;byte&gt; buffer, CancellationToken ct); } /// &lt;summary&gt; /// Utilty methods for testing. /// &lt;/summary&gt; public static class Utilities { /// &lt;summary&gt; /// Writes random bytes to the writer, and reads them from the reader, checking that the xor of all bytes written and read is the same. /// &lt;/summary&gt; /// &lt;typeparam name="TReader"&gt;The type of &lt;see cref="IAsyncByteReader" /&gt; from which to read.&lt;/typeparam&gt; /// &lt;typeparam name="TWriter"&gt;The type of &lt;see cref="IAsyncByteWriter" /&gt; to which to write.&lt;/typeparam&gt; /// &lt;param name="reader"&gt;The &lt;typeparamref name="TReader"/&gt; from which to read.&lt;/param&gt; /// &lt;param name="writer"&gt;The &lt;typeparamref name="TWriter"/&gt; to which to write.&lt;/param&gt; /// &lt;param name="amount"&gt;The total number of bytes to be written.&lt;/param&gt; /// &lt;param name="maxChunk"&gt;The maximum number of bytes to be sent or requested at a time.&lt;/param&gt; public static async Task StressReadWriteTest&lt;TReader, TWriter&gt;(TReader reader, TWriter writer, int amount, int maxChunk) where TReader : IAsyncByteReader where TWriter : IAsyncByteWriter { // tests read and write, where they try to write random sized blocks, some of which won't fit in in buffers var read = ReadRandom(reader, amount, maxChunk); var write = WriteRandom(writer, amount, maxChunk); var wx = await write; var rx = await read; Assert.AreEqual(wx, rx); } /// &lt;summary&gt; /// Writes &lt;paramref name="amount"/&gt; bytes to the writer in random quantities in the range [1, &lt;paramref name="maxChunk"/&gt;]. /// Returns the xor of all bytes written. /// &lt;/summary&gt; /// &lt;typeparam name="TWriter"&gt;The type of &lt;see cref="IAsyncByteWriter" /&gt; to which to write.&lt;/typeparam&gt; /// &lt;param name="writer"&gt;The &lt;typeparamref name="TWriter"/&gt; to which to write.&lt;/param&gt; /// &lt;param name="amount"&gt;The total number of bytes to be written.&lt;/param&gt; /// &lt;param name="maxChunk"&gt;The maximum number of bytes to send per call to &lt;see cref="IAsyncByteWriter.WriteAsync(ArraySegment{byte}, CancellationToken)"/&gt;.&lt;/param&gt; public static async Task&lt;byte&gt; WriteRandom&lt;TWriter&gt;(TWriter writer, int amount, int maxChunk) where TWriter : IAsyncByteWriter { int count = 0; byte xor = 0; byte[] buffer = new byte[maxChunk]; Random rnd = new Random(); while (count &lt; amount) { int chunk = rnd.Next(buffer.Length - 1) + 1; chunk = Math.Min(chunk, amount - count); var data = new ArraySegment&lt;byte&gt;(buffer, 0, chunk); rnd.NextBytes(data); var write = writer.WriteAsync(data); for (int i = 0; i &lt; chunk; i++) xor ^= data[i]; await write; count += chunk; } return xor; } /// &lt;summary&gt; /// Reads &lt;paramref name="amount"/&gt; bytes to the writer in random quantities in the range [1, &lt;paramref name="maxChunk"/&gt;]. /// Returns the xor of all bytes read. /// &lt;/summary&gt; /// &lt;typeparam name="TReader"&gt;The type of &lt;see cref="IAsyncByteReader" /&gt; from which to read.&lt;/typeparam&gt; /// &lt;param name="reader"&gt;The &lt;typeparamref name="TReader"/&gt; from which to read.&lt;/param&gt; /// &lt;param name="amount"&gt;The total number of bytes to be written.&lt;/param&gt; /// &lt;param name="maxChunk"&gt;The maximum number of bytes requested per call to &lt;see cref="IAsyncByteReader.ReadAsync(ArraySegment{byte}, CancellationToken)"/&gt;.&lt;/param&gt; public static async Task&lt;byte&gt; ReadRandom&lt;TReader&gt;(TReader reader, int amount, int maxChunk) where TReader : IAsyncByteReader { int count = 0; byte xor = 0; byte[] buffer = new byte[maxChunk]; Random rnd = new Random(); while (count &lt; amount) { int chunk = rnd.Next(buffer.Length - 1) + 1; chunk = Math.Min(chunk, amount - count); var data = new ArraySegment&lt;byte&gt;(buffer, 0, chunk); await reader.ReadAsync(data, CancellationToken.None); for (int i = 0; i &lt; chunk; i++) xor ^= data[i]; count += chunk; } return xor; } } } </code></pre> <h2>Questions and Concerns</h2> <ul> <li><p>I'm not happy with <code>DisposeInternal</code>: I feel like releasing and disposing the semaphores is redundant, and liable to go wrong. I also feel I can't guarantee that <code>Disposed</code> is invoked, and that is less than ideal.</p></li> <li><p>Things like <code>&lt;see cref="CommMemory{byte}"/&gt;</code> don't work: it still calls it <code>CommMemory&lt;TValue&gt;</code> in intelli-sense: should I give up on the pretence, or is there some way to make it say <code>CommMemory&lt;byte&gt;</code>?</p></li> <li><p>Is there a better (BCL) <code>Exception</code> than <code>InvalidOperationException</code> for the concurrent-access detection?</p></li> <li><p>Is there an existing BCL class that does this (or can be wrapped up to do this) already which I have completely overlooked?</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T04:40:23.107", "Id": "434812", "Score": "0", "body": "Perhaps i'm looking over it but where is the source code for _Memory<T>_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T06:06:48.473", "Id": "434822", "Score": "1", "body": "@dfhwze you need thee [`System.Memory`](https://www.nuget.org/packages/System.Memory/) package to get it... if this is the same thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T06:11:51.433", "Id": "434825", "Score": "1", "body": "Your first question! You can write code ;-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T07:56:19.183", "Id": "434834", "Score": "1", "body": "@t3chb0t I know, I'm as shocked as you are! And yes, it is the `System.Memory`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T17:41:01.010", "Id": "434909", "Score": "1", "body": "@dfhwze Check out [source dot net](https://source.dot.net/#System.Private.CoreLib/shared/System/Memory.cs,d93c3764a7e63186)." } ]
[ { "body": "<h3>Quick Review</h3>\n\n<p>An API like this, dealing with thread-sensitive operations, requires time and effort to test and review rigorously. When I will find this time, I will do a thorough review. But here are some things I notice right off the bat.</p>\n\n<ul>\n<li><code>CommMemoryDisposedException</code> should inherit from <code>ObjectDisposedException</code>. This way, consumers can handle your exception as a common exception when an object is disposed.</li>\n<li>Private utility methods like <code>CheckCapacity</code>, <code>EnsureAlive</code> and <code>EnsureAliveAcquire</code> could/should be adorned with <code>[DebuggerStepThrough]</code> or any of its sibling attributes to enhance debugging interop.</li>\n<li>Local variables <code>ReadAvailable</code> and <code>WriteAvailable</code> may optimize performance, but they are not required.</li>\n<li>Local variables <code>ReadRequest</code>, <code>WriteRequest</code>, <code>ReadState</code> and <code>WriteState</code> and the logic build around them should be replaced with <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlock?view=netframework-4.8\" rel=\"noreferrer\">ReaderWriterLock</a>. Although, reading your goals, you don't want to allow concurrent access. So only implement this if your goals would allow for it.</li>\n<li>Using <code>Semaphore</code> for signaling threads would not be my preferred option. I would opt to use <code>ManualResetEventSlim</code>.</li>\n<li>Variable <code>IsDisposed</code> can return <code>true</code> even if its state might indicate otherwise. Is this a hack? Perhaps you're also including <code>IsDisposing</code> in here.</li>\n<li><code>DisposeInternal</code> should block new readers and writers while allowing existing operations to continue.</li>\n<li><code>DisposeInternal</code> does not clean up event <code>Disposed</code>. This is a memory leak waiting to happen.</li>\n<li>Think about which thread should invoke the event <code>Disposed</code>. I would execute this event asynchronously not to influence the current thread that is disposing the instance.</li>\n<li>An object that is able to <code>Dispose</code> itself is an anti-pattern in my opinion. A mediator or owner object should handle its lifetime.</li>\n<li>Methods <code>RequestWrite</code> and <code>RequestRead</code> perform double-checked locking. This might seem a good idea not to eagerly acquire a lock. But it can still lead to race conditions. Avoid double-checking and just acquire the lock. There are several articles online that address these issues.</li>\n<li>You have written an elaborate question with a good spec and lots of unit tests. Your code also reads very well.</li>\n</ul>\n\n<p>Your goals are clear about not allowing concurrent read/write access. However, if you do want to allow this, then..</p>\n\n<ul>\n<li>you are basically implementing a blocking queue. C# comes with <code>BlockingCollection</code> and <code>ConcurrentQueue</code>. Unfortunately, both don't exactly apply to your case. Java does have a class that does what you want, even using a circular buffer: <a href=\"http://fuseyism.com/classpath/doc/java/util/concurrent/ArrayBlockingQueue-source.html\" rel=\"noreferrer\">ArrayBlockingQueue</a>. Perhaps you could find some inspiration in its implementation. It uses Java's built in class <code>Condition</code> which unfortunately does not exist in C#. You have to work around that by using <code>ManualResetEventSlim</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:19:32.110", "Id": "434836", "Score": "0", "body": "Thanks for the swift feedback! 1. Absolutely, how did I miss that. 2. I prefer not too, but good point. 3. I need at least one 'extra' variable to cover the `ReadPosition = WritePosition` condition, and concluded I would become least confused if I just kept everything symmetric and kept the shared state 'restricted' to a few meaningful fields. 4. They do quite a lot of work more than just access, and read/write can be concurrent, so I'm not sure a `ReaderWriterLock` would improve understanding. 5. My mechanism would require an `AutoResetEvent`, and I want my code to be slim ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:19:37.303", "Id": "434837", "Score": "0", "body": "6. Yep. Old hack, should have gone away long ago. 7. An expressed goal is to kill everything: it's simplier, because a large read/write may be unable to finish (I have to wake everyone up anyway), and one of reasons I provide `IDispose` (to kill it quickly if I need to.). 8. Absolutely. 9. Could you elaborate? My worry is that this will make testing harder, but I'd be interested to hear more. (No rush at my end)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:20:11.603", "Id": "434838", "Score": "1", "body": "10. Not sure I agree: Read-cancellation invoked dispose is important, because it means the state cannot be known, which means it _must_ not be used. I did used to have 'Dead' and 'Disposed', but it was just introducing a distinction that didn't really exist. 11. I'm pretty sure it is safe here, but I know I'd probably be giving the same advice if I were writing an answer ;) 12. _\"Your code also reads very well.\"_ You must be joking! 13. I had a good look online, but all these things only support reading/writing single objects (which is somewhat simpler to implement efficiently). Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:28:10.343", "Id": "434840", "Score": "0", "body": "(Following 3. I do absolutely agree that the redundancy is a problem. I didn't like any of the alternatives I could come up with; I'd be interested if people have suggestions)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:45:13.810", "Id": "434842", "Score": "0", "body": "(Last thing, I promise! Regarding 5. I am an idiot: I could use a `ManualResetEvent`; however, it doesn't have the nice `async` API), so I'll stick to `Semaphore`s for the sake of readability and simplicity)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:49:38.493", "Id": "434843", "Score": "1", "body": "Thanks for all that feedback. About 9. Event listeners could deadlock the thread, throw exceptions etc. Do you want event handlers to influence the thread that is disposing the instance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:52:18.760", "Id": "434844", "Score": "0", "body": "Argh. You can probably tell I don't use events much... That'll need testing..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:58:43.203", "Id": "434845", "Score": "0", "body": "What's not clear in your code is why you need other objects to be informed about disposal of the instance. Perhaps you could elaborate on that. I haven't seen this pattern used.. well ever :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T09:07:59.037", "Id": "434846", "Score": "0", "body": "Now that you mention it, it is a bit odd isn't it... It is mostly there so that code testing other code and wrappers have one place to listen (convenience) and don't have to depend on other objects not swallowing exceptions (testing said objects) to start a tear-down process. It's all an artefact of the instance being able to dispose itself, and again, this used to be called `CommMemoryKilledException`, but I didn't feel there was a useful distinction between killing and disposing." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T05:08:30.930", "Id": "224195", "ParentId": "224185", "Score": "10" } }, { "body": "<p>A little late answer. I have focused on <code>CommMemory</code> and tried to refactor it as I see fit. You have discussed most of the issues with dfhwze, so I have not much to add other than what I have commented inline in the code below. You may agree or not in my changes and/or use it as you want. Any way it was fun to review.</p>\n\n<p>I have removed most of your own comments in order to clear it up a little bit (while reviewing - I don't mean your comments are misplaced) and my comments all start with \"HH:\".</p>\n\n<pre><code> // HH: I definitely don't like the concept of self-disposing, so the below omits that possibility\n // as well as the Disposed event. Instead is introduced a reinforced cancellation pattern, that allows for\n // cancellation via a constructor supplied cancellation token, and the read and write processes react to the state of that.\n\n public sealed class CommMemory&lt;TValue&gt; : IDisposable\n {\n // HH: Added a CancellationToken as mandatory argument\n public CommMemory(int capacity, bool clearOnRead, CancellationToken cancellationToken)\n : this(new Memory&lt;TValue&gt;(new TValue[CheckCapacity(capacity)]), clearOnRead, cancellationToken)\n {\n // nix\n }\n\n // HH: Added a CancellationToken as mandatory argument\n public CommMemory(Memory&lt;TValue&gt; buffer, bool clearOnRead, CancellationToken cancellationToken)\n {\n if (buffer.Length == 0)\n throw new ArgumentException(\"Cannot use a buffer of length 0 for CommMemory\");\n\n memoryBuffer = buffer;\n ClearOnRead = clearOnRead;\n this.cancellationToken = cancellationToken;\n memPosition = 0;\n memUsed = 0;\n }\n\n // HH: All these fields:...\n //private int ReadPosition;\n //private int ReadAvailable;\n //private int WritePosition;\n //private int WriteAvailable;\n // HH: ... can be replaced with these:\n private int memPosition;\n private int memUsed; // HH: See further below.\n\n private readonly Memory&lt;TValue&gt; memoryBuffer;\n private readonly CancellationToken cancellationToken; // HH: Added this to the constructor in order to cancel from both read and write clients\n public int Capacity =&gt; memoryBuffer.Length; // HH: Capacity is a property of memoryBuffer\n\n private readonly object availabilityLock = new object();\n private readonly object disposeLock = new object();\n private readonly object guardLock = new object();\n\n // HH: changed name from ReadAvailableSemaphore\n private readonly SemaphoreSlim readGuard = new SemaphoreSlim(0);\n // HH: Guard against concurrent read\n private readonly SemaphoreSlim readEntryGuard = new SemaphoreSlim(1);\n // HH: changed named from WriteAvailableSemaphore\n private readonly SemaphoreSlim writeGuard = new SemaphoreSlim(0);\n // HH: Guard against concurrent write\n private readonly SemaphoreSlim writeEntryGuard = new SemaphoreSlim(1);\n\n private volatile bool isDisposed = false;\n public bool IsDisposed =&gt; isDisposed;\n public bool ClearOnRead { get; }\n\n private static int CheckCapacity(int capacity)\n {\n if (capacity &lt;= 0)\n throw new ArgumentOutOfRangeException(\"Capacity must be non-negative (greater than 0)\");\n\n return capacity;\n }\n\n public async ValueTask WriteAsync(ReadOnlyMemory&lt;TValue&gt; source)\n {\n if (source.Length == 0) return;\n\n // HH: IMO all the EnsureAlive() is false security, because everywhere in between these calls in both read and write\n // anything can happen. Therefore two initial checks of disposed state here:\n CheckDisposed();\n\n try\n {\n // HH: Guard against concurrent entrence to write\n await writeEntryGuard.WaitAsync(cancellationToken);\n\n CheckDisposed();\n\n int written = 0;\n\n while (written &lt; source.Length)\n {\n cancellationToken.ThrowIfCancellationRequested();\n int currentWritten = PerformWrite(ref source, written);\n written += currentWritten;\n // HH: Here I let it be up to the read thread to determine if there is anything to read so far. If not read will wait\n CompleteWrite(currentWritten);\n TryReleaseGuard(readGuard);\n\n if (currentWritten == 0)\n {\n await writeGuard.WaitAsync(cancellationToken);\n }\n }\n }\n finally\n {\n writeEntryGuard.Release();\n }\n }\n\n private int PerformWrite(ref ReadOnlyMemory&lt;TValue&gt; source, int sourcePosition)\n {\n (int writePosition, int length) = GetWriteInfo();\n if (length == 0) return length;\n\n length = Math.Min(length, source.Length - sourcePosition);\n\n // HH: Moved all manipulation of source and memoryBuffer to here\n // So no magic happens in the call to this method...\n ReadOnlyMemory&lt;TValue&gt; slice = source.Slice(sourcePosition, length);\n\n // HH: I don't think the below will ever happen (in the original), because you guard carefully against that in WriteAsync()\n // And that holds for PerformRead() as well. That eliminates - as I see it - the possibility/need to self-dispose\n //if (required &gt; WriteAvailable)\n //{\n // DisposeInternal();\n // throw new Exception(\"Internal error in CommMemory: attempted to perform a write with insufficient space available.\");\n //}\n\n // determine whether we need to cut the write in two\n if (writePosition + length &gt; Capacity)\n {\n int headLength = Capacity - writePosition; // length of the first write\n int tailLength = length - headLength; // length of the second write\n\n var s0 = slice.Slice(0, headLength);\n var m0 = memoryBuffer.Slice(writePosition, headLength);\n s0.CopyTo(m0);\n\n var s1 = slice.Slice(headLength, tailLength);\n var m1 = memoryBuffer.Slice(0, tailLength);\n s1.CopyTo(m1);\n }\n else\n {\n Memory&lt;TValue&gt; m = memoryBuffer.Slice(writePosition, length);\n slice.CopyTo(m);\n }\n\n return length;\n }\n\n public async ValueTask ReadAsync(Memory&lt;TValue&gt; destination)\n {\n if (destination.Length == 0) return;\n\n // HH: Equivalent considerations as for WriteAsync()\n\n CheckDisposed();\n\n try\n {\n await readEntryGuard.WaitAsync(cancellationToken);\n\n CheckDisposed();\n\n int read = 0;\n\n while (read &lt; destination.Length)\n {\n cancellationToken.ThrowIfCancellationRequested();\n int currentRead = 0;\n currentRead = PerformRead(ref destination, read);\n read += currentRead;\n CompleteRead(currentRead);\n TryReleaseGuard(writeGuard);\n\n if (currentRead == 0)\n {\n await readGuard.WaitAsync(cancellationToken);\n }\n }\n }\n finally\n {\n readEntryGuard.Release();\n }\n }\n\n private int PerformRead(ref Memory&lt;TValue&gt; destination, int destinationStart)\n {\n // HH: The same considerations as for PerformWrite()\n\n (int readPosition, int length) = GetReadInfo();\n\n if (length == 0) return 0;\n\n length = Math.Min(length, destination.Length - destinationStart);\n\n Memory&lt;TValue&gt; slice = destination.Slice(destinationStart, length);\n\n // determine whether we need to cut the read in two\n if (readPosition + length &gt; Capacity)\n {\n int headLength = Capacity - readPosition; // length of the first read\n int tailLength = length - headLength; // length of the second read\n\n var d0 = slice.Slice(0, headLength);\n var m0 = memoryBuffer.Slice(readPosition, headLength);\n m0.CopyTo(d0);\n\n var d1 = slice.Slice(headLength, tailLength);\n var m1 = memoryBuffer.Slice(0, tailLength);\n m1.CopyTo(d1);\n\n if (ClearOnRead)\n {\n m0.Span.Fill(default(TValue));\n m1.Span.Fill(default(TValue));\n }\n }\n else\n {\n var m = memoryBuffer.Slice(readPosition, length);\n m.CopyTo(slice);\n\n if (ClearOnRead)\n {\n m.Span.Fill(default(TValue));\n }\n }\n\n return length;\n }\n\n private (int position, int length) GetWriteInfo()\n {\n lock (availabilityLock)\n {\n // HH: The available memory for writing is all that are not waiting to be read.\n int position = (memPosition + memUsed) % Capacity;\n return (position, Capacity - memUsed);\n }\n }\n\n private (int position, int length) GetReadInfo()\n {\n lock (availabilityLock)\n {\n // HH: Avialable memory for reading is represented by the values of memPosition and memUsed\n return (memPosition, memUsed);\n }\n }\n\n private void CompleteWrite(int consumed)\n {\n if (consumed &lt;= 0) return;\n lock (availabilityLock)\n {\n // HH: Just add the consumed memory to the already used\n memUsed += consumed;\n }\n }\n\n private void CompleteRead(int consumed)\n {\n if (consumed &lt;= 0) return;\n\n lock (availabilityLock)\n {\n // HH: Offest memPosition by consumed and align to Capacity\n memPosition = (memPosition + consumed) % Capacity;\n // HH: reduce memUsed by the memory read \n memUsed -= consumed;\n }\n }\n\n private void TryReleaseGuard(SemaphoreSlim guard)\n {\n lock (guardLock)\n {// HH: I'm not quite sure this is necessary, but I try to prevent the guard to allow more than one entrence at a time\n if (guard.CurrentCount == 0)\n {\n guard.Release();\n }\n }\n }\n\n public void Dispose()\n {\n Dispose(true);\n }\n\n // HH: renamed DisposeInternal() and implemented the normal Dispose pattern\n private void Dispose(bool isDisposing)\n {\n if (isDisposing)\n {\n lock (disposeLock)\n {\n if (isDisposed) return;\n isDisposed = true;\n\n memoryBuffer.Span.Clear();\n\n readEntryGuard.Release();\n readEntryGuard.Dispose();\n readGuard.Release();\n readGuard.Dispose();\n\n writeEntryGuard.Release();\n writeEntryGuard.Dispose();\n writeGuard.Release();\n writeGuard.Dispose();\n }\n }\n }\n\n private void CheckDisposed()\n {\n if (isDisposed)\n {\n // HH: changed from CommMemoryDisposedException\n throw new ObjectDisposedException(nameof(CommMemory&lt;TValue&gt;));\n }\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:05:46.453", "Id": "435304", "Score": "0", "body": "Thanks! Lots of interesting ideas, which I'll try to number. My main complaints would be with the API/behaviour changes and overly eager thread waking (but that's a performance thing, so I don't really care).. 1. I don't like the cancellation token as a member: it doesn't permit using an ephemeral cancellation token from elsewhere to cancel a read (though it is probably more intuitive than cancelling a read causing the whole thing to die). 2. The `memPosition/Used` pair is a nice way of removing the redundancy. I'm not sure I'd use those names, but the `Get*Info()` methods tidy that up nicely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:06:10.543", "Id": "435306", "Score": "0", "body": "3. `Clear` in Dispose is important; however, I also want to 'free' the memory buffer (this is why `Capacity` is its own field, and a few other things are the way they are.). 4. \"I don't think the below will ever happen (in the original)\": indeed, but if it does happen, then I want to know about it immediatly ;). Much as I love `Debug.Assert()`, this code is specifically for testing, and if a test fails I don't want any confusion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:06:42.633", "Id": "435307", "Score": "0", "body": "5. It 'queues' reads and writes, and that is not acceptable (looking at the OP I don't think I made that clear enough). It doesn't make sense to accept multiple operations from different threads, and I want to attempt to detect and throw if this occurs (of course you can't always detect mis-use, but the OP tries about as hard as you reasonably can without complicating the API). 6. If `PerformRead` is returning a length, it might as well remove the 'cut' logic, so that it just does half per call (I didn't do that because I wanted it to do exactly as it was told, and not do any decision making)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:08:14.867", "Id": "435308", "Score": "0", "body": "7. Blocking concurrent `lock` behaviour is an important omission on my part, thanks. 8. \"all the EnsureAlive() is false security\": not sure I follow? The 2 checks in `ReadAsync` are about throwing a sensible exception if it is disposed (coupled with the slightly dodgy read-latch). The checks in `PerformRead` are about ensuring `memoryBuffer` isn't cleared. 9. It passes the basic tests (i.e. those which I was able to quickly map to the changed API), so that's good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:34:06.893", "Id": "435310", "Score": "0", "body": "@VisualMelon: Thanks for feedback. A lot to discuss, but it seems that you have your good reasons to do, what you do, so keep doing that :-). One thing: \"overly eager thread waking\" - what do you mean by that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:51:05.513", "Id": "435313", "Score": "0", "body": "Well, I hope my reasons are good! Regarding overly eager threading, this is just about async overhead. One of the complexities in my code is that e.g. a Reader will only wake a Writer if there is enough space for it to complete the Write (or enough that it might be worth waking a thread to 'get started'). This is the point of the `Request` fields (and the reason I pulled out the `Complete` methods). Basically, I don't want to wake up a Write operation that is trying to move 1MB when 4 bytes become available (not because the writer will care, but because many may be running in parallel)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:36:07.147", "Id": "435318", "Score": "0", "body": "@VisualMelon: Ah, - that makes sense - and is easily changed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:48:58.933", "Id": "435361", "Score": "0", "body": "@HenrikHansen VisualMelon, reading your latest remark, I think you should use a blocking queue instead and let writers block untill availability of data. The threshold for deciding when data is available should be a configurable property. In case 4 bytes become free, all writers should be left alone. When threshold, let's say 1 MB is reached, the writers should be signalled." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T21:31:16.077", "Id": "435635", "Score": "0", "body": "@dfhwze the idea is that the read-queueing behaviour is someone else concern (indeed, I have a `QueuedCommMemory` class which does that job). Trying to read from different threads doesn't always make sense, after all. (P.S. that didn't ping me: you can only ping one person at a time, but the answer/question will always be pinged). In other news, I've given the checkmark to Henrik Hansen for the time being: both answer are great and have been most valuable; however, Henrik didn't get the HNQ inflation, so I think it's fair ;)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T09:07:10.383", "Id": "224391", "ParentId": "224185", "Score": "3" } } ]
{ "AcceptedAnswerId": "224391", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T00:36:00.017", "Id": "224185", "Score": "13", "Tags": [ "c#", "memory-management", "asynchronous", "async-await", "circular-list" ], "Title": "Asynchronous Circular Buffer in C#" }
224185
<p>Working with PyTorch tensors, I need to split the batch of items by its flags, so the items in <code>x_batch_one</code> and <code>x_batch_two</code> are lists of pairs that have the same flags. </p> <pre><code>def pairs_by_flags(self, x_batch, y_batch, max_flag): #split x_batch on pairs sizes = (x_batch.size(0)//2, *x_batch.size()[1:] ) items_pos = torch.zeros((max_flag,), dtype = torch.long, device = x_batch.device) x_batch_one = torch.zeros(sizes, device = x_batch.device) x_batch_one_pos = 0 x_batch_two = torch.zeros(sizes, device = x_batch.device) for index, flag in enumerate(y_batch): x_item = x_batch[index] i_flag = items_pos[flag] if i_flag: x_batch_two[i_flag-1] = x_item items_pos[flag] = 0 else: x_batch_one[x_batch_one_pos] = x_item x_batch_one_pos+=1 items_pos[flag] = x_batch_one_pos return x_batch_one, x_batch_two </code></pre> <p>Here is a simple example with single digits:</p> <pre><code>from torch_helper.myt import thelp import torch arr = torch.tensor([2,7,6,2,7,3,2,8,8,6,2,3]) arr1, arr2 = thelp.pairs_by_flags(arr, arr, 9) print(arr1) print(arr2) </code></pre> <p>Output:</p> <pre><code>tensor([2., 7., 6., 3., 2., 8.]) tensor([2., 7., 6., 3., 2., 8.]) </code></pre> <p>But after making this naive solution I wonder if it could be improved, perhaps eliminating the loop using some tensor [:,,,:,,,:] magic.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T00:48:43.307", "Id": "224187", "Score": "1", "Tags": [ "python", "performance", "pytorch" ], "Title": "Splitting torch tensor by flags" }
224187
<p>I am working my way through "Cracking the Coding Interview" and I came up the question(3.6) to design a data structure to manage an Animal shelter with 2 animals, Cats, and Dogs such that when we dequeue the oldest animal should be removed first (FIFO)</p> <p>E.g. if the animals were taken in order C,C,D,C,C,D (C- Cat, D- Dog) and someone wants to adopt an animal there could be 3 ways either adopt D, adopt C, or adopt any(I have just implemented for any as other two are trivial). If the person chooses to adopt D the first D to come in would be chosen from the queue similarly with C. If the person has no preference either of C, D who came first can be chosen.</p> <p>I implemented it as below. What all improvements can be done here? One possible way is to improve printQueue() function using 'this'.</p> <pre><code>#include &lt;iostream&gt; #include &lt;queue&gt; using namespace std; class Animal { public: virtual string getClassName() = 0; inline int getOrder() { return _order; } void setOrder(int order) { _order = order; } int setType(string type) { _type = type; } inline string getType() { return _type; } bool Compare(Animal* animal) { if (this-&gt;_order &gt; animal-&gt;_order) return true; return false; } private: int _order; string _type; }; class Cat : public Animal { public: Cat(string name) : _name(name) { } inline string getClassName() { return "Cat"; } inline string getName() { return _name; } private: string _name; }; class Dog : public Animal { public: Dog(string name) : _name(name) { } inline string getClassName() { return "Dog"; } inline string getName() { return _name; } private: string _name; }; class AnimalQueue { public: void enqueue(Animal* animal) { if (animal-&gt;getClassName() == "Cat") { Cat* d = dynamic_cast&lt;Cat*&gt;(animal); if (!d) { cout &lt;&lt; "\nCasting Error"; } else { cout &lt;&lt; "\nEnqueued Cat"; d-&gt;setOrder(++queueOrder); d-&gt;setType(animal-&gt;getClassName()); catQueue.push(d); } } else{ Dog* d = dynamic_cast&lt;Dog*&gt;(animal); if (!d) { cout &lt;&lt; "\nCasting Error"; } else { cout &lt;&lt; "\nEnqueued Dog"; d-&gt;setOrder(++queueOrder); d-&gt;setType(animal-&gt;getClassName()); dogQueue.push(d); } } } void dequeue() { if (catQueue.empty()) { dogQueue.pop(); } if (dogQueue.empty()) { catQueue.pop(); } //Pop with smaller timestamp if (catQueue.front()-&gt;Compare(dogQueue.front())) { dogQueue.pop(); } else { catQueue.pop(); } } void printQueue() { queue&lt;Cat*&gt; cQueue = this-&gt;catQueue; queue&lt;Dog*&gt; dQueue = this-&gt;dogQueue; cout &lt;&lt; "\nCat Queue\n"; while (!cQueue.empty()) { cout &lt;&lt; cQueue.front()-&gt;getName() &lt;&lt; " "; cout &lt;&lt; cQueue.front()-&gt;getOrder(); cout &lt;&lt; endl; cQueue.pop(); } cout &lt;&lt; "\nDog Queue\n"; while (!dQueue.empty()) { cout &lt;&lt; dQueue.front()-&gt;getName() &lt;&lt; " "; cout &lt;&lt; dQueue.front()-&gt;getOrder(); cout &lt;&lt; endl; dQueue.pop(); } } queue&lt;Dog*&gt; getDogQueue() { return dogQueue; } queue&lt;Cat*&gt; getCatQueue() { return catQueue; } private: queue&lt;Cat*&gt; catQueue; queue&lt;Dog*&gt; dogQueue; int queueOrder = -1; }; int main() { Animal* d1 = new Dog("Max"),*d2 = new Dog ("Shaun"), *d3 = new Dog("Tiger"); Animal* c1 = new Cat("Trace"), *c2 = new Cat("Han"), *c3 = new Cat("Meow"); AnimalQueue queue; queue.enqueue(d1); queue.enqueue(c1); queue.enqueue(c2); queue.enqueue(d2); queue.enqueue(d3); queue.enqueue(c3); cout &lt;&lt; endl; queue.printQueue(); cout &lt;&lt; endl; queue.dequeue(); queue.printQueue(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T03:53:54.333", "Id": "434802", "Score": "0", "body": "You also need something else for this to compile ... `string` is an undeclared identifier ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T04:05:53.673", "Id": "434804", "Score": "0", "body": "That's why I don't use namespaces, don't know why I did it here @L.F." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:33:24.287", "Id": "490909", "Score": "0", "body": "Just a note: you could solve this in C++ with templates and some constexpr with much less code." } ]
[ { "body": "<p>First off, you should <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">avoid <code>using namespace ::std</code></a>.</p>\n\n<p>In <code>Animal</code>, <code>getOrder</code> and <code>getType</code> should be <code>const</code> (<code>int getOrder() const</code>). Since they're defined within the class definition, you don't need to include the <code>inline</code> keyword. Similarly, getters in the derived classes should be <code>const</code>.</p>\n\n<p>It is rarely ever necessary to use the <code>this</code> keyword, and the places where you use <code>this-&gt;</code> to access a member variable can do without it.</p>\n\n<p><code>Compare</code> should also be <code>const</code> (and take its parameter as a <code>const Animal *</code>, and can be simplified to <code>return _order &gt; animal-&gt;_order;</code>.</p>\n\n<p>You never delete any of the memory you allocate with <code>new</code>.</p>\n\n<p>You should declare a virtual destructor for <code>Animal</code> since it is used as a base class. It isn't a direct problem here, since you never delete any of the memory you allocate, but if you'd delete Animals you dequeue, you'd still leak memory as the strings in the derived classes would not be freed.</p>\n\n<p>In <code>AnimalQueue</code> you can have separate <code>enqueue</code> methods that take <code>Cat *</code> and <code>Dog *</code> parameters. This would avoid needing to have all that code to check the type, and would work better if you have further derived classes (like \"Tiger\" derived from \"Cat\" or \"Wolf\" derived from \"Dog\"). The generic <code>enqueue(Animal *)</code> can call the proper overloaded <code>enqueue</code> after checking the result of the dynamic cast. Something like</p>\n\n<pre><code>if (auto cat = dynamic_cast&lt;Cat*&gt;(animal))\n enqueue(cat);\nelse if (auto dog = dynamic_cast&lt;Dog*&gt;(animal))\n enqueue(dog);\nelse /* error handling */;\n</code></pre>\n\n<p>assuming you're using a compiler that supports the variable declarations in <code>if</code> conditional expressions.</p>\n\n<p><code>dequeue</code> has several bugs. It will attempt to remove elements from empty containers, and could also try to access elements from empty containers.</p>\n\n<p><code>printQueue</code> should be <code>const</code>, and should use iterators to print the contents of the queues. Since displaying the two queues has a bunch of duplicated code, make a function that will display one queue and call that for each queue you want to display.</p>\n\n<p><code>getDogQueue</code> and <code>getCatQueue</code> should be const and return const references.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T04:57:42.970", "Id": "224194", "ParentId": "224188", "Score": "12" } }, { "body": "<p>In addition to the suggestions given by 1201ProgramAlarm's <a href=\"https://codereview.stackexchange.com/a/224194\">answer</a>, I have the following suggestions.</p>\n\n<p>First, your (over)use of RTTI seems overkill here. Even dynamic polymorphism is not necessary. A simple class is enough:</p>\n\n<pre><code>enum class Species { cat, dog };\n\nstruct Animal {\n Species species;\n std::string name;\n};\n</code></pre>\n\n<p>(You are missing <code>#include &lt;string&gt;</code>)</p>\n\n<p>Second, you maintain two queues. Since this is an animal shelter, why not merge them? You can use <code>vector</code> to accommodate for adopters that prefer a specified species.</p>\n\n<pre><code>std::vector&lt;Animal&gt; animals;\n</code></pre>\n\n<p>Third, <code>dequeue</code> returns <code>void</code>. This is <em>abandonment</em>, not adoption. It should return the <code>Animal</code>. (An animal protectionist can even go further and mark the function <code>[[nodiscard]]</code>.)</p>\n\n<p>Also, let <code>print</code> accept an <code>ostream&amp;</code>, so you can print to any stream.</p>\n\n<p>Here's the revised version:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;string&gt;\n#include &lt;utility&gt;\n#include &lt;vector&gt;\n\nenum class Species { cat, dog };\n\nstd::string to_string(Species species)\n{\n switch (species) {\n case Species::cat:\n return \"cat\";\n case Species::dog:\n return \"dog\";\n default:\n throw std::invalid_argument{\"Unrecognized species\"};\n }\n}\n\nstruct Animal {\n Species species;\n std::string name;\n};\n\nclass Shelter {\npublic:\n void enqueue(Animal animal)\n {\n animals.push_back(animal);\n }\n // adopt a specific species\n Animal dequeue(Species species)\n {\n auto it = std::find_if(animals.begin(), animals.end(),\n [=](const Animal&amp; animal) {\n return animal.species == species;\n });\n if (it == animals.end())\n throw std::logic_error{\"No animal to adopt\"};\n Animal animal = std::move(*it);\n animals.erase(it);\n return animal;\n }\n // adopt any animal\n Animal dequeue()\n {\n if (animals.empty())\n throw std::logic_error{\"No animal to adopt\"};\n Animal animal = std::move(animals.front());\n animals.erase(animals.begin());\n return animal;\n }\n void print(std::ostream&amp; os)\n {\n for (const auto&amp; animal : animals) {\n os &lt;&lt; animal.name &lt;&lt; \" (\" &lt;&lt; to_string(animal.species) &lt;&lt; \")\\n\";\n }\n }\nprivate:\n std::vector&lt;Animal&gt; animals;\n};\n\nint main()\n{\n Shelter shelter;\n shelter.enqueue({Species::dog, \"Max\"});\n shelter.enqueue({Species::cat, \"Trace\"});\n shelter.enqueue({Species::cat, \"Han\"});\n shelter.enqueue({Species::dog, \"Shaun\"});\n shelter.enqueue({Species::dog, \"Tiger\"});\n shelter.enqueue({Species::cat, \"Meow\"});\n\n shelter.print(std::cout);\n std::cout &lt;&lt; \"\\n\";\n\n auto new_pet = shelter.dequeue();\n shelter.print(std::cout);\n std::cout &lt;&lt; \"\\n\";\n\n auto new_dog = shelter.dequeue(Species::dog);\n shelter.print(std::cout);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Max (dog)\nTrace (cat)\nHan (cat)\nShaun (dog)\nTiger (dog)\nMeow (cat)\n\nTrace (cat)\nHan (cat)\nShaun (dog)\nTiger (dog)\nMeow (cat)\n\nTrace (cat)\nHan (cat)\nTiger (dog)\nMeow (cat)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T12:12:26.813", "Id": "434866", "Score": "5", "body": "I would note that algorithmic-wise, maintaining differentiating queues has a different complexity trade-off than maintaining a single queue. Popping a Cat off a single-queue is an O(number-animals) operation, while popping a Cat off differentiated queues is O(1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T14:12:37.780", "Id": "434874", "Score": "1", "body": "@MatthieuM. Good point. It seems unlikely that OP would be dealing with a lot of animals in this case, anyway :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T17:30:01.700", "Id": "435031", "Score": "2", "body": "My first thought was \"oh another 'let's use inheritance for animals' type problem, let's see how unnecessary complex it can get\" and I was not disappointed. Would give +2 if I could, given that other answers already started with virtual destructors and Knuth knows what. It' also easy to maintain different queues for each species with this approach as well if that's really necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T12:07:59.590", "Id": "435158", "Score": "0", "body": "@MatthieuM. If you maintain two different queues, how would you account for the case where the species doesn't matter and you just want to dequeue an animal?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T12:15:29.097", "Id": "435160", "Score": "0", "body": "@AleksandrH: You would check the head of each queue, and pop the \"most ancient\". This would be O(number-species)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:54:27.417", "Id": "435241", "Score": "0", "body": "@MatthieuM. Right, yeah, that's what I was thinking, but wouldn't that require storing some sort of timestamp info in the struct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T06:27:33.027", "Id": "435273", "Score": "2", "body": "@AleksandrH: Similarly to what the OP is doing, you need an index (they call \"queueOrder\"). I would not however store it in the Animal itself, as this is metadata, and instead would store `std::pair<Order, Dog>` and `std::pair<Order, Cat>` respectively." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T05:26:50.037", "Id": "224196", "ParentId": "224188", "Score": "16" } }, { "body": "<p>In addition to other answers: you're using <code>inline</code> a lot. Do not.</p>\n\n<p>Modern compilers (almost all starting from year 2000) don't use it for optimization anyways: they are already clever enough to do so without hints when possible. These days <code>inline</code> have another meaning in some contexts (when function is defined in many translation units), but in your situation it's a simple no-op.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T14:05:09.020", "Id": "434872", "Score": "1", "body": "Welcome to Code Review! It would be nice if you could add some external resources or a online compiler example to back your claim." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T13:00:55.563", "Id": "224218", "ParentId": "224188", "Score": "4" } }, { "body": "<p>To supplement the other reviews, here are some other things you might improve.</p>\n\n<h2>Use <code>override</code> where appropriate</h2>\n\n<p>When a virtual function is being overridden, it should be marked <code>override</code> to allow catching errors at compile time. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rh-override\" rel=\"noreferrer\">C.128</a>.</p>\n\n<h2>Make sure all paths return a value</h2>\n\n<p>The <code>setType</code> routine claims it returns an <code>int</code> but it does not. That's an error that should be addressed.</p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Think carefully about object ownership</h2>\n\n<p>The traditional role of a shelter is to take in animals and then give them to a new owner on adoption. This shelter seems to only do bookkeeping of the location of animals (by handling only pointers) rather than actually taking ownership of them. What is actually a more appropriate way to express this is by the use of a <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\"><code>std::unique_ptr</code></a>. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r20-use-unique_ptr-or-shared_ptr-to-represent-ownership\" rel=\"noreferrer\">R.20</a></p>\n\n<h2>Think carefully about the domain and range of numbers</h2>\n\n<p>The <code>_queueOrder</code> increases without bound and is used to assign the <code>_order</code> of each animal. What happens when that number wraps around? </p>\n\n<h2>Use polymorphism effectively</h2>\n\n<p>Whenever you find yourself writing code like this:</p>\n\n<pre><code>if (animal-&gt;getClassName() == \"Cat\") {\n Cat* d = dynamic_cast&lt;Cat*&gt;(animal);\n</code></pre>\n\n<p>stop and question whether this is really needed. By using <code>animal-&gt;getClassName()</code> as a sort of home-grown polymorphism, the code is made much more brittle and hard to maintain. Here's how I'd write that using a <code>std::unique_ptr</code> instead:</p>\n\n<pre><code>void enqueue(std::unique_ptr&lt;Animal&gt; &amp;&amp;animal) {\n animal-&gt;setOrder(++queueOrder);\n if (typeid(*animal) == typeid(Cat)) {\n catQueue.push_back(std::move(animal));\n } else if (typeid(*animal) == typeid(Dog)) {\n dogQueue.push_back(std::move(animal));\n } else {\n throw std::runtime_error(\"This animal is not suitable for the shelter\");\n }\n}\n</code></pre>\n\n<p>Note that this uses true RTTI, built into the language, instead of inventing a poor imitation. It also <code>throw</code>s an error if the passed animal is neither a cat nor a dog. This could be handy if someone attempted to drop off a pet rhinocerous.</p>\n\n<h2>Don't expose class internals</h2>\n\n<p>It seems to me that <code>getDogQueue</code> and <code>getCatQueue</code> are both ill-advised and unneeded. I'd simply omit them both.</p>\n\n<h2>Base destructors should be <code>virtual</code></h2>\n\n<p>The destructor of a base class, including a pure virtual one like <code>Animal</code>, should be <code>virtual</code>. Otherwise, deleting the object could lead to undefined behavior and probably memory leaks.</p>\n\n<h2>Consolidate common items into a base class</h2>\n\n<p>Since all of the derived classes have <code>_name</code>, why not move that functionality into the base class?</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>getName()</code> function does not alter the underlying class because it returns a copy of the name. Similarly, the <code>getClassName()</code> function does not alter the class. Both should be declared const.</p>\n\n<h2>Use standard operators</h2>\n\n<p>Rather than the vaguely named <code>Compare</code>, better would be to simply use the standard <code>operator&lt;</code>. Here's how I'd write it as a member function of <code>Animal</code>:</p>\n\n<pre><code>bool operator&lt;(const Animal&amp; b) const {\n return _order &lt; b._order;\n}\n</code></pre>\n\n<h2>Use better names</h2>\n\n<p>Most of the names are not bad, but rather than <code>AnimalQueue</code> and <code>enqueue</code> and <code>dequeue</code>, I'd suggest giving them more usage-oriented names rather than describing the internal structure. So perhaps <code>AnimalShelter</code>, <code>dropoff</code> and <code>adopt</code> would be more suitable.</p>\n\n<h2>Think carefully about data types</h2>\n\n<p>If you use a <code>std::deque</code> instead of a <code>std::queue</code>, you gain access to iterators which are useful for printing as shown in the next suggestion.</p>\n\n<h2>Use an <code>ostream &amp;operator&lt;&lt;</code> instead of <code>display</code></h2>\n\n<p>The current code has <code>printQueue()</code> function but what would make more sense and be more general purpose would be to overload an <code>ostream operator&lt;&lt;</code> instead. This renders the resulting function much smaller and easier to understand: </p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const AnimalShelter&amp; as) {\n out &lt;&lt; \"\\nCat Queue\\n\";\n for (const auto&amp; critter : as.catQueue) {\n out &lt;&lt; *critter &lt;&lt; '\\n';\n }\n out &lt;&lt; \"\\nDog Queue\\n\";\n for (const auto&amp; critter : as.dogQueue) {\n out &lt;&lt; *critter &lt;&lt; '\\n';\n }\n return out;\n}\n</code></pre>\n\n<p>I also modified the base class to include <code>_name</code> as mentioned above and wrote this <code>friend</code> function of <code>Animal</code>:</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Animal&amp; a) {\n return out &lt;&lt; a.getClassName() &lt;&lt; ' ' &lt;&lt; a._name &lt;&lt; ' ' &lt;&lt; a._order;\n}\n</code></pre>\n\n<h2>Implement the problem specification completely</h2>\n\n<p>The description of the problem mentions that one might be able to adopt either a cat or a dog or the first available, but only the latter function has been implemented. Here's how I wrote all three:</p>\n\n<pre><code>std::unique_ptr&lt;Animal&gt; adopt() {\n std::unique_ptr&lt;Animal&gt; adoptee{nullptr};\n if (catQueue.empty() &amp;&amp; dogQueue.empty())\n return adoptee;\n\n if (catQueue.empty()) {\n std::swap(adoptee, dogQueue.front());\n dogQueue.pop_front();\n } else if (dogQueue.empty() || (catQueue.front() &lt; dogQueue.front())) {\n std::swap(adoptee, catQueue.front());\n catQueue.pop_front();\n } else {\n std::swap(adoptee, dogQueue.front());\n dogQueue.pop_front();\n }\n return adoptee;\n}\n\nstd::unique_ptr&lt;Animal&gt; adoptCat() {\n std::unique_ptr&lt;Animal&gt; adoptee{nullptr};\n if (!catQueue.empty()) {\n std::swap(adoptee, catQueue.front());\n catQueue.pop_front();\n }\n return adoptee;\n}\n\nstd::unique_ptr&lt;Animal&gt; adoptDog() {\n std::unique_ptr&lt;Animal&gt; adoptee{nullptr};\n if (!dogQueue.empty()) {\n std::swap(adoptee, dogQueue.front());\n dogQueue.pop_front();\n }\n return adoptee;\n}\n</code></pre>\n\n<h2>Results</h2>\n\n<p>Here is the modified <code>main</code> to exercise the revised code:</p>\n\n<pre><code>int main()\n{ \n AnimalShelter shelter;\n shelter.dropoff(std::unique_ptr&lt;Animal&gt;(new Dog{\"Max\"}));\n shelter.dropoff(std::unique_ptr&lt;Animal&gt;(new Cat{\"Trace\"}));\n shelter.dropoff(std::unique_ptr&lt;Animal&gt;(new Cat{\"Han\"}));\n shelter.dropoff(std::unique_ptr&lt;Animal&gt;(new Dog{\"Shaun\"}));\n shelter.dropoff(std::unique_ptr&lt;Animal&gt;(new Dog{\"Tiger\"}));\n shelter.dropoff(std::unique_ptr&lt;Animal&gt;(new Cat{\"Meow\"}));\n try {\n shelter.dropoff(std::unique_ptr&lt;Animal&gt;(new Rhino{\"Buster\"}));\n } catch (std::runtime_error &amp;err) {\n std::cout &lt;&lt; err.what() &lt;&lt; '\\n';\n }\n std::cout &lt;&lt; shelter &lt;&lt; '\\n';\n\n for (int i = 0; i &lt; 2; ++i) { \n auto pet = shelter.adoptDog();\n if (pet) {\n std::cout &lt;&lt; \"You have adopted \" &lt;&lt; *pet &lt;&lt; \"\\n\";\n } else {\n std::cout &lt;&lt; \"sorry, there are no more pets\\n\";\n }\n std::cout &lt;&lt; shelter &lt;&lt; '\\n';\n }\n\n for (int i = 0; i &lt; 6; ++i) { // adopt any\n auto pet = shelter.adopt();\n if (pet) {\n std::cout &lt;&lt; \"You have adopted \" &lt;&lt; *pet &lt;&lt; \"\\n\";\n } else {\n std::cout &lt;&lt; \"sorry, there are no more pets\\n\";\n }\n std::cout &lt;&lt; shelter &lt;&lt; '\\n';\n }\n\n std::cout &lt;&lt; \"Final: \\n\" &lt;&lt; shelter &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:36:20.193", "Id": "434936", "Score": "0", "body": "Thankyou for briefly explaining! I didn't know much about std::endl as I have just used it in college to break lines but this explanation is really nice! Also, I did not think of the range of int, good point! Virtual destructor, how did I miss that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T13:10:26.497", "Id": "435006", "Score": "2", "body": "I would suggest to use `std::make_unique` instead of `std::unique_ptr(new …)` if you have C++14 or higher. Not 100% sure that it will work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T13:36:22.943", "Id": "435008", "Score": "0", "body": "@val: You're right about `std::make_unique`. An earlier iteration of my code didn't work with it but this one does. One can use `std::make_unique<Cat>(\"Whiskers\")` for a bit more succinct code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T14:47:45.143", "Id": "435012", "Score": "0", "body": "Why is the exception not const. Main doesn't return a value. It's a better interface if AnimalShelter had separate dropoffDog() and dropoffCat() functions, as then you wouldn't need any RTTI nonsense and the use of unique_ptr's would be hidden from the user. This is essentially Java." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:21:56.257", "Id": "435018", "Score": "0", "body": "@James: The exception could be `const` or even `static const`. `main`'s return value [is implicitly 0](https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c/43558724#43558724). I agree that avoiding RTTI would be better; other reviews have already made that point but you propose yet another way to do so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:20:25.573", "Id": "435124", "Score": "0", "body": "Insisting on exact match for the class instead of allowing extension? Not very general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-09T06:39:49.760", "Id": "499375", "Score": "0", "body": "I've read on https://en.cppreference.com/w/cpp/language/typeid that `typeid(*b)==typeid(B)` is not garanteed. `std::type_index` or `.hash_code()` should be used instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-09T11:37:54.440", "Id": "499417", "Score": "1", "body": "@nowox I believe you are misinterpreting what it says. While they may not return the same _instance_, they are guaranteed to return `true` from their `operator==()`. Otherwise `typeid` would be rather useless." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T17:50:15.220", "Id": "224234", "ParentId": "224188", "Score": "13" } }, { "body": "<p>I'll assume in 2019 that C++17 is available.</p>\n\n<p>All other answers seem to be using two <code>queue</code>s, one for each type of animal, but I think it kinda defeats the purpose that the FIFO behaviour has to be on the whole set of animals. With two <code>queues</code>, the FIFO has to be implemented by an <code>_order</code> stored with the animal, which mixes the data with the algorithm. Once the animal is adopted, out of the shelter, the <code>_order</code>has no meaning, but is still part of the structure.</p>\n\n<p>Using a queue, I would use a single queue of animals, which implements FIFO. (But the <code>deque</code> allows you to remove from the middle of it)</p>\n\n<pre><code>std::deque&lt;Animal&gt; _animals;\n</code></pre>\n\n<p>Now, the animal being either a cat or a dog, I would just say so</p>\n\n<pre><code>using Animal = std::variant&lt;Dog,Cat&gt;;\n</code></pre>\n\n<p>And implement each species as its own class.</p>\n\n<pre><code>class Cat { /* implementation*/ };\nclass Dog { /* implementation*/ };\n</code></pre>\n\n<p>Then, borrowing terminology from Edward's answer, I would simply implement:</p>\n\n<pre><code>void dropoff(Animal a) { _animals.emplace_back(std::move(a)) };\nstd::optional&lt;Animal&gt; adoptAny() {\n if(_animals.empty()) return std::nullopt;\n\n auto adoptee = std::move(_animals.front());\n _animals.pop_front();\n return adoptee; // NRVO\n}\n\n\ntemplate&lt;typename T&gt;\nauto adoptFirstOfType() -&gt; std::optional&lt;T&gt; {\n // Find first animal of given type\n const auto adoptee_it = std::find_if(\n begin(_animals),\n end(_animals), \n [](const Animal&amp; a) { return a.holds_alternative&lt;T&gt;(); };\n\n // If not found, return empty optional.\n if(adoptee_it == end(_animals)) {\n return std::nullopt;\n }\n\n // If found, steal the right alternative, remove from queue and return\n auto adoptee = std::get&lt;T&gt;(std::move(*adoptee_it));\n _animals.erase(adoptee_it);\n return adoptee; //NRVO\n}\n\nauto adoptDog() { // type deduced consistently from returned expression\n return adoptFirstOfType&lt;Dog&gt;();\n}\nauto adoptCat() { // type deduced consistently from returned expression\n return adoptFirstOfType&lt;Cat&gt;();\n}\n</code></pre>\n\n<p>Edward's main function should work fine as is, because <code>optional</code> has the same \"container access\" interface as <code>unique_ptr</code>.</p>\n\n<p>This allows to simply drop the <code>_order</code> and <code>operator&lt;</code> hacks from his solution. (because yes, implementing <code>operator&lt;</code> is a hack - it makes no sense that a Dog be more than a Cat because it arrived first in the shelter) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T18:59:11.947", "Id": "435038", "Score": "0", "body": "Good answer! I also considered the use of `std::optional` for this. I also like to think of C++17 as everywhere by now but just this morning I was trying to compile a program on a Raspberry Pi and found that alas, the compiler was only up to C++14. As for `operator<` being a hack, I disagree. The **only** ordering among animals mentioned in the problem statement is time-in-shelter, so it makes sense that a standard operator would be used to express that. And by the way as I implemented it, it would be `Cat < Dog` if the cat had arrived first. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:12:23.723", "Id": "435099", "Score": "0", "body": "@L.F.: You seem to be right. That would take a `deque` instead of a `queue`. Correcting this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:16:33.373", "Id": "435100", "Score": "0", "body": "@Edward: You're right, the logic is inverted in my answer. Correcting this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:31:52.380", "Id": "435103", "Score": "0", "body": "@Edward : thinking again, I think the problem is not in the `operator<`, but in the fact that the `_order` should not belong to the `Animal` class, because once the animal is out of the shelter, the `_order` matters no more. Maybe the queue(s) should instead store a `std::pair<size_t, Animal or Dog or Cat>`, and then you could define a cleaner `operator<` like `template<typename T, typename U> bool operator<(const std::pair<size_t,T>&, const std::pair<size_t,U>&)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T07:01:49.673", "Id": "435107", "Score": "0", "body": "My single queue is bothering me, come to think of it. Adopting a specific animal implies a lookup, and I suppose `adoptAny` is not the dominating case. As such, one queue per animal type seem to be constant-time in either case, so would be the proper way to handle the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:31:27.073", "Id": "435144", "Score": "0", "body": "I agree that `_order` doesn't really seem like it should be in `Animal`. One way of addressing that would be to omit it from `Animal` and then then maintain a `deque` of `std::pair<Animal, int>` to store the order in the only place it has meaning. I considered but didn't implement it that way." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:24:35.237", "Id": "224292", "ParentId": "224188", "Score": "2" } }, { "body": "<h3>Design</h3>\n\n<p>Is a single queue acceptable, or does each animal need its own?</p>\n\n<p>Multiple queues need more bookkeeping, as well as slight overhead when enqueueing an animal, or dequeueing the senior resident regardless of species.<br>\nWhile one <em>can</em> put the entrance-order in the animal-class, it certainly does not belong.</p>\n\n<p>A single queue potentially require looking at every single animal to find one of a specific species. On the flip-side, adding additional species comes naturally.</p>\n\n<h3>Implementation</h3>\n\n<ol>\n<li><p><code>::std</code> is not designed for wholesale inclusion. It contains myriad symbols, there is no comprehensive list, and it is always evolving. Your code might not \"work\" today, but tomorrow it might fail to compile, or worse silently change ist meaning.<br>\nRead \"<a href=\"https://stackoverflow.com/q/1452721\">Why is “using namespace std” considered bad practice?</a>\" for more detail.</p></li>\n<li><p>You are flat-out leaking all your animals.</p>\n\n<p>As the program terminates directly afterwards, and <code>delete</code>ing them has no observable effect you depend on, that <a href=\"https://stackoverflow.com/a/25142157/3204551\">could be a good idea</a>.<br>\nThat is, if it was intentional, well-explained, and not demo-code, but neither is the case.</p>\n\n<p>Consider an appropriate use of smart-pointers, specifically <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a>, as manual resource-management is error-prone.</p></li>\n<li><p>Generally, polymorphic types should have a virtual dtor, so they can be <code>delete</code>d polymorphically.</p></li>\n<li><p>The string type is set to the classname when enqueueing? Rip that out at the roots, you can use the source directly.</p></li>\n<li><p>Unless you need a friendly name for presistence or display, consider fully relying on builtin RTTI instead of adding your own home-grown variant. Use <code>typeid</code> if you want exact type-matching, or <code>dynamic_cast</code> if subtypes are fair game.</p></li>\n<li><p>All member-functions defined inline are automatically <code>inline</code>.</p></li>\n<li><p>Avoid needlessly copying strings, that's inefficient. Prefer <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> where applicable.</p></li>\n<li><p>Mark functions <code>noexcept</code> if you can.</p></li>\n<li><p>Mark overrides <code>override</code> for documentation and to allow the compiler to catch mistakes.</p></li>\n<li><p><code>printQueue()</code> clears it? That violates all expectations. And anyway, it should be <code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, AnimalQueue const&amp;)</code>.</p>\n\n<p>You probably should move from <code>std::queue</code> to directly using <code>std::deque</code> when fixing that, <a href=\"https://stackoverflow.com/a/5877652/3204551\">even though you can safely access the underlying container</a>.</p></li>\n</ol>\n\n<p>Using a single shared queue (<a href=\"https://coliru.stacked-crooked.com/a/02fd7e7e6e92dda8\" rel=\"nofollow noreferrer\">also live on coliru</a>):</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;memory&gt;\n#include &lt;string&gt;\n#include &lt;string_view&gt;\n#include &lt;utility&gt;\n#include &lt;vector&gt;\n\nclass Animal {\npublic:\n virtual std::string_view friendlyName() noexcept = 0;\n virtual ~Animal() = default;\n};\n\nclass Cat : public Animal {\n std::string _name;\npublic:\n Cat(std::string name) : _name(std::move(name)) {}\n\n std::string_view friendlyName() noexcept override { return \"Cat\"; }\n};\n\nclass Dog : public Animal {\n std::string _name;\npublic:\n Dog(std::string name) : _name(std::move(name)) {}\n\n std::string_view friendlyName() noexcept override { return \"Dog\"; }\n};\n\nclass Shelter {\n std::vector&lt;std::unique_ptr&lt;Animal&gt;&gt; _queue;\npublic:\n template &lt;class T = Animal&gt;\n std::unique_ptr&lt;T&gt; get() noexcept {\n auto pos = std::find_if(_queue.begin(), _queue.end(), [](auto&amp;&amp; x){ return dynamic_cast&lt;T*&gt;(x.get()); });\n if (pos == _queue.end())\n return {};\n std::unique_ptr&lt;T&gt; r(dynamic_cast&lt;T*&gt;(pos-&gt;release()));\n _queue.erase(pos);\n return r;\n }\n\n void put(std::unique_ptr&lt;Animal&gt;&amp;&amp; a) {\n if (a)\n _queue.push_back(std::move(a));\n }\n\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, Shelter const&amp; s) {\n for (auto&amp;&amp; x : s._queue)\n os &lt;&lt; x-&gt;friendlyName() &lt;&lt; ' ';\n os &lt;&lt; '\\n';\n return os;\n }\n};\n\nint main()\n{\n auto d1 = std::make_unique&lt;Dog&gt;(\"Max\");\n auto d2 = std::make_unique&lt;Dog&gt;(\"Shaun\");\n auto d3 = std::make_unique&lt;Dog&gt;(\"Tiger\");\n auto c1 = std::make_unique&lt;Cat&gt;(\"Trace\");\n auto c2 = std::make_unique&lt;Cat&gt;(\"Han\");\n auto c3 = std::make_unique&lt;Cat&gt;(\"Meow\");\n\n Shelter shelter;\n shelter.put(std::move(d1));\n shelter.put(std::move(c1));\n shelter.put(std::move(c2));\n shelter.put(std::move(d2));\n shelter.put(std::move(d3));\n shelter.put(std::move(c3));\n\n std::cout &lt;&lt; shelter;\n shelter.get();\n std::cout &lt;&lt; shelter;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:28:15.823", "Id": "435343", "Score": "1", "body": "I also proposed a solution with a single queue, but it has the inconvenient of requiring a linear search for the common case :adopting an animal of a specific species. The OP's solution of multiple queues with an everincreasing 64-bit order of entry gives constant time search in every case. You're making good points otherwise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T11:00:13.643", "Id": "224337", "ParentId": "224188", "Score": "1" } } ]
{ "AcceptedAnswerId": "224234", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T01:30:15.357", "Id": "224188", "Score": "12", "Tags": [ "c++" ], "Title": "Animal Shelter Management C++" }
224188
<p>I have this list of paths:</p> <pre><code>private static final List&lt;String&gt; paths = Arrays.asList( "assets/css/custom.css", "assets/css/default.css", "assets/js/main.js", "assets/js/old/main-old.js", "fonts/poppins.woff", "favicon.ico", "index.html" ); </code></pre> <p>That I need to create a searchable tree, like this:</p> <p><a href="https://i.stack.imgur.com/kxmOI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kxmOI.jpg" alt="enter image description here"></a></p> <p>and here's what I have now: </p> <pre><code>public void testCreateTree() { Node root = new Node("ROOT", null, Node.NODE_TYPE.ROOT); paths.forEach(path -&gt; { final Node[] currentNode = {root}; if(!path.contains("/")) { // root files currentNode[0].addChild(new Node(path, currentNode[0], Node.NODE_TYPE.FILE)); } else { String folders = DirectoryRegex.matchFolders(path); // e.g. matches/returns "root/" String fileName = DirectoryRegex.matchFile(path); // e.g. matches/returns index.html String[] folderArrays = folders.split("/"); Arrays.asList(folderArrays).forEach(folder -&gt; { Node node = new Node("ROOT", null, Node.NODE_TYPE.ROOT); node.setNodeName(folder); node.setNodeType(Node.NODE_TYPE.FOLDER); node.setParent(currentNode[0]); // check if child exists Node existingNode = currentNode[0].getChild(folder, Node.NODE_TYPE.FOLDER); if(existingNode == null) { existingNode = node; currentNode[0].addChild(node); } currentNode[0] = existingNode; }); currentNode[0].addChild(new Node(fileName, currentNode[0], Node.NODE_TYPE.FILE)); } }); String print = root.printNodeJSON().toString(); Console.log(print); } </code></pre> <p>The <strong>Node.java</strong> class is this:</p> <pre><code>public class Node { public NODE_TYPE getNodeType() { return nodeType; } public void setNodeType(NODE_TYPE nodeType) { this.nodeType = nodeType; } public Node getParent() { return parent; } public void setParent(Node parent) { this.parent = parent; } public List&lt;Node&gt; getChildren() { if(children == null) { children = new LinkedList&lt;&gt;(); } return children; } public void setChildren(List&lt;Node&gt; children) { this.children = children; } public void addChild(Node child) { getChildren().add(child); } public Node getChild(String nodeName, NODE_TYPE nodeType) { final Node[] child = {null}; getChildren().forEach(node -&gt; { if(node.getNodeName().equals(nodeName) &amp;&amp; node.getNodeType().equals(nodeType)) { child[0] = node; } }); return child[0]; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } private Node() {} public Node(String nodeName, Node parent, NODE_TYPE nodeType) { setNodeName(nodeName); setNodeType(nodeType); setParent(parent); } public enum NODE_TYPE { FILE, FOLDER, ROOT } private NODE_TYPE nodeType; private Node parent; private List&lt;Node&gt; children; private String nodeName; public String printNode() { final String[] s = {"["}; s[0] = s[0] + "Node name: " + nodeName + ","; if(nodeType != null) { s[0] = s[0] + "Node type: " + nodeType.toString() + ","; } if(getParent() != null) { s[0] = s[0] + "Node Parent: [ name = " + getParent().getNodeName() + ", type = " + getParent().getNodeType() + " ]"; } s[0] = s[0] + "Node children: ["; getChildren().forEach(child -&gt; { s[0] = "[" + s[0] + child.printNode() + "]"; }); s[0] = s[0] + "]"; s[0] = s[0] + "]"; return s[0]; } public JSONObject printNodeJSON() { JSONObject jsonObject = new JSONObject(); jsonObject.put("nodeName", nodeName); jsonObject.put("nodeType", nodeType != null ? nodeType.toString() : null); jsonObject.put("parent", getParent() != null ? getParent().printNodeJSONWithoutChildren() : null); JSONArray children = new JSONArray(); getChildren().forEach(child -&gt; { children.put(child.printNodeJSON()); }); jsonObject.put("children", children); return jsonObject; } public JSONObject printNodeJSONWithoutChildren() { JSONObject jsonObject = new JSONObject(); jsonObject.put("nodeName", nodeName); jsonObject.put("nodeType", nodeType != null ? nodeType.toString() : null); jsonObject.put("parent", getParent() != null ? getParent().printNodeJSONWithoutChildren() : null); // JSONArray children = new JSONArray(); // getChildren().forEach(child -&gt; { // children.put(child.printNodeJSON()); // }); // jsonObject.put("children", children); return jsonObject; } } </code></pre> <p><strong>The code works fine but I want to know the most efficient way to do this.</strong> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T05:42:31.800", "Id": "434817", "Score": "0", "body": "Would you allow paths like \"./\" or \"temp/../other\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T05:47:09.810", "Id": "434819", "Score": "0", "body": "Is _DirectoryRegex_ a custom class you have written?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T17:14:44.040", "Id": "434903", "Score": "0", "body": "@dfhwze yes it is a custom class; and no, there will be no empty path, as every absolute path in the List ends with a file (similar to object storages like S3, where the path is actually virtual)" } ]
[ { "body": "<p>Short take …<br>\n<code>most efficient way to do this</code><br>\nresources including developer time</p>\n\n<p>… of uncommented code:</p>\n\n<p>Starting with <code>testCreateTree()</code> raises hope for a stab at <em>test first</em> - I don't see it.</p>\n\n<p>What <em>is</em> <code>this</code> above: is there more to <em>tree</em> than <code>Node</code>, how does <em>searchable</em> manifest?</p>\n\n<ul>\n<li>there is no <code>interface</code> for <code>Node</code><br>\n(and <code>testCreateTree()</code> shows one is urgently needed)<br>\n(what use is <em>parent</em> of a <code>Node</code>?)<br>\n(come to think of it:<br>\n what use are all the setters?<br>\n<code>getNodeType()</code> could use <code>null == children</code>, and parent <code>null</code> or not) </li>\n<li>one ticklish part in designing <code>Node</code> is deciding whether construction of a <code>Node</code> with <code>null != parent</code> should add the new <code>Node</code> to <code>parent</code>'s children.<br>\n(One alternative being an instance method <code>Node addChild(name …)</code> which instantiates a child, adds it to children and returns it.)</li>\n<li>the one thing <code>Node</code> provides beyond <em>data members&amp;infrastructure</em> is <em>get child by name and type</em>, which is only useful if there are to be children of identical name, differing in type, only </li>\n<li>with neither assignment nor setter invocation, the lazy instantiation of <code>children</code> doesn't work</li>\n<li><p><code>getChild(name, type)</code> uses linear search (which may be justified if the expected number of children is quite small) - open coded, if using <code>Iterable.forEach()</code> (which seems to preclude \"early out\" - ?):<br>\nif only <code>java.util.Collection</code> (or, at least, <code>Set</code>) provided for an <code>E find(Object toEqual)</code>: implement <code>equals()</code> and use that.</p>\n\n<ul>\n<li>the use of an array with one solitary element is uncalled for</li>\n</ul></li>\n<li><p>\"The Way\" to support a representation of an instance for human reception is a implementing <code>toString()</code><br>\n  - the use of an array with one solitary element is uncalled for</p>\n\n<ul>\n<li>use a <code>StringBuilder</code> to build strings</li>\n<li>you don't need to use <code>.toString()</code> \"in a <code>String</code> context\" (e.g., <code>+</code> multiple <code>String</code>s). Doing so allows <code>NullPointerException</code>s (which are sidestepped (implicitly) using <code>String.valueOf()</code>).</li>\n<li>there's a way to avoid <code>&lt;some (involved) lvalue expression&gt; = &lt;same (involved) lvalue expression&gt; &lt;operator&gt; &lt;expression&gt;</code>: <em>compound assignment operators</em> (e.g., <code>&lt;(involved) lvalue expression&gt; /= &lt;expression&gt;</code>)<br>\n(should prevent the funny pile of <code>'['</code>s at the beginning of the string produced by <code>printNode()</code> - that string is formatted horribly, anyway)</li>\n</ul></li>\n<li>for all I don't know about JSON, I'd pattern support after <code>toString()</code> or (de/)serialisation.</li>\n<li><p><code>printNodeJSON()</code> is weird for duplicating <code>printNodeJSONWithoutChildren()</code>'s code instead of using it.<br>\nNeither prints.</p></li>\n<li><p>in <code>testCreateTree()</code>, you walk the <code>Node</code> structure, potentially searching for the same names time and again.<br>\n  - the use of an array with one solitary element is uncalled for </p>\n\n<ul>\n<li>Why provide parameters to <code>Node</code>'s constructor to go on and set deviating values? </li>\n</ul>\n\n<p>As an alternative, separate <em>path lookup</em> and <em>tree</em>:<br>\nget the index of the last path part separator (<code>'/'</code>), if any.<br>\nif separator was found, use root as folder<br>\nelse look up the folder for the part up to that separator (path)<br>\n  if not found, create folder(s recursively) linked up with its parent and enter into path->folder lookup<br>\ncreate a leaf for the part to the end \"in\" that folder </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T08:12:17.253", "Id": "434996", "Score": "0", "body": "(The current fad in getting JSON objects seems to be `Json.createXyzBuilder().add(…).…().build()`.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T07:58:07.167", "Id": "224278", "ParentId": "224192", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T04:47:14.730", "Id": "224192", "Score": "2", "Tags": [ "java", "algorithm", "tree", "json" ], "Title": "Create Node tree from list of paths" }
224192
<p><a href="https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup" rel="nofollow noreferrer">Problem statement:</a></p> <blockquote> <p>Lilah has a string, <strong>s</strong>, of lowercase English letters that she repeated infinitely many times. Given an integer, <strong>n</strong>, find and print the number of letter <strong>a</strong>'s in the first <strong>n</strong> letters of Lilah's infinite string.</p> <p>For example, if the string <strong>s = 'abcac'</strong> and <strong>n = 10</strong>, the substring we consider is <strong>abcacabcac</strong>, the first <strong>10</strong> characters of her infinite string. There are <strong>4</strong> occurrences of <strong>a</strong> in the substring.</p> <p><strong>Function Description</strong></p> <p>Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of <strong>a</strong> in the prefix of length <strong>n</strong> in the infinitely repeating string.</p> <p><strong>repeatedString has the following parameter(s):</strong></p> <pre><code>s: a string to repeat n: the number of characters to consider </code></pre> <p><strong>Input Format</strong> The first line contains a single string, <strong>s</strong>. The second line contains an integer, <strong>n</strong>.</p> <p><strong>Output Format</strong></p> <p>Print a single integer denoting the number of letter <strong>a</strong>'s in the first letters of the infinite string created by repeating infinitely many times.</p> <p><strong>Sample Input 0</strong></p> <pre><code>aba 10 </code></pre> <p><strong>Sample Output 0</strong></p> <pre><code>7 </code></pre> <p><strong>Explanation 0</strong> The first letters of the infinite string are abaabaabaa. Because there are a's, we print on a new line.</p> <p><strong>Sample Input 1</strong></p> <pre><code>a 1000000000000 </code></pre> <p><strong>Sample Output 1</strong></p> <pre><code>1000000000000 </code></pre> <p><strong>Explanation 1</strong> Because all of the first letters of the infinite string are a, we print on a new line.</p> </blockquote> <p><strong>My Solution:</strong></p> <pre><code>def repeatedString(s: String, n: Long): Long = { def getCount(str: String): Int = str.groupBy(identity).get('a').map(x =&gt; x.length).getOrElse(0) val length= s.length val duplicate: Long = n / length val margin = n % length val numberOccurencesInString = getCount(s) val countInRepetetiveString = numberOccurencesInString * duplicate val numberOfOccurencesInStripedString = getCount(s.take(margin.toInt)) countInRepetetiveString + numberOfOccurencesInStripedString } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T21:29:17.813", "Id": "435053", "Score": "0", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2" } ]
[ { "body": "<p>(Disclamer: It's been quite a while that I used Scala.)</p>\n\n<p>Your code is quite complicated. Scala provides the <code>LazyList</code> which allows to virtually repeat the string indefinitely. You then just need to \"take\" the <code>n</code> first characters, filter out the <code>a</code>s and count them:</p>\n\n<pre><code>def repeatedString(s: String, n: Int) =\n LazyList.continually(s).flatten.take(n).filter(_ == 'a').size\n</code></pre>\n\n<p>(Edit: Changed <code>n</code> to an Int. Unfortunately this solution won't work if <code>n</code> is a <code>Long</code>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T04:33:49.073", "Id": "434981", "Score": "1", "body": "[take](https://www.scala-lang.org/api/current/scala/collection/immutable/LazyList.html#take(n:Int):scala.collection.immutable.LazyList[A]) takes Int as parameter. And we are passing Long value for Int. It is giving compiler error. Even if we use n.toInt, there is a possibility of loosing precision. Try Sample Input 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T08:11:11.507", "Id": "434995", "Score": "0", "body": "@Sandio Thanks for the info." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T10:23:01.153", "Id": "224208", "ParentId": "224199", "Score": "0" } }, { "body": "<p>Your <code>getCount()</code> method is a little difficult to read, on one long line like that, and <em>way</em> too complicated. <code>s.count(_ == 'a')</code> is both concise and efficient.</p>\n\n<p>It's not clear why the number of <code>s</code> repetitions possible in <code>n</code> is called <code>duplicate</code>. It seems an odd choice for that variable name.</p>\n\n<p>Your algorithm is sound, I just find it excessively verbose, especially for a language that prides itself on being both expressive and concise.</p>\n\n<pre><code>val sLen = s.length\ns.count(_ == 'a') * (n/sLen) + s.take((n%sLen).toInt).count(_ == 'a')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T21:38:28.913", "Id": "435055", "Score": "0", "body": "I have considered your suggestions and updated question accordingly. And thank you for the solution it is expressive(self explanatory)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T07:38:43.217", "Id": "224274", "ParentId": "224199", "Score": "3" } } ]
{ "AcceptedAnswerId": "224274", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T07:23:16.000", "Id": "224199", "Score": "3", "Tags": [ "functional-programming", "scala", "immutability" ], "Title": "Count character 'a' in first n characters of indefinitely repeating string s" }
224199
<p>This is a simple boilerplate / template for a bigger program (I hope), either linked to a DB or including a GUI frontend using PYQT or TKinter.</p> <p>This is just a little tool I wrote to keep track of my own hours.</p> <pre><code>from datetime import datetime as dt FMT = "%H:%M" PARSE = (f"00:00", FMT) class WorkingTime: def __init__(self, worker, company): self.worker = worker self.company = company # This can be a JSON file or a SQL DB self.days_dict = { "Monday": {"start": "", "end": ""}, "Tuesday": {"start": "", "end": ""}, "Wednesday": {"start": "", "end": ""}, "Thursday": {"start": "", "end": ""}, "Friday": {"start": "", "end": ""}, "Saturday": {"start": "", "end": ""}, "Sunday": {"start": "", "end": ""}, } def set_start_hour(self, day, hour): self.days_dict[day.title()]["start"] = hour def set_end_hour(self, day, hour): self.days_dict[day.title()]["end"] = hour def set_start_and_end(self, day, start, end): self.days_dict[day.title()]["start"] = start self.days_dict[day.title()]["end"] = end def get_start_hour(self, day): return self.days_dict[day.title()]["start"] def get_end_hour(self, day): return self.days_dict[day.title()]["end"] def get_start_and_end(self, day): return self.days_dict[day.title()]["start"], self.days_dict[day.title()]["end"] def calculate_day_hours(self, hours): """ takes in a tuple and returns the number of hours""" start, end = hours try: start_time_obj = dt.strptime(f"{start[:2]}:{start[2:4]}", FMT) end_time_obj = dt.strptime(f"{end[:2]}:{end[2:4]}", FMT) return end_time_obj - start_time_obj except ValueError: return dt.strptime(*PARSE).strftime(FMT) def calculate_week_hours(self): """ returns the sum of the week """ total = dt.strptime(*PARSE) for k, v in self.days_dict.items(): if v.get("start") and v.get("end"): hours = self.calculate_day_hours((v.get("start"), v.get("end"))) total += hours return total.strftime(FMT) def display_hours_day(self, day, hours): """ Returns a string of the hours for that day """ day_hours = self.get_start_and_end(day) rtn_hours = self.calculate_day_hours(day_hours) space = " " * (11 - len(day)) return f"\n\t{day.title()}{space}:: {rtn_hours} Hours\n" def display_hours_week(self): """ Returns a string of the hours for the week """ rtn_str = "\n" rtn_str += f"\n\tName :: {self.worker}\n\tCompany :: {self.company}" line = "-" * 50 total_line = '-'*26 rtn_str += f"\n{line}" for k, v in self.days_dict.items(): if v: hours = self.calculate_day_hours((v.get("start"), v.get("end"))) rtn_str += self.display_hours_day(k, hours) total = self.calculate_week_hours() rtn_str += f"\t{total_line}" rtn_str += f"\n\tTotal :: {total} Hours\n" rtn_str += f"\n{line}\n\n" return rtn_str wt = WorkingTime('Maffaz', 'IT Circle Consult') # Set hours wt.set_start_hour("monday", "0730") wt.set_end_hour("monday", "1800") wt.set_start_and_end("TUESDAY", "", "") wt.set_start_and_end("wednesday", "", "") wt.set_start_and_end("THUrsday", "", "") wt.set_start_and_end("FrIDAY", "", "") # # get hours print(wt.get_start_hour("Monday")) print(wt.get_end_hour("Wednesday")) print(wt.get_start_and_end("Friday")) # calculate day hours print(wt.calculate_day_hours(wt.get_start_and_end("monday"))) # calculate week hours week = wt.calculate_week_hours() print(week) # print day hours tues_hours = wt.get_start_and_end("tuesday") print(wt.display_hours_day("Tuesday", tues_hours)) # print week hours total print(wt.display_hours_week()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T16:53:09.357", "Id": "435028", "Score": "1", "body": "I rolled back your last edits. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T17:45:44.663", "Id": "435033", "Score": "1", "body": "Thanks for the heads up... noted :)" } ]
[ { "body": "<ul>\n<li><p>Extract <code>day.title()</code> to a separate method. In this case, if you wanted to change how you store the days of the weeks (e.g. Monday, Tuesday ... -> monday, tuesday...), you would have to change <code>day.title()</code> to <code>day.lower()</code> only in one place*.</p></li>\n<li><p>Implement <code>set_start_and_end()</code> by calling <code>set_start()</code> and <code>set_end()</code>. Identically for getters. The rationale is similar to the previous point: if you decided to change the data structure where you store the time slots, you would have to change less code*.</p></li>\n<li><p><strong>Magic numbers</strong>. e.g. 11. First of all extract such number into a constant with a meaningful name. Btw, is this value really a constant? Will you still want to use this value if the names of the days of the week change (e.g. you decide to use Mon, Tue etc., or names in another language)</p></li>\n<li><p>Do not do formatting in <code>calculate_***</code> methods. You have <code>display_**</code> methods responsible for that. Let all the formatting be done there. Btw, maybe <code>format_***</code> would be a better name?</p></li>\n<li><p>Another question is how you initialize your days_dict. Maybe you would want to pass a dictionary with some already existing values as an argument to the constructor. Possibly make it optional, and if we don't pass anything initialize it with default values as you do now: </p>\n\n<pre><code>def __init__(self, worker, company, days_dict=None):\n self.worker = worker\n self.company = company\n # This can be a JSON file or a SQL DB\n self.days_dict = days_dict or DEFAULT_DAYS_DICT\n</code></pre>\n\n<p>Also, maybe it would be nicer to have default values like <code>\"Monday\": {\"start\": \"0000\", \"end\": \"0000\"}</code>?</p></li>\n<li><p>How about having a fluent API?</p>\n\n<pre><code>wt = WorkingTime('Maffaz', 'IT Circle Consult')\n .set_start_hour(\"monday\", \"0730\")\n .set_end_hour(\"monday\", \"1800\")\n ...\n .set_start_and_end(\"FrIDAY\", \"\", \"\")\n</code></pre>\n\n<p>For that you would need to return <code>self</code> object from every setter/getter:</p>\n\n<pre><code>def set_start_hour(self, day, hour):\n ...\n return self\n</code></pre></li>\n</ul>\n\n<p>* I wrote about situations where you would have to change a lot of code. The problem is actually not with changing it. The problem is that in some situations you might forget to do it and your program will start working incorrectly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T14:22:24.140", "Id": "435009", "Score": "0", "body": "I updated my code with your suggestions and some extra logic.. like remaining hours and the length of the working week.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T00:34:57.533", "Id": "224255", "ParentId": "224203", "Score": "2" } } ]
{ "AcceptedAnswerId": "224255", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T08:04:25.737", "Id": "224203", "Score": "6", "Tags": [ "python", "python-3.x", "datetime" ], "Title": "Calculate working hours using Python" }
224203
<p>I have a model called <code>Document</code>, in this I have a method that I use throughout my website to get the full path to the specific document:</p> <pre class="lang-php prettyprint-override"><code>public function getDocument($documentName = true) { $documentName = $documentName ? $this-&gt;name : null; return storage_path('app/' . $this-&gt;getPath() . $documentName); } public function getPath() { return "{$this-&gt;stream-&gt;token}/{$this-&gt;unique_id}/"; } </code></pre> <p>I use it like this (example):</p> <pre class="lang-php prettyprint-override"><code>$documentPath = $this-&gt;document-&gt;getDocument(); </code></pre> <p>However, as you can see, the document path is made up of:</p> <pre><code>$this-&gt;stream-&gt;token/$this-&gt;unique_id/ </code></pre> <p>Where <code>$this-&gt;stream-&gt;token</code> is calling a relationship in my Document model.</p> <pre class="lang-php prettyprint-override"><code>public function stream() { return $this-&gt;belongsTo(Stream::class); } </code></pre> <p>Now the method works - I can use the <code>getDocument()</code> to get the full path to the actual file (or just the folder, if I pass in <code>false</code>).</p> <p>However, this code is called from multiple places at different times - and because the folder structure is dependent on the <code>stream_token</code>, it makes a query to get the associated stream on each request.</p> <h1>Solution(s)?</h1> <p>I have tried adding a <code>$with = ['stream']</code> property to my Document model, so the associated stream is always loaded when fetching the model - but this I don't believe is a good option either, since then all the other queries I have for the document model, that don't care about the stream property make an extra query.</p> <p>What else can I do to improve the method and keep the # of queries to the database to a minimum?</p>
[]
[ { "body": "<p>I'm sorry, this is not an answer to your question, but it is a partial review of your code.</p>\n\n<p>It seems you've got a serious problem with choosing your names. They don't actually tell me what the purpose of the methods is, or the content of the variables. </p>\n\n<p>Your method <code>getDocument()</code> can do two things: Return the path or the folder of the document. The name doesn't tell me that. It should be something like <code>getDocumentPathOrFolder()</code>. The argument <code>$documentName</code> doesn't contain a document name. It's a boolean. The only way to find out, what really is contained in this argument, is to read the code in the method. It seems to decide whether a path or folder should be returned. A better name would have been <code>$addNameToFolder</code>. Still not ideal.</p>\n\n<p>To make matters worse you have a method called <code>getPath()</code> which, you've guessed it, doesn't return a path. By now I no idea what is actually returned by this method. </p>\n\n<p>If I'm allowed to completely rewrite your code, with a better structure and better names, it would look something like this:</p>\n\n<pre><code>class Document \n{\n\n public function getDocumentName()\n {\n return $this-&gt;documentName;\n }\n\n public function getDocumentFolder()\n {\n return storage_path(\"app/{$this-&gt;stream-&gt;token}/{$this-&gt;unique_id}/\"); \n }\n\n public function getDocumentPath()\n { \n return $this-&gt;getDocumentFolder() . $this-&gt;getDocumentName();\n }\n\n}\n</code></pre>\n\n<p>I assume that <code>storage_path()</code> is part of Laravel, and cannot be changed. The long argument to <code>storage_path()</code> should probably be split into its seperate parts, especially if you also use it elsewhere, but please, spent some time to choose good names.</p>\n\n<p>References:</p>\n\n<p><a href=\"http://carlosschults.net/en/how-to-choose-good-names\" rel=\"nofollow noreferrer\">Ten tips to help you choose good names</a></p>\n\n<p><a href=\"https://dev.to/rachelsoderberg/writing-good-method-variable-names-47il\" rel=\"nofollow noreferrer\">Writing Good Method &amp; Variable Names </a></p>\n\n<p><a href=\"https://carlalexander.ca/importance-naming-programming/\" rel=\"nofollow noreferrer\">The importance of naming in programming</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T12:59:34.337", "Id": "224217", "ParentId": "224209", "Score": "4" } } ]
{ "AcceptedAnswerId": "224217", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T11:03:39.050", "Id": "224209", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "A method to get a document's path" }
224209
<p>I have a list of items I pull from SharePoint and want to filter them in my custom list view page. So my function works exactly how I want, but it seems messy and I'm hoping someone could point me to or explain a better way of achieving this or an "optimized" version of what I did.</p> <p>I'm using a <code>for</code> loop with <code>if</code> to compare the values and display only when <code>true</code>. I have multiple filters and this is where it became tricky to me.</p> <p>In below code example: <code>incarr</code> array contains the list items. <code>arri</code> is amount of items in list received from SharePoint list:</p> <pre><code>function displaytable() { document.getElementById("myHTMLTable").innerHTML = ""; $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;th align='left'&gt;"+"&lt;b&gt;Systems Affected&lt;/b&gt;"+"&lt;/th&gt;" + "&lt;th width= 5% align='left'&gt;"+"&lt;b&gt;Incident Date&lt;/b&gt;"+"&lt;/th&gt;" + "&lt;th align='left'&gt;"+"&lt;b&gt;Incident Number&lt;/b&gt;"+"&lt;/th&gt;" + "&lt;th align='left'&gt;"+"&lt;b&gt;Root Cause&lt;/b&gt;"+"&lt;/th&gt;" + "&lt;th align='left'&gt;"+"&lt;b&gt;Description&lt;/b&gt;"+"&lt;/th&gt;" + "&lt;th width= 6% align='left'&gt;"+"&lt;b&gt;Attachments&lt;/b&gt;"+"&lt;/th&gt;" + "&lt;/tr&gt;"); var filtery = document.getElementById("dropdownyear").value; var filterm = document.getElementById("dropdownmonth").value.toUpperCase(); var filters = document.getElementById("dropdownsystem").value.toUpperCase(); var filtersev = document.getElementById("dropdownseverity").value.toUpperCase(); for (i=0;i&lt;arri;i++){ //manual if statements until I can figure our a more effective way if (incarr[i][6] == filtery &amp;&amp; incarr[i][5] == filterm &amp;&amp; incarr[i][0].toUpperCase() == filters &amp;&amp; filtersev == incarr[i][7].toUpperCase()){ $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + //full filter "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (incarr[i][6] == filtery &amp;&amp; incarr[i][5] == filterm &amp;&amp; filters == "SYSTEM" &amp;&amp; filtersev == incarr[i][7].toUpperCase() ) { $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + //system filter all "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (incarr[i][6] == filtery &amp;&amp; filterm == "MONTH" &amp;&amp; incarr[i][0].toUpperCase() == filters &amp;&amp; filtersev == incarr[i][7].toUpperCase() ){ $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + //Month filter all "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (incarr[i][6] == filtery &amp;&amp; filterm == "MONTH" &amp;&amp; filters == "SYSTEM" &amp;&amp; filtersev == incarr[i][7].toUpperCase() ){ $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + //Month &amp; System filter all "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (filtery == "YEAR" &amp;&amp; filterm == "MONTH" &amp;&amp; incarr[i][0].toUpperCase() == filters &amp;&amp; filtersev == incarr[i][7].toUpperCase() ){ $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + //Year &amp; Month filter all "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (incarr[i][6] == filtery &amp;&amp; incarr[i][5] == filterm &amp;&amp; filters == "SYSTEM" &amp;&amp; filtersev == "SEVERITY" ) { $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + //system, severity filter all "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (incarr[i][6] == filtery &amp;&amp; filterm == "MONTH" &amp;&amp; incarr[i][0].toUpperCase() == filters &amp;&amp; filtersev == "SEVERITY" ){ $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + //Month, severity filter all "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (incarr[i][6] == filtery &amp;&amp; filterm == "MONTH" &amp;&amp; filters == "SYSTEM" &amp;&amp; filtersev == "SEVERITY" ){ $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + //Month &amp; System &amp; Severity filter all "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); } else if (filtery == incarr[i][6] &amp;&amp; filterm == incarr[i][5] &amp;&amp; incarr[i][0].toUpperCase() == filters &amp;&amp; filtersev == "SEVERITY"){ $("#myHTMLTable").append("&lt;tr align='middle'&gt;" + "&lt;td align='left'&gt;"+incarr[i][0]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][1]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][2]+"&lt;/td&gt;" + //Severity filter all "&lt;td align='left'&gt;"+incarr[i][3]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][4]+"&lt;/td&gt;" + "&lt;td align='left'&gt;"+incarr[i][8]+"&lt;/td&gt;" + "&lt;/tr&gt;"); }; } } </code></pre> <p>when selecting a filter it must only display items matching that column, and I must be able to select multiple filters to filter the filtered list (if this makes sense?)</p>
[]
[ { "body": "<p>From a short review;</p>\n\n<ul>\n<li><code>filtery</code>, <code>filterm</code> etc. are unfortunate names, just go for <code>filterYear</code>, <code>filterMonth</code>, etc. It would make the code so much more readable and parseable. At the very least it should follow lowerCamelCase -> <code>filterY</code> and <code>filterM</code></li>\n<li><p>This piece of code has been copy pasted a number times, a mortal sin in code review. Please have a function that can be called.</p>\n\n<pre><code> $(\"#myHTMLTable\").append(\"&lt;tr align='middle'&gt;\" +\n \"&lt;td align='left'&gt;\"+incarr[i][0]+\"&lt;/td&gt;\" +\n \"&lt;td align='left'&gt;\"+incarr[i][1]+\"&lt;/td&gt;\" +\n \"&lt;td align='left'&gt;\"+incarr[i][2]+\"&lt;/td&gt;\" + //full filter\n \"&lt;td align='left'&gt;\"+incarr[i][3]+\"&lt;/td&gt;\" +\n \"&lt;td align='left'&gt;\"+incarr[i][4]+\"&lt;/td&gt;\" + \n \"&lt;td align='left'&gt;\"+incarr[i][8]+\"&lt;/td&gt;\" +\n \"&lt;/tr&gt;\"); \n</code></pre></li>\n<li>Your code seems to assume that <code>incarr[i][6]</code> will always contain the year. If you had a yearColumn constant (with the value of 6), you would just access <code>incarr[i][yearColumn]</code>. If one day the year is another column, then you only need to update the <code>yearColumn</code> constant. Look up <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">'Dont Repeat Yourself'</a></li>\n<li>Your code has about 8 lines of comment, of which 6 are the same copy pasted ones</li>\n<li>Variables like \"MONTH\" should be constants defined up top</li>\n<li>If you are using jQuery, then you might as well use more of the feature's, check out\n\n<ul>\n<li><a href=\"https://api.jquery.com/val/\" rel=\"nofollow noreferrer\">.val</a></li>\n<li><a href=\"https://api.jquery.com/html/\" rel=\"nofollow noreferrer\">.html</a></li>\n</ul></li>\n<li>Accessing <code>incarr[i]</code> so many times is hard on the reader, and also is a bit taxing on the JavaScript engine. Why not assign that to a variable in the beginning of the loop?</li>\n</ul>\n\n<p>All in all, that would lead me to an (obviously untested) alternative that looks like this:</p>\n\n<pre><code>function displaytable() { \n $(\"myHTMLTable\").html(\"&lt;tr align='middle'&gt;\" +\n \"&lt;th align='left'&gt;\"+\"&lt;b&gt;Systems Affected&lt;/b&gt;\"+\"&lt;/th&gt;\" +\n \"&lt;th width= 5% align='left'&gt;\"+\"&lt;b&gt;Incident Date&lt;/b&gt;\"+\"&lt;/th&gt;\" + \n \"&lt;th align='left'&gt;\"+\"&lt;b&gt;Incident Number&lt;/b&gt;\"+\"&lt;/th&gt;\" +\n \"&lt;th align='left'&gt;\"+\"&lt;b&gt;Root Cause&lt;/b&gt;\"+\"&lt;/th&gt;\" +\n \"&lt;th align='left'&gt;\"+\"&lt;b&gt;Description&lt;/b&gt;\"+\"&lt;/th&gt;\" + \n \"&lt;th width= 6% align='left'&gt;\"+\"&lt;b&gt;Attachments&lt;/b&gt;\"+\"&lt;/th&gt;\" + \n \"&lt;/tr&gt;\"); \n\n var filterYear = $(\"#dropdownyear\").val();\n var filterMonth = $(\"#dropdownmonth\").val().toUpperCase();\n var filterSystem = $(\"#dropdownsystem\").val().toUpperCase();\n var filterSeverity = $(\"#dropdownseverity\").val().toUpperCase(); \n var yearColumn = 6;\n var monthColumn = 5;\n var systemColumn = 0;\n var severityColumn = 7;\n\n for (i = 0; i &lt; arri; i++){\n var incident = incarr[i];\n\n if(filterYear != \"YEAR\" &amp;&amp; incident[yearColumn] != filterYear)\n continue;\n\n if(filterMonth != \"MONTH\" &amp;&amp; incident[monthColumn] != filterMonth)\n continue;\n\n if(filterSystem != \"SYSTEM\" &amp;&amp; incident[systemColumn] != filterSystem)\n continue;\n\n if(filterSeverity != \"SEVERITY\" &amp;&amp; incident[severityColumn] != filterSeverity)\n continue;\n\n $(\"#myHTMLTable\").append(\"&lt;tr align='middle'&gt;\" +\n \"&lt;td align='left'&gt;\" + incident[0] + \"&lt;/td&gt;\" +\n \"&lt;td align='left'&gt;\" + incident[1] + \"&lt;/td&gt;\" +\n \"&lt;td align='left'&gt;\" + incident[2] + \"&lt;/td&gt;\" + //full filter\n \"&lt;td align='left'&gt;\" + incident[3] + \"&lt;/td&gt;\" +\n \"&lt;td align='left'&gt;\" + incident[4] + \"&lt;/td&gt;\" + \n \"&lt;td align='left'&gt;\" + incident[8] + \"&lt;/td&gt;\" +\n \"&lt;/tr&gt;\"); \n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T06:04:03.767", "Id": "434986", "Score": "0", "body": "this is exactly the type of answer I where looking for, thanks for the suggestions Im going to test this out now and give feedback. sorry for the bad coding im self taught and still learning new concepts every day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T07:06:10.250", "Id": "434990", "Score": "0", "body": "thanks konijn i tested the code and its working perfectly. do you have a article i can read regarding the lowerCamelCase you suggested and when to use it? for example should it only be used for variables of specific type or is it for functions as well? i also read an article about using while loop instead of using for loop to improve performance do you know if this helps at all and if it will make much of a difference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T12:44:58.977", "Id": "435005", "Score": "0", "body": "This is my favourite coding standard: https://github.com/airbnb/javascript It has all that covered." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T16:01:48.253", "Id": "224224", "ParentId": "224210", "Score": "0" } }, { "body": "<p>One different approach could be to have the filtering be just toggling a CSS class so you can build the DOM once, and then just selectively show (/hide) rows. Speaking of CSS, all those inline style definitions should definitely go to a stylesheet.</p>\n\n<p>Multiple filters on the other hand are just <code>AND</code>ing them together.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// a couple of helpers to shorten code\nconst elem = (type, attrs = {}) =&gt;\n Object.assign(document.createElement.bind(document)(type), attrs)\nconst append = (parent, child) =&gt; (parent.appendChild(child), parent)\n\n// NOTE adapt to your date format\nconst yearPart = date =&gt; date.slice(0, 4)\nconst monthPart = date =&gt; date.slice(5, 7)\n\ndocument.addEventListener('DOMContentLoaded', () =&gt; {\n const incidents = document.getElementById('incidents')\n const filters = document.forms.filters\n\n // reduce the data into &lt;select&gt; &lt;option&gt;s and &lt;tbody&gt;\n const {options, tbody} = data.reduce((acc, ary) =&gt; {\n let [system, date] = ary\n let year = yearPart(date)\n let month = monthPart(date)\n\n append(acc.tbody, ary.reduce((tr, datum) =&gt;\n append(tr, elem('td', {textContent: datum}))\n , elem('tr')))\n\n acc.options.system.add(system)\n acc.options.year.add(year)\n acc.options.month.add(month)\n\n return acc\n }, {\n options: { system: new Set(), year: new Set(), month: new Set() }\n , tbody: elem('tbody')\n })\n\n // populate the &lt;select&gt;s\n Object.entries(options).forEach(([key, values]) =&gt;\n Array.from(values).sort().reduce((select, option) =&gt;\n append(select, elem('option', {textContent: option}))\n , filters[key]))\n\n // populate the &lt;table&gt;\n append(incidents, tbody)\n\n // or just disregard the above if the &lt;table&gt; and &lt;select&gt;s are\n // pre-populated.\n // actual filtering\n filters.addEventListener('change', evt =&gt; {\n const rows = incidents.querySelectorAll('tbody tr')\n\n rows.forEach(row =&gt; row.classList.remove('hidden'))\n\n // NOTE that this expects the order of the &lt;select&gt;s to match\n // the order of the fields (with the exception of date)\n Array.prototype.filter.call(rows, ({cells}) =&gt;\n !Array.from(document.forms.filters).reduce((bool, {value}, i) =&gt; {\n if(!value)\n return bool &amp;&amp; true\n\n switch(i) {\n case 1: return bool &amp;&amp; value == yearPart(cells[1].textContent)\n case 2: return bool &amp;&amp; value == monthPart(cells[1].textContent)\n default: return bool &amp;&amp; value == cells[i].textContent\n }\n }, true)\n ).forEach(row =&gt; row.classList.add('hidden'))\n })\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>table { width: 100%; border-collapse: collapse; table-layout: fixed }\ntd:nth-child(5) { width: 20%; overflow: hidden; white-space: nowrap }\nth { text-align: left }\nth, td { padding: .5ex; vertical-align: baseline }\n.hidden { display: none }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;meta charset=\"UTF-8\"&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n &lt;form id=\"filters\"&gt;\n &lt;label&gt;&lt;span&gt;system&lt;/span&gt;\n &lt;select id=\"system\"&gt;\n &lt;option&gt;\n &lt;/select&gt;\n &lt;/label&gt;\n\n &lt;label&gt;&lt;span&gt;year&lt;/span&gt;\n &lt;select id=\"year\"&gt;\n &lt;option&gt;\n &lt;/select&gt;\n &lt;/label&gt;\n\n &lt;label&gt;&lt;span&gt;month&lt;/span&gt;\n &lt;select id=\"month\"&gt;\n &lt;option&gt;\n &lt;/select&gt;\n &lt;/label&gt;\n\n &lt;/form&gt;\n\n &lt;table id=\"incidents\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;Systems affected&lt;/td&gt;\n &lt;th&gt;Incident date&lt;/td&gt;\n &lt;th&gt;Incident number&lt;/th&gt;\n &lt;th&gt;Root cause&lt;/th&gt;\n &lt;th&gt;Description&lt;/th&gt;\n &lt;th&gt;Attachments&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n\n &lt;/table&gt;\n &lt;/body&gt;\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T02:21:18.763", "Id": "224524", "ParentId": "224210", "Score": "0" } } ]
{ "AcceptedAnswerId": "224224", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T11:12:28.980", "Id": "224210", "Score": "2", "Tags": [ "javascript", "array" ], "Title": "Filter list items" }
224210
<p>Here is the question from the book of Mark Newman-Computational Physics Exc 5.1</p> <blockquote> <p>a) Read in the data and, using the trapezoidal rule, calculate from them the approximate distance traveled by the particle in the x direction as a function of time. See Section 2.4.3 on page 57 if you want a reminder of how to read data from a file. </p> <p>b) Extend your program to make a graph that shows, on the same plot, both the original velocity curve and the distance traveled as a function of time.</p> </blockquote> <p>the text file of the data.</p> <pre><code>0 0 1 0.069478 2 0.137694 3 0.204332 4 0.269083 5 0.331656 6 0.391771 7 0.449167 8 0.503598 9 0.554835 10 0.602670 11 0.646912 12 0.687392 13 0.723961 14 0.756491 15 0.784876 16 0.809032 17 0.828897 18 0.844428 19 0.855608 20 0.862439 21 0.864945 22 0.863172 23 0.857184 24 0.847067 25 0.832926 26 0.814882 27 0.793077 28 0.767666 29 0.738824 30 0.706736 31 0.671603 32 0.633638 33 0.593065 34 0.550118 35 0.505039 36 0.458077 37 0.409488 38 0.359533 39 0.308474 40 0.256576 41 0.204107 42 0.151330 43 0.098509 44 0.045905 45 -0.006228 46 -0.057640 47 -0.108088 48 -0.157338 49 -0.205163 50 -0.251347 51 -0.295685 52 -0.337984 53 -0.378064 54 -0.415757 55 -0.450909 56 -0.483382 57 -0.513052 58 -0.539809 59 -0.563563 60 -0.584234 61 -0.601764 62 -0.616107 63 -0.627235 64 -0.635136 65 -0.639814 66 -0.641289 67 -0.639596 68 -0.634786 69 -0.626922 70 -0.616085 71 -0.602366 72 -0.585872 73 -0.566720 74 -0.545039 75 -0.520970 76 -0.494661 77 -0.466272 78 -0.435970 79 -0.403929 80 -0.370330 81 -0.335357 82 -0.299201 83 -0.262054 84 -0.224114 85 -0.185575 86 -0.146636 87 -0.107492 88 -0.068339 89 -0.029370 90 0.009227 91 0.047268 92 0.084574 93 0.120970 94 0.156290 95 0.190375 96 0.223073 97 0.254244 98 0.283753 99 0.311479 100 0.337308 </code></pre> <p>my code</p> <pre><code>from numpy import array from pylab import loadtxt, plot, show, xlabel, ylabel, title,legend values = loadtxt("velocities.txt", float) time = (values[:, 0]).astype(int) # time values in float, using astypr to convert them into integer velocity = values[:, 1] # velocity values function = dict(zip(time, velocity)) N = len(time) - 1 # step size a = time[0] #x_initial b = time[-1] #x_final h = (b - a) // N #difference between each step S = 0 for k in range(1, N): S += function[a + k * h] total_distance = h * (1/2 * (function[a] + function[b]) + S) #the integral value of the velocity distance = [0] #the initial value for k in range(N): d = 1/2 * h * (function[a + k*h] + function[a + (k+1) * h]) distance.append(distance[-1] + d) plot(time, distance, "g--", label = "position") plot(time, velocity, "b-", label= "velocity") legend(loc='upper left') xlabel("Time(s)") title("Velocity vs Time and Distance vs Time") show() </code></pre> <p>Is the code correct? Does it looks like good code in terms of implementation of the trapezoidal rule?</p>
[]
[ { "body": "<p>Just a few things I noticed.</p>\n\n<h1>Utilize built in functions</h1>\n\n<p>This</p>\n\n<pre><code>S = 0\nfor k in range(1, N):\n S += function[a + k * h]\n</code></pre>\n\n<p>can be this</p>\n\n<pre><code>S = sum(function[a + k * h] for k in range(1, N))\n</code></pre>\n\n<p>Python3's <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"nofollow noreferrer\"><code>sum</code></a> takes an iterable, and returns the sum of all the values in that iterable. So, you can pass in the <code>for</code> loop and it will return the sum for you. Looks neater, too.</p>\n\n<h1>Operator Spacing</h1>\n\n<p>There should be a space before and after every operator and equal sign. Here's an example from your code:</p>\n\n<pre><code>d = 1/2 * h * (function[a + k*h] + function[a + (k+1) * h])\n</code></pre>\n\n<p>This should be </p>\n\n<pre><code>d = 1/2 * h * (function[a + k * h] + function[a + (k + 1) * h])\n</code></pre>\n\n<p>Spacing just helps you and other programmers read your code.</p>\n\n<p>This, however, doesn't apply when <em>passing default parameters</em>. Have a look:</p>\n\n<pre><code>plot(time, distance, \"g--\", label = \"position\") # WRONG\nplot(time, distance, \"g--\", label=\"position\") # RIGHT\n</code></pre>\n\n<h1>Variable Naming</h1>\n\n<p>A lot of single character variable names can confuse you, and make a program hard to read. I see you have comments such as <code>#x_initial</code> and <code>#x_final</code>. Why not use those as variable names? They're a lot more concise than <code>a</code> and <code>b</code>. <code>h</code> can also be something like <code>diff</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T08:11:43.937", "Id": "235592", "ParentId": "224211", "Score": "1" } }, { "body": "<h1>Δ​<em>t</em></h1>\n\n<p>Since you have the timestamps of the velocity measurements, there is no need to calculate the step size. For all you know, the steps are not even all equal.\nYou can use <code>np.diff</code> to calculate the differences between all the data points:</p>\n\n<pre><code>time_differences = (np.diff(time))\n</code></pre>\n\n<p>or in pure python:</p>\n\n<pre><code>time_differences = [b - a for a, b in zip(time, time[1:])]\n</code></pre>\n\n<p>or using the <code>pairwise</code> itertools recipe:</p>\n\n<pre><code>time_differences = [b - a for a, b in pairwise(time)]\n</code></pre>\n\n<h1>distance</h1>\n\n<p>How much the particle travelled in a certain period is then as simple as <code>velocity[1:] * dt</code>. To calculate the position from this, you take the cumulative sum:</p>\n\n<pre><code>distance= (velocity[1:] * time_differences).cumsum()\n</code></pre>\n\n<p>or in pure python using <code>itertools.accumulate</code>:</p>\n\n<pre><code>from itertools import accumulate\ndistance = list(\n accumulate(\n v * time_difference\n for v, time_difference in zip(velocity[1:], time_differences)\n )\n)\n</code></pre>\n\n<h1>formatting</h1>\n\n<p>I use <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black</a> (with a maximum line length of 79) to take care of formatting like spacing between operators.</p>\n\n<h1>pylab</h1>\n\n<p>Pylab takes care of a lot of things for you, but I prefer importing <code>numpy</code>, <code>matplotlib</code> etc. individually. Especially <code>from pylab import ...</code> can become problematic if you have a variable which you want to call <code>title</code> or <code>plot</code>. Which happens a lot for me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T09:39:28.920", "Id": "235644", "ParentId": "224211", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T11:23:47.737", "Id": "224211", "Score": "4", "Tags": [ "python", "algorithm", "numpy", "numerical-methods", "physics" ], "Title": "Trapezoidal rule for set of data" }
224211
<p>This is my first large project, a text based fighting simulator. </p> <p>It is very clunky, do you have any ideas on how to make the code better? and how to make the code not get printed at once</p> <pre class="lang-py prettyprint-override"><code> from __future__ import print_function #Zack Ennen 1/12/19 import random import time overheadmod = 3 slashmod = 0 jabmod = 1 def load(): print("Loading: *000000000 10%") time.sleep(.2) print("Loading: **00000000 20%") time.sleep(.2) print("Loading: ***0000000 30%") time.sleep(.2) print("Loading: ****000000 40%") time.sleep(.2) print("Loading: *****00000 50%") time.sleep(.2) print("Loading: ******0000 60%") time.sleep(.2) print("Loading: *******000 70%") time.sleep(.2) print("Loading: ********00 80%") time.sleep(.2) print("Loading: *********0 90%") time.sleep(.2) print("Loading: ********** 100%") print("Loading Complete, Enjoy The Game") start() def start(): global hpenemy global name name = raw_input("Please Select Your Fighters Name " ) global weapon weapon = raw_input("Please Select A Weapon, Axe, Sword, Or Dagger ") weapon = weapon.capitalize() global health global wepmod if weapon == "Axe": health = 30 wepmod = -1 genen() elif weapon == "Sword": health = 25 wepmod = 0 genen() elif weapon == "Dagger": health = 20 wepmod = 1 genen() else: start() def genen(): en = ["Mr,Stroop","Ork","Dragon","Goblin","Halfling","Wizard","Demon","DemiGod"] enwep = ["Club","Belt","Mace","Axe","Sword","Dagger"] secure_random = random.SystemRandom() global enemyweapon enemyweapon = secure_random.choice(enwep) global enemy enemy = secure_random.choice(en) global hpenemy hpenemy = random.randint(20,30) print(enemy + " Blocks Your Path Weilding A " + enemyweapon) attackphase1() def attackphase1(): print("*****Attack Phase*****") time.sleep(1) attack = raw_input("Would You Like To Attack " + enemy + " With Your " + weapon+ " Or Run (Attack Or Run) ") attack = attack.capitalize() if attack == "Attack": attack2() else: attackphase1() def attack2(): global power global hpenemy crit = random.randint(1,10) choice = raw_input("How Would You Like To Swing Your " + weapon + " Overhead, Slash, Or Jab ") choice = choice.capitalize() if choice == "Overhead": x = 1 elif choice == "Jab": x=3 elif choice == "Slash": x = 1 else: attack2() print(name + " Readys Their " + weapon + " For A " + choice + " Attack") time.sleep(1) power = random.randint(1,3) power = power + wepmod if choice == "Overhead": power = power + overheadmod elif choice == "Jab": power = power + jabmod else: power = power + slashmod if crit == 10: power = power * 2 print ("Critical Hit!") else: power = power + 0 time.sleep(1) print(name + " Swings " + weapon + " At " + enemy + " " + choice + " Dealing ", end="") print(power, end="") print(" Damage") time.sleep(1) hpenemy = hpenemy - power time.sleep(1) print(enemy + " Takes ", end="") print(power, end="") print(" Damage From " + name + "'s " + choice) time.sleep(1) print(enemy + " Has ", end="") print(hpenemy, end="") print(" Health Remaining") global hpenemy if hpenemy &lt;= 0: death() enemyattack() def enemyattack(): global health time.sleep(1) enpower = random.randint(1,7) print(enemy + " Swings At " + name + " With Their " + enemyweapon + " For ", end="") print(enpower) health = health - enpower time.sleep(1) print("You Have ", end="") print(health, end="") print(" Health Remaining") dead() def dead(): global health global hpenemy if hpenemy &lt;= 0: print("*****You Win*****") restart = raw_input("Do You Want To Play Again? Yes Or No ") restart = restart.capitlize() if restart == "Yes": load() else: exit elif health &lt;= 0: print("*****You Lose*****") restart = input("Do You Want To Play Again? Yes Or No ") restart = restart.capitlize() if restart == "Yes": load() else: exit else: x=2 attack2() load() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T11:53:50.237", "Id": "434864", "Score": "2", "body": "Welcome to Code Review! Please have a look at [How do I ask a good question?](/help/how-to-ask) and change your title in order to \"*[s]tate what your code does in your title, not your main concerns about it. Be descriptive and interesting, and you'll attract more views to your question.*\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T16:06:08.033", "Id": "434895", "Score": "0", "body": "This question is tagged \"python-3.x\", but the line `from __future__ import print_function` implies that this is actually Python 2 code. Can you confirm which version of Python you are using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T16:23:06.730", "Id": "434898", "Score": "0", "body": "in `attack2()` you call `death()` instead of `dead()`. Please fix this typo." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T16:47:48.410", "Id": "434901", "Score": "0", "body": "Another typo: in `dead()`, the two `.capitlize()`s shoud be `.capitalize()`s" } ]
[ { "body": "<p>I think the most important things to which you should pay attention are: </p>\n\n<ul>\n<li><p><strong>Avoid code duplication.</strong> Every time you find yourself writing the same or similar code even twice, think about using loops (hint: your <code>load</code> method) or extracting the code into a function (hint: <code>dead</code> method). The two most evident out of many existing reasons to avoid code duplication: 1) the code becomes shorter 2) if you need to change something in the logic that is repeated, you need to do it in only one place.</p></li>\n<li><p><strong>Do not use global variables.</strong> You should use them in very very rare cases. Instead, make functions exchange values via parameters. You may want to google why using global variables is so bad.</p></li>\n<li><p><strong>Dicts instead of multilevel elif statements</strong>. If you have something like:</p>\n\n<pre><code>if x==1:\n y = 'a'\n z = 67\nelif x==2:\n y = 'b'\n z = 77\nelif x == 3:\n y = 'c'\n z = 87\n...\n</code></pre>\n\n<p>probably you would want to you a <em>dictionary</em> instead: </p>\n\n<pre><code>dict_name = {1: ('a', 67), 2: ('b', 77), 3: ('c',87)}\ny,z = dict_name[x]\n</code></pre></li>\n<li><p>Regarding <strong>printing</strong>. First, format the string you want to print, then print it (do not call <code>print</code> 3 times to display one sentence). Also, avoid adding strings (with +) </p>\n\n<p>If you use python of version 3.6 and higher, you can you so-called <em>f-strings</em> instead:</p>\n\n<pre><code>print(f'You have {health} remaining')\n</code></pre>\n\n<p>Otherwise:</p>\n\n<pre><code>print('You have {0} remaining'.format(health))\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:49:53.097", "Id": "224246", "ParentId": "224212", "Score": "2" } }, { "body": "<h2>Structure and flow</h2>\n<h3>Add levels of abstraction</h3>\n<p>Your overall program structure is hard to read. You have a bunch of different functions calling each other in a loop/chain, which means you have to look at <em>all</em> of the code just to understand the basic sequence of events.</p>\n<p>One way to fix this problem is to add a <code>main()</code> function that defines the core sequence of your program (load, define player, define enemy, choose attack or run, exchange attacks, declare winner, restart-or-exit), and uses your other, more-specific functions as &quot;helpers&quot; to get the job done. Then the overall structure of the program is easy to understand, and you know which function to read to get further details on any particular step.</p>\n<pre><code>def main():\n restart = True\n while restart:\n load()\n generate_player()\n generate_enemy()\n enter_attack_phase()\n\n # exchange attacks \n global player_hp\n global enemy_hp\n while True:\n player_attack()\n if enemy_hp &lt;= 0:\n break\n enemy_attack()\n if player_hp &lt;= 0:\n break\n\n declare_winner()\n restart = ask_for_restart()\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>In fact, I would separate that &quot;exchange attacks&quot; code into its own function.</p>\n<pre><code>def exchange_attacks():\n global player_hp\n global enemy_hp\n while True:\n player_attack()\n if enemy_hp &lt;= 0:\n break\n enemy_attack()\n if player_hp &lt;= 0:\n break\n\ndef main():\n restart = True\n while restart:\n load()\n generate_player()\n generate_enemy()\n enter_attack_phase()\n exchange_attacks()\n declare_winner()\n restart = ask_for_restart()\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>You can think of this kind of code as having <em>levels</em>, where each level further down handles more and more fine detail, while each level further up binds those more-detailed functions together into a sensible structure. Each lower-level function acts as an <em>abstraction</em>: a generic idea that the higher levels can use without knowing all the messy details (like &quot;Attack each other until somebody dies&quot;).</p>\n<p>Levels of abstraction not only make your code easier to read and understand, but they also make it easier to change. For example, in the code above, if I decided to sometimes randomly give the enemy two attacks in a row instead of one, I could just edit <code>exchange_attacks()</code> to make that happen. I wouldn't have to make any changes to <code>main()</code> (higher level) <em>or</em> to <code>enemy_attack()</code> (lower level). The change is &quot;contained&quot; within its own level.</p>\n<p><em>Tip:</em> If you find yourself writing near-identical code in multiple places, you probably need to add a level of abstraction. Write a function to handle the lower-level messy details and swap that in for the duplicate code.</p>\n<pre><code>def capitalized_input(prompt):\n user_input = raw_input(prompt)\n return user_input.capitalize()\n</code></pre>\n<h3>Remove unnecessary recursive functions</h3>\n<p>You have several functions (<code>start()</code>, <code>attackphase1()</code>, <code>attack2()</code>) that call <em>themselves</em>, as a way of &quot;restarting&quot; if the user input is not valid. This is inefficient (since you have to re-do some work that is not related to accepting the user input) and hard to read.</p>\n<p>More generally, functions that call themselves (called <em>recursive functions</em>) can have some <strong>very</strong> weird and cool and hard-to-understand behaviors, so you shouldn't use them unless you really need them.</p>\n<p>Instead of recursive functions, use a <code>while</code> loop to retry until the user input is acceptable.</p>\n<pre><code>def attackphase1():\n print(&quot;*****Attack Phase*****&quot;)\n time.sleep(1)\n\n attack = &quot;&quot;\n while attack != &quot;Attack&quot;:\n attack = capitalized_input(&quot;Would You Like To Attack &quot; + enemy + &quot; With Your &quot; + weapon+ &quot; Or Run (Attack Or Run) &quot;)\n\n attack2()\n</code></pre>\n<h2>Data and data structures</h2>\n<h3>Remove unused variables</h3>\n<p>This is pretty basic. There are a few places in your code where you set a variable named <code>x</code>, but you never use it for anything. So we can remove it.</p>\n<h3>Use the right data structure for the job</h3>\n<p>For example, you have the enemy names and enemy weapon names stored in lists. Lists in python have two key properties:</p>\n<ol>\n<li>Lists are <em>ordered</em>. The third item in the list will always be the third item, unless the list is altered.</li>\n<li>Lists are <em>mutable</em>; they can be changed. You can add an item, remove an item, sort the entire list, and so on.</li>\n</ol>\n<p>But in this case, you don't care about ordering (because you are just picking one item randomly), and you don't care about mutability either (because you never update the list after it is created). You never use the features that set lists apart from other data structures. So we have to ask, is a list is the best choice?</p>\n<p>Looking at the other basic data structures:</p>\n<ul>\n<li>We don't want a <em>dict</em> because we're not dealing with key-value pairs.</li>\n<li>A <em>set</em> has some interesting properties: it's unordered, and comes with a uniqueness guarantee to make sure you can't add the same item twice. It even has an immutable version called <em>frozenset</em>. Unfortunately, <code>random.choice()</code> doesn't work with sets.</li>\n<li>Tuples are ordered like lists, but immutable.</li>\n</ul>\n<p>In this case the <em>tuple</em> is the basic data structure that best fits your needs. For more on Python's basic data structures, see <a href=\"https://docs.python.org/2.7/library/stdtypes.html\" rel=\"nofollow noreferrer\">the documentation</a>.</p>\n<pre><code> enemies = (&quot;Mr,Stroop&quot;,&quot;Ork&quot;,&quot;Dragon&quot;,&quot;Goblin&quot;,&quot;Halfling&quot;,&quot;Wizard&quot;,&quot;Demon&quot;,&quot;DemiGod&quot;)\n enemy_weapons = (&quot;Club&quot;,&quot;Belt&quot;,&quot;Mace&quot;,&quot;Axe&quot;,&quot;Sword&quot;,&quot;Dagger&quot;)\n</code></pre>\n<h3>Use data structures to store related values together</h3>\n<p>For example, the user's choice of weapon determines both their health and a modifier to their attack, but these values are connected to each other through a series of if-statements, which is awkward. Storing the values together in some kind of data structure, like a dictionary of tuples, makes the logic more compact (and therefore easier to read) and provides a handy central place to add new values or edit existing values in the future.</p>\n<pre><code># structure of dictionary is { weapon name: (player HP, weapon mod) }\nweapon_choice_to_player_stats = {\n &quot;Axe&quot;: (30, -1),\n &quot;Sword&quot;: (25, 0),\n &quot;Dagger&quot;: (20, 1)\n}\n</code></pre>\n<pre><code> global weapon\n while weapon not in weapon_choice_to_player_stats:\n raw_weapon = raw_input(&quot;Please Select A Weapon, Axe, Sword, Or Dagger &quot;)\n weapon = raw_weapon.capitalize()\n global health\n global wepmod\n health, wepmod = weapon_choice_to_player_stats[weapon]\n</code></pre>\n<p>Granted, it's a bit annoying to have to <em>remember</em> which number in the tuple is player health and which one is the weapons mod. What if you get them backwards? Well, you could create a more advanced nested structure of dictionaries-within-dictionaries...</p>\n<pre><code>weapon_choice_to_player_stats = {\n &quot;Axe&quot;: { &quot;health&quot;: 30, &quot;wepmod&quot;: -1 },\n &quot;Sword&quot;: { &quot;health&quot;: 25, &quot;wepmod&quot;: 0 },\n &quot;Dagger&quot;: { &quot;health&quot;: 20, &quot;wepmod&quot;: 1 }\n}\n</code></pre>\n<pre><code> stats = weapon_choice_to_player_stats[weapon]\n global health\n global wepmod\n health = stats[&quot;health&quot;]\n wepmod = stats[&quot;wepmod&quot;]\n</code></pre>\n<p>... or you could go so far as to create a <code>PlayerType</code> class and add the stats as properties of <code>PlayerType</code> objects. But that would open us up to a much deeper restructuring of other parts of the code, so let's set that possibility aside for now...</p>\n<p>Another example: <code>overheadmod</code>, <code>slashmod</code>, and <code>jabmod</code> are all used in the same specific place in one function, but are currently floating out there unattached to each other. It would make sense to group them together into a dictionary.</p>\n<p>I'll let you think of other instances.</p>\n<h3>Be careful with globals</h3>\n<p>You use the <code>global</code> keyword a lot. Global variables in general are considered &quot;risky&quot; in programming. Since they can be accessed from anywhere, it's harder to keep track of when and where they were modified or not modified, which makes it harder to write correct logic, which leads to bugs. You can also run into problems with scope, where you <em>think</em> you're using the global variable, but you're actually creating or calling on a local variable with the same name. Or vice versa. More bugs.</p>\n<p>So using all these <code>global</code>s is not <em>ideal</em>, but I think you can get away with it in this <em>specific</em> case for two reasons:</p>\n<ol>\n<li><code>global</code> variables in Python aren't truly &quot;global&quot; in the traditional sense; they are restricted to a specific module (i.e. they are not visible outside this file). So the amount of stuff that can go wrong is limited by that.</li>\n<li>This program is small and simple enough that you can hold the entire structure of the program in your head at once, so you're unlikely to lose track of which values are modified where. But if the program became much more complicated then <code>global</code>s would definitely be a bad idea.</li>\n</ol>\n<p>A related problem: instead of declaring all these module-wide / <code>global</code> variables in one place, you scatter the declarations throughout the code. This is hard to read and understand. A reader has to go on a scavenger hunt to understand what values are shared by different functions. It also triggers a warning message when you run the code (<code>SyntaxWarning: name 'hpenemy' is assigned to before global declaration</code>).</p>\n<p>So, at minimum, you should declare all the module-wide / <code>global</code> variables at the top of the module. That way you can see all the shared values in one place. Since it's unclear what values the variables should have at that point, give them &quot;empty&quot; values: <code>0</code>, <code>&quot;&quot;</code> (the empty string), <code>None</code>, etc.</p>\n<pre><code>enemy = &quot;&quot;\nenemyweapon = &quot;&quot;\nhealth = 0\nhpenemy = 0\nname = &quot;&quot;\npower = 0\nweapon = 0\nwepmod = 0\n\ndef load():\n ...\n</code></pre>\n<p>Looking at the code, I think <code>power</code> doesn't even <em>need</em> to be a <code>global</code>, and I would change some of the variable names to make them clearer and make them better match each other. E.g. <code>player_hp</code> and <code>enemy_hp</code> instead of <code>health</code> and <code>hpenemy</code>.</p>\n<p>But wait! If we remember our lesson from &quot;Use data structures to store related values together&quot;, we can bundle the player-related values and the enemy-related values together, reducing the number of <code>global</code> variables to 2.</p>\n<pre><code>player = None\nenemy = None\n\n...\n\ndef generate_enemy():\n ...\n\n global enemy\n enemy = {\n &quot;name&quot;: name,\n &quot;hp&quot;: hp,\n &quot;weapon_name&quot;: weapon_name\n }\n\n print(&quot;{} Blocks Your Path Wielding A {}&quot;.format(enemy[&quot;name&quot;], enemy.[&quot;weapon_name&quot;]))\n</code></pre>\n<p>Better yet: instead of using dicts for our <code>player</code> and <code>enemy</code> global variables, we can create some lightweight classes that serve the same role. The advantage of a class is reusability: if for some reason you had two different functions that could both create enemies, you could just call the <code>Enemy</code> class constructor twice, instead of having to type out the whole enemy dict structure in two different places in the code.</p>\n<pre><code>player = None\nenemy = None\n\n\nclass Player(object):\n def __init__(self, name, hp, weapon_name, weapon_attack_mod):\n self.name = name\n self.hp = hp\n self.weapon_name = weapon_name\n self.weapon_attack_mod = weapon_attack_mod\n\n\nclass Enemy(object):\n def __init__(self, name, hp, weapon_name):\n self.name = name\n self.hp = hp\n self.weapon_name = weapon_name\n\n...\n\ndef generate_enemy():\n ...\n\n global enemy\n enemy = Enemy(name, hp, weapon_name)\n\n print(&quot;{} Blocks Your Path Wielding A {}&quot;.format(enemy.name, enemy.weapon_name))\n</code></pre>\n<p>Of course, now that we only have two variables to deal with instead of 8, it becomes a lot easier to just avoid using <code>global</code>s altogether, and just pass them back and forth between functions as parameters:</p>\n<pre><code>def exchange_attacks(player, enemy):\n while True:\n player_attack(player, enemy)\n if enemy.hp &lt;= 0:\n break\n enemy_attack(player, enemy)\n if player.hp &lt;= 0:\n break\n\ndef main():\n restart = True\n while restart:\n load()\n player = generate_player()\n enemy = generate_enemy()\n enter_attack_phase(player, enemy)\n exchange_attacks(player, enemy)\n declare_winner(player, enemy)\n restart = ask_for_restart()\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>So in the end we didn't need <code>global</code>s after all.</p>\n<h2>Miscellaneous</h2>\n<h3>Code Style</h3>\n<p>The developers of Python have a number of recommendations for how to make your code look nice: where to use line breaks, how long your lines should be, whether or not to put spaces before or after certain symbols, etc. You have a few minor violations here (no spaces after commas, etc.). It's not a huge deal, but abiding by the guidelines can help make your code more readable. See the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 document</a> for further details. A text editor plugin like Pylint can help you keep track of this as you write code (and detect actual code errors too, which is nice).</p>\n<h2>Putting it all together</h2>\n<p>Here's my revision of your code using the principles I've discussed. There might still be some room for improvement; for instance, I didn't look to see if there's a cleaner way of separating the &quot;UI logic&quot; (the code that prints to the screen and gets use inputs back) from the &quot;business logic&quot; (the code that actually computes the attacks and hit points). Right now everything is kind of mixed together. Then again, it might not be worth your time to separate them unless the program gets bigger and more complicated.</p>\n<pre><code>from __future__ import print_function\nimport random\nfrom time import sleep\n\n\nclass Player(object):\n def __init__(self, name, hp, weapon, weapon_attack_mod):\n self.name = name\n self.hp = hp\n self.weapon = weapon\n self.weapon_attack_mod = weapon_attack_mod\n\n\nclass Enemy(object):\n def __init__(self, name, hp, weapon):\n self.name = name\n self.hp = hp\n self.weapon = weapon\n\n\ndef capitalized_input(prompt):\n user_input = raw_input(prompt)\n return user_input.capitalize()\n\n\ndef print_and_sleep(msg, time_to_sleep=1):\n print(msg)\n sleep(time_to_sleep)\n\n\ndef build_loading_message(percent_loaded, bar_length,\n loaded_char='*', unloaded_char='0'):\n num_loaded_chars = percent_loaded // bar_length\n num_unloaded_chars = bar_length - num_loaded_chars\n return &quot;Loading: {}{} {}%&quot;.format(loaded_char * num_loaded_chars,\n unloaded_char * num_unloaded_chars,\n percent_loaded)\n\n\ndef load():\n bar_length = 10\n for percent in range(10, 100, 10):\n msg = build_loading_message(percent, bar_length)\n print_and_sleep(msg, .2)\n print(build_loading_message(100, bar_length))\n print(&quot;Loading Complete, Enjoy The Game&quot;)\n\n\ndef generate_player():\n weapon_choice_to_player_stats = {\n &quot;Axe&quot;: {&quot;base_hp&quot;: 30, &quot;weapon_attack_mod&quot;: -1},\n &quot;Sword&quot;: {&quot;base_hp&quot;: 25, &quot;weapon_attack_mod&quot;: 0},\n &quot;Dagger&quot;: {&quot;base_hp&quot;: 20, &quot;weapon_attack_mod&quot;: 1}\n }\n\n name = raw_input(&quot;Please Select Your Fighter's Name: &quot;)\n weapon = &quot;&quot;\n while weapon not in weapon_choice_to_player_stats:\n weapon = capitalized_input(\n &quot;Please Select A Weapon (Axe, Sword, Or Dagger): &quot;)\n\n chosen_stats = weapon_choice_to_player_stats[weapon]\n hp = chosen_stats[&quot;base_hp&quot;]\n weapon_attack_mod = chosen_stats[&quot;weapon_attack_mod&quot;]\n\n player = Player(name, hp, weapon, weapon_attack_mod)\n return player\n\n\ndef generate_enemy():\n enemy_names = (&quot;Mr. Stroop&quot;, &quot;Ork&quot;, &quot;Dragon&quot;, &quot;Goblin&quot;,\n &quot;Halfling&quot;, &quot;Wizard&quot;, &quot;Demon&quot;, &quot;DemiGod&quot;)\n enemy_weapons = (&quot;Club&quot;, &quot;Belt&quot;, &quot;Mace&quot;, &quot;Axe&quot;, &quot;Sword&quot;, &quot;Dagger&quot;)\n\n secure_random = random.SystemRandom()\n name = secure_random.choice(enemy_names)\n hp = secure_random.randint(20, 30)\n weapon = secure_random.choice(enemy_weapons)\n\n enemy = Enemy(name, hp, weapon)\n print(&quot;{} Blocks Your Path Wielding A {}&quot;.format(enemy.name, enemy.weapon))\n return enemy\n\n\ndef enter_attack_phase(player, enemy):\n print_and_sleep(&quot;*****Attack Phase*****&quot;)\n\n action = &quot;&quot;\n while action != &quot;Attack&quot;:\n action = capitalized_input(\n &quot;Would You Like To Attack {} With Your &quot;\n &quot;{} Or Run (Attack Or Run) &quot;.format(enemy.name, player.weapon))\n\n\ndef player_attack(player, enemy):\n attack_type_modifiers = {\n &quot;Overhead&quot;: 3,\n &quot;Slash&quot;: 0,\n &quot;Jab&quot;: 1\n }\n\n attack_type = &quot;&quot;\n while attack_type not in attack_type_modifiers:\n attack_type = capitalized_input(\n &quot;How Would You Like To Swing Your &quot;\n &quot;{} Overhead, Slash, Or Jab &quot;.format(player.weapon))\n\n print_and_sleep(&quot;{} Readies Their {} For A {} Attack&quot;.format(\n player.name, player.weapon, attack_type))\n\n base_power = random.randint(1, 3)\n power = (base_power\n + player.weapon_attack_mod\n + attack_type_modifiers[attack_type])\n crit = random.randint(1, 10)\n if crit == 10:\n power = power * 2\n print_and_sleep(&quot;Critical Hit!&quot;)\n\n print_and_sleep(&quot;{} Swings {} At {} {} Dealing {} Damage&quot;.format(\n player.name, player.weapon, enemy.name, attack_type, power))\n\n enemy.hp = enemy.hp - power\n\n print_and_sleep(&quot;{} Takes {} Damage From {}'s {}&quot;.format(\n enemy.name, power, player.name, attack_type))\n print_and_sleep(&quot;{} Has {} Health Remaining&quot;.format(enemy.name, enemy.hp))\n\n\ndef enemy_attack(player, enemy):\n power = random.randint(1, 7)\n print_and_sleep(&quot;{} Swings At {} With Their {} For {}&quot;.format(\n enemy.name, player.name, enemy.weapon, power))\n\n player.hp = player.hp - power\n print_and_sleep(&quot;You Have {} Health Remaining&quot;.format(player.hp))\n\n\ndef decide_winner(player, enemy):\n if enemy.hp &lt;= 0:\n print(&quot;*****You Win*****&quot;)\n elif player.hp &lt;= 0:\n print(&quot;*****You Lose*****&quot;)\n else:\n raise ValueError(&quot;Cannot decide winner while &quot;\n &quot;both sides have health remaining&quot;)\n\n\ndef ask_for_restart():\n acceptable_responses = (&quot;Yes&quot;, &quot;No&quot;)\n response = &quot;&quot;\n while response not in acceptable_responses:\n response = capitalized_input(&quot;Do You Want To Play Again? Yes Or No &quot;)\n return response == &quot;Yes&quot;\n\n\ndef exchange_attacks(player, enemy):\n while True:\n player_attack(player, enemy)\n if enemy.hp &lt;= 0:\n break\n enemy_attack(player, enemy)\n if player.hp &lt;= 0:\n break\n\n\ndef main():\n restart = True\n while restart:\n load()\n player = generate_player()\n enemy = generate_enemy()\n enter_attack_phase(player, enemy)\n exchange_attacks(player, enemy)\n decide_winner(player, enemy)\n restart = ask_for_restart()\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T00:17:32.630", "Id": "435074", "Score": "0", "body": "@zack-ennen Sorry this got so long, I'm not good at summarizing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T00:13:19.410", "Id": "224314", "ParentId": "224212", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T11:29:09.470", "Id": "224212", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "battle-simulation" ], "Title": "Text based fighting simulator in Python" }
224212
<p>An alternative to <code>std::vector&lt;std::function&lt; &gt;&gt;</code> which uses tail recursion to optimize calling the functions sequentially. I'm using this on a real-time DSP thread. Because the code does single-sample processing, dispatch overhead must be minimized, since the functions (which are usually rather simple) are called 44k times/sec (Note: my target platform, iOS, does not allow JITting).</p> <p>This approaches the performance of computed goto dispatch, but is extensible due to lambdas.</p> <p>Half of the calling overhead on my machine (<code>clang++ -std=c++17 -O3</code>, YMMV):</p> <pre><code>vector&lt;function&lt;void()&gt;&gt; average time: 0.058752 seconds func_vec&lt;&gt; average time: 0.025793 seconds </code></pre> <p>I suspect performance could be further improved by eliminating the virtual function dispatch. I haven't proved if allocating the functions contiguously helps (the idea is to have the lambda closures in the same cache line). Without tail recursion, performance is comparable.</p> <p>Note: I'm <strong>not</strong> trying to create a drop-in replacement for <code>std::vector&lt;std::function&lt;...&gt;&gt;</code>.</p> <p><strong>Complete Code</strong></p> <pre><code>#include &lt;new&gt; // An array of functions which you can subsequently call. // This allocates the functions contiguously. // Can use tail recursion to beat vector&lt;function&lt;...&gt;&gt; template&lt;typename... Arguments&gt; class func_vec { public: // Don't implement copying yet. func_vec(const func_vec&amp;) = delete; func_vec&amp; operator=(const func_vec&amp;) = delete; func_vec() { _storage = new char[sizeof(end_t)]; new (_storage) end_t; _size = sizeof(end_t); _capacity = sizeof(end_t); } ~func_vec() { auto h = reinterpret_cast&lt;holder*&gt;(_storage); while(h) { auto n = h-&gt;next(); h-&gt;~holder(); h = n; } } // Add a callable. template&lt;class F&gt; void push_back(F f) { auto sz = sizeof(callable&lt;F&gt;); // Enlarge our buffer, copying over things. _enlarge_by(sz); // Replace the end object with our callable. auto p = _storage+_size-sizeof(end_t); new (p) callable&lt;F&gt;(f); // Add a new end object. new (p + sz) end_t; _size += sz; } // Run our chain of functions. void execute(Arguments... args) { auto h = reinterpret_cast&lt;holder*&gt;(_storage); while(h) { h = h-&gt;call(args...); } } // Run with tail recursion. void exec_tail(Arguments... args) { auto h = reinterpret_cast&lt;holder*&gt;(_storage); h-&gt;call_tail(args...); } private: struct holder { virtual ~holder() { } virtual holder* call(Arguments...) = 0; virtual void call_tail(Arguments...) = 0; virtual size_t clone_to(void* storage) = 0; virtual holder* next() = 0; }; template&lt;class Lambda&gt; struct callable : public holder { Lambda lambda; callable(Lambda l) : lambda(l) { } holder* call(Arguments... args) override { // This call to the lambda should be inlined. lambda(args...); return this+1; // Achievement unlocked! } void call_tail(Arguments... args) override { lambda(args...); holder* next = this+1; next-&gt;call_tail(args...); } size_t clone_to(void* storage) override { new (storage) callable(lambda); return sizeof(callable); } holder* next() override { return this+1; } }; struct end_t : public holder { holder* call(Arguments... args) override { return nullptr; // terminate iteration } void call_tail(Arguments... args) override { // Terminate tail recursion. } size_t clone_to(void* storage) override { new (storage) end_t; return sizeof(end_t); } holder* next() override { return nullptr; } }; void _enlarge_by(size_t sz) { if(_size + sz &gt;= _capacity) { // Reallocate and clone everything. _capacity = _capacity * 2 + sz; char* new_storage = new char[_capacity]; size_t offset = 0; if(_storage) { auto h = reinterpret_cast&lt;holder*&gt;(_storage); while(h) { offset += h-&gt;clone_to(new_storage+offset); auto n = h-&gt;next(); h-&gt;~holder(); h = n; } } delete[] _storage; _storage = new_storage; } } char* _storage = nullptr; unsigned long _size = 0; unsigned long _capacity = 0; }; </code></pre> <p><strong>Test Code</strong></p> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctime&gt; #include &lt;cassert&gt; #include &lt;vector&gt; #include &lt;new&gt; #include &lt;functional&gt; #include &lt;string&gt; #include &lt;chrono&gt; #include "func_vec.hpp" const int N = 1000; const int M = 10000; // Fill a func_vec with 10 different functions to try // to foil the branch predictor. template&lt;class V&gt; void make_funcs(int* vars, V&amp; v) { srand(0); for(int i=0;i&lt;N;++i) { switch(rand() % 10) { case 0: v.push_back([vars] { vars[0]++; }); break; case 1: v.push_back([vars] { vars[1]++; }); break; case 2: v.push_back([vars] { vars[2]++; }); break; case 3: v.push_back([vars] { vars[3]++; }); break; case 4: v.push_back([vars] { vars[4]++; }); break; case 5: v.push_back([vars] { vars[5]++; }); break; case 6: v.push_back([vars] { vars[6]++; }); break; case 7: v.push_back([vars] { vars[7]++; }); break; case 8: v.push_back([vars] { vars[8]++; }); break; case 9: v.push_back([vars] { vars[9]++; }); break; } } } using std::vector; using std::function; using namespace std::chrono; void sanity() { func_vec&lt;&gt; v; int x=0; for(int i=0;i&lt;N;++i) { v.push_back([&amp;x] { ++x; }); } v.exec_tail(); assert(x == N); } const int runs = 12; const int preroll = 2; // Ignore first two runs as preroll. void std_function_perf() { double t = 0; for(int i=0;i&lt;runs;++i) { vector&lt;function&lt;void()&gt;&gt; v; int vars[10] = {0}; make_funcs(vars, v); auto start = high_resolution_clock::now(); for(int i=0;i&lt;M;++i) { for(auto&amp; f : v) { f(); } } if(i &gt; preroll) { t += duration_cast&lt;duration&lt;double&gt;&gt;(high_resolution_clock::now()-start).count(); } } printf("vector&lt;function&lt;void()&gt;&gt; average time: %f seconds\n", t / (runs-preroll)); } void func_vec_perf() { double t = 0; for(int i=0;i&lt;runs;++i) { func_vec&lt;&gt; v; int vars[10] = {0}; make_funcs(vars, v); auto start = high_resolution_clock::now(); for(int i=0;i&lt;M;++i) { v.exec_tail(); } if(i &gt; preroll) { t += duration_cast&lt;duration&lt;double&gt;&gt;(high_resolution_clock::now()-start).count(); } } printf("func_vec&lt;&gt; average time: %f seconds\n", t / (runs-preroll)); } int main(int argc, char* argv[]) { sanity(); std_function_perf(); func_vec_perf(); // I tried running each test in a separate process // but result were the same. /* if(argc &lt; 2) { printf("usage: test_func_vec [std|func_vec]\n"); return 0; } if(string(argv[1]) == "std") { std_function_perf(); } if(string(argv[1]) == "func_vec") { func_vec_perf(); } */ printf("DONE!\n"); } </code></pre> <p><strong>Review Goals</strong></p> <ol> <li>Does it perform similarly on your machine?</li> <li>Have I tested performance adequately?</li> <li>Ideas for further performance improvement.</li> <li>Is there a simpler way to express this while maintaining performance?</li> </ol>
[]
[ { "body": "<p>Don't like this:</p>\n\n<pre><code> if(i &gt; preroll) {\n t += duration_cast&lt;duration&lt;double&gt;&gt;(high_resolution_clock::now()-start).count();\n\n }\n</code></pre>\n\n<p>The call to finish the clock is inside the <code>if</code> statement. Thus you are timing branch failure successes.</p>\n\n<pre><code> auto end = high_resolution_clock::now();\n if(i &gt; preroll) {\n t += duration_cast&lt;duration&lt;double&gt;&gt;(end - start).count();\n }\n</code></pre>\n\n<p>I think the number of iterations is way too low:</p>\n\n<pre><code>const int M = 10000; // hard to rule out noise.\nconst int runs = 12; // Maybe a couple of million calls.\n\n\nconst int preroll = 2; // I suppose this helps in getting caches warm.\n // But I would simply prefer to run it a lot times.\n</code></pre>\n\n<p>To make sure is no effect on memory because of one test helping the other I would run the test in both orders and average the results.</p>\n\n<pre><code>#ifndef REVERSE_TEST_ORDER\n\nstd_function_perf();\nfunc_vec_perf();\n\n#else\n\nfunc_vec_perf();\nstd_function_perf();\n\n#endif\n</code></pre>\n\n<p>Also I note that the average you print is the average over the number of runs. But each run executes all the numbers <code>M</code> times.</p>\n\n<pre><code>vector&lt;function&lt;void()&gt;&gt; average time: 0.058752 seconds\nfunc_vec&lt;&gt; average time: 0.025793 seconds\n</code></pre>\n\n<p>So we really need to divide these numbers by another <code>10,000</code>!</p>\n\n<pre><code>vector&lt;function&lt;void()&gt;&gt; average time: 0.0000058752 seconds\nfunc_vec&lt;&gt; average time: 0.0000025793 seconds\n</code></pre>\n\n<p>Then there is 10 functions per vector. So we need to divide that by another 10.</p>\n\n<pre><code>vector&lt;function&lt;void()&gt;&gt; average time: 0.00000058752 seconds\nfunc_vec&lt;&gt; average time: 0.00000025793 seconds\n</code></pre>\n\n<p>So .2 micro seconds against .5 micro seconds per call.</p>\n\n<h2>Bug</h2>\n\n<p>I thikn this is a bug:</p>\n\n<pre><code>// Replace the end object with our callable.\nauto p = _storage+_size-sizeof(end_t);\n\n// Need to destroy the old `end_t` so its lifetime ends before you\n// can call the constructer to create an object over it.\nreinterpret_cast&lt;holder*&gt;(p)-&gt;~holder();\n\n// Now you can write over it.\nnew (p) callable&lt;F&gt;(f);\n\n// Add a new end object.\nnew (p + sz) end_t;\n</code></pre>\n\n<h2>ReDesign</h2>\n\n<p>I would separate out the resource management and business logic in func_vec. Id did this and replaced the resource management by using std::vector> and simplified the code to:</p>\n\n<pre><code>template&lt;typename... Arguments&gt;\nclass func_vec {\n\n private:\n\n struct holder {\n holder(holder* next = nullptr): next(next) {}\n virtual ~holder() { } \n virtual holder* call(Arguments...) = 0;\n virtual void call_tail(Arguments...) = 0;\n void setNext(holder* n) {\n next = n;\n } \n holder* next;\n }; \n\n template&lt;class Lambda&gt;\n struct callable : public holder {\n Lambda lambda;\n callable(Lambda l, holder* next) : holder(next), lambda(l) { } \n holder* call(Arguments... args) override {\n // This call to the lambda should be inlined.\n lambda(args...);\n return this-&gt;next;\n } \n void call_tail(Arguments... args) override {\n lambda(args...);\n this-&gt;next-&gt;call_tail(args...);\n } \n }; \n\n struct end_t : public holder {\n holder* call(Arguments... args) override {\n return nullptr; // terminate iteration\n } \n void call_tail(Arguments... args) override {\n // Terminate tail recursion.\n } \n }; \n std::vector&lt;std::unique_ptr&lt;holder&gt;&gt; data;\n end_t end;\n public:\n // Add a callable.\n template&lt;class F&gt;\n void push_back(F f) {\n std::unique_ptr&lt;callable&lt;F&gt;&gt; next(std::make_unique&lt;callable&lt;F&gt;&gt;(f,&amp;end));\n if (!data.empty()) {\n data.back()-&gt;setNext(next.get());\n }\n data.push_back(std::move(next));\n }\n\n // Run our chain of functions.\n void execute(Arguments... args) {\n holder* h = data.front().get();\n while(h != nullptr) {\n h = h-&gt;call(args...);\n }\n }\n\n // Run with tail recursion.\n void exec_tail(Arguments... args) {\n data.front()-&gt;call_tail(args...);\n }\n\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T22:23:56.720", "Id": "435242", "Score": "0", "body": "Did moving the call to stop the clock change the result? I'm guessing no since that's some tiny fraction of the total work involved in the test. Each test run makes 100m calls. Also, did you see the commented out code where I tried running each test in a separate process? It made no difference in the result. Also, no there are N=1000 functions in each vector, they are just chosen at random from 10 possible functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:50:43.037", "Id": "435247", "Score": "0", "body": "OK. Missed the extra `N`. That makes me more comfortable about the number of times the function was called. `N * M * (runs - preroll)` = 100,000,000." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:53:44.650", "Id": "435248", "Score": "0", "body": "`Did moving the call to stop the clock change the result?` I did not try. I am here to review your code like a colleague would do in a big company. My suggestions would be one that I would expect to see so that once I see the results I am confident that the results are accurate. If you don't want to change fine. But then similarly I would not feel confident vouching to our boss that I though you had done a good job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:56:31.540", "Id": "435249", "Score": "0", "body": "The results seem like approximately what I would expect. Your technique takes twice the time. But that is what I would expected as you have added an additional layer of virtual function calls." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T19:47:17.607", "Id": "224363", "ParentId": "224219", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T13:53:20.713", "Id": "224219", "Score": "7", "Tags": [ "c++", "performance" ], "Title": "alternative to std::vector<std::function<...>> which uses tail recursion" }
224219
<p>Is this a good compromise between readability and verbosity? Are there any bugs, additional error checking, or extraneous code as well?</p> <pre><code>// Generate permutations of array of n..n+x // n must have no repetitions, sorted smallest to largest // Steinhaus-Johnson-Trotter algorithm // Results are not in lexicographical order // Switch to using a generator when n! becomes too large. ~12 or 13 probably. #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; enum directions { LEFT, RIGHT }; int **permute(int array[], int n); bool mobile(int array[], int dir[], int count, int n); void swap(int array[], int a, int b); void printArray(int *array, int n, char c); long long factorial(int n); int **permute(int array[], int n) { if (n &lt; 1) { return NULL; } int bigInd; // index of largest mobile num int bigNum; // largest mobile num bool ismobile; // If there is still a mobile number int counter = 0; int fact = factorial(n); int *dir; int **res; if ((dir = malloc(n * sizeof(int))) == NULL) { fprintf(stderr, "Error allocating memory\n"); exit(EXIT_FAILURE); } for (int i = 0; i &lt; n; i++) { dir[i] = LEFT; } if ((res = malloc(fact * sizeof(int *))) == NULL) { fprintf(stderr, "Error allocating memory\n"); exit(EXIT_FAILURE); } for (int i = 0; i &lt; fact; i++) { if ((res[i] = malloc(n * sizeof(int))) == NULL) { fprintf(stderr, "Error allocating memory\n"); exit(EXIT_FAILURE); } } while (1) { memcpy(res[counter], array, n * sizeof(int)); counter++; bigInd = 0; bigNum = 0; ismobile = false; for (int i = 0; i &lt; n; i++) { if (mobile(array, dir, n, i)) { ismobile = true; if (array[i] &gt; bigNum) { bigInd = i; bigNum = array[i]; } } } if (!ismobile) { break; } if (dir[bigInd] == LEFT) { swap(array, bigInd, bigInd - 1); swap(dir, bigInd, bigInd - 1); } else { swap(array, bigInd, bigInd + 1); swap(dir, bigInd, bigInd + 1); } for (int i = 0; i &lt; n; i++) { if (array[i] &gt; bigNum) { dir[i] = !(dir[i]); } } } free(dir); return res; } void swap(int array[], int a, int b) { int temp = array[a]; array[a] = array[b]; array[b] = temp; } bool mobile(int array[], int dir[], int count, int n) { if ((n == 0 &amp;&amp; dir[n] == LEFT) || (n + 1 == count &amp;&amp; dir[n] == RIGHT) || (dir[n] == RIGHT &amp;&amp; array[n + 1] &gt; array[n]) || (dir[n] == LEFT &amp;&amp; array[n - 1] &gt; array[n])) { return false; } return true; } void printArray(int array[], int n, char c) { if (!array || n &lt; 1) { return; } for (int i = 0; i &lt; n; i++) { printf("%d", array[i]); } printf("%c", c); } long long factorial(int n) { long long result = 1; for (long long i = n; i &gt; 1; i--) { result *= i; } return result; } int main(void) { int a[] = {1, 2, 3, 4, 5}; int length = sizeof(a) / sizeof(a[0]); int fact = factorial(length); int **r = permute(a, length); for (long long i = 0; i &lt; fact; i++) { printf("%*lld: ", 3, i + 1); printArray(r[i], length, '\n'); } for (long long i = 0; i &lt; fact; i++) { free(r[i]); } free(r); } </code></pre>
[]
[ { "body": "<h2>verbose vs readable</h2>\n\n<p>Why choose?</p>\n\n<p>Just encapsulate all the explicit code and error checkings into functions (if possible) or macros (only when functions can't do it), and have a clean high level function.</p>\n\n<hr>\n\n<h2>Safe usage of <code>malloc()</code></h2>\n\n<p>Malloc is easily misused. Problems using malloc are the following:</p>\n\n<ul>\n<li><code>sizeof(type)</code> vs <code>sizeof(*foo)</code>:</li>\n</ul>\n\n<p><code>foo = malloc(sizeof(*foo) * nmemb);</code> is better because if you ever change the type of <code>foo</code>, this call will still be valid, while if not, you would have to change every line where malloc is called with foo. If you forget any of those lines, good luck!</p>\n\n<ul>\n<li>overflow:</li>\n</ul>\n\n<p>If <code>(sizeof(*foo) * nmemb) &gt; SIZE_MAX</code>, it will silently wrap around, and allocate a very small amount of memory, and you will most likely end up accessing memory that you shouldn't.</p>\n\n<p>Solution:</p>\n\n<p><a href=\"https://codereview.stackexchange.com/a/223175/200418\">Use this enclosure around <code>malloc</code></a></p>\n\n<hr>\n\n<h2><code>sizeof(type)</code> vs <code>sizeof(*foo)</code></h2>\n\n<p>As I said above, use the second. Apart from <code>malloc</code> you also have this problem in <code>memcpy</code>.</p>\n\n<hr>\n\n<h2><code>fprintf(stderr, ...)</code> + <code>exit()</code></h2>\n\n<p>You could combine those two in just one function call:</p>\n\n<p><a href=\"http://man7.org/linux/man-pages/man3/error.3.html\" rel=\"nofollow noreferrer\"><code>error()</code></a>: GNU extension</p>\n\n<p><a href=\"http://man7.org/linux/man-pages/man3/err.3.html\" rel=\"nofollow noreferrer\"><code>err()</code></a>: BSD extension</p>\n\n<p>I would advise to use the first one: first, GNU extensions are more commonly available (even Clang has most (if not all) of them); second, because <code>err</code> is a common name used in temporary variables or labels used in case of an error.</p>\n\n<hr>\n\n<h2>C99 types</h2>\n\n<p>If you don't have a reason to use old C89 (yes, 1989) types, don't use them. What is <code>long long</code>, and why would you use it?</p>\n\n<p><code>int64_t</code> is clearer, shorter, and better in every way, unless you need to interface a library that hasn't been updated in the last 30 years, which ironically is most of them.</p>\n\n<p>Also instead of <code>int</code>, use <code>int32_t</code>, although if you want factorials that fit into an <code>int64_t</code>, I don't think you need more than <code>int8_t</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:23:10.667", "Id": "434915", "Score": "0", "body": "Thank you. I haven't done much proper programming for a couple of decades, so this gives me some guidance on where to focus on practicing for awhile and fixing old bad habits. The systems used for compilation are _WIN64 and Linux, hence fprintf." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T17:45:34.013", "Id": "224233", "ParentId": "224221", "Score": "3" } }, { "body": "<p><strong>Possible Bugs</strong><br>\nIn <code>main()</code> there is an assignment from a fuction that returns long long (factorial) to an integer variable (fact). This may result in errors depending on the word size of int. One of the possibilities is a positive long long value can be converted to a negative integer. Since there is a comparison between the variable <code>fact</code> and another long long value (the loop control variable <code>i</code>) it would be better if <code>fact</code> was declared as long long.</p>\n\n<p><strong>Reducing Verbosity</strong><br>\nTo reduce the verbosity it might be better to move the functions <code>swap</code>, <code>mobile</code>, <code>printArray</code> and <code>factorial</code> before the function <code>permute</code> and delete all the function prototypes.</p>\n\n<p>The variable names <code>bigInd</code> and <code>bigNum</code> can be confusing it based on the comments and to remove the need for the comments perhaps bigInd could renamed <code>indexLargestMobileNumber</code> and <code>bigNum</code> could be renamed <code>largestMobileNumber</code>. I initialy confused bigInd with big Endian. It is also not clear why <code>dir</code> and <code>res</code> are named <code>dir</code> and <code>res</code>.</p>\n\n<p><strong>Array Memory Allocation</strong><br>\nWhen allocation memory for arrays in the C programming language it might be better to use <code>calloc(size_t SIZE_OF_ARRAY, size_t SIZE_OF_ELEMENT);</code> for 2 reasons, the first is it is obvious that array is being allocated, and the second is that calloc() zeros out all the elements of the array. This means that in the function <code>permute</code> this for loop would not be necessary</p>\n\n<pre><code>for (int i = 0; i &lt; n; i++) {\n dir[i] = LEFT;\n}\n</code></pre>\n\n<p>The <code>calloc()</code> function will perform better than the preceeding for loop. If the code continues to use <code>malloc()</code> rather than calloc it might be better to use <code>memset()</code> since this will also out perform the previous for loop.</p>\n\n<p><strong>Complexity</strong><br>\nThe function <code>permute()</code> is complex and it may be better to break it down into sub-functions where some of the code my be reusable. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:30:31.067", "Id": "434918", "Score": "1", "body": "An old bad habit of keeping names to a max of 6 or 8 chars I suppose. Big Endian didn't even occur to me since it's been awhile since I used a z series or the like. Is there any common consensus on variable name length sizes? dir and res will be changed to direction and results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:35:59.090", "Id": "434935", "Score": "0", "body": "@smp It's been a long time since fortran 66 or basic that limited the length of variable names. I'm not aware of a common consensus." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T23:09:55.413", "Id": "434948", "Score": "0", "body": "@smp Use very explicit names in globals (actually, avoid globals;), and use the shortest while still memorable names for locals. If there are still possible confusions, it's probably that the function is too long and should probably be divided" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T18:04:11.163", "Id": "224235", "ParentId": "224221", "Score": "1" } } ]
{ "AcceptedAnswerId": "224233", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T15:13:54.707", "Id": "224221", "Score": "4", "Tags": [ "c", "array", "combinatorics" ], "Title": "Array of all permutations in C" }
224221
<p>I wanted to measure the performance of Concurrent Dictionary vs Dictionary+Locks in a multithreaded environment. So I created my own <code>SyncDict</code> class of type<code>&lt;int,int[]&gt;</code>. Whenever there is a key match, it adds the <code>int[]</code> array value to itself, it also locks the whole dictionary with <code>ReaderWriterLockSlim</code> while updating the value.<br/> <br/> I replicated the whole code through Concurrent Dictionary and I am using <code>AddOrUpdate()</code> method.<br/> <br/> Whole console app code can be found here <a href="https://dotnetfiddle.net/1kFbGy" rel="nofollow noreferrer">https://dotnetfiddle.net/1kFbGy</a> Just copy paste the code in console app to run. It will not run fiddle<br/></p> <p>After running both codes with the same inputs I see a considerable amount of difference in running time. For example for one particular run on my machine Concurrent dictionary took 4.5 seconds vs SyncDict took less than 1 second. <br/> </p> <p>I would like to know any thoughts / suggestions explaining the above running time. Is there anything wrong am I doing here?</p> <pre><code> class SyncDict&lt;TKey&gt; { private ReaderWriterLockSlim cacheLock; private Dictionary&lt;TKey, int[]&gt; dictionary; public SyncDict() { cacheLock = new ReaderWriterLockSlim(); dictionary = new Dictionary&lt;TKey, int[]&gt;(); } public Dictionary&lt;TKey, int[]&gt; Dictionary { get { return dictionary; } } public int[] Read(TKey key) { cacheLock.EnterReadLock(); try { return dictionary[key]; } finally { cacheLock.ExitReadLock(); } } public void Add(TKey key, int[] value) { cacheLock.EnterWriteLock(); try { dictionary.Add(key, value); } finally { cacheLock.ExitWriteLock(); } } public AddOrUpdateStatus AddOrUpdate(TKey key, int[] value) { cacheLock.EnterUpgradeableReadLock(); try { int[] result = null; if (dictionary.TryGetValue(key, out result)) { if (result == value) return AddOrUpdateStatus.Unchanged; else { cacheLock.EnterWriteLock(); try { Parallel.For(0, value.Length, (i, state) =&gt; { result[i] = result[i] + value[i]; }); } finally { cacheLock.ExitWriteLock(); } return AddOrUpdateStatus.Updated; } } else { Add(key, value); return AddOrUpdateStatus.Added; } } finally { cacheLock.ExitUpgradeableReadLock(); } } public void Delete(TKey key) { cacheLock.EnterWriteLock(); try { dictionary.Remove(key); } finally { cacheLock.ExitWriteLock(); } } public enum AddOrUpdateStatus { Added, Updated, Unchanged }; } </code></pre>
[]
[ { "body": "<h3>Comparison</h3>\n\n<ul>\n<li>A comparison of performance of 2 classes only makes sense if both adhere to the same specification. Does your class do what a <code>ConcurrentDictionary</code> does?</li>\n</ul>\n\n<h3>Review</h3>\n\n<ul>\n<li>Why would you allow access to the underlying dictionary? If you must allow it, return a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlydictionary-2?view=netframework-4.8\" rel=\"nofollow noreferrer\">IReadOnlyDictionary</a>.</li>\n<li>Checking arguments before taking a lock prevents unnecessary locks on bad input.</li>\n<li><code>AddOrUpdate</code> does not work; have you checked <code>if (result == value)</code>?</li>\n</ul>\n\n<pre><code>int[] a = new int[]{ 0, 1 }; \nint[] b = new int[]{ 0, 1 }; \nConsole.WriteLine(a == b); // False\n</code></pre>\n\n<p>Or is this as designed?</p>\n\n<ul>\n<li>What is the purpose of this? What if both arrays have different size?</li>\n</ul>\n\n<blockquote>\n<pre><code> Parallel.For(0, value.Length,\n (i, state) =&gt;\n {\n result[i] = result[i] + value[i];\n });\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:28:56.583", "Id": "224244", "ParentId": "224229", "Score": "2" } } ]
{ "AcceptedAnswerId": "224244", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T16:54:30.557", "Id": "224229", "Score": "3", "Tags": [ "c#", "performance", ".net" ], "Title": "Compare performance of Concurrent Dictionary with Dictionary+Locks" }
224229
<p>I've been thinking about the <code>AsyncLazy&lt;T&gt;</code> class that Stephen Toub and Stephen Cleary present in various resources <a href="https://blog.stephencleary.com/2012/08/asynchronous-lazy-initialization.html" rel="nofollow noreferrer">such as this</a>. I am trying to find a way to integrate cancellation with <code>AsyncLazy&lt;T&gt;</code>. Microsoft has <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.threading.asynclazy-1?view=visualstudiosdk-2019" rel="nofollow noreferrer">a version of <code>AsyncLazy&lt;T&gt;</code> in their Visual Studio 2019 SDK</a> that offers a <code>GetValueAsync(CancellationToken)</code> method, but if you read the fine print, it says: </p> <blockquote> <p>Note that this will not cancel the value factory (since other callers may exist).</p> </blockquote> <p>I would like something that <em>does</em> cancel the value factory. After failing to get anywhere with my research, I decided to attempt my own which is shown in the code below. However, I'm having trouble with thread safety, as I don't want multiple threads to execute the long-running value factory. I want any thread that comes in behind the first one to essentially <code>await</code> the completion of that first thread, and then the subsequent thread would have the trivial task of just returning the already-created value. </p> <p>Here is the code:</p> <pre><code>public sealed class CancelableAsyncLazy&lt;T&gt; { private readonly Func&lt;CancellationToken, Task&lt;T&gt;&gt; _valueFactory; private T _createdValue; private bool _isValueCreated = false; private volatile bool _shouldWait = false; public CancelableAsyncLazy(Func&lt;CancellationToken, Task&lt;T&gt;&gt; valueFactory) =&gt; _valueFactory = valueFactory; public async Task&lt;T&gt; GetValueAsync(CancellationToken cancellationToken) { await Task.Run(() =&gt; { while (_shouldWait) Thread.Sleep(1); }); _shouldWait = true; try { if (_isValueCreated) return _createdValue; cancellationToken.ThrowIfCancellationRequested(); _createdValue = await _valueFactory(cancellationToken).ConfigureAwait(false); _isValueCreated = true; return _createdValue; } finally { _shouldWait = false; } } } </code></pre> <p>I don't like the fact that I'm using <code>Task.Run</code> and <code>Thread.Sleep</code> to wait for the value to be created by an earlier thread, but I can't think of a better way to do it. The key is that it shouldn't block. I tried using a <code>Mutex</code>, but it's possible the same thread could call the method before the value is created, so the subsequent call (from the same thread) would just blow past the <code>Mutex</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T17:27:14.353", "Id": "434905", "Score": "1", "body": "Borderline _on-/off-topic_ question for SE Code Review IMO. Basically you're asking to rewrite your code without these `Thread` features you're currently using (which means asking for code not yet implemented)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T17:30:50.013", "Id": "434906", "Score": "1", "body": "I'm not asking to re-write the code. I'm asking for people to help me determine if the approach is ok or if there's something else I should look at." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T20:37:35.740", "Id": "435048", "Score": "0", "body": "@πάνταῥεῖ This is an interesting question from a meta point of view. It is clear that the OP wants an improved solution for his scenario. The thread sleep is a hack seen from afar. However, the code does work as intended. For me this is review-worthy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T20:40:38.930", "Id": "435049", "Score": "1", "body": "@dfhwze Well, as I mentioned it's a bit _borderline_ (not straightforward _off-topic_). Have an upvote for your review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:33:18.553", "Id": "435176", "Score": "0", "body": "@πάνταῥεῖ I guess I don't understand the essence of this site then. I thought it was basically \"I have working code but I'm not happy with some aspect of it or want to know if there's a better way\". I don't see how my question is borderline \"off topic\". I'm not trying to be nitpicky with your comment; I simply want to know for my own edification and for future use of this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T05:44:54.723", "Id": "435266", "Score": "0", "body": "@πάνταῥεῖ Because it is obvious to anyone, including you, that you have implemented a dirty hack to make the code work. I think you deserve a review because the hack works, so technically, your code works as intended. Another way to view this, is that you don't know an elegant solution to this problem and you are just fishing for a solution to your problem. This question is food for meta :)" } ]
[ { "body": "<h3>Specification Considerations</h3>\n\n<p>Note that the first caller that gets access is the one that provides the <code>cancellationToken</code> for the <code>valueFactory</code>. Other callers use their own <code>cancellationToken</code> for timing out on awaiting the result of the async operation. This is how you designed your class. I did not change this part of the behavior.</p>\n\n<p>If this behavior is not wanted, consider storing a cancellation token through the constructor. This one is used solely for the factory. And each call to <code>GetValueAsync</code> could then use its own cancellation token to time out, without influencing possible cancellation of the factory. This is a design decision you would have to make.</p>\n\n<hr>\n\n<h2>Review</h2>\n\n<p>This is not a good solution. You know it, we all know it :-)</p>\n\n<blockquote>\n<pre><code>await Task.Run(() =&gt;\n{\n while (_shouldWait) Thread.Sleep(1);\n});\n</code></pre>\n</blockquote>\n\n<p>The way to delay a thread the async way is to use <code>Task.Delay</code> (<a href=\"https://blog.stephencleary.com/2012/02/async-and-await.html\" rel=\"nofollow noreferrer\">Overview TAP Guidelines)</a>. This is already better. But as you mentioned, this still feels like a hack (and it is). Using some sort of <code>Mutex</code> would be a better approach, as you rightfully indicated. We'll get to that.</p>\n\n<p>Lets' walk through your code.</p>\n\n<p>You define 2 similar variables <code>_isValueCreated</code> and <code>_shouldWait</code>. If you think about it, they have the same purpose. As long the value is not created, a caller should wait. Let's merge them into a variable named .. let's say <code>_memoized</code>. This is common terminology in caching.</p>\n\n<blockquote>\n<pre><code>private bool _isValueCreated = false;\nprivate volatile bool _shouldWait = false;\n</code></pre>\n</blockquote>\n\n<p>Rather than the whole construct of abusing a thread's <code>Sleep</code> and using a <code>volatile</code> bool to simulate a lock, we could use a <code>Semaphore</code> (<a href=\"https://blog.cdemi.io/async-waiting-inside-c-sharp-locks/\" rel=\"nofollow noreferrer\">Async Mutex using a Semaphore</a>). </p>\n\n<p>As discussed in the previous link, this is not possible..</p>\n\n<pre><code>// example code\nlock (lockObject)\n{\n await Task.Delay(1000);\n}\n</code></pre>\n\n<p>.. but this is..</p>\n\n<pre><code>// example code\nawait semaphoreSlim.WaitAsync();\ntry\n{\n await Task.Delay(1000);\n}\nfinally\n{\n semaphoreSlim.Release();\n}\n</code></pre>\n\n<p>Let's see how we can implement this in your cancellable async lazy class.</p>\n\n<hr>\n\n<h2>Refactoring the Code</h2>\n\n<p>We define our variables. Your two booleans are merged into one. And we use the semaphore described above.</p>\n\n<pre><code>private readonly Func&lt;CancellationToken, Task&lt;T&gt;&gt; _valueFactory;\nprivate volatile bool _memoized;\nprivate readonly SemaphoreSlim _mutex;\nprivate T _value;\n</code></pre>\n\n<p>The constructor is straight-forward. Make sure to use a <code>Semaphore</code> than emulates a <code>Mutex</code> so one thread has access to the resource simultaneously.</p>\n\n<pre><code>public CancelableAsyncLazy(Func&lt;CancellationToken, Task&lt;T&gt;&gt; valueFactory)\n{\n _valueFactory = valueFactory ?? throw new ArgumentNullException(nameof(valueFactory));\n _mutex = new SemaphoreSlim(1, 1);\n}\n</code></pre>\n\n<p>The infamous <code>GetValueAsync</code> can then be rewritten completely. Each caller thread can provide its own <code>cancellationToken</code>. Use it to acquire a lock on <code>_mutex</code>. Once we have the lock, check whether <code>_value</code> is already memoized. If not (<code>!_memoized</code>) execute <code>_valueFactory</code>, and memoize the value. Now, we perform another timeout check for the calling thread <code>ThrowIfCancellationRequested</code>. Even though we have the value available now, the caller might still have timed out, so let him now. Don't forget to release the mutex.</p>\n\n<pre><code>public async Task&lt;T&gt; GetValueAsync(CancellationToken cancellationToken)\n{\n await _mutex.WaitAsync(cancellationToken);\n try\n {\n if (!_memoized)\n {\n _value = await _valueFactory(cancellationToken).ConfigureAwait(false);\n _memoized = true;\n cancellationToken.ThrowIfCancellationRequested();\n }\n return _value;\n }\n finally\n {\n _mutex.Release();\n }\n}\n</code></pre>\n\n<p>We should allow for a convenience overload if no cancellation support is required for a given caller.</p>\n\n<pre><code>public async Task&lt;T&gt; GetValueAsync() =&gt; await GetValueAsync(CancellationToken.None);\n</code></pre>\n\n<p>And since we comply to the concept of <code>Lazy</code> we should also provide a synchronous property <code>Value</code>.</p>\n\n<pre><code>public T Value =&gt; GetValueAsync().Result;\n</code></pre>\n\n<h3>Refactored Code</h3>\n\n<pre><code>public sealed class CancelableAsyncLazy&lt;T&gt;\n{\n private readonly Func&lt;CancellationToken, Task&lt;T&gt;&gt; _valueFactory;\n private volatile bool _memoized;\n private readonly SemaphoreSlim _mutex;\n private T _value;\n\n public CancelableAsyncLazy(Func&lt;CancellationToken, Task&lt;T&gt;&gt; valueFactory)\n {\n _valueFactory = valueFactory \n ?? throw new ArgumentNullException(nameof(valueFactory));\n _mutex = new SemaphoreSlim(1, 1);\n }\n\n public T Value =&gt; GetValueAsync().Result;\n\n public async Task&lt;T&gt; GetValueAsync() =&gt; await GetValueAsync(CancellationToken.None);\n\n public async Task&lt;T&gt; GetValueAsync(CancellationToken cancellationToken)\n {\n await _mutex.WaitAsync(cancellationToken);\n try\n {\n if (!_memoized)\n {\n _value = await _valueFactory(cancellationToken).ConfigureAwait(false);\n _memoized = true;\n // at this point, the value is available, however, the caller\n // might have indicated to cancel the operation; I favor \n // checking for cancellation one last time here, but you\n // might decide against it and return the result anyway\n cancellationToken.ThrowIfCancellationRequested();\n }\n return _value;\n }\n finally\n {\n _mutex.Release();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T07:17:16.043", "Id": "435109", "Score": "0", "body": "What's the `cancellationToken.ThrowIfCancellationRequested();` for in the refactored code? The point of cancellation is to avoid doing expensive operations, but at that point there's nothing left to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T07:30:43.833", "Id": "435110", "Score": "0", "body": "@PeterTaylor Because the caller might have indicated he no longer wants to await the result of the operation. This is an edge case for a race condition. One could design it to favor returning the result anyway. I have decided against it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:21:25.477", "Id": "435175", "Score": "0", "body": "Thank you for your very thorough answer; I appreciate it. One thing I can't seem to wrap my mind around is this: with the `WaitAsync` method [\"there is no thread\"](https://blog.stephencleary.com/2013/11/there-is-no-thread.html), correct? So how can a locking mechanism grab the mutex if it doesn't have a thread to associate it with and prevent other threads from grabbing the mutex until it's released? In fact (based on my testing) the first call never does any async at all because if I use `.ConfigureAwait(false)` it continues on the main thread, not a thread pool thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T05:46:28.267", "Id": "435267", "Score": "0", "body": "@rory.ap A semaphore allows for thread-safe access to a resource. It does not have an affinity to a thread. In other words, thread A may acquire the semaphore, all other threads will block untill any thread A or B releases the semaphore. As you can see, it differs from a lock where thread affinity is required." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:13:28.990", "Id": "224242", "ParentId": "224232", "Score": "4" } } ]
{ "AcceptedAnswerId": "224242", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T17:23:00.897", "Id": "224232", "Score": "3", "Tags": [ "c#", "multithreading", "thread-safety", "lazy" ], "Title": "Cancelable AsyncLazy that is thread-safe" }
224232
<p>This is my third (and hopefully final) time re-writing this <a href="https://codereview.stackexchange.com/questions/224159/rename-and-move-images-to-a-destination-directory-based-on-a-text-file">program</a>. It was recommended I use <code>Pathlib</code> and it simplified my code, it's easier to read and understand than the first two monstrosities. </p> <p>I also changed the way it functions, instead of the user providing a text file, the user creates a directory called <code>Repository</code>, which contains sub directories of images that will be renamed, and a destination directory (<code>R:\Pictures</code> for me). </p> <p>Suppose I have the following directories under <code>Repository</code>:</p> <pre><code>C:\Users\Kiska\Repository\Computers - comp-amd-12342.jpg - 7546345233-pcmag.jpg C:\Users\Kiska\Repository\Landscape - land-345345.jpg - end-field.jpg </code></pre> <p>The program will move and rename it like this:</p> <pre><code>R:\Pictures\Pictures\Computers - computers_1.jpg - computers_2.jpg R:\Pictures\Pictures\Landscape - landscape_1.jpg - landscape_2.jpg </code></pre> <p><strong>Code</strong>:</p> <pre><code>import os from pathlib import Path import shutil def check_if_folder_exists(folder : Path): if not Path.exists(folder): raise FileNotFoundError("{0} is not available".format(folder)) def main(): try: repository = Path("{0}\\{1}".format(os.getenv("USERPROFILE"), "Repository")) desination_root = Path("R:\\Pictures") check_if_folder_exists(folder=repository) check_if_folder_exists(folder=desination_root) for folder in repository.iterdir(): destination = Path(desination_root).joinpath(folder.stem) Path.mkdir(destination, exist_ok=True) start = len(os.listdir(destination)) + 1 for number, image in enumerate(folder.iterdir(), start=start): image_name = "{0}_{1}{2}".format(folder.stem.lower().replace(" ","_"), number,image.suffix) destination_image = Path(destination).joinpath(image_name) print(f"{image} will be named {destination_image}") shutil.move(image, destination_image) except(ValueError, FileNotFoundError, OSError) as error: print(error) finally: pass if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<ul>\n<li>Give <code>main</code> method a more meaningful name. It is always better than a generic <code>main</code>.</li>\n<li>Make <code>repository</code> and <code>destination_root</code> be parameters of the method which is now called <code>main</code>; </li>\n<li>If you use python version that supports f-strings, be consistent, use them everywhere e.g. <code>f'{folder} is not available'</code>;</li>\n<li><code>finally: pass</code> does not have any effect so if you are not going to put any logic there, it can be omitted;</li>\n<li>regarding the <code>start</code> parameter passed to <code>enumerate</code>: can you guarantee that if that the destination folder contains 1 picture, it will be called <em>xxxxx_1.jpg</em>, not <em>xxxxx_2.jpg</em> or <em>xxxxx_27.jpg</em>?</li>\n<li>I would also extract <code>folder.stem.lower().replace(\" \",\"_\")</code> into a separate variable which can get some meaningful name (which can be then used in f-string) to enhance reading;</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:43:17.190", "Id": "434923", "Score": "0", "body": "The `start` parameter is the number of images already present + 1 so if 4 images already exist in the destination, we start at 5." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:53:27.580", "Id": "434926", "Score": "1", "body": "@Kiska Okay, let me rephrase, what would happen if before you run the program `R:\\Pictures\\Pictures\\Computers` contained **one** file with the name `computers_2.jpg`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:16:52.760", "Id": "434933", "Score": "0", "body": "Ah! I see now what you mean. I should check first if the filename is already present in the destination directory." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:39:20.640", "Id": "224241", "ParentId": "224236", "Score": "2" } }, { "body": "<ul>\n<li>You have lots of unneeded empty lines, they also hinder readability.</li>\n<li><code>fn(arg=value)</code> is abnormal. It's common to use <code>fn(value)</code>. It's common only to use the former when the argument is a keyword or default argument.</li>\n<li><p>You don't need to make a path another path.</p>\n\n<blockquote>\n<pre><code>desination_root = Path(\"R:\\\\Pictures\")\ndestination = Path(desination_root).joinpath(folder.stem)\n</code></pre>\n</blockquote></li>\n<li><p><a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir\" rel=\"nofollow noreferrer\"><code>Path.mkdir</code></a> isn't a static method, and so it's abnormal to use it as <code>Path.mkdir(my_path)</code> rather than <code>my_path.mkdir()</code>.</p></li>\n<li><p><code>check_if_folder_exists</code> isn't needed as <code>repository.iterdir</code> and <code>destination.mkdir</code> will error if they don't exist.</p>\n\n<p>It should also be noted that you can pass <code>parents=True</code> to <code>Path.mkdir</code> to automatically create the folder if it doesn't exist, rather than force the user to do that.</p></li>\n<li>It's better if you make another function that moves the files, and one, <code>main</code>, that passes it the values. Preferably <code>main</code> would be changed to not use static values and get the values from a config file.</li>\n<li><code>finally</code> isn't needed.</li>\n<li>You should raise a <code>SystemExit(1)</code> or use <code>sys.exit(1)</code> if there is an error. They both do the same thing which notifies the system that the program failed. It didn't run without problems.</li>\n<li><p>Given that generating a name that doesn't conflict with existing files is not a simple one-liner I'd recommend you move it out into a function.</p>\n\n<p>I should note that it may overwrite files, if you have a folder with <code>file_1.png</code> and <code>file_3.png</code> your code's going to overwrite <code>file_3.png</code>, but not have a <code>file_2.png</code>.</p></li>\n</ul>\n\n<p>You changed away from some of the above, and so I'd recommend you think about the differences, which is easier to re-use, which is easier to read, which performs the correct action in the situation. If you don't know what the difference is even with my explanation, such as with <code>SystemExit(1)</code>, then you should look up what it does.</p>\n\n<pre><code>import os\nfrom pathlib import Path\nimport shutil\n\n\ndef gen_name(path, number):\n orig_name = path.parent.name.lower().replace(\" \", \"_\")\n return f\"{orig_name}_{number}{path.suffix}\"\n\n\ndef move_files(src, dest):\n for folder in Path(src).iterdir():\n destination = Path(dest) / folder.stem\n destination.mkdir(exist_ok=True, parents=True)\n start = len(os.listdir(destination)) + 1\n for number, image in enumerate(folder.iterdir(), start=start):\n image_name = gen_name(image, number)\n destination_image = destination / image_name\n print(f\"{image} will be named {destination_image}\")\n shutil.move(image, destination_image)\n\n\ndef main():\n try:\n move_files(\n \"{0}\\\\{1}\".format(os.getenv(\"USERPROFILE\"), \"Repository\"),\n \"R:\\\\Pictures\",\n )\n except(ValueError, FileNotFoundError, OSError) as error:\n print(error)\n raise SystemExit(1) from None\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I think it could make more sense for <code>gen_name</code> to be a closure, as then it can correctly handle existing files. I won't change how the code functions, but will show how it could be implemented.</p>\n\n<pre><code>def gen_name_builder(folder):\n orig_name = folder.name.lower().replace(\" \", \"_\")\n number = len(os.listdir(destination))\n def gen_name(file):\n nonlocal number\n number += 1\n return f\"{orig_name}_{number}{path.suffix}\"\n return name\n\n\ndef move_files(src, dest):\n for folder in Path(src).iterdir():\n destination = Path(dest) / folder.stem\n destination.mkdir(exist_ok=True, parents=True)\n gen_name = gen_name_builder(destination)\n for image in folder.iterdir():\n image_name = gen_name(image)\n destination_image = destination / image_name\n print(f\"{image} will be named {destination_image}\")\n shutil.move(image, destination_image)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:58:17.687", "Id": "434939", "Score": "0", "body": "Is it okay to use an `if/else` statement in the for loop responsible for moving the images? Check if it exists, if not, move it, if it does, leave it, but notify the user with a print statement" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T22:06:11.723", "Id": "434940", "Score": "0", "body": "@Kiska Please look over the additional code I added to my answer. You should be able to handle if an item exists with that name in `gen_name`. Yes, you can use an `if`. As a hint I would use a `while`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T22:07:17.473", "Id": "434941", "Score": "0", "body": "The docs on `Path.mkdir()` is misleading, it uses it as a static method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T22:11:49.923", "Id": "434942", "Score": "1", "body": "@Kiska I'm not seeing the docs use [`Path.mkdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir) as a static method. I've checked the other languages too, and they also don't show that. I'm sorry that this has caused some confusion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T22:12:50.720", "Id": "434943", "Score": "1", "body": "Right at the top in yellow where you can link to it `Path.mkdir(mode=0o777, parents=False, exist_ok=False)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T22:16:34.423", "Id": "434944", "Score": "1", "body": "@Kiska Ok, I get the confusion now. That isn't an example of how to use the method, it tells you where the method is defined, `Path.mkdir`, and shows the arguments it has, with any defaults they have. If you look at [`Path.open`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.open) you can see the same thing, but it has an example showing it used in a different way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T22:17:51.483", "Id": "434945", "Score": "0", "body": "Ah! Now I see, thanks" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:53:43.250", "Id": "224252", "ParentId": "224236", "Score": "3" } } ]
{ "AcceptedAnswerId": "224252", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T18:18:54.237", "Id": "224236", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Rename and move images to a destination directory based on a text file followup" }
224236
<p>This is a very simple <a href="https://en.wikipedia.org/wiki/Read-copy-update" rel="nofollow noreferrer">read-copy-update (RCU)</a>-inspired synchronization class:</p> <pre><code>#include &lt;atomic&gt; template&lt;typename T&gt; class RCU { private: std::atomic&lt;T*&gt; curr; std::atomic&lt;T*&gt; prev; std::atomic&lt;int&gt; readers; public: RCU() : curr (new T), prev (nullptr), readers(0) { } ~RCU() { delete curr; delete prev; } void lock() { readers++; } void unlock() { readers--; } T* get() { return curr.load(); } T* clone() { return new T(*curr.load()); } bool swap(T* t) { /* If prev is full, a swap is still pending. Clean up memory and abort the operation. */ if (prev.load() != nullptr) { delete t; return false; } /* Store the current pointer into prev. Readers might still be reading through the pointer. */ prev.store(curr); /* Curr contains the new proposed value. No one is reading from this right now. */ curr.store(t); /* Spin until there are no more readers to *prev. When so, free the memory it points to and say goodbye. */ while (readers.load() &gt; 0); T* old = prev.load(); prev.store(nullptr); delete old; return true; } }; </code></pre> <p>The idea is to have many reader threads that repeatedly read from some shared data, while a writer thread that rarely updates it. The writer thread takes care of cleaning up the memory when no readers are reading. Readers are "tracked" through the <code>lock()</code> and <code>unlock()</code> methods. The RCU-like class should synchronize the threads in a lock-free way. </p> <p>Usage:</p> <pre><code>struct Data { int x; int y; int z; }; RCU&lt;Data&gt; rcu; void writer_thread() // the writer rarely runs { while (true) { Data* data = rcu.clone(); // modify data as needed data-&gt;x++; data-&gt;y++; data-&gt;z++; rcu.swap(data); // Checking the return value might be useful } } void reader_thread() { while (true) { rcu.lock(); std::cout &lt;&lt; rcu.get()-&gt;x &lt;&lt; "\n"; // read from data rcu.unlock(); } } </code></pre> <p>Questions: does it make sense? Is it really thread-safe? Can a thread slip through the cracks somewhere, somehow?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:23:19.287", "Id": "435101", "Score": "0", "body": "Did you test this? Does it work as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T08:15:09.980", "Id": "435293", "Score": "0", "body": "@Mast I did. I let it run for ~15 minutes without nasty surprises. So far so good." } ]
[ { "body": "<p>Serious issues with this:</p>\n<ol>\n<li>Memory Management.</li>\n<li>Not using RAII to lock/unlock</li>\n</ol>\n<h3>Memory Management</h3>\n<p>Don't pass pointers it does not indicate owners. Always wrap pointers in a smart pointer. Have a look at <code>std::unique_ptr</code>.</p>\n<p>But for types like <code>Data</code> there is no need to use pointers. Simply use <code>Data</code> as the object type (not <code>Data*</code>).</p>\n<h3>RAII</h3>\n<p>Look up the concept of RAII.</p>\n<p>A good example is <code>std::lock_guard</code> <a href=\"https://en.cppreference.com/w/cpp/thread/lock_guard\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/thread/lock_guard</a> This shows you how to use RAII to automate the processes of lock/unlock so it is exception safe.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:54:31.700", "Id": "434931", "Score": "0", "body": "Good points! Regarding `Data*`: I'm using dynamic memory allocation on purpose to support non-primitive, heavy-weight types (vectors, maps, ...). Does it make any sense?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:02:52.523", "Id": "434932", "Score": "2", "body": "No because you can allow the person using your class decide if it is heavy weight and allow them to templatize the class specifically with a pointer type `RCU<MyHeavyWeightClass*>`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:19:12.753", "Id": "224243", "ParentId": "224238", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:01:31.350", "Id": "224238", "Score": "1", "Tags": [ "c++", "c++11", "multithreading", "lock-free", "atomic" ], "Title": "A minimalistic kind of read-copy-update class" }
224238
<p>I've been working on a script which configures newly imaged computers (power settings, installed apps, etc)</p> <p>This is what I have so far: </p> <pre><code>echo off cls SET WINDOW_WIDTH=100 SET WINDOW_HEIGHT=42 mode con: cols=%WINDOW_WIDTH% lines=%WINDOW_HEIGHT% Set SOURCEPATH=\\networkpath Set JAVAPATH=%SOURCEPATH%\Java\ @echo [TASK] Adding CITY\WorkstationAdmins to Administrators net localgroup Administrators CITY\WorkstationAdmins /add &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo CITY\WorkstationAdmins added to computer) || (call :printFail &amp;&amp; echo Failed to add CITY\WorkstationAdmins to Administrators, may already be added) @echo [TASK] Installing Windows 10 Corporate Pro Key ([XXXXX-XXXXX-XXXXX-XXXXX-XXXXX[0m^) start slmgr.vbs //b /ipk XXXXX-XXXXX-XXXXX-XXXXX-XXXXX &amp;&amp; (call :printPass &amp;&amp; echo Windows 10 Pro Key Installed) || (call :printFail &amp;&amp; echo Failed to add Windows 10 Pro Key) @echo [TASK] Installing Java call "%JAVAPATH%\jre-6u30-windows-i586.exe" /s &amp;&amp; (call :printPass &amp;&amp; echo Java installation complete) || (call :printFail &amp;&amp; echo Java installation failed) reg delete HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run /v SunJavaUpdateSched /f &gt; NUL 2&gt;&amp;1 @echo [TASK] Configuring Remote Registry to Automatically Start sc.exe config RemoteRegistry start= auto &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo Remote registry will auto start on boot) || (call :printFail &amp;&amp; echo Failed to set remote registry to auto start, may already be set) @echo [TASK] Starting Remote Registry net start RemoteRegistry &gt;Nul 2&gt;&amp;1 (call :printPass &amp;&amp; echo Remote registry started) || (call :printFail &amp;&amp; echo Failed to start remote registry, may already be started) @echo [TASK] Disabling Automatic Sleep powercfg /change standby-timeout-ac 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo AC sleep disabled) || (call :printFail &amp;&amp; echo AC sleep still enabled) powercfg /change standby-timeout-dc 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo DC sleep disabled) || (call :printFail &amp;&amp; echo DC sleep still enabled) @echo [TASK] Disabling Automatic Hibernation powercfg /change hibernate-timeout-ac 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo AC hibernation disabled) || (call :printFail &amp;&amp; echo AC hibernation still enabled) powercfg /change hibernate-timeout-dc 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo DC hibernation disabled) || (call :printFail &amp;&amp; echo DC hibernation still enabled) @echo [TASK] Disabling Hybrid Sleep. powercfg -setacvalueindex SCHEME_BALANCED SUB_SLEEP HYBRIDSLEEP 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo AC hybrid sleep disabled) || (call :printFail &amp;&amp; echo AC hybrid sleep still enabled) powercfg -setdcvalueindex SCHEME_BALANCED SUB_SLEEP HYBRIDSLEEP 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo DC hybrid sleep disabled) || (call :printFail &amp;&amp; echo DC hybrid sleep still enabled) @echo [TASK] Clearing Login Screen. REG add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI" /v LastLoggedOnDisplayName /t REG_SZ /d "" /f &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo Removed last logged on DisplayName) || (call :printFail &amp;&amp; echo Could not remove last logged on DisplayName) REG add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI" /v LastLoggedOnSAMUser /t REG_SZ /d "" /f &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo Removed last logged on SAMUser) || (call :printFail &amp;&amp; echo Could not remove last logged on SAMUser) REG add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI" /v LastLoggedOnUser /t REG_SZ /d "" /f &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo Removed last logged on User) || (call :printFail &amp;&amp; echo Could not remove last logged on User) @echo [TASK] Enabling Screensaver Timeout and Password REG add "HKCU\Software\Policies\Microsoft\Windows\Control Panel\Desktop" /v ScreenSaverIsSecure /t REG_SZ /d 1 /f &gt;Nul &amp;&amp; (call :printPass &amp;&amp; echo Set Screensaver password) || (call :printFail &amp;&amp; echo Could not set Screensaver password) REG add "HKCU\Software\Policies\Microsoft\Windows\Control Panel\Desktop" /v ScreenSaveTimeOut /t REG_SZ /d 900 /f &gt;Nul &amp;&amp; (call :printPass &amp;&amp; echo Set Screensaver password) || (call :printFail &amp;&amp; echo Could not set Screensaver timeout) @echo [TASK] Updating group policy echo n | gpupdate /force /wait:0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :printPass &amp;&amp; echo Group Policy Updated) || (call :printFail &amp;&amp; echo Group Policy update failed) @echo [INFO] Configuration Complete. @echo *Check if any errors occured.* @echo Press any key to exit. &amp;&amp; pause&gt;Nul goto:eof :printFail call :printInfo echo |set /p="[31m[FAIL][0m " EXIT /B 0 :printPass call :printInfo echo |set /p="[32m[PASS][0m " EXIT /B 0 :printInfo echo|set /p=[INFO] EXIT /B 0 </code></pre> <p>As you can see at the bottom, I've started to put stuff in separate functions so that it can be a bit modular.</p> <p>Right now I'm thinking of putting each section into its own function so that if I want to disable the section, (ex We fix the Java task sequence so that we don't need to install it post imaging), then it is a simple comment out.</p> <p>Any suggestions or tips, I'm new to batch scripting that why I want to stick on it. It has been suggested to move it to PowerShell which I might do in the future.</p> <p>EDIT:</p> <p>I tried what I was already thinking of doing by moving each task into its own function. Also moved some stuff info variables for the readability of the code.</p> <p>UPDATED CODE:</p> <pre><code>echo off cls SET WINDOW_WIDTH=100 SET WINDOW_HEIGHT=40 mode con: cols=%WINDOW_WIDTH% lines=%WINDOW_HEIGHT% SET SOURCEPATH=\\networkpath SET JAVAPATH="%SOURCEPATH%\Java.exe" SET WINDOWS_KEY=XXXXX-XXXXX-XXXXX-XXXXX-XXXXX SET LOGIN_REG_PATH=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI SET SCRSVR_REG_PATH="HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Windows\Control Panel\Desktop" call :addDomainStuff call :installKey call :installJava call :setDefaultApps call :configRemote call :disableSleep call :clearLogin call :setScreenSaver call :pullGroupPolicy @echo [INFO] Configuration Complete. @echo *Check if any errors occured.* @echo Press any key to exit. &amp;&amp; pause&gt;Nul goto:eof :addDomainStuff @echo [TASK] Adding CITY\WorkstationAdmins to Administrators net localgroup Administrators CITY\WorkstationAdmins /add &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "CITY\WorkstationAdmins added to computer") || (call :echoFail "Failed to add CITY\WorkstationAdmins to Administrators, may already be added") EXIT /B 0 :installKey @echo [TASK] Installing Windows 10 Corporate Pro Key ([93m%WINDOWS_KEY%[0m^) start slmgr.vbs //b /ipk %WINDOWS_KEY% &amp;&amp; (call :echoPass "Windows 10 Pro Key Installed") || (call :echoFail "Failed to add Windows 10 Pro Key") EXIT /B 0 :configRemote @echo [TASK] Configuring Remote Registry to Automatically Start sc.exe config RemoteRegistry start= auto &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "Remote registry will auto start on boot") || (call :echoFail "Failed to set remote registry to auto start, may already be set") @echo [TASK] Starting Remote Registry net start RemoteRegistry &gt;Nul 2&gt;&amp;1 (call :echoPass "Remote registry started") || (call :echoFail "Failed to start remote registry, may already be started") EXIT /B 0 :disableSleep @echo [TASK] Disabling Hybrid Sleep. powercfg -setacvalueindex SCHEME_BALANCED SUB_SLEEP HYBRIDSLEEP 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "AC hybrid sleep disabled") || (call :echoFail "AC hybrid sleep still enabled") powercfg -setdcvalueindex SCHEME_BALANCED SUB_SLEEP HYBRIDSLEEP 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "DC hybrid sleep disabled") || (call :echoFail "DC hybrid sleep still enabled") @echo [TASK] Disabling Automatic Sleep powercfg /change standby-timeout-ac 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "AC sleep disabled") || (call :echoFail "AC sleep still enabled") powercfg /change standby-timeout-dc 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "DC sleep disabled") || (call :echoFail "DC sleep still enabled") @echo [TASK] Disabling Automatic Hibernation powercfg /change hibernate-timeout-ac 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "AC hibernation disabled") || (call :echoFail "AC hibernation still enabled") powercfg /change hibernate-timeout-dc 0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "DC hibernation disabled") || (call :echoFail "DC hibernation still enabled") EXIT /B 0 :clearLogin @echo [TASK] Clearing Login Screen. REG add %LOGIN_REG_PATH% /v LastLoggedOnDisplayName /t REG_SZ /d "" /f &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "Removed last logged on DisplayName") || call :echoFail "Could not remove last logged on DisplayName") REG add %LOGIN_REG_PATH% /v LastLoggedOnSAMUser /t REG_SZ /d "" /f &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "Removed last logged on SAMUser") || (call :echoFail "Could not remove last logged on SAMUser") REG add %LOGIN_REG_PATH% /v LastLoggedOnUser /t REG_SZ /d "" /f &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "Removed last logged on User") || (call :echoFail "Could not remove last logged on User") EXIT /B 0 :setScreenSaver @echo [TASK] Enabling Screensaver Timeout and Password REG add %SCRSVR_REG_PATH% /v ScreenSaverIsSecure /t REG_SZ /d 1 /f &gt;Nul &amp;&amp; (call :echoPass "Set Screensaver password") || (call :echoFail "Could not set Screensaver password") REG add %SCRSVR_REG_PATH% /v ScreenSaveTimeOut /t REG_SZ /d 900 /f &gt;Nul &amp;&amp; (call :echoPass "Set Screensaver password") || (call :echoFail "Could not set Screensaver timeout") EXIT /B 0 :installJava @echo [TASK] Installing Java call %JAVAPATH% /s &amp;&amp; (call :echoPass "Java installation complete") || (call :echoFail "Java installation failed, may already be installed") reg delete HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run /v SunJavaUpdateSched /f &gt; NUL 2&gt;&amp;1 EXIT /B 0 :pullGroupPolicy @echo [TASK] Updating group policy echo n | gpupdate /force /wait:0 &gt;Nul 2&gt;&amp;1 &amp;&amp; (call :echoPass "Group Policy Updated") || (call :echoFail "Group Policy update failed") EXIT /B 0 :setDefaultApps @echo [TASK] Changing default browser to chrome echo not configure @echo [TASK] Changing pdf reader to adobe echo not configure EXIT /B 0 :printFail call :printInfo echo |set /p="[31m[FAIL][0m " EXIT /B 0 :printPass call :printInfo echo |set /p="[32m[PASS][0m " EXIT /B 0 :printInfo echo|set /p=[INFO] EXIT /B 0 :echoFail call :printFail echo %~1 EXIT /B 0 :echoPass call :printPass echo %~1 EXIT /B 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:43:58.853", "Id": "434924", "Score": "2", "body": "Java 6 — really? Also, have you considered Active Directory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:50:04.023", "Id": "434925", "Score": "0", "body": "@200_success java 6 because a whole bunch of apps are still using it and for the active directory, I don't have permission/access to a whole bunch of functions and tools" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-18T21:05:32.330", "Id": "475951", "Score": "0", "body": "I don't think powershell would be beneficial to this code since the functions in powershell work very differently in my opinion. Love this idea!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:26:48.593", "Id": "224240", "Score": "3", "Tags": [ "windows", "installer", "batch" ], "Title": "Batch configuration script for a new computer" }
224240
<p>I have the below method that is responsible for generating and sending a <code>MailMessage</code> using a <code>SmtpClient</code> object:</p> <pre><code>public static void SendEmail( string subject, string body, bool isBodyHtml, List&lt;string&gt; emails, List&lt;string&gt; ccs = null) { if (emails == null) { throw new ArgumentNullException("emails"); } MailMessage message = new MailMessage { Subject = subject, Body = body, IsBodyHtml = isBodyHtml }; foreach (string email in emails) { message.To.Add(email); } if (ccs != null) { foreach (string cc in ccs) { message.CC.Add(cc); } } SmtpClient client = new SmtpClient { EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network }; client.Send(message); } </code></pre> <p>But recently I've been reading more on S.O.L.I.D and principles of OOP design, so I thought to refactor this method, and compartmentalize it more.</p> <p>Am I on the right track with my refactor? Are there ways to make my code more modular/testable?</p> <p>Here's my refactored code:</p> <pre><code>private static MailMessage CreateMailMessage( string subject, string body, bool isBodyHtml, List&lt;string&gt; emails, List&lt;string&gt; ccs = null) { if (emails == null) { throw new ArgumentNullException("emails"); } MailMessage message = new MailMessage { Subject = subject, Body = body, IsBodyHtml = isBodyHtml }; foreach (string email in emails) { message.To.Add(email); } if (ccs != null) { foreach (string cc in ccs) { message.CC.Add(cc); } } return message; } private static SmtpClient CreateSmtpClient( bool enableSsl, SmtpDeliveryMethod deliveryMethod) { SmtpClient client = new SmtpClient { EnableSsl = enableSsl, DeliveryMethod = deliveryMethod }; return client; } </code></pre> <p>And here's the method responsible for calling the above two and sending the email:</p> <pre><code>public static void SendEmail(string subject, string body, List&lt;string&gt; emails, List&lt;string&gt; ccs = null) { using (MailMessage message = CreateMailMessage(subject, body, true, emails, ccs)) { using (SmtpClient client = CreateSmtpClient(true, SmtpDeliveryMethod.Network)) { client.Send(message); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T14:47:03.320", "Id": "435703", "Score": "1", "body": "Why don't you use a custom datatype containing your mail? Now you have to pass around a subject, body, ccs (should be split into ccs & bccs), etc. Should save you a lot of validation as well, eventually." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T16:10:52.527", "Id": "435710", "Score": "0", "body": "It is very difficult to tell if an object is SOLID just from 2 functions, it would be better if the entire class were included." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T12:58:57.780", "Id": "435828", "Score": "0", "body": "@pacmaninbw The class these two methods are contained in is a general purpose utilities class, containing a hodgepodge of static utility methods." } ]
[ { "body": "<p>I'd still say that you should break apart the mail message and SMTP client into separate classes for the \"Single responsibility principle\". In specific:</p>\n\n<blockquote>\n <p>A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.</p>\n</blockquote>\n\n<p>This is usually where you have a <code>MailFactory</code> and a <code>SmtpClientFactory</code> that are injected into the class that actually does the sending (<code>MailSender</code>). The injection (by abstract, so interfaces) would be set into the <code>MailSender</code> to fulfill the \"Dependency inversion principle\"</p>\n\n<blockquote>\n <p>One should \"depend upon abstractions, [not] concretions.\"</p>\n</blockquote>\n\n<p><em>Side Note</em></p>\n\n<p>This would also let you reduce <code>MailFactory.CreateMailMessage</code> to <code>MailFactory.Create</code> (and <code>SmtpClientFactory.CreateSmtpClient</code> to <code>SmtpClientFactory.Create</code>) but that isn't directly related to SOLID. You can get why in various API naming conventions, but the short answer is that it would be redundant.</p>\n\n<p><em>Expansion</em></p>\n\n<p>A reason for this is when you do unit testing. We have an abstract mail client that just sticks messages into an in-memory list in the order they are sent. That way, we can inject it into the sender as <code>ISmtpClientFactory</code> and the rest of the code still works, not knowing that we have taken out the entire implementation of the sending for testing.</p>\n\n<p><em>Edit 2</em></p>\n\n<p>You also want to avoid <code>static</code> in general. It is implied by \"injecting\" but I figured I'd clarify that. Create factory instances and pass them in. That way you can swap them out.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:24:00.390", "Id": "224249", "ParentId": "224247", "Score": "7" } } ]
{ "AcceptedAnswerId": "224249", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:53:19.197", "Id": "224247", "Score": "7", "Tags": [ "c#", "object-oriented", "comparative-review", "email" ], "Title": "Function to send email, refactored based on SOLID principles" }
224247
<p>When working on a large codebase, I often need to switch between deeply nested directories quickly. To make my life easier, I came up with a bookmarking script.</p> <pre><code>#!/bin/bash bm_list() { for i in "${!BOOKMARKS[@]}"; do echo -e $i'\t'"${BOOKMARKS[$i]}" ; done } bm_go() { cd "${BOOKMARKS[$1]}" } bm_add() { for i in "${!BOOKMARKS[@]}"; do [[ "$1" == ${BOOKMARKS[$i]} ]] &amp;&amp; return done BOOKMARKS+=("$1") } bm_clear() { unset BOOKMARKS } bm_delete() { unset BOOKMARKS[$1] } bm_compact() { local SIFS="$IFS"; IFS= BOOKMARKS=("${BOOKMARKS[@]}") IFS="$SIFS" } bm_load() { local bmfile=${1:-~/.bookmarks} local SIFS="$IFS"; IFS=$'\n' bm_clear while read -d ''; do BOOKMARKS+=("$REPLY"); done &lt; "$bmfile" IFS="$SIFS" } bm_save() { local bmfile=${1:-~/.bookmarks} printf '%s\0' "${BOOKMARKS[@]}" &gt; "$bmfile" } bm_help() { cat &lt;&lt;-EOF bm: bookmark directories Usage: bm bookmark current directory bm -l bm list list bookmarks bm index bm -g index bm go index cd to bookmark at index bm -d index bm delete index delete bookmark at index bm -s [filename] bm save [filename] save bookmarks in the file (default ~/.bookmarks) bm -L [filename] bm load [filename] load bookmarks from the file (default !/.bookmarks) bm -c bm clear remove all bookmarks bm -C bm compact compact indices to a sequential list EOF } bm() { local command=$1; shift case $command in -l | list ) bm_list ;; -g | go ) bm_go "$1" ;; -d | delete ) bm_delete "$1";; -s | save ) bm_save "$1" ;; -c | clear ) bm_clear ;; -C | compact ) bm_compact ;; -L | load ) bm_load "$1" ;; '') bm_add "$PWD" ;; *) [[ "$command" =~ [0-9]+ ]] &amp;&amp; bm_go "$command" || bm_help ;; esac } </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/10383546/96588\"><code>#!/usr/bin/env bash</code></a> is a very common shebang line these days.</li>\n<li><a href=\"https://mywiki.wooledge.org/Quotes\" rel=\"nofollow noreferrer\">Use More Quotes™</a>:\n\n<ul>\n<li><code>echo -e $i'\\t'\"${BOOKMARKS[$i]}\"</code> should be <code>echo -e $i'\\t'\"${BOOKMARKS[$i]}\"</code> (or even better, <code>printf '%s\\t%s' \"$i\" \"${BOOKMARKS[$i]}\"</code>)</li>\n<li><code>command=$1</code> should be <code>command=\"$1\"</code></li>\n</ul></li>\n<li>In <code>[[ \"$command\" =~ [0-9]+ ]]</code> you'll want to anchor the regex.</li>\n<li>If this is for your own use I don't quite understand the need for both option-style and command-style invocation.</li>\n<li><code>==</code> in Bash is a bit of a historical accident. It won't make any difference as long as you use Bash, but I usually prefer the POSIX <code>=</code> in this case.</li>\n<li>It seems <code>bm_compact</code> should run on every change, since it'll be super fast and you avoid changing indexes.</li>\n<li><code>bmfile</code> would be better as either configuration or as a single variable.</li>\n<li>\"default !/.bookmarks\" should probably be \"default ~/.bookmarks\".</li>\n<li>You can set <code>IFS</code> for a single command, such as <code>while IFS=… read …</code></li>\n<li><p>All the single semicolons are extraneous - you definitely don't need one for <code>echo -e $i'\\t'\"${BOOKMARKS[$i]}\" ;</code>, and you can use</p>\n\n<pre><code>for i in \"${!BOOKMARKS[@]}\"\ndo\n</code></pre>\n\n<p>for loops and conditionals.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:51:09.303", "Id": "434937", "Score": "0", "body": "I appreciate you elaborating on the bullet 2." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:44:16.177", "Id": "224251", "ParentId": "224248", "Score": "4" } }, { "body": "<h3>Sanity check</h3>\n\n<p><a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">Shellcheck.net</a> reports a couple of issues.\nI will not call them out one by one, I suggest to review and fix.</p>\n\n<h3>Incorrectly saving empty bookmark</h3>\n\n<p>When there are no bookmarks, <code>bm_save</code> will write a single null byte to the file.\nThen, when you list bookmarks the empty entry shows up at index 0.</p>\n\n<p>I suggest to add a check before actually writing to the file:</p>\n\n<pre><code>[[ ${#BOOKMARKS[@]} != 0 ]] || return 0\n</code></pre>\n\n<h3>Do not raise error when file does not exist</h3>\n\n<p><code>bm_load</code> raises an error if the file does not exist.\nIs that the intended behavior?\nI don't think so, because <code>bm_save</code> happily writes to the file.\nPerhaps <code>bm_load</code> should be more forgiving.</p>\n\n<h3>Overriding <code>IFS</code></h3>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/716/l0b0\">@l0b0</a> already pointed out, it's good to prefix with <code>IFS=...</code> just the command where you want the modified value, when possible (usually).\nAnother alternative is to use <code>local IFS=...</code>:\nthe modified value will only be visible within the function,\nso no need to worry about backup and restore.</p>\n\n<h3>Unnecessary overriding of <code>IFS</code></h3>\n\n<p>In <code>bm_compact</code> I don't see a reason to override <code>IFS</code> to recreate <code>BOOKMARKS</code>.</p>\n\n<p>Btw, at first I didn't understand the purpose of this function.\nI think naming it <code>bm_compact_indexes</code> would have made it click.</p>\n\n<h3>What is <code>REPLY</code>?</h3>\n\n<p>I can find what is <code>REPLY</code> if I look at <code>help read</code>.\nI think it will be easier to understand the code if you specify a descriptive variable name with <code>read</code>.</p>\n\n<h3>Can you use Bash 4?</h3>\n\n<p>Where there is Bash, there's usually Bash 4.\nUsing <code>mapfile</code> you could replace the loop reading <code>BOOKMARKS</code> in <code>bm_load</code> with:</p>\n\n<pre><code>mapfile -d '' -t BOOKMARKS &lt; \"$bmfile\"\n</code></pre>\n\n<h3>Avoid <code>echo -e</code></h3>\n\n<p>The flags of <code>echo</code> don't work reliably in all systems, so I suggest to avoid it.\nYour alternatives are using <code>printf</code> (which is not POSIX compliant), or (in your specific case) to embed tab characters in the string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T15:12:21.807", "Id": "225037", "ParentId": "224248", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T20:56:07.493", "Id": "224248", "Score": "5", "Tags": [ "bash", "shell" ], "Title": "Bookmarking directories" }
224248
<p>I've been writing up code to test an alternate way of calculating the Binomial probability mass function. The Binomial random variable is the number of heads out of N coin tosses with coins that have probability p of being heads.</p> <p>The algorithm is pretty simple, we loop through the N coin tosses and update the probability that there are k successes as: </p> <pre><code>pmf[k] = pmf[k-1] * p + pmf[k] * (1 - p) </code></pre> <p>Since we know <code>pmf[k] = 0</code> for <code>k &gt; n</code> (there can't be more successes than coins tossed so far), we evaluate this line N(N+1)/2 times.</p> <p>The algorithm works well, is exact, and avoids a number of common pitfalls when computing the Binomial distribution. This is the best implementation I've managed so far, which takes ~190 ms to run on my Dell XPS-15 for <code>N = 15000</code> and <code>long double p = 0.5</code>.</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename T&gt; std::vector&lt;T&gt; ComputePmf(T p, unsigned int N) { std::vector&lt;T&gt; pmf(N + 1, 0.0); pmf[0] = 1.0; auto k = 0; for (auto n = 0; n &lt; N; n++) { for (k = n + 1; k &gt; 0; --k) { pmf[k] += p * (pmf[k - 1] - pmf[k]); } pmf[0] *= (1 - p); } return pmf; } </code></pre> <p>Ordinarily I'd hang up my hat and move on, but when I implemented the same algorithm in Julia it ran in 150 ms! Since then I've been stuck trying to figure out how to make my c++ version faster - I've tried:</p> <ol> <li>using different data types (<code>long double</code> works best, maybe due to SIMD alignment?),</li> <li><code>std::array</code> versus <code>std::vector</code> (no difference), </li> <li>other ways of factoring the inner loop (this is the best I've come up with),</li> <li>clang and gcc compilers (gcc does slightly better),</li> </ol> <p>It seems like the only real information that I'm not exploiting is the very sequential nature of the data access in this algorithm. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T00:18:45.953", "Id": "434952", "Score": "1", "body": "It's funny that `long double` was best, it *prevents* SIMD from being used (Clang doesn't seem too keen on auto-vectorizing this anyway though)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T00:21:28.660", "Id": "434953", "Score": "0", "body": "The difference is remarkable - using `double` takes ~7 times longer (~1.4 seconds). Maybe this hints at the problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T00:26:55.873", "Id": "434955", "Score": "2", "body": "Maybe it's running into the denormal penalty? Long double benefits from its significantly larger exponent range then" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T00:32:18.140", "Id": "434958", "Score": "0", "body": "That would make sense - using `float` is even slower. Most of these values are _very_ close to zero, some eventually round to zero even with long double values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T03:32:15.957", "Id": "434975", "Score": "0", "body": "@harold you are right about denormals. Setting appropriate compiler flags/macros and switching to doubles made the code run in 50ms. Of course the long double code is still 200ms, but I think julia must be using doubles. If you write up an answer I'll accept it" } ]
[ { "body": "<p>High powers of small-magnitude numbers tend toward zero. When you get subnormal floating-point numbers, then there's a heavy speed penalty; this point is reached sooner with <code>double</code> than with <code>long double</code> (and reached even sooner still using <code>float</code>).</p>\n\n<p>A simple way to improve the speed may be to disable subnormals for this function - e.g. compile with <code>g++ -ffast-math</code> to push subnormal numbers to zero.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-30T14:17:13.243", "Id": "227178", "ParentId": "224253", "Score": "2" } } ]
{ "AcceptedAnswerId": "227178", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T22:26:11.343", "Id": "224253", "Score": "6", "Tags": [ "c++", "performance", "c++11", "combinatorics", "statistics" ], "Title": "A straightforward method for computing the Binomial probability mass function" }
224253
<p>Is this code a good test for a testable Clojure code? </p> <pre><code>(ns github.amexboy.v2-test (:require [github.amexboy.v2 :as t]) (:use [clojure.test])) (deftest test-module-name-default (let [ repository-root "/some/path/to/git" project-root "/some/path/to/project" services [{:input "service|origin/develop" :service-name "service" :ex-branch "origin/develop" :ex-service-name "service-develop"} {:input "service" :service-name "service" :ex-branch "origin/master" :ex-service-name "service-master"} {:input "service|develop" :service-name "service" :ex-branch "develop" :ex-service-name "service-develop"} {:input "" :ex-failure {:error "Service name required"}}]] (run! (fn [test-map] (let [expected-service-name (:ex-service-name test-map) expected-branch (:ex-branch test-map) service-name (:service-name test-map) ; Passing a mock function that validates the inputs git-funcs {:git-worktree (fn [repo worktree branch] (is (= (str repository-root "/" service-name ) repo)) (is (= (str project-root "/" expected-service-name ) worktree)) (is (= expected-branch branch)))}] (let [res (t/gen-worktree repository-root project-root (:input test-map) git-funcs) failure (:ex-failure test-map)] (if failure (is (= (:error res) (:error failure) )) (is (= (not (:error res)))))))) services))) ; Test parse input ; Testing passing differenet parmeters to the entry point ;; Over my head - Classic - MTKO (deftest test-command-line-parse (let [ git-funcs {} test-input [ { :input "-b TEST-branch-name -B origin/develop -m service-one,service-two|master -n TEST-one -r /path/to/root -p /pat/to/projects --no-start" :ex-base-branch "origin/develop" :ex-branch "TEST-branch-name" :ex-project-root "/path/to/projects" :ex-repo-root "/path/to/root" :ex-name "TEST-one" :ex-services ["service-one" "service-two"]} { :input "-b TEST-branch-name -m service-one,service-two -n TEST-one" :ex-base-branch "origin/master" :ex-branch "TEST-branch-name" :ex-project-root "./projects" :ex-repo-root "." :ex-name "TEST-one" :ex-services ["service-one" "service-two"]} { :input "-b TEST-branch -n test-one" :ex-failure {:error "Invalid parameter: module name is required"}} { :input "-b TEST-branch -m service-one,service-two|master" :ex-failure {:error "Invalid parameter: project name is required"}} { :input "-m service-one,service-two|master -n test-one" :ex-failure {:error "Invalid parameter: branch is required"}}]] (run! (fn [t] (let [ gen-project (fn [project-def git-funcs] (is (= (:base-branch project-def) (:ex-base-branch t) )) (is (= (:branch project-def) (:ex-branch t) )) (is (= (:project-root project-def) (:ex-project-root t) )) (is (= (:repo-root project-def) (:ex-repo-root t) )) (is (= (:name project-def) (:ex-name t) )) (is (= (:services project-def) (:ex-services t) ))) ] (let [res (t/gen-project(:input test-map) git-funcs) failure (:ex-failure test-map)] (if failure (is (= (:error res) (:error failure) )) (is (= (not (:error res)))))))) test-input))) </code></pre> <p>The tests are awefully verbose. What I'm trying to do on the first function is to pass a mocked method and validate the paramters. </p> <p>Are you able to tell what the code (if implemented) might do?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T23:53:44.323", "Id": "434951", "Score": "1", "body": "`-B orign/develop` looks like a typo?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T23:27:00.060", "Id": "224254", "Score": "1", "Tags": [ "unit-testing", "clojure", "git" ], "Title": "Clojure test for Git operations" }
224254
<p>I am working on a project that needs to take a <a href="https://en.wikipedia.org/wiki/Glyph_Bitmap_Distribution_Format" rel="nofollow noreferrer">.bdf font file</a> and turn it into a Numpy array. I am using the code below to turn the bitmap for the font into a numpy array. It currently works, I just feel that it's nearly impossible to read but I'm not sure if there's a better way to do it. </p> <p>How the current code works:</p> <ol> <li>It splits the string by line since each line of the string is a row.</li> <li>It selects the first two values from the row since the last two never seem to matter.</li> <li>Using <code>int()</code> I convert the string of hex to an integer.</li> <li>Using <code>bin()</code> I turn the integer to binary.</li> <li>Then I use <code>zfill()</code> because leading zeros in the binary are important. This returns a string of 1's and 0's</li> <li>Then I use <code>list()</code> to break the string of binary into a list of single 1's and 0's</li> <li>Then I convert that all to a numpy array with <code>dtype=int</code></li> </ol> <p>The process feels really messy and it takes a millisecond which I feel like is pretty long for a (15, 9) numpy array. Any ideas for improvements would be greatly appreciated.</p> <pre class="lang-py prettyprint-override"><code>def hexToNumpy(hexValues, columns): return np.array( [ list(bin(int(row[0:2], 16))[2:].zfill(columns)) for row in hexValues.split("\n") ], dtype=int, ) T = """0000 0000 7F00 0800 0800 0800 0800 0800 0800 0800 0800 0800 0000 0000 0000""" hexToNumpy(T, 9) </code></pre>
[]
[ { "body": "<ul>\n<li><p>You can simplify <code>bin(...)[2:].zfill(columns)</code> to <code>f'{...:0&gt;{columns}b}'</code>.</p>\n\n<p>This can use <code>f'{int(row[:2], 16):0&gt;{columns}b}'</code>.</p></li>\n<li><p>I'd recommend you convert to a NumPy array out of the function, as it's not really that important to be in there.</p></li>\n<li><p>Your code isn't idiomatic, as Python uses <code>snake_case</code> not <code>camelCase</code>.</p></li>\n</ul>\n\n<pre><code>def from_hex(values, columns):\n return [\n list(f'{int(row[:2], 16):0&gt;{columns}b}')\n for row in values.split(\"\\n\")\n ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T01:15:36.947", "Id": "224258", "ParentId": "224256", "Score": "2" } } ]
{ "AcceptedAnswerId": "224258", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T00:55:26.160", "Id": "224256", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "numpy" ], "Title": "Converting string of hex values to numpy array of specific shape" }
224256
<blockquote> <p>If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.</p> <p>If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?</p> <p>NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of &quot;and&quot; when writing out numbers is in compliance with British usage.</p> </blockquote> <p>Here's my implementation in Python:</p> <pre><code>def number_to_word(n): &quot;&quot;&quot;Assumes is an integer from 1 - 1000. Returns number in words ex: 122 --&gt; one hundred and twenty-two.&quot;&quot;&quot; # num_to_alpha contains the unique values for numbers that will be returned according to repetitive patterns num_to_alpha =\ {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'one hundred', 1000: 'one thousand'} # Numbers below 21 , 100, 1000 are unique words (cannot be formed using a repetitive rule) if 0 &lt; n &lt; 21 or n == 100 or n == 1000: return num_to_alpha[n] mod = n % 10 # Numbers in range (21 - 99) have a single rule except the multiples of 10 (formed by a single word) if 20 &lt; n &lt; 100: if n % 10 != 0: return f'{num_to_alpha[n // 10 * 10]}-{num_to_alpha[mod]}' return num_to_alpha[n] # Numbers above 100 have a single rule except the following: if 100 &lt; n &lt; 1000: # a) multiples of 100 if n % 100 == 0: return f'{num_to_alpha[n // 100]} hundred' # b) numbers whose last 2 digits are above 20 and are also multiples of 10 if not n % 100 == 0 and n % 100 &gt; 20 and n % 10 == 0: return f'{num_to_alpha[n // 100]} hundred and {num_to_alpha[n % 100]}' # c) numbers whose last 2 digits are below 20 and not multiples of 10 if n % 100 &lt; 21: second_part = num_to_alpha[n % 100] return f'{num_to_alpha[n // 100]} hundred and {second_part}' # d) numbers whose last 2 digits are above 20 and not multiples of 10 if n % 100 &gt; 20: return f'{num_to_alpha[n // 100]} hundred and {num_to_alpha[((n % 100) // 10) * 10]}-' \ f'{num_to_alpha[(n % 100) % 10]}' # To prevent counting False values if n &lt;= 0 or n &gt; 1000: return '' def count(): &quot;&quot;&quot;Cleans numbers from spaces and hyphens and returns count.&quot;&quot;&quot; all_numbers = [number_to_word(x) for x in range(1, 1001)] numbers_without_spaces = [number.replace(' ', '') for number in all_numbers] clean_numbers = [number.replace('-', '') for number in numbers_without_spaces] total = 0 for clean_number in clean_numbers: total += len(clean_number) return total if __name__ == '__main__': print(count()) </code></pre>
[]
[ { "body": "<p><code>num_to_alpha =\\</code> is not Pythonic. If a statement is “incomplete”, there is no need to add a trailing <code>\\</code> to indicate the line is continued. An “incomplete” statement is one which contains unclosed <code>{</code>, <code>[</code>, or <code>(</code>, so this line could be written without the trailing <code>\\</code> simply by moving the <code>{</code> up to the previous line:</p>\n\n<pre><code>num_to_alpha = {\n 1: 'one', ...\n</code></pre>\n\n<p>The <code>if 0 &lt; n &lt; 21 or n == 100 or n == 1000:</code> test could be written more simply as <code>if n in num_to_alpha:</code>. This would also handle many other simple cases where the number exists in the <code>num_to_alpha</code> dictionary.</p>\n\n<p>You compute <code>mod = n % 10</code>, and then go on to test <code>if n % 10 != 0:</code>. You could simply test the already computed value <code>if mod != 0:</code>, or since non-zero values are Truthy, <code>if mod:</code>.</p>\n\n<p>You are testing for values which cannot possibly be true due to early tests. For instance, once a number is above 100, you test:</p>\n\n<pre><code>if n % 100 == 0:\n return ...\n</code></pre>\n\n<p>This is followed by:</p>\n\n<pre><code>if not n % 100 == 0 and ...:\n</code></pre>\n\n<p>If <code>n % 100</code> evaluated to <code>True</code>, the first <code>return</code> statement would have been executed. Testing <code>not n % 100 == 0</code> doesn’t add any value.</p>\n\n<p>At the end of the function, you explicitly check <code>if n &lt;= 0 or n &gt; 1000:</code> and <code>return</code> the empty string. And if THAT test fails ... what happens? <code>None</code> will be returned? If the number passed any of the above tests, and explicit <code>return</code> statement would have already returned the desired string, so if the end of the function is reached, does it matter what the return value is? Could you not unconditionally <code>return ''</code>. Or better: <code>raise ValueError()</code></p>\n\n<hr>\n\n<h2>DRY: Don’t Repeat Yourself</h2>\n\n<p>You code is repeating the same tests. Is the number between 1 and 20? Are the last 2 digits of a 3 digit number between 1 and 20?</p>\n\n<p>If you structured your function in the following manner, you’d repeat yourself less, and find it easy to extend into ten thousands, hundred thousands, millions and beyond:</p>\n\n<ul>\n<li>Start with an empty string</li>\n<li>If <code>n &gt;= 1000</code>\n\n<ul>\n<li>add <code>num_to_alpha[n // 1000]</code> and “thousand” to the string,</li>\n<li><code>n = n % 1000</code></li>\n</ul></li>\n<li>If <code>n &gt;= 100</code>\n\n<ul>\n<li>add <code>num_to_alpha[n // 100]</code> and “hundred” to the string,</li>\n<li><code>n = n % 100</code></li>\n</ul></li>\n<li>If <code>n &gt; 0</code> and the string is not empty,\n\n<ul>\n<li>add “and” to the string</li>\n</ul></li>\n<li>If <code>n &gt; 20</code>,\n\n<ul>\n<li>add <code>num_to_alpha[n // 10 * 10]</code> to the string</li>\n<li><code>n = n % 10</code></li>\n</ul></li>\n<li>If <code>n &gt; 0</code>\n\n<ul>\n<li>add <code>num_to_alpha[n]</code> to the string</li>\n</ul></li>\n<li>Return the resulting string</li>\n</ul>\n\n<hr>\n\n<p>Since you aren’t really using the returned strings, but eventually just counting the number of letters in the resulting string, you could optimize the function to not use strings at all. Just store the number of letters of each number in the dictionary:</p>\n\n<pre><code>num_to_length = {\n 1: 3, 2: 3, 3: 5, 4: 4, ...\n}\n</code></pre>\n\n<p>and add 8, 7, and 3 instead of the strings “thousand”, “hundred” &amp; “and”.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T04:26:57.340", "Id": "434980", "Score": "1", "body": "I thought initially about storing numbers instead of words however I'm too lazy to count letters for each case plus it's a lot harder to debug, in case of mistakes in calculations. Regarding the repeat tests you have a point and I thought about making separate functions for each case but did not do it at the end." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T04:36:10.877", "Id": "434982", "Score": "1", "body": "Yup. Much harder to debug. As for being too lazy to count, that’s what computers are for: `num_to_length = { n: len(word) for n, word in num_to_alpha.items() }` ... but beware of “one hundred” & “one thousand” (But I wasn’t using those values in the DRY algorithm)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T04:04:02.063", "Id": "224266", "ParentId": "224257", "Score": "0" } } ]
{ "AcceptedAnswerId": "224266", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T01:13:38.477", "Id": "224257", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "numbers-to-words" ], "Title": "Project Euler #17: Number Letter Counts" }
224257
<p>I want to get table names and column names from queries in a dataframe. The dataframe is like this:</p> <pre><code>Date Query 29-03-2019 SELECT * FROM table WHERE .. 30-03-2019 SELECT * FROM ... JOIN ... ON ...WHERE .. .... .... 20-05-2019 SELECT ... </code></pre> <p>and I run function to that dataframe to get <code>tablename</code> from the queries.</p> <pre><code>import sqlparse from sqlparse.tokens import Keyword, DML def getTableKey(parsed): findFrom = False wordKey = set( [ "FROM", "JOIN", "LEFT JOIN", "INNER JOIN", "RIGHT JOIN", "OUTER JOIN", "FULL JOIN", ] ) for word in parsed.tokens: if word.is_group: yield from getTableKey(word) if findFrom: if isSelect(word): yield from getTableKey(word) elif word.ttype is Keyword: findFrom = False StopIteration else: yield word if word.ttype is Keyword and word.value.upper() in wordKey: findFrom = True def getTableName(sql): tableReg = re.compile(r"^.+?(?&lt;=[.])") tableName = [] query = sqlparse.parse(sql) for word in query: if word.get_type() != "UNKNOWN": stream = getTableKey(word) table = set(getWord(stream)) for item in table: tabl = tableReg.sub("", item) tableName.append(tabl) return tableName </code></pre> <p>Also, I run function to get <code>columnname</code> from queries.</p> <pre><code>def getKeyword(parsed): kataKeyword = set(["WHERE", "ORDER BY", "ON", "GROUP BY", "HAVING", "AND", "OR"]) from_seen = False for item in parsed.tokens: if item.is_group: yield from getKeyword(item) if from_seen: if isSelect(item): yield from getKeyword(item) elif item.ttype is Keyword: from_seen = False StopIteration else: yield item if item.ttype is Keyword and item.value.upper() in kataKeyword: from_seen = True def getAttribute(sql): attReg = re.compile(r"asc|desc", re.IGNORECASE) namaAtt = [] kueri = sqlparse.parse(sql) for kata in kueri: if kata.get_type() != "UNKNOWN": stream = getKeyword(kata) table = set(getWord(stream)) for item in table: tabl = attReg.sub("", item) namaAtt.append(tabl) return namaAtt </code></pre> <p>But as this is my first try, I need an opinion about what I've tried, because my code runs slowly with a large file.</p>
[]
[ { "body": "<p>That will not speedup your code, but there are some code improvements:</p>\n\n<ol>\n<li><p>follow naming conventions <code>getAttribute</code> -> <code>get_attribute</code> <a href=\"https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html\" rel=\"nofollow noreferrer\">https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html</a></p></li>\n<li><p>You can create set using set literal <code>my_set = {1, 2, 3}</code></p></li>\n<li><p>You can compile <code>tableReg = re.compile(r\"^.+?(?&lt;=[.])\")</code> once</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T07:55:35.130", "Id": "434993", "Score": "0", "body": "The canonical reference related to code style in Python is the official [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) widely known as PEP8." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T07:49:12.217", "Id": "224277", "ParentId": "224261", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T02:51:27.793", "Id": "224261", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "sql", "pandas" ], "Title": "SQL queries in a dataframe" }
224261
<p>I'm one month into self-learning Swift, and I would like some advice to improve my coding skills.</p> <p><em>I have listed 2 situations that I think I need to improve</em>. I'd like some feedback focusing on my use of <code>static</code> variables for changing data between <code>ViewControllers</code> and <code>subviews</code>.</p> <hr> <p><strong>1.0</strong> Image 1 shows the app flow (Left = <code>HomeController</code>), middle = <code>MenuController</code>, Right = <code>FavouritesController</code>)</p> <p><em>Image 1</em> <a href="https://i.stack.imgur.com/IqE4G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqE4G.png" alt="Image 1"></a></p> <p>In <code>HomeController</code> there is a <code>UIView</code> subview. From this subview the current quote (<code>HomeController.homeControllerCurrentQuote</code>) displayed can be saved to <code>favourites</code> array. This is a static array defined in <code>FavouritesController</code>.</p> <p>The functions below are called from the <code>subview</code> within <code>HomeController</code>. I made <code>HomeController.homeControllerCurrentQuote</code> static because the subview needs access to it. Likewise for <code>FavouritesController.favourites</code>.</p> <p>In <code>FavouritesController</code> the data contained in <code>FavouritesController.favourites</code> array is used to populate a <code>tableVIew</code>.</p> <pre><code>// FavouritesController.favourites is static variable! // HomeController.homeControllerCurrentQuote is static variable! updated as user scrolls func handleFavourite() { let favourites = FavouritesController.favourites if favourites.contains(HomeController.homeControllerCurrentQuote) { removeFromFavourites() } else { FavouritesController.favourites.append(HomeController.homeControllerCurrentQuote) UserDefaults.standard.set(try? PropertyListEncoder().encode(FavouritesController.favourites), forKey:"myKey") } } func removeFromFavourites() { var tempArray: [Quote] = [.init(category: "", quote: "", author: "")] tempArray = FavouritesController.favourites let searchString = HomeController.homeControllerCurrentQuote.quote var filteredArray = [Quote]() filteredArray = tempArray.filter( { !$0.quote.contains(searchString) } ) UserDefaults.standard.set(try? PropertyListEncoder().encode(filteredArray), forKey:"myKey") } // update static variable on HomeController internal override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { .... HomeController.homeControllerCurrentQuote = Quote(category: cell.categoryLabel.text ?? "", quote: cell.quoteLabel.text ?? "", author: author) .... } </code></pre> <p>Should I change how this is done? I don't like the use of static variables but as it's my first app I was more focused on getting it done rather than how it was done. Is it a good case for using a <code>delegate</code> and <code>protocol</code> to communicate between the views (I've never used this before)? If so how would I start to think about implementing it or, as it works, is what I've done satisfactory?</p> <hr> <p><strong>2.0</strong> When the app launches on <code>HomeController</code> required data is generated and is stored in a static variable.</p> <pre><code> // [category : [quote : author]] static var xQuotesByCategory: [String : [String : String]] = [:] </code></pre> <p>I make this data static because when I instantiate <code>HomeController</code> again from another controller, I don't want to have to refetch the data. I want to retrieve it once. Then when a new instance of <code>HomeController</code> is called I can make this check which should return false. Is this an appropriate use of a static variable?</p> <pre><code>if HomeController.xQuotesByCategory.values.isEmpty { ... fetchJson() } </code></pre> <p>Following on from this, as <code>HomeController.xQuotesByCategory</code> is static, on <code>CategoriesController</code> I can call</p> <pre><code>var categories = Array(HomeController.xQuotesByCategory.keys) </code></pre> <p>This gets only the outer <code>keys</code> (categories) which I use to create the <code>collectionView</code> <code>cells</code> with the text and images shown in image 2. Again, same question, is this appropriate use of a static variable? Is there better way to ensure data is loaded only once and then pass the <code>keys</code> to <code>CategoriesController</code> in a different way when it's required?</p> <p><a href="https://i.stack.imgur.com/MHjV4l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MHjV4l.png" alt="image 2"></a></p> <hr> <p>If you'd like to try running the app, there is a test version available on TestFlight. Let me know and I can add you in TestFlight!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T03:52:45.643", "Id": "224263", "Score": "4", "Tags": [ "beginner", "swift", "ios", "controller", "cocoa" ], "Title": "Swift iOS app for showing motivational quotes, with multiple screens" }
224263
<p><em>Update: further succinct versions below (inspired by Haskell)</em></p> <p>Quick sort in JS assuming an immutable array:</p> <pre><code> const reorder = (arr, pivot) =&gt; { let larger = [] let smaller = [] let equals = [] for (let i = 0; i &lt; arr.length; i++) { if (arr[i] &lt; arr[pivot]) { smaller.push(arr[i]) } else if (arr[i] &gt; arr[pivot]) { larger.push(arr[i]) } else { equals.push(arr[i]) } } return { smaller: smaller, equals: equals, larger: larger } } const sort = (arr) =&gt; { if (arr.length &lt;= 1) { return arr } const pivot = Math.floor(arr.length / 2) const result = reorder(arr, pivot) return [...sort(result.smaller), ...result.equals, ...sort(result.larger)] } console.log(sort([3, 1, 1, 1, 2])) </code></pre> <p><em>PS: I deleted the question posted earlier, thinking the algo was wrong, but then I realized a small tweak corrected it. The present code is based on comments received on earlier question.</em></p> <p><strong>Update</strong>: <em>Inspired by Haskell, here is a more succinct version using ES6:</em></p> <pre><code> const qsort = (arr) =&gt; { if(arr.length == 0) { return [] } let [x,...xs] = arr let smaller = xs.filter(v =&gt; v &lt;=x) let larger = xs.filter(v =&gt; v &gt; x) return [...qsort(smaller),x,...qsort(larger)] } OR simplified further: const qsort = ([x,...xs]) =&gt; { return x == undefined ? [] : [...qsort(xs.filter(v =&gt; v &lt;=x)),x,...qsort(xs.filter(v =&gt; v &gt; x))] } qsort([3,3,8,1,23,4,5,6,9,9,1,0,45,5,10]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T09:35:22.350", "Id": "435298", "Score": "1", "body": "`return !x ? [] :` this will return an empty array when the first element is 0." } ]
[ { "body": "<p>Your code looks quite good. It is easy to read and understand.</p>\n\n<p>I don't know how efficient it is, though. The <code>reorder</code> function creates lots of objects (3 arrays, and a return object). I think there are more efficient ways to implement this. Since you got the algorithmic complexity correct, I would not worry about these performance issues too much. If the code is fast enough, it's good enough. And it's readable, which is often more important.</p>\n\n<p>Instead of <code>let larger = []</code>, you can write <code>const larger = []</code> since the variable <code>larger</code> is only ever assigned once. Sure, you later modify the contents of the array, but the variable still points to the same array as before.</p>\n\n<p>Instead of the <code>for (let i = 0</code> loop, you can use the simpler <code>for (const elem of arr)</code> loop, which will free your code from the many <code>[i]</code> brackets.</p>\n\n<p>There are some more unnecessary brackets in that function, in the expression <code>arr[pivot]</code>. This expression is evaluated more often than necessary. I would change the pivot element to be the value itself instead of the array index.</p>\n\n<p>The <code>sort</code> function returns the original array in some cases, and a new array in the other cases. That is inconsistent. The caller of the <code>sort</code> function might assume that they may modify the array afterwards, and depending on the array size, this may or may not affect the original array, which you defined as immutable. Therefore you should return a copy of the array in every case.</p>\n\n<p>You should write lots of automated tests. Having just a single example is not enough to cover all cases. I have written a few test cases for you, feel free to add more.</p>\n\n<p>After applying all these suggestions, the code looks like this:</p>\n\n<pre><code>const reorder = (arr, pivot) =&gt; {\n const larger = []\n const smaller = []\n const equals = []\n for (let elem of arr) {\n if (elem &lt; pivot) {\n smaller.push(elem)\n } else if (elem &gt; pivot) {\n larger.push(elem)\n } else {\n equals.push(elem)\n }\n }\n return {\n smaller: smaller,\n equals: equals,\n larger: larger\n }\n}\n\nconst sort = (arr) =&gt; {\n if (arr.length &lt;= 1) {\n return arr.slice()\n }\n const pivotIndex = Math.floor(arr.length / 2)\n const result = reorder(arr, arr[pivotIndex])\n return [...sort(result.smaller), ...result.equals, ...sort(result.larger)]\n}\n\nconst testcase = (unsorted, expected) =&gt; {\n const actual = sort(unsorted)\n const actualStr = actual.join(', ')\n const expectedStr = expected.join(', ')\n if (actualStr !== expectedStr) {\n console.log('error:', 'input:', unsorted, 'expected:', expected, 'actual:', actual)\n }\n\n if (actual.length !== 0) {\n const beforeModification = unsorted.join(', ')\n actual[0] += 1\n const afterModification = unsorted.join(', ')\n if (beforeModification !== afterModification) {\n console.log('error:', 'unsorted:', unsorted, 'before:', beforeModification, 'after:', afterModification)\n }\n }\n}\n\ntestcase([], [])\ntestcase([1], [1])\ntestcase([3, 1, 1, 1, 2], [1, 1, 1, 2, 3])\ntestcase([0, 5, 4, 8, 9, 3, 7, 1, 2, 6], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T08:03:58.883", "Id": "435287", "Score": "1", "body": "Btw, you could also write `return { smaller, equals, larger }` in `order` function, since keys are named the same as the values." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T05:08:14.687", "Id": "224268", "ParentId": "224264", "Score": "4" } } ]
{ "AcceptedAnswerId": "224268", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T03:53:01.280", "Id": "224264", "Score": "7", "Tags": [ "javascript", "quick-sort", "immutability" ], "Title": "Quicksort in JavaScript assuming an immutable array" }
224264
<p>I was messing around with <code>ssh</code> and decided to write a python program that scans for any connections that aren't from the system, then terminates them. It works well for many connections from my iMac to my MacBook. A more in-depth explanation of the program is written at the top of the code. I'd appreciate feedback on any nitpicks you can find, since I threw this together in about thirty minutes. Any and all feedback is appreciated and considered.</p> <p><strong>scanner.py</strong></p> <pre><code>""" Import Statements """ import os import subprocess import time """ Objective: Scan all connections to this computer, every two seconds, and if any are not system, as in not `console` or `s000`, find the PID associated with the connection, then terminate the connection with `kill -9 ...` """ def format_pid(text): """ Formats the output to only include PIDS that are not from the system """ ids = text.split("\n") all_ids = [] del ids[0] #removes uptime stuff for line in ids: pid = line[:13] if pid[12:] != '0': all_ids.append(pid[:5]) return all_ids def get_pids(): """ Returns all users logged into the computer """ return format_pid(subprocess.Popen(['ps'], stdout=subprocess.PIPE).communicate()[0]) def kill(): """ Terminates all processes that are not system """ processes = get_pids() for process in processes: if process: # Makes sure process isn't null/empty os.system('kill -9 ' + process) print("KILLED CONNECTION PROCESS: " + process) time.sleep(2) kill() if __name__ == '__main__': kill() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T09:12:37.737", "Id": "434998", "Score": "0", "body": "No time for a proper review, but you may be interested in [`psutil`](https://pypi.org/project/psutil/)." } ]
[ { "body": "<p>Replace magic numbers like 13 there <code>line[:13]</code> with constansts. \nIMHO:</p>\n\n<ul>\n<li>rename <code>ids</code> to <code>lines</code></li>\n<li><code>all_ids</code> to <code>ids</code></li>\n<li><code>processes</code> to <code>pids</code> </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T07:41:54.083", "Id": "224276", "ParentId": "224271", "Score": "1" } } ]
{ "AcceptedAnswerId": "224276", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T07:04:49.813", "Id": "224271", "Score": "3", "Tags": [ "python", "python-3.x", "ssh", "macos" ], "Title": "SSH autokiller for connections from other systems" }
224271
<p>This Server handles clients communicating with each other. Because I was not willing to actually give every client a name, they are named by their socket's file descriptor. This is my first application which actually is able to communicate using the INET. It is also my first really multithreaded application.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;pthread.h&gt; #include &lt;stdbool.h&gt; #define BUFLEN 255 #define MAX_CONNECTIONS 128 #define MAX_NAME_LENGTH 30 void delete_socket(int socketid); void* job_read(void*); void* job_write(void*); //Global Variables FILE* plogfile; int socket_ids[MAX_CONNECTIONS]; bool endprogramm = false; int open_cnncts = 0; pthread_mutex_t socketids_changingMutex; void error(const char* msg){ perror(msg); exit(1); } int main(int argc, char* argv[]) { printf("Server started...\n"); if(argc &lt; 2){ fprintf(stderr, "You must provide a port number"); exit(EXIT_FAILURE); } if(argc == 3){ plogfile = fopen(argv[2], "w"); } else { plogfile = fopen("logfile.txt", "w"); } stderr = plogfile; int sockfd; uint16_t portnum; //Create nmutthread if(pthread_mutex_init(&amp;socketids_changingMutex, NULL) &lt; 0){ error("Could not initialize Mutex"); } //Initialzing threads and create writethread pthread_t writethread; pthread_create(&amp;writethread, NULL, job_write, NULL); //Setup for connections struct sockaddr_in serv_add; struct sockaddr_in cli_adr; socklen_t clilen; clilen = sizeof(cli_adr); bzero((char*)&amp;serv_add, sizeof(struct sockaddr_in)); portnum = (uint16_t)atoi(argv[1]); serv_add.sin_family = AF_INET; serv_add.sin_addr.s_addr = INADDR_ANY; serv_add.sin_port = htons(portnum); sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd &lt; 0){ error("Error opening socket."); } if(bind(sockfd, (struct sockaddr*) (&amp;serv_add), sizeof(serv_add)) &lt; 0){ error("Binding failed."); } fprintf(plogfile,"Listening...."); listen(sockfd, MAX_CONNECTIONS); for(open_cnncts = 0; (!endprogramm); /*mutex needs to be set*/ ){ socket_ids[open_cnncts] = accept(sockfd, (struct sockaddr*) &amp;cli_adr, &amp;clilen); pthread_mutex_lock(&amp;socketids_changingMutex); fprintf(plogfile,"Client connected.\n"); pthread_t thread; pthread_create(&amp;thread , NULL, job_read, (void*)&amp;socket_ids[open_cnncts]); open_cnncts++; pthread_mutex_unlock(&amp;socketids_changingMutex); } endprogramm = true; close(sockfd); pthread_join(writethread, NULL); pthread_mutex_destroy(&amp;socketids_changingMutex); return EXIT_SUCCESS; } void* job_read(void * p){ int* socketp = (int*)p; int newsockfd = (*socketp); ssize_t n; //Error catching variable ssize_t m; //Error catching variable char buffer[BUFLEN]; char name[MAX_NAME_LENGTH]; sprintf(name, "Client %d: ", newsockfd); while(!endprogramm){ bzero(buffer, BUFLEN); n = read(newsockfd, buffer, BUFLEN); if(n&lt;0){ printf("Buffer: %s", buffer); error("Reading Failed"); } if(n == 0){ delete_socket(newsockfd); pthread_exit(NULL); } pthread_mutex_lock(&amp;socketids_changingMutex); for(int i = 0; i &lt; open_cnncts; i++){ if(socket_ids[i] == newsockfd){ continue; } m = write(socket_ids[i], name, strlen(name)); n = write(socket_ids[i], buffer, strlen(buffer)); if(n &lt; 0 | m &lt; 0){ error("Writing failed"); } } pthread_mutex_unlock(&amp;socketids_changingMutex); printf("%s%s", name, buffer); } delete_socket(newsockfd); pthread_exit( NULL ); } void* job_write(void* args){ (void)args; fprintf(plogfile, "Started writing thread...\n"); ssize_t n; //Error catching variable ssize_t m; //Error catching variable char buffer[BUFLEN]; char* name = "Server: \0"; while(!endprogramm) { fgets(buffer, BUFLEN, stdin); pthread_mutex_lock(&amp;socketids_changingMutex); for(int i = 0; i &lt; open_cnncts; i++){ m = write(socket_ids[i], name, strlen(name)); n = write(socket_ids[i], buffer, strlen(buffer)); if(n &lt; 0 | m &lt; 0){ printf("Writing failed"); } } pthread_mutex_unlock(&amp;socketids_changingMutex); if(strcmp("Bye\n", buffer) == 0){ exit(EXIT_SUCCESS); } } endprogramm = true; pthread_exit( NULL ); } void delete_socket(int socketid){ bool found = false; for(int i = 0; i &lt; open_cnncts; i++){ if(found){ socket_ids[i-1] = socket_ids[i]; } if(socket_ids[i] == socketid){ close(socketid); found = true; } } if(found){ open_cnncts--; } } </code></pre> <p>Obviously, this code needs improvement, so just feel free to criticize everything criticizable, especially about array-, thread-, and mutex-handling.</p>
[]
[ { "body": "<p><strong>Portability</strong><br>\nThe code uses pthread which is a <a href=\"https://en.wikipedia.org/wiki/POSIX\" rel=\"nofollow noreferrer\">POSIX</a> (Portable Operating System Interface) structure. If the code uses <code>POSIX</code> for one thing, it might be better to use <code>POSIX</code> for all things to remain <code>POSIX</code> compliant. This means that instead of using <code>bzero((char*)&amp;serv_add, sizeof(struct sockaddr_in));</code> to zero out the <code>serv_add</code> variable it might be better use <code>memset(&amp;serv_add, 0, sizeof(serv_add));</code>. The function <code>memset()</code> is part of the POSIX standard, the <code>bzero()</code> is not.</p>\n\n<p>There may be other non-POSIX functions that should be changed as well.</p>\n\n<p><strong>Redirecting Output</strong><br>\nMost operating systems provide mechanisms for redirecting output and errors, it might be better to create a shell script to start this program that redirects errors to a log file that changing the value of the system variable <code>stderr</code>. One of the values of this is that the person starting this chat server can name the log file and put it in a certain location on the system. This would also simplify the first part of the code in <code>main()</code>.</p>\n\n<p>It's also not clear what side affects there are when the variable <code>stderr</code> is over written.</p>\n\n<p><strong>Avoid Global Variables When Possible</strong><br>\nGlobal variables make it much harder to write, read and debug code, they can be considered a maintenance nightmare, especially when code is modularised into multiple files, it is better to pass parameters whenever possible.</p>\n\n<p>It is possible to pass arguments to a function used when creating a thread using <code>pthread_create()</code> by passing a pointer to a struct in the 4th parameter. The code already uses this mechanism in <code>job_read()</code> but both <code>job_read()</code> and <code>job_write()</code> could receive pointers to variables which are currently global.</p>\n\n<pre><code>struct JOB_INFO {\n int socket_ids[MAX_CONNECTIONS];\n bool endprogram;\n int open_cnncts;\n pthread_mutex_t *socketids_changingMutex;\n};\n\nint main(int argc, char* argv[])\n{\n struct JOB_INFO job_info;\n job_info.endprogram = false;\n job_info.open_cnncts = 0;\n job_info.socketids_changingMutex = ...;\n\n...\n\n pthread_create(&amp;writethread, NULL, job_write, &amp;job_info);\n\n\nvoid* job_write(void* args) {\n struct JOB_INFO *job_info = (struct JOB_INFO*) args;\n ...\n}\n</code></pre>\n\n<p><strong>Complexity</strong><br>\nThe <code>main()</code> function is overly complex, it might be better to break it up into sub-functions.</p>\n\n<ul>\n<li>Parse arguments</li>\n<li>Set up for connections</li>\n<li>Open connections loop</li>\n</ul>\n\n<p><strong>return over exit in main</strong><br>\nThere is no reason to call <code>exit()</code> in <code>main()</code>, return EXIT_FAILURE; will achieve the same result, <code>exit(int status)</code> is only necessary when trying to exit the program from sub functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T04:11:06.623", "Id": "435086", "Score": "2", "body": "> Calling exit() anywhere in the program may not return resources to the system as necessary - can you please be more specific? Which resources wouldn't be returned by calling exit vs return?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T05:43:11.850", "Id": "435096", "Score": "0", "body": "I don't think the comment about exit is correct. From the manual: `The exit(3) function causes normal process termination`. You may be thinking of _exit(2) or abort(3)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T12:39:43.877", "Id": "435167", "Score": "0", "body": "@GeorgeY. I have removed that portion of `return over exit in main`. Having worked in operating systems I generally don't like the use of `exit()` I prefer to use setjmp and longjmp and let main() clean things up before exiting." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T16:02:19.653", "Id": "224296", "ParentId": "224282", "Score": "7" } }, { "body": "<p>regarding:</p>\n\n<blockquote>\n<pre><code>if(n&lt;0){\n printf(\"Buffer: %s\", buffer);\n error(\"Reading Failed\");\n }\n</code></pre>\n</blockquote>\n\n<p>the call to <code>printf()</code> will change the value in <code>errno</code>. The result is the call to <code>perror()</code> in function: <code>error()</code> will print the wrong message.</p>\n\n<hr>\n\n<p>regarding:</p>\n\n<blockquote>\n<pre><code>void* job_read(void * p){\n int* socketp = (int*)p;\n int newsockfd = (*socketp);\n</code></pre>\n</blockquote>\n\n<p>the variable <code>socketp</code> is not used elsewhere in this function. Suggest:</p>\n\n<pre><code>void* job_read(void * p){\nint newsockfd = *(int*)p;\n</code></pre>\n\n<p>Also, the correct type for a socket is <code>sock_t</code>, not <code>int</code></p>\n\n<hr>\n\n<p>regarding: </p>\n\n<blockquote>\n<pre><code>#define MAX_CONNECTIONS 128\n</code></pre>\n</blockquote>\n\n<p>It would be advisable to check your OS to assure it will allow 128 simultaneous connections. Many 'user' OS versions will not allow anywhere near that many simultaneous connections.</p>\n\n<hr>\n\n<p>regarding:</p>\n\n<blockquote>\n<pre><code>m = write(socket_ids[i], name, strlen(name));\nn = write(socket_ids[i], buffer, strlen(buffer));\nif(n &lt; 0 | m &lt; 0){\n error(\"Writing failed\");\n}\n</code></pre>\n</blockquote>\n\n<p>If the first call to <code>write()</code> fails, it will have set <code>errno</code> indicating the reason the system thinks the error occurred. However, the second call to <code>write()</code> will overlay the value in <code>errno</code>, so the call to <code>error()/perror()</code> will output the wrong message.</p>\n\n<p>suggest:</p>\n\n<pre><code>if( (m = write(socket_ids[i], name, strlen(name)) ) &lt; 0 )\n{\n error( \"write of user name failed\" );\n}\n\nif( (n = write(socket_ids[i], buffer, strlen(buffer)) ) &lt; 0)\n{\n error(\"Writing of user message failed\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T18:31:01.393", "Id": "224299", "ParentId": "224282", "Score": "4" } }, { "body": "<ul>\n<li><code>pthread_create</code> returns value which is needed to be checked too; if your system runs out of resources, the new thread might not start.</li>\n<li>You are listening on all IPs available; considering that there is no visible authentication, this opens possibility for unauthorized access, impersonation etc. Consider listening on localhost only (enough within one server);</li>\n<li>The <code>socket_ids</code> is modified in <code>delete_socket</code> while the mutex is not locked. This creates a race condition if for example a new connection is accepted and at the same time the existing one is closed. Access to <code>socket_ids</code> has to be guarded by mutex.</li>\n<li>Same in access call - you're modifying <code>socket_ids</code> without holding mutex.</li>\n<li>Unix terminals generally send CRLF (\\r\\n) as linefeed, so the check for \"Bye\\n\" will not work for those.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T04:23:54.890", "Id": "435088", "Score": "0", "body": "unix systems generally use _\\n_ though https://en.wikipedia.org/wiki/Newline" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:41:44.383", "Id": "435104", "Score": "1", "body": "In files, but generally not in terminals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:12:42.250", "Id": "435141", "Score": "0", "body": "I cannot make delete_socket lock a mutex, because sometimes it is already locked. What happens if I lock twice and then unlock it? That would be miserable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T06:20:01.550", "Id": "435500", "Score": "0", "body": "If your mutex is recursive, you can lock it multiple times in the same thread without self-blocking; note that you also have to unlock it the same number of times so if you lock it twice, you have to unlock it twice as well." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T04:10:20.890", "Id": "224320", "ParentId": "224282", "Score": "2" } }, { "body": "<p>There is a lot of code duplication between <code>job_read</code> and <code>job_write</code>, and all the work is being done from a lot of threads inside a big mutex that will only allow one thread ever to actually do something. Servicing all clients from a single thread using <a href=\"http://man7.org/linux/man-pages/man2/select.2.html\" rel=\"nofollow noreferrer\"><code>select(2)</code></a> would be more efficient.</p>\n\n<p>The most annoying failure mode for this setup is that if one of the clients does not acknowledge data and the write buffer gets full, the writer thread will be stuck while holding the mutex, so all other threads that need to access the global data will get stuck as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T13:13:18.357", "Id": "435169", "Score": "0", "body": "Could you further describe what exactly you intend? Thank you :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:33:11.770", "Id": "224331", "ParentId": "224282", "Score": "1" } } ]
{ "AcceptedAnswerId": "224296", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T12:46:12.583", "Id": "224282", "Score": "4", "Tags": [ "c", "multithreading", "socket", "unix", "chat" ], "Title": "Unix chat server making communication between terminals possible" }
224282
<p>My code detects if a cycle is present in a graph using Union find algorithm with Weighted tree analysis and path compression.</p> <p>It works and I have included test cases.</p> <pre><code># check cycles in graph using union find # weighted tree balancing added from collections import defaultdict class graph: def __init__(self): self.graph = defaultdict(list) self.parents = {} self.size = {} def addnode(self, key1, key2, edge=0): if key2 not in self.graph: self.graph[key2] = [] self.graph[key1].append(key2) def findcycle(self): for key in self.graph: self.parents[key] = -1 self.size[key] = 1 for vertex in self.graph: for neighbour in self.graph[vertex]: x_par = self.getparent(vertex) y_par = self.getparent(neighbour) if x_par == y_par: return True self.union(x_par, y_par) def getparent(self, vertex): while self.parents[vertex] != -1: vertex = self.parents[vertex] return vertex def union(self, vertex, neighbour): x_par = self.getparent(vertex) y_par = self.getparent(neighbour) if self.size[x_par] &lt;= self.size[y_par]: self.parents[x_par] = y_par self.size[y_par] += self.size[x_par] else: self.parents[y_par] = x_par self.size[x_par] += self.size[y_par] g = graph() g.addnode(0, 1) g.addnode(2, 3) g.addnode(4,2) g.addnode(4,1) if g.findcycle(): print ("Graph contains cycle") else : print ("Graph does not contain cycle ") </code></pre>
[]
[ { "body": "<h2><code>addnode(self, key1, key2, edge=0)</code></h2>\n\n<p>The parameter <code>edge</code> is not used. Either remove it, or use it, but keeping it with a default value and not using it is obfuscation.</p>\n\n<p><code>self.graph</code> is a <code>defaultdict(list)</code>, so testing if <code>key2</code> is not present, and setting that key’s value to an empty list if it isn’t present, which is the raison d’être for the <code>defaultdict(list)</code>, isn’t using that class properly. You want the key to exist, but don’t want to add any values to it. Simply use:</p>\n\n<pre><code>_ = self.graph[key2]\n</code></pre>\n\n<h2><code>findcycle(self)</code></h2>\n\n<p>This function returns <code>True</code> or <code>None</code>. It would be much easier to write documentation for the function if it returned only one “kind” of value. Add <code>return False</code> to the end of the function. </p>\n\n<h2>Test cases</h2>\n\n<p>Put your test cases inside a <code>__name__ == '__main__'</code> guard. Then you can <code>import</code> this as a module into another file without the tests running, but running this file by itself will still execute the tests. </p>\n\n<pre><code>if __name__ == '__main__':\n g = graph()\n g.addnode(0, 1)\n # ...\n</code></pre>\n\n<h2>PEP8</h2>\n\n<p>Follow the PEP8 standard guidelines. Put a space after all commas, don’t put a space before the parentheses in function calls. Use an automatic checker (pylint, pyflakes, ...) to ensure you don’t violate these guidelines. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T14:03:12.537", "Id": "224286", "ParentId": "224283", "Score": "3" } } ]
{ "AcceptedAnswerId": "224286", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T13:00:27.437", "Id": "224283", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented", "graph", "union-find" ], "Title": "Find cycles in Graph using Union Find Algorithm on Adjacency List" }
224283
<p>I write a lot of TODO's but I never keep track of where they are.</p> <p>This program will search through files (and recursively through folders if needed) and find any TODO comments and their line number.</p> <p>The details will be printed to the screen and a file will be generated in the folder which is a csv of the files and TODO details.</p> <p>You can choose different filetypes, comments and <code>TODO</code> phrases to suit , so it is not just for python.</p> <p><a href="https://github.com/johnashu/TODO-Locater" rel="nofollow noreferrer">GitHub</a></p> <pre><code>from os.path import exists import sys from glob import glob class TodoLocater: def __init__(self, path, ext, td, comment, recursive=False): self.path = path self.ext = ext self.td = td self.comment = comment self.recursive = recursive self.todos = {} def get_files(self): try: g = glob(self.path + f"/**/*{self.ext}", recursive=self.recursive) if exists(self.path): for x in g: print(f"Searching :: {x}") result = self.find_todo(x) if result: self.todos[x] = result else: raise OSError("Path does not exist.") except Exception as e: print(e) def find_todo(self, f): temp_todos = [] line_no = 0 with open(f, "r") as input_: for line in input_: line_no += 1 if self.comment in line and self.td in line: temp_todos.append([f, f"Line - {line_no} :: {line.strip()}"]) return temp_todos def show_todos(self): line = "-" * 100 self.get_files() for k, v in self.todos.items(): print(f"\n{line}\n\n{k}") for x in v: print(f"&gt;&gt;&gt;{x[1]}") self.save_csv(k, [v]) def save_csv(self, fn, todos): import csv with open(fn + ".csv", "w", newline="") as csvfile: w = csv.writer(csvfile, delimiter=",", quoting=csv.QUOTE_MINIMAL) for row in todos: for r in row: w.writerow(r) if __name__ == "__main__": path = "." ext = "py" td = "TODO" comment = '#' find = TodoLocater(path, ext, td, comment, recursive=True) find.show_todos() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:57:53.370", "Id": "435020", "Score": "1", "body": "You should never catch a general exception. Catch what you expect and let the other stuff fail. It makes it easier for debugging. (`except Exception as e`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T19:10:34.300", "Id": "435041", "Score": "2", "body": "It's great that you went out and solved a real problem you had. That's a fantastic skill. I would point out however that in this scenario this entire script can be accomplished with something like `grep -rn '# *TODO' .` (`-r` recursively searches the current dir and gives you file names, `-n` prints line numbers). The wrapping on SO ruins the command, note that there's a space between the `#` and the `*` (this means zero of more spaces between the `#` and `TODO`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:27:58.823", "Id": "435102", "Score": "0", "body": "@BaileyParker I am aware of grepping but I use this on windows..:)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:07:53.990", "Id": "435137", "Score": "0", "body": "Using the Pycharm IDE, you can search through a project's TODOs with `Alt 6`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:18:09.863", "Id": "435142", "Score": "0", "body": "I use VSC :P lol but thanks for the tip.. There probably is similar in VSC as well but this creates a csv and this means it will also end up in git so I have quick access anywhere.." } ]
[ { "body": "<h2>Comments regarding the structure of the program:</h2>\n\n<ul>\n<li><p><strong>Method names</strong>. The name of a method should summarize what it does. However, some of your method names are misleading because they do things they should not do.</p>\n\n<ul>\n<li>When I saw the name <code>get_files()</code>, I thought that this method just returns all the files in <code>path</code>, which is not true;</li>\n<li>I would assume <code>show_todos()</code> just prints the todos, however, you also call <code>save_csv()</code> method inside it.</li>\n</ul></li>\n<li><p><strong>Using classes.</strong> I would not create a <code>TodoLocator</code> class. It could be just a method to which <code>path</code>, <code>ext</code>, etc. are passed as parameters. You shouldn't use class fields if you can use local variables and pass them between methods (Similarly to how you should avoid using global variables).</p></li>\n</ul>\n\n<h2>Having said that, I would structure the program as follows:</h2>\n\n<pre><code> def _get_files(path, ext) -&gt; List[str]:\n # return a list of files \n\n def _find_todos_in_file(file, todo_token, coment_start) -&gt; List[Tuple[str, str]]:\n # return a list of todos in the file\n\n def find_todos(path, ext, todo_token = 'TODO', comment_start = '#') -&gt; List[Tuple[str, str]]:\n files = _get_files(path, ext)\n return [todo for file in files for todo in _find_todos_in_file(file, todo_token, coment_start)]\n\n def show_todos(todos: List[Tuple[str, str]]):\n # show todos\n\n def save_csv(todos: List[Tuple[str, str], file: str):\n # save todos to a csv file\n\n if __name__ == \"__main__\":\n todos = find_todos('.', ext='py')\n show_todos(todos)\n save_csv(todos, file)\n</code></pre>\n\n<h2>Other comments:</h2>\n\n<ul>\n<li><p>use <code>for line_no, line in enumerate(input_):</code> instead of:</p>\n\n<pre><code>line_no = 0\nwith open(f, \"r\") as input_:\n for line in input_:\n line_no += 1\n</code></pre></li>\n<li><p>Regarding <code>if self.comment in line and self.td in line:</code> line: what if you have a line like this:</p>\n\n<pre><code>TODOs.append(todo) # there are no todos in this line\n</code></pre></li>\n<li><p>I am not sure about whether you need a <code>recursive</code> param at all. When would you need to use <code>recursive=False</code>?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:46:16.570", "Id": "435105", "Score": "0", "body": "Method names have always been a weak point. You have a point about the classes. I work a lot with OOP in guis and DB's so its my first thought.. Class... I think methods can be good in this case.. Enumerate is one i should have seen! Kudos on the TODOs.append(todo). I put in a check `if todo_index > comment_index:` to combat this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T06:47:16.237", "Id": "435106", "Score": "0", "body": "Recursive is simple.. If you have a large codebase but only want the TODOS from say 1 module, don't use recursion. If you want to assess ALL modules, or even an entire Hard Drive, then use recursion, but it will take longer.." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T23:24:02.200", "Id": "224313", "ParentId": "224288", "Score": "1" } } ]
{ "AcceptedAnswerId": "224313", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T14:49:15.530", "Id": "224288", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Find Todos by Line Number (or any other reference) in Python" }
224288
<p>We're having a small debate in work about the following piece of code:</p> <pre><code>private string GetNextFileName(string fileName) { int index = 1; string nextName = $"{fileName}_{index}.png"; while (File.Exists(nextName)) { nextName = $"{fileName}_{++index}.png"; } return nextName; } </code></pre> <p>Is there anything particularly dangerous about this piece of code? It sort of feels dodgy having the condition in a while loop.</p> <p>Would it be better to use a for-loop with a breakout if the number gets too high?</p> <p>e.g.</p> <pre><code>private string GetNextFileName(string fileName) { int i = 1; string nextName = $"{fileName}_{i}.png"; for (; i &lt; 100; ++i) { if (!File.Exists(nextName)) { return nextName; } nextName = $"{fileName}_{i}.png"; } throw new ApplicationException("Unable to get free filename"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:01:51.877", "Id": "435013", "Score": "0", "body": "It is not thread-safe and is I/O-intensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:06:49.083", "Id": "435014", "Score": "0", "body": "Why downvote - is the question not being asked correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:07:27.663", "Id": "435015", "Score": "1", "body": "Loop conditions should reveal the intent of the loop when possible. Use the condition from the first example and throw on exception. Whether it's best to limit the number of files is a separate question, not some universal moral constant, and it totally depends on what the filename is used for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T16:09:46.537", "Id": "435023", "Score": "1", "body": "This question lacks concrete context. For instance, you are not showing us when you call this code. This method always assumes an _index_ has to be added, which infers that you have checked _File.Exists_ already before the method call." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T16:30:13.727", "Id": "435198", "Score": "1", "body": "Why don't you tell us the use case for this? Do you require this template of file names or are temporary or random file names also ok?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T10:48:48.223", "Id": "435674", "Score": "1", "body": "I also downvoted because it's not clear what happens when some file is deleted. You would then get the _wrong_ filename from somewhere in the middle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T07:28:09.973", "Id": "435769", "Score": "0", "body": "Indeed, knowing what the directories look like is important: some answers assume that the indexes will be sequential, others do not. Only 200_success' answer appears to have the same behaviour (up to 100 files) as yours does." } ]
[ { "body": "<p>It appears that the string you pass into the method is a type of picture not really a filename, since the filename needs an index attached.</p>\n\n<p>I'm not a big fan of either approach. I think using <code>GetFiles</code> and using the <code>Length</code> property is easier to see what's happening.</p>\n\n<p>Something like this should work:</p>\n\n<pre><code>using System;\nusing System.IO;\n\n private static string GetNextFilename(string picName)\n {\n string fileName = $\"{picName}_{1}.png\";\n DirectoryInfo dir; \n if(File.Exists(fileName))\n {\n FileInfo info = new FileInfo(fileName);\n dir = info.Directory; \n }\n else\n {\n return fileName;\n } \n int nextIndex = dir.GetFiles($\"{picName}*.png\").Length + 1;\n return $\"{picName}_{nextIndex}.png\";\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T20:16:33.793", "Id": "224305", "ParentId": "224289", "Score": "1" } }, { "body": "<p>Stylistically, the <code>for</code> loop is more readable. As a general rule, if you start the loop at 1, then I would prefer the termination condition to use <code>&lt;=</code>; if you start counting from 0, then <code>&lt;</code> would be better.</p>\n\n<hr>\n\n<p>The design of this function is conceptually flawed. It will return an unused filename, but presumably you will eventually want to create a file with the name. However, it is possible that someone else will have created a file with the same name, creating a conflict. This <strong>possible race condition</strong> means that you can never be certain that the filename returned by this function is actually unused.</p>\n\n<p>The way to make that guarantee is to <em>actually create the file</em>, such that you effectively grab a reservation on that name. You can do that by calling <code><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.file.open\" rel=\"noreferrer\">File.Open</a>(<em>path</em>, <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.filemode\" rel=\"noreferrer\">FileMode.CreateNew</a>)</code>. The caller would have to delete the file if it doesn't want it.</p>\n\n<pre><code>private static string CreateNextAvailableFile(string fileNamePrefix)\n{\n string name;\n for (int i = 1; i &lt;= 99; ++i)\n {\n try\n {\n FileStream fs = File.Open(name = $\"{fileNamePrefix}_{i}.png\", FileMode.CreateNew);\n fs.Close();\n return name;\n }\n catch (IOException e)\n {\n // Did File.Open() fail due to name collision or another\n // reason? Unfortunately, no specific \"FileAlreadyExists\"\n // exception exists. This is a heuristic, and can be\n // fooled by a race condition where the file was deleted\n // just now by someone else.\n if (!File.Exists(name)) throw;\n }\n }\n\n throw new ApplicationException(\"Unable to get free filename\");\n}\n</code></pre>\n\n<p>As the comment notes, .NET unfortunately has no way to tell whether the <code>IOException</code> was due to a filename collision or something else. The code above is therefore also vulnerable to a race condition, but it's better than your race condition, because:</p>\n\n<ul>\n<li>This race condition is only triggered when there is an underlying I/O problem (such as insufficient permissions to create a file, or a read-only filesystem), <em>and</em> the file in question is deleted during the split-second between the <code>File.Open()</code> call and the exception handler.</li>\n<li>This code fails in a safer way: if the race condition is triggered, it will throw an <code>IOException</code>. (Arguably, such an <code>IOException</code> would happen anyway, later on.) However, it's harder to tell what might be the consequences of your race condition: it might fail to detect a collision, and lead to data being overwritten.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T04:38:57.937", "Id": "435090", "Score": "2", "body": "There are some slight improvements to make: (1) _FileStream_ comes with a _Dispose_ that does more than just _Close_, so use a _using_ block for the stream: https://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs (2) you don't need to declare the exception _e_ since you don't handle it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T10:22:52.050", "Id": "435668", "Score": "0", "body": "_Stylistically, the for loop is more readable._ - Is this `for (; i < 100; ++i)` really more readable than this `while (File.Exists(nextName))`? I doubt." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T10:38:41.243", "Id": "435671", "Score": "1", "body": "I find this exception-driven brute-foce solution is terrible. Having several thousand files would make this the bottleneck #1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T07:34:41.967", "Id": "435770", "Score": "0", "body": "This code will throw `UnauthorizedAccessException` if `$\"{fileNamePrefix}_{i}.png\"` exist as a directory." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T21:16:16.640", "Id": "224308", "ParentId": "224289", "Score": "5" } }, { "body": "<p>Personally I'm a fan of using Regex when it comes to parsing strings for the simplicity it provides. This way we can check for the next available file name without relying on loops. Only problem I see with this method is if the directory contains an absurd amount of files.</p>\n\n<pre><code>//the following regex pattern divides the filename into 3 groups:\n// [1] directory + filename before the last underscore\n// [2] the index or numeric part before the last dot\n// [3] the extension of the file\n\nprivate static Regex fileNamePattern = new Regex(\"(.*)_([0-9]*).(.*)\"); \n\n//this of course takes for granted that the initial file name is correctly generated\n\nprivate static void GetNextFileName(string fileName)\n{\n string newFileName = fileName;\n\n if (File.Exists(newFileName))\n {\n var existingFileNames = Directory.GetFiles(Path.GetDirectoryName(fileName)).Where(x =&gt; fileNamePattern.IsMatch(x));\n string existingMaxIndex = existingFileNames.Max(x =&gt; fileNamePattern.Match(x).Groups[2].Value);\n int newMaxIndex = int.Parse(existingMaxIndex) + 1;\n newFileName = fileNamePattern.Replace(newFileName, m =&gt; $\"{m.Groups[1].Value}_{newMaxIndex}.{m.Groups[3].Value}\");\n }\n\n //here you should proceed to create the file instead of returning it, as @200_success explained\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T10:39:58.450", "Id": "435673", "Score": "1", "body": "This could be cleaner but in general this is the coolest solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T13:49:10.233", "Id": "224343", "ParentId": "224289", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T14:53:43.993", "Id": "224289", "Score": "2", "Tags": [ "c#", "comparative-review", "file" ], "Title": "Finding the next available filename" }
224289
<p>This program opens a file and prints the text out to the terminal 1 character at a time and at a predetermined speed using <code>time.sleep()</code></p> <p>Simple and maybe, if you think like me, pretty cool..</p> <p><a href="https://github.com/johnashu/one-line-print" rel="nofollow noreferrer">GitHub</a></p> <pre><code>from time import sleep import sys BLINK = 0.2 chars_in_line = 50 def open_file(fn): with open(fn, "r") as f: for line in f: if line: yield line def type_out_text_to_line(text, end="", sep="", line_chars=None, blink=0.2): if not text: return "" c = line_chars for i, j in enumerate(text): sys.stdout.flush() sleep(blink) print(j, end=end, sep=sep) if line_chars: if i + 1 == c: print() c += line_chars return "" print("\n\tSTART PRINTING\n") for text in open_file('example.txt'): if len(text) &gt; 1: print(type_out_text_to_line(text, line_chars=chars_in_line, blink=BLINK, sep="")) print("\n\tEND PRINTING\n") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T16:02:08.397", "Id": "435021", "Score": "1", "body": "Can you add the example file you are running?" } ]
[ { "body": "<p>I would recommend just using the built in functionality of <code>print</code> to do the flushing. Though I am an advocate for breaking things out into classes and functions, you should use built in functionality when you can. </p>\n\n<p>Making code complex for no reason results in two things: </p>\n\n<p>1) More bugs.<br>\n2) More programmers who want to wring your neck down the road because they have to maintain or fix your software.</p>\n\n<p>So you can simplify your code like this:</p>\n\n<pre><code>from time import sleep\n\nBLINK = 0.2\n\nprint(\"\\n\\tSTART PRINTING\\n\")\n\nwith open('example.txt') as f:\n for line in f:\n for char in line:\n print(char, flush=True, end='')\n sleep(BLINK)\n\nprint(\"\\n\\tEND PRINTING\\n\")\n</code></pre>\n\n<p>If you want to make this into a function (to make it easier to import/export) then I would do following:</p>\n\n<pre><code>from time import sleep\n\ndef time_print_file(filename, print_rate, **print_kwargs):\n \"\"\"\n INPUT:\n filename: The path to the file to be printing\n print_rate: The delay used to print each character\n print_kwargs: keyword arguments accepted by pythons\n print statement. (Except `end` and `flush`)\n \"\"\"\n print_kwargs.pop('flush', None) # We don't allow the flush print-keyword\n print_kwargs.pop('end', None) # We don't allow the end print-keyword\n with open(filename) as f:\n for line in f:\n for char in line:\n print(char, flush=True, end='', **print_kwargs)\n sleep(print_rate)\n\n\nif __name__ == '__main__':\n print(\"\\n\\tSTART PRINTING\\n\")\n time_print_file(filename='example.txt', print_rate=0.2)\n print(\"\\n\\tEND PRINTING\\n\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T16:29:59.150", "Id": "435025", "Score": "2", "body": "Reading the whole file into memory with `f.readlines` might not be the best idea (although letting the program type out a file larger than memory is probably not going to happen). Instead just iterate over the file with `for line in f`. It also includes the newline characters, just like `f.readlines`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T16:05:09.523", "Id": "224297", "ParentId": "224293", "Score": "4" } } ]
{ "AcceptedAnswerId": "224297", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:45:45.687", "Id": "224293", "Score": "3", "Tags": [ "python", "python-3.x", "console", "io", "animation" ], "Title": "Print file out 1 character at a time in the terminal - Python" }
224293
<p>This code computes the Minimum Spanning Tree of a given graph using Kruskals Algorithm.</p> <p>It works successfully and I have provided test cases within the code.</p> <p>I would like feedback on code efficiency (Choice of ds and functions/function size) and anything else to improve the code (Aside from pep 8 compliance, that is something I will be working to fix soon)</p> <p>Thank you</p> <pre><code>class Graph: def __init__(self): self.graph = [] self.edges = [] self.parents = {} self.size = {} def addnode(self, key1, key2, edge=0): if key1 not in self.graph: self.graph.append(key1) if key2 not in self.graph: self.graph.append(key2) self.edges.append([key1, key2, edge]) def getparent(self, vertex): while self.parents[vertex] != -1: vertex = self.parents[vertex] return vertex def union(self, vertex, neighbour): x_par = self.getparent(vertex) y_par = self.getparent(neighbour) if self.size[x_par] &lt;= self.size[y_par]: self.parents[x_par] = y_par self.size[y_par] += self.size[x_par] else: self.parents[y_par] = x_par self.size[x_par] += self.size[y_par] def kruskal(self): mst = [] total = 0 for key in self.graph: self.parents[key] = -1 self.size[key] = 1 self.edges.sort(key = lambda x:x[2]) for edge in self.edges: vertex, neighbour, weight_edge = edge x_par = self.getparent(vertex) y_par = self.getparent(neighbour) if x_par != y_par: self.union(x_par, y_par) mst.append(edge) total += weight_edge print(mst) print('mst of weight:', total) if __name__ == '__main__': g = Graph() g.addnode(0, 1, 10) g.addnode(0, 2, 6) g.addnode(0, 3, 5) g.addnode(1, 3, 15) g.addnode(2, 3, 4) g.kruskal() </code></pre>
[]
[ { "body": "<h2>Performance</h2>\n\n<p>The main cost of your implementation is in two areas, the sorting and the set memebership test.</p>\n\n<p>When you do check for parents, it is generally advisable to update each of the parent of each of the ones you looked at, such that they would only be one step away from their parent the next time. Here is how it could look:</p>\n\n<pre><code> def shortcut(self, vertex, parent):\n while self.parents[vertex] != -1:\n next = self.parents[vertex]\n self.parents[vertex] = parent\n vertex = next\n\n def getparent(self, vertex):\n start = vertex\n while self.parents[vertex] != -1:\n vertex = self.parents[vertex]\n\n self.shortcut(start, vertex)\n return vertex\n</code></pre>\n\n<p>It can be shown that this assymtotically reduces the cost of the set membership test in this kind of union based data-structure.</p>\n\n<p>You can also cut these comparisons short when you have found the full minimal spanning tree, which would save you all the extra parent lookups for all the edges following in the sorted sequence. You can do this by checking whether you are done after adding an edge with <code>len(mst) == len(self.graph) - 1</code>, and then do a break or return the result, so the code (the loop in the kruskal function) would look like this:</p>\n\n<pre><code> for edge in self.edges:\n vertex, neighbour, weight_edge = edge\n x_par = self.getparent(vertex)\n y_par = self.getparent(neighbour)\n if x_par != y_par:\n self.union(x_par, y_par)\n mst.append(edge)\n total += weight_edge\n if len(mst) == len(self.graph) - 1:\n break\n</code></pre>\n\n<p>For sorting you have two problems:</p>\n\n<ol>\n<li>You specify a key function manually, which means the algorithm will have to call that key function.</li>\n<li>You sort more of the problem than you really need to.</li>\n</ol>\n\n<p>The first part comes from that <code>sort</code> may be implemented in a faster language (it looks to be so in my installation), which means that it generally runs faster if it never have to enter python code, which the manual key function breaks. If you however changes the order of attributes in how you store your edges, such that the weight is first, then you can use the default comparison, which will do lexiographic ordering, which in turn means you get it sorted primarily on the edge weights.</p>\n\n<p>For the second part, the main problem is that you only need to search until you get the <code>n-1</code> edges needed to finish the minimum spanning tree, so you only need this amount sorted. It would therefore be advisable to use a sorting scheme, such as heapsort, where you can stop half-way through and only need to effectively pay in performance for the amount you needed. The downside is that the <code>heapq</code> python module looks to be mainly implemented in python, which means its actual performance might be slower unless you really only need a very small subset (this would typically depend on the graph).</p>\n\n<h2>Convenience</h2>\n\n<p>There are a few areas in the code, which with some improvement would be more convinient/better future-proofed.</p>\n\n<p>The main one here is the need for a simpler way to add several edges to a graph, or even construct a graph with edges already in it. Here is how I would do it:</p>\n\n<pre><code> def __init__(self, edges=None):\n\n self.graph = []\n self.edges = []\n self.parents = {}\n self.size = {}\n self.add_edges(edges)\n\n def add_edges(self, edges=None):\n if edges is not None:\n for edge in edges:\n self.add_node(*edge)\n</code></pre>\n\n<p>The construction of your graph would then be this simple:</p>\n\n<pre><code> g = Graph([\n (0, 1, 10) \n (0, 2, 6) \n (0, 3, 5) \n (1, 3, 15) \n (2, 3, 4) ])\n</code></pre>\n\n<p>In the union fuction, we could parameterize the if statement as follows:</p>\n\n<pre><code> child, parent = (x_par, y_par) if self.size[x_par] &lt;= self.size[y_par] else (y_par, x_par)\n self.parents[child] = parent \n self.size[parent] += self.size[child]\n</code></pre>\n\n<p>This would also seperate the orthogonal parts of the logic, which would make it easier to maintain.</p>\n\n<p>Lastly it would be a good idea to have the <code>kruskal</code> method just return <code>mts, total</code> and then print outside, as this would allow actual use of the class in code outside of problems where this is the final solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T22:38:03.477", "Id": "224311", "ParentId": "224294", "Score": "1" } } ]
{ "AcceptedAnswerId": "224311", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:53:22.023", "Id": "224294", "Score": "3", "Tags": [ "python", "python-3.x", "graph", "union-find" ], "Title": "Kruskals MST Algorithm" }
224294
<p>As a practice exercise, I implemented a cellular automaton (Conway's Game of Life) in python (with help from <a href="https://medium.com/@martin.robertandrew/conways-game-of-life-in-python-2900a6dcdc97" rel="nofollow noreferrer">this</a> tutorial).</p> <p>I am very curious, if this code follows common best practices and I am wondering how to improve the code in terms of performance and readability. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import animation arr = [] size_grid_x = 6 size_grid_y = 6 universe = np.zeros((size_grid_x, size_grid_y)) new_universe = np.copy(universe) beacon = [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]] universe[1:5, 1:5] = beacon def update(universe, x, y): X = size_grid_x Y = size_grid_y neighbors = lambda x, y: [(x2, y2) for x2 in range(x - 1, x + 2) for y2 in range(y - 1, y + 2) if (-1 &lt; x &lt;= X and -1 &lt; y &lt;= Y and (x != x2 or y != y2) and (0 &lt;= x2 &lt;= X) and (0 &lt;= y2 &lt;= Y))] num_neighbours = sum([universe[i] for i in neighbors(x, y)]) new_val = universe[x, y] if universe[x, y] and not 2 &lt;= num_neighbours &lt;= 3: new_val = 0 elif num_neighbours == 3: new_val = 1 return new_val for i in range(100): for x in range(5): for y in range(5): new_universe[x, y] = update(universe, x, y) universe[:, :] = new_universe[:, :] arr.append(np.copy(universe)) fig = plt.figure() i = 0 im = plt.imshow(arr[0], animated=True) def update_figure(*args): global i if i &lt; 99: i += 1 else: i = 0 im.set_array(arr[i]) return im, ani = animation.FuncAnimation(fig, update_figure, blit=True) plt.show() </code></pre>
[]
[ { "body": "<p>I'm on my phone, so I can't write anything too elaborate. I'll just make some notes:</p>\n\n<hr>\n\n<p>I don't think you're making good use of functions here. For the most part, you have everything tucked inside of <code>update</code>. I think that function is far too large, and doing too much explicitly. I would, for example, create a function called <code>should_live</code> or something similar that is passed the cell's current state and number of neighbors, and returns if the cell should be alive the next tick or not.</p>\n\n<p>You do break some of that functionality off into a local function <code>neighbors</code>, but I don't think it's ideal the way you've done it. I would make that an external function, and I would call it <code>n_neighbors</code> or <code>count_neighbors</code> or something similar to make it clearer that it's a function that counts neighbors, not a collection of neighbors. You could also clean up that long list comprehension guard by creating a <code>is_inbounds</code> function that checks if a point is i bounds or not. </p>\n\n<p>I'd also rename <code>update</code>, as is isn't actually updating anything. It's gathering information then returning a decision. </p>\n\n<hr>\n\n<p>I would not have code top-level like you have it here. Having the code run just because you loaded it will get annoying if you ever change your workflow to involve a REPL. I would tuck the routine into a <code>main</code> function, then maybe call that function from a <code>if __name__ == \"__main__\"</code> block.</p>\n\n<hr>\n\n<p>In short, I'd break your code up more and be more cautious when it comes to naming. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T18:51:23.963", "Id": "224301", "ParentId": "224295", "Score": "2" } }, { "body": "<h3>lambda</h3>\n\n<p>If you want to give the function a name, then it shouldn't be a lambda. They are generally good for very short functions to pass as an argument to another function. For example, sorted(list_of_tuples, key=lambda t:t[1]) to sort on based on the second element of a tuple.</p>\n\n<h3>comprehensions</h3>\n\n<p>Long multi-line comprehensions can be hard to read. In 6 months will you remember why the range is (x-1, x+2) and what all the inequalities are checking. For things like this, I find something like this more readable:</p>\n\n<pre><code>def count_neighbors(x, y):\n '''\n Counts the number of living cells in the neighborhood of (x,y)\n '''\n xy = [(x-1, y+1), ( x, y+1), (x+1, y+1),\n (x-1, y ), (x+1, y+0),\n (x-1, y-1), ( x, y-1), (x-1, y+1)]\n\n return sum(universe(nx, ny) for nx,ny in xy if 0&lt;=nx&lt;size_grid_x and 0&lt;=ny&lt;size_grid_y)\n</code></pre>\n\n<h3>sum() takes an iterable</h3>\n\n<p>So you don't need to make a list first. Just pass in the generator, a la:</p>\n\n<pre><code>num_neighbours = sum(universe[i] for i in neighbors(x, y))\n</code></pre>\n\n<h3>logic</h3>\n\n<p>I took awhile to understand the logic for setting <code>new_val</code>. Add some comments to explain the logic. Maybe rearrange it to make it easier to understand when you look at it in a year:</p>\n\n<pre><code>if num_neighbors == 2:\n new_val = universe[x,y] # no change\n\nelif num_neighbors == 3:\n new_val = 1 # birth (or no change if already a 1)\n\nelse:\n new_val = 0 # death \n</code></pre>\n\n<h3>numpy and scipy</h3>\n\n<p>These libraries are full of functions for operating on arrays. You could write this using np.where and scipy.ndimage.convolve like so:</p>\n\n<pre><code>import numpy as np\nfrom scipy.ndimage import convolve\n\n... same setup for universe, beacon, etc...\n\nkernel = np.array([[1,1,1],\n [1,0,1],\n [1,1,1]])\n\nfor i in range(100):\n neighbors = convolve(universe, kernel, mode='constant')\n\n alive = np.logical_or(np.logical_and(universe==1, neighbors==2), neighbors==3)\n\n universe = np.where(alive, 1, 0)\n\n arr.append(np.copy(universe))\n\n... same plotting code ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T07:51:54.350", "Id": "224389", "ParentId": "224295", "Score": "2" } } ]
{ "AcceptedAnswerId": "224389", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T15:56:56.207", "Id": "224295", "Score": "2", "Tags": [ "python", "game-of-life", "cellular-automata" ], "Title": "Cellular automaton (Conway's Game of Life) in python" }
224295
<h1>Issue</h1> <p>Our API returns two formats JSON and this SQL table format. I'm not sure what it is truly called so I'll give a few examples below. Like all API responses, it can be a list or a single response but it is always in the same format. I'm creating a utility function for this SQL table format to be converted into a JSON object so the front-end only needs to be concerned with a single format, JSON.</p> <h1>Problem</h1> <p>Convert SQL Table Response to JSON</p> <h1>Examples of the SQL table format</h1> <p>Here is the SQL table format as a success message.</p> <pre><code>{ "COLUMNS":["SUCCESS","RETMESSAGE"], "DATA":[[true,"Order Approved"]] } </code></pre> <p>Here is an example of a list</p> <pre><code>{ "COLUMNS":["PRODUCTID","PRODUCTNAME"], "DATA":[[1001,"Product1"],[1002,"Product2"],[1003,"Product3"]] } </code></pre> <h1>Current Solution</h1> <p>The current solution is the following. It works well but I keep coming back to it and thinking there is a more elegant way of writing this.</p> <pre class="lang-js prettyprint-override"><code>const request = { "COLUMNS":["SUCCESS","RETMESSAGE"], "DATA":[[true,"Order Approved"]] }; const desiredFormat = [{ "SUCCESS":true, "RETMESSAGE":"Order Approved" }]; function tableToJSON (dataset) { const data = dataset.DATA; const columns = dataset.COLUMNS; const jsonData = []; data.forEach( (row) =&gt; { const json = {}; row.forEach( (item, index) =&gt; { json[columns[index]] = item; }); jsonData.push(json); }); return jsonData; } const formattedResponse = tableToJSON(request); console.log(JSON.stringify(formattedResponse) === JSON.stringify(desiredFormat)) // Outputs: True </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T19:32:28.227", "Id": "435044", "Score": "1", "body": "Is that better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T19:34:27.993", "Id": "435045", "Score": "0", "body": "Ah you want to _pivot_ data. Now it's clear to me." } ]
[ { "body": "<p>Whenever you have code that sets up an array, then has a loop to push items into that array, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array.map()</code></a> could be used to condense that code. For example, these lines:</p>\n\n<blockquote>\n<pre><code>const jsonData = [];\ndata.forEach( (row) =&gt; {\n const json = {};\n row.forEach( (item, index) =&gt; {\n json[columns[index]] = item;\n });\n jsonData.push(json);\n});\nreturn jsonData;\n</code></pre>\n</blockquote>\n\n<p>Could be simplified to this:</p>\n\n<pre><code>return data.map( (row) =&gt; {\n const json = {};\n row.forEach( (item, index) =&gt; {\n json[columns[index]] = item;\n });\n return json;\n});\n</code></pre>\n\n<p>You could optionally simplify the inner loop using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\"><code>Array.reduce()</code></a></p>\n\n<pre><code>return data.map( (row) =&gt; {\n return row.reduce( (json, item, index) =&gt; {\n json[columns[index]] = item;\n return json;\n }, {});\n});\n</code></pre>\n\n<p>There are some good exercises in <a href=\"http://reactivex.io/learnrx/\" rel=\"nofollow noreferrer\"><em>Functional Programming in Javascript</em></a> where you practice implementing some of those methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T20:57:21.230", "Id": "224307", "ParentId": "224302", "Score": "3" } } ]
{ "AcceptedAnswerId": "224307", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T19:05:05.287", "Id": "224302", "Score": "4", "Tags": [ "javascript", "json", "formatting", "ecmascript-6" ], "Title": "Pivotting SQL Table Response to JSON in JavaScript" }
224302
<p>As I explain in my <a href="https://benknoble.github.io/blog/2019/07/12/plink-rant/" rel="nofollow noreferrer">rant</a>, I have been searching for a replacement to hand-crafted POSIX-<code>make</code>-compatible makefiles to manage my dotfiles (which use symlinks). I decided the simplest thing to do would be to roll my own.</p> <p>Requirements:</p> <ul> <li>written in a language likely to be immediately available on major platforms (I have chosen Perl)</li> <li>no other external dependencies (installation for dotfiles should be a clone-and-run process)</li> <li>can live next to/as a submodule of a dotfiles repository</li> </ul> <p>For this I developed <a href="https://github.com/benknoble/plink" rel="nofollow noreferrer">Plink</a>. I will quote the specification from the README, and omit the same from the POD in my Perl code. Full details at the link above, including test code.</p> <h1>DESCRIPTION</h1> <p>The <strong>Plink</strong> module provides an implementation of the Plink language, a DSL built to describe dotfiles via symlinks. The language is a strict superset of make(1); implementations produce (POSIX) makefiles for use. It is important to note that Plink only guarantees that generated code is POSIX-compatible. User-written code may use GNU make or other non-portable features. What follows is the canonical specification of the Plink language.</p> <h2>Plink Specification</h2> <p>Plink is superset of POSIX make. It defines four (4) new syntaxes with semantic meaning.</p> <p>Plink also defines a header and footer.</p> <p>A conforming implementation transforms the input file (or STDIN) as specified by the syntaxes. All lines not participating in one of these syntaxes, in addition to <code>#</code> comments, are copied verbatim (this includes blank lines). The output is written to a file named by the environment variable <code>PLINK_OUTPUT</code>, or <code>Makefile</code> if unset.</p> <p>See <code>t/test.plink</code> for an example Plink file, and <code>t/expected.mk</code> for its output.</p> <h3>Square Brackets <code>[ prerequisites ]</code></h3> <p>Any line like</p> <pre><code>target names [ prerequisites ] ... </code></pre> <p>will be transformed to</p> <pre><code>target names: $MAKEFILE prerequisites ... </code></pre> <p><code>$MAKEFILE</code> denotes the name of the generated filename. The spaces around <code>[]</code> are not <em>required</em>, but often recommended. <code>...</code> may make use of any the bang-syntaxes.</p> <h3>Bang and Double-bang <code>!</code> <code>!!</code></h3> <p>Lines like</p> <pre><code>target ! commands </code></pre> <p>will be transformed to</p> <pre><code>target: &lt;TAB&gt;commands </code></pre> <p>The list <code>commands</code> lasts to the end of the line. <code>commands</code> will be indented by one tab, as make requires.</p> <p>Similarly, lines like</p> <pre><code>target !! commands on more lines !! </code></pre> <p>become</p> <pre><code>target: &lt;TAB&gt;commands &lt;TAB&gt;on more lines </code></pre> <p>The list <code>commands</code> lasts until the line containing <em>exactly</em> <code>!!</code>. Commands will be tab-indented.</p> <h3>Symlink (Fat-arrow) <code>&lt;=</code></h3> <p>The meat of the DSL. Lines like</p> <pre><code>link_in_home &lt;= dotfile_under_$(LINKS) </code></pre> <p>Become part of a mapping. The output creates dependencies of the form</p> <pre><code>$(HOME)/link_in_home: $(LINKS)dotfile_under_$(LINKS) </code></pre> <p>for each fat-arrow, and also gives each the recipe</p> <pre><code>if test -e $@ ; then rm -rf $@ ; fi ln -s <span class="math-container">$$(realpath $?) $@ @echo $@ '-&gt;' $$</span>(realpath $?) </code></pre> <p>which creates the link. Finally, a target named <code>symlink</code> is provided which depends on all the <code>link_in_home</code>s provided: it is considered the public API for any make target that wishes to depend on symlink-generation.</p> <p>Dotfiles are files under the make macro <code>$(LINKS)</code>. Due to the generation rule, if <code>$(LINKS)</code> is not set, the current directory is used. This can be useful to put all dotfiles under a directory named, e.g., <code>dots</code>. Then you want to include a line in your Plink file like</p> <pre><code>LINKS = dots/ </code></pre> <p>(note the trailing slash).</p> <p>The use of the macro <code>SYMLINKS</code> is considered a Plink implementation detail and is subject to change; users who set <code>SYMLINKS</code> or depend on it's effects are invoking undefined behavior.</p> <h3>Header</h3> <p>The Plink header consists of</p> <pre><code>SHELL = /bin/sh .SUFFIXES: </code></pre> <h3>Footer</h3> <p>The Plink footer consists of the symlink target implementation and the following:</p> <pre><code>MAKEFILE: INPUT &lt;TAB&gt;$$(realpath $?) </code></pre> <p><code>MAKEFILE</code> refers to the generated output, and <code>INPUT</code> to the Plink file used as input.</p> <h1>METHODS</h1> <p><em>plink</em> <em>$infname</em>, <em>$outfname</em></p> <p>Implements the Plink specification, transforming the file named <code>infname</code> to <code>outfname</code>. Handles for STDIN and STDOUT are accepted, though STDIN has the side-effect that the Makefile rules now depend on the literal file <code>STDIN</code>. Similarly, STDOUT breaks the rule to make the generated Makefile.</p> <h1>CODE</h1> <pre class="lang-perl prettyprint-override"><code>#! /usr/bin/env perl package Plink v1.0.0; use v5.10; use strict; use warnings; use autodie; use open ':locale'; # implicit with # use v5.10; use feature 'unicode_strings'; use Exporter 'import'; our @EXPORT_OK = qw(plink); main() unless caller(0); sub trim { my $string = shift; $string =~ s/^\s+|\s+$//g; return $string; } sub process_deps { my ($line, $outfname) = @_; return $line if $line =~ /^#/; my ($target, $deps, $rest) = $line =~ m{^ (.+) # target \[(.*)\] # dependencies (.*) # anything else $}x; return $line unless $target; $target = trim $target; $rest = trim $rest; my @deps = grep(!/^\s*$/, map { trim $_ } (split /\s+/, $deps)); return "$target: $outfname @deps $rest\n"; } sub process_bang { my ($line, $outfname) = @_; $line = process_deps($line, $outfname); my ($target, $rest) = $line =~ m{^ ([^!]+) # target ! # bang ([^!]+) # rest $}x; return unless $target; $rest = trim $rest; $target = trim $target; unless ($target =~ /:/) { $target = "$target:" } return &lt;&lt;TARGET; $target \t$rest TARGET } sub print_header { my $out = shift; print $out &lt;&lt;HEADER; SHELL = /bin/sh .SUFFIXES: HEADER } sub print_footer { my ($out, $outfname, $infname) = @_; print $out &lt;&lt;FOOTER; # symlink: ensure symlinks created symlink: $outfname \$(SYMLINKS) <span class="math-container">\$(SYMLINKS): \tif test -e \$</span>@ ; then rm -rf <span class="math-container">\$@ ; fi \tln -s \$</span><span class="math-container">\$(realpath \$</span>?) <span class="math-container">\$@ \t\@echo \$</span>@ '-&gt;' <span class="math-container">\$\$</span>(realpath \$?) $outfname: $infname \t<span class="math-container">\$\$</span>(realpath \$?) FOOTER } sub process_lines { my ($in, $out, $outfname) = @_; my %links; while (my $line = &lt;$in&gt;) { next if ($line =~ m/^#!|^!!$/); # skip comments, no preprocessing if ($line =~ m/^#/) { print $out $line; } # !! elsif ($line =~ m/!!/) { (my $target = process_deps($line, $outfname)) =~ s/!!\s*$//; $target = trim $target; unless ($target =~ /:/) { $target = "$target:" } print $out "$target\n"; while (my $sub_line = &lt;$in&gt;) { last if $sub_line =~ /!!/; print $out "\t$sub_line"; } } # ! elsif ($line =~ m/!/) { print $out process_bang($line, $outfname); } # &lt;= elsif ($line =~ m/&lt;=/) { my ($link, $dotfile) = map { trim $_ } split /&lt;=/, $line; $links{$link} = $dotfile; } else { print $out process_deps($line, $outfname); } } return %links; } sub print_links { my ($out, %links) = @_; print $out "SYMLINKS = \\\n"; # print %links for my $link (sort keys %links) { print $out "\$(HOME)/$link \\\n"; } print $out "\n\n"; for my $link (sort keys %links) { print $out "<span class="math-container">\$(HOME)/$link: \$</span>(LINKS)$links{$link}\n"; } print $out "\n"; } sub get_in { my $infname = shift; if ($infname eq \*STDIN) { return ($infname, 'STDIN'); } else { open(my $in, '&lt;', $infname); return ($in, $infname); } } sub get_out { my $outfname = shift; if ($outfname eq \*STDOUT) { return ($outfname, 'STDOUT'); } else { open(my $out, '&gt;', $outfname); return ($out, $outfname); } } sub plink { my ($infname, $outfname) = @_; my ($in, $out); ($in, $infname) = get_in $infname; ($out, $outfname) = get_out $outfname; print_header $out; my %links = process_lines $in, $out, $outfname; print_links $out, %links; print_footer $out, $outfname, $infname; close($out); close($in); } sub main { my $output = $ENV{PLINK_OUTPUT} // 'Makefile'; my $input = shift @ARGV // \*STDIN; plink $input, $output; } # return true 1; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T06:43:04.437", "Id": "435274", "Score": "0", "body": "in a couple of places you check for emptiness before calling `trim` (which returns an empty value if the input is only whitespace), and then process the possibly-empty value as normal. Is that intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:34:14.330", "Id": "435317", "Score": "0", "body": "It should be—trimming `rest`, it doesnt matter if its empty (it’s an optional part, and may not be there to begin with). If youre referring to trimming `target`, i hadnt thought about that. I dont do a whole lot of error checking. Garbage in, garbage out?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T20:17:54.657", "Id": "224306", "Score": "6", "Tags": [ "beginner", "perl", "makefile" ], "Title": "DSL for Makefile generation for dotfiles using symlinks" }
224306
<p>A triangle of numbers path maximized using a greedy algorithm. It's not the most efficient way since I'm a beginner this is the best I could do. I need your feedback on how to make it better in terms of maximizing the total. It works in a way that it chooses the highest value of the adjacent numbers in the next row. No brute forcing(might take forever with big numbers). I also included a lot of functions that do different things(check the docstrings) including making triangle of size n, reading a triangle from a file ... I want your feedback on how to make things better in terms of optimization/style...</p> <pre><code>from time import time import random def make_row(n, not_str=False): """Makes a row of size n; not_str = True to return integers. Returns a list containing row, if not_str = True, a list of strings(numbers) is returned.""" temp = [] for i in range(n): if not_str: temp.append((random.randint(10, 99))) else: temp.append(str(random.randint(10, 99))) return temp def make_triangle(n, not_str=False): """Makes a triangle of numbers of size n. Returns triangle, a list of lists(rows); if not_str = True, a list of strings is returned else: integers.""" triangle = [] for i in range(1, n + 1): if not_str: temp = make_row(i, not_str) triangle.append(temp) else: temp = make_row(i) triangle.append(temp) return triangle def save_triangle(n, filename): """Assumes filename a string(name of the file) and n size of the triangle to make. Writes triangle to 'filename'.""" triangle = make_triangle(n) triangle_file = open(filename, 'a+') for row in triangle: row = ' '. join(row) triangle_file.writelines(row + '\n') triangle_file.close() def triangle_to_list(triangle, p=False): """Assumes triangle a list or a string and p = True to print triangle. Returns a list of lists(rows) containing integers.""" # If triangle is not a list(ex: a .txt file or a string, clean from new lines and spaces. if not isinstance(triangle, list): rows = triangle.split('\n') # If p, print the triangle of numbers and the size. if p: print(f'Triangle of size {len(rows)}') print() for rw in rows: print(''.join(rw)) # Clean from spaces while '' in rows: rows.remove('') row_nums = [x.split(' ') for x in rows] all_rows = [] # Convert strings to integers. for row in row_nums: temp = [] for num in row: temp.append(int(num)) all_rows.append(temp) # Returns a list of integers. return all_rows # If triangle is produced using make_triangle, it's a list. if isinstance(triangle, list): rows = triangle # If p, print the triangle of numbers and the size. if p: print(f'Triangle of size {len(rows)}') print() # Convert from integers to strings to print using .join(). list_of_strings_to_print = [] for row in rows: temp = [] for number in row: temp.append(str(number)) list_of_strings_to_print.append(temp) for row in list_of_strings_to_print: print(' '.join(row)) print() # Returns a list of integers. return rows def triangle_file_list(filename, p=False): """Assumes 'filename' contains a triangle of numbers(strings), p = True to print. Returns a list of lists(rows) containing integers.""" with open(filename, 'r') as tri: triangle_file = tri.read() # if p: print(triangle_file) raw_triangle = ''.join(triangle_file) return triangle_to_list(raw_triangle) def maximize_path(rows, p=False): """Assumes rows is a list of lists containing all rows and p = True to print path. Returns total of the maximum path. """ start = 0 total = 0 # This list contains number, index in the row (to prevent miscalculations in case of row duplicates), next number). choice_combinations = [] while start &lt; len(rows) - 1: for index, number in enumerate(rows[start]): next_max = (max(rows[start + 1][index], rows[start + 1][index + 1])) if next_max == rows[start + 1][index]: choice_combinations.append((number, index, next_max)) if next_max == rows[start + 1][index + 1]: choice_combinations.append((number, index + 1, next_max)) start += 1 final_choices = [choice_combinations[0]] for number, index, next_number in choice_combinations[1:]: # Performing 2 checks: check by number and check by index. if number == final_choices[-1][-1] and any((index == final_choices[-1][1], final_choices[-1][1] == index - 1)): final_choices.append((number, index, next_number)) for item in final_choices: total += item[0] total += final_choices[-1][-1] # If p, print the maximum path, sum. if p: print('Maximum path:') for item in final_choices: print(f'{item[0]} --&gt; ', end='') print(final_choices[-1][-1]) print() print(f'Maximum sum: {total}') return total def test_triangles(n, one=False): """Assumes n is the maximum size of the triangles to print, prints n triangles, n paths, n sums, n times. If one = True, prints only one triangle of size n.""" time_all = time() if one: time1 = time() tr = make_triangle(n, True) rws = triangle_to_list(tr, True) maximize_path(rws, True) print() print(f'Total time: {time() - time_all} seconds.') else: for i in range(2, n + 1): time1 = time() tr = make_triangle(i, True) rws = triangle_to_list(tr, True) maximize_path(rws, True) print() print(f'Time taken: {time() - time1} seconds.') print() print(f'Total time: {time() - time_all} seconds') if __name__ == '__main__': test_triangles(20, True) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T13:40:04.320", "Id": "435171", "Score": "0", "body": "A greedy algorithm will not always give you the maximum, as it can be “baited” to follow a path which will avoid larger numbers later on. An exhaustive search is \\$O(2^N)\\$, so will not work for larger triangles. The “clever” approach is only \\$O(N^2)\\$. Since this is Project Euler #18 or #67 (from your deleted question), I’ll leave the discovery of the clever algorithm to you. But as a hint, you only need to look at pairs of rows. Top down 1&2, then 2&3, then 3&4, etc.; or bottom up. Another hint: Space requirement is \\$O(N)\\$ if you do not modify the input data." } ]
[ { "body": "<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place.</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere (I'm not sure whether they work with Python 2 though) and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n\n<p>Specific suggestions:</p>\n\n<ol>\n<li>Double negatives are really hard to follow. <code>not_str=False</code> is one such instance.</li>\n<li>Boolean parameters are a code smell. Better to make two methods, optionally calling a third containing the common logic.</li>\n<li>Naming is really important for maintainability - the only difference between names and comments is that names are actual code, and can trivially be refactored by tools. Names like <code>temp</code>, <code>i</code>, <code>n</code>, <code>one</code> and <code>rws</code> make the code unnecessarily hard to follow.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:10:36.420", "Id": "435122", "Score": "0", "body": "Type hints don't work in Python 2, but since the OP uses f-strings in his code, this should not be a concern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T05:15:21.710", "Id": "224322", "ParentId": "224318", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T04:02:08.130", "Id": "224318", "Score": "0", "Tags": [ "python", "performance" ], "Title": "Triangle of numbers maximum path - Greedy algorithm Python" }
224318
<p>This is a simple utility, intended to sit on the desktop for when needed, that does the simple ROT13 encoding and decoding. </p> <p>I am used to coding in VBA, and I am interested in more .Net idiomatic coding styles.</p> <pre><code>Public Class Rot13Decoder Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles txtRotEntry.TextChanged lblResult.Text = Rot13(txtRotEntry.Text) End Sub Function Rot13(Source As String) As String Dim i As Long Dim result As String = "" For i = 0 To Source.Length - 1 Dim myChar As Char myChar = Source.Substring(i, 1) Select Case myChar ' originally used Asc(Source(i)), hence the integers below Case "a" To "m", "A" To "M" '65 To 77, 97 To 109 result &amp;= Chr(Asc(myChar) + 13) 'Chr(Asc(Source(i)) + 13) Case "n" To "z", "N" To "Z" '78 To 90, 110 To 122 result &amp;= Chr(Asc(myChar) - 13) 'Chr(Asc(Source(i)) - 13) Case Else result &amp;= myChar End Select Next Return result End Function Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. End Sub End Class </code></pre> <p><a href="https://i.stack.imgur.com/ewfFh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ewfFh.png" alt="Sample use"></a></p> <p>(The title of the form says decoder, and I am using it in the example to encode!)</p> <p>Double clicking on the form result label copies the text to the clipboard for use.</p>
[]
[ { "body": "<p>The <strong>number one problem</strong> here is that you concatenate translated letters on to your string one at a time. Since strings are immutable in .NET (and most right thinking languages), this means for the first translated character your program allocates space for a new string of length 1 (copying the previous 0-char string), for the second character it allocates space for a new string of length 2 (copying the previous 1-char string), for the third character it allocates space for a new string of length 3 (copying the previous 2-char string), and so on. The end result is that for an input <em>n</em> characters long, your program will allocate 1 + 2 + 3 + ... + n = <span class=\"math-container\">\\$O(n^2)\\$</span> space and, similarly, perform <span class=\"math-container\">\\$O(n^2)\\$</span> operations! A better structure is to use a .NET <code>StringBuilder</code> which is designed precisely for this piecemeal kind of string construction. Using a <code>StringBuilder</code> your program will allocate <span class=\"math-container\">\\$O(n)\\$</span> space and perform <span class=\"math-container\">\\$O(n)\\$</span> operations -- that's a big saving when your input is of any non-trivial length.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T05:05:29.367", "Id": "224321", "ParentId": "224319", "Score": "8" } }, { "body": "<p>One of the problems with your approach, is it's not very extensible. If you wanted different rotation factors or even to make a full Caesar Cypher, you would have to totally rewrite your code. A math based approach(<code>Mod 26</code>) can be used to allow any rotation factor, within reasonable limits.</p>\n\n<p>Another approach which will allow O(n) space is to convert the string to a char array and change the characters in place.</p>\n\n<p>It could look something like this:</p>\n\n<pre><code>Public Function ROT13(input As String) As String\n Dim chars = input.ToArray()\n Const UpperA As Integer = Asc(\"A\"c)\n Const LowerA As Integer = Asc(\"a\"c)\n For i = 0 To chars.Length - 1\n If Char.IsLetter(chars(i)) Then\n If Char.IsUpper(chars(i)) Then\n chars(i) = Chr((((Asc(chars(i)) - UpperA) + 13) Mod 26) + UpperA)\n Else\n chars(i) = Chr((((Asc(chars(i)) - LowerA) + 13) Mod 26) + LowerA)\n End If\n End If\n Next\n Return New String(chars)\nEnd Function\n</code></pre>\n\n<p>I've hard coded the rotation factor to 13. But it should be a simple matter to add a rotation parameter to the function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T20:15:43.383", "Id": "435220", "Score": "1", "body": "On the other hand, the current case-based version is quite clear in what it's doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T20:21:19.550", "Id": "435222", "Score": "0", "body": "@Mark - Clear yes. But extending it to other rotations requires a total rewrite. It's always to good practice to think in terms of being able to re-use an algorithms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T20:23:20.747", "Id": "435223", "Score": "1", "body": "It's also good practice to think in terms of maintenance, and a ROT-13 function is more likely to need maintenance than to need to be turned into a Caesar cipher." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:07:07.547", "Id": "435231", "Score": "0", "body": "Surely a single modulo expression is far more readable and maintainable than something containing branching logic!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T22:29:57.227", "Id": "435399", "Score": "0", "body": "@DanielMcLaury: Maintainable and extensible - yes; readable - not necessarily." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T05:49:59.703", "Id": "224324", "ParentId": "224319", "Score": "4" } } ]
{ "AcceptedAnswerId": "224321", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T04:04:37.937", "Id": "224319", "Score": "8", "Tags": [ ".net", "vb.net", "winforms", "caesar-cipher" ], "Title": "ROT13 encoder/decoder" }
224319
<p>as a beginner in Python I made a rock, paper, scissors game and was wondering if my code was a bit weird and could be simplified???</p> <pre><code>print("Rock, Paper, Scissors") def rps(): userInput = input("Please enter your choice: ") userInput = userInput.lower() if userInput != 'rock' and userInput != 'paper' and userInput != 'scissors': print("Your choice is invalid") import random computerChoice = '' for x in range(1): num = random.randint(1,4) if num == 1: computerChoice = 'rock' elif num == 2: computerChoice = 'paper' elif num == 4: computerChoice = 'scissors' if userInput == computerChoice: print("DRAW!") elif userInput == 'rock' and computerChoice == 'paper': print("COMPUTER WINS!") elif userInput == 'rock' and computerChoice == 'scissors': print('USER WINS!') elif userInput == 'paper' and computerChoice == 'rock': print("USER WINS!") elif userInput == 'paper' and computerChoice == 'scissors': print("COMPUTER WINS!") elif userInput == 'scissors' and computerChoice == 'rock': print("COMPUTER WINS!") elif userInput == 'scissors' and computerChoice == 'paper': print("USER WINS!") print("Would you like to try again?") try_again = input("Y/N ") try_again = try_again.lower() if try_again == "y": print("\n") rps() else: print("\n") print("Thank you for using my Rock, Paper, Scissors Program") </code></pre> <p>rps()</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T07:13:54.910", "Id": "435108", "Score": "2", "body": "Welcome to Code Review! There seems to be a major issue with the indentation of your code. Since indentation is of key importance in Python, please make sure to reformat your code. Copy it as is from your editor, select all of it and press Ctrl+k to make it a properly formatted code block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:08:56.953", "Id": "435139", "Score": "0", "body": "also check the responses on the dozens of other \"rock, paper, scissors\" questions on Code Review" } ]
[ { "body": "<p><strong>Getting the computer choice</strong></p>\n\n<p>Many things can be improved in the way the computer choice is computed:</p>\n\n<pre><code>import random\ncomputerChoice = ''\nfor x in range(1):\n num = random.randint(1,4)\nif num == 1:\n computerChoice = 'rock'\nelif num == 2:\n computerChoice = 'paper'\nelif num == 4:\n computerChoice = 'scissors'\n</code></pre>\n\n<p>Here are different steps to make things better:</p>\n\n<ul>\n<li><p>Useless range: I don't really understand the point of <code>for x in range(1)</code>.</p></li>\n<li><p>Uncaught bug: the case <code>num == 3</code> is not handled in any way. My guess is that both <code>num = random.randint(1,4)</code> and <code>elif num == 4:</code> should use a 3 rather than a 4. Also, when that probleme occurs, we end up with <code>computerChoice = ''</code> which stays undetected until the end of the program.</p></li>\n<li><p>Data structure over code: as mentionned above, there is an issue in the code mapping an integer value to a string value. You could have used a data structure to perform that operation rather than a bunch of <code>if...elif...</code> and that issue would have been detected earlier.</p></li>\n</ul>\n\n<p>This could be done with a list (and some re-indexing):</p>\n\n<pre><code>cpuChoices = ['rock', 'paper', 'scissors']\ncomputerChoice = cpuChoices[random.randint(0, 2)]\n</code></pre>\n\n<p>or a dictionnary:</p>\n\n<pre><code>cpuChoices = {1: 'rock', 2: 'paper', 3: 'scissors'}\ncomputerChoice = cpuChoices[random.randint(1, 3)]\n</code></pre>\n\n<ul>\n<li>The right tool for the right job: the Python standard library contains many nice tools and sometimes there is a perfect fit for what you are trying to achieve. This is particularly true for tasks which are common enough. In your case, there is: <a href=\"https://docs.python.org/3/library/random.html#random.choice\" rel=\"nofollow noreferrer\"><code>random.choice</code></a>.</li>\n</ul>\n\n<pre><code>cpuChoices = ['rock', 'paper', 'scissors']\ncomputerChoice = random.choice(cpuChoices)\n</code></pre>\n\n<p><em>To be continued</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:01:19.950", "Id": "435335", "Score": "0", "body": "Thanks to everyone who answered my question! It really helped expand my knowledge of Python and as this was one of my first projects and am thankful that so many answers were given. I see now that python has a lot more things for (in the future) my projects to be much, much, much more efficient! Once again thanks to everyone who answered my question!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:50:05.910", "Id": "224332", "ParentId": "224325", "Score": "1" } }, { "body": "<p>First I suggest you to split your logic into several function, it will help you to see what is essential and what you could optimize / remove. </p>\n\n<pre><code>import random\nprint(\"Rock, Paper, Scissors\")\n\nAVAILABLE_CHOICES = ['rock', 'paper', 'scissors']\n\n\ndef rps():\n try:\n userInput = getUserInput()\n computerChoice = getComputerChoise()\n result = getResult()\n tryAgainMaybe()\n except Exception as err:\n print(err)\n\n\n def getUserInput() :\n userInput = input(\"Please enter your choice: \")\n userInput = userInput.lower()\n if userInput not in AVAILABLE_CHOICES:\n raise Exception('Your choice is invalid')\n return userInput;\n\n def getComputerChoice():\n return random.choice(AVAILABLE_CHOICES);\n\n def getResult():\n result = ''\n\n if userInput == computerChoice:\n result = \"DRAW!\"\n elif userInput == 'rock' and computerChoice == 'scissors' or \\\n userInput == 'paper' and computerChoice == 'rock' or \\\n userInput == 'scissors' and computerChoice == 'paper':\n result = 'USER WINS!'\n else:\n result = \"COMPUTER WINS!\"\n return result\n\n def tryAgainMaybe():\n print(\"Would you like to try again?\")\n try_again = input(\"Y/N \")\n try_again = try_again.lower()\n if try_again == \"y\":\n print(\"\\n\")\n rps()\n else:\n print(\"\\n\")\n print(\"Thank you for using my Rock, Paper, Scissors Program\")\n</code></pre>\n\n<ol>\n<li><p>Create a list of available choices instead of writing them everywhere. it will be easier to modify and to test for your input values.</p></li>\n<li><p><code>random</code> allow you to select ramdomly a value in a list.</p></li>\n<li><p>you don't need to calculate every single possibility. You can either have a draw, a win or a loose. if you don't win or draw, you loose, no computation needed here.</p></li>\n<li><p>when you name something, try to use the same name for the same thing everything, otherwise it could be missleading. eg (userInput / computerChoice) why do we have input and choice two different words for the same kind of value ? i would choose userChoice and computerChoice instead.</p></li>\n<li><p>Your coding convention does not respect pep8 standard. You should be using snake_case.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:08:27.030", "Id": "435138", "Score": "1", "body": "Python convention (PEP-8) is `snake_case` for functions. Apart from that `rps` is a very unclear function name. Pyhton does not slow down if the variable names get longer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:10:27.673", "Id": "435140", "Score": "0", "body": "Indeed, but i followed the case convention provided in the question to not add confusion. I didn't rename the existing variable neither as it could confuse op. i'll write something about it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:07:19.253", "Id": "224333", "ParentId": "224325", "Score": "3" } }, { "body": "<p>I don't mind the other two answers but I felt like there was a better way to do this. Consider using a <a href=\"https://www.w3schools.com/python/python_dictionaries.asp\" rel=\"nofollow noreferrer\">dictionary</a> where the key will be the selection and the value will be what that selection beats.</p>\n\n<p>So the <code>dict</code> will be:</p>\n\n<pre><code>choices = {\n 'paper': 'rock', # paper beats rock\n 'rock': 'scissors', # rock beats scissors\n 'scissors': 'paper', # scissors beats paper \n}\n</code></pre>\n\n<p>This <code>dict</code> can simplify a lot of our logic.</p>\n\n<p>First lets get the user's choice. The following loop makes sure the <code>user_choice</code> is a valid choice by making sure it is in our <code>dict</code>.</p>\n\n<pre><code>user_choice = None\nwhile user_choice not in choices:\n user_choice = input(f'Please enter one of the following ({\", \".join(choices)}): ')\n</code></pre>\n\n<p><strong>Note:</strong> The <code>', '.join(iterable)</code> notation may be confusing. All we are doing is joining all the dictionary keys together to make one string using ', ' as the delimiter. This results in the following output:</p>\n\n<pre><code>Please enter one of the following (paper, rock, scissors):\n</code></pre>\n\n<p>Now lets let the computer choose an option. Similar to Josay's answer, we can use random's <code>choice</code> to do this; however, because a dictionaries keys are basically a <code>set</code> we need to first turn our keys into a list (or tuple).</p>\n\n<pre><code>from random import choice\ncomputer_choice = choice(list(choices))\n</code></pre>\n\n<p>Great, now we have both choices. Now for the winning logic, which gets simplified because of our <code>choices</code> dict:</p>\n\n<pre><code>if user_choice == computer_choice: # If both choices are the same then its a draw\n print(\"DRAW\")\nelif choices[user_choice] == computer_choice: # If the computer's choice is what the user's choice beats\n print(\"PLAYER WINS\")\nelse: # else the computer must have won\n print(\"COMPUTER WINS\")\n</code></pre>\n\n<p>Putting it all together:</p>\n\n<pre><code>from random import choice\n\nchoices = {\n 'paper': 'rock', # paper beats rock\n 'rock': 'scissors', # rock beats scissors\n 'scissors': 'paper', # scissors beats paper \n}\n\nuser_choice = None\nwhile user_choice not in choices:\n user_choice = input(f'Please enter one of the following ({\", \".join(choices)}): ')\n\ncomputer_choice = choice(list(choices))\nprint(f\"The computer chose {computer_choice}\")\n\nif user_choice == computer_choice:\n print(\"DRAW\")\nelif choices[user_choice] == computer_choice:\n print(\"PLAYER WINS\")\nelse:\n print(\"COMPUTER WINS\")\n</code></pre>\n\n<p>Final output:</p>\n\n<pre><code>Please enter one of the following (paper, rock, scissors): paper\nThe computer chose rock\nPLAYER WINS\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T13:15:46.387", "Id": "224340", "ParentId": "224325", "Score": "2" } }, { "body": "<h1>Suggestions</h1>\n\n<p>In addition to the suggestions provided by others, I observations on how to improve your code:</p>\n\n<ol>\n<li>Problems like these, where we both have some information that needs to be stored and have a bundle of functions closely related can be effectively made into a class. </li>\n<li>The problem is cyclic over the 3 options <code>rock</code>, <code>paper</code>, and <code>scissors</code>, which means we can represent them as numbers and comparisons on between them are constant over modulus 3.</li>\n</ol>\n\n<h1>Suggested Implementation</h1>\n\n<p>If we put these principles into practise we get the following form:</p>\n\n<pre><code>import random\n\nclass RPS:\n\n options = {\n 'rock':0\n 'paper':1\n 'scissors':2\n }\n responses = ('DRAW!','PLAYER WINS!','COMPUTER WINS!')\n prompt_string = 'Please enter your choise of {}: '.format(', '.join(options.keys()))\n\n def __init__(self,prompt=input, out=print):\n self.prompt = prompt\n self.out = out\n\n def __call__(self):\n self.run()\n\n def run(self):\n self.single_round()\n while self.want_more():\n self.out('\\n')\n self.single_round()\n self.out('\\n')\n self.out(\"Thank you for using my Rock, Paper, Scissors Program\")\n\n def want_more(self):\n self.out(\"Would you like to try again?\")\n return self.prompt(\"Y/N \").lower() == \"y\"\n\n def single_round(self):\n player = self.prompt_choice()\n computer = random.randint(0,2)\n self.out(self.responses[(player - computer) % 3])\n\n def prompt_choise(self):\n choise = self.prompt(prompt_string).lower()\n while choise not in options:\n self.out('Your choice is invalid')\n choise = self.prompt(prompt_string).lower()\n return self.options[choise]\n\nif __name__ == \"__main__\":\n RPS().run()\n</code></pre>\n\n<p>Note how easy we can get the proper response by simply refering to it as index, now that we can transform all the results into the same relative region (did the player have the same, go one further in the cycle or one less in the cycle, since the one just further in the cycle beats the previous one).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T14:05:57.110", "Id": "224485", "ParentId": "224325", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T07:11:51.443", "Id": "224325", "Score": "0", "Tags": [ "python", "python-3.x", "game", "rock-paper-scissors" ], "Title": "Rock, paper, scissors game in Python 3" }
224325
<p>I've been learning java for about a year in University and decided to start this Blackjack game which I can hopefully animate into a full app in the future, although I'm still working on the functionality atm.</p> <p>The game functions as it should for the most part, but I still can't figure out how can I implement the Ace having two values (1/11), right now it just has the value of 1. I was thinking of adding an - if statement in the player.getSum() where it distinguishes the ace and gives it a value of 11, but I can't get it to work properly. I can submit my test-code if that helps.</p> <p>The last question I have is about splitting. In blackjack you can split the cards in order to double your profit. Even though there is no in-game currency atm i'd like to implement that.</p> <p><strong>Suit.java</strong></p> <pre><code>public enum Suit{ Hearts(), Spades(), Diamonds(), Clubs(); } </code></pre> <p><strong>Face.java</strong></p> <pre><code>public enum Face { Ace(11), Deuce (2), Three (3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(10), Queen(10), King(10); private final int faceValue; private Face(int faceValue) { this.faceValue = faceValue; } public int getValue() { return faceValue; } public static void main(String[] args) { } } </code></pre> <p><strong>Card.java</strong></p> <pre><code>public class Card { private Suit suit; private Face face; public Card(Face cardFace, Suit cardSuit) { this.face = cardFace; this.suit = cardSuit; } public Face getFace() { return face; } public Suit getSuit() { return suit; } public String toString() { return face + " of " + suit; } } </code></pre> <p><strong>Deck.java</strong></p> <pre><code>import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class Deck { private final ArrayList&lt;Card&gt; cards; public Deck() { cards = new ArrayList&lt;Card&gt;(); for (Suit suit : Suit.values()) { for (Face face : Face.values()) { cards.add(new Card(face,suit)); } } } public void shuffle() { Collections.shuffle(cards); } public Card draw() { return cards.remove(0); } public String showDeck() { String remainingCards = ""; for (Card card : cards) { remainingCards += card.toString() + "\n"; } return remainingCards; } } </code></pre> <p><strong>Player.java</strong></p> <pre><code>import java.util.ArrayList; public class Player { private final ArrayList&lt;Card&gt; hand; private final String name; public Player(String name) { this.name = name; hand = new ArrayList&lt;&gt;(); } public String getName() { return name; } public String giveCard(Card card) { hand.add(card); return card.toString(); } public int getSum() { int numOfAces = 0; int handSum = 0; for (Card card : hand) { if (card.getFace() == Face.Ace) { numOfAces ++; } handSum += card.getFace().getValue(); } //Checking Aces if (handSum &gt; 21 &amp;&amp; numOfAces == 1) { handSum -= 10; } else if (handSum &gt; 21 &amp;&amp; numOfAces &gt; 1) { handSum -= 10 * (numOfAces - 1); } return handSum; } public String showHand(Boolean cheat) { String playerHand = ""; for (Card card : hand) { playerHand += "\n" + card.toString(); } if (cheat == true) { playerHand += "\n" + ("(" + this.getSum() + ")"); } return this.name + ": " + playerHand; } public String checkCheat(Boolean bool) { String sum = ""; if (bool == true) { sum = ("(" + this.getSum() + ")") ; } return sum; } } </code></pre> <p><strong>Blackjack.java</strong></p> <pre><code>import java.util.Scanner; public class Blackjack { public static void main(String[] args) { String nickname ; Scanner scanner = new Scanner(System.in); Boolean cheatOn; String input; Card holdCard; //Asks for name System.out.println("Please insert a nickname:"); nickname = scanner.nextLine(); //cheating? System.out.println("Would you like to display the sum? (y/n)"); input = scanner.nextLine(); System.out.println(); if (input.equals("n")) { cheatOn = false; } else {cheatOn = true ;} //Game restarts here when asked for new game do { Boolean gameOver = false; System.out.println("\n" + "A new game has begun:" + "\n"); //Initiates players and deck Player player = new Player(nickname); Player dealer = new Player("Dealer"); Deck deck = new Deck(); //Shuffle deck deck.shuffle(); //Give first cards to player and dealer player.giveCard(deck.draw()); dealer.giveCard(deck.draw()); // Will be hidden player.giveCard(deck.draw()); System.out.println(player.showHand(cheatOn)); //Checks if cheat is on and if so, prints the total value of the hand //System.out.println(player.checkCheat(cheatOn)); // As the first card the dealer receives is hidden to the the player, // I can't use the function showHand() as it will also show the hidden card. holdCard = deck.draw(); System.out.println("\n" + "Dealer: " + "\n" + "Hidden" + "\n" + dealer.giveCard(holdCard)); // Can't use checkCheat() either because it would display the value of the hidden card if (cheatOn) { System.out.println("(" + holdCard.getFace().getValue() + ")"); } //Loops the "hit" do{ //Player's turn //checks that input is either "hit" or "stand" do { System.out.println("\n" + "Would you like one more card? (hit/stand)"); input = scanner.nextLine(); }while(!input.equalsIgnoreCase("hit") &amp;&amp; !input.equalsIgnoreCase("stand")); //Player Hit if (input.equalsIgnoreCase("hit")) { player.giveCard(deck.draw()); System.out.println("\n" + player.showHand(cheatOn)); //Player Bust if (player.getSum() &gt; 21) { gameOver = true; System.out.println("\n" + "You busted! Sorry, dealer wins."); } //Player Blackjack else if (player.getSum() == 21) { System.out.println("\n" + "Blackjack! You win!"); gameOver = true; } } //Player Stand - doesn't loop else if (input.equalsIgnoreCase("stand")) { System.out.println("\n" + nickname + " stands with " + player.getSum() + "\n"); } } while (input.equalsIgnoreCase("hit") &amp;&amp; !gameOver); // loops this part as long as input is "hit" and not a game over //Dealer's turn //Prints initial dealer's hand without hidden if (gameOver == false) { System.out.println(dealer.showHand(cheatOn)); } //Dealer hits if his hand sums at least 16, if not stand while(dealer.getSum() &lt; 17 &amp;&amp; gameOver == false) { System.out.println(dealer.giveCard(deck.draw())); System.out.println(dealer.checkCheat(cheatOn)); if (dealer.getSum() == 21) { System.out.println("\n" + "Blackjack! Dealer wins this time"); gameOver = true; } else if (dealer.getSum() &gt; 21) { System.out.println("\n" + "Dealer busted! You win!"); gameOver = true; } } //Hand comparison if(!gameOver) { System.out.println("\n" + "Dealer: " + "(" + dealer.getSum() + ")"); System.out.println(nickname + " : " + "(" + player.getSum() + ")"); if (dealer.getSum() &gt; player.getSum()) { System.out.println("Sorry! Dealer wins"); } else if (dealer.getSum() &lt; player.getSum()) { System.out.println("Congratulations! You win!"); } else { System.out.println("You tied!"); } } //New Game? System.out.println(); System.out.println("Would you like to start a new game? 'y/n' :"); do { input = scanner.nextLine(); } while (!input.equalsIgnoreCase("y") &amp;&amp; !input.equalsIgnoreCase("n")); }while (input.equalsIgnoreCase("y")); //Closing scanner scanner.close(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T08:19:47.720", "Id": "435115", "Score": "0", "body": "The problem you _face_ with the Ace is because of the lack of classes. A blackjack hand has a value, regardless of the values of its underlying cards. This means the value of ace in a _hand_ depends upon the other cards of that hand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:04:13.377", "Id": "435121", "Score": "0", "body": "Hi @Nick, the class `Blackjack` is contained twice.. Looks like you want to show us the `Player` class :]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:54:05.863", "Id": "435134", "Score": "0", "body": "@Roman fixed thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:55:16.537", "Id": "435135", "Score": "0", "body": "@dfhwze The Player.java class wasn't properly copied. In this class I have all the functions for the sum of cards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:10:17.537", "Id": "435208", "Score": "0", "body": "ArrayList<Card> should be a class called Hand and getSum one of its methods." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T07:59:40.360", "Id": "224326", "Score": "1", "Tags": [ "java", "beginner", "object-oriented", "game", "playing-cards" ], "Title": "Making text based Blackjack game in Java. Can't figure out how to deal with Ace(1/11) and Splitting" }
224326
<p>In my application I have an Interface <code>IEmailNotification</code> that represents an Email and the concrete implementations have nothing to do with <code>MailMessage</code> class so to be able to send it through <code>SmtpClient</code> I used an adapter to let the communication between <code>SmtpClient</code> and <code>IEmailNotification</code> possible and the job of this <strong>adapter</strong> is simply delegate the Send call to <code>SmtpClient</code> but after converting from <code>EmailNotification</code> to <code>MailMessage</code> <strong>using an abstract Factory</strong> which in fact only copying the values from one object to the new created <code>MailMessage</code> object.</p> <p><strong>The first question is:</strong> my factory method takes a parameter of type IEmailNotification, does that violates the main Job of a Factory which is only creating objects? </p> <pre><code>public interface INotification { string To { get; } string Body { get; } } public interface IEmailNotification : INotification { string From { get; } string Subject { get; } bool IsBodyHtml { get; } string CC { get; } string BCC { get; } string ReplyToList { get; } List&lt;string&gt; AttachmentsPaths { get; } } public interface IEmailNotificationService : IService { void Send(IEmailNotification notification); } public class EmailNotificationServiceAdapter : IEmailNotificationService { private ISmtpClient _client; private MailMessageFactory _mailMessageFactory; public EmailNotificationServiceAdapter(ISmtpClient client, MailMessageFactory mailMessageFactory) { _client = client; _mailMessageFactory = mailMessageFactory; } public void Dispose() { _client.Dispose(); } public void Send(IEmailNotification notification) { **using (var mailMessage = _mailMessageFactory.CreateMailMessage(notification))** { _client.Send(mailMessage); } } } public class EmailMailMessageFactory : MailMessageFactory { public EmailMailMessageFactory(string backupBccEmail) : base(backupBccEmail) { } public override MailMessage CreateMailMessage(IEmailNotification emailNotification) { using (var mailMessage = new MailMessage()) { mailMessage.From = new MailAddress(emailNotification.From); mailMessage.To.Add(emailNotification.To); mailMessage.Subject = emailNotification.Subject; mailMessage.Body = emailNotification.Body; if (emailNotification.To.ToLower().Contains("shopfehler")) mailMessage.Bcc.Add(new MailAddress(_backupBccEmail)); if (!string.IsNullOrEmpty(emailNotification.CC)) mailMessage.CC.Add(emailNotification.CC); if (!string.IsNullOrEmpty(emailNotification.BCC)) mailMessage.Bcc.Add(emailNotification.BCC); if (!string.IsNullOrEmpty(emailNotification.ReplyToList)) mailMessage.ReplyToList.Add(emailNotification.ReplyToList); if (emailNotification.AttachmentsPaths.Count &gt; 0) { foreach (var path in emailNotification.AttachmentsPaths) { mailMessage.Attachments.Add(new Attachment(path)); } } mailMessage.IsBodyHtml = emailNotification.IsBodyHtml; return mailMessage; } } } </code></pre> <p><strong>backupBccEmail</strong> is required for manipulating the EmailNotification based on some logical conditions </p> <p><strong>The second question is:</strong> When I tried to test the logic of this method It failed because it uses an external resource at the line of adding new attachments where it cannot find the related paths on the Hard Drive, what do you people think about it? </p> <p><strong>Unit Test</strong> Note: I know that only one assert per test is recommended but for now let's keep it simple &amp; straightforward</p> <pre><code>[TestFixture] public class EmailMailMessageFactoryTests { private EmailNotification _emailNotification; [SetUp] public void SetUp() { _emailNotification = new EmailNotification("from@test.com", "to@test.com;shopfehler@mail.com", "subject", "body", true) { AttachmentsPaths = new List&lt;string&gt; { "1", "2" }, CC = "cc@test.com", BCC = "bcc@test.com" }; } [Test] public void CreateMailMessage_WhenCalled_CreatesMailMessage() { var emailMailMessageFactory = new EmailMailMessageFactory("backup@test.com"); var result = emailMailMessageFactory.CreateMailMessage(_emailNotification); Assert.That(result.From.Address, Is.EqualTo(_emailNotification.From)); Assert.That(result.To[0].Address, Is.EqualTo(_emailNotification.To)); Assert.That(result.Subject, Is.EqualTo(_emailNotification.Subject)); Assert.That(result.Body, Is.EqualTo(_emailNotification.Body)); Assert.That(result.IsBodyHtml, Is.EqualTo(_emailNotification.IsBodyHtml)); Assert.That(result.Attachments.Count, Is.EqualTo(_emailNotification.AttachmentsPaths.Count)); //this assert fails "FileNotFoundException" Assert.That(result.CC[0].Address, Is.EqualTo(_emailNotification.CC)); Assert.That(result.Bcc[0].Address, Is.EqualTo(_emailNotification.BCC)); } </code></pre> <p>}</p> <p>Maybe I'm misusing what's called Factory Pattern in my code!</p> <p>thanks in advance</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:29:51.517", "Id": "435127", "Score": "1", "body": "Please post sufficient context to help us review your code. Include code for _IEmailNotification_ and _redirectToEmail_. Also show us how you use this code through a trivial unit test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:33:08.247", "Id": "435130", "Score": "0", "body": "and be cautious calling something an abstract factory .. this is a different pattern altogether https://en.wikipedia.org/wiki/Abstract_factory_pattern" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:38:57.303", "Id": "435132", "Score": "0", "body": "@dfhwze \"be cautious calling something an abstract factory\" that's why I have doubts about it, I'll edit the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T11:05:24.660", "Id": "435152", "Score": "0", "body": "I couldn't come up with a better title, I hope this is enough!" } ]
[ { "body": "<p>You are disposing the message before it even has a chance to be used by a consumer.</p>\n\n<p>Remove the <code>using</code> block in the factory method</p>\n\n<pre><code>public override MailMessage CreateMailMessage(IEmailNotification emailNotification) {\n var mailMessage = new MailMessage();\n mailMessage.From = new MailAddress(emailNotification.From);\n mailMessage.To.Add(emailNotification.To);\n mailMessage.Subject = emailNotification.Subject;\n mailMessage.Body = emailNotification.Body;\n\n if (emailNotification.To.ToLower().Contains(\"shopfehler\"))\n mailMessage.Bcc.Add(new MailAddress(_backupBccEmail));\n\n if (!string.IsNullOrEmpty(emailNotification.CC))\n mailMessage.CC.Add(emailNotification.CC);\n\n if (!string.IsNullOrEmpty(emailNotification.BCC))\n mailMessage.Bcc.Add(emailNotification.BCC);\n\n if (!string.IsNullOrEmpty(emailNotification.ReplyToList))\n mailMessage.ReplyToList.Add(emailNotification.ReplyToList);\n\n\n if (emailNotification.AttachmentsPaths.Count &gt; 0) {\n foreach (var path in emailNotification.AttachmentsPaths) {\n mailMessage.Attachments.Add(new Attachment(path));\n }\n }\n\n mailMessage.IsBodyHtml = emailNotification.IsBodyHtml;\n\n return mailMessage; \n}\n</code></pre>\n\n<p>Leave the responsibility of disposal to the consumer of the factory.</p>\n\n<blockquote>\n <p>my factory method takes a parameter of type IEmailNotification, does that violates the main Job of a Factory which is only creating objects?</p>\n</blockquote>\n\n<p>A factory method can take explicit dependencies which it can use to perform its required functionality.</p>\n\n<blockquote>\n <p>When I tried to test the logic of this method It failed because it uses an external resource at the line of adding new attachments where it cannot find the related paths on the Hard Drive, what do you people think about it?</p>\n</blockquote>\n\n<p>Implementation concerns should be encapsulated behind abstractions that avoid tight coupling to external dependencies.</p>\n\n<p>In this case, when you were testing, the <code>Attachment</code> will try to read the file at the provided path. Since those paths may not exist when testing, you should consider refactoring the current design.</p>\n\n<p>Provide an abstraction that would allow the attachment stream to be read in isolation without any adverse behavior.</p>\n\n<pre><code>public interface IFileInfo {\n string Name { get; }\n string PhysicalPath { get; }\n Stream CreateReadStream();\n}\n</code></pre>\n\n<p>Here is a simple implementation that can be used at run-time</p>\n\n<pre><code>public class AttachmentInfo : IFileInfo {\n private readonly FileInfo innerFile;\n\n public AttachmentInfo(string path) {\n innerFile = new FileInfo(path);\n }\n\n public string Name =&gt; innerFile.Name;\n\n public string PhysicalPath =&gt; innerFile.FullName;\n\n public Stream CreateReadStream() =&gt; innerFile.OpenRead();\n}\n</code></pre>\n\n<p>The email notification can be refactored to use the abstraction for attachments</p>\n\n<pre><code>public interface IEmailNotification : INotification {\n string From { get; }\n string Subject { get; }\n bool IsBodyHtml { get; }\n string CC { get; }\n string BCC { get; }\n string ReplyToList { get; }\n List&lt;IFileInfo&gt; Attachments { get; }\n}\n</code></pre>\n\n<p>Resulting in the factory method to become</p>\n\n<pre><code>public class EmailMailMessageFactory : MailMessageFactory {\n\n public EmailMailMessageFactory(string backupBccEmail)\n : base(backupBccEmail) {\n }\n\n public override MailMessage CreateMailMessage(IEmailNotification emailNotification) {\n var mailMessage = new MailMessage {\n From = new MailAddress(emailNotification.From),\n Subject = emailNotification.Subject,\n Body = emailNotification.Body,\n IsBodyHtml = emailNotification.IsBodyHtml\n };\n mailMessage.To.Add(emailNotification.To);\n\n if (emailNotification.To.ToLower().Contains(\"shopfehler\"))\n mailMessage.Bcc.Add(new MailAddress(_backupBccEmail));\n\n if (!string.IsNullOrEmpty(emailNotification.CC))\n mailMessage.CC.Add(emailNotification.CC);\n\n if (!string.IsNullOrEmpty(emailNotification.BCC))\n mailMessage.Bcc.Add(emailNotification.BCC);\n\n if (!string.IsNullOrEmpty(emailNotification.ReplyToList))\n mailMessage.ReplyToList.Add(emailNotification.ReplyToList);\n\n if (emailNotification.Attachments.Count &gt; 0) {\n foreach (var file in emailNotification.Attachments) {\n Stream stream = file.CreateReadStream();\n string filename = file.Name;\n var attachment = new Attachment(stream, filename);\n mailMessage.Attachments.Add(attachment);\n }\n }\n return mailMessage;\n }\n}\n</code></pre>\n\n<p>When testing in isolation, a fake stream can be given to the attachment to allow the subject under test to be exercised.</p>\n\n<pre><code>[TestClass]\npublic class EmailMailMessageFactoryTests {\n [TestMethod]\n public void CreateMailMessage_WhenCalled_CreatesMailMessage() {\n //Arrange\n var stream = new MemoryStream();\n var attachments = new List&lt;IFileInfo&gt; {\n Mock.Of&lt;IFileInfo&gt;(_ =&gt; _.Name == \"1\" &amp;&amp; _.CreateReadStream() == stream)\n };\n var _emailNotification = Mock.Of&lt;IEmailNotification&gt;(_ =&gt;\n _.From == \"from@test.com\" &amp;&amp;\n _.To == \"to@test.com\" &amp;&amp;\n _.Subject == \"subject\" &amp;&amp;\n _.Body == \"body\" &amp;&amp;\n _.IsBodyHtml == true &amp;&amp;\n _.CC == \"cc@test.com\" &amp;&amp;\n _.BCC == \"bcc@test.com\" &amp;&amp;\n _.Attachments == attachments\n );\n var emailMailMessageFactory = new EmailMailMessageFactory(\"backup@test.com\");\n\n //Act\n MailMessage result = emailMailMessageFactory.CreateMailMessage(_emailNotification);\n\n //Assert\n result.From.Address.Should().BeEquivalentTo(_emailNotification.From);\n result.To[0].Address.Should().BeEquivalentTo(_emailNotification.To.Split(',')[0]);\n result.Subject.Should().BeEquivalentTo(_emailNotification.Subject);\n result.Body.Should().BeEquivalentTo(_emailNotification.Body);\n result.IsBodyHtml.Should().Be(_emailNotification.IsBodyHtml);\n\n result.Attachments.Count.Should().Be(_emailNotification.Attachments.Count);\n\n result.CC[0].Address.Should().BeEquivalentTo(_emailNotification.CC);\n result.Bcc[0].Address.Should().BeEquivalentTo(_emailNotification.BCC);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T10:12:21.280", "Id": "435300", "Score": "0", "body": "I'm really grateful for your time & effort!\nyesterday I tried a similar way to let the test pass by introducing a new interface IAttachmentProvider where a concrete implementation should define a method called GetAttachment similar to DateProvider.GetNow() and then in the test I mocked this interface and used the attachment constructor which accepts Stream & FileName and that let the test pass, so now I'm also confident that the pattern I have is a real factory.\nthanks again : )" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T02:02:59.293", "Id": "224376", "ParentId": "224330", "Score": "2" } } ]
{ "AcceptedAnswerId": "224376", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T09:06:12.803", "Id": "224330", "Score": "0", "Tags": [ "c#", "design-patterns", "unit-testing" ], "Title": "Abstracting an Email Notification Service & testing the the logic of the used abstract factory" }
224330
<p>What kind of algorithm wold solve the following problem from <a href="https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=junar" rel="nofollow noreferrer">https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=junar</a> ?</p> <blockquote> <p>I have been given a positive integer <em>n</em>. Take the <em>n</em> first positive integers 1 to <em>n</em> and permute those to some order. At the beginning you can swap the position of two numbers. Each round you go through the sequence and your aim is to collect numbers from ascending order. If the original permutation is given, determine how many ways one can select two numbers from the original sequence to be swapped if one wants to collect all number with minimum number of rounds and how many rounds it would take to collect numbers in ascending order.</p> </blockquote> <p>For example if the numbers are at the beginning 3, 1, 5, 4, 2, then you collect at the first round numbers 1 and 2, on the second round 3 and 4 and on the third round 5. So totally three rounds. But you can make a swap to the original sequence to make the following sequences:</p> <pre><code>3, 4, 5, 1, 2 3, 1, 4, 5, 2 3, 1, 2, 4, 5 </code></pre> <p>and all of them can be collected in two rounds.</p> <p>But what if n is larger than five, say about 100000? The cases are listed in <a href="https://www.ohjelmointiputka.net/tiedostot/junar.zip" rel="nofollow noreferrer">https://www.ohjelmointiputka.net/tiedostot/junar.zip</a> . Each file contains first the number of numbers and the next lines gives the numbers in some order.</p> <p>Express the solution of each file as form</p> <p>a b c</p> <p>where a is the number of numbers to be collected, b is the smallest number of rounds that takes to collect all numbers if you swap at the beginning one pair of numbers, and c denotes how many ways you can swap at the beginning two numbers so that you can collect numbers in ascending order with minimum number of rounds. So the answer to the example <code>3, 1, 5, 4, 2</code> should be <code>5 2 3</code>.</p> <p>My brute force solution is as follows. First download the file in the link above to your computer and unzip it.</p> <pre><code>def swap(A,i,j): temp = A[i] A[i] = A[j] A[j] = temp return A def is_same_round(tables,i,j): return tables.index(i) &lt; tables.index(j) def solve(file): tables = [line.strip('\n') for line in open(file)] for i in range(len(tables)): tables[i]=int(tables[i][0:len(tables[i])-1]) tables = tables[1:len(tables)] roundnumbers = [] for i in range(len(tables)): for j in range(i+1,len(tables)): rounds = 1 tables = swap(tables,i,j) for luku in range(1,len(tables)): if not is_same_round(tables,luku,luku+1): rounds += 1 roundnumbers.append(rounds) tables = swap(tables,i,j) result = "" result += str(len(tables)) result += " " result += str(min(roundnumbers)) result += " " result += str(roundnumbers.count(min(roundnumbers))) print(result) for i in range(1,10): file = 'junar'+str(i)+'.in' solve(file) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T13:26:04.553", "Id": "435170", "Score": "0", "body": "Can you swap tables once per round (at the beginning), or do you swap just once before doing any rounds?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:09:11.727", "Id": "435174", "Score": "0", "body": "I can swap only once and the swap must be done at the beginning before doing any rounds." } ]
[ { "body": "<p>Here are a few suggestions:</p>\n\n<ul>\n<li>You should get in the habit of wrapping all code that isn't contained in a function, in a main guard. This will protect the code from being run when the file is imported.</li>\n<li>Instead of code like, for example, <code>s = \"x\" + str(i) + \"x\"</code>, you should use <code>f\"\"</code>in front of your strings so you can directly include variable names into the strings, like so: <code>s = f\"x{i}x\"</code>.</li>\n<li>You should include module docstrings for all your functions. This will help any documentation identify what your functions are supposed to do.</li>\n<li>Running your code through <code>pylint</code>, here are a few warnings:\n\n<ul>\n<li>Parameters: Having one letter parameters isn't a good practice. Your code lit up when I first pasted it into my editor. Having meaningful names for your parameters also helps remind you what your function is supposed to take in.</li>\n<li>Spacing: Any spacing like <code>s=1</code> or <code>a=b+c</code> should be spread out to <code>s = 1</code> and <code>a = b + c</code>. This improves the readability of your code greatly.</li>\n</ul></li>\n</ul>\n\n<p>Below is the refactored code:</p>\n\n<pre><code>def swap(array, index_one, index_two):\n \"\"\" Swaps two values in an array, then returns the new array\"\"\"\n temp = array[index_one]\n array[index_one] = array[index_two]\n array[index_two] = temp\n return array\n\n\ndef is_same_round(tables, element_one, element_two):\n \"\"\"\n Returns True if the index of `element_one` is greater than the index\n of `element_two`\n \"\"\"\n return tables.index(element_one) &lt; tables.index(element_two)\n\ndef solve(file):\n \"\"\" Solves the file \"\"\"\n tables = [line.strip('\\n') for line in open(file)]\n for i in range(len(tables)):\n tables[i] = int(tables[i][0:len(tables[i]) - 1])\n tables = tables[1:len(tables)]\n roundnumbers = []\n for i in range(len(tables)):\n for j in range(i + 1, len(tables)):\n rounds = 1\n tables = swap(tables, i, j)\n for luku in range(1, len(tables)):\n if not is_same_round(tables, luku, luku + 1):\n rounds += 1\n roundnumbers.append(rounds)\n tables = swap(tables, i, j)\n\n result = f\"{len(tables)} {min(roundnumbers)} {roundnumbers.count(min(roundnumbers))}\"\n print(result)\n\nif __name__ == '__main__':\n for i in range(1, 10):\n file_to_solve = f'junar{i}.in'\n solve(file_to_solve)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:06:02.930", "Id": "435305", "Score": "0", "body": "Thanks for the hint. I think those are good suggestions but the real problem is that the algorithm is too slow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:19:56.127", "Id": "224372", "ParentId": "224334", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:15:11.607", "Id": "224334", "Score": "3", "Tags": [ "python", "performance", "algorithm" ], "Title": "Collecting numbers in ascending order" }
224334
<p>A new function based version of the code from <a href="https://codereview.stackexchange.com/q/224288/">this question</a> as suggested by @Hlib Babii</p> <p>I write a lot of TODO's but I never keep track of where they are.</p> <p>This program will search through files (and recursively through folders if needed) and find any TODO comments and their line number.</p> <p>The details will be printed to the screen and a file will be generated in the folder which is a csv of the files and TODO details. This means there is always a local list of TODOs in the folder and this can be stroed in git..</p> <p>You can choose different filetypes, comments and <code>TODO</code> phrases to suit , so it is not just for python.</p> <p><a href="https://github.com/johnashu/TODO-Locater" rel="nofollow noreferrer">GitHub</a></p> <pre><code>from os.path import exists import sys from glob import glob def _get_files(path, ext, recursive=False): # return a list of files return glob(path + f"/**/*{ext}", recursive=recursive) def _find_todos_in_file(fn, todo_token, comment_start): # return a list of todos in the file temp_todos = [] with open(fn, "r") as input_: for line_no, line in enumerate(input_): if comment_start in line and todo_token in line: # check to make sure that it is a true comment and not a variable name. # Avoid false positives like :: `TODOs.append(todo) # there are no todos in this line` comment_index = line.find(comment_start) todo_index = line.find(todo_token) if todo_index &gt; comment_index: temp_todos.append([fn, f"Line - {line_no+1} :: {line.strip()}"]) return temp_todos def find_todos(path, ext, todo_token = 'TODO', comment_start = '#', recursive=False): # returns a dictionary of todos todos = {} files = _get_files(path, ext,recursive=recursive) if exists(path): for x in files: try: print(f"Searching :: {x}") result = _find_todos_in_file(x, todo_token, comment_start) if result: todos[x] = result except PermissionError: pass # not a ext file (possible a folder) else: raise OSError("Path does not exist.") return todos def show_todos(todos: dict): # show todos line = "-" * 100 for k, v in todos.items(): print(f"\n{line}\n\n{k}") for x in v: print(f"&gt;&gt;&gt;{x[1]}") def save_csv(todos, ext): # save todos to a csv file import csv for k, v in todos.items(): k = k.split(ext)[0][:-1] with open(f"{k}-TODOS.csv", "w", newline="") as csvfile: w = csv.writer(csvfile, delimiter=",", quoting=csv.QUOTE_MINIMAL) for row in v: w.writerow(row) if __name__ == "__main__": todos = find_todos('.', ext='py', comment_start='#', recursive=True) show_todos(todos) save_csv(todos, 'py') </code></pre>
[]
[ { "body": "<p>Overall, pretty good job. Here are some observations:</p>\n\n<h3>_get_files</h3>\n\n<pre><code>path + f\"/**/*{ext}\"\n</code></pre>\n\n<p>Might cause trouble if <code>path</code> ends in a <code>/</code> and may be unsafe. If a user inputs an empty path, this could start at the root of the file system, and try to scan every file. Consider checking for such things and maybe using <code>os.path.normpath</code> or <code>path.resolve()</code> in <code>pathlib</code>. <code>pathlib</code> also provides <code>exists()</code> and <code>glob()</code>.</p>\n\n<h3>find_todos()</h3>\n\n<p><code>if exists(path)</code> should probably come before it is used in the call to <code>_get_files()</code>:</p>\n\n<pre><code>if exists(path):\n files = _get_files(path, ext,recursive=recursive)\n ...\n</code></pre>\n\n<p>A <code>PermissionError</code> might occur when a filed is opened, so I would tend to put the <code>try:...except PermissionError:</code> block in <code>_find_todos_in_file()</code></p>\n\n<h3>_find_todos_in_file()</h3>\n\n<p>Each line is scanned at least twice, and maybe four times:</p>\n\n<pre><code>if comment_start in line and todo_token in line: # two scans\n ....\n comment_index = line.find(comment_start) # one scan\n todo_index = line.find(todo_token) # one scan\n</code></pre>\n\n<p><code>line.find(comment_start)</code> returns -1 if the <code>comment_start</code> isn't in the line. Also, <code>find()</code> takes a parameter that says where to start searching. So the above code can be simplified and made more efficient like so:</p>\n\n<pre><code>comment_index = line.find(comment_start)\nif comment_index &gt;= 0:\n todo_index = line.find(todo_token, comment_index)\n\n if todo_index &gt;= 0:\n temp_todos.append((line_no+1, line.strip))\n</code></pre>\n\n<p>I changed what gets appended. The file name is redundant, it gets passed in as an argument, so the caller already knows what it is -- <code>find_todos()</code> uses it as a dict key. And I put line_no and the text in a tuple rather than format them into a string. Putting them in a string seems more like a job for an output function. And keeping them as a tuple is more more flexible (e.g. you want to put them in a database, or see if TODOs show up more near the end of a file, etc).</p>\n\n<h3>other stuff</h3>\n\n<p><code>find_todos()</code> and <code>find_todos_in_file()</code> basically iterate over all the lines in a bunch of files. This is what the <code>fileinput</code> library does. These two function could be combined and rewritten something like this:</p>\n\n<pre><code>def find_todos(path, ext, todo_token, comment_start, recursive):\n todos = defaultdict(list)\n\n files = glob(\"{path}/**/*{ext}\", recursive=recursive)\n\n with fileinput.input(files=files) as f:\n for line in f:\n if f.isfirstline():\n filename = f.filename()\n print(f\"Searching: {filename}\")\n\n comment_index = line.find(comment_start)\n if comment_index &gt;= 0:\n todo_index = line.find(todo_token, comment_index)\n\n if todo_index &gt;= 0:\n todos[filename].append((f.filelineno(), line.strip))\n</code></pre>\n\n<p>For a simple command line tool, the <code>argparse</code> library can help with parsing command parameters and options. For more complicated or enhanced tools try a command line tool library like <a href=\"https://click.palletsprojects.com/\" rel=\"nofollow noreferrer\">Click</a> or <a href=\"https://python-prompt-toolkit.readthedocs.io/\" rel=\"nofollow noreferrer\">Python Prompt</a>.</p>\n\n<pre><code>def make_arg_parser():\n import argparse\n\n parser = argparse.ArgumentParser(\n description='TODO finder/lister.')\n\n parser.add_argument('path',\n default='.',\n help=\"where to search for TODO's\")\n parser.add_argument('ext',\n default='py',\n help=\"kind of files to search\")\n parser.add_argument('comment',\n default='#',\n help=\"line comment marker\")\n parser.add_argument('todo',\n default='TODO',\n help=\"text to mark TODO items\")\n parser.add_argument('--norecurse',\n action='store_false',\n dest='recursive',\n help=\"don't recurse into subdirs\")\n parser.add_argument('--csv',\n action='store_true',\n help=\"save to a csv file\")\n\n return parser\n\nif __name__ == \"__main__\":\n cli_parser = make_arg_parser()\n args = cli_parser.parse_args()\n\n todos = find_todos(args.path,\n ext=args.ext,\n todo_token=args.todo,\n comment_start=args.comment,\n recursive=args.recursive)\nshow_todos(todos)\n\nif args.csv:\n save_csv(todos, 'py')\n</code></pre>\n\n<p>The above is just an example. It mirrors the call to <code>find_todos()</code> and adds an argument for todo_token and a flag to save to a csv file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T07:23:47.683", "Id": "435282", "Score": "0", "body": "Seems like you're missing a `\"` in the final `if __name__ == ...`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T01:17:46.463", "Id": "224375", "ParentId": "224335", "Score": "3" } } ]
{ "AcceptedAnswerId": "224375", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T10:20:09.437", "Id": "224335", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Find Todos by Line Number (or any other reference) in Python - Revised as functions" }
224335
<p>I need some suggestions on how to approach this. I want to allow users to create sections of website. The code so far is working but since I am new to back-end I feel like there is better, more elegant way to approach this. I am open to any approaches, as long as the code is kept as concise as possible.</p> <blockquote> <ol> <li>The user clicks "add section" button (there would be different types of sections to choose from), the html of each section will be stored in an external file</li> <li>The id of the section should be inserted into the database (alongside some other details such as user uniqid)</li> <li>The section should be inserted inside a div</li> </ol> </blockquote> <p>At the moment this is how I have approached it:</p> <pre><code>if (isset($_POST["add_section"])) { $section_id = $_POST["add_section"]; $stmt = $conn-&gt;prepare('INSERT INTO sections (user_id, section_id) VALUES (?, ?)'); $stmt-&gt;bind_param('ss', $row['user_id'], $section_id); $stmt-&gt;execute(); } </code></pre> <hr> <p>The value of the button is the id of the section passed to the database.</p> <pre><code>&lt;form method="post"&gt; &lt;button class="button_1" value="navigation_ht" name="add_section&gt;Seleccionar&lt;/button&gt; &lt;/form&gt; </code></pre> <hr> <p>I want to allow the user to be able to include up to 3 sections.</p> <pre><code>$sql = "SELECT * FROM sections WHERE user_id = '{$row['user_id']}'"; $result = $conn-&gt;query($sql); if ($result-&gt;num_rows &gt; 0) { while($row = $result-&gt;fetch_assoc()) { include('shared/'.$row['section_id'].'.php'); } } </code></pre> <p>I was considering to do the following, but if the section is not created, there is error message:</p> <pre><code>$sql = "SELECT * FROM sections WHERE user_id = '{$row['user_id']}'"; $result = $conn-&gt;query($sql); while($row = $result-&gt;fetch_assoc()) { include('shared/'.$row['section_id'].'.php'); include('shared/'.$row['section_id'].'.php'); include('shared/'.$row['section_id'].'.php'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T17:21:21.000", "Id": "435866", "Score": "0", "body": "This code is far from complete. I my opinion it cannot be reviewed in this state." } ]
[ { "body": "<p>This looks very clean, there is not much to improve upon.</p>\n\n<p>However, there is a glaring security issue:\n<a href=\"https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)\" rel=\"nofollow noreferrer\">https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)</a></p>\n\n<p>Your code should not allow malicious JavaScript to be stored inside of the db.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T13:40:53.507", "Id": "224342", "ParentId": "224338", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T11:14:09.223", "Id": "224338", "Score": "2", "Tags": [ "javascript", "php", "mysql", "ajax", "dom" ], "Title": "Dynamically inserting html from external file and updating the database" }
224338
<blockquote> <p>Your task is to print all unique ways to climb a staircase of length <code>n</code> where, from each step, you can take steps of size <code>x</code> where x is an integer value from an array For example: if you want to climb a staircase of length <code>3</code> and you can move [1, 2] steps from each stair, the output should be</p> <pre><code> [1, 1, 1] [1, 2] [2, 1] </code></pre> <p>Note the order <strong>is</strong> important and hence <code>[1, 2]</code> is different to <code>[2, 1]</code>.</p> </blockquote> <p>Is this the fastest way to solve this problem <strong>(without using built in libraries such as itertools)</strong>?</p> <pre><code>def valid_moves(position, target, legal, path, permutations): if position &gt; target: return if position == target: permutations.append(path) return for move in legal: valid_moves(position + move, target, legal, path + [move], permutations) return permutations start = 0 length_staircase = 3 legal_moves = [1, 2] print(*valid_moves(start, length_staircase, legal_moves, [], []), sep="\n") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:36:38.143", "Id": "435177", "Score": "0", "body": "How general is the problem you are trying to resolve? Most of the problems with your approach only shows up in the more complicated and larger cases, so if you are only trying to resolve problems close to the scale in the example, then the more advanced methods might have too much overhead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:37:45.940", "Id": "435178", "Score": "0", "body": "I am trying to solve the problem for the most general case." } ]
[ { "body": "<p>I have a few suggestions for you:</p>\n\n<ul>\n<li>You should get in the habit on wrapping all code that isn't in a function in a main guard, to ensure that that code only runs if that file is running, and to protect it from import mishaps</li>\n<li>Running your code with <code>pylint</code>, a few warnings that popped up were:\n\n<ul>\n<li>Returns: All return statements should return something or none of them should return anything. Since you are returning <code>permutations</code>, the other <code>return</code>'s should just return None.</li>\n<li>Module Docstring: Your function should contain a docstring describing what the function does, even if it's very obvious. These will help any documentation.</li>\n<li>Constant variable names: Since the three variables in the main guard do not change, they should be in all <code>UPPERCASE</code> to make it clear that they are constants.</li>\n</ul></li>\n</ul>\n\n<p>Refactored code:</p>\n\n<pre><code>def valid_moves(position, target, legal, path, permutations):\n \"\"\" Returns unique ways to climb a staircase with passed length `target` \"\"\"\n if position &gt; target:\n return None\n if position == target:\n permutations.append(path)\n return None\n for move in legal:\n valid_moves(position + move, target, legal, path + [move], permutations)\n return permutations\n\nif __name__ == '__main__':\n START = 0\n STAIRCASE_LENGTH = 3\n LEGAL_MOVES = [1, 2]\n\n print(*valid_moves(START, STAIRCASE_LENGTH, LEGAL_MOVES, [], []), sep=\"\\n\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T08:14:56.103", "Id": "435292", "Score": "0", "body": "I disagree with the change of the input variables to the function being in CONSTANT style, since they aren't supposed to be referenced directly as constants, they are just variables that happen to live in the global space that does not need to change their value. To see whether a variable should be in CONSTANT style, we simply need to consider whether they would still work if the global code they work on was isolated inside a function (effectively extracting the `__name__ == '__main__'` into a ´main()` function, if they still work (they do) then they are not true global constants." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:00:26.210", "Id": "224370", "ParentId": "224341", "Score": "3" } }, { "body": "<h1>Performance Problems</h1>\n\n<p>Your current solution works decent for small cases, but there are a few problems when the problem starts to scale up, which causes the performance to drop. I will mention the two biggest I have found.</p>\n\n<ol>\n<li>You construct all paths toward the goal, even the unviable ones, in full until you remove them. This causes an exponential amount of extra paths to tried (though you might also have exponential amount of results).</li>\n<li>The <code>+</code> on lists causes full rebuilding of the lists, which causes a single path to cost <strong>O(n^2)</strong> to construct. Note that this cost is shared with some of the other paths investigated, which may cause the amortized cost to still be <strong>O(n)</strong> when you share it with exponential amount of paths.</li>\n</ol>\n\n<p>Note that the first problem may overshadow the second, and that if the smallest move is a common divisor of all the other moves and the result, then early prunning of paths is impossible (because they may only make a mistake on the last step).</p>\n\n<h1>Solution</h1>\n\n<p>We seperate the solution into the subsections that resolve each of the problems mentioned in the problem section, and a subsection for the combined result. The way presented here is just one way to solve the above mentioned problem in a way that remains close to the OP.</p>\n\n<h3>Early Prunning</h3>\n\n<p>To solve the problem of exponentially many paths that lead to no result, we can try to find a way to early stop a path early on if we know that it cannot possible lead to a result. If we have a function that tells us whether we can walk a certain distance we can implement <code>valid_moves</code> in this simple form (note I changed the names <code>valid_moves-&gt;valid_paths</code>, <code>legal-&gt;moves</code>, and <code>permutations-&gt;results</code> and I will be using these names going forward):</p>\n\n<pre><code>def valid_paths(position, target, moves, path, results, is_legal=lambda x: x &gt;= 0):\n for move in moves:\n new_position = position + move\n if is_legal(target - new_position):\n new_path = path + [move]\n if new_position == target:\n results.append(new_path)\n else:\n valid_moves(new_position, target, moves, new_path, results)\n return results\n</code></pre>\n\n<p>So how do we construct a usefull <code>is_legal</code> function? One way to do this is to construct all the reachable path lengths and check if the remaining distance is such a reachable path. The way I will show here to construct all the reachable paths lengths is through dynamic programming:</p>\n\n<pre><code>def construct_is_legal(moves, distance):\n if not moves:\n return lambda length: length==0\n lengths_to_check = [move for move in moves]\n lengths_reachable = {move for move in moves}\n\n min_length = min(lengths_to_check) # used by shortcut\n if distance % min_length and all(move % min_length == 0 for move in moves):\n return lambda length: length &gt;= 0 and length % min_length\n\n while lengths_to_check:\n move = lengths_to_check.pop()\n lengths_to_add = []\n for length in lengths_reachable:\n new_length = length+move\n if new_length not in lengths_reachable and new_length &lt;= distance:\n lengths_to_add.append(new_length)\n for new_length in lengths_to_add:\n lengths_to_check.append(new_length)\n lengths_reachable.add(new_length)\n\n lengths_reachable.add(0) # we can always reach the same place\n return lambda length: length in lengths_reachable\n</code></pre>\n\n<p>Note that we use sets to have fast checks for inclusion (they are implemented kind of like hash-tables under the hood according to <a href=\"https://stackoverflow.com/questions/3949310/how-is-set-implemented/3949350#3949350\">this answer</a>), so we can expect the assymtotic cost to be below of the brute force test of each possible path, as we only check once for each reached position and not for every way to reach said position.\nAlso note that I added some special cases (no results and every number divisiable by the lowest move), so we do not do all the extra work when there is a simple solution to the problem.</p>\n\n<h3>Delayed Concatenation</h3>\n\n<p>To solve the problem of <strong>O(n^2)</strong> cost for building a result (now more relevant since we have cut out the extra false paths it might have been sharing the cost with), we need to ensure we do not have to build the full list when we branch out several versions of it. We can do this by reversed directed linked tree, where each node is a move and point toward the move it took previously. Here is a simple implementation of it:</p>\n\n<pre><code>class Path:\n def __init__(self,value, prev=None):\n self.value = value\n self.prev = prev\n\n def to_list(self):\n result = [self.value]\n prev = self.prev\n while previs not None:\n result.append(prev.value)\n prev = parent.prev\n result.reverse()\n return result\n</code></pre>\n\n<p>We can then replace the <code>new_path = path + [move]</code> with <code>new_path = Path(move, prev=path)</code>, and when we add a result we also need to replace <code>results.append(new_path)</code> with <code>results.append(new_path.to_list())</code>. We could also just add the <code>Path</code> objects and let the user convert them to lists of moves when they need to, since the space complexity of storing many similar paths is much lower due to reuse of space for shared parts of the paths.</p>\n\n<h3>Combined</h3>\n\n<p>We now need to combine the parts into a whole solution. For convinience I have combined many of the tedious parts of the original into a function, which handle the combined solution:</p>\n\n<pre><code>class Path:\n def __init__(self,value, prev=None):\n self.value = value\n self.prev = prev\n\n def to_list(self):\n result = [self.value]\n prev = self.prev\n while previs not None:\n result.append(prev.value)\n prev = parent.prev\n result.reverse()\n return result\n\n\ndef construct_is_legal(moves, distance):\n if not moves:\n return lambda length: length==0\n lengths_to_check = [move for move in moves]\n lengths_reachable = {move for move in moves}\n\n min_length = min(lengths_to_check) # used by shortcut\n if distance % min_length and all(move % min_length == 0 for move in moves):\n return lambda length: length &gt;= 0 and length % min_length\n\n while lengths_to_check:\n move = lengths_to_check.pop()\n lengths_to_add = []\n for length in lengths_reachable:\n new_length = length+move\n if new_length not in lengths_reachable and new_length &lt;= distance:\n lengths_to_add.append(new_length)\n for new_length in lengths_to_add:\n lengths_to_check.append(new_length)\n lengths_reachable.add(new_length)\n\n lengths_reachable.add(0) # we can always reach the same place\n return lambda length: length in lengths_reachable\n\n\ndef list_paths(position, target, moves, path, results, is_legal=lambda x: x &gt;= 0):\n for move in moves:\n new_position = position + move\n if is_legal(target - new_position):\n new_path = Path(move, prev=path)\n if new_position == target:\n results.append(new_path.to_list())\n else:\n valid_moves(new_position, target, moves, new_path, results)\n return results\n\n\ndef valid_paths(target, moves, start=0):\n is_legal = construct_is_legal(moves, target-start)\n if is_legal(target-start): \n return list_paths(start, target, moves, path=None, result=[], is_legal=is_legal)\n else: \n return [] # no paths exist\n\n\nif __name__ == '__main__':\n print(*valid_paths(3, [1, 2]), sep='\\n')\n</code></pre>\n\n<p>Note that we have wrapped many of the annoying parts of the interface into the new <code>valid_paths</code>, and had it also handle the special case of no possible results early on.</p>\n\n<h1>Alternative</h1>\n\n<p>You may have noticed that the construction in <code>is_legal</code> is fairly close to actually solving the full problem, and we can indeed solve the entire problem with this dynamic programming approach \n by changing the set <code>lengths_reachable</code> from a set to a dictionary of combinations we can reach a given length with. Once we have such a dictionary we can easily list the paths by going from the full distance and recursively divide up the problem into the possible subpaths and then combine all the results. Here is an implementation:</p>\n\n<pre><code>def chain(*generators):\n for generator in generators:\n yield from generator\n\n\ndef dynamic_build(moves, distance):\n \"\"\" Build a dictionary of possible subpath decomposition up to distance\"\"\"\n lengths_to_check = [move for move in moves]\n lengths_reachable = {move:{move} for move in moves}\n\n while lengths_to_check:\n move = lengths_to_check.pop()\n lengths_to_add = {}\n for length in lengths_reachable:\n new_length = length+move\n lower, upper = (move, length) if move &lt;= length else (length, move)\n if new_length &lt;= distance:\n if new_length in lengths_reachable:\n lengths_reachable[new_length].add((lower,upper))\n else:\n if new_length in lengths_to_add:\n lengths_to_add[new_length] = {(lower, upper)}\n else:\n lengths_to_add[new_length].add((lower, upper))\n for new_length in lengths_to_add:\n lengths_to_check.append(new_length)\n lengths_reachable[new_length]= lengths_to_add[new_length]\n\n return lengths_reachable\n\n\ndef list_paths(lengths_reachable, target):\n main_node = lengths_reachable[target]\n results = []\n for way in main_node:\n if len(way) == 1:\n results.append([way])\n else:\n lower, upper = way\n lower_results = list_paths(lengths_reachable, lower)\n upper_results = list_paths(lengths_reachable, upper)\n for low_path in lower_results:\n for high_path in upper_results:\n results.append(chain(low_path, high_path))\n results.append(chain(high_path, low_path))\n return results\n\n\ndef valid_paths(target, moves, start=0):\n distance = target - start\n lengths_reachable = dynamic_build(moves, distance)\n if distance not in lengths_reachable:\n return [] \n return list(map(list, list_paths(lengths_reachable, distance)))\n\n\nif __name__ == '__main__':\n print(*valid_paths(3, [1, 2]), sep='\\n')\n</code></pre>\n\n<p>While the work of the alternative is about as much as the other solution, it does provide some more information about the solution, which may be usefull in related problems.</p>\n\n<h1>Notes</h1>\n\n<p>It should be noted that both the original and the solutions provided here all make use of recoursion. The problem is that python does not really like deep recursion (it has poor performance, to the point where the recursion stack is limited to about 1000). This problem is close to exponential in this depth though, so we need some fairly special cases for us to not run into other problems first. If we are indeed in such special cases, then we would need to change the above algorithms from recursive formulation to loop based versions or find a new alternative of this form.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:23:14.917", "Id": "224399", "ParentId": "224341", "Score": "1" } } ]
{ "AcceptedAnswerId": "224399", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T13:31:43.650", "Id": "224341", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "reinventing-the-wheel", "combinatorics" ], "Title": "Staircase challenge - Python" }
224341
<p>I have this code but it brings repeated results. I want it to generate without repeating the letters</p> <pre><code>private char[] lettersArr = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); public char generateLetter() { return lettersArr[rdm.Next(lettersArr.Length)]; } </code></pre> <p>The "L" is independent Result from my code{Lw, Lk, Lk, La} Results i want {La. Lb. Lc, Ld}</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:59:08.093", "Id": "435180", "Score": "0", "body": "Have a look at the [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) algorithm. But of course, if you call the method more than 26 times, you will inevitably have repeating letters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:59:16.627", "Id": "435181", "Score": "0", "body": "Just to confirm your expectations, `abababababababab` would be a valid output since it doesn't have repeating letters, right? Or are you expecting for each letter to be used in the same ratio (e.g. a 52 letter string contains every letter exactly twice)? It helps to disambiguate exactly what you're expecting (examples help a lot!). Especially with randomness, different people have different expectations and it's hard to infer your expectation from the current question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T15:00:28.757", "Id": "435182", "Score": "2", "body": "If you're looking for help with implementing a new feature, then Code Review is not the right place - here we only review code that is already working as intended. Stack Overflow would be a more appropriate place to ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T15:16:26.553", "Id": "435187", "Score": "0", "body": "i added an example @Flater" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T15:49:37.627", "Id": "435194", "Score": "0", "body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
[ { "body": "<p>I'll use a deck of cards as an example here.</p>\n\n<p>What your current code does is draw a random card from a deck. Then, the second time, it draws a random card from a <strong>complete</strong> deck, which means that there's a change you draw the same card twice. The problem persists for all subsequent draws.</p>\n\n<p>What you want to do is when you draw a second card is that you want to draw it from the <strong>same deck</strong>, i.e. the 51 card deck (because you already drew a card earlier).</p>\n\n<p>In a deck of cards, when you draw a random card, you inherently remove it from the deck. But that's not how it works in code. You <em>copy</em> a random value from the array, but you don't automatically remove it from the array.</p>\n\n<p>There are two ways of doing this.</p>\n\n<p><strong>1. Remove the drawn card from the deck before drawing the next card.</strong></p>\n\n<p>In other words, when you get a random letter, you remove that letter from <code>lettersArr</code> so that you can't get the same letter again.</p>\n\n<pre><code>string remainingLetters = \"abcdefghijklmnopqrstuvwxyz\";\n\n// draw the first \"card\"\nvar firstLetter = remainingLetters[rdm.Next(remainingLetters.Length)];\n\n// remove it from the \"deck\"\nremainingLetters = remainingLetters.Replace(firstLetter, String.Empty);\n\n// draw the second \"card\"\nvar secondLetter = remainingLetters[rdm.Next(remainingLetters.Length)];$\n</code></pre>\n\n<p>This can of course be improved by an iterative approach. Also, beware that this makes it impossible for you to get more than 26 letters as your deck will be empty.</p>\n\n<p>There are more performant variation of this algorithm, but this is just an example. I'm skipping the optimalizations because I suggest using the second approach as I find it far better to use:</p>\n\n<p><strong>2. Shuffle the deck</strong></p>\n\n<p>What I mean by shuffling the deck is that you (randomly) rearrange the letters rather than extracting them from the array one by one. This is very analogous to what you'd do to a deck of cards, and it makes a lot more intuitive sense.</p>\n\n<p>I much prefer this method because it's so much cleaner, and you can use LINQ</p>\n\n<pre><code>var orderedAlphabet = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n\nvar shuffledAlphabet = orderedAlphabet.OrderBy(letter =&gt; rdm.Next()).ToArray();\n</code></pre>\n\n<p>Basically, LINQ will generate a random number (<code>rdm.Next()</code>) for every letter, and will then sort the letters by the numerical value of the random number.</p>\n\n<p>The end result is a string (or character array) with the exact same 26 letters, but the order is randomized.</p>\n\n<p>If you then want to fetch letters from the randomized array, just read from left to right. You can either use a substring to get a chunk of a certain size all at once:</p>\n\n<pre><code>var chunk = shuffledAlphabet.Substring(0,5); // 5 letters\n</code></pre>\n\n<p>or read it letter by letter using a counter that you increment:</p>\n\n<pre><code>private int counter = 0;\n\nprivate char GetNextLetter()\n{\n return shuffledAlphabet[counter++];\n}\n</code></pre>\n\n<p>Don't forget to check your upper bound too!</p>\n\n<p>Or if you need all 26, you don't need to process it any further and can just return <code>shuffledAlphabet</code> as is.</p>\n\n<pre><code>private char[] GetShuffledAlphabet()\n{\n return shuffledAlphabet;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T15:21:49.553", "Id": "224350", "ParentId": "224347", "Score": "-1" } } ]
{ "AcceptedAnswerId": "224350", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T14:51:56.070", "Id": "224347", "Score": "-4", "Tags": [ "c#" ], "Title": "Generate random letter without repetition" }
224347
<p>I am trying to add two numbers in the form of linked List and return their result in a Linked List as given in <a href="https://leetcode.com/problems/add-two-numbers/" rel="nofollow noreferrer">https://leetcode.com/problems/add-two-numbers/</a></p> <h2>Question:</h2> <blockquote> <p>You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.</p> <p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p> </blockquote> <p>Example:</p> <p>Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)<br> Output: 7 -> 0 -> 8<br> Explanation: 342 + 465 = 807, my solution has solved all the test cases but after refactoring, it is taking longer than the original code</p> <h2>Solution 1:</h2> <pre><code>//public class ListNode //{ // public int val; // public ListNode next; // public ListNode(int x) { val = x; } //}; public class Solution { public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { ListNode l3 = null; int carry = 0; while (l1 != null || l2 != null) { int first = 0, second = 0; if (l1 != null) { first = l1.val; l1 = l1.next; } if (l2 != null) { second = l2.val; l2 = l2.next; } int Digit = first + second; if (carry != 0) { Digit = Digit + carry; carry = 0; } if (Digit &gt; 9) { carry = Digit / 10; Digit = Digit % 10; } AddLastNode(Digit, ref l3); } if (carry != 0) { AddLastNode(carry, ref l3); carry = 0; } return l3; } /// In here I am looping through the Linked List every time,to find the tail node private static void AddLastNode(int Digit, ref ListNode l3) { if (l3 != null) { AddLastNode(Digit, ref l3.next); } else { l3 = new ListNode(Digit); } } } </code></pre> <p>So to avoid looping through all the Nodes,in the below solution I am using a reference for the Tail Node</p> <h2>Solution 2:</h2> <pre><code>public class Solution { public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { ListNode l3 = null; ListNode tailNode = null; int remainder = 0; while (l1 != null || l2 != null) { int sum = 0; if (l1 != null) { sum = l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } if (remainder != 0) { sum += remainder; } if (sum &gt; 9) { remainder = sum / 10; sum = sum % 10; } else { remainder = 0; } ///In here I am using tailNode has reference for adding new node to the end of Linked List if (tailNode == null) { l3 = new ListNode(sum); tailNode = l3; } else { tailNode.next = new ListNode(sum); tailNode = tailNode.next; } } if (remainder != 0) { tailNode.next = new ListNode(remainder); } return l3; } } </code></pre> <p>Since I got a tail node for the end of Linked List instead of going through entire Linked List,I thought the solution 2 will have better performance.But it is still taking more time to execute than the first solution ,Any code changes would be appreciated</p> <p><a href="https://i.stack.imgur.com/YQnps.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YQnps.jpg" alt="enter image description here"></a></p> <p>Solution 1 is taking 108 ms to execute while Solution 2 is taking 140 ms</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T16:42:11.187", "Id": "435201", "Score": "0", "body": "@dfhwe I have formatted some of the code,let me know if there are any existing changes you want me to make" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:21:49.953", "Id": "435210", "Score": "0", "body": "For future reference: https://www.freecodeformat.com/c-format.php. Also, you are using Java document comments instead of C# comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T01:09:25.920", "Id": "435254", "Score": "0", "body": "@dfhwze Edited the comments as well,didn't notice until it was pointed out,Copied the commented code from the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T08:33:25.507", "Id": "435294", "Score": "0", "body": "Your first solution uses what's sometimes called a ['Schlemiel the painter's algorithm'](https://en.wikipedia.org/wiki/Joel_Spolsky#Schlemiel_the_Painter's_algorithm) - it scales very poorly. Try adding numbers with hundreds and thousands of digits and you'll see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T10:48:27.500", "Id": "435303", "Score": "0", "body": "@PieterWitvoet, Thanks for the Input,I was thinking the same about scalability" } ]
[ { "body": "<p>In terms of the times on LeetCode, they can be dependent upon the server load as much as the code. I tried your code and got a range of times from 100 ms to 136 ms. Holding onto the last node is a better solution than repeatedly trying to find it but on a list of only a few nodes I don't know how much impact it would have.</p>\n\n<p>In terms of the code, this strikes me as a good place to use the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators\" rel=\"nofollow noreferrer\">Null Condtional Operator (?.)</a>. We can get around the repeated null check on the tailnode by using a dummy head for the return list.</p>\n\n<pre><code>public ListNode AddTwoNumbers(ListNode l1, ListNode l2) \n{\n ListNode l3 = new ListNode(-1); // dummy head\n ListNode tailNode = l3;\n int remainder = 0;\n while (l1 != null || l2 != null) {\n\n var sum = (l1?.val ?? 0) + \n (l2?.val ?? 0) + \n remainder;\n l1 = l1?.next;\n l2 = l2?.next;\n\n if (sum &gt; 9) {\n remainder = sum / 10;\n sum = sum % 10;\n }\n else {\n remainder = 0;\n }\n tailNode.next = new ListNode(sum);\n tailNode = tailNode.next;\n\n }\n if (remainder != 0) {\n tailNode.next = new ListNode(remainder);\n }\n return l3.next; // skip the dummy head when returning\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T10:45:36.797", "Id": "435302", "Score": "0", "body": "Thanks for the code,if we change the requirements to allow empty or null Linked List as Input,how can we handle that since we will be returning null ListNode" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:09:30.527", "Id": "435321", "Score": "0", "body": "As far as I can see the existing code allows for null inputs as long as we are happy that two null inputs result in a null being returned. If not, then we can check for two nulls and return whatever we want the answer to be. Either one being null is no different than dealing with numbers of different lengths. Not sure what you mean by an empty input - as far as i can see it can either be null or contains a value, there is no 'empty' list" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:03:55.907", "Id": "435336", "Score": "0", "body": ",Thank you for the input" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T07:27:26.697", "Id": "224386", "ParentId": "224353", "Score": "2" } } ]
{ "AcceptedAnswerId": "224386", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T15:52:59.217", "Id": "224353", "Score": "0", "Tags": [ "c#", "programming-challenge", "linked-list", "comparative-review" ], "Title": "Adding a Node to the Linked List is taking a longer Time when using a reference to the Tail Node" }
224353
<p>After finishing my ds and algorithms course I wanted to implement what I've learned through the semester so here is my try for Linked lists, both regular (one way) and double one (two way).</p> <p>code:</p> <pre class="lang-py prettyprint-override"><code>from node import ListNode class LinkedList(): _length = 0 ''' Init linked list ''' ''' double is boolean ''' def __init__(self, x, doubly=False): if x is not None: self.head = ListNode(x, doubly) self.tail = self.head self._length += 1 else: assert False, 'User entered a None value' ''' representing the list ''' def __str__(self, doubly=False): st = '' arrow = ' &lt;-&gt; ' if doubly else ' -&gt; ' p = self.head while p is not None: st += str(p.key) p = p.next if p is not None: st += arrow return st ''' insert to the end of the list ''' def insert(self, x, doubly=False): if self.head is None: self.__init__(x) return p = self.head new_node = ListNode(x, doubly) self.tail.next = new_node if doubly: new_node.prev = self.tail self.tail = new_node self._length += 1 ''' insert to the head of the list ''' def insert_to_head(self, x, doubly=False): new_node = ListNode(x, doubly) new_node.next = self.head if doubly: self.head.prev = new_node self.head = new_node self._length += 1 ''' delete from list and fix pointers ''' def delete(self, x, doubly=False): ''' deleting first instance of x ''' # if list is empty if self.head is None: raise Exception('List is empty') # else.. p = self.head # if head is x, delete and fix if p.key == x: if len(self) &gt; 1: if doubly: p.next.prev = None self.head = p.next self._length -= 1 else: self.head, self.tail = None, None self._length -= 1 return del p return # regular delete from list while p.next is not None and p.next.key != x: p = p.next if p.key != x: return None tmp = p.next # grab Node contains `x` if self.tail is tmp: self.tail = p p.next = p.next.next if doubly: p.next.next.prev = p del tmp self._length -= 1 ''' search (linear time O(n)) in list ''' def search(self, x): if self.head is None: return None p = self.head if p.key == x: return p while p.key != x and p.next is not None: p = p.next return p if p.key == x else None class DoublyLinkedList(LinkedList): _length = 0 ''' Init double linked list ''' def __init__(self, x): super().__init__(x, True) ''' string with doublt linkedlist ''' def __str__(self): return super().__str__(True) def __len__(self): return self._length def insert(self, x): super().insert(x, True) def insert_to_head(self, x): super().insert_to_head(x, True) def delete(self, x): super().delete(x, True) def search(self, x): return super().search(x) </code></pre> <p>the Node class:</p> <pre class="lang-py prettyprint-override"><code>class ListNode(): def __init__(self, x, double=False): self.key = x self.next = None if double: self.prev = None def __str__(self): try: return str(self.key) except AttributeError: return 'No key for this Node' </code></pre> <p>thanks in advance for you code review!</p> <p>Things I want to check:</p> <ol> <li><p>is the code is understandable?</p></li> <li><p>is it well organized?</p></li> <li><p>is the implementation using abstract class is good or there are conventions I missed/etc ?</p></li> <li><p>any other suggestions?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T21:13:06.473", "Id": "436753", "Score": "1", "body": "After answers were made, the original code cannot be updated. It is advised to ask a follow-up question instead, if you want a review of your updated code: https://meta.stackexchange.com/questions/286803/change-to-question-invalidates-my-answer-what-to-do/286804#286804" } ]
[ { "body": "<h3>Review</h3>\n\n<p>You should take advantage of the bi-directional nature of a doubly linked list. It's a pitty to let it use navigation of a normal linked list just for the sake of enabling inheritance. And why should a normal linked list be able to branch between normal and doubly mode? This is a <strong>code smell</strong>.</p>\n\n<p>A practical way to create a doubly linked list, is to create a circular list. You only need to store the <code>head</code>. <code>tail</code> would be <code>head.prev</code>. This also works with a single node <code>head</code> = <code>head.prev</code> = <code>head.next</code>. The advantage is that less <code>if</code> statements are required to perform <code>insert</code> / <code>delete</code> operations. Walking the nodes starts at <code>head</code> and stops until we encounter <code>head</code> again. We could walk both directions if we wish to.</p>\n\n<p>You can initialise a single node:</p>\n\n<pre><code>self.head = ListNode(x, doubly)\nself.head.prev = self.head\nself.head.next = self.head\n</code></pre>\n\n<p>The delete would be significantly simplified:</p>\n\n<p>After walking the nodes until you get the proper node <code>p</code> given <code>x</code>, you can call</p>\n\n<pre><code>if p.next == p:\n self.head = None\nelse:\n p.next.prev = p.prev\n p.prev.next = p.next\n if self.head == p:\n self.head = p.next\ndel p\nself._length -= 1\n</code></pre>\n\n<p>I don't see a value in using inheritance for these lists.</p>\n\n<hr>\n\n<p>I also don't get why you store <code>p = self.head</code> in <code>insert</code>. It's an unused variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T16:50:34.903", "Id": "435602", "Score": "0", "body": "Thank you so much!! noted" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:47:01.367", "Id": "224437", "ParentId": "224355", "Score": "1" } }, { "body": "<h2>Problems</h2>\n\n<p>The use of <code>_length</code> in your classes is problematic, because that value is shared between all instances of the same class, which means it will refere to the wrong value when you have multiple non-empty lists of the same type. One of the big problems with linked lists in general is the loss of this length information if you do not package the list (and thereby loss the value of having a linked list).</p>\n\n<h2>Advise</h2>\n\n<p>It is generally advised to mainly focus on the nodes when creating linked lists, as the main power of linked list comes from doing operations locally (around some node that you know of), instead of from a common interface (iterating through such a list would be expensive if we need to walk from the beginning each time we want to reference the next position).</p>\n\n<p>There is also a point to be made about trying to implement some of pythons hooks for lists, which can make the rest of the implementation much easier to do.</p>\n\n<h2>Implementation</h2>\n\n<p>Here is how I would go about this, note that prepending is generally done by just calling <code>head = LinkedList(value, head)</code>:</p>\n\n<pre><code>class LinkedList:\n link_symbol = ' -&gt; '\n\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\n def as_generator(self, end=None):\n node = self\n yield node\n while node.next is not end and node.next is not None:\n node = node.next\n yield node\n\n def __iter__(self):\n return map(lambda node: node.value, self.as_generator())\n\n def __str__(self):\n return self.link_symbol.join(value for value in self)\n\n def delete_next(self):\n if self.next is not None:\n self.next = self.next.next\n\n def forward(self, steps):\n for node in self.as_generator():\n if steps == 0:\n return node\n steps -= 1\n\n def __getitem__(self, steps):\n return self.forward(steps).value\n\n def __reverse__(self):\n return self.__class__.from_iter(self, reversed=True)\n\n @classmethod\n def from_iter(cls, iter, start=None, reversed=True):\n result = start\n for value in iter:\n cls(value, result)\n if not reversed:\n result.reversed()\n return result\n\n def tail(self):\n for node in self.as_generator():\n pass\n return node\n\n def __len__(self):\n return sum(1 for __ in self)\n\n def append(self, value):\n self.tail().next = self.__class__(value)\n\n def find(self, value):\n for node in self.as_generator():\n if node.value = value:\n return node\n\nclass DoubleLinkedList(LinkedList):\n link_symbol = ' &lt;-&gt; '\n\n @property\n def next(self):\n return self.__next\n\n @next.setter\n def next(self, node):\n if node is not None:\n node.prev = self\n self.__next = node\n\n def __init__(self, value, next=None, prev=None, cyclic=True):\n super().__init__(value, next)\n self.prev = prev\n if cyclic and self.next is None and self.prev is None:\n self.next, prev = (self, self)\n\n def as_generator(self, end=None)\n if end is None:\n end = self\n super().as_generator(end=end)\n\n # extra stuff we can now do\n def backwards_generator(self, end=None):\n node = self\n yield node\n while node.prev is not end and node.prev is not None:\n node = node.prev\n yield node\n\n def backwards(self, steps):\n if steps &lt; 0: \n return self.forward(-steps)\n for node in self.backwards_generator():\n if steps == 0:\n return node\n steps -= 1\n\n def head(self):\n for node in self.backwards_generator():\n pass\n return node\n\n def forward(self, steps)\n if steps &lt; 0:\n return self.backwards(-steps)\n return super().forward(steps)\n</code></pre>\n\n<p>Note how much easier it was to make <code>DoubleLinkedList</code> when most of the methods is expressed in terms of central functions instead of having each implementing their own specific version of a walk through the list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T16:50:16.183", "Id": "435601", "Score": "0", "body": "Thank you so much!! I got so much to learn, i'll go over it as soon as possible in order to understand it better :)\nBTW I think you made LinkedList as a method instead of a Class, am I right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T17:03:04.857", "Id": "435604", "Score": "1", "body": "@MatanCohen good catch, it was supposed to be a class, so I have corrected that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:19:47.143", "Id": "436396", "Score": "0", "body": "while deeping into the code I saw that in order to get tail we need to iterate over the entire list. it takes O(n) time. why not define an attribute and update it every append? :) also, the length takes O(n) too, why can't we maintain the length as an attribute?\n\nAlso, while trying to append/print DoubleLinkedList I get TypeError: 'NoneType' object is not iterable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T20:31:34.737", "Id": "436582", "Score": "0", "body": "The **O(n)** cost of tail and length is indeed not a mistake, and it is a side effect of node based implementation. It is generally advisable to keep such information separately if you are working with the list in such a context (keep the tail around if you do a lot of appending), and you can add a wrapper around it if you tend to do a lot of those opperations,. You do lose out on a lot of the power of linked lists if you do so though, since you would need a restricted interface. Remember that a node can be part of a whole inversed tree of linked list, and the priced local operations breaks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T20:43:39.197", "Id": "436584", "Score": "0", "body": "If you want a node to only be appart of a single list (ever), then you can make a derived class, where each node keeps track of an object containing information of full list information, such as the head, tail, length and maybe some effective structure for indexing into the list. This does cost at least **O(n)** extra space, and most operations would be more expensive. This is probably overkill for most applications, but the assymtotical costs are mostly the same, so it might have some use for theoretical improvements on some algorithms (I cannot recall a specific one though)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T21:08:25.913", "Id": "436752", "Score": "0", "body": "Updated my code (only regular linked list), Hope you can give it a look,\nBasically what you're saying is that the new code is worse? :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T21:18:27.627", "Id": "436754", "Score": "1", "body": "I had to roll back your changes. Your edit invalidated both answers. Please ask a new question if you wish us to review your updated code. thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T22:54:42.753", "Id": "436760", "Score": "0", "body": "Thank you, Writing it up right now!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:54:17.277", "Id": "436804", "Score": "0", "body": "What I am saying is that linked lists are optimized for a different type of use (based mainly on local changes) compared to other list types (vectors [the default python list type] and arrays). It is not supprising that they perform poorer at some of the operations not optimized for, and if you need both behaviors, then you are best off with a more custom built list type, that is effective for the kinds of operations you need to use it for." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T17:18:08.920", "Id": "224491", "ParentId": "224355", "Score": "1" } } ]
{ "AcceptedAnswerId": "224491", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T16:39:04.377", "Id": "224355", "Score": "8", "Tags": [ "python", "beginner", "linked-list" ], "Title": "Implementing Linked lists in Python from scratch" }
224355
<p><strong>A litle context:</strong></p> <p>This game server is coded entirely on C-with-classes (plain C code using basic C++ features like classes, templates and such, to avoid any possible overhead). At startup the server allocates a big block of memory to hold an awful lot of objects (talking about millions of objects! the map is quite big). I've designed this Object class:</p> <pre><code>class Object { Object* NextObject; // Pointer to first item in our same container (tiles are Map Containers). Can be NULL. Object* Container; // Cannot be NULL, except if we are a Map Container object. Object* Content; // Pointer to our content, if we have, otherwise NULL. ObjectType* Type; // A C array holds all the object types, this points to ours int32_t InstanceAttributes[20]; // Can be plain integers or some sort of reference to other object (i.e the Dynamic String Table). bool State; }; Object::Object() { State = 0; ObjectTableFree.push_front(); } </code></pre> <p>I decided to use a chunked arrays to store my objects, this way:</p> <pre><code>#define TABLESIZE 64 #define CHUNKSIZE 32768 ObjectChunk* ObjectTable; std::forward_list&lt;Object *&gt; ObjectTableFree(TABLESIZE * CHUNKSIZE); struct ObjectChunk { Object Obj[CHUNKSIZE]; }; void InitMap() { ObjectTable = new ObjectChunk[TABLESIZE]; // Here we also read the map from the hard disk, and } </code></pre> <p>These tiny "Helpers" as I call them will happily carry out the Object logic. (Of course I will not include them all, these are just so you can get an idea).</p> <pre><code>Object* CreateObject() { if (ObjectTableFree.empty()) ResizeObjectTable(); Object* obj = ObjectTableFree.front(); assert(obj); ObjectTableFree.pop_front(); return obj; } Object* AppendObject(Object* Con, ObjectType* Type, bool AsContent) { assert(Con); Object* obj = CreateObject(); obj-&gt;Container = Con; Object-&gt;setType(Type); if (AsContent) { if (Con-&gt;Content) obj-&gt;NextObject = Con-&gt;Content; Con-&gt;NextObject = obj; return obj; if (Con-&gt;NextObject) obj-&gt;NextObject = Con-&gt;NextObject; Con-&gt;NextObject = obj; return obj; } </code></pre> <p>When my map loads I append the objects to the map containers and start manipulating them through pointers through the whole code. Please note that even though this is a C++ project, I can't use most of its features because of internal convention.</p> <ul> <li>Is this all-pointer design a smart one? </li> <li>How could this be redesigned to make it more efficient/faster?. </li> <li>Is there any way to accomplish this without all those pointers?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T17:57:08.873", "Id": "435207", "Score": "0", "body": "Take a look at allocators, and placement new." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:30:27.023", "Id": "435213", "Score": "3", "body": "This question is incomplete. To help reviewers give you (better) answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](https://codereview.meta.stackexchange.com/a/1231). In this particular case, we are missing a scenario where you show us how your code can be used. Unit tests wouldn't hurt either." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T17:48:28.030", "Id": "224358", "Score": "1", "Tags": [ "c++", "performance", "object-oriented", "memory-management" ], "Title": "Managing millions of objects in a MMO game server" }
224358
<p>anyone can provide some suggestion about my answer for the questions <a href="https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/" rel="nofollow noreferrer">987. Vertical Order Traversal of a Binary Tree</a></p> <blockquote> <p>Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates). If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.</p> <p>Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.</p> <p>Input: [3,9,20,null,null,15,7]</p> <p>Given binary tree [1, 2, 3, 4, 6, 5, 7]</p> </blockquote> <pre><code> 1 / \ 2 3 / \ / \ 4 6 5 7 </code></pre> <blockquote> <p>return its vertical order traversal as</p> <p>Output: [[4], [2], [1, 5, 6], [3], [7]]</p> </blockquote> <pre><code>class Solution: def verticalOrder(self, root: TreeNode) -&gt; List[List]: stack = [(root, 0)] node_map = dict() while stack: tmp = dict() for _ in range(len(stack)): node, index = stack.pop(0) if node: tmp[index] = tmp.get(index, []) + [node.val] if node.left: stack.append((node.left, index - 1)) if node.right: stack.append((node.right, index + 1)) tmp = {k: sorted(i) for k, i in tmp.items()} node_map = {k: node_map.get(k, []) + tmp.get(k, []) for k in list(tmp.keys()) + list(node_map.keys())} res = sorted([(index, val) for index, val in node_map.items()], key=lambda x: x[0]) return [i for _, i in res] </code></pre>
[]
[ { "body": "<p>Your code seems to have the right general structure, but is doing some extra work.</p>\n\n<p>Comments would help people (including you in the future) understand what your code does and why (e.g the comment below explaining why -y is used).</p>\n\n<p>Also, the problem says that nodes at the same x-coord are listed in order of their y-coord (top-to-bottom) and then by value, but you don't seem to keep track of the y-coord.</p>\n\n<pre><code>from collections import defaultdict\n\nclass Solution:\n def verticalOrder(self, root: TreeNode) -&gt; List[List]:\n # the stack keeps track of nodes that are waiting to be\n # processed, along with their x and y coordinates\n stack = [(root, 0, 0)]\n\n # the key is x-coordinate of a tree node, the value is a list of (-y, node_value) tuples.\n # We use -y so so that when the list is sorted later, the tuples are sorted top-to-bottom\n # and then by node_value\n node_map = defaultdict(list)\n\n # while there are nodes left to be processed, get the next one and add it to the node_map\n while stack:\n node, x, y = stack.pop()\n node_map[x].append((-y, node.val))\n\n # add the node's children to the stack for processing\n if node.left: \n stack.append((node.left, x - 1, y - 1))\n\n if node.right:\n stack.append((node.right, x + 1, y - 1))\n\n result = []\n\n # process groups of nodes in order from smallest to largest x-coordinate\n for x_coord in sorted(node_map.keys()):\n\n # sort the tuples by y-coordinate and then value\n values_at_this_x = [node_value for _,node_value in sorted(node_map[x_coord])]\n\n result.append(values_at_this_x)\n\n return result\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T05:38:37.870", "Id": "435496", "Score": "0", "body": "thank you. yap. my idea is using BFS and at each level, tmp dictionary (key: index, value: List[node.val]) will be generated. so it must be at the same level. so at the end i just merged the two dictionary. and sorted by index" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T07:21:52.610", "Id": "224458", "ParentId": "224359", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:31:27.680", "Id": "224359", "Score": "0", "Tags": [ "python", "python-3.x", "tree" ], "Title": "leetcode 987. Vertical Order Traversal of a Binary Tree" }
224359
<p>I am aiming to compute the Hurst Exponent of a 1-D signal time series in Python. For now, I have one existing function <code>hurst(sig)</code> which returns the Hurst exponent of <code>sig</code> as a float. Unfortunately, the code runs <em>very slowly</em> even for signals with only ~7500 data points. My main concerns are:</p> <ol> <li>Calculate the computational complexity of my algorithm given the size of <code>sig</code>.</li> <li>Reduce computational complexity of the algorithm.</li> <li>Reduce run-time (~1s).</li> <li>Improve readability and address style convention as applies.</li> </ol> <p>My code, awaiting your feedback:</p> <pre><code>import numpy as np def hurst(sig: np.ndarray) -&gt; float: """Compute the Hurst exponent of sig. arguments sig -- 1D signal returns hurst_exponent -- float """ n = sig.size # num timesteps t = np.arange(1, n + 1) y = sig.cumsum() # marginally more efficient than: np.cumsum(sig) mean_t = y / t # running mean s_t = np.zeros(n) r_t = np.zeros(n) for i in range(n): s_t[i] = np.std(sig[:i + 1]) x_t = y - t * mean_t[i] r_t[i] = np.ptp(x_t[:i + 1]) r_s = r_t / s_t r_s = np.log(r_s)[1:] n = np.log(t)[1:] a = np.column_stack((n, np.ones(n.size))) [hurst_exponent, c] = np.linalg.lstsq(a, r_s)[0] return hurst_exponent </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:43:33.347", "Id": "435214", "Score": "0", "body": "Does the signal have any special properties or would it be appropriate to test with random values of a given length?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:45:06.947", "Id": "435215", "Score": "0", "body": "@AlexV you could test with random values of a given length. Currently, the length is anywhere between 7680 and 153600." } ]
[ { "body": "<p>A few observations:</p>\n\n<hr>\n\n<p><code>s_t = np.zeros(n)</code> and <code>r_t = np.zeros(n)</code> are more than you need. Since you don't actually use the array values but solely overwrite them, you can use <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html\" rel=\"nofollow noreferrer\"><code>np.empty</code></a> here.</p>\n\n<hr>\n\n<p>You're doing quite a bit of redundant work in the <code>for</code> loop.</p>\n\n<p>When calculating <code>s_t[i]</code>, numpy basically has to repeat all the computations it has already done for <code>s_t[i-1]</code>. If you have a look at the definition of <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html\" rel=\"nofollow noreferrer\"><code>np.std</code></a>, you can see that the mean plays a role here. Since you have already come up with a nice solution for the mean value, you could reuse it here:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>s_t = np.empty(n)\n\nfor i in range(n):\n s_t[i] = np.mean((sig[:i+1] - mean_t[i])**2)\n ...\ns_t = np.sqrt(s_t)\n</code></pre>\n\n<p>I validated this against the original code with <code>np.allclose</code>.</p>\n\n<p><code>r_t</code> also has some extra work that you can get rid of. At the moment your code does the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x_t = y - t * mean_t[i]\nr_t[i] = np.ptp(x_t[:i + 1])\n</code></pre>\n\n<p>All the values of <code>x_t</code> at <code>[i+1:n]</code> are computed, but never used, so you can do</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>r_t[i] = np.ptp(y[:i+1] - t[:i+1] * mean_t[i])\n</code></pre>\n\n<p>instead, without changing the outcome. You could also write this as two list comprehensions:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>s_t = np.sqrt(\n np.array([np.mean((sig[:i+1] - mean_t[i])**2) for i in range(n)])\n)\nr_t = np.array([np.ptp(y[:i+1] - t[:i+1] * mean_t[i]) for i in range(n)])\n</code></pre>\n\n<p>Or even a single one if you'd like to get a little bit creative:</p>\n\n<pre><code>rs_t = np.array([\n [\n np.mean((sig[:i + 1] - mean_t[i])**2),\n np.ptp(y[:i + 1] - t[:i + 1] * mean_t[i])\n ] for i in range(n)\n])\nrs_t[:, 0] = np.sqrt(rs_t[:, 0])\n</code></pre>\n\n<p>A fully vectorized computation of <code>x_t</code> I have come up with, starting from</p>\n\n<pre><code>x_t = y.reshape(1, -1) - mean_t.reshape(-1, 1) @ t.reshape(1, -1)\n</code></pre>\n\n<p>is considerably slower than the looped version.</p>\n\n<hr>\n\n<p>I'm actually not quite sure about the rest of the code from this point on at the moment. I will have to take a closer look to give a meaningful review performancewise. As a first non-functional feedback I would like to invite you to think about more meaningful variable names in the future. Especially there at the end of the code around the least-squares optimization, they are quite hard to understand.</p>\n\n<hr>\n\n<p>I did some timing of different versions of this algorithm. The full benchmark code can be found in <a href=\"https://gist.github.com/alexvorndran/aad69fa741e579aad093608ccaab4fe1\" rel=\"nofollow noreferrer\">this gist</a>. This is what I got so far (for <code>n=15360</code>):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>base: 3.748915s\nbetter_loop: 2.605374s\ndouble_lc: 2.430255s\nsingle_lc: 2.445943s\n-----------------------\nbase_numba: 0.866583s\nbetter_loop_numba: 0.813630s\ndouble_lc_numba: 0.776361s\nsingle_lc_numba*: N/A\n</code></pre>\n\n<p>The lower group of results uses <a href=\"https://numba.pydata.org/\" rel=\"nofollow noreferrer\">numba</a>, a just-in-time compiler for Python code, that can sometimes help to speed up loops. Unfortunately, numba does not support all types of array operations in its fast <code>nonpython</code> mode, e.g. I could not get the single list comprehension version to properly work with numba.</p>\n\n<p>The results are actually a little bit worse than I had originally expected, especially without numba, but there is still a good amount profiling work to be done here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:00:26.080", "Id": "435243", "Score": "0", "body": "I wish I could upvote this twice. By the way, the variable names match the symbols of the numbers used in the hurst exponent calculation E[R(n)/S(n)]=Cn^h" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T06:50:46.333", "Id": "435275", "Score": "2", "body": "If you refer to a mathematical formula, I find it quite helpful to link to the resource you are getting it from, or at least a short \"natural language\" description in a comment (where necessary). Sometimes authors use notation that slightly differs from \"the usual way\", though I have to admit I've never heard of the Hurst exponent before this question, so I'm maybe not the best person to judge this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:58:02.647", "Id": "224369", "ParentId": "224360", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:35:51.687", "Id": "224360", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "numpy", "signal-processing" ], "Title": "Hurst Exponent calculator" }
224360
<p>So I had previously posted <a href="https://codereview.stackexchange.com/questions/211957/implementing-a-logging-system-in-c17">this question</a> and asked for some feedback regarding my (now) <a href="https://github.com/Rietty/Lumberjack/blob/master/Log.hpp" rel="nofollow noreferrer">header-only logging system</a> and figured it would be a good time to go back to the changes I made it and see if it can be further improved before starting a larger project.</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once /* Header only logging system. Should be thread-safe and type-safe, as well as easier to use. Hopefully no major errors to deal with. */ // Standard Headers. #include &lt;ostream&gt; #include &lt;variant&gt; #include &lt;memory&gt; #include &lt;utility&gt; #include &lt;mutex&gt; #include &lt;array&gt; #include &lt;string_view&gt; // Everything will take place in this namespace, so we can use the Logger:: prefix for functions. namespace Logger { // Various logging severity levels. enum class Level { Info, Debug, Warning, Error, Fatal }; class Log { public: // Takes standard streams cout, cerr, etc. explicit Log(std::ostream&amp; p_stream) : m_log(&amp;p_stream) {} // Create logger using std::make_unique&lt;std::ofstream&gt;(...) so ownership is passed. explicit Log(std::unique_ptr&lt;std::ostream&gt; p_stream) : m_log(std::move(p_stream)) {} template &lt;typename T&gt; inline void info(T&amp;&amp; p_message); template &lt;typename T&gt; inline void debug(T&amp;&amp; p_message); template &lt;typename T&gt; inline void warning(T&amp;&amp; p_message); template &lt;typename T&gt; inline void error(T&amp;&amp; p_message); template &lt;typename T&gt; inline void fatal(T&amp;&amp; p_message); private: template &lt;typename T&gt; void log(T&amp;&amp; p_msg) const { auto const t_lock = std::lock_guard(*m_lock); std::visit([&amp;](auto&amp;&amp; p_ptr) { (*p_ptr) &lt;&lt; p_msg; }, m_log); }; std::ostream&amp; stream() const { return std::visit([](auto&amp;&amp; ptr) -&gt; std::ostream&amp; { return *ptr; }, m_log); } template &lt;typename T&gt; inline void add(Logger::Level p_level, T&amp;&amp; p_message); std::variant&lt;std::unique_ptr&lt;std::ostream&gt;, std::ostream*&gt; m_log; std::unique_ptr&lt;std::mutex&gt; m_lock = std::make_unique&lt;std::mutex&gt;(); std::array&lt;std::string_view, 5&gt; m_levels = { "Info", "Debug", "Warning", "Error", "Fatal" }; }; template &lt;typename T&gt; void Log::add(Level p_level, T&amp;&amp; p_message) { auto const f_lock = std::lock_guard(*m_lock); stream() &lt;&lt; m_levels[static_cast&lt;size_t&gt;(p_level)] &lt;&lt; ": " &lt;&lt; p_message &lt;&lt; '\n'; } template &lt;typename T&gt; inline void Log::info(T&amp;&amp; p_message) { add(Level::Info, p_message); } template &lt;typename T&gt; inline void Log::debug(T&amp;&amp; p_message) { add(Level::Debug, p_message); } template &lt;typename T&gt; inline void Log::warning(T&amp;&amp; p_message) { add(Level::Warning, p_message); } template &lt;typename T&gt; inline void Log::error(T&amp;&amp; p_message) { add(Level::Error, p_message); } template &lt;typename T&gt; inline void Log::fatal(T&amp;&amp; p_message) { add(Level::Fatal, p_message); } } </code></pre> <p>Is this thread-safe? Is it type-safe? How can I improve on it? What have I done badly? What have I done correctly so I know to keep that for the future?</p> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:52:42.743", "Id": "435216", "Score": "0", "body": "Are the severity levels configurable? Could you configure a minimum level? Is Debug allowed in production environment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:15:07.727", "Id": "435352", "Score": "0", "body": "@dfhwze No, no, and I don't understand the last point. Can you clarify a bit I would add that in and set up a minimum level?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:36:30.930", "Id": "435359", "Score": "0", "body": "Logging at Debug level could indicate that you only want these logs in test environments, not in production. A minimum level would indicate that all calls to the logger below this level would be silently ignored. This way, you can put a very fine trace log level when introspecting some issues, and reset the log level afterwards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:21:00.053", "Id": "435377", "Score": "0", "body": "How would I specify those switches during build? I.e. How would the code know it's being built for a particular environment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:24:03.250", "Id": "435378", "Score": "0", "body": "I would expect compiler flags or configuration files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:29:36.693", "Id": "435379", "Score": "0", "body": "Hmmm, okay thank you for the advice! I'll see if I can work that in somehow. :) It seems fairly useful actually. Would severity levels be configured the same way or is there a better way for that?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T18:49:15.627", "Id": "224361", "Score": "4", "Tags": [ "c++", "thread-safety", "logging", "c++17", "type-safety" ], "Title": "Type & Thread-safe Logger Implementation" }
224361
<p>I am implementing the Bellman equation for utilities, in a grid environment as follow. It is an example on Chapter 17 of Artificial Intelligence: A Modern Approach 3rd Edition. </p> <p>There are some math bended in, I would be extremely appreciate if you can verify the mathematical accuracy of my implementation, but if it takes too much time, any comments on programming technique or data structure is very much welcome. I am impementing using C++, not my most familiar language, so newbie errors aheads.</p> <p>The problem: Given this grid. An agent (or robot) can move to 4 direction, N, E, W, S.</p> <pre><code> |----|----|----|----| 3| ** | | | +1 | |----|----|----|----| 2| | x | | -1 | |----|----|----|----| 1| | | | | |----|----|----|----| 1 2 3 4 </code></pre> <p>Each time an agent (<code>**</code>) moves to a cell, it would receive a reward from that cell. The <code>+1</code> and <code>1</code> is the end state, once the agent move to those cell, the game is over. <code>x</code> is an obstacle, which bounces the agent back when being hit.</p> <p>The agent, however, has the probability to side step (p=0.1).</p> <pre><code>Sidestep (p=0.1) ↑ xx ----&gt; Intended direction (p=0.8) ↓ Sidestep (p=0.1) </code></pre> <p>The goal is find a policy that would earn the highest reward. For example, with a reward of -0.04 per cell, optimal policy is </p> <pre><code>→ → → ✗ ↑ ✗ ↑ ✗ ↑ ← ↑ ← </code></pre> <p>Where a reward of 1 would result in this policy</p> <pre><code>↓ ← ← ✗ ↓ ✗ ↓ ✗ → → ↓ ↓ </code></pre> <p>Basically the agent never wants to enter the end states since life is good.</p> <p>The extended version of Bellman equation looks like (γ) is the discounting factor</p> <pre><code>U(1,1)=−0.04+γ max[ 0.8U(1,2)+0.1U(2,1)+0.1U(1,1), (Up) 0.9U (1, 1) + 0.1U (1, 2), (Down) 0.9U (1, 1) + 0.1U (2, 1), (Left) 0.8U (2, 1) + 0.1U (1, 2) + 0.1U (1, 1) ]. (Right) </code></pre> <p>The problem is pretty similar to <a href="https://gym.openai.com/envs/FrozenLake-v0/" rel="nofollow noreferrer">https://gym.openai.com/envs/FrozenLake-v0/</a>.</p> <p>My code is at <a href="https://github.com/minhtriet/gridworld" rel="nofollow noreferrer">https://github.com/minhtriet/gridworld</a>, but I still post them here.</p> <p><code>try.cpp (Main file)</code></p> <pre><code>#include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;limits&gt; #include "Board.cpp" void read_special_states(std::fstream&amp; fp, std::vector&lt;Point&gt;&amp; states, Board&amp; board) { int n_states; int temp_x, temp_y; fp &gt;&gt; n_states; states.resize(n_states); for (auto&amp; state : states) { fp &gt;&gt; temp_x &gt;&gt; temp_y; state.x = temp_x; state.y = temp_y; board.best_policy[temp_x][temp_y] = Point(0,0); board.best_value[temp_x][temp_y] = std::numeric_limits&lt;float&gt;::lowest(); } } void init_board(Board&amp; board, char *filename) { std::fstream fp(filename); int n_row, n_col; fp &gt;&gt; n_row &gt;&gt; n_col; board.height = n_row; board.width = n_col; fp &gt;&gt; board.start_state.x &gt;&gt; board.start_state.y; fp &gt;&gt; board.reward; board.best_value = std::vector(n_col, std::vector&lt;float&gt;(n_row, board.reward)); // init to a random value to discourage staying in the same place board.best_policy = std::vector(n_col, std::vector&lt;Point&gt;(n_row, Point(0,1))); read_special_states(fp, board.end_states, board); read_special_states(fp, board.obstacles, board); for (auto i : board.end_states) { fp &gt;&gt; board.best_value[i.x][i.y]; } } int main(int argc, char *argv[]) { Board board; init_board(board, argv[1]); board.run(); return 0; } </code></pre> <p><code>Point.h</code></p> <pre><code>#include &lt;ostream&gt; struct Point { int x; int y; public: Point(); Point(int x_, int y_); std::ostream operator&lt;&lt;(const Point&amp; p) ; }; </code></pre> <p><code>Board.h</code></p> <pre><code>#include &lt;vector&gt; #include &lt;map&gt; #include &lt;queue&gt; #include "Point.cpp" class Board { private: bool is_inside(const Point&amp; location); std::queue&lt;Point&gt; schedule; public: std::vector&lt;std::vector&lt;float&gt;&gt; best_value; std::vector&lt;std::vector&lt;Point&gt;&gt; best_policy; int width; int height; std::vector&lt;Point&gt; direction{Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1)}; std::vector&lt;Point&gt; end_states; Point start_state; std::vector&lt;Point&gt; obstacles; float reward; float gamma{0.9}; float move(const Point&amp; current_loc, const Point&amp; direction); float move(const Point&amp; current_loc, const Point&amp; direction, float prob); const std::vector&lt;float&gt; probs{0.8, 0.1, 0.1}; void init(const Point&amp; start_state); int run(); }; </code></pre> <p><code>Point.cpp</code></p> <pre><code>#include "Point.h" Point::Point(): x{0}, y{0} {} Point::Point(int x_, int y_): x{x_}, y{y_} {} std::ostream &amp;operator&lt;&lt;(std::ostream&amp; os, const Point&amp; p) { if (p.x == 1 &amp;&amp; p.y == 0) return os &lt;&lt; "→"; if (p.x == -1 &amp;&amp; p.y == 0) return os &lt;&lt; "←"; if (p.x == 0 &amp;&amp; p.y == -1) return os &lt;&lt; "↑"; if (p.x == 0 &amp;&amp; p.y == 1) return os &lt;&lt; "↓"; if (p.x == 0 &amp;&amp; p.y == 0) return os &lt;&lt; "✗"; return os &lt;&lt; "(" &lt;&lt; p.x &lt;&lt; ";" &lt;&lt; p.y &lt;&lt; ")"; } </code></pre> <p><code>Board.cpp</code></p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;cmath&gt; #include "Board.h" #include "util.cpp" bool Board::is_inside(const Point&amp; location) { if ((location.x &gt;= 0) &amp;&amp; (location.y &gt;= 0) \ &amp;&amp; (location.x &lt; this-&gt;width) &amp;&amp; (location.y &lt; this-&gt;height)) return true; return false; } float Board::move(const Point&amp; current_loc, const Point&amp; direction) { float total_reward = 0; if (direction.x == 0) { total_reward += move(current_loc, Point(-1, 0), this-&gt;probs[1]); total_reward += move(current_loc, Point(1, 0), this-&gt;probs[2]); } if (direction.y == 0) { total_reward += move(current_loc, Point(0, -1), this-&gt;probs[1]); total_reward += move(current_loc, Point(0, 1), this-&gt;probs[2]); } if (!util::is_in_vector(current_loc + direction, this-&gt;end_states)) { total_reward += Board::move(current_loc, direction, this-&gt;probs[0]); total_reward *= gamma; total_reward += this-&gt;reward; } else { total_reward *= gamma; total_reward += Board::move(current_loc, direction, this-&gt;probs[0]); } return total_reward; } float Board::move(const Point&amp; current_loc, const Point&amp; direction, float prob) { Point new_loc = current_loc + direction; // edge cases if (util::is_in_vector(new_loc, this-&gt;obstacles) || !is_inside(new_loc)) { return prob * best_value[current_loc.x][current_loc.y]; } if (util::is_in_vector(new_loc, this-&gt;end_states)) { return prob * best_value[new_loc.x][new_loc.y]; } // end of edges cases return prob * this-&gt;best_value[new_loc.x][new_loc.y]; } int Board::run() { for (int i = 0; i &lt; 10; i++) { this-&gt;schedule.push(start_state); std::vector&lt;Point&gt; visited; while (this-&gt;schedule.size() &gt; 0) { Point p = schedule.front(); this-&gt;schedule.pop(); visited.insert(visited.begin(), p); float result, best_result = std::numeric_limits&lt;float&gt;::lowest(); Point best_direction; for (auto direction : direction) { Point new_loc = p + direction; if (this-&gt;is_inside(new_loc)) { if (!util::is_in_vector(new_loc, visited) &amp;&amp; (!util::is_in_vector(new_loc, obstacles)) &amp;&amp; (!util::is_in_vector(new_loc, end_states))) { schedule.push(new_loc); } } result = move(p, direction); if (result &gt; best_result) { best_result = result; best_direction = direction; } } best_value[p.x][p.y] = best_result; best_policy[p.x][p.y] = best_direction; } util::print&lt;float&gt;(best_value); util::print&lt;Point&gt;(best_policy); } return 0; } </code></pre> <p><code>util.cpp</code></p> <pre><code>#include&lt;vector&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;type_traits&gt; #include &lt;limits&gt; namespace util { template &lt;typename T&gt; bool is_in_vector(const T&amp; location, const std::vector&lt;T&gt;&amp; to_check) { if (std::find(to_check.begin(), to_check.end(), location) != to_check.end()) { return true; } return false; } template &lt;typename T&gt; void print(const std::vector&lt;std::vector&lt;T&gt;&gt;&amp; matrix) { std::cout &lt;&lt; std::setprecision(3) &lt;&lt; std::fixed; for (int j=0; j &lt; matrix[0].size(); j++) { for (int i=0; i &lt; matrix.size(); i++) { if (matrix[i][j] == std::numeric_limits&lt;T&gt;::lowest()) { std::cout &lt;&lt; "✗ "; continue; } std::cout &lt;&lt; matrix[i][j] &lt;&lt; " "; } std::cout &lt;&lt; "\n"; } } } Point operator+(const Point&amp; p0, const Point&amp; p1) { return Point(p1.x + p0.x, p1.y + p0.y); } bool operator==(const Point&amp; p0, const Point&amp; p1) { return (p1.x == p0.x) &amp;&amp; (p1.y == p0.y); } bool operator&lt;(const Point&amp; p0, const Point&amp; p1) { return (p1.x &lt; p0.x) || (p1.y &lt; p0.y); } </code></pre> <p>EDIT: The code compiles and give out correct result for the policy. For the values (or return) calculation, it is consistency 0.05 higher than the expected value across the board (and I am not sure if I should investigate on this).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:27:40.450", "Id": "435245", "Score": "1", "body": "Does this actually compile and run for you, and provide expected output? Also please specify what operating system and compiler you are using." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T04:47:53.733", "Id": "435259", "Score": "0", "body": "Hi @pacmaninbw please see my edit at the end" } ]
[ { "body": "<p><strong>Program and File Structure</strong><br>\nAs a general rule C++ source files (.cpp) are not included in other C++ source files, each .cpp file is compiled separately and the resulting object files are linked together by the linker. The benefits of this are that the entire program does not need to be rebuilt when a .cpp file is modified, just the module that was modified and then the program is re-linked. This allows bug fixes and feature requests to be implemented without rather long build times. If the program is implemented in shared libraries it means just a single library may need to be updated for bug fixes to be delivered to users.</p>\n\n<p>In some cases very simple classes may be implemented using only a header file.</p>\n\n<p>One of the problems with including source files in other source files is that it can lead to multiple definitions of objects or functions at link time. An example would be using the <code>util.cpp</code> in multiple other source files.</p>\n\n<p>A second possible problem with including source files in other source files is that the compile time for the final source file will increase.</p>\n\n<p>In C++ classes are generally implemented as a header file (.h or .hpp) and a C++ source file pair. The structure and public interface of the class are in the header file and in most cases the internal implementation of the class is in the C++ source file. Public interfaces are expected to not change often but internal implementation can change as often as necessary.</p>\n\n<p>In <code>try.cpp</code> <code>board.cpp</code> is included, this ends up including <code>point.cpp</code> and <code>util.cpp</code>, the problem with this is that the <code>main()</code> function only needs to know about the <code>Board</code> class, it does not need to know about the <code>Point</code> struct or the items in <code>util.cpp</code>.</p>\n\n<p>Rather than using <code>compile.sh</code> to build the project it might be better to use an Integrated Development Environment (IDE) such as <a href=\"https://stackoverflow.com/questions/2487931/llvm-c-ide-for-windows\">Eclipse CDT</a> or <code>Visual Studio</code>. In both cases the development environments create the build process for the program as well as providing a programming and debugging interface. <a href=\"https://www.eclipse.org/downloads/packages/\" rel=\"nofollow noreferrer\">Eclipse</a> is an open source project and can be downloaded for free, there is a free version of <code>Visual Studio</code> as well. If you are developing on <code>Linux</code> <code>Eclipse</code> is part of the development options. Programming and debugging using an IDE is much easier, the code is scanned as it is entered which reduces compile time errors. In most IDE's you can select the C++ standard you want to work with (C+=11, C++14, C++17, ...).</p>\n\n<p><strong>Class and Object Initialization</strong><br>\nIn <code>Board.h</code> there is a public method called <code>void init(const Point&amp; start_state);</code>. This function is not defined or implemented anywhere which may cause linking errors in some build environments. In <code>try.cpp</code> there is instead a function called <code>void init_board(Board&amp; board, char *filename)</code>. Classes should handle their own initialization in their constructors. Class constructors can use sub functions as necessary. A function such as <code>init_board()</code> forces the knowledge of internals of the board class on outside structures and forces members of the <code>Board</code> class to be declared <code>public</code> where the might be better declared as either <code>protected</code> or <code>private</code>. examples of members of <code>Board</code> that should be <code>private</code> or <code>protected</code> are <code>std::vector&lt;std::vector&lt;float&gt;&gt; best_value;</code> and <code>std::vector&lt;std::vector&lt;Point&gt;&gt; best_policy;</code>. The function <code>void read_special_states(std::fstream&amp; fp, std::vector&lt;Point&gt;&amp; states, Board&amp; board)</code> in <code>try.cpp</code> might better be a member function of the <code>Board</code> class. This would reduce the number of parameters to the function and might be called by the <code>Board</code> constructor. Note there can be multiple <code>Board</code> constructors, one that takes a file name and one that doesn't. A safer way to do this might be to create the file pointer in <code>main()</code> test to see that the file exists and then pass the file pointer to the <code>Board</code> constructor.</p>\n\n<p><strong>Error Checking, Handling and Reporting</strong><br>\nThe <code>main()</code> program assumes that there is at least one command line argument, this is not safe there should be a function to parse the command line called by <code>main()</code>. In the function <code>init_board()</code> there is no test that there is a file or that it can be opened, this is also not a safe practice. In either of the functions the program can fail without the user knowing because of a simple user error, either not entering a file name or entering the wrong file name. A good practice is to check user input and provide meaningful error messages when user input is incorrect.</p>\n\n<p><strong>The Use of this to Access Members</strong><br>\nIn <code>Board.cpp</code> the <code>this</code> pointer is used many times, unlike PHP and some other languages in C++ there is generally no reason to use the <code>this</code> pointer. When an object is compiled in a .cpp file the compiler will first look for local symbols within the class.</p>\n\n<p><strong>Code Complexity</strong><br>\nIn the <code>util.cpp</code> file the function <code>is_in_vector()</code> could be simplified to:</p>\n\n<pre><code>template &lt;typename T&gt;\nbool is_in_vector(const T&amp; location, const std::vector&lt;T&gt;&amp; to_check) {\n return (std::find(to_check.begin(), to_check.end(), location) != to_check.end());\n}\n</code></pre>\n\n<p><strong>Public Versus Private in struct</strong><br>\nIn C++ in a struct <a href=\"https://stackoverflow.com/questions/1247745/default-visibility-of-c-class-struct-members\">all fields are public by default</a>. In <code>Point.h</code> there is no reason to have <code>public</code> for the members <code>Point()</code>, <code>Point(int x_, int y_)</code> and <code>std::ostream operator&lt;&lt;(const Point&amp; p)</code>. If the members <code>x</code> and <code>y</code> should be private, you can either specify that or make the struct into a class. Making <code>Point</code> a class might simplify the code in <code>std::ostream operator&lt;&lt;(const Point&amp; p)</code> since it would no longer be necessary to add p as an argument. It might be better to move the <code>Point</code> operators in <code>util.cpp</code> into either <code>Point.h</code> or <code>Point.cpp</code>.</p>\n\n<p><strong>Magic Number</strong><br>\nIt is not clear what the numeric value 10 represents in the for loop in <code>Board::run()</code>. It might be better to create a symbolic constant somewhere in the program, or for <code>Board</code> to have a member size_t variable that is used in that loop.</p>\n\n<p><strong>Unnecessary Include Files</strong><br>\nBoard.cpp includes cassert and cmath, but they are not used within the file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:24:28.573", "Id": "224418", "ParentId": "224364", "Score": "3" } } ]
{ "AcceptedAnswerId": "224418", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T20:34:16.743", "Id": "224364", "Score": "6", "Tags": [ "c++" ], "Title": "Basic Reinforcement learning in a grid environment" }
224364
<p>I am writing a program that allows me to find all possible pairs of square numbers including duplicates. We can also assume the array elements to be of positive integers only. e.g an array of {5,25,3,25,4,2,25} will return <code>[5,25],[5,25],[2,4],[5,25]</code> since 25 is square of 5.</p> <p>Currently, I am using a nested for loop to find the squares. I'm just wondering if there is a better way to do this?</p> <pre><code>import java.lang.Math.*; public static void main(String args[]) { int arr[] = {5,25,3,25,4,2,25}; String s = ""; for(int i =0; i &lt; arr.length;i++) { for(int j = 0;j &lt; arr.length;j++) { if(Math.sqrt(arr[i]) == arr[j]) { s += arr[j] + "," + arr[i] + " "; } } } System.out.println(s); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:11:48.647", "Id": "435391", "Score": "0", "body": "Are the duplicates in the result intentional?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T20:04:20.690", "Id": "435394", "Score": "0", "body": "Yes, they are intentional. I've updated my post." } ]
[ { "body": "<h2>Avoid string addition</h2>\n\n<p>String addition is not good for building up strings from many pieces inside of loops. You should use <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a> instead.</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n\n// ... omitted ...\n\n sb.append(arr[j]).append(',').append(arr[j]).append(' ');\n\n// ... omitted ...\n\nString s = sb.toString();\nSystem.out.println(s);\n</code></pre>\n\n<h2>Avoid square-roots</h2>\n\n<p>Checking <span class=\"math-container\">\\$\\sqrt x == y\\$</span> is ... dangerous.</p>\n\n<ul>\n<li>The results of the square-root are a float-point number, and may not exactly equal your integer value.</li>\n<li>If you have a negative number in your list, <code>Math.sqrt()</code> will raise an exception, yet <code>{ -5, 25 }</code> is a valid pair.</li>\n</ul>\n\n<p>Testing <code>x == y*y</code> is safer, as long as there is no danger of <code>y*y</code> overflowing.</p>\n\n<h2>Avoid repeated calculations</h2>\n\n<pre><code>for(int i =0; i &lt; arr.length;i++) {\n for(int j = 0;j &lt; arr.length;j++) {\n if(Math.sqrt(arr[i]) == arr[j]) {\n ...\n</code></pre>\n\n<p>In the inner-loop, <code>i</code> is constant. Yet you are computing <code>Math.sqrt(arr[i])</code> every time through the loop. The value should not be changing, so you could compute it once, outside of the inner loop.</p>\n\n<pre><code>for(int i =0; i &lt; arr.length;i++) {\n double sqrt_arr_i = Math.sqrt(arr[i]);\n for(int j = 0;j &lt; arr.length;j++) {\n if(sqrt_arr_i == arr[j]) {\n ...\n</code></pre>\n\n<h2>Pairs need distinct indices</h2>\n\n<p>If your input contains a single <code>0</code> or <code>1</code>, it will mistakenly report that it has found a pair, since <code>0 == 0*0</code> and <code>1 == 1*1</code>. You can protect against this by adding <code>i != j &amp;&amp;</code> to your test.</p>\n\n<p>If the input contains two <code>0</code>'s (or two <code>1</code>'s), your algorithm will emit 4 pairs: <code>[first,first], [first,second], [second,first], and [second,second]</code>. Adding the <code>i != j</code> guard will eliminate the first and last of those pairs, but it will still declare two pairs: <code>[first,second], [second,first]</code> since <code>first² = second</code> and <code>first = second²</code> would both be true. You'd have to weight in on whether this would be two distinct pairs or not.</p>\n\n<h2>Formatting</h2>\n\n<p>Consistent and liberal use of white space is always recommended. Add white space after every semicolon inside of <code>for(...)</code>, on both sides of operators (<code>i = 0</code> not <code>i =0</code>), and after every comma in <code>{5,25,3,25,4,2,25}</code>.</p>\n\n<hr>\n\n<p>With the above recommendations, your function body would become:</p>\n\n<pre><code>int arr[] = { 5, 25, 3, 25, 4, 2, 25 };\nStringBuilder sb = new StringBuilder();\n\nfor(int i = 0; i &lt; arr.length; i++)\n{\n for(int j = 0; j &lt; arr.length; j++)\n {\n if(arr[i] == arr[j] * arr[j])\n {\n sb.append(arr[j]).append(',').append(arr[i]).append(\" \");\n }\n }\n}\n\nString s = sb.toString();\nSystem.out.println(s);\n</code></pre>\n\n<hr>\n\n<h2>Additional considerations</h2>\n\n<p>You have a trailing space in your resulting string. There are several tricks you can use to remove it. However, an interesting alternative is to use <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/StringJoiner.html\" rel=\"nofollow noreferrer\"><code>StringJoiner</code></a>:</p>\n\n<pre><code>StringJoiner sj = new StringJoiner(\" \");\n\n// ... omitted ...\n\n sj.add(arr[j] + \",\" + arr[j]);\n\n// ... omitted ...\n\nString s = sj.toString();\nSystem.out.println(s);\n</code></pre>\n\n<p>When <code>StringJoiner</code> adds the second and successive strings, it automatically adds the <code>delimiter</code> specified in the constructor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:30:05.633", "Id": "435235", "Score": "1", "body": "A binary search requires a sorted list. If you are willing to sort your list, \\$O(n \\log n)\\$, then you are better off moving two index (`i` & `j`) through the list from one end to the other. If `arr[i] > arr[j]*arr[j]`, increase `j`. If `arr[i] < arr[j]*arr[j]`, then increase `i`. *Note*: you'll need a different approach to handle negative numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:45:10.770", "Id": "435238", "Score": "0", "body": "However, if i were to sort ( O(n^2) ) and then uses binary search ( O(nlogn) ), the performance of the new algorithm will be slower than what my code ( O(n^2) ) is doing now right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:49:00.967", "Id": "435239", "Score": "0", "body": "[`Arrays.sort(int[])`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Arrays.html#sort(int%5B%5D)) is \\$O(n \\log n)\\$, not \\$O(n^2)\\$. If you sort, and the loop over every index (\\$O(n)\\$), and did a binary search (\\$O(\\log n)\\$), you'd end up with \\$O(n \\log n)\\$. But sort & n binary searches is \\$O(n \\log n + n \\log n)\\$ where as sort & a single pass scan is \\$O(n \\log n + n)\\$, so slightly faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:52:18.457", "Id": "435240", "Score": "0", "body": "Alright, thank you so much for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T07:39:02.530", "Id": "435283", "Score": "0", "body": "@AJNeufeld: Your statement regarding the string addition is since JDK 9/JEP 280 not correct anymore. Read e.g.: https://dzone.com/articles/jdk-9jep-280-string-concatenations-will-never-be-t Nowadays the long despised + operator for string concatenation is recommended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:00:30.933", "Id": "435314", "Score": "1", "body": "@JoachimRohde Interesting article. But original JEP doesn't state that anything will be changed regarding loops. Btw, found this interesting repo: https://github.com/mtumilowicz/java9-string-concat (didn't tested it though)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T18:37:58.333", "Id": "435386", "Score": "0", "body": "@AJNeufeld Caveat: in practice, algorithms with worse asymptotic time complexities perform better over small datasets than algorithms with better asymptotic time complexities. Classic examples are 1) linear search through a small array can be faster than a hash lookup into a set with the same size, 2) insertion sort can be faster over small arrays than many `O(n*log(n))` algorithms like quick sort" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T18:55:14.423", "Id": "435388", "Score": "0", "body": "@Alexander These comments started with a comment asking how to speed up the algorithm over larger datasets, and specifically if a binary search could help. That comment was unfortunately deleted. You'll notice my answer-post did not change the OP's original double for-loop into anything else, as the input array was only 7 elements long. If the OP needs help adapting the code to a more efficient algorithm for larger datasets, I would happily help the OP on Stack Overflow. On the other hand, if they successfully write it, I would happily review it here on Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:08:50.913", "Id": "435390", "Score": "0", "body": "@AJNeufeld Makes sense!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:13:44.073", "Id": "224367", "ParentId": "224365", "Score": "8" } }, { "body": "<p>rather than writing all the loops by hand, can I suggest you use a different data structure? (I'm a C# programmer, hopefully my code will be easy to translate into Java.)</p>\n\n<p>If the output order doesn't matter and you aren't interested in duplicates, you could get away with something like this:</p>\n\n<pre><code>var arr = new [] {5, 25, 3, 25, 4, 2, 25};\nvar set = new HashSet&lt;int&gt;(arr);\nvar roots = arr.Where(x =&gt; set.Contains(x * x));\nforeach (var root in roots) Console.WriteLine($\"{root}, {root * root}\");\n</code></pre>\n\n<p>The set construction cost is <span class=\"math-container\">\\$O(n \\log n)\\$</span>, which dominates the running time here (compare this to the nested loops approach which will cost <span class=\"math-container\">\\$O(n^2)\\$</span>). Also, as @AJNeufeld points out, you definitely want to avoid calculating square roots when you can get away with simple integer multiplication.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T05:06:33.410", "Id": "435260", "Score": "1", "body": "`The set construction cost is O(n log n)` docs.microsoft.com: `This constructor is an O(n) operation`. `If the output order doesn't matter`good catch, I might have missed that one. `… and you aren't interested in duplicates` big if, judging from the example output of three pairs given one instance of `5` and three instances of its square." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T06:26:09.837", "Id": "435272", "Score": "0", "body": "You're right about the set construction being O(n), I was thinking of persistent data structures rather than hash tables -- old habits. If you need duplicates, you can use this one-liner to calculate frequencies:\n`var freqs = arr.OrderBy(x => x).GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T07:49:26.333", "Id": "435284", "Score": "0", "body": "Corresponding Java code could look like [this](https://tio.run/##bU/LTsMwEDzHX7GqVClGrQ88Ti2VOCCBBFxyRBzcxE03xE6w10VV1Z/iE/ixsCEBiYdka1czO7M7ld7peVU8dx3atvEEFQMqEtbqynu9Dwvxh7jRYZsZ@of5REUb1zXmkNc6BLjX6MRBJCMYSBOXXYMFWKbSjDy68vEJtC@DBJ5Mbh2Z0njGXLRr4wNcwgEuZnDK/2wo51z6Do4LVvDe5ahaQXT4Es3Dt9SZVxhPXq7SIZXS4Q4DpeMCKXuXH0IVyBttU6k2WJPxKcL8l7fKG0ecITB3AigleySJ2jT@WufbQZDtAxmrmkiq5aBUfyXux6ymdDIt3t/4ymkxmQHyG6z6g45CHLvuAw)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T08:49:21.457", "Id": "435296", "Score": "0", "body": "Thank you all for the respond. Just wondering how do you guys calculate the run time complexity of in-built collections such as HashSet? Do we just take it from the documentation manual or are we able to calculate it by analysing the algorithm just like a nested for loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:10:14.653", "Id": "435315", "Score": "0", "body": "@JanB generally, you dont. You know the complexity of the ADT which language-independent (found on wiki) and hope any widely-spread implementation is the optimal one." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T23:23:11.987", "Id": "224373", "ParentId": "224365", "Score": "5" } }, { "body": "<p>From eyeballing it, your code doesn't quite produce the format shown after <code>will return</code> (pairs separated by <code>\" \"</code> instead of <code>\"], [\"</code>).<br>\nAn alternative to building a <code>String</code> and then printing it is printing its parts immediately -<br>\nI'd define a method like <code>long squares(Appendable destination)</code>:<br>\nworks with both <code>StringBuilder</code> and <code>OutputStream</code>. (Returning the count of pairs.)</p>\n\n<hr>\n\n<p>Just a sketch how to reduce run time machine operations: </p>\n\n<ul>\n<li>determine <code>max</code> as the maximum input value (terminate with no pairs if negative), and maxRoot = floor(sqrt(<code>max</code>+1))</li>\n<li>establish the count of every number from -maxRoot to maxRoot<br>\n(<strong><em>assuming</strong> [5, 25] was to be reported six times if another five was in the example input</em> -<br>\nspecifying required output by example is hard, by <em>a single</em> example sub-optimal)</li>\n<li>for every non-negative input number that has integer roots in the input, report as many pairs for each of its roots as there are occurrences of that root<br>\n(<strong><em>assuming</strong> the order didn't matter between, say, <code>[2,4]</code> and <code>[-2,4]</code></em>. \nIf that mattered, too, you'd need to keep positions instead of counts (order on first lookup as a root), increasing <em>additional space</em> to O(n))</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T09:02:17.717", "Id": "435297", "Score": "0", "body": "Thank you for your advice. However, may i ask how does establishing a count reduces run time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:55:52.040", "Id": "435393", "Score": "0", "body": "When \"in phase 3\" you find a root of some square, you don't need to consult the input array to output the appropriate number of pairs if you got that count. (You can do similar (and more, see *if order of negative and positive roots mattered*) with a set of tuples (`Map<Integer, List<Integer>>`).)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T20:11:51.707", "Id": "435395", "Score": "0", "body": "Ahh makes sense.. Thank you for the reply!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T04:39:57.193", "Id": "435413", "Score": "0", "body": "(Coding this in Java looked, hm, verbose. I can see where [AJNeufeld] may have got the idea to use streams.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T06:09:48.593", "Id": "224383", "ParentId": "224365", "Score": "2" } }, { "body": "<p>My answer is additive to the others; I'm not going to repeat points already made.</p>\n\n<h1>1. Nitpick: prefer <code>int[] arr</code> over <code>int arr[]</code></h1>\n\n<p>The \"arrayness\" (<code>[]</code>) has more to do with the type than it does the variable name, so it's better to keep them together. Not to appeal to authority, but <a href=\"https://google.github.io/styleguide/javaguide.html#s4.8.3-arrays\" rel=\"nofollow noreferrer\">Google's style guide also suggests this.</a></p>\n\n<h1>2. Avoid \"for\" loops where \"for-each\" loops are applicable.</h1>\n\n<p>You never really need the indices <code>i</code> and <code>j</code>, aside from using them to get the elements. Just avoid them altogether:</p>\n\n<pre><code>for (int a : arr) {\n for (int b : arr) {\n if (Math.sqrt(a) == b) {\n s += a + \",\" + b + \" \";\n }\n }\n}\n</code></pre>\n\n<p>Even if a <code>for-each</code> loop wasn't available (e.g. in C), I would still recommend extracting repeated terms (<code>arr[i]</code>, <code>arr[j]</code>) to a variable.</p>\n\n<h1>3. Don't intermix computation of a result, and the printing of the result</h1>\n\n<p>I would advise against this cross-over of computing and printing that you're doing.</p>\n\n<p>Perhaps you want to use this list as an input to some other process. Parsing the string back would be both inconvenient and inefficient. It's better to make systems that shuttle around machine-usable values (e.g. a list of numbers) as much as possible, and only formatting and printing them as the last possible moment.</p>\n\n<p>Here's a first approximation:</p>\n\n<pre><code>import java.util.List;\nimport java.util.ArrayList;\n\nclass Untitled {\n public static void main(String[] args) {\n int arr[] = {5,25,3,25,4,2,25};\n\n List&lt;Integer&gt; discoveredRoots = new ArrayList&lt;&gt;();\n for (int a : arr) {\n for (int b : arr) {\n if (Math.sqrt(a) == b) {\n discoveredRoots.add(b);\n }\n }\n }\n\n String s = \"\";\n for (int root : discoveredRoots) {\n int perfectSquare = root * root;\n s += root + \",\" + perfectSquare + \" \";\n }\n System.out.println(s);\n }\n}\n</code></pre>\n\n<h1>4. Split off distinct chunks of code</h1>\n\n<p>Now we have two distinct chunks of our code within the <code>main</code> function. These are clearly two new functions, just waiting to get out:</p>\n\n<pre><code>class Untitled {\n public static void main(String[] args) {\n int[] input = {5,25,3,25,4,2,25};\n\n List&lt;Integer&gt; discoveredRoots = findPerfectSquarePairs(input);\n String formattedResult = formatPerfectSquarePairs(discoveredRoots);\n System.out.println(formattedResult);\n }\n\n\n // Returns a stream of factors whose squares (which are perfect squares)\n // were found in `input`.\n static List&lt;Integer&gt; findPerfectSquarePairs(int[] input) {\n List&lt;Integer&gt; discoveredRoots = new ArrayList&lt;&gt;();\n\n for (int a : input) {\n for (int b : input) {\n if (Math.sqrt(a) == b) {\n discoveredRoots.add(b);\n }\n }\n }\n\n return discoveredRoots;\n }\n\n static String formatPerfectSquarePairs(List&lt;Integer&gt; discoveredRoots) {\n String s = \"\";\n\n for (Integer root : discoveredRoots) {\n int perfectSquare = root * root;\n s += root + \",\" + perfectSquare + \" \";\n }\n\n return s;\n }\n}\n</code></pre>\n\n<p>These functions have the added benefit of being <a href=\"https://en.wikipedia.org/wiki/Pure_function\" rel=\"nofollow noreferrer\"><em>pure</em></a>. They don't do anything besides process over their parameters, and return a value (e.g. they don't print anything directly).\n * The lack of side-effects make these methods trivial to unit unit test. Just provide some hard-coded parameters, and assert that their equality to some hard-coded results.\n * Their separation make isolation trivial. You can test printing without processing, and processing without printing.</p>\n\n<h1>5. Optimize the internals of <code>findPerfectSquarePairs</code> and <code>formatPerfectSquarePairs</code>.</h1>\n\n<p>Now that we've \"discovered\" these two functions, we can improve each component separately. We're able to lean on unit tests to ensure we didn't break anything.</p>\n\n<p>First, we can use a <code>Set</code> to remember which numbers we've seen, without having to do a <code>O(input.length * 2)</code> search over every possible pair of numbers. We don't even have to put every number in the set, only those which are perfect squares.</p>\n\n<pre><code> /*\n import static java.lang.Math.pow;\n import static java.lang.Math.sqrt;\n import static java.lang.Math.round;\n */\n\n static boolean isPerfectSquare(int i) {\n if (i &lt; 0) return false; // negative numbers can't be perfect squares\n\n double root = sqrt(i);\n double squared = pow(round(root), 2);\n return round(squared) == i;\n }\n static List&lt;Integer&gt; findPerfectSquarePairs(int[] input) {\n Set&lt;Integer&gt; uniqueNumbers = new HashSet&lt;&gt;();\n for (int a: input) {\n if (isPerfectSquare(a)) uniqueNumbers.add(a);\n }\n\n List&lt;Integer&gt; discoveredRoots = new ArrayList();\n\n for (int a : uniqueNumbers) {\n int perfectSquare = a * a;\n if (uniqueNumbers.contains(perfectSquare)) {\n discoveredRoots.add(a);\n }\n }\n\n return new ArrayList(discoveredRoots);\n }\n</code></pre>\n\n<p>All of these loops are just a stream screaming to get out. Let's do that:</p>\n\n<pre><code> /*\n import static java.lang.Math.pow;\n import static java.lang.Math.sqrt;\n import static java.lang.Math.round;\n\n import static java.util.stream.Collectors.toSet;\n import static java.util.stream.Collectors.toList;\n */\n\n static List&lt;Integer&gt; findPerfectSquarePairs(int[] input) {\n Set&lt;Integer&gt; perfectSquares = Arrays.stream(input)\n .filter(Untitled::isPerfectSquare)\n .boxed()\n .collect(toSet());\n\n List&lt;Integer&gt; discoveredRoots = perfectSquares.stream()\n .filter (root -&gt; {\n int perfectSquare = root * root;\n return perfectSquares.contains(perfectSquare);\n })\n .collect(toList());\n\n return discoveredRoots;\n }\n</code></pre>\n\n<p>Next we can turn our attention to <code>formatPerfectSquarePairs</code>. It too could be simplified with a stream:</p>\n\n<pre><code> static String formatPerfectSquarePairs(List&lt;Integer&gt; discoveredRoots) {\n return discoveredRoots.stream()\n .map(root -&gt; {\n int perfectSquare = root * root;\n return root + \",\" + perfectSquare;\n })\n .collect(joining(\" \"));\n }\n</code></pre>\n\n<h1>6. Redesign the interaction of <code>findPerfectSquarePairs</code> and <code>formatPerfectSquarePairs</code></h1>\n\n<p>At this point, we can realize that both of these methods use streams internally, but don't communicate to each other using streams. <code>findPerfectSquarePairs</code> unnecessarily collects results into a <code>List&lt;Integer&gt;</code>, only for <code>formatPerfectSquarePairs</code> to <code>stream()</code> its elements. This is unnecessary.</p>\n\n<p>Returning a <code>Stream&lt;Integer&gt;</code> would use less memory (there's no need to concurrently store all <code>discoveredRoots</code> in memory), and would be more flexible. If consumers want a <code>List&lt;Integer&gt;</code>, they can <code>.collect(toList())</code> it themselves. But now we've given them the ability to iterate over the stream, to <code>reduce</code> it, <code>map</code> it, etc.</p>\n\n<pre><code> static Stream&lt;Integer&gt; findPerfectSquarePairs(int[] input) {\n Set&lt;Integer&gt; perfectSquares = Arrays.stream(input)\n .filter(Untitled::isPerfectSquare)\n .boxed()\n .collect(toSet());\n\n return perfectSquares.stream()\n .filter (root -&gt; {\n int perfectSquare = root * root;\n return perfectSquares.contains(perfectSquare);\n });\n }\n\n static String formatPerfectSquarePairs(Stream&lt;Integer&gt; discoveredRoots) {\n return discoveredRoots\n .map(root -&gt; {\n int perfectSquare = root * root;\n return root + \",\" + perfectSquare;\n })\n .collect(joining(\" \"));\n }\n</code></pre>\n\n<h1>7. Fix the formatting of the output</h1>\n\n<p>...to match your desired <code>[5,25],[5,25],[2,4],[5,25]</code> style:</p>\n\n<pre><code> static String formatPerfectSquarePairs(Stream&lt;Integer&gt; discoveredRoots) {\n return discoveredRoots\n .map(root -&gt; {\n int perfectSquare = root * root;\n return root + \",\" + perfectSquare;\n })\n .map(s -&gt; \"[\" + s + \"]\")\n .collect(joining(\",\"));\n }\n</code></pre>\n\n<h1>Final result</h1>\n\n<pre><code>import java.util.Set;\nimport java.util.Arrays;\n\nimport java.util.stream.Stream;\n\nimport static java.lang.Math.pow;\nimport static java.lang.Math.sqrt;\nimport static java.lang.Math.round;\n\nimport static java.util.stream.Collectors.toSet;\nimport static java.util.stream.Collectors.joining;\n\nclass Untitled {\n public static void main(String[] args) {\n int[] input = {5,25,3,25,4,2,25};\n\n Stream&lt;Integer&gt; discoveredRoots = findPerfectSquarePairs(input);\n String formattedResult = formatPerfectSquarePairs(discoveredRoots);\n System.out.println(formattedResult);\n }\n\n static boolean isPerfectSquare(int i) {\n if (i &lt; 0) return false; // negative numbers can be perfect squares\n\n double root = sqrt(i);\n double squared = pow(round(root), 2);\n return round(squared) == i;\n }\n\n\n static Stream&lt;Integer&gt; findPerfectSquarePairs(int[] input) {\n Set&lt;Integer&gt; perfectSquares = Arrays.stream(input)\n .filter(Untitled::isPerfectSquare)\n .boxed()\n .collect(toSet());\n\n return perfectSquares.stream()\n .filter (root -&gt; {\n int perfectSquare = root * root;\n return perfectSquares.contains(perfectSquare);\n });\n }\n\n static String formatPerfectSquarePairs(Stream&lt;Integer&gt; discoveredRoots) {\n return discoveredRoots\n .map(root -&gt; {\n int perfectSquare = root * root;\n return root + \",\" + perfectSquare;\n })\n .map(s -&gt; \"[\" + s + \"]\")\n .collect(joining(\",\"));\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T04:13:11.850", "Id": "435411", "Score": "0", "body": "Can you try and doc-comment what it is your `findPerfectSquarePairs()` returns? I end up with something like *stream of perfect squares from the input the perfect square of which appeared in the input, too*, and the output looks the type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T04:51:30.687", "Id": "435414", "Score": "0", "body": "@greybeard I couldn't find a good name for it. Ideally, I would have like to return tuple of two integers (\"root\" and \"square\"). I could make a POJO class to store them, but it's just way too verbose, so I didn't bother. Instead, the method only returns the roots, and any consumer can calculate the perfect square for themselves by just squaring it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T05:51:11.027", "Id": "435418", "Score": "0", "body": "(Funny coincidence lamenting verbosity) The problem is not just the name or documenting the return value: it is the return value, too, and the way it is generated. (Did you try running it?) (Why on earth return (ordered) tuples where one element can be derived from the other? That said, in Java you can still use an array for a homogeneous tuple - pity the notation is clumsy but in initialisers.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T06:10:02.117", "Id": "435419", "Score": "0", "body": "I did run it, yes. What's the issue, I'm not catching on. \"That said, in Java you can still use an array for a homogeneous tuple - pity the notation is clumsy but in initialisers.\" Yeah, I was tempted to do it, but it's really quite ugly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T17:33:07.537", "Id": "435462", "Score": "0", "body": "What output do you get for the array from the question? I get an empty output; more (`[4,16],[25,625]`) if I add `, 16, 625` to the input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T02:07:10.370", "Id": "436039", "Score": "0", "body": "Down-voted for not defending suggesting code not giving the output from the example in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T02:14:55.293", "Id": "436040", "Score": "0", "body": "I'm on mobile, but I got a correct (but deduped) result. I might have made a copy/paste error or something from pasting in all these variants. What did you get, and for which code snippet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T21:14:51.867", "Id": "436249", "Score": "0", "body": "I get an empty output for the code presented as *final result*. And the cause I presume is there right in the first attempt to code a non-screaming `findPerfectSquarePairs()`. (`I did run it, yes.` - What did you get, and for which code snippet? )" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T20:17:35.903", "Id": "224438", "ParentId": "224365", "Score": "0" } }, { "body": "<p>Consider building a different data structure. </p>\n\n<pre><code>Map&lt;Integer, Integer&gt; valueCounts = new HashMap&lt;&gt;();\nfor (int element : arr) {\n Integer count = valueCounts.getOrDefault(element, 0);\n valueCounts.put(element, count + 1);\n}\n</code></pre>\n\n<p>Now we know how many times each element appears in the data. So we can just </p>\n\n<pre><code>Map&lt;Integer, Integer&gt; results = new HashMap&lt;&gt;();\nfor (Map.Entry&lt;Integer, Integer&gt; valueCount : valueCounts.entrySet()) {\n int square = valueCount.getKey() * valueCount.getKey();\n int count = valueCounts.getOrDefault(square, 0);\n\n if (count &gt; 0) {\n results.put(valueCount.getKey(), valueCount.getValue() * count);\n }\n}\n</code></pre>\n\n<p>This tells us how many pairs there are without actually counting them. It only counts the elements (in the first block). </p>\n\n<p>Your original was <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>. This version is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. You were using nested loops, where this uses sequential loops. </p>\n\n<p>Note: I haven't tested this so beware of typos, etc. </p>\n\n<p>I separated generation from display. You'll still have to generate the display string. If it seems like we're missing part of the pair, remember that the second part is always the square of the first part. You can just generate it as you go. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T23:29:10.607", "Id": "224444", "ParentId": "224365", "Score": "1" } } ]
{ "AcceptedAnswerId": "224367", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T20:41:08.170", "Id": "224365", "Score": "7", "Tags": [ "java", "algorithm", "array" ], "Title": "Finding all possible pairs of square numbers in an array" }
224365
<p>I am sharing my Bowling Game Score Kata made in Java, it is available for whoever wants to code review it. I appreciate any comments.</p> <pre><code>class BowlingGameScore { private int[] pinsKnockedDown = new int[21]; private int currentRoll = 0; void roll(int pinsKnockedDown) { this.pinsKnockedDown[currentRoll++] = pinsKnockedDown; } int score() { int totalScore = 0; int rollNumber = 0; for (int frameNumber = 0; frameNumber &lt; 10; frameNumber++) { int frameScore; if (isSpare(rollNumber)) { frameScore = 10 + getSpareBonus(rollNumber); rollNumber += 2; } else if (isStrike(pinsKnockedDown[rollNumber])) { frameScore = 10 + getStrikeBonus(rollNumber); rollNumber++; } else { frameScore = pinsKnockedDown[rollNumber] + pinsKnockedDown[rollNumber + 1]; rollNumber += 2; } totalScore += frameScore; } return totalScore; } private int getStrikeBonus(int roll) { return pinsKnockedDown[roll + 1] + pinsKnockedDown[roll + 2]; } private boolean isStrike(int roll) { return roll == 10; } private int getSpareBonus(int roll) { return pinsKnockedDown[roll + 2]; } private boolean isSpare(int roll) { return pinsKnockedDown[roll] + pinsKnockedDown[roll + 1] == 10; } } </code></pre> <p>And its tests:</p> <pre><code>class BowlingGameScoreTest { private BowlingGameScore game; @BeforeEach void setUp() { game = new BowlingGameScore(); } @Test void game_no_pins_get_hit() { rollMany(0, 20); Assertions.assertEquals(0, game.score()); } @Test void game_just_1_pin_get_hit() { rollMany(1, 20); Assertions.assertEquals(20, game.score()); } @Test void game_with_1_spare() { rollSpare(); game.roll(3); rollMany(0, 17); Assertions.assertEquals(16, game.score()); } @Test void game_with_1_strike() { game.roll(10); game.roll(3); game.roll(4); rollMany(0, 16); Assertions.assertEquals(24, game.score()); } @Test void game_of_strikes() { rollMany(10, 12); Assertions.assertEquals(300, game.score()); } @Test void knockdown_nine_and_miss_ten_times() { int firstRollPinsKnockedDown = 9; int secondRollPinsKnockedDown = 0; int repeatTimes = 10; rollPair(repeatTimes, firstRollPinsKnockedDown, secondRollPinsKnockedDown); Assertions.assertEquals(90, game.score()); } @Test void knockdown_five_and_spare_ten_times_and_fice() { rollPair(10, 5, 5); game.roll(5); Assertions.assertEquals(150, game.score()); } private void rollPair(int repeatTimes, int firstRollPinsKnockedDown, int secondRollPinsKnockedDown) { for (int i = 0; i &lt; repeatTimes; i++) { game.roll(firstRollPinsKnockedDown); game.roll(secondRollPinsKnockedDown); } } private void rollSpare() { game.roll(5); game.roll(5); } private void rollMany(int pins, int times) { for (int i = 0; i &lt; times; i++) { game.roll(pins); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T00:33:33.570", "Id": "435251", "Score": "3", "body": "The problem statement would be very helpful." } ]
[ { "body": "<p>As far as <code>BowlingGameScore</code> goes, LGTM. I have no remarks. (And usually I have <em>lots</em>.)</p>\n\n<p>In the tests, after each <code>void</code> (e.g. before <code>game_no_pins_get_hit</code>),\nit's a bit odd to have a newline.</p>\n\n<p>Also, a static import to turn <code>Assertions.assertEquals</code> into\na concise <code>assertEquals</code> would be convenient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T22:38:26.327", "Id": "435638", "Score": "0", "body": "thank you for your code-review @J_H. I included the static import in my code.\nregarding the new lines after void, it is Intellij auto format, do you know how to customize it to keep the following format ?\n @ Test void (new line)\n game_no_pins_get_hit() {" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T17:24:51.293", "Id": "224427", "ParentId": "224368", "Score": "2" } }, { "body": "<p><strong>Kata compliance</strong></p>\n\n<p>Your solution is very close to the <a href=\"http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata\" rel=\"nofollow noreferrer\">template</a>. Bob seems to expect you to more or less type in his solution, working through the steps in order to end up with the same code, thus forming a way of thinking through repetition. Your code is slightly different, but still satisfies the requirements, and of course you may have worked from a different description. You've generated similar refactorings making the code easy to read.</p>\n\n<p><strong>The invisible bug</strong></p>\n\n<p>You have a slight bug in your code. I say slight, because it currently has no observable impact. Given three rolls (10, 0, 1). There's a strike, and a frame of 1, which would score <strong>strike (10) + bonus (0 + 1) + second frame (1) = 12</strong>. The way your code processes, it's a <strong>spare (10 + 0) + bonus (1) + second frame (1) = 12</strong>. The end result is the same, but it's running through your code in an unexpected route. This seems like something that 'could' cause future issues, if for example you wanted to provide a summary of the frame scores. It can be fixed by checking if it's a strike, before checking if it's a spare.</p>\n\n<p><strong>Test Formatting</strong></p>\n\n<p>Your tests are in a slightly weird format. I'd expect the layout to be:</p>\n\n<pre><code>@Test\nvoid game_just_1_pin_get_hit() {\n</code></pre>\n\n<p><strong>Consistency</strong></p>\n\n<p>In your tests you've got two methods that do a similar thing:</p>\n\n<pre><code>private void rollMany(int pins, int times) {\nprivate void rollPair(int repeatTimes, int firstRollPinsKnockedDown, int secondRollPinsKnockedDown) {\n</code></pre>\n\n<p>One takes the number of times to perform the iteration as the second parameter, the other takes it as a first. This can be a bit misleading when reading the tests. Your initial test names start with <code>game_of</code>, setting the context that the test is checking an entire game. You then drop the prefix and instead go with <code>knockdown</code>, even though you're still testing the whole game in these tests. Taking a consistent naming approach can make it easier to know what to expect from the test.</p>\n\n<p><strong>Constants</strong></p>\n\n<p>The Kata template I've looked at has a similar approach to yours, so this may be more of a comment on the Kata, however I think the code could benefit from the use of some constants. This would help to set context for people that don't know the game, about the number of pins per frame and the maximum number of rolls in a standard game.</p>\n\n<p><strong>Error checking</strong></p>\n\n<p>Again, this seems to be more a reflection of the Kata itself, there's no error checking in the written code. There's nothing to check that you're not knocking down more than the number of pins the game allows, no checking that you're not trying to roll more balls than the class has capacity to deal with, etc. It's an important next step to consider what situations the class might need to handle.</p>\n\n<p><strong>Typo</strong></p>\n\n<p>There seems to be a typo in this test name:</p>\n\n<pre><code>knockdown_five_and_spare_ten_times_and_fice\n</code></pre>\n\n<p>Should be <code>five</code> not <code>fice</code>?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T14:22:54.407", "Id": "238037", "ParentId": "224368", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T21:33:50.727", "Id": "224368", "Score": "3", "Tags": [ "java", "unit-testing" ], "Title": "Bowling Kata in Java" }
224368
<p>I use the Laravel API and want make messy code cleaner.</p> <p>I have a form for registering business and businessOwner. And stylist who is working under this business registering from same function. </p> <p>And which case best to use there? if statements or Switch case statements?</p> <pre><code>public function businessRegister (Request $request) { if ($request['stylist'] === "stylist") { $validator = Validator::make($request-&gt;all(), [ 'firstName' =&gt; 'required|string', 'lastName' =&gt; 'required|string', 'gender' =&gt; 'required|in:Male,Female', 'email' =&gt; 'required|string|email|max:255|unique:stylists', 'password' =&gt; 'required|string|min:6|confirmed', 'mobileNumber' =&gt; 'required|integer', 'address' =&gt; 'required|string', 'name' =&gt; 'required|string', 'registrationNumber' =&gt; 'required|unique:businesses', 'bMobileNumber' =&gt; 'required|integer', 'bAddress' =&gt; 'required', ]); } elseif ($request['business'] === "business") { $validator = Validator::make($request-&gt;all(), [ 'firstName' =&gt; 'required|string', 'lastName' =&gt; 'required|string', 'gender' =&gt; 'required|in:Male,Female', 'email' =&gt; 'required|string|email|max:255|unique:stylists', 'password' =&gt; 'required|string|min:6|confirmed', 'mobileNumber' =&gt; 'required|integer', 'address' =&gt; 'required|string', 'name' =&gt; 'required|string', 'registrationNumber' =&gt; 'required|unique:businesses', 'bMobileNumber' =&gt; 'required|integer', 'bAddress' =&gt; 'required', ]); } if ($validator-&gt;fails()) { return response(['errors' =&gt; $validator-&gt;errors()-&gt;all()], 422); } if ($request['stylist'] === "stylist") { $findBusiness = Business::where([['name',$request-&gt;name], ['inviteCode',$request-&gt;inviteCode]])-&gt;first(); } elseif ($request['business'] === "business") { $inviteCode = $this-&gt;inviteCodeGen(); //print_r($inviteCode); $findBusiness = $this-&gt;business($request-&gt;name, $request-&gt;registrationNumber, $request-&gt;bImage, $request-&gt;bAddress, $request-&gt;bLongitude, $request-&gt;bLatitude, $request-&gt;bMobileNumber, 0, $inviteCode); } if (count($findBusiness) === 1 || $findBusiness['success'] === 1) { $request['device'] = "deviceToken|Or|DeviceTypeLike|IOS|OR|Android|IDK"; $request['longitude'] = "getStylistLongitude"; $request['latitude'] = "getStylistLatitude"; if ($request['stylist'] === "stylist") { $id = $findBusiness-&gt;id; } elseif ($request['business'] === "business") { $id = $findBusiness['id']; } $stylist = Stylist::create([ 'firstName' =&gt; $request['firstName'], 'lastName' =&gt; $request['lastName'], 'image' =&gt; $request['image'], 'stylistStatus' =&gt; "Stylist", // Freelancer - Stylist 'businessId' =&gt; $id, // Last inserted Business ID 'gender' =&gt; $request['gender'], 'email' =&gt; $request['email'], 'password' =&gt; Hash::make($request['password']), 'mobileNumber' =&gt; $request['mobileNumber'], 'address' =&gt; $request['address'], 'longitude' =&gt; $request['longitude'], 'latitude' =&gt; $request['latitude'], 'device' =&gt; $request['device'], ]); BookingTimes::insert(array( array('stylistId' =&gt; $stylist-&gt;id, 'day' =&gt; 'Monday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('stylistId' =&gt; $stylist-&gt;id, 'day' =&gt; 'Tuesday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('stylistId' =&gt; $stylist-&gt;id, 'day' =&gt; 'Wednesday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('stylistId' =&gt; $stylist-&gt;id, 'day' =&gt; 'Thursday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('stylistId' =&gt; $stylist-&gt;id, 'day' =&gt; 'Friday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('stylistId' =&gt; $stylist-&gt;id, 'day' =&gt; 'Saturday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('stylistId' =&gt; $stylist-&gt;id, 'day' =&gt; 'Sunday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), )); if ($request['business']) { Business::where('id', $findBusiness['id'])-&gt;update(['ownerId' =&gt; $stylist-&gt;id]); } $token = $stylist-&gt;createToken('Stylist registered')-&gt;accessToken; $response = ['token' =&gt; $token]; return response($response, 200); } $response = ['error' =&gt; 'Registration error']; return response($response, 422); } private function inviteCodeGen($length = 3) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i &lt; $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } $randomString2 = ''; for ($i = 0; $i &lt; $length; $i++) { $randomString2 .= $characters[rand(0, $charactersLength - 1)]; } return strtoupper($randomString . "-" . $randomString2); } protected function business ($name, $registrationNumber, $image, $address, $longitude, $latitude, $mobileNumber, $ownerId, $inviteCode) { $business = Business::create([ 'name' =&gt; $name, 'inviteCode' =&gt; $inviteCode, 'registrationNumber' =&gt; $registrationNumber, 'image' =&gt; $image, 'address' =&gt; $address, 'longitude' =&gt; $longitude, 'latitude' =&gt; $latitude, 'mobileNumber' =&gt; $mobileNumber, ]); BusinessBookingTimes::insert(array( array('businessId' =&gt; $business-&gt;id, 'day' =&gt; 'Monday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('businessId' =&gt; $business-&gt;id, 'day' =&gt; 'Tuesday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('businessId' =&gt; $business-&gt;id, 'day' =&gt; 'Wednesday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('businessId' =&gt; $business-&gt;id, 'day' =&gt; 'Thursday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('businessId' =&gt; $business-&gt;id, 'day' =&gt; 'Friday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('businessId' =&gt; $business-&gt;id, 'day' =&gt; 'Saturday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), array('businessId' =&gt; $business-&gt;id, 'day' =&gt; 'Sunday', 'slotDuration' =&gt; 30, 'status' =&gt; 1, 'startTime' =&gt; '08:00:00', 'endTime' =&gt; '16:00:00'), )); return ['id' =&gt; $business-&gt;id, 'success' =&gt; 1]; } </code></pre>
[]
[ { "body": "<p>You have repeated the following block of code twice:</p>\n\n<pre><code>'firstName' =&gt; 'required|string',\n'lastName' =&gt; 'required|string',\n'gender' =&gt; 'required|in:Male,Female',\n...\n</code></pre>\n\n<p>What I would do would be to create a <a href=\"https://laravel.com/docs/5.8/validation#creating-form-requests\" rel=\"nofollow noreferrer\">Custom Form Request</a>, let's call that ValidateNewUserRequest. Then, your controller can take the argument <code>ValidateNewUserRequest $request</code>.</p>\n\n<p>In ValidateNewUserRequest, you can apply the validation in the <code>rules()</code> function. I've also noticed that both pieces of your validation above contains the line: \n<code>'email' =&gt; 'required|string|email|max:255|unique:stylists'</code>, but I'm guessing that you want the stylists to be unique to the stylists, and the businesses unique to the businesses (potentially). If so, at the top of <code>rules()</code> you can have your if statement that determines which table to look at.</p>\n\n<pre><code>public function rules()\n{\n\n if ($request-&gt;stylist == \"stylist\") {\n $table = 'stylists';\n\n } elseif ($request-&gt;business == \"business\") {\n $table = 'business';\n }\n\n // TODO :: you will want to determine which table to use if neither of the above\n\n return [\n 'firstName' =&gt; 'required|string',\n 'lastName' =&gt; 'required|string',\n 'gender' =&gt; 'required|in:Male,Female',\n 'email' =&gt; 'required|string|email|max:255|unique:stylists',\n 'password' =&gt; 'required|string|min:6|confirmed',\n 'mobileNumber' =&gt; 'required|integer',\n 'address' =&gt; 'required|string',\n 'name' =&gt; 'required|string',\n 'registrationNumber' =&gt; 'required|unique:businesses',\n 'bMobileNumber' =&gt; 'required|integer',\n 'bAddress' =&gt; 'required',\n ];\n} \n</code></pre>\n\n<p>When you have this as your request object in your controller, it's already validated for (yay). There's lots of other stuff you can do in the custom request including error handling which you will be able to read about in the docs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:05:48.677", "Id": "226497", "ParentId": "224379", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T04:50:46.843", "Id": "224379", "Score": "2", "Tags": [ "php", "laravel", "controller" ], "Title": "Laravel controller methods for registering businesses and stylists" }
224379
<p>I wanted to experiment with a reusable thread pool that allows to add tasks and execute them repetitively. After going through,</p> <p><a href="https://github.com/progschj/ThreadPool" rel="nofollow noreferrer">https://github.com/progschj/ThreadPool</a> and another Stack Overflow post I came up with the implementation in <a href="https://github.com/dragsu/CPPThread" rel="nofollow noreferrer">https://github.com/dragsu/CPPThread</a>.</p> <p>The main bit of the code is,</p> <p><strong>ThreadPool.h</strong></p> <pre><code>#pragma once #include &lt;condition_variable&gt; #include &lt;future&gt; #include &lt;list&gt; #include &lt;memory&gt; #include &lt;mutex&gt; #include &lt;thread&gt; #include &lt;map&gt; #include "ITask.h" /** * A simple imlpementation of a thread pool that can excute * {@link ITask}s. */ class ThreadPool { public: //---------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------- ThreadPool( size_t threadCount ); ~ThreadPool(); //---------------------------------------------------------- // INSTANCE METHODS //---------------------------------------------------------- /** * Adds a {@link ITask} to a thread. * &lt;p/&gt; * &lt;b&gt;Note:&lt;/b&gt; The task will be added to the thread with a minimum * task load. * * @param task The {@link ITask} to be added to the task queue of a thread */ void submit( std::shared_ptr&lt;ITask&gt; &amp;task ); /** * Removes a {@link ITask} from a thread. * * @param task The {@link ITask} to be removed from the queue * @return &lt;code&gt;true&lt;/code&gt; if the task been removed successfully, * otherwise false */ bool remove( std::shared_ptr&lt;ITask&gt; &amp;task ); /** * Sets a wait time for threads before starting another execution * round. * * @param milliseconds Wait time of individual thread after * completing a round of its job queue. */ void setWaitTime( unsigned int milliseconds ); private: /* * Holds an individual thread and related resources of it */ struct ThreadData { ThreadData() : threadObj(), jobs(), stop( false ) { } ThreadData( const ThreadData&amp; ) = delete; ThreadData&amp; operator=( const ThreadData&amp; ) = delete; std::thread threadObj; std::map&lt;int, std::shared_ptr&lt;ITask&gt;&gt; jobs; std::mutex mutexGuard; std::condition_variable condition; bool stop; }; private: void threadFunc( ThreadData* data ); private: // To keep track of threads so we can join them at the destruction std::list&lt; ThreadData &gt; workers; unsigned int waitTIme; }; </code></pre> <p>ThreadPool.cpp</p> <pre><code>#include "ThreadPool.h" using namespace std; ThreadPool::ThreadPool( size_t threadCount ) : waitTIme(1) { for( size_t i = 0; i &lt; threadCount; ++i ) { workers.emplace_back(); // create threadData object inside the list } for( auto &amp;thredData : workers ) { thredData.threadObj = thread( &amp;ThreadPool::threadFunc, this, &amp;thredData ); } } ThreadPool::~ThreadPool() { for( auto &amp;worker :workers ) { worker.stop = true; worker.condition.notify_one(); } // Join all the threads for( auto &amp;worker : workers ) { worker.threadObj.join(); } } void ThreadPool::threadFunc( ThreadData* data ) { unique_lock&lt;mutex&gt; lock( data-&gt;mutexGuard, defer_lock ); while( true ) { lock.lock(); data-&gt;condition.wait( lock, [data, &amp;lock]{ bool shouldContinue = false; shouldContinue = data-&gt;stop || !data-&gt;jobs.empty(); return shouldContinue; }); // Stop was signaled, let's exit the thread if( data-&gt;stop ) return; for( auto &amp;task : data-&gt;jobs ) { task.second-&gt;run(); } lock.unlock(); this_thread::sleep_for( chrono::milliseconds(waitTIme) ); } } void ThreadPool::submit( shared_ptr&lt;ITask&gt; &amp;task ) { ThreadData *candidate = nullptr; int currentMin = INT_MAX; for( auto &amp;thredData : workers ) { int jobCount = thredData.jobs.size(); if( jobCount &lt; currentMin ) { currentMin = jobCount; candidate = &amp;thredData; } } if( candidate ) { unique_lock&lt;mutex&gt; l( candidate-&gt;mutexGuard ); candidate-&gt;jobs.insert( pair&lt;int, shared_ptr&lt;ITask&gt;&gt;(task-&gt;getId(), task) ); candidate-&gt;condition.notify_one(); } } bool ThreadPool::remove( shared_ptr&lt;ITask&gt; &amp;task ) { bool success = false; for( auto &amp;thredData : workers ) { unique_lock&lt;mutex&gt; l( thredData.mutexGuard ); auto it = thredData.jobs.find( task-&gt;getId() ); if( it != thredData.jobs.end() ) { thredData.jobs.erase( it ); success = true; break; } } return success; } void ThreadPool::setWaitTime( unsigned int milliseconds ) { this-&gt;waitTIme = milliseconds; } </code></pre> <p>I would be glad if I can get some feedback on this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T04:42:15.637", "Id": "436457", "Score": "3", "body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p><strong>First of all, the good things:</strong> </p>\n\n<p>The use of Doxygen documentation of classes and functions is very good style, which even pros too often \"forget\", and I like it. Also the use of a setter for the wait time. Also your try to use your locks in a <em>RAII</em> way is good thinking. Also to define return values at start and have only one return statement, instead of return statements in branches, is very good style and even has sometimes performance benefits. \nAnd the best part is that you also checked for <em>spurious wake ups</em>, something most people, including professors for concurrency programming, tend to forget.</p>\n\n<p><strong>However your code has a very high count of issues which make it unusable, and in general I find in overall a bad design too.</strong></p>\n\n<hr>\n\n<p>First your code is very hard to read since you do things twice or do unnecessary stuff. Then you reinvent the wheel often, which could be solved with classes and stuff from <code>std</code>. You use things wrong or don`t seem to know how they are intended to be used. You don't care about <em>exception safety</em> at all, lower the usability for the caller by restricting the usage of an interface for its tasks.</p>\n\n<p>It seems to me you were overwhelmed by the good solution your first link represents, since it uses the best but advanced stuff, but knew run time polymorphism and some basic stuff already. Unfortunately you still need to improve your understandings of C++ basics first and also a bit in concurrency, although already respectable, like the use of atomics and the uselessness of the sleep. <strong>Keep on learning, you are on a good path, including by appreciating code reviews and putting yourself out in the open for critique!</strong> C++ is hard, but returns that with the fastest code you can get, while being safer and easier to use then C.</p>\n\n<p>Here are some of the problems I found (far from complete):</p>\n\n<ol>\n<li>Don't use references to <code>std::shared_ptr</code>, you always want your own copy, thats the reason whz you create a new one when you insert them to, but reduce caller usage</li>\n<li><code>submit</code> will not tell the caller if the task was submitted</li>\n<li>Use of an own Interface Class <code>ITask</code>, why the overhead of run-time polymorphism and duplication of <code>std::packaged_task</code></li>\n<li>Missing header <code>#include &lt;climits&gt; int currentMin = INT_MAX;</code></li>\n<li>Use <code>lock_guard</code> instead of <code>unique_lock</code> in <code>threadFund</code></li>\n<li>Consider the precision of your data types, for instance you assign the <code>size_t</code> of <code>jobs.size()</code> to an <code>int</code>, which is very bad, since the <code>int</code> could overflow and lead to <em>undefined behavior</em></li>\n<li>Don't create objects to replace them anyway as in <code>ThreadPool::ThreadPool</code>, you could have done the things you want already in the <code>emplace_back</code> and also replace the <code>for</code> loop with <code>std::generate_n</code></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T01:05:41.687", "Id": "436034", "Score": "0", "body": "I appreciate for taking time to reply 1. _Don't use references to shared_ptr_\"- Isn't reference counting expensive?\n2. _Use lock_guard instead of unique_lock in threadFund_ - condition_variable::wait requires a unique_lock and it has advantages like being able to lock and unlock when needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T01:05:49.913", "Id": "436035", "Score": "0", "body": "3. _Don't create objects to replace them anyway_ - If you look closely I am not actually replacing them. My thread data struct has a deleted copy and assignment operators and therefore I have to create them inside my container. Inside the loop I'm just initialising a member of the struct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T01:10:01.623", "Id": "436038", "Score": "0", "body": "4. _duplication of packaged_task_ - In this particular implementation I am already managing ITasks in the main thread and the thread pool must update the state of them regularly. Then the main thread will use accessors to retrieve the state of ITask whenever it needs. Also, I do not want to return a future which adds an extra managing load in the main thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T07:43:29.947", "Id": "436093", "Score": "0", "body": "1. Not it isn't, your locks and vtable lockup probably take more time, besides, you are copying the shared_ptr in the insert in submit anyway. Which is good, otherwise it would defeat the purpose of shared_ptr all along and you could use raw pointers or references.\n2. You lock and unlock the the mutex in the inner scope, which is exactly what lock_guard would do. Your manual usage + the wrong scope defeats the RAII purpose of unique_lock.\n3. Then I suggest you write a constructor for that, and do that in emplace. When you are concerned about performace, as 1. suggests, here is wh to start." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T07:44:57.637", "Id": "436094", "Score": "0", "body": "4. I don't see from your description how the usage of future would not make the main code easier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T07:58:21.133", "Id": "436098", "Score": "0", "body": "1. Have a look at https://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2011-Scott-Andrei-and-Herb-Ask-Us-Anything#time=04m34s 2. But condition.wait required a unique_lock." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T08:29:45.560", "Id": "436102", "Score": "0", "body": "2. Ahhh I see, well you are right that you still need unique_lock, but still it makes much more sense, to move it to the inner scope, (where you lock it), don't defer the lockin in the constructor, and save the unlock at the end of the while, by either removing the sleep or putting everthing but the sleep into another nested scope (with the advantage to clearly see where you hold the lock without the possibility of forgetting to unlock).\n1. For what exactly? I read C++ concurrency in Action and went to OS and parallel prog. courses in ms CS school. Overall I would just use std::async or asio" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T08:36:04.027", "Id": "436104", "Score": "0", "body": "1. If you were refering to the shared_ptr part: Of course shared ptr a some work , espescially if misused. That however doesn't mean you should not use them, when you need them. If you can design your objects lifetime so that you can use unique_ptr or just references or call with concrete types with move overloads/forwarding refs. the better. \nBut the performance of shared_ptr is not the thing you should worry in your project, because you probably have bigger problems like superscription, amdahls law, false sharing, cache usage, malloc overhead, alg. complexity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T08:40:43.367", "Id": "436105", "Score": "0", "body": "Or to quote Donald Knuth “Premature optimization is the root of all evil” .\nIf performance is key, build it and MEASURE, don't refrain from things because some one said it has overhead, unless you exactly know the overhead. That's also what Herb said \"Measure!\"" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T16:24:22.057", "Id": "224684", "ParentId": "224385", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T07:24:19.853", "Id": "224385", "Score": "2", "Tags": [ "c++", "multithreading" ], "Title": "Implementing a thread pool for task execution" }
224385
<p>I`m writing a function for small pygame program. The ideas is that I have a 500 pixels square screen and I want to place 5 objects per row with the size of <em>width</em> and <em>height</em> in random order and I need a function to generate and store coordinates. <br><p></p> <pre><code>from random import randint def gen_coords(width=50, height=50, side_of_scr=500): """Generates random coordinates for objects in rows that are positioned on 5x5 grid.""" coords = [] for row in range(5): # creating row container coords.append([]) for pos in range(5): # range of values in randint reflects that i want the objects # to be placed with offset of the sides of the screen x = randint(0.5 * width, side_of_scr - 0.5 * width) # the distance between the rows is equal to the height of an object y = 0.5 * height + row * 2 * height coords[row].append((x, y)) return coords </code></pre> <p>So this</p> <pre class="lang-py prettyprint-override"><code>for coord in gen_coords(): print(coord) </code></pre> <p>returns</p> <pre class="lang-py prettyprint-override"><code>[(177, 25.0), (367, 25.0), (214, 25.0), (284, 25.0), (125, 25.0)] [(425, 125.0), (446, 125.0), (126, 125.0), (409, 125.0), (187, 125.0)] [(210, 225.0), (188, 225.0), (215, 225.0), (132, 225.0), (431, 225.0)] [(303, 325.0), (471, 325.0), (252, 325.0), (26, 325.0), (111, 325.0)] [(468, 425.0), (127, 425.0), (452, 425.0), (30, 425.0), (345, 425.0)] </code></pre> <p><p> I've done this using list of lists and it's working so far, but im looking for the better way to do it. Thanks for help.</p>
[]
[ { "body": "<p>I am not entirely sure what you are unhappy about, so I am going to assume you find it too cumbersome, so here is a \"one line\" way to do it:</p>\n\n<pre><code>import random\ngen_coords = (lambda rows=range(5), cols=range(5): lambda width=50, height=50, side_of_scr=500: [[\n (random.randint(width/2, side_of_scr - width/2), height/2 + row * 2 * height)\n for col in cols] for row in rows])()\n</code></pre>\n\n<p>That is still ugly, so let us make an elegant solution, with better performance:</p>\n\n<pre><code>import random\ndef gen_coords(width=50, height=50, side_of_scr=500, rows=5, cols=5):\n lower = width/2\n upper = side_of_scr - width/2\n height_step = 4 * height\n gen_x = lambda : random.randint(lower, upper)\n def gen_row(row):\n y = (row + 0.25) * height_step\n return [(gen_x,y) for col in range(cols))]\n return [gen_row(row) for row in range(rows)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:02:56.393", "Id": "224408", "ParentId": "224392", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T09:09:05.477", "Id": "224392", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Store coordinates in 2d grid" }
224392
<p>I've recently started going through the Head First C book. I'd like to get up to speed in terms of writing good, idiomatic, modern C. I have read the first few chapters of the Modern C book too but found Head First to be a better introduction to the language. </p> <p>The code below is for the first, bigger, arduino assignment. It's a pretty straight forward assignment, an LED should be used to indicate the soil moisture of a plant. I've gone beyond the base assignment by using a 3-color LED where pin 11 should be high for green, 12 high for red and both high for orange.</p> <p>This creates a bit of a challenge in creating a nice, consistent api which abstracts those details. I wanted to use pointers and pointer arithmentic in the solution just to get some exposure to them. I could probably re-write using arrays and avoid the need for 0 last elements although I would still need to deal with pointer decay.</p> <p>Any pointers :-) on what could be changed to turn this into a good, idiomatic, modern solution? Regardless of pointer use or not.</p> <pre><code> int const RED[] = { 12, 0 }; int const GREEN[] = { 11, 0 }; int const ORANGE[] = { 11, 12, 0 }; int const DEFAULT_DURATION = 1000; int const DEFAULT_COUNT = 1; void blink(int color[]); void blink(int color[], int duration, int count); void blinkSequence(int* color[]); void blinkSequence(int* color[], int duration, int count); void on(int color[]); void off(int color[]); void setup() { // initialize LED Pins as output Serial.begin(9600); pinMode(11, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); digitalWrite(11, LOW); digitalWrite(12, LOW); digitalWrite(13, LOW); } void loop() { int m = analogRead(0); int interval = 2000; Serial.print("Moisture is: "); Serial.println(m); if (m &lt;= 580) { //Really Dry!: 580- int* seq[] = { RED, ORANGE, 0 }; blinkSequence(seq, 150, 2); interval = 0; } else if (m &lt;= 700) { //Needs water: 700 - 581 blink(RED, 500); interval = 500; } else if (m &lt;= 740) { //Could be wetter: 740 - 701 blink(ORANGE, 4000); interval = 50; } else if (m &lt;= 870) { //Happy range: 870 - 741 blink(GREEN, 5000); interval = 50; } else { //Overwatered: 870+ int* seq[] = { GREEN, ORANGE, 0 }; blinkSequence(seq, 200, 5); interval = 3000; } delay(interval); } void blinkSequence(int* colors[], int duration, int count) { for (int i = count; i &gt; 0; i--) { int** inner = colors; for(;*inner;inner++) { blink(*inner, duration); } } } void blink(int color[], int duration) { on(color); delay(duration); off(color); } void blinkSequence(int* colors[]) { for(;*colors;colors++) { blink(*colors); } } void blink(int color[]) { on(color); delay(DEFAULT_DURATION); off(color); } void on(int color[]) { for(;*color;color++) { digitalWrite(*color, HIGH); //Serial.print("HIGH:"); //Serial.println(*color); } } void off(int color[]) { for(;*color;color++) { digitalWrite(*color, LOW); //Serial.print("LOW:"); //Serial.println(*color); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:40:25.287", "Id": "435381", "Score": "0", "body": "Can you add the header files you are including? Where is the definition or declaration of Serial?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T18:43:10.570", "Id": "435387", "Score": "0", "body": "@pacmaninbw, I expect that the arduino ide adds those in. Serial, digitalWrite, analogRead, pinMode etc. are standard arduino methods." } ]
[ { "body": "<p>You wrote several <code>for</code> loops without any spaces.\nPlease don't do that, as it makes the code harder to read.</p>\n\n<p>Instead of</p>\n\n<pre><code> for(;*colors;colors++) {\n blink(*colors);\n }\n</code></pre>\n\n<p>you might prefer</p>\n\n<pre><code> while (*colors) {\n blink(*colors++);\n }\n</code></pre>\n\n<p>Moving <code>loop()</code> to the bottom of the file would save you\nsome forward declarations.</p>\n\n<p>Your <code>Serial.print()</code> statements might benefit from the addition\nof a <code>debug</code> flag, so there's no need to comment them.</p>\n\n<p>Things like counts and durations won't go negative.\nI can't see the signatures for <code>delay()</code> and <code>digitalWrite()</code>,\nbut it seems like some of your <code>int</code>s might want to be <code>uint</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T08:50:26.930", "Id": "435527", "Score": "0", "body": "Thanks, all good points." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T17:37:38.003", "Id": "224428", "ParentId": "224393", "Score": "2" } }, { "body": "<p>First this is probably C++ rather than C, the C programming language does not support function overloading (blink as an example).</p>\n\n<p><strong>Magic Numbers</strong> </p>\n\n<p>In programming a <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Number</a> is a numeric constant in code that doesn't identify what is is. Magic numbers make the code harder to understand, debug and maintain. When magic numbers are used as a basis for arrays it means that the code may need to be edited in multiple places rather than just in one location.</p>\n\n<p>Example:</p>\n\n<pre><code>int *colors[10];\n\nfor (c = 0; c &lt; 10; c++)\n{\n do_something_with_color(colors[c]);\n}\n</code></pre>\n\n<p>This would be easier to modify and maintain if a symbolic constant was defined.</p>\n\n<pre><code>int const MAX_COLORS = 10;\nint *colors[MAX_COLORS];\n\nfor (c = 0; c &lt; MAX_COLORS; c++)\n{\n do_something_with_color(colors[c]);\n}\n</code></pre>\n\n<p>There are a large number of numeric constants in the program, in very few cases they have been defined using <code>int const SYMBOLIC_NAME = value</code>. It might be better if all the numeric constants were defined in this manner. Some examples of these numeric constants are 700, 581, 500, 2000, 4000, etc.</p>\n\n<p>Are 500, 2000 and 4000 milliseconds?</p>\n\n<p><strong>Comments</strong><br>\nThe comments</p>\n\n<pre><code> //Really Dry!: 580-\n //Needs water: 700 - 581\n //Could be wetter: 740 - 701\n</code></pre>\n\n<p>aren't very meaningful in this context. If you want to create a block comment that describes what the LED is being used for and then base the symbolic name of the constants on this block comment it might be more helpful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T08:54:11.420", "Id": "435528", "Score": "0", "body": "Thanks, all good points. I see here that it seems like arduino is sort of a mix and customization of C and C++. https://arduino.stackexchange.com/a/817" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:14:54.440", "Id": "224435", "ParentId": "224393", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T09:45:33.663", "Id": "224393", "Score": "4", "Tags": [ "beginner", "arduino" ], "Title": "Arduino project to indicate soil moisture using LEDs" }
224393
<p>I had a need to group the same dataset in several groups. So instead of repeatedly query the dataset, I made an extension that could do it once. The caveat is, that the result is materialized in dictionaries, because I didn't managed to find an way to avoid that. Maybe you can?</p> <pre><code>public static IDictionary&lt;string, Dictionary&lt;object, HashSet&lt;T&gt;&gt;&gt; MultiGroupBy&lt;T&gt;(this IEnumerable&lt;T&gt; source, params (string Label, Func&lt;T, object&gt; Getter)[] groupers) { if (source == null) throw new ArgumentNullException(nameof(source)); if (groupers == null) throw new ArgumentNullException(nameof(groupers)); IDictionary&lt;string, Dictionary&lt;object, HashSet&lt;T&gt;&gt;&gt; results = new Dictionary&lt;string, Dictionary&lt;object, HashSet&lt;T&gt;&gt;&gt;(); using (var enumer = source.GetEnumerator()) { while (enumer.MoveNext()) { foreach ((var label, var func) in groupers) { if (!results.TryGetValue(label, out var dict)) { dict = new Dictionary&lt;object, HashSet&lt;T&gt;&gt;(); results[label] = dict; } var key = func(enumer.Current); if (!dict.TryGetValue(key, out var set)) { set = new HashSet&lt;T&gt;(); dict[key] = set; } set.Add(enumer.Current); } } } return results; } </code></pre> <hr> <p>Use case:</p> <pre><code>static void TestMultiGrouping() { string[] data = { "Black", "White", "Yellow", "green", "Red", "blue", "cyan", "Magenta", "Orange" }; foreach (var result in data.MultiGroupBy( ("First UCase", s =&gt; s.Length &gt; 0 &amp;&amp; char.IsUpper(s[0])), ("Length", s =&gt; s.Length), ("Length Four", s =&gt; s.Length == 4), ("Contains 'e'", s =&gt; s.Contains('e')), ("Num n's", s =&gt; s.Count(c =&gt; c == 'n')))) { Console.WriteLine($"Results for {result.Key}:"); foreach (var dict in result.Value) { Console.WriteLine($"{dict.Key}: {dict.Value.Count} [{(string.Join(", ", dict.Value))}]"); } Console.WriteLine(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T05:05:20.723", "Id": "435415", "Score": "0", "body": "If you're trying to avoid materializing this data, I think that is better suited to a push interface (`IObservable`) rather than a pull interface (`IEnumerable`). Rather than returning a dict mapping keys to sets of elements, you can try returning a dict mapping keys to streams of elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T06:14:48.497", "Id": "435421", "Score": "0", "body": "@Alexander, tanks for input. Your suggestion could be a solution, but the datasets datatype (`IEnumerable`) was given. Maybe the header of the question is a little misleading - the primary goal was performance optimization rather than \"one iteration\", but I thought, that \"one iteration\" was the way to optimize - which it still may be if memory allocation matters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T06:45:09.310", "Id": "435423", "Score": "0", "body": "RxNet adds `IEnumerable.toObservable()`, which would be a perfect fit. I think the performance characteristics would be pretty good. Using a cold observable (one that doesn't do anything until there's a subscriber), nothing happens until anyone is interested in the result, and they won't have to be concurrently stored in memory" } ]
[ { "body": "<p>If you only want to enumerate <code>source</code> once, then you'll have to cache it somehow. Either by materializing it immediately, as you do, or whenever the first group is enumerated, but that's more complicated.</p>\n\n<p>If you don't mind duplicate entries in your groups and throwing on duplicate labels, then your code can be simplified to the following:</p>\n\n<pre><code>public static IDictionary&lt;string, IEnumerable&lt;IGrouping&lt;object, T&gt;&gt;&gt; MultiGroupBy&lt;T&gt;(\n this IEnumerable&lt;T&gt; source,\n params (string label, Func&lt;T, object&gt; keySelector)[] groupings)\n{\n if (source == null) throw new ArgumentNullException(nameof(source));\n if (groupings == null) throw new ArgumentNullException(nameof(groupings));\n\n var materializedSource = source.ToArray();\n return groupings.ToDictionary(\n grouping =&gt; grouping.label,\n grouping =&gt; materializedSource.GroupBy(grouping.keySelector));\n}\n</code></pre>\n\n<p>This materializes <code>source</code> up-front, but each grouping is lazily evaluated. Some quick enumeration tests with randomly generated strings show a roughly 40% speed improvement. I haven't measured memory consumption, but I expect that to be a bit higher due to the extra references/values stored in <code>materializedSource</code>.</p>\n\n<p>I suspect the main reason for the speed difference is that your code performs a lookup into <code>results</code> for every item/grouping combination, something that separate <code>GroupBy</code> calls don't need to do.</p>\n\n<hr>\n\n<p>Other notes:</p>\n\n<ul>\n<li>That <code>using GetEnumerator/while MoveNext</code> construction can be simplified to a <code>foreach</code> loop.</li>\n<li>You do not guard against duplicate labels, so you can end up with mixed results (and even mixed key types).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:46:18.647", "Id": "435326", "Score": "0", "body": "Nifty. But I can't get the same result as you when it comes to performance: If the source is a materialized array itself - yes, but if not, then mine is about double as fast as yours and for large sets even more. But one thing yours showed me, is that I can't use `HashSet<T>`as the inner vector, because it handles doublets wrongly for value types. `HashSet<T> made sense in the original context though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:46:24.543", "Id": "435327", "Score": "0", "body": "About `foreach` vs. `GetEnumerator()` - it is my experience that the latter is slightly (sometimes much) faster - which is strange because `foreach` calls `GetEnumerator()`. Duplicate labels - thanks - has to be dealt with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:17:44.797", "Id": "435340", "Score": "3", "body": "It's getting into micro-optimisation, but there's an argument for using `ToList()` in preference to `ToArray()` for temporary private eager evaluation results: the implementation is effectively almost the same, but `ToArray()` does a final copy to a shorter array for most inputs." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:43:14.603", "Id": "224406", "ParentId": "224398", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>public static IDictionary&lt;string, Dictionary&lt;object, HashSet&lt;T&gt;&gt;&gt; MultiGroupBy&lt;T&gt;(this IEnumerable&lt;T&gt; source, params (string Label, Func&lt;T, object&gt; Getter)[] groupers)\n</code></pre>\n</blockquote>\n\n<p>I don't understand the mixture of interfaces (<code>IDictionary</code>) and implementations (<code>Dictionary</code>, <code>HashSet</code>), nor the mixture of generics (<code>&lt;T&gt;</code>) and non-generics (<code>object</code>). Why is it not</p>\n\n<pre><code>public static IDictionary&lt;string, IDictionary&lt;K, ISet&lt;T&gt;&gt;&gt; MultiGroupBy&lt;T, K&gt;(this IEnumerable&lt;T&gt; source, params (string Label, Func&lt;T, K&gt; Getter)[] groupers)\n</code></pre>\n\n<p>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> IDictionary&lt;string, Dictionary&lt;object, HashSet&lt;T&gt;&gt;&gt; results = new Dictionary&lt;string, Dictionary&lt;object, HashSet&lt;T&gt;&gt;&gt;();\n\n using (var enumer = source.GetEnumerator())\n {\n while (enumer.MoveNext())\n {\n foreach ((var label, var func) in groupers)\n {\n if (!results.TryGetValue(label, out var dict))\n {\n dict = new Dictionary&lt;object, HashSet&lt;T&gt;&gt;();\n results[label] = dict;\n }\n\n ...\n</code></pre>\n</blockquote>\n\n<p>I'm not quite sure why you want to return an empty dictionary if the source is empty. As a caller of your library, I'd probably rather get a dictionary mapping the grouper names to empty dictionaries.</p>\n\n<p>That also simplifies the initialisation:</p>\n\n<pre><code> var results = groupers.ToDictionary(grouper =&gt; grouper.Item1, _ =&gt; new Dictionary&lt;object, HashSet&lt;T&gt;&gt;());\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> using (var enumer = source.GetEnumerator())\n {\n while (enumer.MoveNext())\n {\n ...\n }\n\n }\n</code></pre>\n</blockquote>\n\n<p>KISS. <code>foreach</code> is much kinder on the maintenance programmer, who doesn't have to check for correct usage patterns of the unsugared API. Using <code>MoveNext() / Current</code> for speed is the epitome of premature optimisation unless benchmarking shows that it's a bottleneck, in which case there should be a comment explaining the bottleneck to justify the more complex code.</p>\n\n<p>Moreover, if this is a bottleneck then it seems likely that the dictionary lookups in <code>results</code> for every single element in the source will be slower than the overhead of <code>foreach</code>, so you could start by replacing <code>results</code> with a <code>List&lt;(string Label, Func&lt;T, K&gt; Getter, IDictionary&lt;K, ISet&lt;T&gt;&gt; Groups)&gt;</code> and just convert it to a dictionary after the loop.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> foreach ((var label, var func) in groupers)\n</code></pre>\n</blockquote>\n\n<p><code>var (label, func)</code> saves the repetition.</p>\n\n<hr>\n\n<p>After my proposed refactors and some minor tidying of whitespace, I get</p>\n\n<pre><code>public static IDictionary&lt;string, IDictionary&lt;K, ISet&lt;T&gt;&gt;&gt; MultiGroupBy&lt;T, K&gt;(this IEnumerable&lt;T&gt; source, params (string Label, Func&lt;T, K&gt; Getter)[] groupers)\n{\n if (source == null) throw new ArgumentNullException(nameof(source));\n if (groupers == null) throw new ArgumentNullException(nameof(groupers));\n\n var results = groupers.ToDictionary(grouper =&gt; grouper.Item1, _ =&gt; (IDictionary&lt;K, ISet&lt;T&gt;&gt;)new Dictionary&lt;K, ISet&lt;T&gt;&gt;());\n\n foreach (var elt in source)\n {\n foreach (var (label, func) in groupers)\n {\n var dict = results[label];\n var key = func(elt);\n if (!dict.TryGetValue(key, out var set))\n {\n set = new HashSet&lt;T&gt;();\n dict[key] = set;\n }\n\n set.Add(elt);\n }\n }\n\n return results;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:47:51.353", "Id": "435348", "Score": "0", "body": "Fine solution. You're right about the interface/class mix. One thing though: I can't use the type parameter `K` because the keys may not be of the same type - that's why I use `object`. The instantiation of the `results` dictionary the way you do, is definitely smarter and cleaner code - I'll use that, but apparently I can't measure any significant difference from mine. About `ISet/HashSet` see my comment to Pieter Witvoet answer. Tanks for interesting points - as always." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:49:13.370", "Id": "435349", "Score": "0", "body": "LINQ provides _public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer);_. Why not use that one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:25:09.567", "Id": "435354", "Score": "1", "body": "@HenrikHansen, nothing stops you calling it with `object` for `K`. I admit that the downside is that the inference is less likely to work, so it's usually going to be necessary to use explicit type arguments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:25:35.667", "Id": "435355", "Score": "0", "body": "@dfhwze, was that intended for me or someone else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:26:10.433", "Id": "435356", "Score": "0", "body": "It was intended on Pieter's answer. See my answer for an explanation." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:13:41.103", "Id": "224410", "ParentId": "224398", "Score": "5" } }, { "body": "<h1>GroupBy vs ToLookup</h1>\n\n<p>From reference source: <a href=\"https://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs\" rel=\"noreferrer\">Linq Enumerable</a></p>\n\n<p><code>Dictionary&lt;object, HashSet&lt;T&gt;&gt;&gt;</code> can be replaced with a <code>ILookup&lt;object, T&gt;</code>. </p>\n\n<blockquote>\n<pre><code>public static ILookup&lt;TKey, TSource&gt; ToLookup&lt;TSource, TKey&gt;(\n this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector) \n{\n // impl ..\n}\n</code></pre>\n</blockquote>\n\n<p>There is also an overload in case you require compliant behavior with <code>HashSet&lt;T&gt;</code>.</p>\n\n<blockquote>\n<pre><code>public static ILookup&lt;TKey, TSource&gt; ToLookup&lt;TSource, TKey&gt;(\n this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector, \n IEqualityComparer&lt;TKey&gt; comparer)\n{\n // impl ..\n}\n</code></pre>\n</blockquote>\n\n<p>This is much faster than <code>GroupBy</code>. Have a look at the implementation of the latter.</p>\n\n<blockquote>\n<pre><code>public static IEnumerable&lt;IGrouping&lt;TKey, TSource&gt;&gt; GroupBy&lt;TSource, TKey&gt;(\n this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector) \n{\n return new GroupedEnumerable&lt;TSource, TKey, TSource&gt;(source, keySelector, IdentityFunction&lt;TSource&gt;.Instance, null);\n}\n</code></pre>\n</blockquote>\n\n<p>And <code>GroupedEnumerable</code> wraps <code>Lookup</code>.</p>\n\n<blockquote>\n<pre><code>public IEnumerator&lt;IGrouping&lt;TKey, TElement&gt;&gt; GetEnumerator() \n{\n return Lookup&lt;TKey, TElement&gt;.Create&lt;TSource&gt;(source, keySelector, elementSelector, comparer).GetEnumerator();\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h3>Refactored Code</h3>\n\n<p>Pieter's answer could be updated with a performance boost substituting <code>GroupBy</code> with <code>ToLookup</code>, also including Peter's micro-optimized <code>ToList</code>.</p>\n\n<pre><code>public static IDictionary&lt;string, ILookup&lt;object, T&gt;&gt; MultiLookupBy&lt;T&gt;(\n this IEnumerable&lt;T&gt; source, params (string Label, Func&lt;T, object&gt; Getter)[] groupings)\n{\n if (source == null) throw new ArgumentNullException(nameof(source));\n if (groupings == null) throw new ArgumentNullException(nameof(groupings));\n\n var materializedSource = source.ToList();\n return groupings.ToDictionary(\n grouping =&gt; grouping.Label, \n grouping =&gt; materializedSource.ToLookup(grouping.Getter));\n}\n</code></pre>\n\n<p>And your test code would change a bit.</p>\n\n<pre><code> sb.AppendLine($\"Results for {result.Key}:\");\n foreach (var dict in result.Value)\n {\n sb.AppendLine($\"{dict.Key}: {dict.Count()} [{(string.Join(\", \", dict))}]\");\n }\n sb.AppendLine();\n</code></pre>\n\n<p>I get performance close to the initial OP with this refactored code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:55:11.120", "Id": "435362", "Score": "1", "body": "This seems to be the \"testwinner\" both according to elegance and performance (for large datasets about 20 %). My problem is now to accept an answer, because I think ,you have contributes evenly to the best solution. I have written a number [1,99] in notepad. Comment a number, and closest will be accepted :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T11:24:49.210", "Id": "435434", "Score": "1", "body": "@HenrikHansen you should usually accept the answer, which is the most useful to you and future readers, which stumble upon this problem. People landing here via search will often take the accepted answer as providing a final \"best\" solution - so the accepted answer should include all relevant facts and not just be a partial answer. - If you are worried about fame, the accepted answer could be edited to a community answer, with credits to both posters." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:24:25.563", "Id": "224417", "ParentId": "224398", "Score": "5" } }, { "body": "<h3>Consistency with LINQ</h3>\n\n<p>I find in order to be consistent with other LINQ APIs and to make the usage of this extension more intuitive you should slightly adjust the parameter names and the return value and rename it to <code>ToLookups</code>.</p>\n\n<p><code>ToLookup</code> calls the <code>Func</code> <code>keySelector</code> and since this extension is accepting a collection, I suggest the name <code>keySelectors</code>.</p>\n\n<p>As far as the return value is concerned, I would use <code>ILookup</code> twice here so that the behaviour of the result is consistent.</p>\n\n<h3>Unexpected behaviour due to <code>HashSet</code></h3>\n\n<p>If you require unique elements then the source should be prefiltered. Ignoring them here is not something I would expect from a grouping. On the contrary, it should group them together because this is what grouping is for. A <code>HashSet</code> could also change the order of elements which the builtin grouping wouldn't so it's another surprise here.</p>\n\n<h3>Suggested code</h3>\n\n<p>This is how I think it should look like:</p>\n\n<pre><code>public static ILookup&lt;string, ILookup&lt;object, T&gt;&gt; ToLookups&lt;T&gt;\n(\n this IEnumerable&lt;T&gt; source, \n params (string Name, Func&lt;T, object&gt; KeySelector)[] keySelectors\n)\n{\n if (source == null) throw new ArgumentNullException(nameof(source));\n if (keySelectors == null) throw new ArgumentNullException(nameof(keySelectors));\n\n var materializedSource = source.ToList(); \n return \n keySelectors\n .Select(t =&gt; (t.Name, Lookup: materializedSource.ToLookup(t.KeySelector)))\n .ToLookup(t =&gt; t.Name, t =&gt; t.Lookup);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T06:48:09.870", "Id": "435507", "Score": "0", "body": "Check my answer on _HashSet_ behavior. You can use _ToLookup_ with an overload that takes a _IEqualityComparer<TKey> comparer_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T06:52:47.743", "Id": "435508", "Score": "0", "body": "@dfhwze I'm not quite sure what it has to do with the `HashSet`? The `IEqualityComparer<T>` It's for grouping, whereas `HashSet` is for throwing away duplicates and a grouping shouldn't be doing that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T06:56:35.873", "Id": "435510", "Score": "0", "body": "You are right, it's on the _Key_. Doh!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T07:06:19.017", "Id": "435512", "Score": "0", "body": "Thanks for the answer. According to `HashSet`, you're absolutely right - see my first comment to Pieter Witvoet's answer. I'll consider the renaming, but I think I prefer my name of the method itself. I look forward to benchmark you solution a little later." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T06:44:17.770", "Id": "224533", "ParentId": "224398", "Score": "3" } }, { "body": "<p>FYI. I've now tested the different versions of the algorithm from the different answers, and the result is as follows:</p>\n\n<pre><code>Data Size: 10\nName Iterations Average Min Max Total Std Dev Units\nPieter Wit: 50 0.38341 0.05530 16.09750 19.17070 2.24480 [Milliseconds]\ndfhwze : 50 0.09890 0.01250 3.96660 4.94510 0.55250 [Milliseconds]\nPeter Tayl: 50 0.14559 0.01500 6.16400 7.27940 0.85970 [Milliseconds]\nT3chb0t : 50 0.18089 0.01240 8.06260 9.04470 1.12590 [Milliseconds]\nOriginal : 50 0.11584 0.01640 4.54850 5.79220 0.63330 [Milliseconds]\n\nData Size: 100\nName Iterations Average Min Max Total Std Dev Units\nPieter Wit: 50 0.52665 0.48760 0.78700 26.33230 0.05190 [Milliseconds]\ndfhwze : 50 0.14118 0.11800 0.24010 7.05920 0.02070 [Milliseconds]\nPeter Tayl: 50 0.15725 0.14010 0.35670 7.86250 0.03030 [Milliseconds]\nT3chb0t : 50 0.13385 0.11880 0.18680 6.69250 0.01470 [Milliseconds]\nOriginal : 50 0.15542 0.14090 0.32780 7.77100 0.02600 [Milliseconds]\n\nData Size: 1000\nName Iterations Average Min Max Total Std Dev Units\nPieter Wit: 50 4.86897 4.56660 5.49500 243.44840 0.19180 [Milliseconds]\ndfhwze : 50 1.22802 1.14460 1.55030 61.40110 0.10070 [Milliseconds]\nPeter Tayl: 50 1.51039 1.41420 1.83450 75.51970 0.10540 [Milliseconds]\nT3chb0t : 50 1.33878 1.13730 2.61480 66.93920 0.21000 [Milliseconds]\nOriginal : 50 1.53352 1.39930 1.93510 76.67620 0.12120 [Milliseconds]\n\nData Size: 10000\nName Iterations Average Min Max Total Std Dev Units\nPieter Wit: 50 53.30435 48.53940 59.39360 2665.21760 2.12420 [Milliseconds]\ndfhwze : 50 13.29163 11.58010 17.93610 664.58150 1.42940 [Milliseconds]\nPeter Tayl: 50 15.99885 13.73030 19.87350 799.94260 1.62800 [Milliseconds]\nT3chb0t : 50 13.35479 11.60260 17.27620 667.73940 1.33350 [Milliseconds]\nOriginal : 50 16.06655 14.10760 21.15530 803.32750 1.57870 [Milliseconds]\n\nData Size: 100000\nName Iterations Average Min Max Total Std Dev Units\nPieter Wit: 50 759.18213 671.44490 972.02490 37959.10640 106.57280 [Milliseconds]\ndfhwze : 50 184.68625 157.19610 240.79290 9234.31240 27.82440 [Milliseconds]\nPeter Tayl: 50 247.55367 207.27300 296.28640 12377.68350 38.71610 [Milliseconds]\nT3chb0t : 50 200.40129 159.78880 241.07520 10020.06430 31.49570 [Milliseconds]\nOriginal : 50 250.01759 208.41280 324.99400 12500.87940 39.78020 [Milliseconds]\n\nData Size: 500000\nName Iterations Average Min Max Total Std Dev Units\nPieter Wit: 50 4241.30253 3572.39540 4887.39420 212065.12660 382.99050 [Milliseconds]\ndfhwze : 50 1009.33538 798.42660 1143.81710 50466.76910 124.30220 [Milliseconds]\nPeter Tayl: 50 1344.13312 1085.37460 1562.34310 67206.65590 185.08020 [Milliseconds]\nT3chb0t : 50 1002.87650 784.16660 1195.38060 50143.82510 136.03740 [Milliseconds]\nOriginal : 50 1354.36220 1072.92070 1536.09860 67718.10980 171.94550 [Milliseconds]\n</code></pre>\n\n<p>Test Data: randomly generated strings of length [0, 20), and the testcase was:</p>\n\n<pre><code> foreach (var result in data.MultiGroupBy(\n (\"First UCase\", s =&gt; s.Length &gt; 0 &amp;&amp; char.IsUpper(s[0])),\n (\"Length\", s =&gt; s.Length),\n (\"Length Four\", s =&gt; s.Length == 4),\n (\"Contains 'e'\", s =&gt; s.Contains('e')),\n (\"Num 'n's\", s =&gt; s.Count(c =&gt; c == 'n'))))\n {\n foreach (var dict in result.Value)\n {\n sum += dict.Value.Count;\n }\n }\n</code></pre>\n\n<p>In order to get equivalent results, I changed the <code>HashSet</code> in the original with a <code>List</code>.</p>\n\n<p>It's somehow a little disappointing that my efforts to do it in one iteration didn't pay off.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T09:17:48.507", "Id": "435663", "Score": "0", "body": "I'm too lazy to try it myself, but what happens when you replace the `results` dictionaries with an array in the original and Peter Taylor's answers? There's really no reason to use a dictionary over the labels in the loop, when the groupers are already in an ordered list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T14:12:28.553", "Id": "435696", "Score": "0", "body": "@VisualMelon: Good suggestion. I've tried with the original, and it seems to improve it by about 7-10 percent." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T04:45:17.970", "Id": "224595", "ParentId": "224398", "Score": "2" } } ]
{ "AcceptedAnswerId": "224406", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T10:43:28.560", "Id": "224398", "Score": "7", "Tags": [ "c#", "linq", "extension-methods" ], "Title": "Grouping into more groups in one iteration" }
224398
<p>Today I have dealt with logging in PowerShell as well as with the different streams and the pipeline. Unfortunately, none of these solutions really met my needs.</p> <p>My requirements are:</p> <ul> <li>I need to output information from PowerShell to a file log.</li> <li>The file log has a predefined structure. So it's not enough to just redirect all streams to the file.</li> <li>I want to use mainly standard PowerShell functions such as Write-Error, Write-Warning, Write-Verbose.</li> <li>The overhead in the code through logging should be minimal.</li> </ul> <p>I have developed the following idea now:</p> <ol> <li>When calling a function from my script, all streams are piped to a logging function.</li> <li>This function separates the debug, verbose, warning and error objects from the resulting object.</li> <li>The resulting object is released back into the pipeline.</li> </ol> <p>Here is my solution:</p> <pre><code>function Split-Streams { [CmdletBinding()] param( [Parameter(ValueFromPipeline)] $InputStream ) process{ switch($InputStream.GetType()) { 'System.Management.Automation.DebugRecord' { # Do whatever you want, like formatting an writing to a file. Write-Host $InputStream -ForegroundColor Gray } 'System.Management.Automation.ErrorRecord' { Write-Host $InputStream -ForegroundColor Red Write-Host ('Error function: {0}' -f $InputStream[0].InvocationInfo.MyCommand.Name) -ForegroundColor Red } 'System.Management.Automation.VerboseRecord' { Write-Host $InputStream -ForegroundColor Cyan } 'System.Management.Automation.WarningRecord' { Write-Host $InputStream -ForegroundColor Yellow } default { return $InputStream } } } } function Write-Messages { [CmdletBinding()] param() Write-Debug "Debug message" Write-Output "Output message" Write-Verbose "Verbose message" Write-Warning "Warning message" Write-Error "Error message" } $Test2 = Write-Messages -Verbose -Debug *&gt;&amp;1 | Split-Streams Write-Host $Test2 -ForegroundColor White </code></pre> <p>So now my question:</p> <ul> <li>Is there something wrong with my solution?</li> <li>Have I missed any problems?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:09:25.453", "Id": "435320", "Score": "0", "body": "Well, nothing will ever end up in a file - `Write-Host` writes directly to the host screen buffer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:16:50.413", "Id": "435339", "Score": "0", "body": "This is just an example. To show the possibilies of the consturct. you can redirect from there to whatever function you like. ie. \"$InputStream | Add-Content -Path $LogFilePath -Encoding ASCII\"" } ]
[ { "body": "<ul>\n<li><em>Is there something wrong with my solution?</em> I don't think so.</li>\n<li><em>Have I missed any problems?</em> \n\n<ul>\n<li>Omitted <em>Information</em> stream, cf <a href=\"https://stackoverflow.com/q/57303102/3439404\">How to process Write-Information pipeline output when using SilentlyContinue</a></li>\n<li><em>The <code>-Debug</code> parameter overrides the value of the <code>$DebugPreference</code> variable for the current command, setting the value of <code>$DebugPreference</code> to <code>Inquire</code></em>. Prompts to continue for every <code>Write-Debug</code> statement which may be considered inconvenient (or even harmful) in batch processing.</li>\n</ul></li>\n</ul>\n\n<p>Here's my solution (partially commented script):</p>\n\n<pre><code>[CmdletBinding()]\nparam(\n # [switch]$debug # alternative to [CmdletBinding()]\n)\n\nfunction Split-Streams {\n [CmdletBinding()]\n param(\n [Parameter(Mandatory,ValueFromPipeline)]\n [ValidateNotNull()] # avoid crashing . property dereference operator\n $InputStream,\n [switch]$revert\n )\n process {\n if ( -not $revert.IsPresent ) {\n # return an object which contains type and value of $InputStream\n [PSCustomObject] @{\n stream = $InputStream.GetType().FullName\n value = $InputStream\n }\n }\n else {\n # basic input object validity check\n if ( ($InputStream.psobject.Properties.Name -join ',') -match \n \"\\bstream\\b.*\\bvalue\\b|\\bvalue\\b.*\\bstream\\b\" ) {\n # review split streams and handle them individually\n switch($InputStream.stream)\n {\n 'System.Management.Automation.DebugRecord' { \n # Do whatever you want, like formatting an writing to a file. \n Write-Host ($InputStream.value) -ForegroundColor Gray\n }\n 'System.Management.Automation.ErrorRecord' {\n Write-Host ($InputStream.value) -ForegroundColor Red\n Write-Host ('Error function: {0}' -f ($InputStream.value).InvocationInfo.MyCommand.Name) -ForegroundColor DarkRed\n }\n 'System.Management.Automation.VerboseRecord' { \n Write-Host ($InputStream.value) -ForegroundColor Cyan \n }\n 'System.Management.Automation.WarningRecord' { \n Write-Host ($InputStream.value) -ForegroundColor Yellow \n }\n 'System.Management.Automation.InformationRecord' { \n Write-Host ($InputStream.value) -ForegroundColor Green\n }\n default { \n Write-Host \"output type: $($InputStream.stream)\" -ForegroundColor Blue\n # keep original output stream unchanged\n $InputStream.value\n }\n }\n }\n }\n }\n}\n\nfunction Write-Messages\n{\n [CmdletBinding()]\n param()\n Write-Debug \"Debug message $DebugPreference\"\n Write-Verbose \"Verbose message $VerbosePreference\"\n Write-Warning \"Warning message $WarningPreference\"\n Write-Error \"Error message $ErrorActionPreference\"\n Write-Information \"Information message $InformationPreference\"\n\n # Write-Output: it is generally not necessary to use the cmdlet.\n 'Output message'\n # I'm checking a more complex object than plain string\n Write-Output $Host\n}\n\n$DebugPreferenceSave = $DebugPreference # backup $DebugPreference\nIf ($PSBoundParameters['Debug']) {\n # The Debug parameter overrides the value of the $DebugPreference\n # variable for the current command, setting the value\n # of $DebugPreference to Inquire.\n # The following setting suppresses asking whether you want to continue\n # even if examined `Write-Messages` is a third-party black box.\n $DebugPreference = 'Continue'\n}\n\nWrite-Messages -Verbose *&gt;&amp;1 | Split-Streams | Split-Streams -revert\n\n$DebugPreference = $DebugPreferenceSave # restore $DebugPreference\n</code></pre>\n\n<p>Alternatively to the (sample) usage in the one pipeline:</p>\n\n<pre><code>Write-Messages -Verbose *&gt;&amp;1 | Split-Streams | Split-Streams -revert\n</code></pre>\n\n<p>(cf above code) you can call it as follows:</p>\n\n<pre><code>$test3 = Write-Messages -Verbose *&gt;&amp;1 | Split-Streams\n# preprocess the $test3 variable here (optional)\n$test3 | Split-Streams -revert\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-09T11:43:51.777", "Id": "225823", "ParentId": "224400", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:40:04.653", "Id": "224400", "Score": "4", "Tags": [ "logging", "powershell" ], "Title": "Powershell - Simplified Logging" }
224400
<p>I have a JavaScript function to categorize data by their "styles" attribute, and store the key-"unicode" pair.</p> <p>Here's my current code:</p> <pre><code>function processMetadata(metadata) { let regular = {}, solid = {}, brands = {} for (let icon in metadata) { let styles = metadata[icon].styles let codePoint = metadata[icon].unicode if (styles.includes('regular')) { regular[icon] = codePoint } if (styles.includes('solid')) { solid[icon] = codePoint } if (styles.includes('brands')) { brands[icon] = codePoint } } return {regular, solid, brands} } </code></pre> <p>However, CodeClimate keeps complaining about</p> <blockquote> <p>Function <code>processMetadata</code> has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring.</p> </blockquote> <p>I want to resolve this issue, but I'm not aware of any way to further reduce the complexity without reducing the performance of this code. The following snippet does reduce the cognitive complexity to under 5 but at the expense of performance (3+3 loops instead of 1) and extra dependency:</p> <pre><code>function processMetadata(metadata) { let regular = _.pickBy(metadata, icon =&gt; icon.styles.includes('regular')) regular = _.mapValues(regular, icon =&gt; icon.unicode) let solid = _.pickBy(metadata, icon =&gt; icon.styles.includes('solid')) solid = _.mapValues(solid, icon =&gt; icon.unicode) let brands = _.pickBy(metadata, icon =&gt; icon.styles.includes('brands')) brands = _.mapValues(brands, icon =&gt; icon.unicode) return {regular, solid, brands} } </code></pre> <p>Is there any way I can achieve this without having a significant impact on the performance?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:41:07.967", "Id": "435360", "Score": "0", "body": "Enforcing a complexity of 5 or lower seems too harsh. Is this a default setting, a personal setting or a team/company setting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T01:01:15.337", "Id": "435406", "Score": "0", "body": "@konjin It's the default setting. It's not that I have to satisfy the requirement, but I'd just like to know if there is any way to achieve it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T18:08:59.097", "Id": "435624", "Score": "0", "body": "Could you include an example input and output object?" } ]
[ { "body": "<p>First off, some code review items;</p>\n\n<ul>\n<li>Don't skip on semicolons</li>\n<li>You are not changing a number of variables, consider <code>const</code> over <code>let</code> in those cases</li>\n<li>The names of your styles match the names of your variables, you could use this</li>\n</ul>\n\n<p>Given that, I would consider something like this</p>\n\n<pre><code>function processMetadata(metadata) {\n let out = {regular: {}, solid: {}, brands: {}};\n for (const icon in metadata) {\n const styles = metadata[icon].styles;\n const codePoint = metadata[icon].unicode;\n for(const style in out){\n if (styles.includes(style)) {\n out[style][icon] = codePoint;\n }\n }\n }\n return out;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:35:37.663", "Id": "435346", "Score": "1", "body": "If you make the inner loop an `Array.forEach` then the callback functions content is not counted in the main functions complexity and should reduce the whole thing to 2 (depending on how you count it)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:29:08.803", "Id": "435357", "Score": "1", "body": "It would have been `Object.keys(out).forEach()` because `out` is an `Object`. I had considered it and didn't go for it in the end." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T01:13:22.650", "Id": "435407", "Score": "0", "body": "I think the semicolon or the lack of one is more of a personal/organizational preference than an issue? If you look at all the style guides over the Internet, some actually enforce no-semicolon. By the way, the project uses ESLint and it will warn you of any potential pitfall when relying on ASI." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T02:28:56.563", "Id": "435408", "Score": "0", "body": "Thank you, this does reduce the cognitive complexity to 6 (still 1 away from 5 ‍♂️) at the expense of 14% performance(which is acceptable for me)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:14:29.297", "Id": "435436", "Score": "0", "body": "Blindman67's suggestion works to get to 5. As for semicolons, I think it is idiomatic and will become more idiomatic over time. No-semicolons smell like a fad to me. (Very personal opinion of course)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:27:37.077", "Id": "224404", "ParentId": "224401", "Score": "2" } } ]
{ "AcceptedAnswerId": "224404", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T11:56:02.393", "Id": "224401", "Score": "3", "Tags": [ "javascript", "cyclomatic-complexity" ], "Title": "JavaScript function to categorize data by their \"styles\" attribute, and store the key-\"unicode\" pair" }
224401
<p>I am trying out some Go code examples (while coding a private project) to get more "in-depth" knowledge about the language.</p> <p>I have come across <a href="https://tour.golang.org/methods/18" rel="nofollow noreferrer">an exercise from the Go Tour website</a> about displaying correctly an IP number, making use of type method and the Stringer interface.</p> <p>I found two ways to achieve the goal but I am wondering if there is no other clean way of doing it.</p> <p>I strongly believe that a method with fewer code lines is always better - even though, looking around some Go OpenSource projects differs from that!</p> <p><a href="https://play.golang.org/p/yplYlWVgVR3" rel="nofollow noreferrer">Example 1 with range.</a></p> <pre><code>package main import "fmt" type IPAddr [4]byte // TODO: Add a "String() string" method to IPAddr. func (ip IPAddr) String() string { rs := "" for k, v := range ip { if k == 0 { rs += fmt.Sprintf("%v", v) continue } rs += fmt.Sprintf(".%v", v) } return rs } func main() { hosts := map[string]IPAddr{ "loopback": {127, 0, 0, 1}, "googleDNS": {8, 8, 8, 8}, } for name, ip := range hosts { fmt.Printf("%v: %v\n", name, ip) } } </code></pre> <p><a href="https://play.golang.org/p/p423hhwjsqO" rel="nofollow noreferrer">Example 2 with a simple <em>fmt.Sprintf</em></a></p> <pre><code>package main import "fmt" type IPAddr [4]byte // TODO: Add a "String() string" method to IPAddr. func (ip IPAddr) String() string { return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3]) } func main() { hosts := map[string]IPAddr{ "loopback": {127, 0, 0, 1}, "googleDNS": {8, 8, 8, 8}, } for name, ip := range hosts { fmt.Printf("%v: %v\n", name, ip) } } </code></pre> <p>What do you guys suggest?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T00:30:00.253", "Id": "435405", "Score": "0", "body": "\"I strongly believe that a method with fewer code lines is always better.\" Really?!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T07:52:41.043", "Id": "435515", "Score": "0", "body": "Yes totally! For me, one of the most painful tasks is to dig into legacy code with methods +50 lines that do 125 tasks controlled by another 66 \"if\" statements ..." } ]
[ { "body": "<blockquote>\n <p><a href=\"https://tour.golang.org/methods/18\" rel=\"nofollow noreferrer\">an exercise from the Go Tour website</a></p>\n \n <p>I found two ways to achieve the goal but I am wondering if there is no\n other clean way of doing it.</p>\n \n <p><a href=\"https://play.golang.org/p/yplYlWVgVR3\" rel=\"nofollow noreferrer\">Example 1 with range.</a></p>\n \n <p><a href=\"https://play.golang.org/p/p423hhwjsqO\" rel=\"nofollow noreferrer\">Example 2 with a simple <em>fmt.Sprintf</em></a></p>\n</blockquote>\n\n<hr>\n\n<p>Another way (Example 3):</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\ntype IPAddr [4]byte\n\nfunc (ip IPAddr) String() string {\n s := make([]byte, 0, (1+3)*len(IPAddr{}))\n for i, b := range ip {\n if i &gt; 0 {\n s = append(s, '.')\n }\n s = strconv.AppendInt(s, int64(b), 10)\n }\n return string(s)\n}\n\nfunc main() {\n hosts := map[string]IPAddr{\n \"loopback\": {127, 0, 0, 1},\n \"googleDNS\": {8, 8, 8, 8},\n }\n for name, ip := range hosts {\n fmt.Printf(\"%v: %v\\n\", name, ip)\n }\n}\n</code></pre>\n\n<p>Playground: <a href=\"https://play.golang.org/p/HQPd8cVAg-U\" rel=\"nofollow noreferrer\">https://play.golang.org/p/HQPd8cVAg-U</a></p>\n\n<p>Output:</p>\n\n<pre><code>loopback: 127.0.0.1\ngoogleDNS: 8.8.8.8\n</code></pre>\n\n<hr>\n\n<p>Yet another way (Example 4):</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"net\"\n)\n\ntype IPAddr [4]byte\n\nfunc (ip IPAddr) String() string {\n return net.IP(ip[:]).String()\n}\n\nfunc main() {\n hosts := map[string]IPAddr{\n \"loopback\": {127, 0, 0, 1},\n \"googleDNS\": {8, 8, 8, 8},\n }\n for name, ip := range hosts {\n fmt.Printf(\"%v: %v\\n\", name, ip)\n }\n}\n</code></pre>\n\n<p>Playground: <a href=\"https://play.golang.org/p/p3XKFFMBVI-\" rel=\"nofollow noreferrer\">https://play.golang.org/p/p3XKFFMBVI-</a></p>\n\n<p>Output:</p>\n\n<pre><code>loopback: 127.0.0.1\ngoogleDNS: 8.8.8.8\n</code></pre>\n\n<hr>\n\n<p>Go programmers strongly believe in meaningful code metrics. For example, performance.</p>\n\n<p>A Go benchmark for Example 1:</p>\n\n<pre><code>$ go test string1_test.go -bench=. -benchmem\n</code></pre>\n\n<p><code>string1_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"testing\"\n)\n\ntype IPAddr [4]byte\n\nfunc (ip IPAddr) String() string {\n rs := \"\"\n for k, v := range ip {\n if k == 0 {\n rs += fmt.Sprintf(\"%v\", v)\n continue\n }\n rs += fmt.Sprintf(\".%v\", v)\n }\n return rs\n}\n\nfunc BenchmarkString1(b *testing.B) {\n hosts := map[string]IPAddr{\n \"loopback\": {127, 0, 0, 1},\n \"googleDNS\": {8, 8, 8, 8},\n }\n for N := 0; N &lt; b.N; N++ {\n for name, ip := range hosts {\n fmt.Sprintf(\"%v: %v\\n\", name, ip)\n }\n }\n}\n</code></pre>\n\n<p>Running the same benchmark for all four examples:</p>\n\n<pre><code>BenchmarkString1-8 841730 1412 ns/op 176 B/op 19 allocs/op\nBenchmarkString2-8 1228399 931 ns/op 128 B/op 8 allocs/op\nBenchmarkString3-8 1765022 626 ns/op 128 B/op 8 allocs/op\nBenchmarkString4-8 1984806 574 ns/op 128 B/op 8 allocs/op\n</code></pre>\n\n<p>Examples 1 and 2 are inefficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T07:58:51.657", "Id": "435517", "Score": "0", "body": "Ok, I got the point with performance but, for instance, you are using in _Example 4_ the package **\"net\"**, which by the question context and my experience, unfortunately, I had no idea about (thanks for it!). In case that I want to be focused (as you) on performance, how normally do you proceed? You write few version of the same code, run a benchmark and pick the fastest? Curious to know how Go Programmer goes into the subject..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T00:11:52.027", "Id": "224447", "ParentId": "224403", "Score": "0" } }, { "body": "<p>Your first variant is unnecessary detailed and hard to read:</p>\n\n<ul>\n<li>an IPv4 address consists of exactly 4 digit groups</li>\n<li>4 is a small number, maybe it's worth to inline the <code>for</code> loop</li>\n<li>the <code>for</code> loop treats the case <code>k == 0</code> specially</li>\n<li>the <code>+=</code> operator for strings allocates a new string each time</li>\n<li>the code is much longer than the description in the task \"join the four numbers with dots\"</li>\n</ul>\n\n<p>Your second variant is short, easy to grasp and probably efficient enough for all practical cases.</p>\n\n<pre><code>func (ip IPAddr) String() string {\n return fmt.Sprintf(\"%v.%v.%v.%v\", ip[0], ip[1], ip[2], ip[3])\n}\n</code></pre>\n\n<p>You can replace the <code>%v</code> with <code>%d</code> to make it more specific, since the arguments are integer values.</p>\n\n<p>The main reason for choosing this variant is readability. The format string shows at a glance how the formatted string will look like.</p>\n\n<p>If you want to write the fastest possible code, you should probably allocate a byte array of size 3+1+3+1+3+1+3 and append each number and dot individually, without using a loop at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T05:24:28.330", "Id": "435416", "Score": "0", "body": "Did you use Go benchmarks to measure eficciency?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T05:26:07.863", "Id": "435417", "Score": "0", "body": "No, because speed is probably not the most important thing to measure in this case. This is a standalone program, not part of the standard library. And even if it were, it's not the code that gets called most often." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T08:40:47.310", "Id": "435427", "Score": "0", "body": "What is the unnecessary detail in the first variant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:26:44.997", "Id": "435439", "Score": "0", "body": "The for loop is unnecessary since it makes the code much longer and more complicated than necessary. The special case action for `k == 0` should be extracted from the loop. The string being built consumes another few tokens." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T05:02:01.113", "Id": "224454", "ParentId": "224403", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:25:19.140", "Id": "224403", "Score": "4", "Tags": [ "comparative-review", "formatting", "go", "interface", "ip-address" ], "Title": "Displaying IP addresses in Go using Stringer interface" }
224403
<p>I developed this CSS Masonry.</p> <p>It works with a CSS <code>grid</code> with <code>grid-auto-rows: 1px</code>. There is a JS <code>recalc</code> script in there, which recalculates the <code>grid-row-end</code> values (with the <code>span</code> prefix). Apart from that, the layout is totally up to the Browser's engine.</p> <p>(The <code>--raster</code> property is used to set vertical raster on or off. With the raster enanbled the heights of the items are calculated as multiples of the gaps, so the bottoms of the grid items align a little bit nicer).</p> <p><strong>On slow machines (esp. in Chrome) it might become a little bit laggy (not too dramatically), so I want to work on the performance a little bit.</strong></p> <p>I know, I could use a debounce on the <code>resize</code> event handler, but that's not the point here. I want to improve on the performace of the <code>recalc</code> function alone.</p> <p>I used <code>getElementsByClassName</code> instead of <code>querySelectorAll</code> to improve performance. I needed to filter the resulting Elements by only direct descendants (simulate <code>querySelectorAll(':scope &gt; .item')</code>). Don't know, if this is slower in the end than using <code>querySelectorAll</code> in the first place.</p> <p>I used <code>getBoundingClientRect()</code> to calculate height of the items, so there doesn't seem to be any improvement there.</p> <p><strong>Is there anything else I could improve?</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict"; console.clear(); { const gridClass = 'grid'; const itemClass = 'item'; const grid = document.getElementsByClassName(gridClass); const recalc = () =&gt; { Array.from(grid).forEach(gr =&gt; { // const items = gr.querySelectorAll(`:scope &gt; .${itemClass}`); const items = gr.getElementsByClassName(itemClass); Array.from(items) .filter(el =&gt; el.parentElement === gr) .forEach(it =&gt; { it.style.setProperty('grid-row-end', 'span 1'); const h = parseInt(Math.ceil(it.children[0].getBoundingClientRect().height)); const gap = parseInt(getComputedStyle(it).getPropertyValue('--gap')); const raster = !!parseInt(getComputedStyle(it).getPropertyValue('--raster'), 10) let span; if (raster) { span = parseInt(Math.ceil((h + gap) / gap) * gap); } else { span = parseInt(Math.ceil(h + gap)); } it.style.setProperty('grid-row-end', `span ${span}`); }) }) } window.addEventListener('resize', recalc); window.addEventListener('load', recalc); recalc() }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grid { --cols: 12; --gap: 16; --raster: 1; display: grid; grid-template-columns: repeat(var(--cols, 12), calc((100% - 1px * var(--gap, 20) * (var(--cols, 12) - 1)) / var(--cols, 12))); grid-auto-rows: 1px; grid-gap: 0px calc(1px * var(--gap, 20)); margin-top: calc(-1px * var(--gap, 20)); } @media screen and (max-width: 900px) and (min-width: 600px) { .grid { --cols: 8; } } @media screen and (max-width: 599px) { .grid { --cols: 4; } } .grid &gt; .item { grid-column-end: span 4; grid-row-end: span 400; margin-top: calc(1px * var(--gap, 20)); display: flex; flex-direction: column; justify-items: stretch; } .grid &gt; .item &gt; div { background-color: gold; flex-basis: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;CSS Grid Masonry with little help from JS&lt;/h1&gt; &lt;div class="grid" style="--raster: 1;"&gt; &lt;div class="item"&gt; &lt;div&gt;&lt;div&gt;1&lt;br&gt;1&lt;br&gt;&lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;&lt;div&gt;2&lt;br&gt;2&lt;br&gt;2&lt;br&gt;2&lt;br&gt;2&lt;br&gt;2&lt;br&gt;2&lt;br&gt;&lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;3&lt;br&gt;3&lt;br&gt;3&lt;br&gt;3&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;4&lt;br&gt;4&lt;br&gt;4&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;5&lt;br&gt;5&lt;br&gt;5&lt;br&gt;5&lt;br&gt;5&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;6&lt;br&gt;6&lt;br&gt;6&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;7&lt;br&gt;7&lt;br&gt;7&lt;br&gt;7&lt;br&gt;7&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;8&lt;br&gt;8&lt;br&gt;8&lt;br&gt;8&lt;br&gt;8&lt;br&gt;&lt;div class="item"&gt;item&lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;9&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;10&lt;br&gt;10&lt;br&gt;10&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;11&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;12&lt;br&gt;12&lt;br&gt;12&lt;br&gt;12&lt;br&gt;12&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;13&lt;br&gt;13&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;14&lt;br&gt;14&lt;br&gt;14&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;15&lt;br&gt;15&lt;br&gt;15&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;16&lt;br&gt;16&lt;br&gt;16&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;17&lt;br&gt;17&lt;br&gt;17&lt;br&gt;17&lt;br&gt;17&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;18&lt;br&gt;18&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;19&lt;br&gt;19&lt;br&gt;19&lt;br&gt;19&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;20&lt;br&gt;20&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;21&lt;br&gt;21&lt;br&gt;21&lt;br&gt;21&lt;br&gt;21&lt;br&gt;21&lt;br&gt;21&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;22&lt;br&gt;22&lt;br&gt;22&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;23&lt;br&gt;23&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;24&lt;br&gt;24&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div&gt;25&lt;br&gt;25&lt;br&gt;25&lt;br&gt;25&lt;br&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h1>Good things</h1>\n<ul>\n<li>variables are block scoped, declared with <code>const</code> unless re-assignment is necessary</li>\n<li>indentation is consistent</li>\n</ul>\n<h1>Suggestions</h1>\n<h2>Number of times <code>recalc</code> is called initially</h2>\n<p>Given the last two lines of the whole block:</p>\n<blockquote>\n<pre><code> window.addEventListener('load', recalc);\n recalc()\n</code></pre>\n</blockquote>\n<p>Is the last line really necessary, given that the function would be called when the window is loaded? Perhaps instead of listening for the <code>load</code> event it should listen for the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event\" rel=\"nofollow noreferrer\"><code>DOMContentLoaded</code> event</a>.</p>\n<h2>loops</h2>\n<p>It looks like the code does the following:</p>\n<ul>\n<li>loops over elements with class name <code>grid</code>\n<ul>\n<li>loops over sub-elements with class <code>item</code>\n<ul>\n<li>filters out any item that isn't a child of the outer element with class <code>grid</code>, yet the inner loop doesn't appear to depend on the outer element with class <code>grid</code></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>I'm not sure what would be quicker but I would either take one of these approaches:</p>\n<ul>\n<li>use <code>document.querySelectorAll('.grid &gt; .item')</code> (like you mentioned in the description) to find the elements to iterate over, thus allowing one loop instead of a loop inside a loop</li>\n<li>instead of calling <code>.filter().forEach()</code> do one loop - instead of the <code>.filter()</code> have the <code>.forEach()</code> callback return if the parent is not <code>gr</code>.</li>\n</ul>\n<h2>spreading items into an array</h2>\n<p>Instead of calling <code>Array.from()</code> - e.g.</p>\n<blockquote>\n<pre><code>Array.from(grid)\n</code></pre>\n</blockquote>\n<p>the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> can be used for the same result:</p>\n<pre><code>[...grid]\n</code></pre>\n<h2>Redundant styles</h2>\n<p>The CSS for <code>.grid</code> contains <code>--raster: 1</code></p>\n<blockquote>\n<pre><code>.grid {\n --cols: 12;\n --gap: 16;\n --raster: 1;\n</code></pre>\n</blockquote>\n<p>And yet the element with class <code>grid</code> has the <code>--raster</code> style in-line:</p>\n<blockquote>\n<pre><code>&lt;div class=&quot;grid&quot; style=&quot;--raster: 1;&quot;&gt;\n</code></pre>\n</blockquote>\n<p>I see that the inline style is used by the JavaScript code to determine the calculation for <code>span</code>. It may be simpler to simply make a class name - e.g.</p>\n<pre><code>.raster1 { \n --raster: 1\n}\n</code></pre>\n<p>Then add that to the list of class names for that element and check for that class name in the JavaScript code instead of parsing the inline-style.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T00:10:21.543", "Id": "248065", "ParentId": "224405", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:33:29.540", "Id": "224405", "Score": "6", "Tags": [ "javascript", "css", "ecmascript-6" ], "Title": "Pure (almost) CSS Masonry" }
224405
<p>I'm working on a segment of code where it runs a number of tasks and then combine individual task results to construct a complete task result object, there's no concurrency involved so it's purely a question of the best use of class inheritance/pattern.</p> <p>Below is the skeleton of the code I've written, it loops through <code>IList&lt;ITask&gt;</code> where each <code>ITask</code> returns an <code>ITaskResult</code>, the main method will then have to examine the type of each <code>ITaskResult</code> and set the property on <code>CompleteTaskResult</code> accordingly. </p> <p>The goal is to keep the code easy to understand and easy to add new Task/TaskResult.</p> <p>What I'm not happy about is the part where it has to check the type of <code>ITaskResult</code> individually and then set the value on <code>CompleteTaskResult</code>, it feels a little cumbersome with lots of repetitions.</p> <p>Is there a better way to structure this code?</p> <p>Thanks. </p> <pre><code> public interface ITask { ITaskResult Execute(); } public class AlphaTask : ITask { public ITaskResult Execute() { return new AlphaTaskResult(); } } public class BetaTask : ITask { public ITaskResult Execute() { return new BetaTaskResult(); } } public class GammaTask : ITask { public ITaskResult Execute() { return new GammaTaskResult(); } } public interface ITaskResult { } public class AlphaTaskResult : ITaskResult { } public class BetaTaskResult : ITaskResult { } public class GammaTaskResult : ITaskResult { } public class CompleteTaskResult { public AlphaTaskResult AlphaTaskResult { get; set; } public BetaTaskResult BetaTaskResult { get; set; } public GammaTaskResult GammaTaskResult { get; set; } } static void Main(IList&lt;ITask&gt; tasks) { var taskResults = tasks.Select(x =&gt; x.Execute()); var completeTaskResult = new CompleteTaskResult(); foreach (var taskResult in taskResults) { if (taskResult is AlphaTaskResult alphaTaskResult) { completeTaskResult.AlphaTaskResult = alphaTaskResult; continue; } if (taskResult is BetaTaskResult betaTaskResult) { completeTaskResult.BetaTaskResult = betaTaskResult; continue; } if (taskResult is GammaTaskResult gammaTaskResult) { completeTaskResult.GammaTaskResult = gammaTaskResult; continue; } throw new InvalidOperationException("unsupported task") } } </code></pre> <p>Edit: The intention is one can pass a number of tasks in the form of <code>IList&lt;ITask&gt;</code> to the library and then retrieve concrete results back from <code>CompleteTaskResult</code> <code>CompleteTaskResult</code> may have null properties if no specific tasks related to the properties were executed. The main caller is well aware of what concrete type of <code>ITask</code> were sent in so it also knows what properties from <code>CompleteTaskResult</code> to query for the results</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:14:14.630", "Id": "435322", "Score": "1", "body": "Why does `CompleteTaskResult` contain specific result types, instead of a list of `ITaskResult`s? If that is intentional, then why does `Main` accept a list of `ITask`s, instead of specific task types whose output match the properties in `CompleteTaskResult`? (Note that your code is fairly abstract. That tends to result in downvotes due to lack of concrete context)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:26:02.517", "Id": "435324", "Score": "2", "body": "Your question lacks concrete context about your specific design desicions. Why do you need to know the specific type of `ITaskResult` at all. Give it a meaningful interface, with properties and functions you can use independently of the underlying type. Note that asking for reviewing stub code like that is _off-topic_ here. – πάντα ῥεῖ 8 mins ago" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:45:54.820", "Id": "435325", "Score": "0", "body": "@PieterWitvoet The idea is that the caller of `main` can send in any number of `ITask` and then receive the results from `CompleteTaskResult` by querying specific result types. `CompleteTaskResult` is the client-facing side of object so it contains concrete types. Without the use of `List<ITask>`, I'm not sure the best way to achieve that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:48:36.720", "Id": "435328", "Score": "0", "body": "@πάνταῥεῖ `CompleteTaskResult` is what the end-user will interact with so it needs to have some concrete types. Sorry if the code lacks sufficient context, this is what I have in mind so I'm seeking some early advise (I know this is not perfect)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:52:09.860", "Id": "435329", "Score": "0", "body": "@Godsent Generally we only review fully working code for improvement here. If you have a specific question regarding the usage of the [tag:design-patterns] then that tag is appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:52:54.497", "Id": "435330", "Score": "4", "body": "This code is too sketchy and hypothetical to review. Foo/bar examples are not acceptable on Code Review. What do these tasks have in common, and how do they differ? You need to post your real code, or at least something plausibly realistic, so that we can give you proper advice. Please see [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:57:27.247", "Id": "435332", "Score": "2", "body": "@πάνταῥεῖ thanks, I'll ask for advise again after I get it fully working, my apologies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:06:43.890", "Id": "435337", "Score": "2", "body": "@Godsent: that makes little sense. If your method accepts a list of `ITask`, then it should return a list of `ITaskResult` (if necessary, a caller could use Linq's `OfType<T>` to fetch specific results). If it specifically returns only an alpha, beta and gamma result, then it should accept only an alpha, beta and gamma task. Otherwise, what about callers that pass in omega tasks? Or multiple alpha tasks?" } ]
[ { "body": "<p>You could simply add the task results to a collection. Different types of collections can be used:</p>\n\n<ol>\n<li><p><code>List&lt;ITaskResult&gt;</code>: You can add several results of the same type. You must enumerate to find a task of a specific type.</p></li>\n<li><p><code>Dictionary&lt;Type, ITaskResult&gt;</code>: Each task result type can be added only once. You can query specific task types.</p>\n\n<pre><code>if (results.TryGetValue(typeof(BetaTaskResult), out ITaskResult taskResult)) {\n ...\n}\n</code></pre>\n\n<p>or if you know a result is there for sure:</p>\n\n<pre><code>ITaskResult taskResult = results[typeof(BetaTaskResult)];\n</code></pre>\n\n<p>Of course, you can also use other types of keys, like enums or strings.</p></li>\n<li><p><code>Dictionary&lt;Type, List&lt;ITaskResult&gt;&gt;</code>: Each task result type can be added several times. You can query specific task result types. Handling is a bit more complex.</p></li>\n</ol>\n\n<p>If you want to access members who are not part of the interface, you must cast the result to specific types.</p>\n\n<pre><code>// Assuming each result type occurs only once.\nDictionary&lt;Type, ITaskResult&gt; results = tasks\n .Select(x =&gt; x.Execute())\n .ToDictionary(r =&gt; r.GetType()); // alternative: .ToList()\n</code></pre>\n\n<hr>\n\n<p>If you prefer to keep your current solution, you can simplify it a bit. This will enumerate the tasks several times; however, this is acceptable, because you have a very small number of tasks.</p>\n\n<pre><code>var taskResults = tasks\n .Select(x =&gt; x.Execute())\n .ToList();\nvar completeTaskResult = new CompleteTaskResult {\n AlphaTaskResult = taskResults.OfType&lt;AlphaTaskResult&gt;().FirstOrDefault(),\n BetaTaskResult = taskResults.OfType&lt;BetaTaskResult&gt;().FirstOrDefault(),\n GammaTaskResult = taskResults.OfType&lt;GammaTaskResult&gt;().FirstOrDefault(),\n};\n</code></pre>\n\n<p>It is important to call <code>.ToList()</code>, otherwise this would execute the tasks several times.</p>\n\n<p>See also: <a href=\"https://blogs.msdn.microsoft.com/ericwhite/2006/10/04/lazy-evaluation-and-in-contrast-eager-evaluation/\" rel=\"nofollow noreferrer\">Lazy Evaluation (and in contrast, Eager Evaluation)</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T14:23:47.467", "Id": "435452", "Score": "1", "body": "I up-voted, but in the future I would refrain from answering questions that are clearly off-topic. @see https://codereview.stackexchange.com/help/how-to-answer and https://codereview.stackexchange.com/help/dont-ask" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T13:30:58.297", "Id": "224409", "ParentId": "224407", "Score": "1" } } ]
{ "AcceptedAnswerId": "224409", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T12:47:58.853", "Id": "224407", "Score": "-1", "Tags": [ "c#", "object-oriented", "design-patterns", "inheritance" ], "Title": "Class Inheritance in C# (possibly generics)" }
224407
<p>I've implemented <a href="https://en.cppreference.com/w/cpp/algorithm/includes" rel="nofollow noreferrer">C++'s <code>std::includes</code> algorithm</a> in Python, so that I can use it to efficiently implement a Scrabble "can I make this word" function:</p> <pre><code>def word_can_be_made_from_rack(word, rack): return set_includes(sorted(rack), sorted(word)) </code></pre> <p>Here's the implementation, with some test cases:</p> <pre><code>def set_includes(haystack, needle): j = 0 hn = len(haystack) for c in needle: while j != hn and haystack[j] &lt; c: j += 1 if j == hn: return False if haystack[j] &gt; c: return False j += 1 return True assert set_includes('abcdef', 'af') assert set_includes('abcdef', 'bce') assert set_includes('abcdef', 'abcdef') assert set_includes('aaaaa', 'a') assert set_includes('aaaaa', 'aa') assert set_includes('aaaaax', 'ax') assert set_includes('abbbcxx', 'abc') </code></pre> <p>This is similar to <a href="https://codereview.stackexchange.com/questions/215324/find-if-one-list-is-a-subsequence-of-another">Find if one list is a subsequence of another</a> except that it assumes (and requires) that the two input strings are sorted.</p> <p>The manual management of index <code>j</code> in this code doesn't feel very Pythonic. Am I missing an easier way to write this algorithm?</p> <p><code>itertools</code> one-liners <strong>will</strong> be accepted as answers, especially if they're more performant. :)</p>
[]
[ { "body": "<ul>\n<li><p>AFNP. The loop condition <code>j != hn</code> is more idiomatically expressed as an exception:</p>\n\n<pre><code>try:\n for c in needle:\n while haystack[j] &lt; c:\n ....\nexcept IndexError:\n return False\n</code></pre></li>\n<li><p>No naked loops. Factor the <code>while haystack[j] &lt; c:</code> into a function. Among other benefits, it'd allow</p>\n\n<pre><code> j = search_character(haystack[j:], c)\n</code></pre></li>\n<li><p>The binary search for <code>c</code> seems more performant than linear. See <a href=\"https://docs.python.org/2/library/bisect.html\" rel=\"nofollow noreferrer\">bisect</a> module.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:57:18.537", "Id": "435364", "Score": "0", "body": "AFNP? Do you mean [EAFP](https://docs.python.org/3/glossary.html#term-eafp)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:12:46.793", "Id": "435374", "Score": "0", "body": "@MathiasEttinger Same (Ask Forgiveness, Not Permission)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:17:51.437", "Id": "224414", "ParentId": "224412", "Score": "1" } }, { "body": "<p>I had an idea to just try to make the word by removing all the needed characters from the rack/haystack and see if it works. The idea also follows the \"Easier to ask for forgiveness than permission\" approach.</p>\n\n<pre><code>def set_includes(haystack, needle):\n haystack = list(haystack)\n try:\n for char in needle:\n haystack.remove(char)\n return True\n except ValueError:\n return False\n</code></pre>\n\n<p>Obviously, this will scale badly for cases where <code>haystack == needle</code> for larger string lengths (noticeable starting at about n >= 500), but it does not need sorting. So you will have to check whether or not this is more efficient for your use case.</p>\n\n<p>Depending on how often the check would return false because <code>needle</code> does contain one or more letters that are not on the rack, <a href=\"https://docs.python.org/2/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set</code></a>s can maybe help you to take a shortcut:</p>\n\n<pre><code>if set(haystack).issuperset(needle):\n # check if there are enough letters to build needle from haystack\n ...\nelse:\n # haystack does not contain all the letters needed to build needle\n return False\n</code></pre>\n\n<hr>\n\n<p>Just for fun: We here in Python have iterators, too :-D</p>\n\n<pre><code>def set_includes(haystack, needle):\n it1 = iter(haystack)\n it2 = iter(needle)\n char2 = next(it2)\n while True:\n try:\n char1 = next(it1)\n except StopIteration:\n return False\n if char2 &lt; char1:\n return False\n\n if not char1 &lt; char2:\n try:\n char2 = next(it2)\n except StopIteration:\n return True\n</code></pre>\n\n<p>If you move the last <code>try: ... catch ...:</code> a few levels outwards, you can get quite close to the structure of the possible implementation given on cppreference. Don't take this to serious though. </p>\n\n<p>We can do a little bit better:</p>\n\n<pre><code>def set_includes(haystack, needle):\n it2 = iter(needle)\n char2 = next(it2)\n for char1 in haystack:\n if char2 &lt; char1:\n return False\n\n if not char1 &lt; char2:\n try:\n char2 = next(it2)\n except StopIteration:\n return True\n\n return False\n</code></pre>\n\n<p>Here, at least one of the <code>try: ... catch ...:</code>s is transformed into a proper loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:15:44.657", "Id": "224424", "ParentId": "224412", "Score": "1" } }, { "body": "<h2>Use str.index()</h2>\n\n<p>The lines:</p>\n\n<pre><code> while j != hn and haystack[j] &lt; c:\n j += 1\n</code></pre>\n\n<p>are basically trying to find the index of <code>c</code> in <code>haystack.</code>\nSo just use <code>str.index()</code>:</p>\n\n<pre><code>def set_includes(haystack, needle):\n try:\n i = -1\n for c in needle:\n i = haystack.index(c, i+1)\n\n except ValueError:\n return False\n\n return True\n</code></pre>\n\n<p>Or, if you prefer use <code>str.find()</code>:</p>\n\n<pre><code>def set_includes(haystack, needle):\n i = -1\n for c in needle:\n i = haystack.find(c, i+1)\n if i&lt;0:\n return False\n return True\n</code></pre>\n\n<h3>itertools one-liner</h3>\n\n<p>Almost forgot, here's your one-liner:</p>\n\n<pre><code>from itertools import groupby\n\nset_includes = lambda h, n:not any(h.find(''.join(g))&lt;0 for _,g in groupby(n)) \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T21:55:28.170", "Id": "224442", "ParentId": "224412", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T14:40:09.393", "Id": "224412", "Score": "1", "Tags": [ "python", "algorithm", "strings", "python-2.x" ], "Title": "`set_includes` (string subsequence-containment) in Python 2" }
224412
<p>I have Ajax function with a callback which fetches all the Patient data however I have some perfomance issues and trying to figure out what it might be, does anyone have idea? That's my Code</p> <pre><code>var patient = new Array(); function sync(arg, callback){ //ajax result $('.loader').show(); $.ajax({ method: 'GET', url: 'sync/active.php', dataType: 'json', data: arg, // argument schicken und aktualisieren success: function(data, status, xhr){ $('.loader').hide(); callback(data); // setTimeout(sync, ajaxDelay); }, error: function(xhr, ajaxOptions, thrownError){ console.log(thrownError); } }); } function onPatientCallback(data) { var res = data; for(var i=0; i&lt;res.length;i++){ for(var key in res[i]){ var value = res[i][key]; switch(key){ case "id": res[i][key] = parseInt(value); break; case "kundennr": res[i][key] = parseInt(value); break; case "client": res[i][key] = value; break; case "start": res[i][key] = new Date(value); break; case "end": res[i][key] = new Date(value); break; case "title": res[i][key] = value; break; case "description": res[i][key] = value; break; case "termart": res[i][key] = parseInt(value); break; case "userId": res[i][key] = parseInt(value); break; default: console.log("unbekannter Datentyp "+key); } } } patient = res; } </code></pre> <p>I use the function to fill the patient variable and call it in another js file like that <code>sync({calling: "patient"}, onPatientCallback);</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:03:54.390", "Id": "435370", "Score": "0", "body": "Is this real life or for school?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:08:04.080", "Id": "435373", "Score": "0", "body": "it's for work and the function should have the best performance in all browsers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:20:44.160", "Id": "435376", "Score": "1", "body": "Welcome to Code Review! For the sake of reviewers, would you be able to [edit] your post to include 1. when `snyc()` and `onPatientCallback()` are called, and 2. possible HTML corresponding to this code?" } ]
[ { "body": "<p>From a short review;</p>\n\n<ul>\n<li><code>patient</code> is a global variable, <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"nofollow noreferrer\">global variables are bad</a></li>\n<li><code>var patient = []</code> is more idiomatic than <code>var patient = new Array();</code></li>\n<li>Comments should be all German or all English (I would go for all English, its the common language of the developers)</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch\" rel=\"nofollow noreferrer\">You can group <code>switch</code> labels</a>, this is valid JavaScript:</p>\n\n<pre><code> switch(key){\n case \"id\":\n case \"kundennr\":\n case \"termart\":\n case \"userId\":\n res[i][key] = parseInt(value);\n break;\n case \"client\":\n case \"title\":\n case \"description\":\n res[i][key] = value;\n break;\n case \"start\":\n case \"end\":\n res[i][key] = new Date(value);\n break;\n default:\n console.log(\"unbekannter Datentyp \" + key);\n</code></pre></li>\n<li>Your data fields should be either all English or all German (you have <code>userId</code>, but also <code>kundennr</code>), here as well I would go for all English</li>\n<li>Since <code>value</code> already contains <code>res[i][key]</code> for \"client\", \"title\", etc., you should probably comment on that </li>\n<li>Since this is real, you should not log to console for an unknown data type, you should call a REST service that will log this entry in a database table, and even possibly send out an email to developers </li>\n<li><code>var key in Object.keys(res[i])</code> is safer than <code>var key in res[i]</code>, you never know when someone decides to extend <code>Object</code></li>\n<li>Your indenting is off, consider using a beautifier</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T18:07:20.943", "Id": "224429", "ParentId": "224420", "Score": "2" } } ]
{ "AcceptedAnswerId": "224429", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:49:45.637", "Id": "224420", "Score": "3", "Tags": [ "javascript", "performance", "jquery", "ajax", "callback" ], "Title": "Ajax function with a callback" }
224420
<p>About this <a href="https://www.hackerrank.com/challenges/30-2d-arrays/problem" rel="nofollow noreferrer">2D Arrays</a> HackerRank problem. </p> <p>The task is to find the maximum sum of a region in a 2D array. Specifically, it is to find the maximum sum of an "hourglass" region, defined as a 3x3 square without the middle entries on the left and right sides, as shown by this mask. </p> <pre><code>1 1 1 0 1 0 1 1 1 </code></pre> <p>Here's my solution.</p> <p>I'd appreciate some review about code quality.</p> <pre class="lang-py prettyprint-override"><code># Begin of HackerRank code: data entries for testing the user code # ---------------------------------------------------------------- arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) # ---------------------------------------------------------------- # End of HackerRank code my_hourglasses = list() for i in range(0,4): for j in range(0,4): hourglass = list() hourglass += arr[i][j:j+3] hourglass.append(arr[i+1][j+1]) hourglass += arr[i+2][j:j+3] my_hourglasses.append(hourglass) hourglasses_sums = [sum(item) for item in my_hourglasses] print(max(hourglasses_sums)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:07:53.030", "Id": "435372", "Score": "10", "body": "Links can rot or become broken. [Please include a description of the challenge here in your question.](https://codereview.meta.stackexchange.com/a/1994)" } ]
[ { "body": "<p>One thing I like about this code is the clear division of role. </p>\n\n<p>You have a section for identifying and extracting the hourglasses. Then you sum the individual hourglasses. Then you find the maximum. </p>\n\n<p>There's a quote by Computer Scientist Tony Hoare that \"There are two ways to write code: write code so simple there are obviously no bugs in it, or write code so complex that there are no obvious bugs in it.\" The clear structure helps make this into the first category. This is the sort of code that I'd like to see, for example, in a reference implementation or test case. </p>\n\n<p>On the other hand, that simplicity comes at a cost. Your implementation requires allocating a bunch of extra memory to hold all the temporary hourglasses, and a bit more still to hold all the sums. </p>\n\n<p>In principle, you could add them up as soon as you identify the elements in an hourglass, and then only store <code>hourglasses_sums</code> instead of <code>my_hourglasses</code>. Furthermore, instead of storing a list of all the sums you have seen, you could just keep track of the highest score you have seen thus far. You'd then have something like this:</p>\n\n<pre><code>max_hourglass_score = -63 # Minimum possible score = -9 * 7\nfor i in range(0,4):\n for j in range(0,4):\n hourglass = list()\n hourglass += arr[i][j:j+3]\n hourglass.append(arr[i+1][j+1])\n hourglass += arr[i+2][j:j+3]\n hourglass_sum = sum(hourglass)\n max_hourglass_score = max(max_hourglass_score, hourglass_sum)\n\nprint(max_hourglass_score)\n</code></pre>\n\n<p>Of course, the same pattern could be applied to do the sum as you go rather than picking it into an intermediate <code>hourglass</code> list.</p>\n\n<pre><code>max_hourglass_score = -63 # Minimum possible score\nfor i in range(0,4):\n for j in range(0,4):\n hourglass_sum = 0\n hourglass_sum += sum(arr[i][j:j+3])\n hourglass_sum += arr[i+1][j+1]\n hourglass_sum += sum(arr[i+2][j:j+3])\n max_hourglass_score = max(max_hourglass_score, hourglass_sum)\n\nprint(max_hourglass_score)\n</code></pre>\n\n<p>This only allocates a few primitive variables rather than all the extra arrays you had before. </p>\n\n<p>There are in fact still cleverer algorithms which require fewer arithmetic operations. The key idea is easier to explain with squares rather than hourglasses. \nIf you look at the square in the top left corner and compare it with the square one place across, many of the entries are the same. Specifically, of the nine entries in a square, six are overlapped. The potential for speeding up the program come from not looking that the overlap squares any more, but starting from the last sum, taking away the values that are no longer in it, and adding the values that are new to it. </p>\n\n<p>That algorithm, however clever, is complicated. It's hard to get right, and even hard to see whether it is right. It's therefore a judgement call how much you value making your code run as fast as possible, and how much you prefer writing it in a way that is easy to understand. There isn't a best answer. It depends on what you want to use it for. If this were running in real time on video frames and were (somewhat appropriately) the biggest bottleneck in your program, then you'd probably prefer faster. If it's trundling along on a small grid, you would want clear code. </p>\n\n<hr>\n\n<p>A couple of other general comments:</p>\n\n<ul>\n<li>Variable naming is important. Although \"hourglass\" would usually seem like a fairly specific and helpful word to identify what's going on, when three of your main variables are built around the same word one should wonder whether it actually gets confusing. (Also, \"my_\" is usually unnecessary.)</li>\n<li>I appreciate the use of Python comprehensions. If you only want to use it once, a generator comprehension is often better. In terms of how it's written, just swap the square brackets around <code>sum(item) for item in my_hourglasses</code> for parentheses. In terms of what it does, it avoids actually doing the calculation until you need it, giving space and sometimes time savings.</li>\n<li>Beware of magic numbers. I realise that 4 is the width of the big grid, minus 2, which you need because the width of the hourglass is 3 and the overlap is 1. But that's not immediately obvious, so it's worth spelling out what 4 means. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T19:34:13.110", "Id": "435887", "Score": "0", "body": "Thanks! But I got lost `max_hourglass_score = -63 # Minimum possible score = -9 * 7`. Where this calculation came from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T19:36:20.387", "Id": "435888", "Score": "0", "body": "I enjoyed a lot the `max_hourglass_score = max(max_hourglass_score, hourglass_sum)`. Sounded very clever to me. It´s a great way to avoid using \"if\" for cheking the highest value, isn´t it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T20:05:48.887", "Id": "435894", "Score": "2", "body": "The problem description says that each cell is between plus and minus 9, and an hourglass has 7 cells. Therefore the minimum possible total is 7*-9" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T20:09:44.023", "Id": "435896", "Score": "1", "body": "And yes, max(old_max, new_possible) hides the if. It doesn't behave any differently, but most people would find it easier to read." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T22:44:16.363", "Id": "224443", "ParentId": "224421", "Score": "5" } } ]
{ "AcceptedAnswerId": "224443", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T15:55:10.337", "Id": "224421", "Score": "1", "Tags": [ "python", "algorithm", "python-3.x", "programming-challenge" ], "Title": "HarckerRank 2D Arrays Hourglass challenge" }
224421
<p>I've decided to start working on a budget application for the purposes of getting started on Rust. In its current form this program takes given expenses and income and tells the user whether they have a surplus, a deficit, or if they are breaking even. I will add more functionality to this program as I move along in the development process.</p> <p>Did I respect every best practice in Rust ? Is there something I could improve ?</p> <pre><code>use std::io; use std::process; fn income_ask() -&gt; String { println!("Add income? [y/n]: "); let mut add_income = String::new(); io::stdin() .read_line(&amp;mut add_income) .expect("Failed to read input"); return add_income; } fn income_sum(income_list: &amp;Vec&lt;u64&gt;, income: &amp;mut u64) { *income = income_list.iter().sum(); println!("{}", income); } fn expense_ask() -&gt; String { println!("Add expense? [y/n]: "); let mut add_expense = String::new(); io::stdin() .read_line(&amp;mut add_expense) .expect("Failed to read input"); return add_expense; } fn expense_sum(expense_list: &amp;Vec&lt;u64&gt;, expenses: &amp;mut u64) { *expenses = expense_list.iter().sum(); } fn prompt_income(income_list: &amp;mut Vec&lt;u64&gt;, income_name: &amp;mut Vec&lt;String&gt;, income: &amp;mut u64) { loop { let result = income_ask(); if result.trim() == "y" { println!("Enter source of income. [Numbers Only]: "); let mut income_input = String::new(); io::stdin() .read_line(&amp;mut income_input) .expect("Failed to read input"); let income_input: u64 = match income_input.trim().parse() { Ok(num) =&gt; num, Err(_) =&gt; continue, }; income_list.push(income_input); println!("Enter income name. [Name Only]: "); let mut income_name1 = String::new(); io::stdin() .read_line(&amp;mut income_name1) .expect("Failed to read input"); income_name.push(income_name1); } else { break; } } income_sum(&amp;income_list, income); println!("Total user income: {} ", income); } fn prompt_expense(expense_list: &amp;mut Vec&lt;u64&gt;, expense_name: &amp;mut Vec&lt;String&gt;, expenses: &amp;mut u64) { loop { let result = expense_ask(); if result.trim() == "y" { println!("Enter expense amount. [Numbers Only]: "); let mut expense_input = String::new(); io::stdin() .read_line(&amp;mut expense_input) .expect("Failed to read input"); let expense_input: u64 = match expense_input.trim().parse() { Ok(num) =&gt; num, Err(_) =&gt; continue, }; expense_list.push(expense_input); println!("Enter expense name. [Name Only]: "); let mut expense_name1 = String::new(); io::stdin() .read_line(&amp;mut expense_name1) .expect("Failed to read input"); expense_name.push(expense_name1); } else { break; } expense_sum(&amp;expense_list, expenses); println!("Total user expenses: {}", expenses); } } fn uservalue(income: u64, expenses: u64) { let valoutput: i64; valoutput = income as i64 - expenses as i64; if valoutput &lt; 0 { println!( "You are in the negative, you have a deficit of {}", valoutput ); } else if valoutput == 0 { println!("You have broken even, you are spending exactly as much as you make."); } else if valoutput &gt; 0 { println!( "You are in the positive, you have a surplus of {}", valoutput ); } } fn close_program() { println!("Exiting Program."); process::exit(1); } fn main() { let mut expense_list: Vec&lt;u64&gt; = Vec::new(); let mut income_list: Vec&lt;u64&gt; = Vec::new(); let mut expense_name: Vec&lt;String&gt; = Vec::new(); let mut income_name: Vec&lt;String&gt; = Vec::new(); let mut income: u64 = 0; let mut expenses: u64 = 0; loop { prompt_income(&amp;mut income_list, &amp;mut income_name, &amp;mut income); prompt_expense(&amp;mut expense_list, &amp;mut expense_name, &amp;mut expenses); uservalue(income, expenses); println!("Would you like to run another analysis? [y/n]: "); let mut another = String::new(); io::stdin() .read_line(&amp;mut another) .expect("Failed to read input"); if another.trim() == "y" { income = 0; expenses = 0; expense_list.clear(); income_list.clear(); expense_name.clear(); income_name.clear(); } else { close_program(); } } } </code></pre>
[]
[ { "body": "<p>I rewrote some of your program to make it more idiomatic in Rust. I tried to comment significant changes I made, but if you have any questions about why I changed things, you can click \"add a comment\" below my answer. Side note: the comments I made aren't necessarily good code comments (as in I wouldn't keep them in the code, they're just to explain to you the changes)</p>\n\n<pre><code>// Pulling out this repeated code into one function reduces repetition.\nfn ask(buf: &amp;mut String, prompt: &amp;str, guide: &amp;str) {\n use std::io::{stdin, stdout, Write};\n\n // Using print (not println) lets you have the input seen on the same line.\n print!(\"{} [{}]: \", prompt, guide);\n // Since stdout is line-buffered, you must flush if you are not printing a new line.\n stdout().flush().expect(\"Failed to flush output\");\n stdin().read_line(buf).expect(\"Failed to read input\");\n}\n\nfn ask_name(prompt: &amp;str) -&gt; String {\n let mut buf = String::new();\n ask(&amp;mut buf, prompt, \"Name only\");\n buf\n}\n\n// Here we keep asking until we get a valid number.\nfn ask_numeric(prompt: &amp;str) -&gt; u64 {\n let mut buf = String::new();\n loop {\n ask(&amp;mut buf, prompt, \"Numbers only\");\n if let Ok(num) = buf.trim().parse() {\n return num;\n }\n buf.clear();\n println!(\"Try again.\");\n }\n}\n\n// Here we may also want to keep asking until we get either y/n, to be more exact.\nfn ask_yn(prompt: &amp;str) -&gt; bool {\n let mut buf = String::new();\n ask(&amp;mut buf, prompt, \"y/n\");\n buf.trim().eq_ignore_ascii_case(\"y\")\n}\n\n// By grouping the name and amount for each entry, we make it more explicit that the vec of names\n// and vec of amounts are paired together. We could have just used a tuple like (String, u64), but\n// since this is what the program revolves around, its certainly worth making a struct for.\n#[derive(Clone, Debug)]\nstruct Record {\n name: String,\n amount: u64,\n}\n\nfn prompt_income(income_list: &amp;mut Vec&lt;Record&gt;) -&gt; u64 {\n // Using our ask functions simplify this loop greatly.\n while ask_yn(\"Add income?\") {\n income_list.push(Record {\n amount: ask_numeric(\"Enter income amount.\"),\n name: ask_name(\"Enter income name.\"),\n });\n }\n // Here we map from Record to u64, so that we sum the amounts.\n let income = income_list.iter().map(|r| r.amount).sum();\n println!(\"Total user income: {} \", income);\n income\n}\n\n// Note that this function is almost identical to prompt_income, this would be another good target\n// to deduplicate.\nfn prompt_expense(expense_list: &amp;mut Vec&lt;Record&gt;) -&gt; u64 {\n while ask_yn(\"Add expense?\") {\n expense_list.push(Record {\n amount: ask_numeric(\"Enter expense amount.\"),\n name: ask_name(\"Enter expense name.\"),\n });\n }\n let expenses = expense_list.iter().map(|r| r.amount).sum();\n println!(\"Total user expenses: {} \", expenses);\n expenses\n}\n\nfn uservalue(income: u64, expenses: u64) {\n use std::cmp::Ordering;\n\n // Here we always subtract the smaller number from the bigger one, which keeps us from having\n // to worry about casting to signed types and having any problems with overflow, etc. We\n // compare the numbers first, then do different things based on that.\n match income.cmp(&amp;expenses) {\n Ordering::Less =&gt; {\n println!(\n \"You are in the negative, you have a deficit of {}\",\n expenses - income\n );\n }\n Ordering::Equal =&gt; {\n println!(\"You have broken even, you are spending exactly as much as you make.\")\n }\n Ordering::Greater =&gt; {\n println!(\n \"You are in the positive, you have a surplus of {}\",\n income - expenses\n );\n }\n }\n}\n\nfn main() {\n let mut expense_list = Vec::new();\n let mut income_list = Vec::new();\n\n loop {\n let income = prompt_income(&amp;mut income_list);\n let expenses = prompt_expense(&amp;mut expense_list);\n\n uservalue(income, expenses);\n\n if !ask_yn(\"Would you like to run another analysis?\") {\n // This break gets us out of this loop and continues main, eventually just exiting\n // the program normally.\n break;\n }\n\n expense_list.clear();\n income_list.clear();\n }\n\n // In the close_program function you had, you were exiting with status 1 which actually\n // signifies an error. By just letting main end, we exit normally. You could put a println here\n // if you wanted.\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:00:40.443", "Id": "435473", "Score": "0", "body": "Thank you very much for your input! I will take a look into it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T20:30:55.003", "Id": "224502", "ParentId": "224422", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:06:13.877", "Id": "224422", "Score": "4", "Tags": [ "rust", "finance" ], "Title": "Simple income/expenses accounting program" }
224422
<p>Recently, I have appeared for coding exercise to design the Shopping Cart which should have following features:</p> <ol> <li>handles barcoded (like Chips) and non-barcoded item (like Banana 400gm) </li> <li>Can add item, remove item, increment &amp; decrement quantity of item. </li> <li>Supports 2 For 1 offer for BarCoded Item.</li> </ol> <p>I have completed the exercise and tried to follow the SOLID principle as much as I can. However, I can see there is lot of scope of improvement. I really appreciate if some one have a look at the code below and let me know the area of improvements.</p> <ol> <li><p><strong>Booking.java</strong></p> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket; public class Basket { private List&lt;CartItem&gt; cartItemList = new ArrayList&lt;&gt;(); private Float totalPriceBeforeDiscount = 0.0f; private Float totalPriceAfterDiscount = 0.0f; private Float totalDiscount = 0.0f; /* Key Value Pair of product code and Offer. */ Map&lt;String, Offer&gt; offerMap = new HashMap&lt;&gt;(); private DiscountStrategy discountStrategy; /** * @param offerMap * @param discountStrategy */ public Basket(Map&lt;String, Offer&gt; offerMap, DiscountStrategy discountStrategy) { super(); this.offerMap = offerMap; this.discountStrategy = discountStrategy; } public void addCartItem(CartItem cartItem) { int idxPos = cartItemList.indexOf(cartItem); if( idxPos != -1) { cartItem = cartItemList.get(idxPos); cartItem.addOne(); }else { cartItemList.add(cartItem); } refreshTotal(); } public int getTotalLineItem() { return cartItemList.size(); } public Boolean removeCartItem(CartItem cartItem) { Boolean isLineItemRemoved = cartItemList.remove(cartItem); refreshTotal(); return isLineItemRemoved; } /** * if cart item already in the basket then remove the item when there is only one quantity else reduce it by one. * if cart item not **/ public Boolean decreaseByOne(CartItem cartItem) { Boolean isLineItemReduced = false; int idxPos = cartItemList.indexOf(cartItem); if( idxPos != -1) { cartItem = cartItemList.get(idxPos); int qty = cartItem.reduceOne(); if(qty == 0) { cartItemList.remove(cartItem); } isLineItemReduced = true; refreshTotal(); } return isLineItemReduced ; } private void refreshTotal() { totalPriceBeforeDiscount = 0.0f; cartItemList.forEach(item -&gt; totalPriceBeforeDiscount += item.getLineItemTotalBeforeDiscount()); totalDiscount = discountStrategy.calculateDiscount(this.offerMap, this.cartItemList); totalPriceAfterDiscount = totalPriceBeforeDiscount - totalDiscount; } /** * @return the lineItemList */ public List&lt;CartItem&gt; getCartItems() { return Collections.unmodifiableList(cartItemList); } /** * @return the totalPriceBeforeDiscount */ public Float getTotalPriceBeforeDiscount() { return totalPriceBeforeDiscount; } public Float getTotalPriceAfterDiscount() { return totalPriceAfterDiscount; } public Float getTotalDiscount() { return totalDiscount; } } </code></pre></li> <li><p><strong>CartItem.java</strong> </p> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket; public class CartItem { private final Product product; private Integer quantity; private Float weight ; /** * @param product */ public CartItem(Product product, Integer quantity) { super(); this.product = product; this.quantity = quantity; } /** * @param product */ public CartItem(Product product) { this(product, 1); } /** * @param product * @param weight */ public CartItem(Product product, Float weight) { this(product); this.weight = weight; } public Float getLineItemTotalBeforeDiscount() { switch(product.getProductType()) { case LOOSE : return this.weight * product.getPrice().getUnitPrice(); default : return quantity * this.product.getPrice().getUnitPrice() ; } } /** * @return the product */ public final Product getProduct() { return product; } /** * @return the quantity */ public Integer addOne() { return quantity = quantity + 1; } /** * @return the quantity */ public Integer reduceOne() { return quantity = quantity - 1; } /** * @return the quantity */ public Integer getQuantity() { return quantity; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((product == null) ? 0 : product.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CartItem other = (CartItem) obj; if (product == null) { if (other.product != null) return false; } else if (!product.equals(other.product)) return false; return true; } } </code></pre></li> <li><p><strong>Product.java</strong> </p></li> </ol> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket; public class Product { private String productCode; private ProductType productType; private Price price; /** * @param productCode * @param productType * @param price */ public Product(String productCode, ProductType productType, Price price) { super(); this.productCode = productCode; this.productType = productType; this.price = price; } /** * @return the price */ public Price getPrice() { return price; } public String getProductCode() { return productCode; } /** * @return the productType */ public ProductType getProductType() { return productType; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((productCode == null) ? 0 : productCode.hashCode()); result = prime * result + ((productType == null) ? 0 : productType.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Product other = (Product) obj; if (productCode == null) { if (other.productCode != null) return false; } else if (!productCode.equals(other.productCode)) return false; if (productType != other.productType) return false; return true; } } </code></pre> <ol start="4"> <li><strong>ProductType.java</strong></li> </ol> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket; public enum ProductType { BARCODED, LOOSE; } </code></pre> <ol start="5"> <li><strong>Discount.java</strong></li> </ol> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket.offers; import uk.co.supermarket.CartItem; public interface Discount { float applyDiscount(CartItem lineItem); } </code></pre> <ol start="6"> <li><strong>DiscountType.java</strong></li> </ol> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket.offers; public enum DiscountType { TWO_FOR_ONE(new PercenatageDiscount(0.50f)), THREE_FOR_ONE(new PercenatageDiscount(0.33f)); private final Discount discount; public Discount getDiscount() { return discount; } private DiscountType(Discount discount) { this.discount = discount; } } </code></pre> <ol start="7"> <li><strong>Offer.java</strong></li> </ol> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket.offers; import uk.co.supermarket.Product; public class Offer { private final Product product; private final DiscountType discountType; private final int quantity; /** * @param product * @param quantity * @param discountType */ public Offer(Product product, int quantity, DiscountType discountType) { super(); this.product = product; this.quantity = quantity; this.discountType = discountType; } /** * @return the product */ public Product getProduct() { return product; } /** * @return the quantity */ public int getQuantity() { return quantity; } /** * @return the discount */ public DiscountType getDiscountType() { return discountType; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Offer [product=" + product + ", quantity=" + quantity + ", discountType=" + discountType + "]"; } } </code></pre> <ol start="8"> <li><strong>PercenatageDiscount.java</strong></li> </ol> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket.offers; import uk.co.supermarket.CartItem; public class PercenatageDiscount implements Discount{ private float discountPercent ; public float getDiscountPercent() { return discountPercent; } public PercenatageDiscount(float discountPercent) { super(); assert discountPercent &lt;= 1; this.discountPercent = discountPercent; } @Override public String toString() { return "Discount [ discountPercent=" + discountPercent + "]"; } @Override public float applyDiscount(CartItem lineItem) { return lineItem.getLineItemTotalBeforeDiscount() - (lineItem.getLineItemTotalBeforeDiscount() * ( discountPercent)); } } </code></pre> <ol start="9"> <li><strong>DiscountStrategy.java</strong></li> </ol> <pre class="lang-java prettyprint-override"><code>package uk.co.supermarket; import java.util.List; import java.util.Map; import uk.co.supermarket.offers.Offer; public class DiscountStrategy { public Float calculateDiscount(final Map&lt;String, Offer&gt; offerMap, final List&lt;CartItem&gt; set) { float totalDiscount = 0.0f; //apply discount if the offer matches with line item for(CartItem item : set) { Offer offer = offerMap.get(item.getProduct().getProductCode()); if(offer != null &amp;&amp; item.getProduct().getProductCode().equals(offer.getProduct().getProductCode()) &amp;&amp; item.getQuantity() &gt;= offer.getQuantity()) { //This is the logic to handle the case when cart item quantity is more than offer // eg. when cart item are 3 and offer is 2 For 1 int mod = item.getQuantity() % offer.getQuantity(); int quantityOnWhichOfferIsApplied = mod == 0 ? item.getQuantity() : item.getQuantity() - mod; totalDiscount += offer.getDiscountType().getDiscount().applyDiscount(new CartItem(item.getProduct(), quantityOnWhichOfferIsApplied)); } } return totalDiscount; } } </code></pre> <ol start="10"> <li><strong>BasketTest.java</strong></li> </ol> <pre><code>package uk.co.supermarket; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import uk.co.supermarket.offers.DiscountType; import uk.co.supermarket.offers.Offer; public class BasketTest { private Basket basket = null; private DiscountStrategy discountStrategy = null; private Map&lt;String,Offer&gt; map = null; private Price price_5 = new Price(5.0f); private Price price_10 = new Price(10.0f); private Price price_15 = new Price(15.0f); private Price price_20 = new Price(20.0f); private Product bean_can = new Product("BEAN_CAN",ProductType.BARCODED,price_10); private Product coke_bottle = new Product("COKE_BOTTLE", ProductType.BARCODED,price_15); private Product coke_can = new Product("COKE_CAN", ProductType.BARCODED,price_5); private Product orange = new Product("ORANGE", ProductType.LOOSE,price_10); private Product apple = new Product("APPLE", ProductType.LOOSE,price_15); private Product banana = new Product("BANANA", ProductType.LOOSE,price_20); @Before public void setup() { discountStrategy = new DiscountStrategy(); map = new HashMap&lt;&gt;(); basket = new Basket(map,discountStrategy); } @After public void cleanUp() { map.clear(); } @Test public void testAddSingleBarCodedLineItem() { CartItem barCodedItem = new CartItem(bean_can); basket.addCartItem(barCodedItem); assertTrue(1 == basket.getTotalLineItem()); assertTrue(10.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(10.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleQuantityOfSingleBarCodedProduct() { CartItem barCodedItem_1 = new CartItem(bean_can); CartItem barCodedItem_2 = new CartItem(bean_can); CartItem barCodedItem_3 = new CartItem(bean_can); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); assertTrue(1 == basket.getTotalLineItem()); assertTrue(3 == basket.getCartItems().get(0).getQuantity()); assertTrue(30.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(30.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleQuantityofSingleBarCodedProductWithRemovingOneUnit() { CartItem barCodedItem_1 = new CartItem(bean_can); CartItem barCodedItem_2 = new CartItem(bean_can); CartItem barCodedItem_3 = new CartItem(bean_can); CartItem barCodedItem_4 = new CartItem(new Product("BEAN_CAN", ProductType.BARCODED,new Price(10.0f))); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); basket.addCartItem(barCodedItem_4); assertTrue(1 == basket.getTotalLineItem()); assertTrue(4 == basket.getCartItems().get(0).getQuantity()); assertTrue(40.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(40.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); basket.decreaseByOne(barCodedItem_4); assertTrue(1 == basket.getTotalLineItem()); assertTrue(3 == basket.getCartItems().get(0).getQuantity()); assertTrue(30.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(30.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleQuantityofSingleBarCodedProductWithRemovingCartItem() { CartItem barCodedItem_1 = new CartItem(bean_can); CartItem barCodedItem_2 = new CartItem(bean_can); CartItem barCodedItem_3 = new CartItem(bean_can); CartItem barCodedItem_4 = new CartItem(bean_can); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); basket.addCartItem(barCodedItem_4); //checking product with right quantity are added assertTrue(1 == basket.getTotalLineItem()); assertTrue(4 == basket.getCartItems().get(0).getQuantity()); assertTrue(40.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(40.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); // remove the product altogether basket.removeCartItem(barCodedItem_4); assertTrue(0 == basket.getTotalLineItem()); assertTrue(basket.getCartItems().isEmpty()); assertTrue(0.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(0.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleQuantityofMultipleBarCodedProduct() { CartItem barCodedItem_1 = new CartItem(bean_can); CartItem barCodedItem_2 = new CartItem(bean_can); CartItem barCodedItem_3 = new CartItem(bean_can); CartItem barCodedItem_4 = new CartItem(bean_can); CartItem barCodedItem_5 = new CartItem(coke_bottle); CartItem barCodedItem_6 = new CartItem(coke_bottle); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); basket.addCartItem(barCodedItem_4); basket.addCartItem(barCodedItem_5); basket.addCartItem(barCodedItem_6); //checking product with right quantity are added assertTrue(2 == basket.getTotalLineItem()); assertTrue(4 == basket.getCartItems().get(0).getQuantity()); assertTrue(2 == basket.getCartItems().get(1).getQuantity()); assertTrue(70.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(70.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleQuantityofMultipleBarCodedProductWithReducingOneUnitEach() { CartItem barCodedItem_1 = new CartItem(bean_can); CartItem barCodedItem_2 = new CartItem(bean_can); CartItem barCodedItem_3 = new CartItem(bean_can); CartItem barCodedItem_4 = new CartItem(bean_can); CartItem barCodedItem_5 = new CartItem(coke_bottle); CartItem barCodedItem_6 = new CartItem(coke_bottle); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); basket.addCartItem(barCodedItem_4); basket.addCartItem(barCodedItem_5); basket.addCartItem(barCodedItem_6); //checking product with right quantity are added assertTrue(2 == basket.getTotalLineItem()); assertTrue(4 == basket.getCartItems().get(0).getQuantity()); assertTrue(2 == basket.getCartItems().get(1).getQuantity()); assertTrue(70.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(70.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); //reducing the quantity for both products basket.decreaseByOne(barCodedItem_4); basket.decreaseByOne(barCodedItem_5); assertTrue(2 == basket.getTotalLineItem()); assertTrue(3 == basket.getCartItems().get(0).getQuantity()); assertTrue(1 == basket.getCartItems().get(1).getQuantity()); assertTrue(45.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(45.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleQuantityofMultipleBarCodedProductWithRemovingOneCartItem() { CartItem barCodedItem_1 = new CartItem(bean_can); CartItem barCodedItem_2 = new CartItem(bean_can); CartItem barCodedItem_3 = new CartItem(bean_can); CartItem barCodedItem_4 = new CartItem(bean_can); CartItem barCodedItem_5 = new CartItem(coke_bottle); CartItem barCodedItem_6 = new CartItem(coke_bottle); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); basket.addCartItem(barCodedItem_4); basket.addCartItem(barCodedItem_5); basket.addCartItem(barCodedItem_6); //checking product with right quantity are added assertTrue(2 == basket.getTotalLineItem()); assertTrue(4 == basket.getCartItems().get(0).getQuantity()); assertTrue(2 == basket.getCartItems().get(1).getQuantity()); assertTrue(70.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(70.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); //reducing the quantity for both products basket.decreaseByOne(barCodedItem_4); assertTrue(2 == basket.getTotalLineItem()); assertTrue(3 == basket.getCartItems().get(0).getQuantity()); assertTrue(2 == basket.getCartItems().get(1).getQuantity()); assertTrue(60.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(60.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddSingleWeightedProduct() { CartItem weightedItem = new CartItem(orange, 0.20f); basket.addCartItem(weightedItem); assertTrue(1 == basket.getTotalLineItem()); assertTrue(2.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(2.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleWeightedProduct() { CartItem looseItem_1 = new CartItem(orange, 0.20f); CartItem looseItem_2 = new CartItem(apple, 0.40f); basket.addCartItem(looseItem_1); basket.addCartItem(looseItem_2); assertTrue(2 == basket.getTotalLineItem()); assertTrue(1 == basket.getCartItems().get(0).getQuantity()); assertTrue(1 == basket.getCartItems().get(1).getQuantity()); assertTrue(8.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(8.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testAddMultipleBarCodedAndMultipleWeightedLineItems() { CartItem barCodedItem_1 = new CartItem(bean_can); CartItem barCodedItem_2 = new CartItem(coke_bottle); CartItem barCodedItem_3 = new CartItem(coke_can); CartItem weightedItem_1 = new CartItem(orange, 0.4f); CartItem weightedItem_2 = new CartItem(apple, 0.5f); CartItem weightedItem_3 = new CartItem(banana, 2.5f); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); basket.addCartItem(weightedItem_1); basket.addCartItem(weightedItem_2); basket.addCartItem(weightedItem_3); assertTrue(6 == basket.getTotalLineItem()); assertTrue(91.5f == basket.getTotalPriceBeforeDiscount()); assertTrue(91.5f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } @Test public void testApply2For1Offer() { map.put("COKE_CAN", new Offer(coke_can,2,DiscountType.TWO_FOR_ONE)); map.put("BEAN_CAN", new Offer(bean_can,3,DiscountType.THREE_FOR_ONE)); CartItem barCodedItem_1 = new CartItem(coke_can); CartItem barCodedItem_2 = new CartItem(coke_can); CartItem barCodedItem_3 = new CartItem(bean_can); CartItem barCodedItem_4 = new CartItem(bean_can); CartItem barCodedItem_5 = new CartItem(bean_can); CartItem barCodedItem_6 = new CartItem(bean_can); basket.addCartItem(barCodedItem_1); basket.addCartItem(barCodedItem_2); basket.addCartItem(barCodedItem_3); basket.addCartItem(barCodedItem_4); basket.addCartItem(barCodedItem_5); basket.addCartItem(barCodedItem_6); assertTrue(2 == basket.getTotalLineItem()); assertTrue(2 == basket.getCartItems().get(0).getQuantity()); assertTrue(4 == basket.getCartItems().get(1).getQuantity()); assertTrue(50.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(Math.abs(basket.getTotalPriceAfterDiscount() - 24.900002f) &lt; 0.0001f); assertTrue(Math.abs(basket.getTotalDiscount()- 25.099998) &lt; 0.0001f); } @Test public void testRemoveSingleBarCodedProduct() { CartItem barCodedItem_1 = new CartItem(bean_can); basket.addCartItem(barCodedItem_1); assertTrue(1 == basket.getTotalLineItem()); assertTrue(1 == basket.getCartItems().get(0).getQuantity()); assertTrue(10.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(10.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); basket.decreaseByOne(barCodedItem_1); assertTrue(0 == basket.getTotalLineItem()); assertTrue(basket.getCartItems().isEmpty()); assertTrue(0.0f == basket.getTotalPriceBeforeDiscount()); assertTrue(0.0f == basket.getTotalPriceAfterDiscount()); assertTrue(0.0f == basket.getTotalDiscount()); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:16:38.653", "Id": "435437", "Score": "2", "body": "Don't use float for prices since calculation results can become quite inaccurate. Better use BigDecimal. See also https://stackoverflow.com/questions/12496555/java-best-type-to-hold-price" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T13:26:59.183", "Id": "435442", "Score": "0", "body": "Thanks. Indeed I should be using BigDecimal. I will make the correction. Is there anything from the design perspective I am missing here ? Any thoughts ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T06:33:36.483", "Id": "437475", "Score": "1", "body": "The Basket class doesn't extend anything so there is no need for the super() call in the constructor." } ]
[ { "body": "<p>The best way to see how the system is architected is to look at the tests. It is great that you have provided such tests with the <code>BasketTest</code> class! So I will review your code by reviewing the <code>BasketTest</code>class.</p>\n\n<ul>\n<li>Initializing class fields to null is unnecessary and duplicate as they are automatically initialized to null (default value)</li>\n<li><code>setup()</code> would be a better place to setup your products.</li>\n<li>Don't use field and variable names like <code>map</code>, <code>list</code>. They need to speak to whomever is reading the code. I have no idea what your <code>map</code> represents.</li>\n<li>Make name of the products like <code>\"COKE_CAN\"</code> constants and replace all occurrences in the code with the new constants. </li>\n<li>Without looking into the implementation, I cannot tell what the 2nd parameter means: <code>new Offer(coke_can, 2, DiscountType.TWO_FOR_ONE)</code>. I would like this code to be improved to be readable with less effort.</li>\n<li>Use <a href=\"https://junit.org/junit4/javadoc/4.12/org/junit/Assert.html#assertArrayEquals(float[],%20float[],%20float)\" rel=\"nofollow noreferrer\">assertArrayEquals(float[] expecteds, float[] actuals, float delta)</a> for comparing floats. </li>\n<li>Improve <code>testApply2For1Offer()</code> test. There you put elements to the <code>map</code> but it is not clear how the <code>map</code> interacts with the rest of the code.</li>\n<li>Every basked needs to have <code>DiscountStrategy</code> and offers in form of <code>Map&lt;String, Offer&gt;</code>. This does not seem right. I would think that there is only one <code>Discounts</code> object that can calculate a discount or final price for a given <code>Basket</code>. This is the biggest issues I see here, the design of the <code>Basket</code>.</li>\n</ul>\n\n<p>Overall you did great with your design! I like it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-13T23:42:30.893", "Id": "439167", "Score": "0", "body": "Thanks for your review. Excluding the last point, I have updated the code base for the review comment The last one require some thought before I do any change. I agree basket does not need to know about Offer. I think Offer should sit inside the product." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-12T20:37:48.480", "Id": "226002", "ParentId": "224425", "Score": "1" } } ]
{ "AcceptedAnswerId": "226002", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:19:38.847", "Id": "224425", "Score": "4", "Tags": [ "java", "object-oriented", "e-commerce" ], "Title": "JAVA Shopping Cart Design" }
224425
<p>I made this little function for flyweighting any type that has <code>operator&lt;</code>. I followed the convention of <code>make_unique</code> and <code>make_shared</code> with <code>make_one</code>. Not sure if that's the best name.</p> <pre><code>// Create a single instance of an object, using // operator&lt; to determine equality. // Note that we take a value instead of a constructor // arguments because often we'll want to mutate a field, // then create a new object, without passing in everything. template&lt;class T&gt; std::shared_ptr&lt;const T&gt; make_one(const T&amp; value) { struct cmp { bool operator()(const T* a, const T* b) const { return *a &lt; *b; } }; static std::set&lt;const T*, cmp &gt; values; auto iter = values.find(&amp;value); if(iter != values.end()) { return (*iter)-&gt;shared_from_this(); } auto ptr = std::shared_ptr&lt;T&gt;(new T(value), [](T* p) { values.erase(p); delete p; }); values.insert(ptr.get()); return ptr; } </code></pre> <p>Test code:</p> <pre><code> struct Foo : std::enable_shared_from_this&lt;Foo&gt; { int x = 0; Foo(int x) : x(x) { } bool operator&lt;(Foo rhs) const { return x &lt; rhs.x; } }; auto p0 = make_one(Foo{0}); auto p1 = make_one(Foo{0}); assert(p0 == p1); auto p2 = make_one(Foo{42}); assert(p2 != p0); </code></pre> <p>Review goals:</p> <ol> <li>Can I avoid requiring <code>enable_shared_from_this</code>?</li> <li>Can I make it thread safe without too much trouble?</li> <li>Any other ideas for improvement.</li> </ol>
[]
[ { "body": "<p>The first thing I would note is that you should point out non obvious features of your implementation. The nice thing that is not immediately obvious is that when all external references are gone the object is automatically deleted from the <code>make_one()::values</code> set.</p>\n\n<p>This is not really a requirement of a flyweight.<br>\nBut a nice little trick here.</p>\n\n<p>So if the automatic deletion is required then the answers to the question are:</p>\n\n<blockquote>\n <p>Can I avoid requiring enable_shared_from_this?</p>\n</blockquote>\n\n<p>No. I don't think so. </p>\n\n<p>You could re-invent some reference counting model but that seems a lot of work in comparison to simply using the standard libraries.</p>\n\n<p>As an alternative, You can get around it slightly by using <code>std::set&lt;std::weak_ptr&lt;T&gt;&gt;</code> the trouble here is that even though the resource would be cleaned up the actual space for the resource would be maintained after the object is destroyed.</p>\n\n<p>If on the other hand automatic deletion is not required.</p>\n\n<blockquote>\n <p>Can I avoid requiring enable_shared_from_this?</p>\n</blockquote>\n\n<p>Yes. there are simpler ways that this could be written if there is no requirement to delete upon all external references going away. Now if you want it again it will still be there.</p>\n\n<pre><code>template&lt;class T&gt;\nT const&amp; make_one(const T&amp; value) {\n\n static std::set&lt;T&gt; values;\n\n auto result = values.insert(value);\n return *(result.first);\n}\n</code></pre>\n\n<blockquote>\n <p>Can I make it thread safe without too much trouble?</p>\n</blockquote>\n\n<p>Yes simply add a lock on the <code>make_one()</code></p>\n\n<blockquote>\n <p>Any other ideas for improvement.</p>\n</blockquote>\n\n<p>You could add the ability to move an object into your <code>make_once()</code> rather than copy it each time. Even better would be to allow the construction of T from its parameters.</p>\n\n<pre><code>// Move an object in your set\ntemplate&lt;typename T&gt;\nstd::shared_ptr&lt;const T&gt; make_one(T&amp;&amp; value)\n\n// Emplace a value in your set\ntemplate&lt;typename T, typename... Args&gt;\nstd::shared_ptr&lt;const T&gt; make_one(Args&amp;&amp;... value)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T00:12:42.160", "Id": "435402", "Score": "0", "body": "Would need a lock in the deleter too, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T00:15:22.030", "Id": "435403", "Score": "0", "body": "Would the `T&&` or `Args&&` reduce copies even though I have to create a value to call `set<...>::find`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T16:36:12.260", "Id": "435457", "Score": "1", "body": "@Taylor Absolutely. That is the whole point of the introduction of move semantics. Move will never be more expensive than a copy and even objects that don't support move will have a cost equal to a copy. So you it could be the same cost but usually its better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T16:37:34.370", "Id": "435459", "Score": "1", "body": "@Taylor Support of the emplace build `Args...` is great for objects that are expensive to create (don't move) and/or expensive to copy. As it allows you to pass the arguments (which are usually small and scaler) rather than the whole object." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T23:58:41.580", "Id": "224446", "ParentId": "224433", "Score": "1" } } ]
{ "AcceptedAnswerId": "224446", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:05:13.547", "Id": "224433", "Score": "2", "Tags": [ "c++", "c++11" ], "Title": "generic flyweighting function" }
224433
<p>I'd be grateful for a review of my AJAX request. If I have taken the correct approach here and especially any security concerns!</p> <p>I am creating a Purchase Order system for my manager (as part of an apprenticeship I am doing). </p> <p>There is a select html element where a supplier can be selected. I also have a button to trigger a bootstrap modal with a form to enter a new supplier. I have an AJAX request to add the new supplier to the database then a chain AJAX request to query the database so the select element can be updated.</p> <pre><code> &lt;script&gt; window.addEventListener('DOMContentLoaded', function () { // User can add a new supplier using a modal form. // 1) Send an AJAX POST request to update the database // 2) Send AJAX GET request to query the database // 3) Repopulate the select element with the updated records. document.getElementById("newSupplierModalForm").addEventListener('submit', function (e) { // Send AJAX request to add new supplier. // TODO: Validate name field has text and handle error. e.preventDefault(); const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); const xhr = new XMLHttpRequest(); xhr.open('POST', '/supplier', true); // Set headers xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('X-CSRF-Token', token); //Set paramaters const params = new URLSearchParams(); params.set("name", document.getElementById('supName').value); params.set("address_1", document.getElementById('supAddress_1').value); params.set("address_2", document.getElementById('supAddress_2').value); params.set("town", document.getElementById('supTown').value); params.set("post_code", document.getElementById('supPost_code').value); params.set("contact_name", document.getElementById('supContact_name').value); params.set("contact_tel", document.getElementById('supContact_tel').value); params.set("contact_email", document.getElementById('supContact_email').value); // Logic xhr.onload = function (e) { if (xhr.status === 200) { // Close modal document.getElementById('addSuppModalClose').click(); // AJAX request for updated supplier records to repopulate select element. const xhr_getSuppliers = new XMLHttpRequest(); xhr_getSuppliers.open('GET', '/getSuppliers', true); // Set headers xhr_getSuppliers.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr_getSuppliers.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr_getSuppliers.setRequestHeader('X-CSRF-Token', token); // Logic xhr_getSuppliers.onload = function (e) { if (xhr.status === 200) { const data = JSON.parse(xhr_getSuppliers.response); const selectElem = document.getElementById('supplier'); selectElem.options.length = 0; //reset options // populate options for (index in data) { console.log(data[index], index); selectElem.options[selectElem.options.length] = new Option(data[index], index); } } }; // Send GET Request xhr_getSuppliers.send(); } else { // Show alert if AJAX POST Request does not receive a 200 response. // I need to write code to feed this back to the user later. alert(xhr.response); }; }; // Send POST Request xhr.send(params.toString()); }); }); &lt;/script&gt; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T09:02:15.680", "Id": "465429", "Score": "0", "body": "Just Curious, Seeing as Javascript is ClientSide, couldn't they just console.log(token) & then they would have you csrf token value, which kinda defeats the object of setting one up?" } ]
[ { "body": "<h3>For let variable in</h3>\n\n<p>EcmaScript6 lets you create a closure in a for loop using <code>let</code>. It is preferred over <code>var</code>, which is preferred over nothing (unless you specifically want to reuse an existing variable declared before the loop).</p>\n\n<blockquote>\n<pre><code>for (index in data) {\n console.log(data[index], index);\n selectElem.options[selectElem.options.length] = new Option(data[index], index);\n}\n</code></pre>\n</blockquote>\n\n<pre><code>for (let index in data) {\n console.log(data[index], index);\n selectElem.options[selectElem.options.length] = new Option(data[index], index);\n}\n</code></pre>\n\n<h3>Semi-colon</h3>\n\n<p><code>If-Else</code> branch does not require a semi-colon to terminate it.</p>\n\n<blockquote>\n<pre><code> } else {\n // Show alert if AJAX POST Request does not receive a 200 response.\n // I need to write code to feed this back to the user later.\n alert(xhr.response);\n };\n</code></pre>\n</blockquote>\n\n<pre><code> } else {\n // Show alert if AJAX POST Request does not receive a 200 response.\n // I need to write code to feed this back to the user later.\n alert(xhr.response);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T04:57:33.283", "Id": "225395", "ParentId": "224434", "Score": "2" } }, { "body": "<h2>Feedback</h2>\n<p>The code uses <code>const</code> for variables that don't need to be re-assigned. This is good because it prevents accidental re-assignment. It also uses <code>===</code> when comparing the status codes, avoiding type coercion. That is a good habit.</p>\n<p>There are at least four indentation levels because the <code>onload</code> callbacks are anonymous functions. Some readers of the code would refer to this as &quot;<em>callback hell</em>&quot;, because really there is just one large function here with functions defined inside of it, making it challenging to read. See the first section of the <strong>Suggestions</strong> below for tips on avoiding this.</p>\n<p>The <code>const</code> keyword was added to the Ecmascript Latest Draft in Draft status and standard in the Ecmascript 2015 specification<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Specifications\" rel=\"nofollow noreferrer\">1</a></sup> so other ecmascript-2015 (AKA ES-6) features could be used to simplify the code.</p>\n<h2>Suggestions</h2>\n<h3>Callbacks and Nesting/Indentation levels</h3>\n<p>While most of the examples on <a href=\"http://callbackhell.com\" rel=\"nofollow noreferrer\">callbackhell.com</a> focus on promise callbacks and asynchronous code, the concepts apply here as well. Name the functions and then move the definitions out to different lines. If you need to access variables from outside then you may need to pass them as arguments.</p>\n<h3>Data Object and repeated DOM lookups</h3>\n<p>I will be honest - I haven't encountered the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\"><code>URLSearchParams</code></a> before. I typically see code that uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FormData\" rel=\"nofollow noreferrer\"><code>FormData</code></a>. Are all of the input elements inside of a <code>&lt;form&gt;</code> tag? if they are then a reference to that element could be passed to the FormData constructor. Otherwise, do the <code>name</code> attributes match the keys added to <code>params</code> - i.e. the <em>id</em> attributes without the <em>sup</em> prefix? You could iterate over the input elements and add the parameters to <code>params</code>.</p>\n<h3>Avoid global variables</h3>\n<p>In the review by dfhwze, The following line is referenced:</p>\n<blockquote>\n<pre><code>for (index in data) {\n</code></pre>\n</blockquote>\n<p>Without any keyword before <code>index</code>, like <code>var</code>, <code>let</code> or <code>const</code> that variable becomes a global (on <code>window</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-09T19:02:36.143", "Id": "438655", "Score": "2", "body": "Pointing out good aspects of the OP's code is something I should do more often in my reviews. Well done." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-09T18:55:59.167", "Id": "225845", "ParentId": "224434", "Score": "2" } } ]
{ "AcceptedAnswerId": "225845", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:12:48.057", "Id": "224434", "Score": "8", "Tags": [ "javascript", "event-handling", "ajax" ], "Title": "Vanilla Javascript: Chained AJAX request" }
224434
<p>I am making a program that transfers files from one client to another. Right now I am just working on sending the file to the server and then later I will work on transferring it to the other client. Here is my client class*:</p> <pre class="lang-java prettyprint-override"><code>public class Client implements Runnable { private Socket socket; private InputStream input; private OutputStream output; private PrintWriter printer; private BufferedReader reader; private boolean running = true; private long ping = System.nanoTime() / 1000000; public Client(String address) { String host = address.substring(0, address.indexOf(":")); int port = Integer.parseInt(address.substring(address.indexOf(":") + 1)); System.out.println("Attempting to connect to " + host + ":" + port); try { socket = new Socket(host, port); printer = new PrintWriter(socket.getOutputStream(), true); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = socket.getOutputStream(); System.out.println("Successfully connected!"); running = true; } catch (IOException e) { e.printStackTrace(); running = false; System.out.println("Failed to connect."); Thread.currentThread().interrupt(); ; } } @Override public void run() { if (!running) return; String str; printer.println("ping"); try { while (running &amp;&amp; (str = reader.readLine()) != null) { handle(str); } } catch (IOException e) { e.printStackTrace(); } this.close(); } public void handle(String str) { if (str.equals("ping")) { send("pong"); } else if (str.equals("pong")) { ping = ((System.nanoTime() / 1000000) - ping) / 2; System.out.println("Ping: " + ping + "ms"); File file = new File("./res/" + "send.zip"); send("pong"); for (int lcv = 0; lcv &lt; 1; lcv++) { sendFile(file); wait(1000); } } if (str.equals(SocketKey.CLOSE_CONNECTION)) { running = false; printer.println(SocketKey.CLOSE_CONNECTION); } } public void sendFile(File file) { long startTime = (System.nanoTime() / 1000000); long fileSize = file.length(); send("new_file:[" + file.getName() + "][" + fileSize + "]"); System.out.println("Name: " + file.getName() + " Size: " + Util.readableFileSize(fileSize)); System.out.print("Transferring file"); byte[] bytes = new byte[16 * 1024]; try { input = new FileInputStream(file); int count, totalCount = 0; double perc = 0; while ((count = input.read(bytes)) &gt; 0) { totalCount += count; if (perc &lt; ((double) totalCount) / fileSize) { System.out.print("."); perc += .1; } do { output.write(bytes, 0, count); } while (waitFor(".", 1000) == null); } } catch (IOException e) { e.printStackTrace(); } String str; try { while (running &amp;&amp; (str = reader.readLine()) != null) { if (str.equals("Complete.") || str.equals("Failed.")) { System.out.println( "\nFile successfully sent! (" + ((System.nanoTime() / 1000000) - startTime) + "ms)"); break; } else handle(str); } } catch (IOException e) { e.printStackTrace(); } } public String[] waitFor(String string, long ms) { String str; List&lt;String&gt; strings = new ArrayList&lt;String&gt;(); long startTime = (System.nanoTime() / 1000000); try { while ((str = reader.readLine()) != null) { if (str.equals(string) || !running) break; else if ((System.nanoTime() / 1000000) - startTime &lt; ms) return null; else strings.add(str); } } catch (IOException e) { e.printStackTrace(); } String[] ret = new String[strings.size()]; for (int lcv = 0; lcv &lt; strings.size(); lcv++) ret[lcv] = strings.get(lcv); return ret; } public void close() { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } public void send(Object... objects) { String output = ""; for (Object obj : objects) { output += obj.toString(); } printer.println(output); } public void wait(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws UnknownHostException, IOException { // startUI(); Client client = new Client("localhost:1123"); new Thread(client).start(); // File file = new File("./res/" + ""); // client.sendFile(file); } } </code></pre> <p>here is my server class*:</p> <pre class="lang-java prettyprint-override"><code>public class Server { public static boolean running = true; public static List&lt;Thread&gt; threads = new ArrayList&lt;Thread&gt;(); public static List&lt;Connection&gt; clients = new ArrayList&lt;Connection&gt;(); public static void main(String[] args) throws InterruptedException, IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(1123); } catch (IOException ex) { System.out.println("Can't setup server on this port number. "); } // Make a thread that detects if the thread count has changed and redistribute that info while (running) { try { Socket socket = serverSocket.accept(); System.out.println("New connection from " + socket.getInetAddress()); Thread newThread = new Thread(new Connection(socket)); threads.add(newThread); newThread.start(); Thread.sleep(10000); break; } catch (IOException ex) { System.out.println("Can't accept client connection. "); } } serverSocket.close(); } } </code></pre> <p>and finally here is my class that handles each connection*:</p> <pre class="lang-java prettyprint-override"><code>public class Connection implements Runnable { private Socket socket; private InputStream input; private PrintWriter printer; private BufferedReader reader; private boolean running = true; private long ping = System.nanoTime() / 1000000; public Connection(Socket socket) { this.socket = socket; try { input = socket.getInputStream(); printer = new PrintWriter(socket.getOutputStream(), true); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (IOException ex) { System.out.println("Can't get socket input/output stream."); } } @Override public void run() { String str; connect(); try { while (Server.running &amp;&amp; running &amp;&amp; (str = reader.readLine()) != null) { handle(str); } } catch (IOException e) { e.printStackTrace(); } close(); } private void connect() { } private void handle(String str) { if (str.equals("ping")) { send("pong"); } else if (str.equals("pong")) { ping = (System.nanoTime() / 1000000) - ping; System.out.println("Ping: " + ping + "ms"); send(SocketKey.CLOSE_CONNECTION); } if (str.equals(SocketKey.CLOSE_CONNECTION)) { running = false; System.out.println("Server Closing."); printer.println(SocketKey.CLOSE_CONNECTION); } if (str.startsWith("new_file:")) { receiveFile(str); } } public boolean receiveFile(String str) { System.out.print("Receiving file"); long startTime = (System.nanoTime() / 1000000); String fileName = str.substring(str.indexOf("[") + 1, str.indexOf("]")); fileName = checkFileName( fileName.substring(0, fileName.lastIndexOf(".")) + fileName.substring(fileName.lastIndexOf("."))); long fileSize = Long.parseLong(str.substring(str.lastIndexOf("[") + 1, str.lastIndexOf("]"))); OutputStream output = null; try { output = new FileOutputStream("./res/" + fileName); } catch (FileNotFoundException ex) { System.out.println("File not found. "); } byte[] bytes = new byte[16 * 1024]; int count; long totalCount = 0, totalToDo = fileSize; double perc = 0; try { while ((count = input.read(bytes, 0, (int) Math.min(bytes.length, fileSize))) != -1 &amp;&amp; 0 &lt; fileSize) { fileSize -= count; output.write(bytes, 0, count); totalCount += count; if (perc &lt; ((double) totalCount) / totalToDo) { System.out.print("."); perc += .1; } send("."); } output.close(); long tdiff = ((System.nanoTime() / 1000000) - startTime); System.out.println("\nFile successfully saved. (" + tdiff + "ms)"); System.out.println("Average transfer speed: " + Util.readableFileSize(totalToDo / (tdiff / 1000)) + "/s"); Util.printFileInfo(new File("./res/" + fileName)); } catch (IOException e) { send("Complete."); return false; } send("Complete."); return true; } public void close() { try { reader.close(); printer.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } public String checkFileName(String fileName) { if (new File("./res/" + fileName).exists()) { if (fileName.contains("_")) { String hex = fileName.substring(fileName.lastIndexOf("_") + 1, fileName.lastIndexOf(".")); return checkFileName(fileName.replace("_" + hex + ".", "_" + Integer.toHexString(Integer.parseInt(hex, 16) + 1) + ".")); } return checkFileName(fileName.substring(0, fileName.lastIndexOf(".")) + "_1" + fileName.substring(fileName.lastIndexOf("."))); } else { return fileName; } } public void send(Object... objects) { String output = ""; for (Object obj : objects) { output += obj.toString(); } printer.println(output); } } </code></pre> <p>Here is my Util class in case it is needed:</p> <pre class="lang-java prettyprint-override"><code>public class Util { public static final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); public static final int width = (int) screenSize.getWidth(), height = (int) screenSize.getHeight(); public static String lower_alphabet = "abcdefghijklmnopqrstuvwxyz", upper_alphabet = "ABCDEFGHJKLMNOPQRSTUVWXYZ", digits = "0123456789", hex = "0123456789abcdef"; public static JFrame getDefaultFrame() { JFrame frame = new JFrame(); frame.setTitle("DataDrop"); frame.setResizable(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); return frame; } public static boolean isDigit(String s) { return digits.contains(s); } public static boolean areDigits(String s) { for (char c : s.toCharArray()) if (!isDigit(c + "")) return false; return true; } public static boolean isHex(String s) { return hex.contains(s); } public static boolean areHex(String s) { for (char c : s.toCharArray()) if (!isHex(c + "")) return false; return true; } public static boolean isLetter(String s) { return lower_alphabet.contains(s) || upper_alphabet.contains(s); } public static boolean areLetters(String s) { for (char c : s.toCharArray()) if (!isLetter(c + "")) return false; return true; } public static String readableFileSize(long size) { if (size &lt;= 0) return "0"; final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" }; int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; } public static void printFileInfo(File file) { String fileName = file.getName(); System.out.println("File info:"); System.out.println(" File Name : " + fileName.substring(0, fileName.lastIndexOf("."))); System.out.println(" File Size : " + readableFileSize(file.length())); System.out.println(" File Extension: " + fileName.substring(fileName.lastIndexOf("."))); System.out.println(" Full Path : " + file.getAbsolutePath()); } } </code></pre> <p>*I removed the getters and setters because they are just the auto-generated ones from eclipse and they have no other function.</p> <p>I am unsure of the efficiency of my transfer methods and I am pretty sure it's bad practice to send both bytes and strings through the socket, but I do not know another way.</p> <p>I also don't know how to send more than one file without making the thread sleep for a second. If I don't let the Thread sleep, the program eventually gets hung up because a packet gets lost somehow. I know it shouldn't be possible, but I managed to find a way.</p>
[]
[ { "body": "<p>You need to use some kind wire protocol. In simplest case a triple (int length, int/enum \n for tag/type, byte[] data). Then you will be able to differentiate between command \"ping\" and a sending a file with content \"ping\". Also look into ProtoBuf or ObjectInputStream - it is futile to try parsing objects from <code>toString()</code> output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T19:37:46.087", "Id": "436421", "Score": "0", "body": "Thank you for trying to help me, could you go into a little more detail about what a triple is? I didn't learn what an enum was in my APCS class, and I have never used one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T14:30:25.290", "Id": "224814", "ParentId": "224436", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T19:45:39.800", "Id": "224436", "Score": "2", "Tags": [ "java", "socket", "network-file-transfer" ], "Title": "Java file transfer through sockets" }
224436
<p>For learning Rust I decided to make a <a href="https://en.wikipedia.org/wiki/Wavefront_.obj_file" rel="nofollow noreferrer">3D .obj</a> viewer. I wrote a simplified OBJ parser without materials that only supports triangles.</p> <p>Considering I'm completely new to Rust and don't really know anyone who's good at idiomatic Rust I figured I'd ask here :)</p> <pre class="lang-rust prettyprint-override"><code>use std::fs; use crate::geometry::*; use crate::object::Object; fn str_to_vec3(s: &amp;str) -&gt; Option&lt;Vec3&gt; { let bits: Vec&lt;&amp;str&gt; = s.split(" ").collect(); if bits.len() != 3 { return None; } Some(Vec3 { x: bits[0].parse().unwrap(), y: bits[1].parse().unwrap(), z: bits[2].parse().unwrap(), }) } fn str_to_vec2(s: &amp;str) -&gt; Option&lt;Vec2&gt; { let bits: Vec&lt;&amp;str&gt; = s.split(" ").collect(); if bits.len() != 2 { return None; } Some(Vec2 { x: bits[0].parse().unwrap(), y: bits[1].parse().unwrap(), }) } type VertexDescription = (usize, usize, usize); type TriangleDescription = (VertexDescription, VertexDescription, VertexDescription); fn str_to_vertex_description(s: &amp;str) -&gt; Option&lt;VertexDescription&gt; { let bits: Vec&lt;&amp;str&gt; = s.split("/").collect(); if bits.len() != 3 { return None; } Some(( bits[0].parse::&lt;usize&gt;().unwrap() - 1, bits[1].parse::&lt;usize&gt;().unwrap() - 1, bits[2].parse::&lt;usize&gt;().unwrap() - 1, )) } fn str_to_triangle_description(s: &amp;str) -&gt; Option&lt;TriangleDescription&gt; { let bits: Vec&lt;&amp;str&gt; = s.split(" ").collect(); if bits.len() != 3 { return None; } Some(( str_to_vertex_description(bits[0]).expect("Failed to parse vertex"), str_to_vertex_description(bits[1]).expect("Failed to parse vertex"), str_to_vertex_description(bits[2]).expect("Failed to parse vertex"), )) } pub fn parse(path: String) -&gt; Object { let object_string = fs::read_to_string(path).expect("Cannot read .obj file!"); let lines = object_string.lines(); let mut positions: Vec&lt;Vec3&gt; = vec![]; let mut normals: Vec&lt;Vec3&gt; = vec![]; let mut uvs: Vec&lt;Vec2&gt; = vec![]; let mut triangle_descriptions: Vec&lt;TriangleDescription&gt; = vec![]; for line in lines { match &amp;line[0..2] { "v " =&gt; match str_to_vec3(&amp;line[2..]) { Some(vec3) =&gt; positions.push(vec3), None =&gt; panic!("Malformed 'v' value!"), }, "vn" =&gt; match str_to_vec3(&amp;line[3..]) { Some(vec3) =&gt; normals.push(vec3), None =&gt; panic!("Malformed 'vn' value!"), }, "vt" =&gt; match str_to_vec2(&amp;line[3..]) { Some(vec2) =&gt; uvs.push(vec2), None =&gt; panic!("Malformed 'vt' value!"), }, "f " =&gt; match str_to_triangle_description(&amp;line[2..]) { Some(td) =&gt; triangle_descriptions.push(td), None =&gt; panic!("Malformed 'f' value!"), }, _ =&gt; {} } } let triangles: Vec&lt;Triangle3&gt; = triangle_descriptions .iter() .map(|&amp;td| { let v1: Vertex3 = Vertex3 { pos: positions[(td.0).0], uv: uvs[(td.0).1], normal: normals[(td.0).2], }; let v2: Vertex3 = Vertex3 { pos: positions[(td.1).0], uv: uvs[(td.1).1], normal: normals[(td.1).2], }; let v3: Vertex3 = Vertex3 { pos: positions[(td.2).0], uv: uvs[(td.2).1], normal: normals[(td.2).2], }; (v1, v2, v3) }) .collect(); let mut obj = Object::new(); obj.triangles = triangles; obj } </code></pre> <p>Is this a good approach? What can I improve on?</p> <p>Any feedback is welcome!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T20:55:51.470", "Id": "435472", "Score": "0", "body": "First glance: consider implementing [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) for your `Vec3`, `Vec2`, etc. Then you can use `str`'s parse method. Also, try to use `Result` or `Option` more, rather than `panic`/`unwrap`/`expect`." } ]
[ { "body": "<pre><code>fn str_to_vec3(s: &amp;str) -&gt; Option&lt;Vec3&gt; {\n let bits: Vec&lt;&amp;str&gt; = s.split(\" \").collect();\n if bits.len() != 3 {\n return None;\n }\n\n Some(Vec3 {\n x: bits[0].parse().unwrap(),\n y: bits[1].parse().unwrap(),\n z: bits[2].parse().unwrap(),\n })\n\n}\n</code></pre>\n\n<p>For some errors, you panic (if parsing fails) and for other errors you return None. You really should pick one strategy and stick with it. If you want to avoid panicing it is more idiomatic to return Result than Option when it is an error.</p>\n\n<p>Much of your code repeats the same basic action: split/parse/return. You can combine some of the code with a function like this:</p>\n\n<pre><code>fn split_parse&lt;T: std::str::FromStr&gt;(text: &amp;str, split: &amp;str) -&gt; Result&lt;Vec&lt;T&gt;, T::Err&gt; {\n text.split(split).map(str::parse).collect()\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T20:43:45.793", "Id": "437056", "Score": "0", "body": "I've implemented some of the suggested changes, it now gives more consistent and cleaner errors. I've rewritten most of it to plug more easily into openGL now but I've taken the consistency errors into consideration.\nI also considered using the ::from more, but I didn't want to have one generic from str function since this is specific to this parser." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-23T16:55:26.917", "Id": "224746", "ParentId": "224441", "Score": "1" } } ]
{ "AcceptedAnswerId": "224746", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T21:53:53.627", "Id": "224441", "Score": "4", "Tags": [ "beginner", "parsing", "rust", "coordinate-system" ], "Title": "Wavefront 3D Obj parser/viewer" }
224441
<p>I am trying to write an integer field in Python with the following attributes:</p> <ul> <li>Minimum</li> <li>Exclusive minimum</li> <li>Maximum</li> <li>Exclusive maximum</li> <li>Multiple of</li> <li>Value</li> </ul> <p>Basically, given the constraints and the value, the class will have a validate method which will return the errors if they occur. If the minimum is not null, then the exclusive minimum is explicitly set to null to avoid redundancy. The same is done for maximum and exclusive maximum. All the constraints can be null. The constraints work as follows:</p> <ul> <li>The value must be greater than or equal to the minimum.</li> <li>The value must be greater than the exclusive minimum.</li> <li>The value must be less than or equal to the maximum.</li> <li>The value must be less than the exclusive maximum.</li> <li>The multiple of must be a factor of the value.</li> </ul> <p><strong>Note: All the constraints are assumed to be integers, so no type checks are done. This is because these values are coming from a database, so type will always be integer or null.</strong></p> <p>So far, I have written the following class:</p> <pre><code>def is_not_factor(dividend, divisor): """Checks if the given divisor is not a factor of the given dividend. Notes: - Since both the `dividend` and `divisor` are coming from the database, it is assumed that both these parameters are numbers, and the `divisor` is non-zero. Therefore, no type checks are done. """ return dividend % divisor != 0 class IntegerField: def add_error(self, key, error): self.errors.setdefault(key, []) self.errors[key].append(error) def __init__(self, minimum=None, exclusive_minimum=None, maximum=None, exclusive_maximum=None, multiple_of=None): self.minimum = minimum self.exclusive_minimum = exclusive_minimum self.maximum = maximum self.exclusive_maximum = exclusive_maximum self.multiple_of = multiple_of if self.minimum: self.exclusive_minimum = None if self.maximum: self.exclusive_maximum = None self.value = None self.errors = {} if (self.minimum and self.maximum): if self.minimum &gt; self.maximum: self.add_error( 'minimum', f'The minimum must be less than or equal to the maximum ' f'of {self.maximum}.' ) self.add_error( 'maximum', f'The maximum must be greater than or equal to the ' f'minimum of {self.minimum}.' ) elif (self.minimum and self.exclusive_maximum): if self.minimum &gt;= self.exclusive_maximum: self.add_error( 'minimum', f'The minimum must be less than the exclusive maximum of ' f'{self.exclusive_maximum}.' ) self.add_error( 'exclusive_maximum', f'The exclusive maximum must be greater than the ' f'minimum of {self.minimum}.' ) elif (self.exclusive_minimum and self.maximum): if self.exclusive_minimum &gt;= self.maximum: self.add_error( 'exclusive_minimum', f'The exclusive minimum must be less than the maximum of ' f'{self.maximum}.' ) self.add_error( 'maximum', f'The maximum must be greater than the exclusive minimum ' f'of {self.exclusive_minimum}.' ) elif (self.exclusive_minimum and self.exclusive_maximum): if self.exclusive_minimum &gt;= (self.exclusive_maximum - 1): self.add_error( 'exclusive_minimum', f'The exclusive minimum must be less than one minus the ' f'exclusive maximum of {self.exclusive_maximum}. For ' f'example, if the exclusive maximum is set to 101, then ' f'the exclusive minimum must be less than 100, ie, 99 or ' f'less.' ) self.add_error( 'exclusive_maximum', f'The exclusive maximum must be greater than one plus the ' f'exclusive minimum of {self.exclusive_minimum}. For ' f'example, if the exclusive minimum is set to 99, then ' f'the exclusive maximum must be greater than 100, ie, 101 ' f'or more.' ) if self.multiple_of: if self.multiple_of == 0: self.add_error( 'multiple_of', 'The multiple of must be non-zero' ) if bool(self.errors): print(f'The following errors were encountered: {self.errors}') # Raise the errors def set_value(self, value): self.value = value def validate(self): if self.value: print('Please set a value.') else: validation_errors = [] if self.multiple_of: if is_not_factor(self.value, self.multiple_of): validation_errors.append( f'The value must be a multiple of {self.multiple_of}.' ) if self.minimum: if self.value &lt; self.minimum: validation_errors.append( f'The value must be greater than or equal to the minimum ' f'of {self.minimum}.' ) return elif self.exclusive_minimum: if self.value &lt;= self.exclusive_minimum: validation_errors.append( f'The value must be greater than the exclusive minimum of ' f'{self.exclusive_minimum}.' ) return if self.maximum: if self.value &gt; self.maximum: validation_errors.append( f'The value must be less than or equal to the maximum of ' f'{self.maximum}.' ) elif self.exclusive_maximum: if self.value &gt;= self.exclusive_maximum: validation_errors.append( f'The value must be less than the exclusive maximum of ' f'{self.exclusive_maximum}.' ) </code></pre> <p>Am I missing something in my class? Specifically, I would like to know if the two methods (init and validate) will work in every possible scenario or not. Moreover, is my current code checking for every single combination of constraints, or am I missing something?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T00:03:31.277", "Id": "435401", "Score": "0", "body": "`is_not_factor` is missing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T11:05:23.627", "Id": "435433", "Score": "0", "body": "Please assume that its coming from another module." } ]
[ { "body": "<h3><code>__init__()</code></h3>\n\n<p>There appears to be a typo in:</p>\n\n<pre><code>if self.multiple_of:\n if self.multiple_of == 0: &lt;&lt;&lt;\n</code></pre>\n\n<h3><code>validate()</code></h3>\n\n<p>Should the first check be:</p>\n\n<pre><code>if self.value == None:\n print('Please set a value.')\n</code></pre>\n\n<p>Some tests end with a <code>return</code> statement, other's don't. This kind of inconsistency could be an indication of an error.</p>\n\n<p>Nothing gets done with <code>validation_errors</code>, it is just discarded when the <code>validate()</code> returns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T01:43:27.723", "Id": "435484", "Score": "0", "body": "Those are conditions which can never occur at the same time though. For example, if the minimum exists, then the exclusive minimum is set to null. So why bother checking 3 other conditions knowing they can never be true?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T01:49:04.013", "Id": "435485", "Score": "0", "body": "@darkhorse the problem description doesn't say that the class can't be initialized with both a minimum and an exclusive_minimum, etc. If that it part of the interface, then it isn't being checked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T01:53:27.940", "Id": "435486", "Score": "0", "body": "It is clearly written in the second paragraph (after the list), and the check is done in the 8th line of the init method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T02:24:38.623", "Id": "435487", "Score": "0", "body": "I guess I read it differently. It appears to work as you intended, so I deleted that part of my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T19:42:22.850", "Id": "224496", "ParentId": "224445", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T23:32:16.177", "Id": "224445", "Score": "1", "Tags": [ "python", "python-3.x", "validation" ], "Title": "Integer field in Python with extra constraints (Testable class)" }
224445
<p>The question can be found here <a href="https://leetcode.com/problems/letter-case-permutation" rel="nofollow noreferrer">https://leetcode.com/problems/letter-case-permutation</a></p> <blockquote> <p>Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.</p> </blockquote> <p>My question pertains mostly to the pattern that I am following. I find that with alot of these leetcode question that I want to use recursion for I find myself making two versions of a function. One which acts as the "interface" is this case <code>letterCasePermutation</code> and one which acts as the worker (<code>letterCasePermutationAux</code>) where the only difference is the arguments (I would usually have something like a counter and a reference to a vector to hold my answers). </p> <p>I choose this question as an example but really any recursive question could act as a stand in here. </p> <pre><code>class Solution(object): ans = [] def letterCasePermutationAux(self, S, i=0): if i &gt;= len(S): self.ans.append(S) return if S[i].isalpha(): temp = list(S) temp[i] = S[i].upper() if S[i].islower() else S[i].lower() self.letterCasePermutationAux("".join(temp), i+1) self.letterCasePermutationAux(S,i+1) def letterCasePermutation(self, S): self.ans=[] self.letterCasePermutationAux(S) return self.ans </code></pre> <p>My question is, is there a nicer way I can go about accomplishing this task? One which can perform recursion only using one function? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T03:17:29.173", "Id": "435409", "Score": "0", "body": "Why do the functions have a `self` parameter? Is this part of a class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T03:23:31.007", "Id": "435410", "Score": "0", "body": "@RootTwo, yes it is, I only took the relevant parts of the solution but I'll update it with the whole answer" } ]
[ { "body": "<p>It's fairly common to use an auxiliary parameter as an index or accumulator in recursive functions. If you don't like having the extra function or method \"cluttering\" the namespace, you can nest it inside the driver like this:</p>\n\n<pre><code>class Solution:\n\n def letterCasePermutation(self, S):\n\n def aux(S, i):\n\n if i &gt;= len(S) and len(S) &gt; 0:\n self.ans.append(S)\n return\n\n if S[i].isalpha():\n temp = list(S)\n temp[i] = S[i].upper() if S[i].islower() else S[i].lower()\n self.letterCasePermutationAux(\"\".join(temp), i+1)\n\n self.letterCasePermutationAux(S,i+1)\n\n self.ans=[]\n self.letterCasePermutationAux(S)\n\n return self.ans\n</code></pre>\n\n<p>A common way to recursively process a string, list, or other sequence is to define the base case as an empty sequence which returns a list with with the base case answer. If the sequence isn't empty, take off the first element of the sequence and recursively call the function with the rest of the list. Then process the list returned by the recursive call to add back in the first element.</p>\n\n<pre><code>class Solution:\n def letterCasePermutation(self, s):\n\n # base case the answer is a list with an empty string\n if s == '':\n return ['']\n\n else:\n ans = []\n\n if s[0].isalpha(): \n # if s[0] is a letter, prepend it to all the answers in the list\n # returned by the recursive call. First as a lowercase letter\n # and then as an uppercase letter\n for tail in self.letterCasePermutation(s[1:]):\n ans.append(s[0].lower() + tail)\n ans.append(s[0].upper() + tail)\n\n else:\n # if it's not a letter, just prepend it to all the answers in \n # the list returned by the recursive call.\n for tail in self.letterCasePermutation(s[1:]):\n ans.append(s[0] + tail)\n\n return ans\n</code></pre>\n\n<p>Here's an elegant solution using generators to create the permutations lazily:</p>\n\n<pre><code>class Solution:\n\n def letterCasePermutation(self, s):\n def aux(s, acc):\n if s == '':\n yield acc\n\n else:\n yield from aux(s[1:], acc + s[0])\n\n if s[0].isalpha():\n yield from aux(s[1:], acc + s[0].swapcase())\n\n yield from aux(s, '')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:19:00.170", "Id": "435438", "Score": "0", "body": "I had no idea it was possible to nest functions like that, thanks for the answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T04:23:28.417", "Id": "224453", "ParentId": "224450", "Score": "1" } }, { "body": "<h1>Solving without Recursion</h1>\n\n<p>Here is a very simple way to solve this specific problem without recursion and with only a single function. It might not extend to all the similar problems you want to, but it could extend to some of them:</p>\n\n<pre><code>def letterCasePermutation(S):\n results = [S]\n for i, char in enumerate(S):\n if char.isalpha():\n new_char = char.upper() if char.islower() else char.lower()\n results += [''.join([result[:i], new_char, result[i+1:]]) for result in results]\n return results\n</code></pre>\n\n<p>The idea is that each time we change a character, we can construct a new result for each old result, by simply slicing in the changed character on all those new results.</p>\n\n<h1>Recursion with Decorator</h1>\n\n<p>If the structure of the outer function is simple (or you are through enough in how you write your decorator) then we can write a simple decorator for such functions to use. The one to use here will be one lazily constructing parameters.</p>\n\n<h3>Decorator based on reference</h3>\n\n<p>If want to keep the format of your solution (the recursive function is side effect only), then we need to have the decorator specifically know that parameter and return it as a result. Your solution (taken as a function instead of as a method) with this method applied to it:</p>\n\n<pre><code>def lazy_curry_by_ref(results=list,**other_params):\n def dec(f):\n def wrapped(*args,**kwargs):\n result_item = results()\n other_params_items = {param:other_params[param]() for param in other_params}\n f(*args, **kwargs, result=result_item, **other_params_items, call_self=f)\n return result_item\n return wrapped\n return dec\n\n@lazy_curry_by_ref(results=list,i=int)\ndef letterCasePermutation(self, S, i=0, results=None, call_self=None):\n\n if i &gt;= len(S):\n results.append(S)\n return\n\n if S[i].isalpha():\n temp = list(S)\n temp[i] = S[i].upper() if S[i].islower() else S[i].lower()\n call_self(\"\".join(temp), i+1, results)\n\n call_self(S, i+1, results)\n</code></pre>\n\n<p>Note that I have specifically not included the typical <code>functools.wrap(f)</code> decorator on the inner decorator, since the the signature have changed and cannot be used anymore, so one would need to write a different type of decorator or special code to handle this.</p>\n\n<h3>Decoratur based on return</h3>\n\n<p>The above solution would be even simpler if we rewrote the program to return results, then we could just use a classic lazy_curry decorator:</p>\n\n<pre><code>def lazy_curry(**params):\n def dec(f):\n def wrapped(*args,**kwargs):\n params_items = {param:params[param]() for param in params}\n return f(*args,**kwargs, **params_items, call_self=f)\n return wrapped\n return dec\n\n@lazy_curry(results=list,i=int)\ndef letterCasePermutation(self, S, i=0, results=None, call_self=None):\n\n if i &gt;= len(S):\n results.append(S)\n return results\n\n if S[i].isalpha():\n temp = list(S)\n temp[i] = S[i].upper() if S[i].islower() else S[i].lower()\n call_self(\"\".join(temp), i+1, results)\n\n return call_self(S, i+1, results)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T13:45:51.420", "Id": "435443", "Score": "0", "body": "Did you test your implementations? At least Python 3.7 does not seem to like the \"decorator based on return approach\" and complains about `TypeError: letterCasePermutation() got multiple values for argument 'results'`. But it also could be me missing something here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T13:56:18.213", "Id": "435447", "Score": "0", "body": "@AlexV I can see how the problem happened (the recursion happens on the decorated version instead of itself). This can be fixed in several ways, The one I will use here includes the function as a new parameter." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:44:50.377", "Id": "224479", "ParentId": "224450", "Score": "1" } } ]
{ "AcceptedAnswerId": "224453", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T01:50:29.797", "Id": "224450", "Score": "4", "Tags": [ "python", "programming-challenge", "strings", "combinatorics" ], "Title": "Letter case permutation" }
224450
<blockquote> <p>You are given the following information, but you may prefer to do some research for yourself.</p> <p>1 Jan 1900 was a Monday.<br /> Thirty days has September,<br /> April, June and November.<br /> All the rest have thirty-one,<br /> Saving February alone,<br /> Which has twenty-eight, rain or shine.<br /> And on leap years, twenty-nine.<br /> A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.</p> <p>How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?</p> </blockquote> <pre><code>day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] month_days_common = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] month_to_days = dict(zip(month_names, month_days_common)) def is_leap(year): &quot;&quot;&quot;return True if a year is leap. False otherwise.&quot;&quot;&quot; if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return True else: return False else: return True else: return False def get_date_day_names(end_year): &quot;&quot;&quot;return a list of tuples containing day name, day, month, year from 1900 to end_year(exclusive).&quot;&quot;&quot; start_year = 1900 total = 0 all_day_names = [] all_months1 = [] all_months2 = {} year_month_times_number_of_days = [] final_dates = [] for year in range(start_year, end_year): count = 0 while count &lt; 12: all_months1.append((year, month_names[count])) count += 1 for year in range(start_year, end_year): if is_leap(year): total += 366 else: total += 365 for i in range(total): all_day_names.append(day_names[i % 7]) for year, month in all_months1: if is_leap(year): if month == 'February': all_months2[(year, month)] = 29 else: all_months2[(year, month)] = month_to_days[month] else: all_months2[(year, month)] = month_to_days[month] for date, number_of_days in all_months2.items(): for i in range(number_of_days): year_month_times_number_of_days.append((date, i + 1)) date_day_name = list(zip(all_day_names, year_month_times_number_of_days)) for date_item in date_day_name: final_dates.append((date_item[0], date_item[1][1], date_item[1][0][1], date_item[1][0][0])) return final_dates def count(day_name, day_of_the_month, end_year): &quot;&quot;&quot;returns count of a given day from 1901 to end_year(exclusive)&quot;&quot;&quot; final_dates = [] dates_1900_to_end_year = get_date_day_names(end_year) for date in dates_1900_to_end_year: if date[-1] != 1900 and date[0] == day_name and date[1] == day_of_the_month: final_dates.append(date) return len(final_dates) if __name__ == '__main__': print(count('Sunday', 1, 2001)) </code></pre>
[]
[ { "body": "<h1>whole algorithmic change => <span class=\"math-container\">\\$O(n)\\$</span></h1>\n\n<p>Your existing algorithm is quite confusing. Perhaps instead you could try a simpler structure such as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from datetime import date\n\ndef num_sundays_on_first_of_month(year1, year2):\n num_sundays = 0\n for i in range(year1, year2+1):\n for j in range(1, 13):\n if date(i, j, 1).weekday() == 6:\n num_sundays += 1\n return num_sundays\n\nif __name__ == '__main__':\n print(num_sundays_on_first_of_month(1901,2000))\n</code></pre>\n\n<p>This code is much more readable and <em>far</em> briefer. It makes effective use of the <a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\"><code>datetime</code> module</a> and its <code>date</code> objects. It works by looping through every month between <code>year1</code> and <code>year2</code> inclusive and counting if it is a Sunday.</p>\n\n<p>This runs at <span class=\"math-container\">\\$O(n)\\$</span> time where <span class=\"math-container\">\\$n = year2 - year1\\$</span></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T09:48:32.217", "Id": "435430", "Score": "1", "body": "Yeah, you have a point, I sometimes overcomplicate stuff. The whole point was trying not to use modules and I did it for fun I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T23:55:36.983", "Id": "435482", "Score": "0", "body": "If you don't. Want to use modules, The date class is a very simple object that can easily be added to your program." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T09:26:24.540", "Id": "224469", "ParentId": "224451", "Score": "1" } } ]
{ "AcceptedAnswerId": "224469", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T03:24:21.770", "Id": "224451", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "datetime" ], "Title": "Project Euler # 19 Counting Sundays in Python" }
224451
<blockquote> <p>n! means n × (n − 1) × ... × 3 × 2 × 1</p> <p>For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100!</p> </blockquote> <pre><code>def fact(n): &quot;&quot;&quot;returns factorial of n.&quot;&quot;&quot; if n &lt;= 1: return 1 return n * fact(n - 1) def count_digits(n): &quot;&quot;&quot;Assumes n &gt; 1. returns sum of digits of n's factorial.&quot;&quot;&quot; factorial = fact(n) total = 0 for digit in str(factorial): total += int(digit) return total if __name__ == '__main__': print(count_digits(100)) </code></pre>
[]
[ { "body": "<p>The standardlibrary module <code>math</code> already contains a <code>factorial</code> function. On my machine it is about 20 times faster than your function using <code>n = 100</code>. It also does not suffer from stack size limitations as yours does (try computing <code>fact(3000)</code>).</p>\n\n<p>Alternatively you could learn about memoizing, which will help you in many Project Euler problems. Here it would be useful if you had to evaluate the factorial of many numbers (and even better if the numbers are increasing).</p>\n\n<pre><code>from functools import wraps\n\ndef memoize(func):\n cache = func.__cache = {}\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n key = args, frozenset(kwargs.items())\n if key in cache:\n ret = cache[key]\n else:\n ret = cache[key] = func(*args, **kwargs)\n return ret\n return wrapper\n\n\n@memoize\ndef fact(n):\n ...\n</code></pre>\n\n<p>Note that this decorator only works if your arguments are hashable (so no lists for example).</p>\n\n<hr>\n\n<p>Since getting the sum of the digits of a number is something you will regularly need for Project Euler problems, you should make it a function on its own, which you put in a <code>utils</code> module, to be reused later:</p>\n\n<pre><code>def digit_sum(n):\n \"\"\"Return the sum of the digits of `n`\"\"\"\n return sum(map(int, str(n)))\n</code></pre>\n\n<p>This will also be faster than your manual <code>for</code> loop or a list comprehension. Not by much, but it is measurable for very large numbers:</p>\n\n<pre><code>def digit_sum_list_comprehension(n):\n return sum(int(x) for x in str(n))\n\ndef digit_sum_for(n):\n total = 0\n for digit in str(n):\n total += int(digit)\n return total\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/daPFa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/daPFa.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T06:40:48.643", "Id": "507550", "Score": "1", "body": "Bit odd to say \"don't reinvent math.factorial\" and then reinvent functools.lru_cache :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T07:28:58.407", "Id": "507553", "Score": "0", "body": "@Manuel You are absolutely right. But in my excuse, I was still stuck having to use Python 2 at the time, which does not have `lru_cache`, as it was only introduced in Python 3.2 (albeit in 2011)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T14:11:37.587", "Id": "224487", "ParentId": "224452", "Score": "3" } }, { "body": "<p>For even more speed than Graipher's solution, we can count the digits and multiply instead of turning every single one into an <code>int</code>:</p>\n<pre><code>def digit_sum_count(n):\n count = str(n).count\n return sum(i * count(str(i)) for i in range(1, 10))\n</code></pre>\n<p>Benchmark with Graipher's three versions and mine on n=3333! (which has 10297 digits):</p>\n<pre><code>2.75 ms 2.75 ms 2.73 ms digit_sum\n3.22 ms 3.18 ms 3.20 ms digit_sum_list_comprehension\n3.31 ms 3.31 ms 3.32 ms digit_sum_for\n1.73 ms 1.72 ms 1.74 ms digit_sum_count\n</code></pre>\n<p>Benchmark code:</p>\n<pre><code>from timeit import repeat\nfrom math import factorial\n\ndef digit_sum(n):\n return sum(map(int, str(n)))\n\ndef digit_sum_list_comprehension(n):\n return sum(int(x) for x in str(n))\n\ndef digit_sum_for(n):\n total = 0\n for digit in str(n):\n total += int(digit)\n return total\n\ndef digit_sum_count(n):\n count = str(n).count\n return sum(i * count(str(i)) for i in range(1, 10))\n\nfuncs = [\n digit_sum,\n digit_sum_list_comprehension,\n digit_sum_for,\n digit_sum_count,\n]\n\nn = factorial(3333)\nprint(len(str(n)))\nnumber = 10\n\n# Correctness\nexpect = funcs[0](n)\nfor func in funcs:\n print(func(n) == expect, func.__name__)\nprint()\n\n# Speed\ntss = [[] for _ in funcs]\nfor _ in range(3):\n for func, ts in zip(funcs, tss):\n t = min(repeat(lambda: func(n), number=number)) / number\n ts.append(t)\n print(*('%.2f ms ' % (t * 1e3) for t in ts), func.__name__)\n print()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T06:11:07.807", "Id": "507548", "Score": "0", "body": "Now I would be curious to see how using a `collections.Counter` would fare, since it only needs one pass on the string instead of ten. Would also be interesting to see when, if ever, your approach becomes slower than mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T06:24:25.053", "Id": "507549", "Score": "1", "body": "@Graipher You mean you'd like to see whether `Counter` would slow it down so much that it'd be slower than yours? And I guess if you make `n` *small* enough, yours might eventually be faster. Oh and I'm not doing ten passes, I'm doing nine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T07:30:22.560", "Id": "507554", "Score": "0", "body": "I will test it later and then I'll see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T07:53:42.680", "Id": "507557", "Score": "1", "body": "You are right: https://i.stack.imgur.com/fCjMT.png\nThis is with the `str(n)` taken out and directly passing a string to the functions, since at ~10^5 digits that seems to start dominating the results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T11:48:49.827", "Id": "507585", "Score": "0", "body": "Thanks for plotting. Btw I also tried mine with `count = str(n).replace('0', '').count`. That's another pass, but for n=3333!, about 17% of the digits are zeros and thus the nine counting passes have 17% less to do. But it was slightly slower." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-10T21:54:48.943", "Id": "256997", "ParentId": "224452", "Score": "1" } }, { "body": "<p>100! ends with 24 zeros. You can save carrying those around unnecessarily. With a bit of thought, we don't need to remove them every iteration, because zeros only appear when we multiply by a number containing 5 in its factorisation:</p>\n<pre><code>def factorial_no_trailing_0s(n):\n &quot;&quot;&quot;Factorial of n, with trailing zeros removed.&quot;&quot;&quot;\n fact = 1\n for i in range(2, n+1):\n fact *= i\n if i % 5 == 0:\n while fact % 10 == 0:\n fact //= 10\n return fact\n</code></pre>\n<p>or, probably more efficient (but I haven't benchmarked):</p>\n<pre><code>def factorial_no_trailing_0s(n):\n &quot;&quot;&quot;Factorial of n, with trailing zeros removed.&quot;&quot;&quot;\n fact = 1\n for i in range(2, n+1):\n while i % 5 == 0:\n i //= 5\n fact //= 2\n fact *= i\n return fact\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T21:17:47.947", "Id": "507647", "Score": "0", "body": "Actually, 100! ends with *24* zeros. Interesting idea, though benchmarks would be good to see whether / how much faster these are / make it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T21:49:54.993", "Id": "507649", "Score": "0", "body": "I didn't count - I just reckoned 25 from 5,10,15,... and 4 more from 25,50,75,100. Ah, I see what I did - that first batch is only 20 elements!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T17:20:58.467", "Id": "257035", "ParentId": "224452", "Score": "0" } } ]
{ "AcceptedAnswerId": "224487", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T03:36:25.063", "Id": "224452", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 20 factorial digit sum in Python" }
224452
<p>I'm currently working on a unit testing course (<code>NUnit 3.x</code>). I've been tasked with a simple class to test all edge cases.</p> <pre><code>using System; namespace TestNinja.Fundamentals { public class DemeritPointsCalculator { private const int SpeedLimit = 65; private const int MaxSpeed = 300; public int CalculateDemeritPoints(int speed) { if (speed &lt; 0 || speed &gt; MaxSpeed) throw new ArgumentOutOfRangeException(); if (speed &lt;= SpeedLimit) return 0; const int kmPerDemeritPoint = 5; var demeritPoints = (speed - SpeedLimit)/kmPerDemeritPoint; return demeritPoints; } } } </code></pre> <p>And -</p> <pre><code>using System; using NUnit.Framework; using TestNinja.Fundamentals; namespace TestNinja.UnitTests { [TestFixture] public class CalculateDemeritPointsTests { private DemeritPointsCalculator _demeritPointsCalculator; [SetUp] public void SetUp() { _demeritPointsCalculator = new DemeritPointsCalculator(); } // my solutions [Test] [TestCase(65,0)] [TestCase(70,1)] [TestCase(75,2)] [TestCase(80,3)] [TestCase(0,0)] [TestCase(60,0)] [TestCase(66,0)] public void CalculateDemeritPoints_WhenCalled_ReturnsExpectedInt(int speed, int expectedResult) { var result = _demeritPointsCalculator.CalculateDemeritPoints(speed); Assert.That(result, Is.EqualTo(expectedResult)); } [Test] public void CalculateDemeritPoints_SpeedLessThan0_ThrowsException() { Assert.That(() =&gt; _demeritPointsCalculator.CalculateDemeritPoints(-1), Throws.InstanceOf&lt;ArgumentOutOfRangeException&gt;()); } [Test] public void CalculateDemeritPoints_SpeedGreaterThan300_ThrowsException() { Assert.That(() =&gt; _demeritPointsCalculator.CalculateDemeritPoints(301), Throws.InstanceOf&lt;ArgumentOutOfRangeException&gt;()); } } } </code></pre> <p>Am I using to many test cases for <code>CalculateDemeritPoints_WhenCalled_ReturnsExpectedInt</code>?</p> <p>I was thinking about merging the final two tests into one as they would also work with test cases, but I wasn't sure if I was doing to many.</p>
[]
[ { "body": "<p>You probably want to </p>\n\n<ul>\n<li>add a constant for speed 0</li>\n<li>create a test for MaxSpeed</li>\n<li>create a test case for 64 (it's one edge of the <em>partition class</em> <code>0 &lt;= x &lt; speedlimit</code> and it could replace 60 which is in the same partition class)</li>\n</ul>\n\n<p>I would keep the 66 test case since it is and edge case.</p>\n\n<p>Even though the edges are cut pretty clear with ints (compared to using float values) you might still want to test them explicitly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T13:14:11.920", "Id": "224480", "ParentId": "224460", "Score": "2" } }, { "body": "<p>Since this code is a <strong>black box</strong>, because it calculates everything itself without calling any dependencies the caller can be aware of, we should test this method with sufficient variations of input to yield us:</p>\n\n<ul>\n<li>any <code>speed &lt; 0</code> should yield <code>error</code></li>\n<li>any <code>speed &gt; 300</code> should yield <code>error</code></li>\n<li>any <code>speed</code> between <code>0</code> and <code>65</code> (bounds included) should yield <code>0</code></li>\n<li>any <code>speed</code> between <code>66</code> and <code>300</code> (bounds included) should yield the integer division <code>(speed - 65) / 5</code></li>\n</ul>\n\n<p>If the method would have been coded as a <strong>white box</strong> instead, using mockable dependencies, things would have been different. We could then just test <code>Assert.WasCalled(depedency.method(speed))</code>.</p>\n\n<h1>In-depth testing</h1>\n\n<p><em>These are the test cases a developer/tester should write that does not have access to the content of the method, only the interface and specification.</em></p>\n\n<p>Since the <strong><em>entropy</em></strong> is not that big and we are working with <strong>discrete integers</strong>, I suggest to test any integer from <code>0 - buffer</code> to <code>300 + buffer</code> against either a matrix of pre-calculated results or a formula in the unit test that emulates the algorithm. I prefer the former, since a bug in the method flow is easily introduced in the unit test as well.</p>\n\n<h1>Minimal test cases</h1>\n\n<p><em>These are the minimal test cases the developer that knows the content of the method could perform.</em></p>\n\n<pre><code>// speed result test case justification\n// -1 error upper bound of of speed &lt; 0\n// 0 0 lower bound of speed &gt;= 0 and speed &lt;= SpeedLimit\n// 65 0 upper bound of speed &gt;= 0 and speed &lt;= SpeedLimit\n// 66 0 lower bound of speed &gt; SpeedLimit &amp; speed &lt;= MaxSpeed\n// 70-74 1 group #1 to test (speed - SpeedLimit) / 5\n// 75-79 2 group #2 to test (speed - SpeedLimit) / 5\n// 300 47 upper bound of speed &gt; SpeedLimit &amp; speed &lt;= MaxSpeed\n// 301 error lower bound of speed &gt; MaxSpeed\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T18:49:04.950", "Id": "224493", "ParentId": "224460", "Score": "1" } }, { "body": "<blockquote>\n <p>Am I using too many test cases for <code>CalculateDemeritPoints_WhenCalled_ReturnsExpectedInt</code>?</p>\n</blockquote>\n\n<p>Yes. I'd say so, anyway.</p>\n\n<p>Let's say I'm maintaining code you've written. When a test case fails, ideally it will give me exactly the information I need to fix it, and it will give me that information as quickly as possible. The very first thing I will see when I learn a test has failed? That test's name.</p>\n\n<p>Currently if I see that this test method has failed, all I learn from the name is that the calculator didn't return what was expected. That doesn't give me very much information about what kind of bug to look for, so I'll have to dig a little deeper to find what what speed was passed in, what demerit value was returned, and why that value was unexpected.</p>\n\n<p>You can save me that digging by adding a test called <code>CalculateDemeritPoints_LegalSpeed_GivesNoDemerits</code>, and putting all your <code>TestCase(_,0)</code> cases there. As a bonus, <code>[TestCase(60)]</code> on top of a method named \"Legal Speed\" is more instantly readable than <code>[TestCase(60,0)]</code> on top of a method named \"Expected\".</p>\n\n<p>In general, if a single test method is testing different <em>kinds</em> of behavior, I will say it's too much. As a rule of thumb, different branches of code probably deserve different test methods.</p>\n\n<hr>\n\n<p>As a side note, I think it would be fine if you combined the two exception test methods into one.</p>\n\n<p>On the other hand, I'd also be fine if you skipped test parameterization and made separate test methods for every single test case.</p>\n\n<p>The key, in my opinion, is to look at it through the maintainer's eyes. How much can you assist that person in understanding what your code is doing, and what's going wrong with it?</p>\n\n<hr>\n\n<p>As another side note, I also dislike (although it's not a strong dislike) the common practice of class-level setup and teardown methods. Especially in a case like this; the <code>[Setup]</code> is saving you exactly one line of code per test, and test code is <em>cheap</em>.</p>\n\n<p>As a maintenance programmer, if I see that a test has failed, I will always have to go inspect the failing test method. Will you <em>also</em> make me search for any other methods that might have fired as a part of the test? For example: If a test is failing because the test object was constructed with a strange argument, and the call to the constructor was in a setup method, that means cause of the failure has been hidden from me.</p>\n\n<p>For that reason, I like to err on the side of verbose test methods, in order to make each method self-contained (and therefore, easier to follow).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T20:34:55.167", "Id": "435634", "Score": "0", "body": "very good point from the perspective of maintenance, a failed unit test should give a concrete and meaningful error message" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T22:53:29.673", "Id": "224511", "ParentId": "224460", "Score": "2" } } ]
{ "AcceptedAnswerId": "224511", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T07:28:01.127", "Id": "224460", "Score": "3", "Tags": [ "c#", "unit-testing", "nunit" ], "Title": "Unit tests for a function that calculates demerit points for speeding" }
224460
<p>Let <span class="math-container">\$d(n)\$</span> be defined as the sum of proper divisors of <span class="math-container">\$n\$</span> (numbers less than <span class="math-container">\$n\$</span> which divide evenly into <span class="math-container">\$n\$</span>). If <span class="math-container">\$d(a) = b\$</span> and <span class="math-container">\$d(b) = a\$</span>, where <span class="math-container">\$a ≠ b\$</span>, then <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> are an amicable pair and each of <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> are called amicable numbers.</p> <p>For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.</p> <p>Evaluate the sum of all the amicable numbers under 10000. Here's my implementation in Python. I need your feedback on how this can be improved.</p> <p>Note: I'm a beginner in programming.</p> <pre><code>from time import time def get_divisors(n): """Yields divisors of n.""" divisor = 2 while divisor * divisor &lt;= n: if n % divisor == 0 and n // divisor != divisor: yield divisor if n // divisor != divisor: yield n // divisor divisor += 1 yield 1 def get_sum_amicable(n, divs={2:1}): """Yields amicables below n.""" for number1 in range(n): for number2 in range(number1): try: if divs[number2] == number1 and divs[number1] == number2: yield number1 yield number2 except KeyError: divs[number1] = sum(get_divisors(number1)) divs[number2] = sum(get_divisors(number2)) if divs[number2] == number1 and divs[number1] == number2: yield number1 yield number2 if __name__ == '__main__': start = time() print(sum(get_sum_amicable(10000))) print(f'Time: {time() - start} seconds.') </code></pre>
[]
[ { "body": "<h3>Readability / maintainability</h3>\n\n<pre><code>def get_sum_amicable(n, divs={2:1}):\n \"\"\"Yields amicables below n.\"\"\"\n for number1 in range(n):\n for number2 in range(number1):\n try:\n if divs[number2] == number1 and divs[number1] == number2:\n yield number1\n yield number2\n except KeyError:\n divs[number1] = sum(get_divisors(number1))\n divs[number2] = sum(get_divisors(number2))\n if divs[number2] == number1 and divs[number1] == number2:\n yield number1\n yield number2\n</code></pre>\n\n<p>This is awful. It violates the rule \"<em>Don't Repeat Yourself</em>\"; it expects exceptions as part of non-exceptional flow; and it relies on an obscure language feature/mis-feature.</p>\n\n<p>All you need to do is sum numbers <code>x in range(n)</code> (or, perhaps better, <code>range(2, n)</code>, to avoid complications around <code>0</code> and <code>1</code>) for which <code>d(x) &lt; n and d(d(x)) == x</code>. (And given the way the question is phrased, you might assume that there will be no amicable pair which is split around <code>n</code>, so the first half of the test is probably unnecessary). That's a one-liner.</p>\n\n<p>If you want to cache <code>d</code>, instead of using default values you can use <code>functools.lru_cache</code>. But...</p>\n\n<h3>Performance</h3>\n\n<p>Whenever you're doing divisibility checks on every number from <code>1</code> to <code>n</code>, you should think about using a sieve. Either build an array of one prime factor of each number, and work from that, or (where appropriate) inline the calculation into the sieve processing.</p>\n\n<p>It's fairly easy to adapt the sieve of Eratosthenes to generate an array of <code>d</code> efficiently using the inline approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T08:38:02.303", "Id": "435426", "Score": "0", "body": "Thank you for the feedback and any real examples you can provide will be greatly appreciated, it's a bit ambiguous what you explained maybe because i'm not that experienced in programming and i'm in the learning process I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T11:03:54.837", "Id": "435432", "Score": "1", "body": "If you have specific questions relating to code, I can try to answer them. But I'm probably not going to write the code for you, or go into details on the maths, because (a) that misses the point of Project Euler; you'll learn more by doing than by reading; and (b) if you really want to miss the point of Project Euler, there are already resources out there with detailed explanations of the first hundred problems." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T08:20:06.477", "Id": "224462", "ParentId": "224461", "Score": "1" } } ]
{ "AcceptedAnswerId": "224462", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T07:34:23.630", "Id": "224461", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "dynamic-programming" ], "Title": "Project Euler # 21 amicable numbers Python" }
224461
<p>I wanted to detect if I have a member in a simple POD struct and after some searching and merging some methods I found on the web I've come up with this solution:</p> <pre><code>#include &lt;iostream&gt; template&lt;class...Fs&gt; struct funcs_t{}; template&lt;class F0, class...Fs&gt; struct funcs_t&lt;F0, Fs...&gt;: F0, funcs_t&lt;Fs...&gt; { funcs_t(F0 f0, Fs... fs): F0(std::move(f0)), funcs_t&lt;Fs...&gt;(std::move(fs)...) {} using F0::operator(); using funcs_t&lt;Fs...&gt;::operator(); }; template&lt;class F&gt; struct funcs_t&lt;F&gt;:F { funcs_t(F f) : F(std::move(f)) {}; using F::operator(); }; template&lt;class...Fs&gt; funcs_t&lt;std::decay_t&lt;Fs&gt;...&gt; funcs(Fs&amp;&amp;...fs) { return {std::forward&lt;Fs&gt;(fs)...}; } #define HAS_MEMBER(cls, memb)\ [](){\ auto with_memb = [](auto &amp;&amp;A, int x)\ -&gt; decltype(typename std::remove_reference&lt;decltype(A)&gt;::type().memb, std::true_type())\ {\ return std::true_type();\ };\ auto with_no_memb = [](auto &amp;&amp;A, float x) -&gt; std::false_type {\ return std::false_type();\ };\ auto has_memb = funcs(with_memb, with_no_memb);\ return has_memb(cls(), 1);\ }() struct A { int a; int b; }; int main(int argc, char const *argv[]) { std::cout &lt;&lt; HAS_MEMBER(A, b) &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T16:39:58.357", "Id": "435460", "Score": "1", "body": "Why do you need this? What are you trying to achieve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T18:45:41.190", "Id": "435467", "Score": "0", "body": "I have different pod structs with many common fields with the same meaning and I wanted to print them on screen. I will see if I can use it for other things but for now that's what I needed it for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T19:04:47.037", "Id": "435468", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. If you want a fixed-version of your code to be available, post it as answer linking to Deduplicator's for credit (or post it as a new question, but it's hardly a major change)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T19:16:34.767", "Id": "435469", "Score": "0", "body": "Ok, I'll keep that in mind." } ]
[ { "body": "<ol>\n<li><p>Your detector fails in the face of overloading and templating. Also, it will only detect (static) member-variables and (static) member-functions. While you can extend it to types (and type-aliases), accepting templates and overloading would need better language-provided reflection-facilities.</p>\n\n<p>Anyway, pure existence is generally uninteresting, supported operations count.</p></li>\n<li><p><code>funcs()</code> and <code>funcs_t</code> are nearly a generally useful abstraction.</p>\n\n<p>Just use perfect forwarding instead of by-value and <code>std::move()</code>. Allowing for all callables, including <code>final</code> classes, function-pointers, member-function-pointers, and the same wrapped in a <code>std::reference_wrapper</code> would admittedly add significant amounts of code.</p>\n\n<p>A good name would be <code>overloaded</code>.</p></li>\n<li><p><code>HAS_MEMBER</code> needlessly depends on default-constructing the passed class. Fix that by using <code>decltype</code>, <code>std::declval()</code> and unevaluated contexts.</p></li>\n<li><p>If you don't use an argument, don't name it. Specifically for <code>main()</code>, just don't ask for it.</p></li>\n<li><p>Don't use <code>std::endl</code>. In the rare cases you actually need to flush manually, be explicit and use <code>std::flush</code>. Nearly always you are just crippling performance.</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>. Make of that what you will.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T09:18:51.503", "Id": "224468", "ParentId": "224463", "Score": "6" } } ]
{ "AcceptedAnswerId": "224468", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T08:26:10.380", "Id": "224463", "Score": "8", "Tags": [ "c++", "c++14", "meta-programming" ], "Title": "Detecting existence of a class member" }
224463
<p>Please can I have some feedback on my Python Turtle implementation of the 15 Puzzle?</p> <p>I have deliberately avoided using OOP as my aim is to develop a clear and clean coding style suitable for teaching programming at school (at a level before OOP is relevant). I also tried to avoid using globals by passing arguments, but found that doing so introduced more complexity than seemed justifiable.</p> <p>I would like comments on the quality and consistency of the code, and any improvements that seem necessary to meet the criteria of "code that doesn't suck."</p> <p>The images can be found here: <a href="https://github.com/Robin-Andrews/15-Puzzle-Python-Turtle" rel="nofollow noreferrer">https://github.com/Robin-Andrews/15-Puzzle-Python-Turtle</a></p> <p>I would like confirmation that the logic is completely correct, and given that the design of the solution was entirely mine, perhaps some indication in the great scheme of things of my apparent skill level at this stage.</p> <pre><code>import turtle import tkinter as tk import random NUM_ROWS = 4 NUM_COLS = 4 TILE_WIDTH = 90 # Actual image size TILE_HEIGHT = 90 # Actual image size FONT_SIZE = 24 FONT = ('Helvetica', FONT_SIZE, 'normal') SCRAMBLE_DEPTH = 10 images = [] for i in range(NUM_ROWS * NUM_COLS - 1): file = f"number-images/{i+1}.gif" images.append(file) images.append("number-images/empty.gif") def register_images(): global screen for i in range(len(images)): screen.addshape(images[i]) def index_2d(my_list, v): """Returns the position of an element in a 2D list.""" for i, x in enumerate(my_list): if v in x: return (i, x.index(v)) def swap_tile(tile): """Swaps the position of the clicked tile with the empty tile.""" global screen current_i, current_j = index_2d(board, tile) empty_i, empty_j = find_empty_square_pos() empty_square = board[empty_i][empty_j] if is_adjacent([current_i, current_j], [empty_i, empty_j]): temp = board[empty_i][empty_j] board[empty_i][empty_j] = tile board[current_i][current_j] = temp draw_board() def is_adjacent(el1, el2): """Determines whether two elements in a 2D array are adjacent.""" if abs(el2[1] - el1[1]) == 1 and abs(el2[0] - el1[0]) == 0: return True if abs(el2[0] - el1[0]) == 1 and abs(el2[1] - el1[1]) == 0: return True return False def find_empty_square_pos(): """Returns the position of the empty square.""" global board for row in board: for candidate in row: if candidate.shape() == "number-images/empty.gif": empty_square = candidate return index_2d(board, empty_square) def scramble_board(): """Scrambles the board in a way that leaves it solvable.""" global board, screen for i in range(SCRAMBLE_DEPTH): for row in board: for candidate in row: if candidate.shape() == "number-images/empty.gif": empty_square = candidate empty_i, empty_j = find_empty_square_pos() directions = ["up", "down", "left", "right"] if empty_i == 0: directions.remove("up") if empty_i &gt;= NUM_ROWS - 1: directions.remove("down") if empty_j == 0: directions.remove("left") if empty_j &gt;= NUM_COLS - 1: directions.remove("right") direction = random.choice(directions) if direction == "up": swap_tile(board[empty_i - 1][empty_j]) if direction == "down": swap_tile(board[empty_i + 1][empty_j]) if direction == "left": swap_tile(board[empty_i][empty_j - 1]) if direction == "right": swap_tile(board[empty_i][empty_j + 1]) def draw_board(): global screen, board # Disable animation screen.tracer(0) for i in range(NUM_ROWS): for j in range(NUM_COLS): tile = board[i][j] tile.showturtle() tile.goto(-138 + j * (TILE_WIDTH + 2), 138 - i * (TILE_HEIGHT + 2)) # Restore animation screen.tracer(1) def create_tiles(): """ Creates and returns a 2D list of tiles based on turtle objects in the winning configuration. """ board = [["#" for _ in range(NUM_COLS)] for _ in range(NUM_ROWS)] for i in range(NUM_ROWS): for j in range(NUM_COLS): tile_num = 4 * i + j tile = turtle.Turtle(images[tile_num]) tile.penup() board[i][j] = tile def click_callback(x, y, tile=tile): """Passes `tile` to `swap_tile()` function.""" return swap_tile(tile) tile.onclick(click_callback) return board def create_scramble_button(): global screen canvas = screen.getcanvas() button = tk.Button(canvas.master, text="Scramble", background="cadetblue", foreground="white", bd=0, command=scramble_board) canvas.create_window(0, -240, window=button) def main(): global screen, board # Screen setup screen = turtle.Screen() screen.setup(600, 600) screen.title("15 Puzzle") screen.bgcolor("aliceblue") screen.tracer(0) # Disable animation register_images() # Initialise game and display board = create_tiles() create_scramble_button() scramble_board() draw_board() screen.tracer(1) # Restore animation main() turtle.done() </code></pre>
[]
[ { "body": "<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place. Conversely, on an ugly old piece of code I wrote without static analysis support I recently found the complexity reaches 87!)</p></li>\n<li><p>I would then normally recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<p>I'm ambivalent about introducing this in code for beginners since it's a complex thing to get right, but in example code I think it could be useful to explain what is happening.</p></li>\n</ol>\n\n<p>Specific suggestions:</p>\n\n<ol>\n<li>I would argue that globals are <em>more</em> confusing than passing arguments around. After all, keeping that global state in mind as we jump from function to function is one of the main reasons it's unpopular for readability, debuggability and maintainability.</li>\n<li>When introducing programming I think it would be helpful to expand every non-obvious abbreviation, such as <code>NUM_COLS</code>. A programmer will recognize that pretty much instantly, but a beginner may be better served with more legibility rather than succinctness. I would also avoid using the indirection of aliases such as <code>tk</code> for <code>tkinter</code> - it may be common to do so among tkinter users, but it's an entirely new concept for students.</li>\n<li>On that note, naming is incredibly important for maintainability, because it makes the code easier to read and it especially makes it possible to read each part of the code <em>in isolation</em> and understand what it does, without reference to the rest of it. So I would recommend expanding names like <code>v</code> to <code>value</code>, <code>i</code> to <code>index</code> and <code>el1</code> to <code>first_element</code> and avoiding vacuous names like <code>temp</code> wherever possible.</li>\n<li>You can provide an extra parameter to <code>range</code> to start at 1 instead of 0, simplifying your f-string.</li>\n<li>There's some dead code in here (using an IDE like the excellent <a href=\"https://www.jetbrains.com/pycharm/\" rel=\"nofollow noreferrer\">PyCharm Community Edition</a> will show you most of these and more for free):\n\n<ul>\n<li><code>swap_tile</code>'s <code>empty_square</code>.</li>\n<li><code>scramble_board</code>'s <code>empty_square</code>.</li>\n<li><code>FONT</code> and <code>FONT_SIZE</code>.</li>\n<li><code>click_callback</code>'s <code>x</code> and <code>y</code> parameters.</li>\n</ul></li>\n<li><code>abs(±0)</code> is zero, so <code>abs(el2[1] - el1[1]) == 0</code> can be simplified to <code>el2[1] - el1[1] == 0</code>.</li>\n<li><code>is_adjacent</code> does the same calculations twice unless the first conditional is true. Pulling out variables like <code>x_adjacent</code> and <code>y_adjacent</code> has the additional benefit of simplifying the expression to just <code>return x_adjacent or y_adjacent</code>.</li>\n<li><code>find_empty_square_pos</code> should <em>stop</em> as soon as it finds the empty square. You can simply <code>return index_2d(board, candidate)</code>.</li>\n<li><code>for i in range(SCRAMBLE_DEPTH):</code> would be more idiomatic as <code>for _ in range(SCRAMBLE_DEPTH):</code> since the index variable is not used, but that may not be worth explaining.</li>\n<li>There are a few \"magic\" values which would be easier to read as constants, like 600 (<code>WINDOW_SIZE</code>? Could this be calculated based on the tile size and margins?), -240 (<code>WINDOW_Y_OFFSET</code>?), 4 (<code>COLUMN_COUNT</code>, aka. <code>NUM_COLS</code>?) and 2 (<code>TILE_PADDING</code>?).</li>\n<li><p>The canonical way to make an executable Python script is to put this ugly thing (and nothing else) at the end of the file:</p>\n\n<pre><code>if __name__ == \"__main__\":confirmation that the logic is completely correct\n main()\n</code></pre>\n\n<p>doing that makes the script contents reusable, because they can be imported by other scripts without actually running the program. This might be too much for beginners, but it's an extremely common pattern so I thought it was worth mentioning.</p></li>\n</ol>\n\n<p>As for</p>\n\n<blockquote>\n <p>confirmation that the logic is completely correct</p>\n</blockquote>\n\n<p>I'm pretty sure you can't get a definite answer from anyone on this site unless there are actually obvious bugs. A comprehensive test suite would help, and is probably the simplest way to achieve some confidence in the workings. Unfortunately this code would be hard to test, because display and logic are tightly coupled.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T19:57:56.850", "Id": "435892", "Score": "0", "body": "Thanks @l0b0. All very useful. I forgot to keep the logic separate from the display in my haste to get the thing working! Next time..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T10:16:48.550", "Id": "224471", "ParentId": "224465", "Score": "1" } } ]
{ "AcceptedAnswerId": "224471", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T08:40:43.573", "Id": "224465", "Score": "2", "Tags": [ "python", "sliding-tile-puzzle", "turtle-graphics" ], "Title": "Python Turtle implementation of the 15 Puzzle" }
224465
<p>Recently I got test task at the project, it is fairly simple:</p> <blockquote> <pre><code>const _ = require('underscore'); // Challenge: // // Write a function that accepts as argument a "function of one variable", and returns a new // function. The returned function should invoke the original parameter function on every "odd" // invocation, returning undefined on even invocations. // // Test case: // function to wrap via alternate(): doubleIt, which takes a number and returns twice the input. // input to returned function: 1,2,3,4,9,9,9,10,10,10 // expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined const input = [1,2,3,4,9,9,9,10,10,10]; const doubleIt = x =&gt; x * 2; const alternate = (fn) =&gt; { // Implement me! // // The returned function should only invoke fn on every // other invocation, returning undefined the other times. } var wrapped = alternate(doubleIt) _.forEach(input, (x) =&gt; console.log(wrapped(x))) // expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined </code></pre> </blockquote> <p>And my solution was:</p> <pre><code>const alternate = (fn) =&gt; { let odd = false; return (x) =&gt; { odd = !odd; if (odd) { return fn(x); } return undefined; }; }; // An alternate solution if ternary operator (?) is allowed according to coding standards used on the project. // Sometimes it's treated as bad practise. const alternateShort = (fn) =&gt; { let odd = false; return (x) =&gt; (odd = !odd) ? fn(x) : undefined; }; </code></pre> <p>And I got the reply that tech lead didn't like my solution at all and I'm not hired to the project. I'm really confused, do you have any idea what else he could expect? Do you see here any alternative solutions?</p>
[]
[ { "body": "<p>A short review of things that could trigger me if I were the lead</p>\n\n<ul>\n<li>Why are you returning <code>undefined</code>? That is what a function does by default.</li>\n<li>All your functions are anonymous, a nightmare in stacktraces</li>\n<li>There is a time and place for arrow functions, this code implies that you never use <code>function</code>\n\n<ul>\n<li>Though to be fair, the challenge over-uses arrow functions as well</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:32:53.167", "Id": "224477", "ParentId": "224466", "Score": "4" } }, { "body": "<p>Code style is not the problem. The expectation is that a new coder uses the in house style guides when writing.</p>\n\n<p>I think the problem is that you missed an important assumption. </p>\n\n<p>The test case passes one argument, however that does not mean that the function you are given will have only one argument.</p>\n\n<p>Thus maybe (I am just guessing) if you wrote... </p>\n\n<pre><code>const alternate = fn =&gt; {\n let odd = false;\n return (...args) =&gt; (odd = !odd) ? fn(...args) : undefined;\n};\n</code></pre>\n\n<p>Also though not stated there could have been an expectation that it not throw on bad input. Thus first vet the input function.</p>\n\n<pre><code>const alternate = fn =&gt; {\n let odd = false;\n return typeof fn === \"function\" ?\n (...args) =&gt; odd = !odd ? fn(...args) : undefined :\n () =&gt; {};\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function alternate (fn) {\n if (typeof fn === \"function\") {\n let odd = false;\n return (...args) =&gt; odd = !odd ? fn(...args) : undefined;\n }\n return () =&gt; {};\n}\n</code></pre>\n\n<p>As the documentation does not say anything about throwing an error the safer bet is to silently deal with bad input</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T20:13:05.503", "Id": "435633", "Score": "0", "body": "the one function variable is literally part of the written challenge. That doesnt take away that your code would get extra bonus points." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T22:50:09.420", "Id": "224510", "ParentId": "224466", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T09:01:14.807", "Id": "224466", "Score": "8", "Tags": [ "javascript", "interview-questions", "functional-programming", "comparative-review" ], "Title": "Function invocation every second time" }
224466
<p>I have solved an assignment (Exercise 3) from the MOOC <a href="https://materiaalit.github.io/2013-oo-programming/part2/week-7/" rel="noreferrer">Object-Oriented programming with Java, part II</a>, but I'm not enrolled in said course.</p> <blockquote> <p><strong>Assignment Summary:</strong> </p> <p>Make a simple calculator. You may create a Reader class that encapsulates the Scanner-object in order to communicate with the user. The Scanner-object can be an instance variable. Implement class Reader with the following methods: </p> <ul> <li>public String readString() </li> <li>public int readInteger() </li> </ul> <p>To take care of the application logic of your program, a method <em>public void start()</em> may be used. The calculator has the commands <em>sum</em>, <em>difference</em>, <em>product</em> and <em>end</em>. Add an instance variable of the type Reader for the calculator and create the reader in the constructor. You may also implement a method <em>private void statistics()</em>. The method is meant to print the amount of operations done with the Calculator-object. If an invalid command is given (something other than sum, difference, product or end), the calculator should not react to the command in any way, but should instead continue by asking the next command. Statistics should not count as an invalid command as a completed calculation.</p> </blockquote> <p><strong>Changes made from assignment</strong> </p> <ul> <li>The <code>Reader</code> class doesn't exactly encapsulate the Scanner-object, and I have only provided static methods to the class. I had wanted it to inherit from the Scanner class, but Scanner was a <em>final</em> class.</li> <li>Scanner-object wasn't made an instance variable.</li> <li><em>enum</em> is used for the various calculator commands.</li> <li>The calculator gives a message when an invalid command is given.</li> <li>The calculator contains only static methods.</li> <li>I have omitted method: public void start()</li> <li>A static variable : public static boolean isRunning(), is used a state variable</li> </ul> <p>How do you <em>refactor</em> this code so that it follows OOP, reads better, is manageable? How can I write method names and classes better? How do you know which entities are to be made separate classes, and how to use classes efficiently? </p> <p>I had thought of using a separate Command class that has a list of commands to use (whether in calculator or in any other class that uses a command style execution, like a terminal), but I didn't know how to proceed with that. Functions aren't objects in Java and generalizing seems difficult even with using Reflection in Java, especially the number and type of the return values, and typecasting new parameters with said types.</p> <p><code>Reader</code> Class used to simplify Scanner class (It can't be inherited, it seems)</p> <pre class="lang-java prettyprint-override"><code>import java.util.Scanner; public class Reader { public static String readString(String prompt) { System.out.print(prompt); return new Scanner(System.in).nextLine(); } public static int readInteger(String prompt) { return Integer.parseInt(readString(prompt)); } } </code></pre> <p><code>Calculator</code> class</p> <pre class="lang-java prettyprint-override"><code>import java.util.stream.IntStream; public class Calculator { private static int statistics = 0; private static boolean isRunning = true; enum Command { SUM, DIFFERENCE, PRODUCT, END } public static boolean isRunning() { return isRunning; } public static Command getCommand() throws IllegalCommand { String command = Reader.readString("command: "); try { return Command.valueOf(command.toUpperCase()); } catch (Exception e) { throw new IllegalCommand("Command " + command + " not found"); } } private static void printResult(String operation, int result) { System.out.println(operation + " of the values " + result); } private static int[] readOperands(int noOfOperands) { int[] array = new int[noOfOperands]; for (int i = 0; i &lt; noOfOperands; i++) { array[i] = Reader.readInteger(String.format("value%d: ", i + 1)); } return array; } public static int sum(int... a) { return IntStream.of(a).sum(); } public static int product(int... a) { int result = 1; for (int i = 0; i &lt; a.length; i++) { result *= a[i]; } return result; } public static void execute(Command command) { switch (command) { case SUM: { int[] operands = readOperands(2); printResult("Sum", sum(operands)); statistics++; break; } case DIFFERENCE: { int[] operands = readOperands(2); printResult("Difference", operands[0] - operands[1]); statistics++; break; } case PRODUCT: { int[] operands = readOperands(2); printResult("Product", product(operands)); statistics++; break; } case END: { System.out.println("Calculations done " + statistics); isRunning = false; break; } } } } </code></pre> <p>Main</p> <pre class="lang-java prettyprint-override"><code>public class Main { public static void main(String[] args) { while (Calculator.isRunning()) { try { Calculator.execute(Calculator.getCommand()); System.out.println(); } catch(IllegalCommand e) { System.out.println(e); } } } } </code></pre> <p><code>IllegalCommand</code> , a custom Exception class. Is this an overkill? I just wanted to give it a type, in case it clashes with other Exception types in the future.</p> <pre class="lang-java prettyprint-override"><code>public class IllegalCommand extends Exception { public IllegalCommand(String s) { super(s); } } </code></pre> <p>Expected output</p> <pre><code>command: sum value1: 4 value2: 6 Sum of the values 10 command: product luku1: 3 luku2: 2 Product of the values 6 command: integral IllegalCommand: Command integral not found command: difference value1: 3 value2: 2 Difference of the values 1 command: end Calculations done 3 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T09:33:45.983", "Id": "435429", "Score": "1", "body": "Links can rot. [Please include a description of the challenge here in your question.](//codereview.meta.stackexchange.com/q/1993)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T11:00:18.343", "Id": "435431", "Score": "0", "body": "@Matt Even if I'm not strictly following the assignment? If so, shall I remove the link? Should I add a question summary?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T11:38:37.433", "Id": "435435", "Score": "1", "body": "A link is fine for bonus context, but should be accompanied by a description of sorts. If your interpretation of the assignment differs from the original, either post a modified description or the original *with* a note of what you've done differently." } ]
[ { "body": "<pre><code>new Scanner(System.in).nextLine()\n</code></pre>\n\n<p>This is wasteful. Creating a new scanner object every time that you read a line is very bad for performance. Not to mention that you never close it.</p>\n\n<p>Why does your <code>Calculator</code> get commands and read STDIN? Your calculator class should do one thing: calculate. It is after all, a calculator.</p>\n\n<p>Maybe make a <code>UserInputHandler</code> class if you want to take the input handling out of the main class.</p>\n\n<pre><code>public class UserInputHandler implements AutoCloseable {\n\n private Scanner scanner;\n private Boolean isRunning = false;\n\n class Commands {\n public static final String SUM = \"sum\";\n public static final String DIFFERENCE = \"difference\";\n public static final String PRODUCT = \"product\";\n public static final String END = \"end\";\n }\n\n public UserInputHandler() {\n this(new Scanner(System.in));\n }\n\n public UserInputHandler(Scanner scanner) {\n this.scanner = scanner;\n }\n\n public boolean isRunning() { return isRunning; }\n\n public void startBlocking() {\n isRunning = true;\n startHandlingInput();\n }\n\n public void stop() {\n isRunning = false;\n }\n\n private void startHandlingInput() {\n while (isRunning) {\n System.out.print(\"Command: \");\n if (scanner.hasNext()) handleCommand(scanner.nextLine());\n }\n }\n\n private void handleCommand(String input) {\n switch(input) {\n case Commands.SUM:\n System.out.printf(\"Result: %s\\n\",\n Calculator.sum(readOperands(2)));\n break;\n case Commands.DIFFERENCE:\n System.out.printf(\"Result: %s\\n\",\n Calculator.subtract(readOperands(2)));\n break;\n case Commands.PRODUCT:\n System.out.printf(\"Result: %s\\n\",\n Calculator.product(readOperands(2)));\n break;\n case Commands.END:\n stop();\n break;\n default:\n System.out.println(\"Unknown command!\");\n }\n }\n\n private int[] readOperands(int noOfOperands) {\n int[] array = new int[noOfOperands];\n for (int i = 0; i &lt; noOfOperands; i++) {\n System.out.printf(\"value %d: \", i+1);\n String nextLine = scanner.nextLine();\n\n try {\n int nextInt = Integer.parseInt(nextLine);\n array[i] = nextInt;\n } catch (NumberFormatException e) {\n System.out.println(\"Invalid number, please enter again.\");\n i--;\n }\n }\n return array;\n }\n\n @Override\n public void close() throws IOException {\n scanner.close();\n }\n\n}\n</code></pre>\n\n<p>Don't use <code>Enum#valueOf</code> using exceptions in control flow is a terrible idea.</p>\n\n<p>Your <code>Calculator</code> can be simple. Also, why use streams for some things and not others? </p>\n\n<pre><code>public class Calculator {\n private static int statistics = 0;\n\n public static int subtract(int... a) {\n statistics++;\n return a[0] - IntStream.of(a)\n .skip(1)\n .sum();\n }\n\n public static int sum(int... a) {\n statistics++;\n return IntStream.of(a).sum();\n }\n\n public static int product(int... a) {\n statistics++;\n return IntStream.of(a)\n .reduce((x, y) -&gt; x * y)\n .orElseThrow(RuntimeException::new);\n }\n}\n</code></pre>\n\n<p>Now just run your app:</p>\n\n<pre><code>public class Main {\n public static void main(String[] args) {\n try (UserInputHandler handler = new UserInputHandler()) {\n handler.startBlocking();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n\n<p>Simple!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T05:58:49.037", "Id": "436068", "Score": "0", "body": "What exactly might throw an IOException?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T00:24:57.990", "Id": "436262", "Score": "1", "body": "@GraceMathew my bad, you are right, this IOException catch is unnecessary and can be removed. I am used to catching on Scanner#close but that's unnecessary with the new try w/ resources :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T00:37:52.687", "Id": "224773", "ParentId": "224467", "Score": "4" } } ]
{ "AcceptedAnswerId": "224773", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T09:14:07.077", "Id": "224467", "Score": "8", "Tags": [ "java", "beginner", "object-oriented", "calculator" ], "Title": "Object-oriented calculator" }
224467
<p>I need to read a remote file using FTP and process it and insert the processed data to a PostgreSQL database in another server.</p> <p>The below code is working fine, <em>but i want some advice to modify few things</em>.</p> <ol> <li><p>In this line i don't want to write the actual details, I want that to be hidden from my script. How can i do that?</p> <blockquote> <pre><code>ftp = FTP('server.com','user_name','password') </code></pre> </blockquote></li> <li><p>The script downloads the file to my local system and process it as it is a local file. Is there any way to read and process it without downloading it to the source server (there might be permission issues also)?</p></li> <li>If there is no way rather than downloading it to the source, should I specify a path where this file would be downloaded rather than the way I have written it?</li> <li>Is there anything which i can do to improve this code?</li> </ol> <p>Any guidance will be of great help.</p> <pre><code>import psycopg2 import time import os #import MySQLdb #import paramiko from ftplib import FTP #from utils.config import Configuration as Config #from utils.utils import get_global_config start_time = time.perf_counter() cnx_psql = psycopg2.connect(host="localhost", database="postgres", user="postgres", password="postgres", port="5432") # Cursors initializations cur_psql = cnx_psql.cursor() def getFile(ftp, filename): try: local_filename = os.path.join(r"/Users/linu/Downloads/", filename) lf = open(local_filename, "wb") ftp.retrbinary("RETR " + filename ,lf.write) print("file copied") except: print ("Error") try: filePath='''/Users/linu/Downloads/log''' #filePath='''/cmd/log/stk/log.txt''' table='staging.stock_dump' SQL="""DROP TABLE IF EXISTS """+ table + """;CREATE TABLE IF NOT EXISTS """+ table + """ (created_date TEXT, product_sku TEXT, previous_stock TEXT, current_stock TEXT );""" cur_psql.execute(SQL) cnx_psql.commit() ftp = FTP('server.com','user_name','password') print("FTP connection succesful") data = [] ftp.cwd('/stockitem/') getFile(ftp,'log') read_file = open(filePath, "r") my_file_data = read_file.readlines() for line in my_file_data: if 'Stock:' in line: fields=line.split(" ") date_part1=fields[0] date_part2=fields[1][:-1] sku=fields[3] prev_stock=fields[5] current_stock=fields[7] if prev_stock.strip()==current_stock.strip(): continue else: cur_psql.execute("insert into " + table+"(created_date, product_sku, previous_stock , current_stock)" + " select CAST('" + date_part1+ " "+ date_part2 + "' AS TEXT)" +", CAST('"+sku+"' AS TEXT),CAST('" + prev_stock +"' AS TEXT),CAST('" +current_stock + "' AS TEXT);") cnx_psql.commit() cur_psql.close() cnx_psql.close() print("Data loaded to DWH from text file") print("Data porting took %s seconds to finish---" % (time.perf_counter() - start_time)) except (Exception, psycopg2.Error) as error: print ("Error while fetching data from PostgreSQL", error) print("Error adding information.") quit() finally: ftp.close() </code></pre>
[]
[ { "body": "<blockquote>\n <ol>\n <li>In this line i don't want to write the actual details,i want that to be hidden from my script.How can i do that? ftp = FTP('server.com','user_name','password')</li>\n </ol>\n</blockquote>\n\n<p>You may want to declare constants, either at the beginning of your file or in a <code>Credentials</code> class that would be used as an enum:</p>\n\n<pre><code>SERVER = 'server.com'\nUSER_NAME = 'Linu'\nPASSWORD = 'CR.SEisGreat'\n\nftp = FTP(SERVER, USER_NAME, PASSWORD)\n</code></pre>\n\n<p>You may also want to encrypt your password, with <code>base64</code> or something alike. Storing passwords in files isn't a good idea anyway, so if you're using this file as a script you're going to call via bash or something alike, I would use a <a href=\"https://docs.python.org/3.3/library/argparse.html\" rel=\"nofollow noreferrer\">placeholder</a> like <code>argparse</code> that would prompt your password when calling the script: </p>\n\n<pre><code>parser = argparse.ArgumentParser(description='Reading a file from a distant FTP server.')\nparser.add_argument('--passwd', dest='password', type=str,\n help='password required for FTP connection')\n</code></pre>\n\n<blockquote>\n <ol start=\"2\">\n <li>The script downloads the file to my local system and process it as it\n is a local file, Is there anyway too read and process it without\n downloading it to the source server(there might be permission issues\n also)?</li>\n </ol>\n</blockquote>\n\n<p>I don't know much about FTP manipulation with Python so I'm not sure there is a way to read a file without having to download it.</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>If there is no way rather than downloading it to the source, shall I\n able to mention specific path where this file would be downloaded\n rather than the way i have written?</li>\n </ol>\n</blockquote>\n\n<p>Again, you may place the path into a class constant (or in a separate class):</p>\n\n<pre><code>FILE_PATH='''/path/to/file/''' \n</code></pre>\n\n<blockquote>\n <ol start=\"4\">\n <li>Is there anything which i can do to improve this code?</li>\n </ol>\n</blockquote>\n\n<h2>Imports</h2>\n\n<pre><code>import psycopg2\nimport time\nimport os\n</code></pre>\n\n<p>I would edit this to import only the parts you need, e.g. </p>\n\n<pre><code>from psycopg2 import connect, sql \nfrom time import perf_counter\n</code></pre>\n\n<p>There is no need to import the whole module if you only use a couple of functions, so whenever you can, I'd suggest you only import what you will actually use. </p>\n\n<hr>\n\n<h2>Raising exceptions</h2>\n\n<pre><code>try:\n # ...\nexcept:\n print (\"Error\")\n</code></pre>\n\n<p>I would raise an exception here, since it's a undesired behaviour:</p>\n\n<pre><code> try:\n # ...\nexcept Exception as e:\n print (\"Error: {}\".format(e))\n</code></pre>\n\n<p>You may want to do the same with your psycopg and FTP errors, I see you catch them but don't read their value. It may provide a more helpful message than the prints, which just indicate you encountered an error but don't tell more about what actually happened.</p>\n\n<h2>SQL placeholders</h2>\n\n<pre><code>SQL=\"\"\"DROP TABLE IF EXISTS \"\"\"+ table + \"\"\";CREATE TABLE IF NOT EXISTS \"\"\"+ table + \"\"\"\n(created_date TEXT, product_sku TEXT, previous_stock TEXT, current_stock TEXT );\"\"\"\n</code></pre>\n\n<p>Should you want to make your code more generic, you could transform the above mentioned statement into:</p>\n\n<pre><code>sql.SQL=\"\"\"DROP TABLE IF EXISTS {table_name} ; CREATE TABLE IF NOT EXISTS {table_name}\n (created_date TEXT, product_sku TEXT, previous_stock TEXT, \n current_stock TEXT );\"\"\".format(\n table_name = sql.Literal(table)\n)\n</code></pre>\n\n<p>That way you may reuse the query on other tables. You may do the same on the table attributes, i.e. </p>\n\n<pre><code>keys = ['created_date', 'product_sku', 'previous_stock', 'current_stock']\nsql.SQL(\"\"\"CREATE TABLE IF NOT EXISTS {} ({});\"\"\").format(\n sql.Identifier(table),\n sql.SQL('{} TEXT,').join(map(sql.Identifier, keys))\n)\n</code></pre>\n\n<p>It alleviates the query and makes it more generic and reusable. By the way, I don't think you need to add <code>IF NOT EXISTS</code> after <code>CREATE</code> since you already deleted the table in the first part of your query.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T18:38:11.910", "Id": "435466", "Score": "0", "body": "I think this answer has a lot of great suggestions but I don't believe that giving the password as part of a bash command is an improvement over storing the password in the file, because now the password will end up in `~/.bash_history` and can be discovered by anyone who has momentary access to your computer. I don't think secret storage is a perfectly solved problem but it may be safer just staying in the script." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T20:13:30.667", "Id": "435471", "Score": "1", "body": "base64 is not encryption, it is encoding. Converting a password to base64 does not offer any security benefits." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:04:24.463", "Id": "224474", "ParentId": "224470", "Score": "2" } }, { "body": "<p>I will not repeat what has been already said in the <a href=\"https://codereview.stackexchange.com/a/224474/98493\">other, excellent, answer</a> by <a href=\"https://codereview.stackexchange.com/users/164931/avazula\">@avazula</a>.</p>\n\n<p>You open a few files, but never close them. This might lead to bad things. Instead just use the <a href=\"https://effbot.org/zone/python-with-statement.htm\" rel=\"nofollow noreferrer\"><code>with</code></a> keyword, which takes care of closing the file, even if an exception occurs. In addition, you can just iterate over a file and it will iterate over the lines. No need for <code>readlines</code>, which reads the whole file into memory (which might not be possible).</p>\n\n<pre><code>with open(filePath) as read_file:\n for line in read_file:\n ...\n</code></pre>\n\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which programmers are encouraged to follow. It recommend using <code>lower_case</code> for variables and functions, not <code>camelCase</code>.</p>\n\n<p>An important thing to think about any time you use SQL are <a href=\"https://www.w3schools.com/sql/sql_injection.asp\" rel=\"nofollow noreferrer\">SQL injections</a>. If there is any chance at all that a user can manipulate the content of the variables, they might be able to execute a malicious query if you are not careful. </p>\n\n<p>The <a href=\"http://initd.org/psycopg/docs/usage.html\" rel=\"nofollow noreferrer\"><code>psycopg2</code> documentation</a> even has this not so subtle warning:</p>\n\n<blockquote>\n <p><strong>Warning:</strong> Never, <strong>never</strong>, <strong>NEVER</strong> use Python string concatenation (<code>+</code>) or string\n parameters interpolation (<code>%</code>) to pass variables to a SQL query string.\n Not even at gunpoint.</p>\n</blockquote>\n\n<p>To alleviate this, you can use the second argument of <code>execute</code>, as mentioned in the documentation:</p>\n\n<pre><code>cur_psql.execute(f\"INSERT INTO {table}\"\n \" (created_date, product_sku, previous_stock , current_stock)\"\n \" VALUES (%s, %s, %s, %s)\",\n (date_part1+ \" \"+ date_part2, sku, prev_stock, current_stock))\n</code></pre>\n\n<p>Here I have used an <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> (Python 3.6+) to insert the table name (unescaped in this case). You can properly escape it using <code>sql.Identifier(table)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T12:32:02.620", "Id": "224476", "ParentId": "224470", "Score": "2" } } ]
{ "AcceptedAnswerId": "224476", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T09:55:11.460", "Id": "224470", "Score": "3", "Tags": [ "python", "python-3.x", "postgresql", "ftp" ], "Title": "Importing data into PostgreSQL from remote text file using ftplib class" }
224470
<h1>Double Pendulum</h1> <p>I made a little application that embeds a <code>matplotlib</code> dynamic plot into <code>tkinter</code> that enables control through the <code>tkinter</code> GUI. Code is in <a href="https://github.com/bvermeulen/Double-Pendulum" rel="nofollow noreferrer">Github</a>. It also uses <code>numpy</code> and <code>scipy</code> to solve the ordinary differential equations for a double pendulum.</p> <p>To change the initial theta's just drag the bobs to another position...</p> <p><a href="https://i.stack.imgur.com/ZRR8W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZRR8W.png" alt="screen plot"></a></p> <p>Would appreciate review for comments and improvements and I have one question: why does <code>highlightthickness</code> work for the <code>canvas_pendulum</code> (line 54)</p> <pre><code>cls.canvas_pendulum.get_tk_widget().configure(highlightthickness=1) </code></pre> <p>but not for canvas_graphs (line 72) ?</p> <pre><code>cls.canvas_graphs.get_tk_widget().configure(highlightthickness=1, bg='yellow') </code></pre> <h1>Code</h1> <p>Add the following packages to your environment</p> <pre><code>pip install numpy matplotlib scipy </code></pre> <pre><code>import sys import tkinter as tk import time import numpy as np import matplotlib.pyplot as plt from matplotlib import patches as mpl_patches from matplotlib import lines as mpl_lines from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from scipy.integrate import ode TWOPI = 2*np.pi PI = np.pi FIG_SIZE_PENDULUM = (5, 5) X_MIN, X_MAX = -10, 10 Y_MIN, Y_MAX = -10, 10 TICK_INTERVAL = 1.5 FIG_SIZE_GRAPHS = (5, 1) update_label_interval_ms = 150 fps = 24 seconds_per_frame = 1 / fps time_window_graphs = 20 update_graph_interval_s = 0.25 class MplMap(): ''' set up map consisting of two figures: fig_pendulum and fig_graphs fig_pendulum: has one ax showing the pendulum movements fig_graphs: has two ax showing plots of theta1 and theta2 ''' @classmethod def settings(cls, root, fig_size_pendulum, fig_size_graphs): # set the plot outline, including axes going through the origin cls.root = root cls.fig_pendulum, cls.ax_pendulum = plt.subplots(figsize=fig_size_pendulum) cls.ax_pendulum.set_xlim(X_MIN, X_MAX) cls.ax_pendulum.set_ylim(Y_MIN, Y_MAX) cls.ax_pendulum.set_aspect(1) tick_range = np.arange( round(X_MIN + (10*abs(X_MIN) % TICK_INTERVAL*10)/10, 1), X_MAX + 0.1, step=TICK_INTERVAL) cls.ax_pendulum.set_xticks(tick_range) cls.ax_pendulum.set_yticks([]) cls.ax_pendulum.tick_params(axis='x', which='major', labelsize=6) cls.ax_pendulum.spines['left'].set_color('none') cls.ax_pendulum.spines['right'].set_color('none') cls.ax_pendulum.spines['bottom'].set_position('zero') cls.ax_pendulum.spines['top'].set_color('none') cls.fig_pendulum.tight_layout() cls.canvas_pendulum = FigureCanvasTkAgg(cls.fig_pendulum, master=cls.root) cls.canvas_pendulum.get_tk_widget().configure(highlightthickness=1) cls.fig_graphs, (cls.ax_graph_1, cls.ax_graph_2) = plt.subplots( 1, 2, figsize=fig_size_graphs) cls.ax_graph_1.set_ylim(-180, 180) cls.ax_graph_1.set_yticks([-180, -90, 0, 90, 180]) cls.ax_graph_1.tick_params(axis='y', which='major', labelsize=6) cls.ax_graph_1.tick_params(axis='x', which='major', labelsize=6) cls.ax_graph_1.grid(True) cls.ax_graph_2.set_ylim(-190, 190) cls.ax_graph_2.set_yticks([-180, -90, 0, 90, 180]) cls.ax_graph_2.tick_params(axis='y', which='major', labelsize=6) cls.ax_graph_2.tick_params(axis='x', which='major', labelsize=6) cls.ax_graph_2.grid(True) cls.fig_graphs.tight_layout() cls.canvas_graphs = FigureCanvasTkAgg(cls.fig_graphs, master=cls.root) cls.canvas_graphs.get_tk_widget().configure(highlightthickness=1, bg='yellow') @classmethod def get_cnvs_pendulum(cls): return cls.canvas_pendulum @classmethod def get_cnvs_graphs(cls): return cls.canvas_graphs class DoublePendulum(MplMap): ''' class defining methods for Pendulum for positions and motions of a double pendulum ''' def __init__(self, _a1, _a2): # Physical constants and initial settings self.g = 9.8 self.damping1 = 0.0 # damping factor bob1 self.damping2 = 0.0 # dampling factor bob2 self.length_r1 = 5.0 self.length_r2 = 2.5 self.mass_bob1 = 5.0 self.mass_bob2 = 2.5 self.color_bob1 = 'green' self.color_bob2 = 'red' self.plotsize = 1.10 * (self.length_r1 + self.length_r2) # initial state if _a1 and _a2: self.theta1_initial = np.radians(_a1) self.theta2_initial = np.radians(_a2) else: self.theta1_initial = + 120 / 180 * np.pi self.theta2_initial = + 180 / 180 * np.pi self.theta1_dot_initial = 0 self.theta2_dot_initial = 0 self.theta1 = self.theta1_initial self.theta2 = self.theta2_initial self._time = 0 _x1, _y1 = self.calc_xy(self.length_r1, self.theta1_initial) self.bob1 = mpl_patches.Circle((_x1, _y1), 0.2 + self.m1 * 0.02, fc=self.color_bob1, alpha=1, zorder=2) self.bob1.set_picker(0) self.ax_pendulum.add_patch(self.bob1) self.stick1 = mpl_lines.Line2D([0, _x1], [0, _y1], zorder=2) self.ax_pendulum.add_line(self.stick1) cv_bob1 = self.bob1.figure.canvas cv_bob1.mpl_connect('pick_event', self.on_pick) cv_bob1.mpl_connect('motion_notify_event', self.on_motion) cv_bob1.mpl_connect('button_release_event', self.on_release) _x2, _y2 = self.calc_xy(self.length_r2, self.theta2_initial) _x2 += _x1 _y2 += _y1 self.bob2 = mpl_patches.Circle((_x2, _y2), 0.2 + self.m2 * 0.02, fc=self.color_bob2, alpha=1, zorder=2) self.bob2.set_picker(0) self.ax_pendulum.add_patch(self.bob2) self.stick2 = mpl_lines.Line2D([_x1, _x2], [_y1, _y2], zorder=2) self.ax_pendulum.add_line(self.stick2) cv_bob2 = self.bob2.figure.canvas cv_bob2.mpl_connect('pick_event', self.on_pick) cv_bob2.mpl_connect('motion_notify_event', self.on_motion) cv_bob2.mpl_connect('button_release_event', self.on_release) self.x_traces = [] self.y_traces = [] self.trace_line, = self.ax_pendulum.plot( [0], [0], color='black', linewidth=0.2, zorder=1) self.current_object = None self.current_dragging = False self.break_the_loop = False self.theta_graphs = ThetaGraphs() self.blip() def switch_colors_of_bob(self): print('switch color') self.color_bob1, self.color_bob2 = self.color_bob2, self.color_bob1 self.bob1.set_color(self.color_bob1) self.bob2.set_color(self.color_bob2) self.blip() def toggle_trace_visible(self): print(self.trace_line.get_visible()) if self.trace_line.get_visible(): self.trace_line.set_visible(False) else: self.trace_line.set_visible(True) self.blip() def clear_trace(self): self.x_traces = [] self.y_traces = [] self.trace_line.set_data([0], [0]) self.blip() @property def gravity(self): return self.g @gravity.setter def gravity(self, value): self.g = value @property def m1(self): return self.mass_bob1 @m1.setter def m1(self, value): self.mass_bob1 = value self.bob1.set_radius(0.2 + self.mass_bob1 * 0.02) self.blip() @property def m2(self): return self.mass_bob2 @m2.setter def m2(self, value): self.mass_bob2 = value self.bob2.set_radius(0.2 + self.mass_bob2 * 0.02) self.blip() @property def l1(self): return self.length_r1 @l1.setter def l1(self, value): self.length_r1 = value self.calc_positions() self.blip() @property def l2(self): return self.length_r2 @l2.setter def l2(self, value): self.length_r2 = value self.calc_positions() self.blip() @property def k1(self): return self.damping1 @k1.setter def k1(self, value): self.damping1 = value @property def k2(self): return self.damping2 @k2.setter def k2(self, value): self.damping2 = value @property def angle1_initial(self): angle = self.theta1_initial return np.degrees(-PI + (angle - PI) % TWOPI) @property def angle2_initial(self): angle = self.theta2_initial return np.degrees(-PI + (angle - PI) % TWOPI) @property def angle1(self): angle = self.theta1 return np.degrees(-PI + (angle - PI) % TWOPI) @property def angle2(self): angle = self.theta2 return np.degrees(-PI + (angle - PI) % TWOPI) @property def time(self): return self._time def on_pick(self, event): if event.artist != self.bob1 and \ event.artist != self.bob2: return self.current_dragging = True self.current_object = event.artist def on_motion(self, event): if not self.current_dragging: return if self.current_object == self.bob1: self.theta1 = self.calc_theta(event.xdata, event.ydata, self.theta1) self.theta1_initial = self.theta1 elif self.current_object == self.bob2: _x1, _y1 = self.bob1.center self.theta2 = self.calc_theta( event.xdata - _x1, event.ydata - _y1, self.theta2) self.theta2_initial = self.theta2 else: return self.calc_positions() self.blip() def on_release(self, _): self.current_object = None self.current_dragging = False def start_swing(self): self.break_the_loop = False self.theta1_initial = self.theta1 self.theta2_initial = self.theta2 self.y_traces = [] self.x_traces = [] self.plot_double_pendulum() def stop_swing(self): self.break_the_loop = True def calc_positions(self): _x1, _y1 = self.calc_xy(self.l1, self.theta1) self.bob1.center = (_x1, _y1) self.stick1.set_data([0, _x1], [0, _y1]) _x2, _y2 = self.calc_xy(self.l2, self.theta2) _y2 += _y1 _x2 += _x1 self.bob2.center = (_x2, _y2) self.stick2.set_data([_x1, _x2], [_y1, _y2]) def add_to_trace(self): _x2, _y2 = self.bob2.center self.x_traces.append(_x2) self.y_traces.append(_y2) self.trace_line.set_data(self.x_traces[:], self.y_traces[:]) @staticmethod def calc_theta(x, y, theta): try: return np.arctan2(x, -y) except TypeError: return theta @staticmethod def calc_xy(length, theta): x = length * np.sin(theta) y = - length * np.cos(theta) return x, y def blip(self): self.fig_pendulum.canvas.draw() self.fig_pendulum.canvas.flush_events() def get_derivatives_double_pendulum(self, t, state): ''' definition of ordinary differential equation for a double pendulum. See for derivations at https://ir.canterbury.ac.nz/bitstream/handle/10092/12659/chen_2008_report.pdf ''' t1, w1, t2, w2 = state dt = t1 - t2 _sin_dt = np.sin(dt) _den1 = (self.m1 + self.m2 * _sin_dt * _sin_dt) _num1 = self.m2 * self.l1 * w1 * w1 * np.sin(2*dt) _num2 = 2 * self.m2 * self.l2 * w2 * w2 * _sin_dt _num3 = 2 * self.g * self.m2 * np.cos(t2) * _sin_dt + \ 2 * self.g * self.m1 * np.sin(t1) _num4 = 2 * (self.k1 * w1 - self.k2 * w2 * np.cos(dt)) w1_dot = (_num1 + _num2 + _num3 + _num4)/ (-2 * self.l1 * _den1) _num1 = self.m2 * self.l2 * w2 * w2 * np.sin(2*dt) _num2 = 2 * (self.m1 + self.m2) * self.l1 * w1 * w1 * _sin_dt _num3 = 2 * self.g * (self.m1 + self.m2) * np.cos(t1) * _sin_dt _num4 = 2 * (self.k1 * w1 * np.cos(dt) - \ self.k2 * w2 * (self.m1 + self.m2)/ self.m2) w2_dot = (_num1 + _num2 + _num3 + _num4)/ (2 * self.l2 *_den1) state_differentiated = np.zeros(4) state_differentiated[0] = w1 state_differentiated[1] = w1_dot state_differentiated[2] = w2 state_differentiated[3] = w2_dot return state_differentiated def plot_double_pendulum(self): ''' methods to plot pendulum in matplotlib ''' # note a frame per second (fps) &gt; 24 the actual time # may not be able to keep up with model time def current_time(): return time.time() def check_drift(_time, running_time): # check every 5 seconds if _time % 5 &lt; seconds_per_frame: print(f'time (ms): {1000*_time:,.0f}, ' f'drift: {1000*(running_time - _time):,.0f}') self._time = 0 dp_integrator = ode(self.get_derivatives_double_pendulum).set_integrator('vode') state = np.array([self.theta1, self.theta1_dot_initial, self.theta2, self.theta2_dot_initial]) dp_integrator.set_initial_value(state, self._time) self.add_to_trace() actual_start_time = current_time() while dp_integrator.successful() and not self.break_the_loop: self.theta1, _, self.theta2, _ = state self.calc_positions() self.add_to_trace() if self._time % update_graph_interval_s &lt; seconds_per_frame: self.theta_graphs.plot_thetas(self._time, self.theta1, self.theta2) running_time = current_time() - actual_start_time check_drift(self._time, running_time) while running_time &lt; self._time: running_time = current_time() - actual_start_time else: self.blip() state = dp_integrator.integrate(dp_integrator.t + seconds_per_frame) self._time += seconds_per_frame class ThetaGraphs(MplMap): ''' Method to display the theta1 and theta2 graphs ''' def __init__(self): self.time_window = time_window_graphs self.time_base = 0 self.time_values = [] self.angle1_values = [] self.angle2_values = [] self.theta1_graph, = self.ax_graph_1.plot( [0], [0], color='black', linewidth=0.5, zorder=2) self.theta2_graph, = self.ax_graph_2.plot( [0], [0], color='black', linewidth=0.5, zorder=2) self.ax_graph_1.set_xlim( self.time_base, self.time_base + self.time_window) self.ax_graph_2.set_xlim( self.time_base, self.time_base + self.time_window) def plot_thetas(self, _time, theta1, theta2): if _time % self.time_window &lt; seconds_per_frame: # reset when time is zero if _time &lt; seconds_per_frame: self.time_base = -self.time_window self.angle1_values = [] self.angle2_values = [] self.time_values = [] self.time_base += self.time_window self.ax_graph_1.set_xlim( self.time_base, self.time_base + self.time_window) self.ax_graph_2.set_xlim( self.time_base, self.time_base + self.time_window) self.time_values.append(_time) self.angle1_values.append(np.degrees(-PI + (theta1 - PI) % TWOPI)) self.theta1_graph.set_data(self.time_values, self.angle1_values) self.angle2_values.append(np.degrees(-PI + (theta2 - PI) % TWOPI)) self.theta2_graph.set_data(self.time_values, self.angle2_values) self.fig_graphs.canvas.draw() self.fig_graphs.canvas.flush_events() class TkHandler(): ''' Methods to handle the tkinter GUI and links with matplotlib canvases and pendulum class. Methods: __init__: parameters: :root: tk root :cnvs_pendulum: maplotlib canvas showing the movement of the pendulum :cnvs_graphs: matplotlib canvas showing the graphs of theta1 and theta2 :doublependulum: class handling the doublependulum status and positions create_slider_status_frame: Creates frame of the sliders and status values of initial theta1, initial theta2, time, theta1, theta2 The slider values are connected to the pendulum class by the _set_value function that sets values for: gravity, mass1, mass2, length1, length2, damping1, damping2 update_labels: Updates the status values. Update rate is set by: update_label_interval_ms create_button_frame: Creates frame with control buttons and links with button functions: _quit: quits the program The following button functions connect to the pendulum class to change status: _set_colors: swaps colors of the bobs _toggle_trace_visible: toggles trace on or off _clear_trace: clears the trace _start: starts the pendulum swing _stop: stops the pendulum swing create_grid: Creates the GUI grid ''' def __init__(self, root, cnvs_pendulum, cnvs_graphs, doublependulum): self.root = root self.cnvs_pendulum = cnvs_pendulum self.cnvs_graphs = cnvs_graphs self.pendulum = doublependulum self.root.wm_title("Double Pendulum") self.create_slider_status_frame() self.create_button_frame() self.create_grid() self.update_labels() tk.mainloop() def create_slider_status_frame(self): self.sliders_status_frame = tk.Frame(self.root) sliders_frame = tk.Frame(self.sliders_status_frame) sliders = {'gravity': {'label':'Gravity ', 'settings': [0, 30, 1]}, # 'settings': [min, max, resolution] # pylint: disable=C0301 'm1': {'label':'Mass bob 1', 'settings': [1, 10, 0.1]}, 'm2': {'label':'Mass bob 2', 'settings': [1, 10, 0.1]}, 'l1': {'label':'Length r1 ', 'settings': [0.1, 10, 0.1]}, 'l2': {'label':'Length r2 ', 'settings': [0.1, 10, 0.1]}, 'k1': {'label':'Damping 1 ', 'settings': [0, 1, 0.1]}, 'k2': {'label':'Damping 2 ', 'settings': [0, 1, 0.1]}, } def create_slider(slider_key, slider_params): _min, _max, _resolution = slider_params['settings'] slider_frame = tk.Frame(sliders_frame) label_slider = tk.Label(slider_frame, font=("TkFixedFont"), text=f'\n{slider_params["label"]:&lt;11s}') slider = tk.Scale(slider_frame, from_=_min, to=_max, resolution=_resolution, orient=tk.HORIZONTAL, sliderlength=15, length=150, command=lambda value: self._set_value(value, slider_key)) slider.set(getattr(self.pendulum, slider_key)) label_slider.pack(side=tk.LEFT) slider.pack(side=tk.LEFT) slider_frame.pack() for key, slider_params in sliders.items(): create_slider(key, slider_params) status_frame = tk.Frame(self.sliders_status_frame) self.label_status1 = tk.Label(status_frame, font=("TkFixedFont"),) self.label_status1.pack(anchor=tk.W) self.label_status2 = tk.Label(status_frame, font=("TkFixedFont"),) self.label_status2.pack(anchor=tk.W) self.label_status3 = tk.Label(status_frame, font=("TkFixedFont"),) self.label_status3.pack(anchor=tk.W) self.label_status4 = tk.Label(status_frame, font=("TkFixedFont"),) self.label_status4.pack(anchor=tk.W) self.label_status5 = tk.Label(status_frame, font=("TkFixedFont"),) self.label_status5.pack(anchor=tk.W) sliders_frame.pack(anchor=tk.NW) status_frame.pack(anchor=tk.W) def update_labels(self): self.label_status1.config( text=f'\ntheta1 initial: {self.pendulum.angle1_initial:+3.2f}') self.label_status2.config( text=f'theta2 initial: {self.pendulum.angle2_initial:+3.2f}') self.label_status3.config( text=f'time: {self.pendulum.time:+3.1f}') self.label_status4.config( text=f'theta1: {self.pendulum.angle1:+3.0f}') self.label_status5.config( text=f'theta2: {self.pendulum.angle2:+3.0f}') self.root.after(update_label_interval_ms, self.update_labels) def create_button_frame(self): self.buttons_frame = tk.Frame(self.root) tk.Button( self.buttons_frame, text='Quit', command=self._quit).pack(side=tk.LEFT) tk.Button( self.buttons_frame, text='Switch colors', command=lambda *args: self._set_colors(*args)).pack(side=tk.LEFT) tk.Button( self.buttons_frame, text='Trace on/ off', command=lambda *args: self._toggle_trace_visible(*args)).pack(side=tk.LEFT) tk.Button( self.buttons_frame, text='Clear trace', command=lambda *args: self._clear_trace(*args)).pack(side=tk.LEFT) tk.Button( self.buttons_frame, text='Start', command=self._start).pack(side=tk.LEFT) tk.Button( self.buttons_frame, text='Stop', command=self._stop).pack(side=tk.LEFT) def create_grid(self): tk.Grid.rowconfigure(self.root, 0, weight=1) tk.Grid.columnconfigure(self.root, 0, weight=1) self.sliders_status_frame.grid( row=0, column=0, sticky=tk.NW) self.cnvs_pendulum.get_tk_widget().grid( row=0, column=1, rowspan=1, columnspan=1, sticky=tk.W+tk.E+tk.N+tk.S) self.cnvs_graphs.get_tk_widget().grid( row=1, column=0, rowspan=1, columnspan=2, sticky=tk.W+tk.E+tk.N+tk.S) self.buttons_frame.grid( row=2, column=0, columnspan=2, sticky=tk.W) def _quit(self): self.pendulum.stop_swing() self.root.after(100, self.root.quit) self.root.after(100, self.root.destroy) def _set_colors(self): self.pendulum.switch_colors_of_bob() def _toggle_trace_visible(self): self.pendulum.toggle_trace_visible() def _clear_trace(self): self.pendulum.clear_trace() def _set_value(self, value, name): value = float(value) print(name, value) if name == 'gravity': self.pendulum.gravity = float(value) elif name == 'm1': self.pendulum.m1 = float(value) elif name == 'm2': self.pendulum.m2 = float(value) elif name == 'l1': self.pendulum.l1 = float(value) elif name == 'l2': self.pendulum.l2 = float(value) elif name == 'k1': self.pendulum.k1 = float(value) elif name == 'k2': self.pendulum.k2 = float(value) else: assert False, f'wrong key value given: {name}' def _start(self): self.pendulum.start_swing() def _stop(self): self.pendulum.stop_swing() def main(_a1, _a2): root = tk.Tk() MplMap.settings(root, FIG_SIZE_PENDULUM, FIG_SIZE_GRAPHS) TkHandler(root, MplMap.get_cnvs_pendulum(), MplMap.get_cnvs_graphs(), DoublePendulum(_a1, _a2)) if __name__ == "__main__": main_arguments = sys.argv angle1 = None angle2 = None if len(main_arguments) == 3: try: angle1 = float(main_arguments[1]) angle2 = float(main_arguments[2]) except ValueError: print('invalid arguments, refer to defaults ..') main(angle1, angle2) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T10:28:08.040", "Id": "224472", "Score": "3", "Tags": [ "python", "tkinter", "matplotlib", "scipy" ], "Title": "Double pendulum real time plot" }
224472
<p>I have ported <a href="https://github.com/apache/lucene-solr/tree/98c85a0e1a611d3a0337483ab87183bfeccec33b/lucene/analysis/stempel/src/java/org" rel="nofollow noreferrer">Stempel stemmer in Java</a> (Apache Lucene) to Python. I come from Java world, so I'm afraid my translation might not be "pythonic" enough. </p> <p>I would like to hear your feedback on quite representative part of the code, translation of <a href="https://github.com/apache/lucene-solr/blob/67104dd615c82de64839de60418110211438f574/lucene/analysis/stempel/src/java/org/egothor/stemmer/Diff.java" rel="nofollow noreferrer"><code>Diff</code></a> class that applies stemming command (<code>diff</code>) to a string (<code>dest</code>).</p> <pre><code> @classmethod def apply(cls, dest, diff): """ Apply the given patch string diff to the given string dest :param dest: Destination string :param diff: Patch string :return: """ if diff is None: return if not isinstance(dest, MutableString): raise ValueError if not dest: return pos = len(dest) - 1 try: for i in range(int(len(diff) / 2)): cmd = diff[2 * i] param = diff[2 * i + 1] par_num = ord(param) - ord('a') + 1 if cmd == '-': pos -= (par_num - 1) elif cmd == 'R': cls.__check_index(dest, pos) dest[pos] = param elif cmd == 'D': o = pos pos -= (par_num - 1) cls.__check_index(dest, pos) dest[pos:o + 1] = '' elif cmd == 'I': pos += 1 cls.__check_offset(dest, pos) dest.insert(pos, param) pos -= 1 except IndexError: # swallow, same thing happens in original Java version pass @classmethod def __check_index(cls, s, index): if index &lt; 0 or index &gt;= len(s): raise IndexError @classmethod def __check_offset(cls, s, offset): if offset &lt; 0 or offset &gt; len(s): raise IndexError </code></pre> <p>Some justifications of decisions I took:</p> <ul> <li><p>The original implementation uses <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html" rel="nofollow noreferrer"><code>StringBuffer</code></a> to manipulate characters in a string. Since Python <code>str</code> type is immutable I used my own class <code>MutableString</code> that behaves like a Python <a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow noreferrer"><code>list</code></a>.</p></li> <li><p>Also, original logic was based on catching <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html" rel="nofollow noreferrer"><code>IndexOutOfBoundsException</code></a>. Contrary to Java, Python allows negative indexes in a list and list ranges. Therefore, I've introduces guards like <code>__check_X</code>. </p></li> <li><p>Java implementation uses switch/case/default clause. I translated that to if/elif/else clause in Python.</p></li> </ul>
[]
[ { "body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>Python <em>will</em> throw an <code>IndexError</code> if you try to access an element past the end of a list, so you don't need to check <code>index &gt;= len(s)</code> or <code>offset &gt; len(s)</code>.</li>\n<li>After the simplification above I would inline the <code>__check</code> methods as assertions.</li>\n<li>Throwing an exception and catching it again <em>within the same context</em> is a code smell - it's too much like <code>goto</code>. Why not just <code>return</code> instead? Or let the user know the input could not be processed?</li>\n<li>You don't actually use any OOP in your code, so <code>apply</code> might as well not be within a class</li>\n<li>In the same way I think you could just use a <code>List[str]</code> for <code>dest</code>.</li>\n<li>Checking the type of an argument is unpythonic. Basically you're responsible for passing some value which <em>can be used</em> by the code. And with type checking (below) you could even enforce this at a test or linting stage.</li>\n<li>Abbreviations make code harder to read. I would expand things like <code>destination</code>, <code>position</code> and <code>command</code>.</li>\n<li>Magic values like <code>R</code> and <code>D</code> should be named constants to improve readability.</li>\n</ol>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place. Conversely, on an ugly old piece of code I wrote without static analysis support I recently found the complexity reaches 87!)</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<p>As a Java developer I'm sure you'd appreciate the clarity this lends to the code.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T10:16:33.930", "Id": "435547", "Score": "0", "body": "Thanks. I've started to introduce type hinting but I've realized in many cases it makes reading the code harder. Right, it helps clarify ambiguous parts but in other parts it's seems overly verbose like in Java. What's your take on using type hinting *selectively*, for documentation purposes *only* when the code is ambiguous?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T10:59:53.057", "Id": "435551", "Score": "1", "body": "Seems sensible if any of the types get complicated. For this algorithm I expect the finished code would make for relatively simple type hints." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T20:51:20.050", "Id": "224504", "ParentId": "224473", "Score": "2" } } ]
{ "AcceptedAnswerId": "224504", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T10:48:02.050", "Id": "224473", "Score": "4", "Tags": [ "python", "strings" ], "Title": "Porting stemming algorithm from Java to Python" }
224473
<p><strong>Short problem description:</strong> </p> <blockquote> <p>A sequence of numbers are antiarithemtic if there exists no three numbers <code>a_i</code>, <code>a_j</code>, <code>a_k</code> – where <code>a_i</code> preceeds <code>a_j</code> which then again preceeds <code>a_k</code> in the sequence – such that <code>a_i - a_j = a_j - a_k</code>. Example: (5, 0, -1, 3, 1) is <strong>not</strong> antiarithemtic, because 5-3 = 3-1, wheras the sequence (1, 5, 3, 0, -1) <strong>is</strong> antiarithemtic.</p> </blockquote> <p>Link to the <a href="https://open.kattis.com/problems/antiarithmetic" rel="nofollow noreferrer">Kattis page</a>.</p> <p>My attempt:</p> <pre><code>import sys lines = sys.stdin.readlines() lines = [x[:-1] for x in lines] for line in lines: if len(line) &gt; 1: line = line.split(':') found = False visited = {} curr = line[1].split() r = len(curr) for i in range(r): visited_2 = {} if curr[i] in visited: continue else: visited[curr[i]] = True for j in range(i+1, r): if curr[j] in visited_2: continue else: visited_2[curr[j]] = True tmp = int(curr[i]) - int(curr[j]) for k in range(j+1, r): if int(curr[j]) - int(curr[k]) == tmp: print("no") found = True break if not found: print("yes") else: break </code></pre> <p>I believe my attempt solves the problem of finding out whether a sequence is antiarithmetic or not, as I've made my own extensive example-set to test that. My optimizing step so far has been to include dictionaries of visited "nodes" so as to not repeat searches for numbers that we already know do not result in an arithmetic sequence. However, it is not fast enough for Kattis, so I would much appreciate any suggestions on how to improve this.</p>
[]
[ { "body": "<p>making your code harder to read:</p>\n\n<ul>\n<li>lack of docstrings</li>\n<li>lack of comments</li>\n<li>unwarranted indentation using an <code>else:</code> after a \"disruptive <code>if</code>\" \n(transferring execution with return, break, continue)<br>\n(Here, you are using this with otherwise empty \"<code>if</code>-parts\":<br>\nyou could negate the conditions and just use the former <code>else:</code>-statements. Hello again, indentation.)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T17:44:52.730", "Id": "435620", "Score": "0", "body": "You are absolutely right. I will clean up the code some time tomorrow when I have some free time. I didn't bother with it at first, thought maybe someone would see something that I've done wrong conceptually either way. But thank you, you are absolutely right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T17:54:19.800", "Id": "435622", "Score": "1", "body": "(I belatedly noticed one more incidence of *avoidable indentation* right in the outer loop: you could use `if len(line) <= 0: break;`) If you are going to change the code more than a trifle/in any aspect mentioned by answers, ask a new question and cross-link unless you delete this one altogether." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T07:40:43.607", "Id": "224538", "ParentId": "224483", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T13:55:53.757", "Id": "224483", "Score": "2", "Tags": [ "python", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "Coding Challenge: Kattis" }
224483
<p>This question is to see if I can get some input on the "design pattern" I tried to implement here. I'm just learning about closure in JavaScript and I think I'm starting to get it. I'm wondering if the way I wrote this code is or is not <em>terrible</em> stylistically. </p> <p>The code in question is attempting to answer a challenge given in the JavaScript: The Hard Parts (by Will Sentance) on Frontend Masters. Based on the challenge, it seems I went above and beyond as the solution provided, when run, doesn't work properly.</p> <p>The challenge: </p> <blockquote> <p>Write a function changeColor that when invoked will first check if the current page background color is "rgb(221, 238, 255)". If it is, it changes the color to "rgb(255, 238, 221)". If it isn't, it sets the color to "rgb(221, 238, 255)".</p> <p>Add a click event listener to button #1 above (it has an id of "activate"). On click, the button should log to the console "clicked 1". It should also set up a click event listener on button #2 (id of "color"). That listener should log to console "clicked 2" and then call the changeColor function you just created.</p> <p>Clear the console and hit the 'Run with JS' button. Look at what code has run by analyzing the console. Then try to change the background color by clicking button #2. What needs to happen for the button to work?</p> </blockquote> <p>Based on the wording of the challenge it seemed like the solution that was hinted at was (in pseudo-ish code):</p> <pre class="lang-js prettyprint-override"><code>// Provided solution to the question above // Assume all necessary HTML is in place activationButton.addEventListener("click", () =&gt; { console.log("clicked activation button") colorChangerButton.addEventListener("click", () =&gt; { console.log("clicked color changer button") changeTheColor() }) }) </code></pre> <p>The obvious problem with the code above is that a new event listener will be added to the colorChangerButton every time you click the activationButton. This was where I started thinking about trying to use a closure to keep track of a state variable so that I could make sure that the event listener only gets added to the second button once. Also, this is the solution provided in the solution set for the challenge.</p> <p>To that end, this is what I came up with (please assume that the correct HTML is there, etc):</p> <pre class="lang-js prettyprint-override"><code>(function () { let clickCount = 0 function changeColor() { if (document.body.style.backgroundColor === "rgb(221, 238, 255)") { document.body.style.backgroundColor = "rgb(255, 238, 221)" } else { document.body.style.backgroundColor = "rgb(221, 238, 255)" } } function activateButton2() { const btn2 = document.querySelector('#color') // Appropriate to grab button here? btn2.addEventListener("click", () =&gt; { console.log("clicked #2") changeColor() }) } const btn1 = document.querySelector('#activate') // Appropriate to have variable declaration here? btn1.addEventListener("click", () =&gt; { clickCount++ if (clickCount === 1) { activateButton2() } console.log("clicked #1") return }) // Initially had an un-necessary return statement here })() </code></pre> <p>The code above - that I wrote - <em>is</em> working how I'd expect it to - the color change functionality and the console logs are firing as I would expect.</p> <p>One question I had about my implementation was about containing the button variables inside the IIFE. I feel like I see a lot of front-end scripts putting all the query selectors at the top of the script - is there a reason to do that vs. including them within a function like this? If I understand closure correctly, once the event handlers are created there is a persistent reference to everything in the IIFE, so I can fire this function and the buttons and their handlers persist and behave as expected.</p> <p>It also seems like I could probably use a boolean to track the "clicked" status of the first button, and a switch statement for checking the background color of the page.</p> <p>Any other pointers anyone wants to offer?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T16:28:23.367", "Id": "435455", "Score": "1", "body": "Welcome to Code Review! Please clarify whether your code works or not? You said that it doesn't work properly, and then that it's working as you expect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T16:47:55.720", "Id": "435461", "Score": "1", "body": "@200_success I will edit but the code that I wrote does work. I'm posting here to see if the approach I used is sensible/readable. I'll write some edits." } ]
[ { "body": "<p>This is a partial answer, that only addresses style, but I prefer something like this for the changeColor function. </p>\n\n<p>I'm not thrilled with activateColorButton, but it works.</p>\n\n<p>This is much more readable and maintainable to me:</p>\n\n<pre><code>const changeColor = e =&gt; {\n const lightOrange = \"rgb(221, 238, 255)\"\n const lightBlue = \"rgb(255, 238, 221)\"\n const {style} = document.body\n style.backgroundColor = style.backgroundColor === lightOrange \n ? lightBlue\n : lightOrange\n}\n\nconst activateColorButton = e =&gt; {\n const btnColor = document.querySelector('#color');\n btnColor.removeEventListener('click', changeColor);\n btnColor.addEventListener('click', changeColor);\n}\n</code></pre>\n\n<p><strong>Some Explanation:</strong></p>\n\n<p><strong>TLDR</strong></p>\n\n<ul>\n<li>Use good variable names</li>\n<li>Avoid duplication</li>\n<li>Use whitespace effectively</li>\n<li>Prepare assignments for future abstraction</li>\n</ul>\n\n<p><strong>/TLDR</strong></p>\n\n<p>In changeColor, I have eliminated as much duplication as possible by assigning variables with names that are deliberately chosen to help the code to describe what it does without additional comments.</p>\n\n<p>Moving the variable names to the top of the function allows them to be extended, changed, or even abstracted out to another function or data structure entirely.</p>\n\n<p>The repeated reference to document.body.style.backgroundColor takes up half of a line of code, is very distracting, hard to read, hard to reason about, and unnecessary. style.backgroundColor could not be reduced to simply backgroundColor. This was as far down as it would go without losing functionality.</p>\n\n<p>I personally find the compactness of the tertiary if statement to be more readable than the explicit if statement and especially prefer it when either assigning or returning one of 2 choices.</p>\n\n<p>I renamed activateButton2 to activateColorButton b/c it more clearly expresses its purpose.</p>\n\n<p>In activateColorButton, I chose to remove the click handler if it's already there and reassign it, rather than have confusing 'flag' variables lying around. I'm not thrilled with it b/c, ideally, it would check to see if the click handler was already assigned via the DOM directly, but I was too lazy to implement that here, which seems ok in this case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T10:01:55.313", "Id": "435792", "Score": "1", "body": "Welcome to Code Review, thanks for improving your answer as requested!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T16:26:59.630", "Id": "435856", "Score": "0", "body": "Thank you for taking the time to write this out, this is exactly the sort of feedback I was looking for. I like that you got rid of the weird flag variable, and I like that everything is still contained within functions to keep the global namespace clean. It's readable and much more terse. This is the sort of code I'm looking to write! Would you recommend enclosing these functions inside an IIFE as in my first attempt? I am/was attempting to learn the \"module\" pattern as it pertains to using closure effectively and so I'm curious about whether that is a good approach or not. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T17:24:26.000", "Id": "435867", "Score": "1", "body": "@Anthony: There's really not too much to do as an IIFE here b/c you can just attach the first buttons handler through ```onclick``` in the DOM. If you do that, then try to put your js in an external file and use the IIFE to create a namespace for it, sort of like how jQuery does it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T17:25:26.100", "Id": "435868", "Score": "1", "body": "I think you're probably better off coming up with a less trivial example to practice the module pattern on. Something like a todo list or a table with add/delete row functionality." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T06:07:21.343", "Id": "224653", "ParentId": "224489", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T15:54:14.060", "Id": "224489", "Score": "2", "Tags": [ "javascript", "functional-programming", "dom", "closure" ], "Title": "Toggling the background color of a page using JavaScript closures" }
224489
<p>Using <code>names.txt</code> (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.</p> <p>For example, when the list is sorted into alphabetical order, <code>COLIN</code>, which is worth <span class="math-container">\$3 + 15 + 12 + 9 + 14 = 53\$</span>, is the 938<sup>th</sup> name in the list. So, <code>COLIN</code> would obtain a score of <span class="math-container">\$938 × 53 = 49714\$</span>.</p> <p>What is the total of all the name scores in the file?</p> <pre><code>import string def calculate_score(filename): """Reads names and returns total scores.""" letter_scores = {letter: ord(letter) - 64 for letter in string.ascii_uppercase} with open(filename) as names: total = 0 names = sorted(names.read().replace('"', '').split(',')) for index, name in enumerate(names): temp = 0 for letter in name: temp += letter_scores[letter] total += temp * (index + 1) return total if __name__ == '__main__': print(calculate_score('p022_names.txt')) </code></pre>
[]
[ { "body": "<p>The code looks quite good in general. Without a deeper look at the problem, there are <strike>two</strike>three things that can easily be improved:</p>\n\n<h2>Building the look-up table</h2>\n\n<p>You use</p>\n\n<pre><code>letter_scores = {letter: ord(letter) - 64 for letter in string.ascii_uppercase}\n</code></pre>\n\n<p>which makes use of the ASCII encoding to determine the value of each letter. The following could be considered a little bit more straightforward:</p>\n\n<pre><code>letter_scores = {letter: index for index, letter in enumerate(string.ascii_uppercase, 1)}\n</code></pre>\n\n<p>This uses <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> with a starting value of 1 to assign the position in the alphabet.</p>\n\n<h2>Iterating over the sorted names</h2>\n\n<p>When iterating over the sorted names, you already use <code>enumerate</code> to get <code>index</code>, but since you only use <code>index+1</code>, you can reuse the trick from above to simplify this even further (as <a href=\"https://codereview.stackexchange.com/users/98633/\">@RootTwo</a> rightfully pointed out in his comment).</p>\n\n<h2>Computing the score</h2>\n\n<p>To compute the score you use a for loop with an intermediate variable:</p>\n\n<pre><code>temp = 0\nfor letter in name:\n temp += letter_scores[letter]\ntotal += temp * (index + 1)\n</code></pre>\n\n<p>This can be rewritten using a <a href=\"https://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow noreferrer\">generator expression</a> and <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"nofollow noreferrer\"><code>sum</code></a>:</p>\n\n<pre><code>total += sum(letter_scores[letter] for letter in name) * (index + 1)\n</code></pre>\n\n<p>It basically allows you to get rid of the additional counter variable.</p>\n\n<hr>\n\n<h2>Going nuts</h2>\n\n<p>You can also reapply that generator expression idea to the first loop and end with something like:</p>\n\n<pre><code>def calculate_score(filename):\n \"\"\"Reads names and returns total scores.\"\"\"\n letter_scores = {letter: index for index, letter in enumerate(string.ascii_uppercase, 1)}\n with open(filename) as names:\n names = sorted(names.read().replace('\"', '').split(','))\n return sum(\n sum(letter_scores[letter] for letter in name) * index\n for index, name in enumerate(names, 1)\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:35:02.293", "Id": "435476", "Score": "0", "body": "Change the `for` loop to use `enumerate(names, 1)`. Then just use `index` instead of `(index + 1)` when updating `total`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:48:41.583", "Id": "435477", "Score": "0", "body": "@RootTwo: I included your feedback and also added a nested generator expression solution." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T19:45:07.177", "Id": "224497", "ParentId": "224494", "Score": "1" } } ]
{ "AcceptedAnswerId": "224497", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T19:26:33.280", "Id": "224494", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 22 names scores in Python" }
224494
<p>I am check first time userDefaults will not save value return 0 else get value from userDefaults </p> <p>I am checking if <code>userDefaults</code> will not save the value, and If it doesn't, return 0. If it does, then I get the value from <code>userDefaults</code>.</p> <pre><code>func scaleMeter() { let numberPicker = NumberPicker(delegate: self, maxNumber: 100) numberPicker.tintColor = .white numberPicker.heading = “Select Scale” let ageCount = UserDefaults.value(forKey: defaultsKeys.age) guard countValue != nil else { numberPicker.defaultSelectedNumber = 0 self.tabBarController?.present(numberPicker, animated: true, completion: nil) return } numberPicker.defaultSelectedNumber = Int(ageCount as! String)! self.tabBarController?.present(numberPicker, animated: true, completion: nil) } </code></pre> <p>Is this a correct approach, having <code>self.tabBarController?.present</code> both inside and outside the guard?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T19:59:37.467", "Id": "224499", "Score": "2", "Tags": [ "swift", "ios" ], "Title": "check condition with userdefaults value exist or not" }
224499
<p>This is the code I came up with: </p> <pre><code>void set_bit_at_pos(int* num, int pos, bool val) { if (val) { int mask = 1 &lt;&lt; pos; *num |= mask; } else { int mask = ~(1 &lt;&lt; pos); *num &amp;= mask; } } </code></pre> <p>I'm new to bitwise operations, so this approach may not be the best. Nevertheless any suggestions are appreciated.</p> <p>For the following main: </p> <pre><code>int main() { int num = 5; cout &lt;&lt; num &lt;&lt; endl; set_bit_at_pos(&amp;num, 1, true); cout &lt;&lt; num &lt;&lt; endl; } </code></pre> <p>(I know about <code>using namespace std;</code>) </p> <p>This is the output:</p> <pre><code>5 7 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:34:50.940", "Id": "435475", "Score": "3", "body": "It would be very helpful if you demonstrated how this function was expected to be used. In most cases I would recommend using unsigned int rather than int for num. There aren't very many reasons to adjust bits in signed integers and removing a bit may make it go negative." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T22:36:41.717", "Id": "435480", "Score": "0", "body": "Well, that's the point, @pacmaninbw , I'm not sure if it works correctly. I don't know if there's an off by 1 error, maybe bits start from 0 as well, and not from 1 which is I believe the way I wrote it. I'll provide some output though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T00:11:48.297", "Id": "435483", "Score": "2", "body": "@MarkCeitlin Bitwise operations on `signed` integers are unsafe. If you want to manipulate bits on signed integers, it's better to cast to `unsigned` integers, manipulate, and cast back to signed integers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T05:40:26.570", "Id": "435497", "Score": "0", "body": "You should'nt ask a question if you're not sure your code works. At least you could have written some tests to verify the correctness of your method. Here's a great post about bit operations: https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T06:36:59.617", "Id": "435501", "Score": "0", "body": "I have retagged the question. This is clearly c++ code not c." } ]
[ { "body": "<p>This is simpler:</p>\n\n<pre><code>#include &lt;stdint.h&gt; // #include &lt;cstdint&gt; in C++\n\nvoid write_bit_32b(uint32_t *num, uint8_t pos, bool val)\n{\n\n *num &amp;= ~(UINT32_C(1) &lt;&lt; pos);\n *num |= (uint32_t)val &lt;&lt; pos;\n}\n</code></pre>\n\n<hr>\n\n<p>Use fixed-width integers if you can (see above).</p>\n\n<hr>\n\n<p>Use <code>int main(void)</code>:</p>\n\n<p>C17::6.11.6: </p>\n\n<blockquote>\n <p>Function declarators The use of function declarators with empty\n parentheses (not prototype-format parameter type declarators) is an\n obsolescent feature.</p>\n</blockquote>\n\n<hr>\n\n<p>This may be interesting to you:</p>\n\n<p><a href=\"https://stackoverflow.com/q/47981/6872717\">https://stackoverflow.com/q/47981/6872717</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T06:39:18.890", "Id": "435502", "Score": "0", "body": "The OP obviously asks about c++ code. Thus citing c standards is pretty useless here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T06:09:32.163", "Id": "435761", "Score": "0", "body": "There is a subtle difference between `int main()` and `int main(void)` in C. In C++ though the use of `(void)` is equivalent to `()` it is considered archaic and to avoid confusion with `C` considered bad practice by most coding standards. There are only two valid declarations for main `int main()` and `int main(int, char**)` See: `n4820 6.8.3.1 main function [basic.start.main]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T11:52:01.320", "Id": "435822", "Score": "0", "body": "@MartinYork In C, in a function definition, `()` and `(void)` are the same (unlike in function declarators other that definitions; don't remember and can't find the paragraph). Given that in C++ they are absolutely equivalent, although the wording of the standard is unfortunate, I would interpret it as in C17::5.1.2.2.1: *\"or equivalent\"*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T11:53:31.417", "Id": "435823", "Score": "0", "body": "BTW, the only reason for the `(void)` comment is that this question was originally asked as a C question, not C++" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T16:10:51.333", "Id": "435854", "Score": "0", "body": "In `C` `()` and `(void)` are subtly different in that `void` indicates an unknown number of parameters. I was unaware that declaration and definition have different rules for `void` in `C`. But that just reinforces my conviction that you should use the version without `void` for both consistency and readability. Also since the rules are obscure using the one with the least exceptions would be best from a maintenance stand point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T23:43:24.587", "Id": "435915", "Score": "0", "body": "@MartinYork In C, that would be `void`, which always means zero parameters, and is the only non-deprecated standard way. It is `()` that indicates an unknown number of parameters in some cases, and is explicitly an obsolescent feature in the standard." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T00:21:22.000", "Id": "224517", "ParentId": "224500", "Score": "1" } } ]
{ "AcceptedAnswerId": "224517", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T20:01:24.173", "Id": "224500", "Score": "3", "Tags": [ "c++", "bitwise" ], "Title": "Set a specific bit to a specific value" }
224500
<p><a href="https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/" rel="nofollow noreferrer">codility OddOccurrencesInArray</a>:</p> <blockquote> <p>A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.</p> <p><em>For example, in array A such that:</em>   A[0] = 9  A[1] = 3  A[2] = 9<br />   A[3] = 3  A[4] = 9  A[5] = 7  A[6] = 9<br />     • the elements at indexes 0 and 2 have value 9,<br />     • the elements at indexes 1 and 3 have value 3,<br />     • the elements at indexes 4 and 6 have value 9,<br />     • the element at index 5 has value 7 and is unpaired.</p> <p>Write a function:<br />     <code> class Solution { public int solution(int[] A); }</code><br /> that, given an array A consisting of N integers fulfilling the above conditions,<br /> returns the value of the unpaired element.</p> </blockquote> <pre><code>class Solution { public int solution(int[] A) { final int len = A.length; Arrays.sort(A); for (int i = 0; i &lt; len ;) { int counter = 1; int current = A[i]; while ((i &lt; len - 1) &amp;&amp; (current == A[++i])) { counter++; } if (counter % 2 == 1) { return current; } } return -1; } } </code></pre> <p>Could this code be bettered in terms of time complexity or code quality?</p>
[]
[ { "body": "<ul>\n<li><p>Regarding <strong>time complexity</strong>. If you use an additional array, you can make only one passage through the array (not doing sorting) and have time complexity <code>O(N)</code>, where <code>N</code> - the number of elements in the array. Currently, it's <code>O(NlogN)</code> because of sorting.</p></li>\n<li><p>Currently looks like if your method returns -1, it means that you have an even number of elements in the array (Invalid input?) So maybe you should throw some Exception such as <code>IllegalArgumentException</code> in this case? Moreover, what if you have elements with value -1 in your array?</p></li>\n<li><p>You should simplify your <strong>loops</strong>. You have nested loop structure, however, you can have only one since you traverse the array only once. Currently, because of 2 loop structures, it takes some time to understand what's going on, where you increment your <code>i</code> variable, what is the stop condition, etc.</p></li>\n</ul>\n\n<h2>Minor comments</h2>\n\n<ul>\n<li>Do not start your variable names with a capital letter (<code>A</code>). This convention is reserved for classes.</li>\n</ul>\n\n<h2>Edit</h2>\n\n<p>Now it came to my mind that you can solve this task with one passage (in <code>O(N)</code>) without an additional array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:56:17.480", "Id": "453737", "Score": "0", "body": "`[using] an additional array, you can make only one passage through the array (not doing sorting) and have time complexity O(N)` care to sketch *how* (other than the cancellation approach mentioned in [Vikas' answer](https://codereview.stackexchange.com/a/224520/93149)?)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T23:18:05.510", "Id": "224512", "ParentId": "224501", "Score": "3" } }, { "body": "<p>Sorting of the array will take O(n (log n)) in the average case. You can do it in linear time using bitwise operation</p>\n\n<pre><code>public class Test {\n public static void main(){\n int a = 0;\n int[] arr = {9,3,9,3,9,7,9};\n\n for (int i = 0; i &lt; arr.length; i++ ){\n a = a ^ arr[i];\n }\n\n System.out.println(a);\n }\n}\n</code></pre>\n\n<p>Any number which will XOR with 0 will be the number itself. But if it will XOR with itself, it will be 0. In the end, we'll get the non paired number.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T08:13:15.887", "Id": "435518", "Score": "1", "body": "Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T08:24:45.193", "Id": "435522", "Score": "0", "body": "It's possible to use a stream and `reduce` for a relatively clean [one-liner](https://tio.run/##LY7BCoMwDIbP61Pk2IIruB2GyAYed9jJ49ig0yJxtUobBRGf3VXdDyHhS/4ktRrUsS6/y4JN1zqCOgDZExqZOadGnzLW9R@DBRRGeQ8PhXZiEPTHnhSFNLRYQhOaPCeHtnq@QLnKC9iHV6GljTq4wpRE52iPS5TMKTvkoyfdyLYn2YUFZCzfP5CenFYND0YhnS77QnOOcQR4EnC8AcbwXmtZacr83RIXIt2Ozmxmy/ID). As a bonus, it fails with an empty array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T22:18:35.390", "Id": "435912", "Score": "0", "body": "@EricDuminil, Here are the requirements from the original question - \"A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired\". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-23T05:06:44.297", "Id": "435925", "Score": "0", "body": "sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T00:59:53.713", "Id": "224520", "ParentId": "224501", "Score": "8" } } ]
{ "AcceptedAnswerId": "224520", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T20:06:52.240", "Id": "224501", "Score": "3", "Tags": [ "java", "array", "complexity" ], "Title": "Finding unpaired number in an odd length Array of integers" }
224501
<p><a href="https://codingbat.com/prob/p138533" rel="nofollow noreferrer">Link To Question</a></p> <blockquote> <p>Given a string, return a version without the first and last char, so &quot;Hello&quot; yields &quot;ell&quot;. The string length will be at least 2.</p> <p>without_end('Hello') → 'ell'</p> <p>without_end('java') → 'av'</p> <p>without_end('coding') → 'odin'</p> </blockquote> <p>This is the code I wrote as a solution to this problem. I feel that this simple of a problem can be written in one line, but I can baffled as to how I can do so; after many attempts. Any and all feedback is appreciated and considered so I can further improve my python practices.</p> <pre><code>def without_end(str): if len(str) &lt;= 2: return &quot;&quot; no_start = str[1:] no_end = no_start[:len(no_start) - 1] return no_end </code></pre>
[]
[ { "body": "<p>You were right on track with</p>\n\n<pre><code>no_start = str[1:]\nno_end = no_start[:len(no_start) - 1]\n</code></pre>\n\n<p>In a first step, they can be combined:</p>\n\n<pre><code>return str_[1:len(str_)-1]\n</code></pre>\n\n<p><strong>Note:</strong> I changed <code>str</code> to <code>str_</code> because <code>str</code> is actually <a href=\"https://docs.python.org/3/library/functions.html#func-str\" rel=\"nofollow noreferrer\">a datatype</a> in Python.</p>\n\n<p>The next thing to know about <a href=\"https://stackoverflow.com/a/509295/5682996\">slicing</a>, is that you can use negative indices to index from the back without specifically using the length of the string like so:</p>\n\n<pre><code>return str_[1:-1]\n</code></pre>\n\n<p>And since this also works for strings with a length equal to two, you can also get rid of the earlier check.</p>\n\n<p>So your are now down to basically:</p>\n\n<pre><code>def without_start_end(input_):\n return input_[1:-1]\n</code></pre>\n\n<p><strong>Again take note:</strong> <code>input_</code> also has the trailing <code>_</code>, since, you guessed it, <a href=\"https://docs.python.org/3/library/functions.html#input\" rel=\"nofollow noreferrer\"><code>input</code></a> is already taken.</p>\n\n<hr>\n\n<p>A non-directly code relate side-note: the official <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (aka PEP8) recommends to use 4 spaces per indentation level, and most people seem to follow that recommendation. There are however exceptions, e.g. Google's TensorFlow framework uses 2 spaces per indentation level (see <a href=\"https://www.tensorflow.org/community/contribute/code_style\" rel=\"nofollow noreferrer\">their style guide</a>), although Google's own <a href=\"http://google.github.io/styleguide/pyguide.html#34-indentation\" rel=\"nofollow noreferrer\">\"general purpose\" style guide</a> for Python code sticks with 4 spaces.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:25:17.220", "Id": "224506", "ParentId": "224503", "Score": "5" } } ]
{ "AcceptedAnswerId": "224506", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T20:34:47.130", "Id": "224503", "Score": "2", "Tags": [ "python", "programming-challenge", "strings" ], "Title": "CodingBat: without_end" }
224503
<p>I have <code>Gig</code> and <code>Singer</code> Active Record models (standard--no customization just yet) with a many-to-many relationship through a generic join table which holds nothing but the respective ids of <code>Gig</code> and <code>Singer</code>. My form sends a given gig id and all the singers who will be attending, denoted with check boxes. I need to have the ability to check or uncheck singers. The following code works, but it does so by removing all the singers from a gig and re-adding them. This feels hacky... is there a better way? (I think this is all the code necessary but let me know if you need me to add anything)</p> <pre><code>class GigSingersController &lt; ApplicationController def create gig = Gig.find(params[:gig_id]) singer_ids = params[:singer_ids] # [1, 4, 5,] gig.singers = [] singer_ids.each do |id| singer = Singer.find(id) gig.singers &lt;&lt; singer end redirect_to gigs_path end end </code></pre> <p>EDIT: </p> <p>As requested in the comments, here are the schema and relevant models, although as I said, they are completely generic. Perhaps I didn't do a good job of making my question clear: <strong>Is the best way to create these relationships when using a checkbox to remove all existing ones and recreate them from the boxes currently checked, thereby removing any that the user <em>unchecked</em> on an edit?</strong></p> <pre><code>ActiveRecord::Schema.define(version: 2019_07_19_195106) do create_table "gig_singers", force: :cascade do |t| t.integer "gig_id" t.integer "singer_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "gigs", force: :cascade do |t| t.string "name" t.text "notes" t.datetime "datetime" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "singers", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "active" end class Gig &lt; ApplicationRecord has_many :gig_singers has_many :singers, through: :gig_singers end class GigSinger &lt; ApplicationRecord belongs_to :gig belongs_to :singer end class Singer &lt; ApplicationRecord has_many :gig_singers has_many :gigs, through: :gig_singers end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T17:57:12.980", "Id": "435623", "Score": "0", "body": "These are [tag:active-record] models?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T11:37:59.623", "Id": "436132", "Score": "1", "body": "On database questions, it's customary to provide a database schema. This allows us to see exactly how you store your data and the inefficiencies in the code used to retrieve data from it. Please consider adding those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T11:38:31.050", "Id": "436133", "Score": "0", "body": "The current code is simply too small a part of what you're doing to say anything sensible about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T22:21:21.497", "Id": "436255", "Score": "0", "body": "@Mast It's not a database question. I will include the things you are asking for but I can't see how they will possibly be of any help to the question I've asked." } ]
[ { "body": "<p>Actually, Active Record can work with joined collection (including has_many :through) from the box.</p>\n\n<p>So, you just need to pass new collection instead of old, and AR will delete excessive and add new records.</p>\n\n<p>In your code, need to change <code>create</code> method body to:</p>\n\n<pre><code>gig = Gig.find(params[:gig_id])\nsinger_ids = params[:singer_ids] # [1, 4, 5,]\ngig.singers = Singer.find(singer_ids)\nredirect_to gigs_path\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:46:00.053", "Id": "437567", "Score": "0", "body": "That's much better--thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T10:58:08.557", "Id": "225338", "ParentId": "224505", "Score": "2" } } ]
{ "AcceptedAnswerId": "225338", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:08:03.237", "Id": "224505", "Score": "5", "Tags": [ "ruby", "ruby-on-rails", "join", "active-record" ], "Title": "Update join table using list of checkboxes in Rails" }
224505
<p>The objective of the game is to survive as long as possible. You have a need and that is hunger. Your hunger decreases by 10 every 3 minutes and if your hunger reaches 0 you will die and the amount of time you survived will be displayed. You need to eat or drink something to increase your hunger and that cost money! you start off with $100 that should be enough for a while but soon you will run out of money so you can work and there are a total of 5 jobs you can work for, you can start off as a cashier and work your way up by gaining Skill points!</p> <h2>Future plans:</h2> <ul> <li>Add a loan system</li> <li>Add housing system</li> <li>Random events that would steal cash or hunger or both!</li> <li>Add more items to store</li> <li>Add a shopping cart to the store</li> <li><strike>Add save/load system</strike></li> <li><strike>Add a pin to the bank system.</strike></li> </ul> <pre><code>import random; import time; import threading; import sys; import psutil; from colorama import init; from termcolor import colored while True: # Contains all variables and hunger decrease def show_faster(str): for char in str: time.sleep(0.1) sys.stdout.write(char) sys.stdout.flush() init() print(colored(&quot;&quot;&quot; M ega ga mMe imMe imMega g imMeg SimMe mMegaS aSi Meg egaSim SimM mM gaS Meg imMegaSimMe imM aSi egaSimMe MegaSim SimMe Meg imMegaSimMega SimMegaS mMe SimM gaSi ega mMe aSim imMega Meg imM aSi ega Sim ga mMe SimMegaSi ega mMe mMegaSim mMegaS Meg imM aSi ega Sim ga mMe aSim MegaSimMe imMe aSim MegaS mMeg SimM gaSi ega aSim mMegaSimM gaSi egaSimMe SimMe aSim gaSimMega mMeg Sim gaSi egaS aSim mMeg SimMegaSi imMe SimMegaSim gaSimMega imMegaSim gaSi egaS gaSim mMeg imMegaS Me SimMe imMegaSim gaSimMe imMegaSim gaSi egaS mMegaSimM mMegaSim &quot;&quot;&quot;, 'red')) t0 = time.time() print(&quot;=&quot;*15) while True: try: user = input('Enter a name:') if len(user) &lt; 3: print(&quot;Your name must be at least 3 char long&quot;) else: break except ValueError: print(&quot;Sorry, I didn't understand that. Please try again&quot;) print(&quot;=&quot;*15) time.sleep(1) show_faster(&quot;...Loading....\n&quot;) time.sleep(1) show_faster(&quot;...Initializing.....\n&quot;) time.sleep(1) show_faster(&quot;...Done..\n&quot;) print(&quot;=&quot;*15) print(colored(&quot;Please check out the more info section to know what to do!&quot;, &quot;green&quot;)) print(&quot;=&quot;*15) cash = 100 Bank_balance = 0 hunger = 100 inventory = [] Skill = 0 count = 0 job_position = [] shutdown = psutil.Process() def hungerdecrease(): global hunger if hunger &gt; 0: # no rearm when dead threading.Timer(0.001,hungerdecrease).start() # rearm timer lock.acquire() hunger -= 0.001 lock.release() elif hunger &lt;= 0: t1 = time.time() total = t1 - t0 total2 = round(total / 60) print(f&quot;\nYou died of hunger. :( should have eaten!. You stood alive for {total2} minutes.&quot;) shutdown.terminate() lock = threading.Lock() threading.Timer(0.001,hungerdecrease).start() def count_work(num): global Bank_balance bonus = random.randint(500,3000) if count &gt;= num: print(colored(f&quot;You got a bonus of ${bonus}.&quot;, 'green')) print(&quot;=&quot;*15) Bank_balance += bonus break def mainmenu(): print(&quot;Welcome To the game!&quot;) print(&quot;=&quot;*15) time.sleep(1) main = input(&quot;Where would you like to go?\nA)The Bank\nB)Store\nC)Work\nD)Inventory\nE)More information\nF)Exit\n&gt;&gt;&gt;&quot;).lower().strip() if main == &quot;a&quot;: Bank_Of_Omni() elif main == &quot;b&quot;: store() elif main == &quot;c&quot;: print(&quot;=&quot;*15) work() elif main == &quot;d&quot;: Your_Stuff() elif main == &quot;e&quot;: moreinfo() elif main == &quot;f&quot;: print(&quot;Good Bye!&quot;) quit() else: print(&quot;=&quot;*15) print(&quot;Invalid input. Try again!&quot;) print(&quot;=&quot;*15) mainmenu() def Bank_Of_Omni(): print(&quot;=&quot;*15) print(f&quot;Welcome to Omnibank {user}.&quot;) print(&quot;=&quot;*15) time.sleep(.01) option = input(&quot;What will you like to do?\nA)Deposit\nB)Withdraw\nC)Check Balance\nD)Mainmenu\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if option == &quot;a&quot;: Deposit() elif option == &quot;b&quot;: Withdraw() elif option == &quot;c&quot;: Checkbalance() elif option == &quot;d&quot;: mainmenu() else: print(&quot;Invlid input&quot;) Bank_Of_Omni() def Deposit(): global cash global Bank_balance depositing = input(&quot;Do you want to make a deposit?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() if cash &lt;= 0: print(&quot;=&quot;*15) print(colored(f&quot;You don't have enough in cash to depsoit! You have ${cash} in cash.&quot;, 'red')) Bank_Of_Omni() if depositing == &quot;y&quot;: try: print(&quot;=&quot;*15) Deposit1 = float(input(f&quot;You have ${cash} cash! How much do you want to deposit?\n&gt;&gt;&gt;&quot;)) # make an option print(&quot;=&quot;*15) if Deposit1 &lt;= cash: if Deposit1 &gt; 0: Bank_balance = Bank_balance + Deposit1 cash = cash - Deposit1 print(colored(f&quot;{user}, your bank balance is now: ${Bank_balance}, and your cash is now: ${cash}&quot;, 'green')) Bank_Of_Omni() elif Deposit1 &lt; 0: print(colored(&quot;Insufficient Funds&quot;, 'red')) Bank_Of_Omni() else: print(colored(&quot;Insufficient Funds&quot;, 'red')) Bank_Of_Omni() elif Deposit1 &gt; cash: print(colored(&quot;Insufficient Funds&quot;, 'red')) Bank_Of_Omni() except ValueError: print(colored(&quot;Invalid input. Try again!&quot;, 'red')) print(&quot;=&quot;*15) Deposit() elif depositing == &quot;n&quot;: print(&quot;=&quot;*15) print(colored(&quot;Invalid input. Try again!&quot;, 'red')) Bank_Of_Omni() else: print(&quot;=&quot;*15) print(colored(&quot;Invalid input. Try again!&quot;, 'red')) Bank_Of_Omni() def Withdraw(): global cash global Bank_balance withdrawing = input(&quot;Do you want to make a withdraw?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if Bank_balance &lt;= 0: print(colored(f&quot;You don't have enough in the bank to withdraw! Your bank balance is ${Bank_balance}&quot;, 'red')) Bank_Of_Omni() if withdrawing == &quot;y&quot;: try: withdraw1 = float(input(f&quot;You have ${Bank_balance} in your bank account and ${cash} in cash! How much do you want to withdraw?\n&gt;&gt;&gt;&quot;)) # make an option print(&quot;=&quot;*15) if withdraw1 &lt;= Bank_balance: if withdraw1 &gt; 0: Bank_balance = Bank_balance - withdraw1 cash = cash + withdraw1 print(colored(f&quot;{user}, your bank balance is now: ${Bank_balance}, and your cash is now: ${cash}&quot;, 'green')) Bank_Of_Omni() elif withdraw1 &lt; 0: print(colored(&quot;Insufficient Funds&quot;, 'red')) Bank_Of_Omni() else: print(colored(&quot;Insufficient Funds&quot;, 'red')) Bank_Of_Omni() elif withdraw1 &gt; Bank_balance: print(colored(&quot;Insufficient Funds&quot;, 'red')) Bank_Of_Omni() except ValueError: print(&quot;=&quot;*15) print(colored(&quot;Invalid input. Try again!&quot;, 'red')) print(&quot;=&quot;*15) Withdraw() elif withdrawing == &quot;n&quot;: print(&quot;=&quot;*15) print(colored(&quot;Invalid input. Try again!&quot;, 'red')) Bank_Of_Omni() else: print(colored(&quot;Invalid input. Try again!&quot;, 'red')) Bank_Of_Omni() def Checkbalance(): print(colored(f&quot;Your Bank balance is: ${Bank_balance}. You have ${cash} in cash.&quot;, 'green')) Bank_Of_Omni() def store(): global inventory global cash global Bank_balance print(&quot;Welcome to David's Grocery&quot;) print(&quot;=&quot;*15) # ask = ('buy', 'quit') items = [('eggs', 3.16), ('mealdeal', 8), ('chicken', 4.38), ('milk', 2.60), ('tomatoes', 4), ('cheese', 3), ('apples', 2), ('potatoes', 4), ('beer', 3.37), ('wine', 15), ('coca-cola', 1.92)] print(&quot;This is our menu! Take a look around!&quot;) print(f&quot;&quot;&quot; Wine ..... $15.00 ...(+8 hunger) Chicken.... $4.38 ...(+9 hunger) Coca-Cola ...... $1.92 ...(+4 hunger) Milk ..... $2.60 ...(+2 hunger) Beer ..... $3.37 ...(+5 hunger) Tomatoes ....... $4 ...(+1 hunger) MealDeal .... $8.00 ...(+10 hunger) Cheese ..... $3.00 ...(+4 hunger) Potatoes ...... $4 ...(+3 hunger) Apples ....... $2 ...(+2 hunger) Eggs ..... $3.16 ... (+3 hunger) &quot;&quot;&quot;) buying = input(&quot;Do you want to buy something?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() if buying == &quot;y&quot;: item = input(&quot;What item do you want to buy?\n&gt;&gt;&gt;&quot;).lower().strip() # make an option print(&quot;=&quot;*15) if item == &quot;&quot;: print(&quot;=&quot;*15) print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) store() for i in items: if item == i[0]: print(item, '(are) is $', i[1]) buy = input(&quot;\nAre you sure you want to buy this item?(y/n)\n&gt;&gt;&quot;).lower() print(&quot;=&quot;*15) if buy == &quot;y&quot;: if cash &gt; i[1]: cash = cash - i[1] print(&quot;You bought (a) &quot; + item + f&quot; you have ${cash} left over&quot;) print(&quot;=&quot;*15) inventory.append(item) store() else: print(&quot;=&quot;*15) print(colored(&quot;Insufficient Funds&quot;, 'red')) print(&quot;=&quot;*15) mainmenu() elif buy == 'n': print(&quot;=&quot;*15) print(&quot;Too bad you don't want (a) &quot; + item) print(&quot;=&quot;*15) mainmenu() else: print(&quot;=&quot;*15) print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) mainmenu() if i[1] &gt; cash: print('You do not have enough money for this item.\n') print(&quot;Going back to menu!&quot;) print(&quot;=&quot;*15) mainmenu() else: if item != i[0]: print(&quot;=&quot;*15) print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) store() elif buying == &quot;n&quot;: print(&quot;=&quot;*15) mainmenu() else: print(&quot;=&quot;*15) print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) store() def work(): print(&quot;Welcome to the Job Assocaition!&quot;) print(&quot;=&quot;*15) intro_job = input(&quot;Select an option!\n\nA)Job Selection\nB)Position\nC)Go to work!\nD)Mainmenu\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if intro_job == &quot;a&quot;: job_selection() elif intro_job == &quot;b&quot;: position() elif intro_job == &quot;c&quot;: go_to_work() elif intro_job == &quot;d&quot;: mainmenu() else: print(colored(&quot;Invalid input. Try again!&quot;, 'red')) print(&quot;=&quot;*15) work() def job_selection(): global Skill global job_position job = input(&quot;Select a job\n\nA)Cashier\nB)Waitress\nC)Teacher\nD)Administrative assistant\nE)HR Manager\nF)Go back\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if job == &quot;a&quot;: print(colored(&quot;Cashiers are paid $12 an hr and require no skill. Hunger is decreased by 10 per day! You will work 8hrs a day!&quot;, 'green')) print(&quot;=&quot;*15) want_job = input(&quot;Do you want the job?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if want_job == &quot;y&quot;: if job_position &gt; []: if &quot;Cashier&quot; == job_position: print(colored(&quot;You already work in this position!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() else: change = input(&quot;Are you sure you want to change position?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if change == &quot;y&quot;: del job_position[:] if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 0.5 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Cashier') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif change == &quot;n&quot;: print(&quot;Going back!&quot;) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif job_position &lt;= []: if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 0.5 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Cashier') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif want_job == &quot;n&quot;: print(colored(&quot;Going Back&quot;, 'green')) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif job == &quot;b&quot;: print(colored(&quot;Waitress are paid $9 an hr plus tips! and require 10 skill. Hunger is decreased by 10 per day! You will work 8hrs a day!&quot;, 'green')) print(&quot;=&quot;*15) want_job = input(&quot;Do you want the job?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if want_job == &quot;y&quot;: if job_position &gt; []: if &quot;Waitress&quot; == job_position: print(colored(&quot;You already work in this position!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() if Skill &gt;= 10: change = input(&quot;Are you sure you want to change position?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if change == &quot;y&quot;: del job_position[:] if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 1.5 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Waitress') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif change == &quot;n&quot;: print(&quot;Going back!&quot;) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif Skill &lt; 10: print(colored(&quot;You don't have enough Skills to get the job! You need 10 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif job_position &lt;= []: if Skill &gt;= 10: if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 1.5 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Waitress') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif Skill &lt; 10: print(colored(&quot;You don't have enough Skills to get the job! You need 10 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif want_job == &quot;n&quot;: print(colored(&quot;Going Back&quot;, 'green')) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif job == &quot;c&quot;: print(colored(&quot;Teachers are paid $15 an hr plus bonuses! and require 50 skill. Hunger is decreased by 10 per day! You will work 8hrs a day!&quot;, 'green')) print(&quot;=&quot;*15) want_job = input(&quot;Do you want the job?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if want_job == &quot;y&quot;: if job_position &gt; []: if &quot;Teacher&quot; == job_position: print(colored(&quot;You already work in this position!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() if Skill &gt;= 50: change = input(&quot;Are you sure you want to change position?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if change == &quot;y&quot;: del job_position[:] if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 5 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Teacher') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif change == &quot;n&quot;: print(&quot;Going back!&quot;) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif Skill &lt; 10: print(colored(&quot;You don't have enough Skills to get the job! You need 50 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif job_position &lt;= []: if Skill &gt;= 50: if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 5 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Teacher') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif Skill &lt; 50: print(colored(&quot;You don't have enough Skills to get the job! You need 50 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif want_job == &quot;n&quot;: print(colored(&quot;Going Back&quot;, 'green')) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif job == &quot;d&quot;: print(colored(&quot;Administrative assistant are paid $22 an hr plus bonuses! and require 250 skill. Hunger is decreased by 12 per day! You will work 8hrs a day!&quot;, 'green')) print(&quot;=&quot;*15) want_job = input(&quot;Do you want the job?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if want_job == &quot;y&quot;: if job_position &gt; []: if &quot;Administrative assistant&quot; == job_position: print(colored(&quot;You already work in this position!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() if Skill &gt;= 250: change = input(&quot;Are you sure you want to change position?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if change == &quot;y&quot;: del job_position[:] if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 10 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Administrative assistant') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif change == &quot;n&quot;: print(&quot;Going back!&quot;) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif Skill &lt; 250: print(colored(&quot;You don't have enough Skills to get the job! You need 250 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif job_position &lt;= []: if Skill &gt;= 250: if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 10 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('Administrative assistant') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif Skill &lt; 250: print(colored(&quot;You don't have enough Skills to get the job! You need 250 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif want_job == &quot;n&quot;: print(colored(&quot;Going Back&quot;, 'green')) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif job == &quot;e&quot;: print(colored(&quot;HR Manager's are paid $35 an hr plus bonuses! and require 1500 skill. Hunger is decreased by 15 per day! You will work 6hrs a day!&quot;, 'green')) print(&quot;=&quot;*15) want_job = input(&quot;Do you want the job?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if want_job == &quot;y&quot;: if job_position &gt; []: if &quot;HR Manager&quot; == job_position: print(colored(&quot;You already work in this position!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() if Skill &gt;= 1500: change = input(&quot;Are you sure you want to change position?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if change == &quot;y&quot;: del job_position[:] if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 20 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('HR Manager') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif change == &quot;n&quot;: print(&quot;Going back!&quot;) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif Skill &lt; 250: print(colored(&quot;You don't have enough Skills to get the job! You need 1,500 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif job_position &lt;= []: if Skill &gt;= 1500: if want_job == &quot;y&quot;: print(colored(&quot;You got the job! You will be paid per day you work! Your skill will increase by 20 per day of work!(Go to work to start working!)&quot;, 'green')) print('='*15) job_position.append('HR Manager') work() elif want_job == &quot;n&quot;: job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif Skill &lt; 1500: print(colored(&quot;You don't have enough Skills to get the job! You need 1,500 Skills!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() elif want_job == &quot;n&quot;: print(colored(&quot;Going Back&quot;, 'green')) print(&quot;=&quot;*15) job_selection() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) print('='*15) job_selection() elif job == &quot;f&quot;: work() else: print(colored(&quot;Invalid input. Try again!&quot;, 'red')) print(&quot;=&quot;*15) job_selection() def position(): global job_position print(colored(f&quot;Your job position is {job_position}.&quot;, 'green')) print('='*15) job_selection() def go_to_work(): global Skill, job_position, Bank_balance, hunger, count print(&quot;Welcome to your work station!&quot;) print(&quot;=&quot;*15) if job_position == []: print(colored(&quot;You need to have a job to work!(Go to job selection)&quot;, &quot;red&quot;)) print(&quot;=&quot;*15) work() sure1 = input(&quot;Do you want to work today?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if sure1 == &quot;y&quot;: if &quot;Cashier&quot; in job_position: print(colored(&quot;You worked hard today! $89 Has Been deposited to your bank account! -10 hunger, +0.5 skills!&quot;,&quot;green&quot;)) print(&quot;=&quot;*15) tax = round(96 * 0.0699) Bank_balance += 96 - tax hunger -= 10 Skill += 0.5 work() if &quot;Waitress&quot; in job_position: Tip = random.randint(0, 100) if sure1 == &quot;y&quot;: print(colored(f&quot;You worked hard today! $67 Has Been deposited to your bank account. Your Tip for today is: ${Tip}. -10 hunger, +1.5 skills!&quot;, &quot;green&quot;)) print(&quot;=&quot;*15) tax = round(72 * 0.0699) Bank_balance += 72 + Tip - tax hunger -= 10 Skill += 1.5 work() elif sure1 == &quot;n&quot;: work() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) go_to_work() elif &quot;Teacher&quot; in job_position: if sure1 == &quot;y&quot;: print(colored(f&quot;You worked hard today! $120 Has Been deposited to your bank account. -10 hunger, +5 skill!&quot;, &quot;green&quot;)) print(&quot;=&quot;*15) tax = round(120 * 0.0699) Bank_balance += 120 - tax hunger -= 10 Skill += 5 count += 1 count_work(12) count_work(24) count_work(36) count_work(48) count_work(60) count_work(72) work() elif sure1 == &quot;n&quot;: work() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) go_to_work() elif &quot;Administrative assistant&quot; in job_position: if sure1 == &quot;y&quot;: print(colored(f&quot;You worked hard today! $176 Has Been deposited to your bank account. -12 hunger, +10 skill!&quot;, &quot;green&quot;)) print(&quot;=&quot;*15) tax = round(176 * 0.0699) Bank_balance += 176 - tax hunger -= 12 Skill += 10 count += 1 count_work(12) count_work(24) count_work(36) count_work(48) count_work(60) count_work(72) work() elif sure1 == &quot;n&quot;: work() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) go_to_work() elif &quot;HR Manager&quot; in job_position: if sure1 == &quot;y&quot;: print(colored(f&quot;You worked hard today! $210 Has Been deposited to your bank account. -15 hunger, +20 skill!&quot;, &quot;green&quot;)) print(&quot;=&quot;*15) tax = round(210 * 0.0699) Bank_balance += 210 - tax hunger -= 15 Skill += 20 count += 1 count_work(12) count_work(24) count_work(36) count_work(48) count_work(60) count_work(72) work() elif sure1 == &quot;n&quot;: work() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) go_to_work() elif sure1 == &quot;n&quot;: work() else: print(colored(&quot;Invlid input. Try agian!&quot;, 'red')) work() def moreinfo(): print(&quot;=&quot;*15) print(colored(f&quot;Hey {user}, Your objective is to survive as long as possible. You start off with $100 cash and 100 hunger, Go to inventory to see your hunger level and inventory and more!&quot;, 'green')) print(&quot;=&quot;*15) print(colored(&quot;Your hunger will decrease every 3 minutes by 10 hunger. So make sure to eat!&quot;, 'green')) print(&quot;=&quot;*15) print(colored(&quot;You can't eat something that will increase your hunger past 100.&quot;, 'green')) print(&quot;=&quot;*15) print(colored(&quot;You can work to have an income and survive. You can start of as a Cashier and gradually get better paying jobs but each job require a certain amount of skill to get the job! when you recieve your check it will automatically be taxed!&quot;, 'green')) print(&quot;=&quot;*15) print(colored(&quot;Tax rate is 6.99%!&quot;, 'green')) print(&quot;=&quot;*15) print(colored(&quot;More stuff to come soon!&quot;, 'red')) print(&quot;=&quot;*15) mainmenu() def Your_Stuff(): global hunger global player global inventory items = [('eggs', 3), ('mealdeal', 10), ('chicken', 9), ('milk', 2), ('tomatoes', 1), ('cheese', 4), ('apples', 2), ('potatoes', 3), ('beer', 5), ('wine', 8), ('coca-cola', 4)] ask = input(&quot;Choose an option:\n\nA)Show hunger level\nB)Inventory\nC)Quick check\nD)Mainmenu\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if ask == &quot;a&quot;: print(f&quot;Your hunger level is at &quot; + str(hunger)) print(&quot;=&quot;*15) if hunger &lt; 50: print(&quot;You should eat something.&quot;) print(&quot;=&quot;*15) Your_Stuff() elif hunger &gt; 80: print(&quot;You hunger is good!!&quot;) print(&quot;=&quot;*15) Your_Stuff() else: print(&quot;You are just ok!&quot;) print(&quot;=&quot;*15) Your_Stuff() elif ask == &quot;b&quot;: print(f&quot;You have {inventory} in your inventory!&quot;) print(&quot;=&quot;*15) if inventory &gt; []: if hunger &lt; 100: eat = input(&quot;Do you want to eat something?(y/n)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if eat == &quot;y&quot;: nibble = input(&quot;What do you want to eat?(Must be in inventory)\n&gt;&gt;&gt;&quot;).lower().strip() print(&quot;=&quot;*15) if nibble in inventory: for i in items: if nibble == i[0]: print(nibble, 'is going to increase hunger by ' + str(i[1]) + &quot;.&quot;) print(&quot;=&quot;*15) sure = input(f&quot;Are you sure you want to eat the {nibble}?(y/n)&quot;).lower().strip() print(&quot;=&quot;*15) if sure == &quot;y&quot;: print(f&quot;You ate the {nibble} you gained &quot; + str(i[1]) + &quot; hunger.&quot;) print(&quot;=&quot;*15) hunger = hunger + i[1] inventory.remove(nibble) Your_Stuff() hunger2 = hunger + i[1] if hunger2 &gt; 100: print(&quot;You can't eat this because it will increase you hunger beyond 100 hunger! Try and eat something else!&quot;) print(&quot;=&quot;*15) Your_Stuff() elif sure == &quot;n&quot;: Your_Stuff() else: print(&quot;You don't have this item in your inventory.&quot;) print(&quot;=&quot;*15) Your_Stuff() elif eat == &quot;n&quot;: Your_Stuff() else: print(&quot;Invlid input. Try again!&quot;) Your_Stuff() elif hunger &gt;= 100: print(&quot;you are full&quot;) print(&quot;=&quot;*15) Your_Stuff() else: Your_Stuff() else: Your_Stuff() elif ask == &quot;c&quot;: print(colored(f&quot;Your hunger is at {hunger}, Your job_position is {job_position}, Your inventory has {inventory}, Your bank Balance is ${Bank_balance}, Your skill is at {Skill}.&quot;, 'magenta')) print(&quot;=&quot;*15) mainmenu() elif ask == &quot;d&quot;: print(&quot;Going to menu!&quot;) print(&quot;=&quot;*15) mainmenu() else: print(&quot;Invlaid input. Try again!&quot;) print(&quot;=&quot;*15) Your_Stuff() mainmenu() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:56:19.237", "Id": "435478", "Score": "0", "body": "Welcome to Code Review! To raise the intereset in actually looking at your code, you should give a short description on what the game is about and what aspects make it stand out from all the other \"I did this game to learn Python\" posts. Following our site goals, you should then also [update your title to make the question more interesting](/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T22:41:14.117", "Id": "435481", "Score": "0", "body": "@AlexV Thanks for that! I added what the game does and what I have planned for the future of the game! But I don't know what to name the title." } ]
[ { "body": "<p><strong>Wow! What a project!</strong></p>\n\n<p>I had tons of fun working on this! There are a lot of things to like about your code. Instead of going over the general improvements I made, I'm going to explain each part that I changed and why I changed it. </p>\n\n<p><em>Note: I did not touch the</em> <code>threading</code> * and other hunger behavior because I am not confident enough with my ability to improve that. Another answer can possible touch on that.*</p>\n\n<p>Here we go!</p>\n\n<p><strong>Import Statements</strong></p>\n\n<pre><code>import random; import time; import threading; import sys; import psutil; from colorama import init; from termcolor import colored\n</code></pre>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>, this is unconventional. All imports should be on their own line, and ordered alphabetically, with the <code>from .. import ..</code> statements being ordered after.</p>\n\n<pre><code>import psutil\nimport random\nimport sys\nimport time\nimport threading\nfrom colorama import init\nfrom termcolor import colored\n</code></pre>\n\n<p><strong>Job Selection</strong></p>\n\n<p>Your method to choose a job was a whole <strong>332</strong> lines long! That's a lot of code to just select what your profession is. Using a simple <a href=\"https://www.w3schools.com/python/python_dictionaries.asp\" rel=\"nofollow noreferrer\">dict</a>, we can use the names of the jobs as <code>values</code>, and have each <code>abcde</code> option as the <code>key</code>. Using this method, I was about to shrink the method down to <strong>23</strong> lines, <strong>309</strong> lines shorter!</p>\n\n<p><strong>Global Variables</strong></p>\n\n<p>Q: <em>Should you use global variables in your program?</em></p>\n\n<p>A: <strong>90% of the time, <em>NO.</em></strong></p>\n\n<p>It's anyones guess what the right answer is. Using global variables has a plethora of nasty things that can affect your program. <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"nofollow noreferrer\">This document</a> can explain the negative effects of using global variables better than I ever will be.</p>\n\n<p><strong>Method Docstrings</strong></p>\n\n<p>You should include docstrings on the first line of every method you write. This will help documentation identify what your method is supposed to do.</p>\n\n<p><strong>Variable/Method Naming</strong></p>\n\n<p>You should use <code>snake_case</code> and not <code>camelCase</code> or <code>nonexistentcase</code> when naming variables in python.</p>\n\n<p><strong>Main Guard</strong></p>\n\n<p>When running code outside a method/class, it's always good to use a main guard. This is a <a href=\"https://stackoverflow.com/questions/19578308/what-is-the-benefit-of-using-main-method-in-python\">StackOverflow question</a> that helps explain the benefit/use of the guard. An excerpt from the accepted answer:</p>\n\n<blockquote>\n <p>Having a main guard clause in a module allows you to both run code in the module directly and also use procedures and classes in the module from other modules. Without the main guard clause, the code to start your script would get run when the module is imported.</p>\n</blockquote>\n\n<p><strong>Objects</strong></p>\n\n<p>In your code, you have variables like so:</p>\n\n<pre><code>cash = 100\nBank_balance = 0\nhunger = 100\ninventory = []\nSkill = 0\ncount = 0\njob_position = []\n</code></pre>\n\n<p>This code is just screaming to be organized into an object. Having classes, especially in this context of a simulator, can really help the flow of the program, and help you remember what belongs to what. I put the above code into a player class:</p>\n\n<pre><code>class Player:\n \"\"\" Player Class \"\"\"\n\n def __init__(self, name):\n self.name = name\n self.bank_account = BankAccount(self)\n self.cash = 100\n self.hunger = 100\n self.job = None\n self.skill = 0\n self.inventory = []\n self.pin = 0\n\n #Used to calculate bonuses for Teacher, AA, and HR\n self.fulltime_days_worked = 0\n</code></pre>\n\n<p>Now, you have all that code neatly organized into one place.</p>\n\n<p>I also want to touch up on the job selection a bit more. You have tons of if statements and nested if statements explaining and collecting input about if the player wanted to choose that job. You can store all the information about the job into an object as well. Using this method, I was able to neatly organize a <code>list</code> of jobs that would be available for the player to select:</p>\n\n<pre><code>class Job:\n \"\"\" Job Class \"\"\"\n\n def __init__(\n self,\n title,\n pay,\n skill_required,\n working_hours,\n hunger_decrease,\n skill_increase):\n\n self.title = title\n self.pay = pay\n self.skill_required = skill_required\n self.working_hours = working_hours\n self.hunger_decrease = hunger_decrease\n self.skill_increase = skill_increase\n\n def __str__(self):\n return f\"\"\"\n Title: {self.title}\n Pay: ${self.pay}\n Skill Required: {self.skill_required}\n Hours Per Day Working: {self.working_hours}\n Hunger Decrease Per Day: {self.hunger_decrease}\n Skill Increase Per Day: {self.skill_increase}\n \"\"\"\n</code></pre>\n\n<p>Finally, the banking portion of the program can also be organized into an object, storing it's own <code>account_balance</code>, and PIN number (I saw your future plans to implement a PIN and decided to go for it!).</p>\n\n<p><strong>Shop</strong></p>\n\n<p>I could have put this into its own <code>Shop</code> class, and almost did, but I relented. Since the user is really only interacting with the shop through one means, I decided that a method would be good enough. Instead of using <code>tuples</code>, I changed it to a <code>dict</code> again, so I could easily lookup the price of the item with its corresponding name.</p>\n\n<p><strong>Main Menu</strong></p>\n\n<p>Awesome ASCII title! I stored the methods in a <code>dict</code> as well, so instead of having multiple <code>if/elif</code> spam, I could simply match the input with the key in the <code>dict</code>, and call that method.</p>\n\n<p><strong>count_work => determine_bonus</strong></p>\n\n<p>I changed the method name to be more resemblant of what the method is actually doing. Since</p>\n\n<pre><code>count_work(12)\ncount_work(24)\ncount_work(36)\ncount_work(48)\ncount_work(60)\ncount_work(72)\n</code></pre>\n\n<p>is just checking every 12 days, you can use the <a href=\"https://stackoverflow.com/questions/17524673/understanding-the-modulus-operator\">moludo</a> operator to check if it's divisible by 12, like so:</p>\n\n<pre><code># Changed `count` to `fulltime_days_worked` because its more descriptive and\n# that's essentially what `count` was counting\nif (player.fulltime_days_worked % 12) == 0:\n</code></pre>\n\n<p>Below is the refactored code for you. Thank you for posting this, I really had a blast reviewing and rewriting it!</p>\n\n<p><em>Note: If anything doesn't work the way it is supposed to, mention me in a comment and I'll fix it (obviously not the hunger/threading. Because I didn't touch it, it is not included in the final reviewed code. I'll leave it up to you to implement it.). I went through tons of tests through each and every method, and everything was fine, but something could always fall through the cracks</em></p>\n\n<p><strong>Refactored Code</strong></p>\n\n<pre><code>\"\"\" Import Statements\"\"\"\nimport random\nimport time\nimport threading\nimport sys\nimport psutil\nfrom colorama import init\nfrom termcolor import colored\n\ndef main_menu():\n \"\"\" Main Menu of the game \"\"\"\n options = {\n \"a\": player.bank_account.interface,\n \"b\": store,\n \"c\": work,\n \"d\": your_stuff,\n \"e\": more_info,\n \"f\": quit\n }\n print(\"Welcome To the game!\")\n print(\"=\"*15)\n time.sleep(1)\n main = input(\"Where would you like to go?\\nA) The Bank\\nB) Store\\nC) Work\\nD) Inventory\\nE) More information\\nF) Exit\\n&gt;&gt;&gt;\").lower().strip()\n\n if main in list(options.keys()):\n options[main]()\n else:\n print(\"=\"*15)\n print(\"Invalid input. Try again!\")\n print(\"=\"*15)\n main_menu()\n\nclass Job:\n \"\"\" Job Class \"\"\"\n\n def __init__(\n self,\n title,\n pay,\n skill_required,\n working_hours,\n hunger_decrease,\n skill_increase):\n\n self.title = title\n self.pay = pay\n self.skill_required = skill_required\n self.working_hours = working_hours\n self.hunger_decrease = hunger_decrease\n self.skill_increase = skill_increase\n\n def __str__(self):\n return f\"\"\"\n Title: {self.title}\n Pay: ${self.pay}\n Skill Required: {self.skill_required}\n Hours Per Day Working: {self.working_hours}\n Hunger Decrease Per Day: {self.hunger_decrease}\n Skill Increase Per Day: {self.skill_increase}\n \"\"\"\n\nclass Player:\n \"\"\" Player Class \"\"\"\n\n def __init__(self, name):\n self.name = name\n self.bank_account = BankAccount(self)\n self.cash = 100\n self.hunger = 100\n self.job = None\n self.skill = 0\n self.inventory = []\n self.pin = 0\n\n #Used to calculate bonuses for Teacher, AA, and HR\n self.fulltime_days_worked = 0\n\nclass BankAccount:\n \"\"\" Bank Class \"\"\"\n\n def __init__(self, user):\n self.user = user\n self.options = {\n \"a\": self.deposit,\n \"b\": self.withdraw,\n \"c\": self.check_balance,\n \"d\": main_menu\n }\n self.account_balance = 0.00\n\n def interface(self):\n \"\"\" Main interface for the bank \"\"\"\n print(\"=\"*15)\n print(f\"Welcome to Omnibank {self.user.name}.\")\n print(\"=\"*15)\n time.sleep(.01)\n\n #Check if user has set a pin\n if player.pin != 0:\n\n login = input(\"Enter your PIN: \")\n\n if login == player.pin:\n\n while True:\n option = input(\"What will you like to do?\\nA) Deposit\\nB) Withdraw\\nC) Check Balance\\nD) Mainmenu\\n&gt;&gt;&gt;\").lower().strip()\n print(\"=\"*15)\n if option in list(self.options.keys()):\n self.options[option]()\n\n print(colored(\"Invalid PIN!\", \"red\"))\n self.interface()\n\n #Prompt user to set a pin\n pin = input(\"Enter a four digit pin for future logins: \")\n if len(pin) != 4:\n print(colored(\"That was an invalid pin length! Enter again!\", \"red\"))\n self.interface()\n player.pin = pin\n print(colored(\"Your personal pin has been set up!\", \"green\"))\n self.interface()\n\n def deposit(self):\n \"\"\" Bank Deposit Method \"\"\"\n print(f\"Your current cash is ${player.cash}\")\n amount = input(\"How much would you like to deposit?\")\n if float(amount) &gt; self.user.cash:\n print(colored(\"You don't have that much money to deposit!\", \"red\"))\n self.interface()\n self.account_balance += float(amount)\n self.user.cash -= float(amount)\n print(colored(f\"Your account balance is now ${self.account_balance}!\", \"green\"))\n print(colored(f\"Your current cash is now ${self.user.cash}!\", \"green\"))\n self.interface()\n\n def withdraw(self):\n \"\"\" Bank Withdraw Method \"\"\"\n print(f\"Your current account balance is ${player.bank_account.account_balance}\")\n amount = input(\"How much would you like to withdraw?\")\n if float(amount) &gt; self.account_balance:\n print(colored(\"You don't have that much money to withdraw!\", \"red\"))\n self.interface()\n self.account_balance -= float(amount)\n self.user.cash += float(amount)\n print(colored(f\"Your bank balance is now ${self.account_balance}!\", \"green\"))\n print(colored(f\"Your current cash is now ${self.user.cash}!\", \"green\"))\n self.interface()\n\n def check_balance(self):\n \"\"\" Bank Check Balance Method \"\"\"\n print(colored(f\"Your current balance is ${self.account_balance}\", \"green\"))\n\ndef store():\n \"\"\" Method for purchasing items at the store \"\"\"\n\n print(\"Welcome to David's Grocery\")\n print(\"=\"*15)\n\n items = {\n 'eggs': 3.16,\n 'mealdeal': 8,\n 'chicken': 4.38,\n 'milk': 2.60,\n 'tomatoes': 4,\n 'cheese': 3,\n 'apples': 2,\n 'potatoes': 4,\n 'beer': 3.37,\n 'wine': 15,\n 'coca-cola': 1.9\n }\n\n print(\"This is our menu! Take a look around!\")\n print(f\"\"\"\n\n Wine ..... $15.00 ...(+8 hunger)\n Chicken.... $4.38 ...(+9 hunger)\n Coca-Cola ...... $1.92 ...(+4 hunger)\n Milk ..... $2.60 ...(+2 hunger)\n Beer ..... $3.37 ...(+5 hunger)\n Tomatoes ....... $4 ...(+1 hunger)\n MealDeal .... $8.00 ...(+10 hunger)\n Cheese ..... $3.00 ...(+4 hunger)\n Potatoes ...... $4 ...(+3 hunger)\n Apples ....... $2 ...(+2 hunger)\n Eggs ..... $3.16 ... (+3 hunger)\n\n \"\"\")\n\n buy = input(\"Would you like to buy something? (Y/N)\")\n\n if buy.lower() == \"y\":\n item = input(\"Enter item to buy: \").lower()\n if item in list(items.keys()):\n cost = items[item]\n if player.cash &lt; cost:\n print(colored(f\"Not enough money to buy {item}!\", \"red\"))\n store()\n print(colored(f\"{item} bought for ${cost}\", \"green\"))\n player.cash -= cost\n player.inventory.append(item)\n store()\n print(colored(\"Invalid option, choose again!\", \"red\"))\n store()\n main_menu()\n\ndef more_info():\n \"\"\"Displays more information about the game \"\"\"\n\n print(\"=\"*15)\n print(colored(f\"Hey {player.name}, Your objective is to survive as long as possible. You start off with $100 cash and 100 hunger, Go to inventory to see your hunger level and inventory and more!\", 'green'))\n print(\"=\"*15)\n print(colored(\"Your hunger will decrease every 3 minutes by 10 hunger. So make sure to eat!\", 'green'))\n print(\"=\"*15)\n print(colored(\"You can't eat something that will increase your hunger past 100.\", 'green'))\n print(\"=\"*15)\n print(colored(\"You can work to have an income and survive. You can start of as a Cashier and gradually get better paying jobs but each job require a certain amount of skill to get the job! when you recieve your check it will automatically be taxed!\", 'green'))\n print(\"=\"*15)\n print(colored(\"Tax rate is 6.99%!\", 'green'))\n print(\"=\"*15)\n print(colored(\"More stuff to come soon!\", 'red'))\n print(\"=\"*15)\n main_menu()\n\ndef select_job():\n \"\"\" ORIGIONAL METHOD WAS 332 LINES LONG!!!!!!!!!! \"\"\"\n job_titles = {\n \"a\": \"Cashier\",\n \"b\": \"Waitress\",\n \"c\": \"Teacher\",\n \"d\": \"Administrative Assistant\",\n \"e\": \"HR Manager\"\n }\n selected_job = input(\"Select a job\\n\\nA) Cashier\\nB) Waitress\\nC) Teacher\\nD) Administrative assistant\\nE) HR Manager\\n&gt;&gt;&gt;\").lower().strip()\n for job in get_jobs():\n if job.title == job_titles[selected_job]:\n print(job)\n interested = input(\"Would you like this job? (Y/N)\").lower()\n if interested == \"y\":\n if player.skill &gt;= job.skill_required:\n print(colored(f\"You have successfully taken the job of {job.title}!\", \"green\"))\n player.job = job\n main_menu()\n print(colored(\"You don't have enough skill for this job!\", \"red\"))\n select_job()\n print(colored(\"That is an invalid option! Select again!\", \"red\"))\n select_job()\n main_menu()\n\ndef your_stuff():\n \"\"\" Prints all of the players attributes \"\"\"\n print(f\"\"\"\n\n Name: {player.name}\n Hunger Level: {player.hunger}\n Job: {player.job}\n Skill: {player.skill}\n Cash: {player.cash}\n Money In Bank Account: {player.bank_account.account_balance}\n \"\"\")\n print(\"Inventory\")\n for item in player.inventory:\n print(f\"\\t{item}\")\n\ndef work():\n \"\"\" Traversing through another work day \"\"\"\n if player.job is None:\n select_job()\n\n switch_jobs = input(\"Do you want to switch jobs?\").lower()\n if switch_jobs == \"y\":\n select_job()\n\n work_today = input(\"Do you want to work today? (Y/N)\").lower()\n if work_today == \"y\":\n\n if player.job.title == \"Cashier\":\n print(colored(\"You worked hard today! $89 Has Been deposited to your bank account! -10 hunger, +0.5 skills!\", \"green\"))\n tax = round(96 * 0.0699)\n player.bank_account.account_balance += (96 - tax)\n player.hunger -= 10\n player.skill += 0.5\n work()\n\n if player.job.title == \"Waitress\":\n tip = random.randint(0, 100)\n print(colored(f\"You worked hard today! $67 Has Been deposited to your bank account. Your Tip for today is: ${tip}. -10 hunger, +1.5 skills!\", \"green\"))\n tax = round(72 * 0.0699)\n player.bank_account.account_balance += (72 + tip - tax)\n player.hunger -= 10\n player.skill += 1.5\n work()\n\n if player.job.title == \"Teacher\":\n print(colored(f\"You worked hard today! $120 Has Been deposited to your bank account. -10 hunger, +5 skill!\", \"green\"))\n tax = round(120 * 0.0699)\n player.bank_account.account_balance += (120 - tax)\n player.hunger -= 10\n player.skill += 5\n player.fulltime_days_worked += 1\n determine_bonus()\n work()\n\n if player.job.title == \"Administrative Assistant\":\n print(colored(f\"You worked hard today! $176 Has Been deposited to your bank account. -12 hunger, +10 skill!\", \"green\"))\n tax = round(176 * 0.0699)\n player.bank_account.account_balance += 176 - tax\n player.hunger -= 12\n player.skill += 10\n player.fulltime_days_worked += 1\n determine_bonus()\n work()\n\n if player.job.title == \"HR Manager\":\n print(colored(f\"You worked hard today! $210 Has Been deposited to your bank account. -15 hunger, +20 skill!\", \"green\"))\n print(\"=\"*15)\n tax = round(210 * 0.0699)\n player.bank_account.account_balance += 210 - tax\n player.hunger -= 15\n player.skill += 20\n player.fulltime_days_worked += 1\n determine_bonus()\n work()\n main_menu()\n\ndef determine_bonus():\n \"\"\" Used to determine bonuses \"\"\"\n if (player.fulltime_days_worked % 12) == 0:\n bonus = random.randint(500, 3000)\n print(colored(f\"You got a bonus of ${bonus}.\", 'green'))\n player.bank_account.account_balance += bonus\n\ndef get_jobs():\n \"\"\" This method was a pain in my butt!!!!!! \"\"\"\n jobs = []\n jobs.append(Job(\"Cashier\", 12, 0, 8, 10, 0.5))\n jobs.append(Job(\"Waitress\", 9, 10, 8, 10, 1.5))\n jobs.append(Job(\"Teacher\", 15, 50, 8, 10, 5))\n jobs.append(Job(\"Administrative Assistant\", 22, 250, 8, 12, 10))\n jobs.append(Job(\"HR Manager\", 35, 1500, 6, 15, 20))\n return jobs\n\ndef show_slower(str):\n \"\"\" Prints letter by letter \"\"\"\n for char in str:\n time.sleep(0.1)\n sys.stdout.write(char)\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n print(colored(\"\"\"\n\n\n M M ega ga\n mMe imMe imMega g\n imMeg SimMe mMegaS aSi Meg egaSim SimM mM gaS Meg\n imMegaSimMe imM aSi egaSimMe MegaSim SimMe Meg imMegaSimMega\n SimMegaS mMe SimM gaSi ega mMe aSim imMega Meg imM aSi ega\n Sim ga mMe SimMegaSi ega mMe mMegaSim mMegaS Meg imM aSi ega\n Sim ga mMe aSim MegaSimMe imMe aSim MegaS mMeg SimM gaSi ega\n aSim mMegaSimM gaSi egaSimMe SimMe aSim gaSimMega mMeg Sim gaSi egaS\n aSim mMeg SimMegaSi imMe SimMegaSim gaSimMega imMegaSim gaSi egaS\n gaSim mMeg imMegaS Me SimMe imMegaSim gaSimMe imMegaSim gaSi egaS\n mMegaSimM\n mMegaSim\n\n \"\"\", 'yellow'))\n init() #colorama\n shutdown = psutil.Process() #psutil\n name = input(\"Enter your name! \")\n player = Player(name)\n\n time.sleep(1)\n show_slower(\"Loading............\\n\")\n time.sleep(1)\n show_slower(\"Initializing.............\\n\")\n time.sleep(1)\n show_slower(\"Done\\n\")\n\n main_menu()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T19:14:49.287", "Id": "435627", "Score": "0", "body": "Thank you so much for reviewing and rewriting the code. it was very informative and I will learn how to use and implement it in future code! I need to learn how to use classes and this is a great starting point for that! Thank you again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T19:30:24.980", "Id": "435630", "Score": "0", "body": "There are two things that don't work. 1) unable to consume the item in your inventory to increase hunger. It just shows what's in your inventory 2) Unable to choose another job or switch jobs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T19:35:18.380", "Id": "435631", "Score": "0", "body": "@JoshuaTorres As mentioned, I did not touch the hunger portion of your program so it is not included in the program. I edited code to allow you to switch jobs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T21:49:59.110", "Id": "435910", "Score": "4", "body": "PEP8's [section on imports](https://www.python.org/dev/peps/pep-0008/#imports) has no notion on ordering them alphabetically, only that you should group them meaningfully. So it's basically up to you how to order your imports, someone else may prefer to order them by the length of their name ;-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T09:09:12.150", "Id": "224543", "ParentId": "224507", "Score": "5" } } ]
{ "AcceptedAnswerId": "224543", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T21:40:08.523", "Id": "224507", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "game" ], "Title": "Sim survival game" }
224507