body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a dataset of video frames in a folder with the directory structure looking like this:</p> <pre><code>-parent -video_id -frame0 -frame1 -... </code></pre> <p>My code, gathering frames into a Pytorch dataset and splitting them up into patches is quite slow in the <code>__init__</code> method/phase when scaled up to quite a lot of frames/videos. Might there be a more efficient way to create the dataset?</p> <p>Code:</p> <pre><code>class Dataset(torch.utils.data.Dataset): def __init__(self, directory='../data/*', get_subdirs=True, size=(16,16), max_ctx_length=4096, dry_run=False): print(&quot;Loading dataset...&quot;) self.data = glob.glob(directory) if get_subdirs: data_temp = [] for p, i in enumerate(self.data): print(&quot;Loading data from {0}. {1} more to go...&quot;.format(i, len(self.data)-p)) file_data = glob.glob(i+&quot;/*&quot;) file_data.sort(key=lambda r: int(''.join(x for x in r if (x.isdigit())))) #This sort... data_temp.extend(file_data) if dry_run: break self.data = data_temp self.max_ctx_length = max_ctx_length self.size = size def __len__(self): return len(self.data)*self.size[0]-self.max_ctx_length-1 def __getitem__(self, key): frame_start = int(np.floor(key / self.size[0])) patch_start = int(np.mod(key, self.size[0])) patches = [] i_frame = frame_start while len(patches) &lt;= self.max_ctx_length+1: frame = (Tvio.read_image(self.data[i_frame], mode=Tvio.ImageReadMode.RGB).float() / 255).unsqueeze(0) if len(patches) == 0: patches.extend(F.unfold(frame, self.size, stride=self.size).transpose(1,2).split(1,1)[patch_start:]) else: patches.extend(F.unfold(frame, self.size, stride=self.size).transpose(1,2).split(1, 1)) i_frame += 1 patches = patches[:self.max_ctx_length+1] data_x = patches[0:-1] data_y = patches[1:] return torch.cat(data_x, dim=1).squeeze(0), torch.cat(data_y, dim=1).squeeze(0) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T06:09:23.950", "Id": "266115", "Score": "0", "Tags": [ "performance", "image", "video", "pytorch" ], "Title": "Pytorch Video Frames Dataset Implementation" }
266115
<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>let array = [1,7,2,2,3,7,4]; while(array.length){ // get last item let item = array.pop() // remove duplicates const filteredArray = array.filter(content =&gt; content!==item); // if filteredArray had duplicate items then log the item if ( filteredArray.length !== array.length) console.log(item) array = filteredArray }</code></pre> </div> </div> </p> <p>This code is to find elements that have duplicate entries. Is this code optimized and what is the complexity or execution time of this.</p> <p>is there a better way to do this , i am really stuck in understanding how to determine complexity</p>
[]
[ { "body": "<p><strong>Time complexity is calculated as the worst case condition:</strong></p>\n<p>Here the while loop <strong>can loop &quot;n&quot; times max</strong> ( case where there are no repeating elements )</p>\n<p>each statement inside while loop <strong>expect array.filter has complexity of 0(1)</strong> so we can ignore it (Because these are just constant linear operations so complexity is always 0(1) )</p>\n<p>While the <strong>array.filter as a time complexity of 0(n-1)</strong> [After removing last item] which when constants are removed becomes 0(n)</p>\n<p>so the total time complexity of this equation becomes (while loop complexity * filter complexity) as they are nested loop operation</p>\n<p><strong>so the final answer is 0(n^2)</strong></p>\n<p>Also we should consider <strong>space complexity</strong> .</p>\n<p>in the solution in question ,there is an intermittent variable called filteredArray which will have max length of &quot;n&quot; (in case of no duplicate element) so space complexity is 0(n) ( as it needs space in memory for each item in array)</p>\n<p>so total space complexity will be</p>\n<pre><code>array (0(n)) + item(0(1)) + filteredArray(0(n)) = 0(n)\n</code></pre>\n<p><strong>Better solution:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> const arry = [1,7,2,2,3,7,4];\n \n const toFindDuplicates = arry =&gt; arry.filter((item, index, arr) =&gt; arr.indexOf(item) !== index)\n const duplicateElements = toFindDuplicates(arry);\n console.log(duplicateElements);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Has time complexity of <strong>O(n^2)</strong> due to indexof and filter functions</p>\n<p><strong>Space complexity</strong></p>\n<p>here tofindDuplicates is a function so 0(1) , duplicateElements will have max n/2 duplicates</p>\n<pre><code>array (0(n)) + toFindDuplicates 0(1) + duplicateElements (0(n/2)) = 0(n)\n</code></pre>\n<p><strong>Best approach:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>array = [1, 7, 2, 2, 3, 7, 4]\narray.sort(function (a, b) {\n return a - b;\n});\n\nconst duplicateEntries = array.filter((element, index, array) =&gt; {\n if (index !== 0) {\n const nextElement = array[index + 1]\n const previousElement = array[index - 1]\n return nextElement !== element &amp;&amp; previousElement === element\n }\n})\n\nconsole.log(duplicateEntries)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Here time complexity is</strong></p>\n<pre><code>array.sort(nlog(n)) + filter(n) = O(n)+O(nlogn) = O(nlogn)\n</code></pre>\n<p><strong>space complexity is :</strong></p>\n<pre><code>O(n/2) = O(n) which is the worst for duplicate entries\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T08:43:38.947", "Id": "525735", "Score": "3", "body": "The example snippet you provide is \\$O(n^2)\\$ not \\$O(n)\\$ because you have `indexOf` inside the filter which must iterate the array to locate a duplicate, so if there are no duplicates for each item you check each item for a match. You can use a `set` to make the function \\$O(n)(\\$ eg `const a = new Set(), dups = []; array.forEach(item => a.has(item) ? dups.push(item) : a.add(item)); console.log(dups); // >> array of duplicated items`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T09:07:52.607", "Id": "525736", "Score": "0", "body": "@Blindman67 thank you so much so both the question and answer has the same time complexity ? there is no added benefit than space complexity for the approach in answer ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T13:17:54.293", "Id": "525755", "Score": "0", "body": "@Blindman67 thanks for the help , updated the answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T13:18:06.403", "Id": "525756", "Score": "0", "body": "the answer you mentioned is not working" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T18:01:01.350", "Id": "525790", "Score": "0", "body": "Note the I named the array `array` rather than `arry`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:14:45.110", "Id": "525801", "Score": "0", "body": "@Blindman67 ya but the issue is that the out put prints 2,2,7" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:15:15.800", "Id": "525802", "Score": "0", "body": "Any comments on the nlogn approach" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:35:08.107", "Id": "525805", "Score": "1", "body": "For me it outputs `[2, 7]` You are correct using the sort and then locating neighboring duplicates has time \\$O(nlogn)\\$ and space \\$O(n)\\$" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T11:06:19.950", "Id": "525846", "Score": "0", "body": "Thank you so much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T11:07:14.737", "Id": "525847", "Score": "0", "body": "@Blindman67 also one more question , you are using a.has() doesn't taht has O(n) complexity which makes your approach same as O(n^2)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T17:28:55.490", "Id": "525880", "Score": "2", "body": "`Set`, `Map`, `WeakSet`, and `WeakMap` are [hash maps](https://en.wikipedia.org/wiki/Hash_table) as are `Object`s and sparse `Array`s. A unique hash is generated from each entry which is then is used to index the entry. That makes hash maps \\$O(1)\\$ time for searches. Note that WC3 JS standard does not dictate how to implement Hash maps. The highly competitive vendor market has helped ensure that hash maps use the optimal algorithms in all but the most obscure implementations (browsers)" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T21:34:11.697", "Id": "266146", "ParentId": "266120", "Score": "1" } }, { "body": "<p>Consider there may be cases where altering the input array is undesirable - be careful when calling methods like <code>pop</code> or <code>sort</code> as they modify the input array.</p>\n<p>Another option is to use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\"><code>Map()</code></a> to store the counts of each number. This allows lookups of values in constant time. Then after the counts are stored in the map the entries in the map can be filtered to only those that have a value greater than 1 and mapped to get the key of those values.</p>\n<p>A plain-old JavaScript object (i.e. POJO) could also be used (e.g. like in <a href=\"https://codereview.stackexchange.com/q/176262/120114\">this similar code</a>). However <a href=\"https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order\">iteration order might not be preserved</a> since the keys would be numeric.</p>\n<p>In the snippet below note that <code>const</code> is used for all variables since they are never re-assigned. This can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const array = [1, 7, 2, 2, 3, 7, 4];\nconst values = new Map();\nfor (const value of array) {\n values.set(value, (values.get(value) || 0) + 1);\n}\n\nconst filteredValues = [...values].filter(([key, value]) =&gt; value &gt; 1)\n .map(([k, v]) =&gt; k);\nconsole.log(filteredValues)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T08:04:44.193", "Id": "528680", "Score": "0", "body": "Thank you so much for the answer , could you explain why did you use value = new map() instead of values = [...array]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T18:16:54.453", "Id": "528702", "Score": "0", "body": "As was mentioned in [the comment by blindman67](https://codereview.stackexchange.com/questions/266120/getting-items-that-have-more-than-one-entry-in-the-array-with-optimized-code/268101?noredirect=1#comment525880_266146) last month it is a hash map- it allows for lookups in constant time i.e. \\$O(n)\\$. Using `values = [...array]` would just copy the values into a new array" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T22:06:48.203", "Id": "268101", "ParentId": "266120", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T09:12:20.757", "Id": "266120", "Score": "-2", "Tags": [ "javascript", "performance", "functional-programming", "ecmascript-6", "complexity" ], "Title": "Getting items that have more than one entry in the array with optimized code" }
266120
<p>I have multiples measurements and I want to render it into tables like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Measurements</th> <th></th> <th></th> <th>Operator</th> <th>browsings</th> <th></th> <th></th> <th>FTP DL</th> <th></th> <th></th> <th>FTP UL</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>Location</td> <td>Event</td> <td>Date</td> <td>Operator</td> <td>avg</td> <td>min</td> <td>max</td> <td>avg</td> <td>min</td> <td>max</td> <td>avg</td> <td>min</td> <td>max</td> </tr> <tr> <td></td> <td></td> <td></td> <td>Verizon</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td>USCell</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td>T-Mobile</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>for each measurement rendered there is always 3 operator</p> <p>the operator is fixed/determined value they are <code>[&quot;Verizon&quot;, &quot;USCell&quot;, &quot;T-Mobile&quot;]</code></p> <p>my current approach is to use multiple loop and using <code>where</code> clause to achieve this</p> <p><code>measurements/index.html.erb</code></p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th colspan=&quot;3&quot;&gt;Measurement&lt;/th&gt; &lt;th colspan=&quot;3&quot;&gt;FTP DL&lt;/th&gt; &lt;th colspan=&quot;3&quot;&gt;FTP UL&lt;/th&gt; &lt;th colspan=&quot;3&quot;&gt;Browsing&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Location&lt;/th&gt; &lt;th&gt;Event&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Average Browsing Speed (Mbps)&lt;/th&gt; &lt;th&gt;Minimum Browsing Speed (Mbps)&lt;/th&gt; &lt;th&gt;Maximum Browsing Speed (Mbps)&lt;/th&gt; &lt;th&gt;Average FTP Download Speed (Mbps)&lt;/th&gt; &lt;th&gt;Minimum FTP Download Speed (Mbps)&lt;/th&gt; &lt;th&gt;Maximum FTP Download Speed (Mbps)&lt;/th&gt; &lt;th&gt;Average FTP Upload Speed (Mbps)&lt;/th&gt; &lt;th&gt;Minimum FTP Upload Speed (Mbps)&lt;/th&gt; &lt;th&gt;Maximum FTP Upload Speed (Mbps)&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;% @measurements.each do |measurement| %&gt; &lt;% @operators.each do |operator| %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= measurement.location %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.event %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.date %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= operator %&gt;&lt;/td&gt; &lt;% if measurement.browsings.where(operator: operator).any? %&gt; &lt;td&gt;&lt;%= measurement.browsings.where(operator: operator).first.avg %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.browsings.where(operator: operator).first.min %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.browsings.where(operator: operator).first.max %&gt;&lt;/td&gt; &lt;% else %&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;% end %&gt; &lt;% if measurement.ftp_dls.where(operator: operator).any? %&gt; &lt;td&gt;&lt;%= measurement.ftp_dls.where(operator: operator).first.avg %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.ftp_dls.where(operator: operator).first.min %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.ftp_dls.where(operator: operator).first.max %&gt;&lt;/td&gt; &lt;% else %&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;% end %&gt; &lt;% if measurement.ftp_uls.where(operator: operator).any? %&gt; &lt;td&gt;&lt;%= measurement.ftp_uls.where(operator: operator).first.avg %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.ftp_uls.where(operator: operator).first.min %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= measurement.ftp_uls.where(operator: operator).first.max %&gt;&lt;/td&gt; &lt;% else %&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;% end %&gt; &lt;/tr&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I'm wondering if I could avoid using multiple loop and where clause on my code to achieve this?</p> <p>because I think using multiple loop and where approach considered it as bad practices, isn't it?</p> <p>I'm thinking since I have multiple repeated <code>operator</code> I could use that as a group or something, I'm thinking about joining all my <code>has_many</code> and group them by using <code>group_by operator</code> but I don't know how to do it yet (need a little guidance there if its really possible and good approach)</p> <p>here are my others code</p> <p><code>measurement.rb</code></p> <pre><code>class Measurement &lt; ApplicationRecord has_many :ftp_uls, dependent: :destroy has_many :ftp_dls, dependent: :destroy has_many :browsings, dependent: :destroy end </code></pre> <p><code>measurement_controller.rb</code></p> <pre><code>class MeasurementsController &lt; ApplicationController before_action :authenticate_user!, only: [:index, :show] before_action :set_measurement, only: %i[ show edit update destroy ] def index @measurements = Measurement.all @operators = [&quot;Verizon&quot;, &quot;USCell&quot;, &quot;T-Mobile&quot;] end end </code></pre> <p><code>schema.rb</code></p> <pre><code>ActiveRecord::Schema.define(version: 2021_08_17_062327) do # These are extensions that must be enabled in order to support this database enable_extension &quot;plpgsql&quot; create_table &quot;browsings&quot;, force: :cascade do |t| t.bigint &quot;measurement_id&quot;, null: false t.string &quot;operator&quot; t.decimal &quot;avg&quot; t.decimal &quot;min&quot; t.decimal &quot;max&quot; t.index [&quot;measurement_id&quot;], name: &quot;index_browsings_on_measurement_id&quot; end create_table &quot;ftp_dls&quot;, force: :cascade do |t| t.bigint &quot;measurement_id&quot;, null: false t.string &quot;operator&quot; t.decimal &quot;avg&quot; t.decimal &quot;min&quot; t.decimal &quot;max&quot; t.index [&quot;measurement_id&quot;], name: &quot;index_ftp_dls_on_measurement_id&quot; end create_table &quot;ftp_uls&quot;, force: :cascade do |t| t.bigint &quot;measurement_id&quot;, null: false t.string &quot;operator&quot; t.decimal &quot;avg&quot; t.decimal &quot;min&quot; t.decimal &quot;max&quot; t.index [&quot;measurement_id&quot;], name: &quot;index_ftp_uls_on_measurement_id&quot; end create_table &quot;measurements&quot;, force: :cascade do |t| t.string &quot;location&quot; t.string &quot;event&quot; t.date &quot;date&quot; end end </code></pre>
[]
[ { "body": "<p>there is many way to refactor this</p>\n<p>first change operator into integer/enum instead string, or change operator to become an object/table instead with a <code>name</code> and <code>order</code> column</p>\n<p>so that we can sort the browsings/ftpdl/ftp ul using <code>operator</code> column more easier</p>\n<p>then to simplify the loop and query we can transform it into and array first then render the table row/data from that array</p>\n<p>the new <code>measurement_controller.rb</code> <code>index</code> method would be like this</p>\n<pre><code>def index\n @measurements = Measurement.all #we could also add eager loading here \n #Measurement.all.includes(:browsings, :ftp_dls, :ftp_uls)\n @rows = []\n @measurements.each do |measurement|\n row = []\n Operator.all.each_with_index do |operator, index|\n row &lt;&lt; [measurement.location, measurement.event, measurement.date, operator.name]\n end\n measurement.browsings.each_with_index do |browsing, index|\n row[index].concat([browsing.avg, browsing.min, browsing.max])\n end \n measurement.ftp_dls.each_with_index do |ftp_dl, index| \n row[index].concat([ftp_dl.avg, ftp_dl.min, ftp_dl.max])\n end\n measurement.ftp_uls.each_with_index do |ftp_ul, index|\n row[index].concat([ftp_ul.avg, ftp_ul.min, ftp_ul.max])\n end\n @rows &lt;&lt; row\n end \n @rows = @rows.flatten(1)\nend\n</code></pre>\n<p>the new <code>measurements/index.html.erb</code> <code>&lt;tbody&gt;</code> table render would be like this</p>\n<pre><code>&lt;tbody&gt;\n &lt;% @rows.each do |row|%&gt;\n &lt;tr&gt;\n &lt;% row.each do |data| %&gt;\n &lt;td&gt;&lt;%= data %&gt;&lt;/td&gt;\n &lt;% end %&gt;\n &lt;/tr&gt;\n &lt;% end%&gt;\n&lt;/tbody&gt;\n</code></pre>\n<p>I think it will perform faster than the code before and the code is more readable and also we avoid loop inside loop idk but people said loop inside loop is bad</p>\n<p>I just test it and in my use case it reduce the load time from <code>266693.0 ms</code> to <code>13103.0 ms</code> and to <code>7432.4 ms</code> with eager loading</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T08:24:17.890", "Id": "526223", "Score": "0", "body": "why the downvotes? can you give me some comment/edit suggestion?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T17:05:05.823", "Id": "526389", "Score": "0", "body": "So - this code doesn't work. Even if you order by operator, unless we know that 100% of the data exists for each operator and measurement (which your initial code assumes is not the case) then the operators won't always be at the same index. For example, if you order \"Verizon\", \"USCell\", \"T-Mobile\" but there's no \"Verizon\" data then it would be \"USCell\" with `index:0`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T17:09:32.690", "Id": "526391", "Score": "0", "body": "Another issue is that if you use eager-load it joins measurements to browsings to ftp_uls to ftp_dls, you're doing: measurement x 3 browsings x 3 ftp_uls x3 ftp_dls, so you're creating a table 27x larger than the measurements table (9x larger than necessary) and then rails is going through the results and de-duping the rows. This is all very costly/time intensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T17:12:10.443", "Id": "526392", "Score": "0", "body": "Even if you fix the logical problem and ensure that it's building a nested array - there's a big implicit coupling of the order of the columns in the view / table to the positional order of the fields you're putting into each row. It's impossible to know why the fields are added in that order unless you know the order of the columns in the view. This is makes our backend implementation tightly coupled to the front-end, which is bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T06:07:36.257", "Id": "526421", "Score": "0", "body": "ok I'll refactor it later" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T09:24:05.470", "Id": "266316", "ParentId": "266122", "Score": "-2" } }, { "body": "<p>So, the first problem I'd try to address is that you're running SQL queries in your views. This is generally considered a bad practice (and there are helpful gems/frameworks that will throw errors if you try to do this).</p>\n<p>The second major issue is the # of sql queries being run, as we're executing multiple queries for each measurement (1+N problem). This is the source of your performance issue in both the original example and your updated code.</p>\n<p>Ideally you want all the relevant data to be loaded in a small number of SQL queries ahead of time.</p>\n<p>It looks like you want 1 row per measurement per operator (is that right?). This is not easy to do with your current database schema. I've added a sql query that builds this but it's complex. This could be a great use case for a SQL view with an activerecord object on top of it.</p>\n<p>I'm also assuming you only have at most 1 row per measurement + operator combo in the browsings/ftp_dls/ftp_uls tables. If this is correct, I'd add a unique index to enforce this on each table. If there could be multiple rows per operator and measurement then you'll need to adjust the SQL or this will return duplicate rows.</p>\n<p>So I'd start by building SQL queries that generates the data you want. Something like...</p>\n<pre><code>@operators = [&quot;Verizon&quot;, &quot;USCell&quot;, &quot;T-Mobile&quot;]\n\n# You don't need to hard-code the operators but I thought it made\n# the SQL easier to understand\noperator_join_sql = &lt;&lt;-SQL\n INNER JOIN (('Verizon'),('USCell'),('T-Mobile')) \n AS operators(name) \n ON true\nSQL\nbrowsings_join_sql = &lt;&lt;-SQL\n LEFT OUTER JOIN browsings ON browsings.operator = operators.name \n AND browsings.measurment_id = measurements.id\nSQL\nftp_uls_join_sql = &lt;&lt;-SQL\n LEFT OUTER JOIN ftp_uls ON ftp_uls.operator = operators.name \n AND ftp_uls.measurment_id = measurements.id\nSQL\nftp_dls_join_sql = &lt;&lt;-SQL\n LEFT OUTER JOIN ftp_dls ON ftp_dls.operator = operators.name \n AND ftp_dls.measurment_id = measurements.id\nSQL\nselect_sql = &lt;&lt;-SQL\n SELECT measurements.*\n , operators.name AS operator\n , browsings.avg AS ftp_urls_avg\n , browsings.min AS ftp_urls_min\n , browsings.max AS ftp_urls_max\n , ftp_urls.avg AS ftp_urls_avg\n , ftp_urls.min AS ftp_urls_min\n , ftp_urls.max AS ftp_urls_max\n , ftp_drls.avg AS ftp_drls_avg\n , ftp_drls.min AS ftp_drls_min\n , ftp_drls.max AS ftp_drls_max\nSQL\n\n@measurement_by_operator = @measurements.select(select_sql)\n .joins(operator_join_sql)\n .joins(browsings_join_sql)\n .joins(ftp_uls_join_sql)\n .joins(ftp_dls_join_sql)\n</code></pre>\n<p>Then, in your view, you would do:</p>\n<pre><code>&lt;% @measurement_by_operator.each do |measurement| %&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;%= measurement.location %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.event %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.date %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.operator %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.browsings_avg %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.browsings_min %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.browsings_max %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.ftp_uls_avg %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.ftp_uls_min %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.ftp_uls_max %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.ftp_dls_avg %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.ftp_dls_min %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.ftp_dls_max %&gt;&lt;/td&gt;\n &lt;/ul&gt;\n&lt;% end %&gt;\n</code></pre>\n<h3>---- EDIT ----</h3>\n<p>Some additional thoughts on your data schema...</p>\n<p>Your three tables (browsings, ftp_uls, fpt_dls) have identical schema. They could be a single table (e.g. &quot;measurement_readings&quot; with a a &quot;type&quot; column, for example).</p>\n<p>While the first approach I'm suggesting is probably best, it's fairly advanced. With the readings in a single table, there's an alternative that might be more approachable and still reasonable. Something like:</p>\n<p><strong>In your model (or better, a helper or presenter!)</strong></p>\n<pre><code>class Measurement\n def for(operator, type)\n measurement_readings.detect{|mr| mr.operator == operator &amp;&amp; mr.type == type } || NullMeasurementReading.new\n end\nend\n# A `NullMeasurementReading` is just a nullobject pattern. Could be a PORO or subclass of MeasurementReading or whatever.\n# Alternatively use `&amp;.` in the view.\n# We're using `detect` here because we expect the array of readings to already be loaded \n# and explicitly *do not* want to trigger SQL queries\n</code></pre>\n<p><strong>your controller</strong></p>\n<pre><code>@measurements = @measurements.preload(:measurement_readings)\n</code></pre>\n<p><strong>in the view</strong></p>\n<pre><code>&lt;% @measurements.each do |measurement| %&gt;\n &lt;% operators.each do |operator| %&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;%= measurement.location %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.event %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.date %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= operator %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= measurement.for(operator, 'browsings').avg %&gt;\n &lt;td&gt;&lt;%= measurement.for(operator, 'browsings').min %&gt;\n &lt;td&gt;&lt;%= measurement.for(operator, 'browsings').max %&gt;\n &lt;%# etc.. %&gt;\n &lt;/tr&gt;\n &lt;% end %&gt;\n&lt;% end %&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T06:18:07.807", "Id": "526423", "Score": "0", "body": "yes I want 1 row per measurement per operator, should I change my database schema then? and yes it also unique 1 measurement only have 3 operator for each type of measurement" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T16:07:12.270", "Id": "526593", "Score": "0", "body": "Your current database schema makes rendering this report difficult (an issue can be addressed fairly well with a view). It may make other things easy. Evaluating what database schema is best for an application is difficult, and changes over time as the needs of the application change. It's impossible for me to say." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T16:09:09.273", "Id": "526594", "Score": "0", "body": "That having been said - having three tables with identical column names/types is definitely a design-smell to me and I'd be quick to refactor those into a single table with a type field. If you want different activerecord models (although I'd question why) you can use STI and keep them separate." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T16:54:45.243", "Id": "266450", "ParentId": "266122", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T10:29:23.137", "Id": "266122", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "database", "postgresql" ], "Title": "Querying and rendering an HTML table of ISP performance statistics" }
266122
<p><strong>Description</strong></p> <p>It is valid to say, this work started and evolved from a standalone DQN implementation, which I included in an old <a href="https://codereview.stackexchange.com/questions/253886/playing-pong-atari-game-using-a-dqn-agent">question</a>, to a mini-library <a href="https://github.com/schissmantics/xagents" rel="nofollow noreferrer">xagents</a>, housing 7 re-usable tensorflow-based implementations of DRL algorithms. Due to the medium-sized codebase ~= 6k lines, it cannot be included in a single post due to character limits. Therefore, I'll break down the code into smaller logical components, that can be named, contained and reviewed separately, and I'll try to make it less boring and more interactive as much as I can.</p> <p><strong>Demo</strong></p> <p>Let me walk you through the features interactively ...</p> <p><strong>1. Installation</strong></p> <p>I am assuming you have python3.8+, virtualenv, and git installed and you're on some unix shell. Please run the following in terminal:</p> <pre><code>mkdir xagent-demo cd xagent-demo virtualenv demo-env source demo-env/bin/activate git clone https://github.com/schissmantics/xagents pip install xagents/ </code></pre> <p>Which should take a few minutes, then you can verify the installation by running:</p> <pre><code>&gt;&gt;&gt; xagents xagents 1.0 Usage: xagents &lt;command&gt; &lt;agent&gt; [options] [args] Available commands: train Train given an agent and environment play Play a game given a trained agent and environment tune Tune hyperparameters given an agent, hyperparameter specs, and environment Use xagents &lt;command&gt; to see more info about a command Use xagents &lt;command&gt; &lt;agent&gt; to see more info about command + agent </code></pre> <p>Use the syntax demonstrated above if you want to learn more about command and agent options. For example, to know A2C training options, run <code>xagents train a2c</code>, which should display respective options.</p> <p><strong>2. Training</strong></p> <p>Let's train a PPO agent on OpenAI gym's <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiruYnk2LfyAhXEZs0KHfkoBG8QtwJ6BAgOEAM&amp;url=https%3A%2F%2Fgym.openai.com%2Fenvs%2FCartPole-v1&amp;usg=AOvVaw1FyWyOvJWzIa5iBqUtPgWi" rel="nofollow noreferrer">CartPole-v1</a> environment to get a target reward of 250. It shouldn't take more than 2-3 mins to train on cpu. Please run the following command in terminal:</p> <pre><code>xagents train ppo --env CartPole-v1 --target-reward 250 --n-envs 16 --n-steps 1024 --checkpoints ppo-cartpole.tf --history-checkpoint ppo-cartpole.parquet --seed 123 </code></pre> <p>After the training is complete, you should see a <code>Reward achieved in 376832 steps</code>. There will be some resulting checkpoint files, which we will use later in the next steps.</p> <p><strong>3. Visualize training history</strong> Visualizing the training is not currently available from the command line, therefore you need to run python interactively, then run the following:</p> <pre><code>from xagents.utils.common import plot_history import matplotlib.pyplot as plt plot_history(['ppo-cartpole.parquet'], ['PPO'], 'CartPole-v1', history_interval=100) plt.show() </code></pre> <p><strong>Which should display:</strong></p> <p><a href="https://i.stack.imgur.com/mLoR5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mLoR5.png" alt="ppo-cartpole-curve" /></a></p> <p><strong>4. Play game</strong></p> <p>Now we will use the weight checkpoints that resulted from the training earlier to play one episode of cartpole. Please run the following in terminal:</p> <pre><code>xagents play ppo --env CartPole-v1 --render --weights ppo-cartpole.tf --video-dir video </code></pre> <p>which will display the episode being played by the trained PPO agent, and result in the following vid (I manually converted it to gif to upload here):</p> <p><a href="https://i.stack.imgur.com/y3gbs.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y3gbs.gif" alt="gameplay" /></a></p> <p>That's not all, there are other features including hyperparameter tuning which I will be discussing in other posts with the respective code. For more info, feel free to check the project <a href="https://github.com/schissmantics/xagents#xagents---reusable-scalable---performant-reinforcement-learning-algorithms-in-tf2" rel="nofollow noreferrer">README</a> whenever you need to.</p> <p><strong>Project architecture</strong></p> <pre><code>xagents ├── LICENSE ├── MANIFEST.in ├── README.md ├── img │   ├── bipedal-walker.gif │   ├── breakout.gif │   ├── carnival.gif │   ├── gopher.gif │   ├── lunar-lander.gif │   ├── pacman.gif │   ├── param-importances.png │   ├── pong.gif │   ├── step-benchmark.jpg │   ├── time-benchmark.jpg │   └── wandb-agents.png ├── requirements.txt ├── scratch_commands.sh ├── setup.py └── xagents ├── __init__.py ├── a2c │   ├── __init__.py │   ├── agent.py │   ├── cli.py │   └── models │   ├── ann-actor-critic.cfg │   └── cnn-actor-critic.cfg ├── acer │   ├── __init__.py │   ├── agent.py │   ├── cli.py │   └── models │   └── cnn-actor-critic.cfg ├── base.py ├── cli.py ├── ddpg │   ├── __init__.py │   ├── agent.py │   ├── cli.py │   └── models │   ├── ann-actor.cfg │   └── ann-critic.cfg ├── dqn │   ├── __init__.py │   ├── agent.py │   ├── cli.py │   └── models │   └── cnn.cfg ├── ppo │   ├── __init__.py │   ├── agent.py │   ├── cli.py │   └── models │   ├── ann-actor-critic.cfg │   └── cnn-actor-critic.cfg ├── td3 │   ├── __init__.py │   ├── agent.py │   ├── cli.py │   └── models │   ├── ann-actor.cfg │   └── ann-critic.cfg ├── tests │   ├── __init__.py │   ├── conftest.py │   ├── test_base.py │   ├── test_buffers.py │   ├── test_cli.py │   ├── test_common_utils.py │   ├── test_tuning.py │   └── utils.py ├── trpo │   ├── __init__.py │   ├── agent.py │   ├── cli.py │   └── models │   ├── ann-actor.cfg │   ├── ann-critic.cfg │   ├── cnn-actor.cfg │   └── cnn-critic.cfg └── utils ├── __init__.py ├── buffers.py ├── cli.py ├── common.py └── tuning.py </code></pre> <p>For those with no RL background, there are 2 types of learning: on-policy and off-policy. For more info about the terms, you can check this <a href="https://stats.stackexchange.com/questions/184657/what-is-the-difference-between-off-policy-and-on-policy-learning">question</a> which should clarify what these are. All implemented agents inherit from 2 base agents: <code>OnPolicy</code> and <code>OffPolicy</code>. Both inherit from <code>BaseAgent</code> and all are included in base.py which is the subject of this post. All agents inheriting from these classes must implement <code>train_step()</code> abstract method, which defines one train step logic. All agents share <code>play()</code> method which is called to play one episode as demonstrated above. Also, they share <code>fit()</code> method which runs the training loop and is called for training an agent. The rest of the implemented methods are helper methods, and you can check the docstrings to understand what they do.</p> <p>Here's a function definition you will need:</p> <pre><code>import pyarrow as pa import pyarrow.parquet as pq def write_from_dict(_dict, path): &quot;&quot;&quot; Write to .parquet given a dict Args: _dict: Dictionary of label: [scalar] path: Path to .parquet fiile. Returns: None &quot;&quot;&quot; table = pa.Table.from_pydict(_dict) pq.write_to_dataset(table, root_path=path, compression='gzip') </code></pre> <p>base.py</p> <pre><code>import os import random from abc import ABC from collections import deque from datetime import timedelta from pathlib import Path from time import perf_counter, sleep import cv2 import gym import numpy as np import optuna import pandas as pd import tensorflow as tf import wandb from gym.spaces.box import Box from gym.spaces.discrete import Discrete from xagents.utils.common import write_from_dict class BaseAgent(ABC): &quot;&quot;&quot; Base class for various types of agents. &quot;&quot;&quot; def __init__( self, envs, model, checkpoints=None, reward_buffer_size=100, n_steps=1, gamma=0.99, display_precision=2, seed=None, log_frequency=None, history_checkpoint=None, plateau_reduce_factor=0.9, plateau_reduce_patience=10, early_stop_patience=3, divergence_monitoring_steps=None, quiet=False, trial=None, ): &quot;&quot;&quot; Initialize base settings. Args: envs: A list of gym environments. model: tf.keras.models.Model that is expected to be compiled with an optimizer before training starts. checkpoints: A list of paths to .tf filenames under which the trained model(s) will be saved. reward_buffer_size: Size of the reward buffer that will hold the last n total rewards which will be used for calculating the mean reward. n_steps: n-step transition for example given s1, s2, s3, s4 and n_step = 4, transition will be s1 -&gt; s4 (defaults to 1, s1 -&gt; s2) gamma: Discount factor used for gradient updates. display_precision: Decimal precision for display purposes. seed: Random seed passed to random.seed(), np.random.seed(), tf.random.seed(), env.seed() log_frequency: Interval of done games to display progress after each, defaults to the number of environments given if not specified. history_checkpoint: Path to .parquet file to which episode history will be saved. plateau_reduce_patience: int, Maximum times of non-improving consecutive model checkpoints. plateau_reduce_factor: Factor by which the learning rates of all models in self.output_models are multiplied when plateau_reduce_patience is consecutively reached / exceeded. early_stop_patience: Number of times plateau_reduce_patience is consecutively reached / exceeded. divergence_monitoring_steps: Number of steps at which reduce on plateau, and early stopping start monitoring. quiet: If True, all agent messages will be silenced. trial: optuna.trial.Trial &quot;&quot;&quot; assert envs, 'No environments given' self.n_envs = len(envs) self.envs = envs self.model = model self.checkpoints = checkpoints self.total_rewards = deque(maxlen=reward_buffer_size) self.n_steps = n_steps self.gamma = gamma self.display_precision = display_precision self.seed = seed self.output_models = [self.model] self.log_frequency = log_frequency or self.n_envs self.id = self.__module__.split('.')[1] self.history_checkpoint = history_checkpoint self.plateau_reduce_factor = plateau_reduce_factor self.plateau_reduce_patience = plateau_reduce_patience self.early_stop_patience = early_stop_patience self.divergence_monitoring_steps = divergence_monitoring_steps self.quiet = quiet self.trial = trial self.reported_rewards = 0 self.plateau_count = 0 self.early_stop_count = 0 self.target_reward = None self.max_steps = None self.input_shape = self.envs[0].observation_space.shape self.n_actions = None self.best_reward = -float('inf') self.mean_reward = -float('inf') self.states = [np.array(0)] * self.n_envs self.dones = [False] * self.n_envs self.steps = 0 self.frame_speed = 0 self.last_reset_step = 0 self.training_start_time = None self.last_reset_time = None self.games = 0 self.episode_rewards = np.zeros(self.n_envs) self.done_envs = 0 self.supported_action_spaces = Box, Discrete if seed: self.set_seeds(seed) self.reset_envs() self.set_action_count() self.img_inputs = len(self.states[0].shape) &gt;= 2 self.display_titles = ( 'time', 'steps', 'games', 'speed', 'mean reward', 'best reward', ) def assert_valid_env(self, env, valid_type): &quot;&quot;&quot; Assert the right type of environment is passed to an agent. Args: env: gym environment. valid_type: gym.spaces class. Returns: None &quot;&quot;&quot; assert isinstance(env.action_space, valid_type), ( f'Invalid environment: {env.spec.id}. {self.__class__.__name__} supports ' f'environments with a {valid_type} action space only, got {env.action_space}' ) def display_message(self, *args, **kwargs): &quot;&quot;&quot; Display messages to the console. Args: *args: args passed to print() **kwargs: kwargs passed to print() Returns: None &quot;&quot;&quot; if not self.quiet: print(*args, **kwargs) def set_seeds(self, seed): &quot;&quot;&quot; Set random seeds for numpy, tensorflow, random, gym Args: seed: int, random seed. Returns: None &quot;&quot;&quot; tf.random.set_seed(seed) np.random.seed(seed) for env in self.envs: env.seed(seed) env.action_space.seed(seed) os.environ['PYTHONHASHSEED'] = f'{seed}' random.seed(seed) def reset_envs(self): &quot;&quot;&quot; Reset all environments in self.envs and update self.states Returns: None &quot;&quot;&quot; for i, env in enumerate(self.envs): self.states[i] = env.reset() def set_action_count(self): &quot;&quot;&quot; Set `self.n_actions` to the number of actions for discrete environments or to the shape of the action space for continuous. &quot;&quot;&quot; assert ( type(action_space := self.envs[0].action_space) in self.supported_action_spaces ), f'Expected one of {self.supported_action_spaces}, got {action_space}' if isinstance(action_space, Discrete): self.n_actions = action_space.n if isinstance(action_space, Box): self.n_actions = action_space.shape[0] def check_checkpoints(self): &quot;&quot;&quot; Ensure the number of given checkpoints matches the number of output models. Returns: None &quot;&quot;&quot; assert (n_models := len(self.output_models)) == ( n_checkpoints := len(self.checkpoints) ), ( f'Expected {n_models} checkpoints for {n_models} ' f'given output models, got {n_checkpoints}' ) def checkpoint(self): &quot;&quot;&quot; Save model weights if current reward &gt; best reward. Returns: None &quot;&quot;&quot; if self.mean_reward &gt; self.best_reward: self.plateau_count = 0 self.early_stop_count = 0 self.display_message( f'Best reward updated: {self.best_reward} -&gt; {self.mean_reward}' ) if self.checkpoints: for model, checkpoint in zip(self.output_models, self.checkpoints): model.save_weights(checkpoint) self.best_reward = max(self.mean_reward, self.best_reward) def display_metrics(self): &quot;&quot;&quot; Display progress metrics to the console when environments complete a full episode each. Metrics consist of: - time: Time since training started. - steps: Time steps so far. - games: Finished games / episodes that resulted in a terminal state. - speed: Frame speed/s - mean reward: Mean game total rewards. - best reward: Highest total episode score obtained. Returns: None &quot;&quot;&quot; display_values = ( timedelta(seconds=perf_counter() - self.training_start_time), self.steps, self.games, f'{round(self.frame_speed)} steps/s', self.mean_reward, self.best_reward, ) display = ( f'{title}: {value}' for title, value in zip(self.display_titles, display_values) ) self.display_message(', '.join(display)) def update_metrics(self): &quot;&quot;&quot; Update progress metrics which consist of last reset step and time used for calculation of fps, and update mean and best rewards. The model is saved if there is a checkpoint path specified. Returns: None &quot;&quot;&quot; self.checkpoint() if ( self.divergence_monitoring_steps and self.steps &gt;= self.divergence_monitoring_steps and self.mean_reward &lt;= self.best_reward ): self.plateau_count += 1 if self.plateau_count &gt;= self.plateau_reduce_patience: current_lr, new_lr = None, None for model in self.output_models: current_lr = model.optimizer.learning_rate new_lr = current_lr * self.plateau_reduce_factor self.display_message( f'Learning rate reduced {current_lr.numpy()} ' f'-&gt; {new_lr.numpy()}' ) current_lr.assign(new_lr) self.plateau_count = 0 self.early_stop_count += 1 self.frame_speed = (self.steps - self.last_reset_step) / ( perf_counter() - self.last_reset_time ) self.last_reset_step = self.steps self.mean_reward = np.around( np.mean(self.total_rewards), self.display_precision ) def report_rewards(self): &quot;&quot;&quot; Report intermediate rewards or raise an exception to prune current trial. Returns: None Raises: optuna.exceptions.TrialPruned &quot;&quot;&quot; self.trial.report(np.mean(self.total_rewards), self.reported_rewards) self.reported_rewards += 1 if self.trial.should_prune(): raise optuna.exceptions.TrialPruned() def check_episodes(self): &quot;&quot;&quot; Check environment done counts to display progress and update metrics. Returns: None &quot;&quot;&quot; if self.done_envs &gt;= self.log_frequency: self.update_metrics() if self.trial: self.report_rewards() self.last_reset_time = perf_counter() self.display_metrics() self.done_envs = 0 def training_done(self): &quot;&quot;&quot; Check whether a target reward or maximum number of steps is reached. Returns: bool &quot;&quot;&quot; if self.early_stop_count &gt;= self.early_stop_patience: self.display_message(f'Early stopping') return True if self.target_reward and self.mean_reward &gt;= self.target_reward: self.display_message(f'Reward achieved in {self.steps} steps') return True if self.max_steps and self.steps &gt;= self.max_steps: self.display_message(f'Maximum steps exceeded') return True return False def concat_buffer_samples(self): &quot;&quot;&quot; Concatenate samples drawn from each environment respective buffer. Args: Returns: A list of concatenated samples. &quot;&quot;&quot; if hasattr(self, 'buffers'): batches = [] for i, env in enumerate(self.envs): buffer = self.buffers[i] batch = buffer.get_sample() batches.append(batch) dtypes = ( self.batch_dtypes if hasattr(self, 'batch_dtypes') else [np.float32 for _ in range(len(batches[0]))] ) if len(batches) &gt; 1: return [ np.concatenate(item).astype(dtype) for (item, dtype) in zip(zip(*batches), dtypes) ] return [item.astype(dtype) for (item, dtype) in zip(batches[0], dtypes)] def update_history(self, episode_reward): &quot;&quot;&quot; Write 1 episode stats to .parquet history checkpoint. Args: episode_reward: int, a finished episode reward Returns: None &quot;&quot;&quot; data = { 'mean_reward': [self.mean_reward], 'best_reward': [self.best_reward], 'episode_reward': [episode_reward], 'step': [self.steps], 'time': [perf_counter() - self.training_start_time], } write_from_dict(data, self.history_checkpoint) def step_envs(self, actions, get_observation=False, store_in_buffers=False): &quot;&quot;&quot; Step environments in self.envs, update metrics (if any done games) and return / store results. Args: actions: An iterable of actions to execute by environments. get_observation: If True, a list of [states, actions, rewards, dones, new_states] of length self.n_envs each will be returned. store_in_buffers: If True, each observation is saved separately in respective buffer. Returns: A list of observations as numpy arrays or an empty list. &quot;&quot;&quot; observations = [] for ( (i, env), action, *items, ) in zip(enumerate(self.envs), actions): state = self.states[i] new_state, reward, done, _ = env.step(action) self.states[i] = new_state self.dones[i] = done self.episode_rewards[i] += reward observation = state, action, reward, done, new_state if store_in_buffers and hasattr(self, 'buffers'): self.buffers[i].append(*observation) if get_observation: observations.append(observation) if done: if self.history_checkpoint: self.update_history(self.episode_rewards[i]) self.done_envs += 1 self.total_rewards.append(self.episode_rewards[i]) self.games += 1 self.episode_rewards[i] = 0 self.states[i] = env.reset() self.steps += 1 return [np.array(item, np.float32) for item in zip(*observations)] def init_from_checkpoint(self): &quot;&quot;&quot; Load previous training session metadata and update agent metrics to go from there. Returns: None &quot;&quot;&quot; previous_history = pd.read_parquet(self.history_checkpoint) expected_columns = { 'time', 'mean_reward', 'best_reward', 'step', 'episode_reward', } assert ( set(previous_history.columns) == expected_columns ), f'Expected the following columns: {expected_columns}, got {set(previous_history.columns)}' last_row = previous_history.loc[previous_history['time'].idxmax()] self.mean_reward = last_row['mean_reward'] self.best_reward = previous_history['best_reward'].max() history_start_steps = last_row['step'] history_start_time = last_row['time'] self.training_start_time = perf_counter() - history_start_time self.last_reset_step = self.steps = int(history_start_steps) self.total_rewards.append(last_row['episode_reward']) self.games = previous_history.shape[0] def init_training(self, target_reward, max_steps, monitor_session): &quot;&quot;&quot; Initialize training start time, wandb session &amp; models (self.model / self.target_model) Args: target_reward: Total reward per game value that whenever achieved, the training will stop. max_steps: Maximum time steps, if exceeded, the training will stop. monitor_session: Wandb session name. Returns: None &quot;&quot;&quot; self.target_reward = target_reward self.max_steps = max_steps if monitor_session: wandb.init(name=monitor_session) if self.checkpoints: self.check_checkpoints() self.training_start_time = perf_counter() self.last_reset_time = perf_counter() if self.history_checkpoint and Path(self.history_checkpoint).exists(): self.init_from_checkpoint() def train_step(self): &quot;&quot;&quot; Perform 1 step which controls action_selection, interaction with environments in self.envs, batching and gradient updates. Returns: None &quot;&quot;&quot; raise NotImplementedError( f'train_step() should be implemented by {self.__class__.__name__} subclasses' ) def get_model_outputs(self, inputs, models, training=True): &quot;&quot;&quot; Get single or multiple model outputs. Args: inputs: Inputs as tensors / numpy arrays that are expected by the given model(s). models: A tf.keras.Model or a list of tf.keras.Model(s) training: `training` parameter passed to model call. Returns: Outputs as a list in case of multiple models or any other shape that is expected from the given model(s). &quot;&quot;&quot; if self.img_inputs: inputs = tf.cast(inputs, tf.float32) / 255.0 if isinstance(models, tf.keras.models.Model): return models(inputs, training=training) elif len(models) == 1: return models[0](inputs, training=training) return [sub_model(inputs, training=training) for sub_model in models] def at_step_start(self): &quot;&quot;&quot; Execute steps that will run before self.train_step(). Returns: None &quot;&quot;&quot; pass def at_step_end(self): &quot;&quot;&quot; Execute steps that will run after self.train_step(). Returns: None &quot;&quot;&quot; pass def get_states(self): &quot;&quot;&quot; Get most recent states. Returns: self.states as numpy array. &quot;&quot;&quot; return np.array(self.states) def get_dones(self): &quot;&quot;&quot; Get most recent game statuses. Returns: self.dones as numpy array. &quot;&quot;&quot; return np.array(self.dones, np.float32) @staticmethod def concat_step_batches(*args): &quot;&quot;&quot; Concatenate n-step batches. Args: *args: A list of numpy arrays which will be concatenated separately. Returns: A list of concatenated numpy arrays. &quot;&quot;&quot; concatenated = [] for arg in args: if len(arg.shape) == 1: arg = np.expand_dims(arg, -1) concatenated.append(arg.swapaxes(0, 1).reshape(-1, *arg.shape[2:])) return concatenated def fit( self, target_reward=None, max_steps=None, monitor_session=None, ): &quot;&quot;&quot; Common training loop shared by subclasses, monitors training status and progress, performs all training steps, updates metrics, and logs progress. Args: target_reward: Target reward, if achieved, the training will stop max_steps: Maximum number of steps, if reached the training will stop. monitor_session: Session name to use for monitoring the training with wandb. Returns: None &quot;&quot;&quot; assert ( target_reward or max_steps ), '`target_reward` or `max_steps` should be specified when fit() is called' self.init_training(target_reward, max_steps, monitor_session) while True: self.check_episodes() if self.training_done(): break self.at_step_start() self.train_step() self.at_step_end() def play( self, video_dir=None, render=False, frame_dir=None, frame_delay=0.0, max_steps=None, action_idx=0, frame_frequency=1, ): &quot;&quot;&quot; Play and display a game. Args: video_dir: Path to directory to save the resulting game video. render: If True, the game will be displayed. frame_dir: Path to directory to save game frames. frame_delay: Delay between rendered frames. max_steps: Maximum environment steps. action_idx: Index of action output by self.model frame_frequency: If frame_dir is specified, save frames every n frames. Returns: None &quot;&quot;&quot; self.reset_envs() env_idx = 0 total_reward = 0 env_in_use = self.envs[env_idx] if video_dir: env_in_use = gym.wrappers.Monitor(env_in_use, video_dir) env_in_use.reset() steps = 0 agent_id = self.__module__.split('.')[1] for dir_name in (video_dir, frame_dir): os.makedirs(dir_name or '.', exist_ok=True) while True: if max_steps and steps &gt;= max_steps: self.display_message(f'Maximum steps {max_steps} exceeded') break if render: env_in_use.render() sleep(frame_delay) if frame_dir and steps % frame_frequency == 0: frame = cv2.cvtColor( env_in_use.render(mode='rgb_array'), cv2.COLOR_BGR2RGB ) cv2.imwrite(os.path.join(frame_dir, f'{steps:05d}.jpg'), frame) if hasattr(self, 'actor') and agent_id in ['td3', 'ddpg']: action = self.actor(self.get_states())[env_idx] else: action = self.get_model_outputs( self.get_states(), self.output_models, False )[action_idx][env_idx].numpy() self.states[env_idx], reward, done, _ = env_in_use.step(action) total_reward += reward if done: self.display_message(f'Total reward: {total_reward}') break steps += 1 class OnPolicy(BaseAgent, ABC): &quot;&quot;&quot; Base class for on-policy agents. &quot;&quot;&quot; def __init__(self, envs, model, **kwargs): &quot;&quot;&quot; Initialize on-policy agent. Args: envs: A list of gym environments. model: tf.keras.models.Model that is expected to be compiled with an optimizer before training starts. **kwargs: kwargs passed to BaseAgent. &quot;&quot;&quot; super(OnPolicy, self).__init__(envs, model, **kwargs) class OffPolicy(BaseAgent, ABC): &quot;&quot;&quot; Base class for off-policy agents. &quot;&quot;&quot; def __init__( self, envs, model, buffers, **kwargs, ): &quot;&quot;&quot; Initialize off-policy agent. Args: envs: A list of gym environments. model: tf.keras.models.Model that is expected to be compiled with an optimizer before training starts. buffers: A list of replay buffer objects whose length should match `envs`s'. **kwargs: kwargs passed to BaseAgent. &quot;&quot;&quot; super(OffPolicy, self).__init__(envs, model, **kwargs) assert len(envs) == len(buffers), ( f'Expected equal env and replay buffer sizes, got {self.n_envs} ' f'and {len(buffers)}' ) self.buffers = buffers def fill_buffers(self): &quot;&quot;&quot; Fill each buffer in self.buffers up to its initial size. Returns: None &quot;&quot;&quot; total_size = sum(buffer.initial_size for buffer in self.buffers) sizes = {} for i, env in enumerate(self.envs): buffer = self.buffers[i] state = self.states[i] while buffer.current_size &lt; buffer.initial_size: action = env.action_space.sample() new_state, reward, done, _ = env.step(action) buffer.append(state, action, reward, done, new_state) state = new_state if done: state = env.reset() sizes[i] = buffer.current_size filled = sum(sizes.values()) complete = round((filled / total_size) * 100, self.display_precision) self.display_message( f'\rFilling replay buffer {i + 1}/{self.n_envs} ==&gt; {complete}% | ' f'{filled}/{total_size}', end='', ) self.display_message('') self.reset_envs() def fit( self, target_reward=None, max_steps=None, monitor_session=None, ): &quot;&quot;&quot; Common training loop shared by subclasses, monitors training status and progress, performs all training steps, updates metrics, and logs progress. ** Additionally, replay buffers are pre-filled before training starts ** Args: target_reward: Target reward, if achieved, the training will stop max_steps: Maximum number of steps, if reached the training will stop. monitor_session: Session name to use for monitoring the training with wandb. Returns: None &quot;&quot;&quot; self.fill_buffers() super(OffPolicy, self).fit(target_reward, max_steps, monitor_session) </code></pre> <p>Regarding the respective test module <code>test_base.py</code> I will include it in a separate post because beside testing base agents, it tests additional functionalities outside their scope, and of course, the character limit. If someone is interested in reviewing this, please let me know if you have any questions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T09:17:35.947", "Id": "526080", "Score": "0", "body": "anyone interested in reviewing this?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T11:08:42.423", "Id": "266124", "Score": "2", "Tags": [ "python", "python-3.x", "library", "machine-learning", "tensorflow" ], "Title": "xagents - implementations of reinforcement learning algorithms" }
266124
<p>I'm working on a GPyT (generative python transformer) project and I have written the below script to download lots of Python files from github.com to train my model. It works fine, but there is a problem I guess because it becomes slower with every file it downloads. It takes more time to download new files and while the size of the Python files is almost the same and small.</p> <p>At first I wanted to ask my question on Stack Overflow but as the script works and there is no error I thought it would be better to ask it here. To get some advice on my work, because I think it smells spaghetti and there is a performance issue involved.</p> <p>The part I have doubts about is this 'if` statement:</p> <pre><code>if not os.path.isfile(f'{repos_path}/{file_content.name}') </code></pre> <p>I think it takes longer every time to check if the file exists because the number of files is increasing. It checks against a growing list. I've also checked the memory and CPU usage running this script and there is no difference when I first started the script.</p> <p>Code:</p> <pre><code># Part one &gt;&gt;&gt; cloning lots of python related repositories from **GITHUB** # and put them into repos directory. import os import subprocess import wget from colorama import Fore from github import Github from requests.exceptions import HTTPError &quot;&quot;&quot; There are two ways to do so: 1. Clone lots of repositories and then walk through the directories and delete every single file except python files, 2. Get a specific content file which is the chosen way here &quot;&quot;&quot; &quot;&quot;&quot; There are many ways to download the files: 1. Using wget, 2. Implementing your own dl.py file in order to download files using requests library or even making a function named download &quot;&quot;&quot; # replace with your desired directory repos_path = '' try: access_token = open('', 'r').read() github = Github(access_token) query = 'language:python' res = github.search_repositories(query) # print(res.totalCount) # print(dir(res)) for repo in res: contents = repo.get_contents('') while contents: file_content = contents.pop(0) if file_content.type == 'dir': contents.extend(repo.get_contents(file_content.path)) else: # print(f'{Fore.GREEN} + URL: {file_content.download_url}') if file_content.path.endswith('.py'): contents_url = file_content.download_url if not os.path.isfile(f'{repos_path}/{file_content.name}'): try: wget.download( contents_url, out=repos_path, bar=None) except HTTPError as http_err: print( f'{Fore.YELLOW} - &quot;Error occurred&quot;: {http_err}') continue except Exception as err: print(f'{Fore.YELLOW} - &quot;Error occurred&quot;: {err}') continue else: print(f'{Fore.GREEN} + {Fore.WHITE} &quot;{file_content.name}&quot; {Fore.GREEN} Downloaded') else: print(f'{Fore.RED} - {Fore.WHITE} &quot;{file_content.name}&quot; {Fore.RED} Exists') except Exception as e: command = 'du -sh repos/' paths = [] for path, dirs, files in os.walk(repos_path): for f in files: fp = os.path.join(path, f) paths.append(fp) print(f'\n{e}') print(f'{Fore.WHITE}There are {len(paths)} Python files under &quot;repos&quot; directory') subprocess.call(command) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T11:44:14.730", "Id": "266126", "Score": "3", "Tags": [ "python", "api" ], "Title": "Generative Python transformer hitting Github API" }
266126
<p>I'm implementing a function called <code>is_proper_integer</code> that will check the string whether it is a valid integer literal by borrowing the idea from C++ grammar.</p> <p>Function signature:</p> <pre class="lang-cpp prettyprint-override"><code>constexpr bool is_proper_integer(std::string_view str, std::optional&lt;std::reference_wrapper&lt;parse_integer_errc_t&gt;&gt; errc = {}); </code></pre> <p>Where:</p> <ul> <li>the function is declared as <code>constexpr</code> so that the function is usable at compile-time.</li> <li><code>str</code> has the plain type <code>std::string_view</code> so that I could modify it by calling <code>remove_prefix</code> and <code>remove_suffix</code> within the definition.</li> <li><code>errc</code> acts as an error code to report the reason why it returns <code>false</code> and I made it <code>std::optional&lt;std::reference_wrapper&lt;...&gt;&gt;</code> because the parameter is obviously <strong>optional</strong> and there is no <code>std::optional&lt;T&amp;&gt;</code>, so I wrap it inside the class template <code>std::reference_wrapper</code>.</li> </ul> <p>These are the helpful utilities in order to work with the function:</p> <pre class="lang-cpp prettyprint-override"><code>enum class parse_integer_errc_t { normal, foreign_char, adjacent_radix_sep, invalid_prefix, invalid_radix_sep, invalid_binary_fmt, invalid_octal_fmt, invalid_decimal_fmt, invalid_hexadecimal_fmt, unknown }; enum class integer_prefix_t { binary, octal, decimal, hexadecimal, unknown }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, parse_integer_errc_t errc) { switch (errc) { using enum parse_integer_errc_t; case normal: return os &lt;&lt; &quot;normal&quot;; case foreign_char: return os &lt;&lt; &quot;foreign_char&quot;; case adjacent_radix_sep: return os &lt;&lt; &quot;adjacent_radix_sep&quot;; case invalid_prefix: return os &lt;&lt; &quot;invalid_prefix&quot;; case invalid_radix_sep: return os &lt;&lt; &quot;invalid_radix_sep&quot;; case invalid_binary_fmt: return os &lt;&lt; &quot;invalid_binary_fmt&quot;; case invalid_octal_fmt: return os &lt;&lt; &quot;invalid_octal_fmt&quot;; case invalid_decimal_fmt: return os &lt;&lt; &quot;invalid_decimal_fmt&quot;; case invalid_hexadecimal_fmt: return os &lt;&lt; &quot;invalid_hexadecimal_fmt&quot;; case unknown: return os &lt;&lt; &quot;unknown&quot;; } return os; } </code></pre> <p>Main implementation:</p> <pre class="lang-cpp prettyprint-override"><code>constexpr bool is_proper_integer(std::string_view str, std::optional&lt;std::reference_wrapper&lt;parse_integer_errc_t&gt;&gt; errc = {}) { constexpr char valid_chars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f' }; /// span version auto&amp;&amp; span_chars = std::span{valid_chars}; /// check if it has unary '-' or '+' operator if (str.front() == '-' || str.front() == '+') str.remove_prefix(1); /// check if the front character is valid (after '-') if ( auto&amp;&amp; span_ = span_chars.first&lt;10&gt;(); std::ranges::find(span_, str.front()) == span_.end() ) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_prefix; return false; } /// check the prefix integer_prefix_t flag_ = integer_prefix_t::unknown; if (str.starts_with(&quot;0x&quot;) | str.starts_with(&quot;0X&quot;)) { str.remove_prefix(2); flag_ = integer_prefix_t::hexadecimal; } else if (str.starts_with(&quot;0b&quot;) || str.starts_with(&quot;0B&quot;)) { str.remove_prefix(2); flag_ = integer_prefix_t::binary; } else if (str.starts_with('0')) { str.remove_prefix(1); flag_ = integer_prefix_t::octal; } else { flag_ = integer_prefix_t::decimal; } /// check again... if (str.starts_with('\'')) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_radix_sep; return false; } /// check the suffix if (str.ends_with(&quot;ull&quot;) || str.ends_with(&quot;ULL&quot;) || str.ends_with(&quot;uLL&quot;) || str.ends_with(&quot;Ull&quot;) ) str.remove_suffix(3); else if ( str.ends_with(&quot;ul&quot;) || str.ends_with(&quot;uL&quot;) || str.ends_with(&quot;Ul&quot;) || str.ends_with(&quot;UL&quot;) || str.ends_with(&quot;ll&quot;) || str.ends_with(&quot;LL&quot;) || str.ends_with(&quot;uz&quot;) || str.ends_with(&quot;uZ&quot;) || str.ends_with(&quot;Uz&quot;) || str.ends_with(&quot;UZ&quot;) ) str.remove_suffix(2); else if ( str.ends_with('z') || str.ends_with('Z') || str.ends_with('u') || str.ends_with('U') || str.ends_with('l') || str.ends_with('L') ) str.remove_suffix(1); /// check again... if (str.ends_with('\'')) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_radix_sep; return false; } /// flag for radix grouping check bool radix_sep_state { false }; /// normal loop checking for (char c : str) { if (c == '\'') { if (radix_sep_state) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::adjacent_radix_sep; return false; } radix_sep_state = true; continue; } radix_sep_state = false; if (std::ranges::find(span_chars, c) == span_chars.end()) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::foreign_char; return false; } switch (flag_) { using enum integer_prefix_t; case binary: { auto&amp;&amp; span_ = span_chars.first&lt;2&gt;(); if (std::ranges::find(span_, c) == span_.end()) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_binary_fmt; return false; } break; } case octal: { auto&amp;&amp; span_ = span_chars.first&lt;8&gt;(); if (std::ranges::find(span_, c) == span_.end()) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_octal_fmt; return false; } break; } case decimal: { auto&amp;&amp; span_ = span_chars.first&lt;10&gt;(); if (std::ranges::find(span_, c) == span_.end()) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_decimal_fmt; return false; } break; } case hexadecimal: { if (std::ranges::find(span_chars, c) == span_chars.end()) { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_hexadecimal_fmt; return false; } break; } case unknown: { if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::unknown; return false; } } } if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::normal; return true; } </code></pre> <p>Compile-time Check:</p> <pre class="lang-cpp prettyprint-override"><code> static_assert(is_proper_integer(&quot;1234&quot;)); /// normal case static_assert(is_proper_integer(&quot;+1234&quot;)); /// positive static_assert(is_proper_integer(&quot;-1234&quot;)); /// negative static_assert(is_proper_integer(&quot;1234u&quot;)); /// has suffix 'u' static_assert(is_proper_integer(&quot;-1234ull&quot;)); /// has suffix 'ull' (ofc, overflow, but still valid) static_assert(is_proper_integer(&quot;1234uz&quot;)); /// has suffix 'uz' static_assert(is_proper_integer(&quot;0b10010&quot;)); /// ok, binary static_assert(!is_proper_integer(&quot;0b1012&quot;)); /// '2' strayed in binary fmt static_assert(is_proper_integer(&quot;+0B11001U&quot;)); /// has suffix 'U' static_assert(!is_proper_integer(&quot;ajsdsad&quot;)); /// obviously, invalid chars static_assert(is_proper_integer(&quot;0172613&quot;)); /// octal, ok static_assert(is_proper_integer(&quot;-012112&quot;)); /// ok static_assert(is_proper_integer(&quot;+0xabc'def&quot;)); /// hexadecimal, ok static_assert(is_proper_integer(&quot;-0XCAFEdead&quot;)); /// ok, case-insensitive static_assert(is_proper_integer(&quot;0xdeadbeefull&quot;)); /// ok, has suffix 'ull' static_assert(!is_proper_integer(&quot;deadbeef&quot;)); /// invalid prefix static_assert(!is_proper_integer(&quot;12'3''2&quot;)); /// wrong radix grouping. static_assert(is_proper_integer(&quot;0b1111'0000'1010ull&quot;)); /// ok static_assert(!is_proper_integer(&quot;0123;1&quot;)); /// foreign character </code></pre> <p>Runtime Check:</p> <pre class="lang-cpp prettyprint-override"><code> std::vector&lt;std::string_view&gt; queues { &quot;1234&quot;, &quot;+1234&quot;, &quot;-1234&quot;, &quot;1234u&quot;, &quot;-1234ull&quot;, &quot;1234uz&quot;, &quot;0b10010&quot;, &quot;0b1012&quot;, &quot;+0B11001U&quot;, &quot;ajsdsad&quot;, &quot;0172613&quot;, &quot;-012112&quot;, &quot;+0xabc'def&quot;, &quot;-0XCAFEdead&quot;, &quot;0xdeadbeefull&quot;, &quot;deadbeef&quot;, &quot;12'3''2&quot;, &quot;0b1111'0000'1010ull&quot;, &quot;0123;1&quot; }; parse_integer_errc_t errcode; std::cout &lt;&lt; std::boolalpha; for (const auto&amp; str : queues) { std::cout &lt;&lt; &quot;String: &quot; &lt;&lt; std::setw(23) &lt;&lt; std::left &lt;&lt; str &lt;&lt; &quot;Is valid?: &quot; &lt;&lt; std::setw(8) &lt;&lt; std::left &lt;&lt; (is_proper_integer(str, errcode) ? &quot;yes&quot; : &quot;no&quot;) &lt;&lt; &quot;Reason: &quot; &lt;&lt; std::setw(20) &lt;&lt; std::left &lt;&lt; errcode &lt;&lt; '\n'; } </code></pre> <p>Output:</p> <pre><code>String: 1234 Is valid?: yes Reason: normal String: +1234 Is valid?: yes Reason: normal String: -1234 Is valid?: yes Reason: normal String: 1234u Is valid?: yes Reason: normal String: -1234ull Is valid?: yes Reason: normal String: 1234uz Is valid?: yes Reason: normal String: 0b10010 Is valid?: yes Reason: normal String: 0b1012 Is valid?: no Reason: invalid_binary_fmt String: +0B11001U Is valid?: yes Reason: normal String: ajsdsad Is valid?: no Reason: invalid_prefix String: 0172613 Is valid?: yes Reason: normal String: -012112 Is valid?: yes Reason: normal String: +0xabc'def Is valid?: yes Reason: normal String: -0XCAFEdead Is valid?: yes Reason: normal String: 0xdeadbeefull Is valid?: yes Reason: normal String: deadbeef Is valid?: no Reason: invalid_prefix String: 12'3''2 Is valid?: no Reason: adjacent_radix_sep String: 0b1111'0000'1010ull Is valid?: yes Reason: normal String: 0123;1 Is valid?: no Reason: foreign_char </code></pre> <p>Is there anything I could simplify?</p>
[]
[ { "body": "<blockquote>\n<p>the function is declared as constexpr so that the function is usable at compile-time.</p>\n</blockquote>\n<p><strong>good</strong>!</p>\n<blockquote>\n<p>str has the plain type std::string_view so that I could modify it by calling remove_prefix and remove_suffix within the definition.</p>\n</blockquote>\n<p><strong>good!</strong> that's a good feature for this kind of parsing.</p>\n<blockquote>\n<p>errc acts as an error code to report the reason why it returns false and I made it std::optionalstd::reference_wrapper&lt;...&gt; because the parameter is obviously optional and there is no std::optional&lt;T&amp;&gt;, so I wrap it inside the class template std::reference_wrapper.</p>\n</blockquote>\n<p>You might consider two overloaded forms, with and without an <code>error_code&amp;</code> out parameter, as seen with the <code>&lt;filesystem&gt;</code> header. The form without is just a one-liner that passes a local variable to the regular form, essentially throwing it away. There's no complicated code in the function for dealing with an optional.</p>\n<h2>standard error codes</h2>\n<p>You should define an <a href=\"https://en.cppreference.com/w/cpp/error/error_category\" rel=\"nofollow noreferrer\">error category</a> class that has the proper function for looking up the error message, rather than the <code>operator&lt;&lt;</code> you have.</p>\n<p>Your stand-alone <code>parse_integer_errc_t</code> should be able to be set as <a href=\"https://en.cppreference.com/w/cpp/error/error_code\" rel=\"nofollow noreferrer\"><code>error_code</code></a>.</p>\n<h2>repeated calls</h2>\n<p>You have a long list of <code>.ends_with(xxx)</code> with different strings. You could put all the allowed suffixes in a simple array and use a loop, which also picks up the length of the suffix automatically rather than needing different cases.</p>\n<p>If you do a check that folds case rather than <code>.ends_with</code> you would not need a power-of-two of the length of the suffix for the number of cases to try!</p>\n<pre><code> constexpr string_view suffixes[]= {&quot;ull&quot;,&quot;ul&quot;,&quot;l&quot;,&quot;uz&quot;,&quot;z&quot;,&quot;u&quot;};\n for (auto sfx : suffixes) {\n if case-insentive-match of the end of the input,\n remove the suffix and break\n }\n</code></pre>\n<h2>alternatives</h2>\n<p>A much simpler (but probably slower) way to check would be to use a <em>regex</em>. There is a Compile Time RegEx library (work in progress) that is looking quite nice, that would let you check compile-time strings.</p>\n<p>Or, you could just call <code>from_chars</code> and see if you got an error or not, ignoring the parsed integer it produced.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T14:21:10.263", "Id": "266130", "ParentId": "266127", "Score": "2" } }, { "body": "<p>In no particular order:</p>\n<ul>\n<li><p><code>enum class parse_integer_errc_t { normal, ...</code> I think if we call this an error code (<code>errc</code>), then <code>no_error</code> would be a clearer name than <code>normal</code>. On the other hand, if the intent is to categorise the string, then the enum shouldn't be referred to as an &quot;error code&quot;.</p>\n</li>\n<li><p><code>unknown</code> I think this category could be removed (both in the error code and the prefix type).</p>\n</li>\n<li><p>It's a lot simpler to always require a <code>parse_integer_errc_t&amp;</code> parameter. We could also provide an overloaded version taking only one parameter, that calls the first one and discards the error code internally.</p>\n</li>\n<li><p><code>auto&amp;&amp; span_chars = std::span{valid_chars};</code> The <code>&amp;&amp;</code> is unnecessary (as in other declarations below).</p>\n</li>\n<li><p><strong>bug:</strong> <code>if (str.front() == '-' || str.front() == '+') str.remove_prefix(1);</code> We need to check that the string isn't empty first!!! (Even for <code>std::string</code> this is undefined behavior for an empty string, and <code>std::string_view</code> doesn't have the same guarantees of a terminating null).</p>\n</li>\n<li><p><code>str.ends_with(&quot;ull&quot;)</code> I guess it depends what format spec you're following, but <code>llu</code> (and case variations) are also valid for C++ literals: <a href=\"https://en.cppreference.com/w/cpp/language/integer_literal\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/integer_literal</a></p>\n</li>\n<li>\n<pre><code> auto&amp;&amp; span_ = span_chars.first&lt;2&gt;();\n if (std::ranges::find(span_, c) == span_.end()) {\n if (errc.has_value()) errc-&gt;get() = parse_integer_errc_t::invalid_binary_fmt;\n return false;\n }\n</code></pre>\n<p>If we define the span of valid characters (and the error code) outside of the loop, we shouldn't need the switch statement and the duplication here.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T14:51:08.757", "Id": "266134", "ParentId": "266127", "Score": "2" } }, { "body": "<blockquote>\n<p>Is there anything I could simplify?</p>\n</blockquote>\n<p>I’m going to answer this question specifically, rather than give a general code review. And they answer is: yes… this function is <em>way</em> too big, and <em>way</em> too complex. This calls for refactoring.</p>\n<p>Merely breaking the function into smaller logical chunks would be good enough on its own; nobody wants to maintain a 100 line function (or even a 50 line function; if your function is longer than 10 lines, that’s a smell; if your single function creates a scroll bar on CodeReview, that’s <em>really</em> a smell). But there are easily half a dozen things this function does that would be useful on their own. Breaking them out would not only benefit future projects, it would allow those smaller functions to be brutally tested individually, which would be better for <code>is_proper_integer()</code> too. (It would, for example, probably have immediately caught the bug in the sign check part.)</p>\n<p>For example:</p>\n<pre><code>auto has_proper_integer_sign(std::string_view);\nauto has_proper_integer_prefix(std::string_view);\nauto has_proper_integer_suffix(std::string_view);\nauto has_proper_integer_binary_digits(std::string_view);\nauto has_proper_integer_octal_digits(std::string_view);\nauto has_proper_integer_decimal_digits(std::string_view);\nauto has_proper_integer_hexadecimal_digits(std::string_view);\n</code></pre>\n<p>With functions like these, the main function is much easier to write and understand:</p>\n<pre><code>auto is_proper_integer(std::string_view s)\n{\n return has_proper_integer_sign(s)\n and has_proper_integer_prefix(s)\n and has_proper_integer_suffix(s)\n // and so on...\n}\n</code></pre>\n<p>This alone isn’t really <em>that</em> much help, which is why I would also suggest refactoring each test into a function that actually parses. For example:</p>\n<pre><code>enum class integer_parse_errc\n{\n // all the error codes you'll need for parsing integers\n};\n\n// of course, add all the machinery to make the above a legit system_error\n// error code (like a category, is_error_code_enum, etc.)\n\nenum class integer_sign_type\n{\n none,\n positive,\n negative\n};\n\nstruct parse_integer_sign_result_t\n{\n integer_sign_type type = integer_sign_type::none;\n std::string_view sign = {};\n std::string_view rest = {};\n integer_parse_errc ec = {};\n};\n\nconstexpr auto parse_integer_sign(std::string_view s) noexcept -&gt; parse_integer_sign_result_t\n{\n if (not s.empty())\n {\n auto const c = s.front();\n auto const sign = s.substr(0, 1);\n auto const rest = s.substr(1);\n\n if (c == '+')\n return {integer_sign_type::positive, sign, rest};\n if (c == '-')\n return {integer_sign_type::negative, sign, rest};\n }\n\n // or maybe you could consider being empty an error condition\n //\n // that's up to you\n\n return {integer_sign_type::none, {}, s};\n}\n</code></pre>\n<p>Now your function can look something like:</p>\n<pre><code>constexpr auto is_proper_integer(std::string_view s)\n{\n // First parse the sign.\n if (auto const res = parse_integer_sign(s); res.ec != integer_parse_errc{})\n return false;\n else\n s = res.rest;\n\n // Now parse the prefix\n if (auto const res = parse_integer_prefix(s); res.ec != integer_parse_errc{})\n return false;\n else\n s = res.rest;\n\n // ... and so on\n}\n</code></pre>\n<p>Even better, you could probably write a function that parses an integer into its components, and then base <code>is_proper_integer()</code> on that:</p>\n<pre><code>struct parse_integer_result_t\n{\n // the parsed components:\n sign_t sign = sign_t::none; // or positive/negative\n prefix_t prefix = prefix_t::decimal; // or binary/octal/hexadecimal\n suffix_t suffix = suffix_t::none; // or l/ll/z/u/ul/ull/uz\n\n // the unparsed components:\n std::string_view sign_part = {};\n std::string_view prefix_part = {};\n std::string_view suffix_part = {};\n std::string_view number_part = {};\n\n integer_parse_errc = {};\n};\n\nconstexpr auto parse_integer_components(std::string_view s) noexcept\n{\n // for each component XXX, basically do:\n // auto XXX_res = parse_integer_XXX(s);\n // whittling down the string as you go\n\n // if any return an error code, you're done, just return the error code\n\n // if none of them return an error code, construct the full parse result\n // from the component results you already have\n}\n\nconstexpr auto is_proper_integer(std::string_view s) noexcept\n{\n return parse_integer_components(s).ec == integer_parse_errc{};\n}\n</code></pre>\n<p>The <code>parse_integer_components()</code> function would be useful in its own right, because you could then take the information in the components and actually parse the number if you want, or just do stuff like make sure the number is non-negative, or in hex form, or whatever you please.</p>\n<p>That’s not all you could refactor out of this function. Another bit of functionality you use repeatedly that would also be useful on its own is caseless comparisons. For example, you have:</p>\n<pre><code> if (str.ends_with(&quot;ull&quot;) ||\n str.ends_with(&quot;ULL&quot;) ||\n str.ends_with(&quot;uLL&quot;) ||\n str.ends_with(&quot;Ull&quot;)\n</code></pre>\n<p>That’s not just ugly, it’s incomplete. You forgot <code>llu</code>, <code>LLu</code>, <code>llU</code>, and <code>LLU</code>.</p>\n<p>Wouldn’t it be much nicer to write:</p>\n<pre><code> if (ends_with_ci(str, &quot;ull&quot;) or ends_with_ci(str, &quot;llu&quot;))\n</code></pre>\n<p>And <code>ends_with_ci()</code> is a function you could use many other places, too.</p>\n<p>It might make sense to write:</p>\n<pre><code>constexpr auto starts_with_ci(std::string_view, char) noexcept -&gt; bool;\nconstexpr auto starts_with_ci(std::string_view, std::string_view) noexcept -&gt; bool;\n\nconstexpr auto ends_with_ci(std::string_view, char) noexcept -&gt; bool;\nconstexpr auto ends_with_ci(std::string_view, std::string_view) noexcept -&gt; bool;\n\nconstexpr auto equals_ci(char, char) noexcept -&gt; bool;\nconstexpr auto equals_ci(std::string_view, char) noexcept -&gt; bool;\nconstexpr auto equals_ci(char, std::string_view) noexcept -&gt; bool;\nconstexpr auto equals_ci(std::string_view, std::string_view) noexcept -&gt; bool;\n\n// and maybe a find function that returns the found position or end,\n// and a contains function that just uses the find function and returns bool.\n//\n// maybe also a rfind function.\n//\n// up to you\n</code></pre>\n<p>These functions make your parse functions <em>much</em> simpler, and have other uses too.</p>\n<p>Here’s a summary of suggestions I would make:</p>\n<ol>\n<li>Refactor <em><strong>EVERYTHING</strong></em>. Find the bits that are reusable, and useful on their own, and pull them out into their own functions. That includes not only the parsing sub-processes (parsing signs, parsing prefixes, parsing suffixes, etc.), but also algorithms you use throughout (caseless comparisons). And, of course, test everything rigorously. Testing smaller components of bigger functions makes you more confident about the bigger functions.</li>\n<li>Don’t use out parameters; no not even optional out parameters. Here I strongly disagree with @JDługosz: do <em><strong>NOT</strong></em> copy what <code>&lt;filesystem&gt;</code> did. That was a disaster only created because we didn’t have <code>std::expected</code> or <code>std::error</code> or structured bindings… don’t repeat the mistake. Return result <code>struct</code>s for any functions that return anything more than one “thing”. For any parse functions, that will be <em>at least</em> what was parsed, the remainder that was <em>not</em> parsed (so you can continue parsing with other functions), and an error code if there was a parse failure. Returning <code>struct</code>s is <em>much</em> more ergonomic than out parameters—even optional out parameters—especially with structured bindings.</li>\n<li>Don’t return unnecessary information. If your function is <code>is_proper_integer()</code>, then it needs only return <code>bool</code>. It does <em>not</em> need to return an error code (and certainly not an optional-reference-error-code… which, by the way, should really just be <code>parse_integer_errc_t* ec = nullptr</code> (though, even better, should be two different functions, because optional arguments suck), and you should do <code>if (ec != nullptr) *ec = whatever-error;</code>). If the question is “is it an integer?”, that is a yes-or-no question. If the question is “why is it <em>not</em> an integer?” that is not the same question as “is it an integer?”, so it should be a different function. <code>is_proper_integer()</code> answers the yes-or-no question; <code>parse_integer_components()</code> answers the more complex question, with all the detail you could want.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T15:54:33.137", "Id": "525771", "Score": "0", "body": "Re point 2: rather than imitating `<filesystem>`, look to a more recent addition to the standard library: [`from_chars`](https://en.cppreference.com/w/cpp/utility/from_chars). There does not seem to be a `std::expected` yet as of C++20." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T15:56:15.077", "Id": "525772", "Score": "0", "body": "I agree that a _parser_ gives all the complex information you want. I like that as an object, not a function, as it can hold a complex state describing the error, including an error code and its position in the input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T01:46:58.077", "Id": "525814", "Score": "0", "body": "I'm waiting for `constexpr` `from_chars`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T16:30:13.200", "Id": "266141", "ParentId": "266127", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T13:29:38.957", "Id": "266127", "Score": "1", "Tags": [ "c++", "strings", "integer", "c++20" ], "Title": "Validating an integer with affixes in compile-time or runtime" }
266127
<p>This is my third version of building a simple Python calculator. The first two versions only operate on two inputs to perform calculation, this version allows multiple inputs. However, the result will leave a <code>.0</code>. Other than that, is there any way I can further improve this program? I've also included docstrings to explain the function of each code block.</p> <pre><code>import operator from functools import reduce import sys # Display a list of math operators that the user can choose to perform their calculation MATH_OPERATIONS = &quot;&quot;&quot;\n\nList of math operations: 1. Addition (+) 2. Subtraction (-) 3. Multiplication (*) 4. Division (/) 5. Exponentiation (**) &quot;&quot;&quot; # A dictionary that contain options of operations to perform the calculation OPERATIONS = { 1: operator.add, 2: operator.sub, 3: operator.mul, 4: operator.truediv, 5: operator.pow } def ask_user_yes_no(yes_no_question): &quot;&quot;&quot; Simplifies if/else in determining the correct answers from the user input. Returns True if the user answer the prompt with any of the values in choice_yes. Returns False if the user enters any of the values in choice_no &quot;&quot;&quot; choice_yes = [&quot;yes&quot;, 'y'] choice_no = [&quot;no&quot;, 'n'] while True: user_choice = input(yes_no_question).lower() if user_choice in choice_yes: return True elif user_choice in choice_no: return False else: print(&quot;\n\nInvalid Input. Try again.&quot;) def count_number_input(): &quot;&quot;&quot; Takes a user input and count the amount of numbers that the user wants to calculate. Prints out a message if ValueError occurs. &quot;&quot;&quot; while True: try: count_input = int(input(&quot;\nHow many number would you like to calculate?: &quot;)) except ValueError: print(&quot;\nINVALID INPUT - Field must not be blank or contained non-integer or non-numerical values.&quot;) else: return count_input def get_number_list(): &quot;&quot;&quot; Calls count_number_input function to get how many numbers that the user wants to calculate. Iterates over the range of the elements in the function and then asks the user to input the number that they would want to calculate. Prints out messages if a ValueError occurs. &quot;&quot;&quot; input_amount = count_number_input() while True: try: numbers_list = [float(input(&quot;\nNumbers: &quot;)) for _ in range(input_amount)] except ValueError: print(&quot;\nInvalid input, try again.&quot;) print(&quot;\nPlease ensure that the prompt does not contain a null or non-integer or non-numerical values.&quot;) else: return numbers_list def select_choice(): &quot;&quot;&quot; Prints out a list of math operations. Asks the user to select an option to use in the calculation. Check user's selection for ValueError and skip if none is found. Prints out a message if the user has selected an option beyond the specified range of options. &quot;&quot;&quot; print(MATH_OPERATIONS) while True: try: user_choice = int(input(&quot;Select an option | 1 | 2 | 3 | 4 | 5 |: &quot;)) except ValueError: print(&quot;\nINVALID INPUT - Field must not be blank or contained non-integer or non-numerical values.\n&quot;) continue if user_choice &gt; 5: print(&quot;\nOption selected must be from 1 to 5 only!\n&quot;) else: return user_choice def calculate(numbers, choice): &quot;&quot;&quot; Applies operations across all numbers and return the result. Calculation: &gt;&gt;&gt; calculate([2, 2], 1) 4.0 &gt;&gt;&gt; calculate([5, 3], 2) 2.0 &gt;&gt;&gt; calculate([5, 5] 3) 25.0 &gt;&gt;&gt; calculate([9, 3] 4) 3.0 &gt;&gt;&gt; calculate([4, 4] 5) 256.0 &quot;&quot;&quot; return reduce(OPERATIONS[choice], numbers) def start_program(): &quot;&quot;&quot; Starts the program by asking the user the amount of numbers that they want to calculate, and then perform a calculation on those numbers. Prints out the result of calculation. &quot;&quot;&quot; user_number = get_number_list() user_choice = select_choice() print(&quot;\nResult: &quot;, calculate(user_number, user_choice)) def should_calculate_again(): &quot;&quot;&quot; Calls start_program function to run the program first. Asks the user if they want to perform more calculation. Restarts the program if ask_user_yes_no returns True. Exits the program telling the user that the program has exited if ask_user_yes_no returns False. &quot;&quot;&quot; while True: start_program() if not ask_user_yes_no(&quot;\n\nWould you like to perform more calculation? (Y/N): &quot;): sys.exit(&quot;\n\n-----Program Exited-----\n&quot;) should_calculate_again() </code></pre>
[]
[ { "body": "<h1>Doc test</h1>\n<p>It looks like you've intended to include &quot;doctests&quot; in your <code>&quot;&quot;&quot;docstrings&quot;&quot;&quot;</code>, but it doesn't appear that you've used them.</p>\n<p>Running the tests ...</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; import doctest\n&gt;&gt;&gt; doctest.testmod()\n</code></pre>\n<p>... shows all 5 tests fail!</p>\n<h2>Test failures (wrong output)</h2>\n<p>Integer input produces integer output, not floating point:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Failed example:\n calculate([2, 2], 1)\nExpected:\n 4.0\nGot:\n 4\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Failed example:\n calculate([5, 3], 2)\nExpected:\n 2.0\nGot:\n 2\n</code></pre>\n<h2>Test failures (syntax errors)</h2>\n<p>You're missing commas in these examples:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Failed example:\n calculate([5, 5] 3)\nException raised:\n Traceback (most recent call last):\n File &quot;C:\\Program Files\\Python39\\lib\\doctest.py&quot;, line 1336, in __run\n exec(compile(example.source, filename, &quot;single&quot;,\n File &quot;&lt;doctest __main__.calculate[2]&gt;&quot;, line 1\n calculate([5, 5] 3)\n ^\n SyntaxError: invalid syntax\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Failed example:\n calculate([9, 3] 4)\nException raised:\n Traceback (most recent call last):\n File &quot;C:\\Program Files\\Python39\\lib\\doctest.py&quot;, line 1336, in __run\n exec(compile(example.source, filename, &quot;single&quot;,\n File &quot;&lt;doctest __main__.calculate[3]&gt;&quot;, line 1\n calculate([9, 3] 4)\n ^\n SyntaxError: invalid syntax\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Failed example:\n calculate([4, 4] 5)\nException raised:\n Traceback (most recent call last):\n File &quot;C:\\Program Files\\Python39\\lib\\doctest.py&quot;, line 1336, in __run\n exec(compile(example.source, filename, &quot;single&quot;,\n File &quot;&lt;doctest __main__.calculate[4]&gt;&quot;, line 1\n calculate([4, 4] 5)\n ^\n SyntaxError: invalid syntax\n</code></pre>\n<h1>Killing the interpreter</h1>\n<p>If you add a call to <code>doctest.testmod()</code> after the call to <code>should_calculate_again()</code>, you find the doctests never run. The reason: <code>sys.exit()</code> kills the interpreter. Any tests you intend to run cannot run, or never get a chance to report their final status.</p>\n<p>Changing <code>sys.exit(...)</code> to <code>print(...)</code> and <code>break</code> statements would terminate the while loop, and <code>should_calculate_again()</code> would return normally.</p>\n<p>TL;DR: You almost never need to or want to call <code>sys.exit()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:01:19.257", "Id": "525779", "Score": "0", "body": "Thank you for your feedback. I didn't know about the `doctest` module, I thought that the docstring just explains what the code do. So, for the wrong outputs part, I'm still working on returning the right data type based on user input. I have fixed the syntax errors and changed the `sys.exit()` to the ones you provided. And about `sys`.exit()`, would it still be the same if I just use `exit()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:18:02.963", "Id": "525783", "Score": "0", "body": "The docstring is describing how to use the function. After the module is imported, typing `help(calculate)` at the Python prompt will present the help information to the user. Including examples of how the function behaves or is used is a great addition to the documentation. As a bonus, it can double as a built-in unit test, via the `doctest` module. I wouldn't include every last test inside the docstring -- that makes the help text too long and unreadable. External unit tests should be used for complete code coverage. But the tests you do include in the help text should pass." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:26:27.670", "Id": "525787", "Score": "0", "body": "My test of `exit(message)` and `sys.exit(message)` show the same behaviour. One is probably implemented in terms of the other. The point is not to call either of those functions. Instead, let the script natural terminate by returning from the last function that was called and reaching the end of top-level script. Consider a unit test, written in Python, that sets the standard input to `\"2\\n2.0\\n3.0\\3\\nNo\\n\"`, captures standard output, calls `should_calculate_again()` and tries to check the correct output is generated. It would neither pass nor fail because the Python interpreter exited." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T22:13:06.893", "Id": "525806", "Score": "0", "body": "Hmm, still new to this `doctest` module. So, how much is too much to include each test in the docstring? I might've confused myself thinking that docstring is just there to explain the code because I've seen so many examples providing explanation of the function. As for your unit test example, I'm not not sure what do you mean by neither pass nor fail. You would get your result before the program asks if you want to continue or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T22:31:54.660", "Id": "525808", "Score": "0", "body": "\"Too much\" is definitely a gray area, open to interpretation. _\"The first two versions only operate on two inputs to perform calculation, this version allows multiple inputs.\"_ Well, perhaps an example showing more than two inputs would be in order. Other tests may be good for a unit-test, but not so important for including in the `help(calculate)` documentation: division-by-zero, operations involving infinities and non-a-numbers, or square-root-of-negative tests. The latter operations are important to test, & may warrant a comment in the help text, but a full example may be too much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T03:46:21.190", "Id": "525817", "Score": "0", "body": "I see, so for example, I have this test failure here \"Expected: Math ERROR - Division by 0\" and it says \"Got: <BLANKLINE> Math ERROR - Division by 0\", I found out that it was because of the \"\\n\" I put in the message under ZeroDivisionError in my try...except statement. Is that necessary to fix it by removing the newline? I put it there so that the message will display nicely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T04:15:17.987", "Id": "525819", "Score": "1", "body": "See [what about exceptions](https://docs.python.org/3/library/doctest.html#what-about-exceptions) for how to use docktest to test the correct exceptions are raised. But again, **is the docktest example with an exception helping a user understand how to use the function???** If not, the test is better off done in a [unittest](https://docs.python.org/3/library/unittest.html?highlight=unittest#module-unittest) instead of polluting the `\"\"\"docstring\"\"\"`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T16:43:32.810", "Id": "266173", "ParentId": "266129", "Score": "1" } } ]
{ "AcceptedAnswerId": "266173", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T14:13:57.257", "Id": "266129", "Score": "4", "Tags": [ "python", "python-3.x", "calculator" ], "Title": "Simple Calculator Program That Operates On Multiple Inputs" }
266129
<blockquote> <p>I have array [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4] so I want to move all duplicates at the end of the array [1, 2, 3, 4,1, 2, 2, 3, 3, 4, 4, 4]. is there is another best way to do the same <em><strong>Go</strong></em> Time O(n) and space O(1)</p> </blockquote> <pre><code>package main import &quot;fmt&quot; func main() { a := []int{1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4} key := make(map[int]bool) var original []int var duplicate []int for _, v := range a { if _, val := key[v]; !val { key[v] = true original = append(original, v) } else { duplicate = append(duplicate, v) } } fmt.Println(append(original, duplicate...)) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T05:27:04.667", "Id": "525826", "Score": "0", "body": "But your solution is not `O(1)` space. You use additional memory for `key` map, and `original`/`duplicate` slices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T05:33:50.180", "Id": "525828", "Score": "0", "body": "@demas I said is there any other way to do in space O(1). Please read my question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T05:43:03.683", "Id": "525829", "Score": "2", "body": "`Any other` means that you already have one solution and looking for `other`. Btw, you can decrease memory usage if you will use `map[int]int` where the `key` is a number in `a` and `value` is a number of occurrences this number in the `a`. And after that you can modify `a` in-place using this map. In this case you still have `O(n)` in time and `O(uniq(n))` in space." } ]
[ { "body": "<p>the full program available <a href=\"https://play.golang.org/p/a8mCEj36ddR\" rel=\"nofollow noreferrer\">here</a> outputs</p>\n<pre><code> original []int{1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4}\n sorted orig []int{1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4}\n withMap []int{1, 2, 3, 4, 1, 2, 2, 3, 3, 4, 4, 4}\n withSlice []int{1, 2, 3, 4, 1, 2, 3, 3, 2, 4, 4, 4}\n withBest []int{1, 2, 3, 4, 1, 2, 3, 3, 2, 4, 4, 4}\n\n original []int{3, 5, 3, 4, 1, 1, 2, 2, 2, 3, 3, 3, 5, 4, 4, 4, 4}\n sorted orig []int{1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5}\n withMap []int{3, 5, 4, 1, 2, 3, 1, 2, 2, 3, 3, 3, 5, 4, 4, 4, 4}\n withSlice []int{1, 2, 3, 4, 5, 1, 3, 2, 2, 3, 3, 3, 5, 4, 4, 4, 4}\n withBest []int{1, 2, 3, 4, 5, 1, 3, 2, 2, 3, 3, 3, 5, 4, 4, 4, 4}\n\n original []int{4, 3, 4, 3, 1, 2, 3, 4}\n sorted orig []int{1, 2, 3, 3, 3, 4, 4, 4}\n withMap []int{4, 3, 1, 2, 4, 3, 3, 4}\n withSlice []int{1, 2, 3, 4, 3, 4, 3, 4}\n withBest []int{1, 2, 3, 4, 3, 4, 3, 4}\n\n original []int{100, 150, 400, 302, 450}\n sorted orig []int{100, 150, 302, 400, 450}\n withMap []int{100, 150, 400, 302, 450}\n withSlice []int{100, 150, 302, 400, 450}\n withBest []int{100, 150, 302, 400, 450}\n</code></pre>\n<p>It contains this function, which based on some conditions will make use of either a map based algorithm or a slice based algorithm.</p>\n<pre><code>func dedupBest(in []int) ([]int, int) {\n ln := len(in)\n if ln &lt; 2 {\n return in, 1\n }\n min, max := minMax(in)\n if max &lt; ln {\n // in-place.\n for i := 0; i &lt; ln; i++ {\n v := in[i]\n for in[v] != v {\n in[v], in[i] = in[i], in[v]\n v = in[i]\n }\n }\n var e int\n for i := 0; i &lt; ln; i++ {\n if i == in[i] {\n in[e], in[i] = in[i], in[e]\n if in[e] == max {\n break\n }\n e++\n }\n }\n return in, e + 1\n }\n if (max-min)/ln &gt;= 70 {\n return dedupWithMap(in)\n }\n // with alloc.\n tmp := make([]vl, max-min+1, max-min+1)\n for i := 0; i &lt; ln; i++ {\n v := in[i]\n k := tmp[v-min]\n k.v = v\n k.c++\n tmp[v-min] = k\n }\n var e int\n for i := 0; i &lt; len(tmp); i++ {\n k := tmp[i]\n if k.c &gt; 0 {\n k.c--\n in[e] = k.v\n tmp[e] = k\n e++\n }\n }\n ee := e\n tmp = tmp[:e]\n for e &lt; len(in) {\n for i := 0; i &lt; len(tmp); i++ {\n k := tmp[i]\n for k.c &gt; 0 {\n k.c--\n in[e] = k.v\n e++\n }\n }\n }\n return in, ee\n}\n</code></pre>\n<p>It is faster when it can work without allocation when <code>max(list)</code> is smaller than <code>len(list)</code>. If, not, then a rapid estimation of the iteration cost is compared to a threshold to figure out which next algorithm should perform best.</p>\n<p>When working in place it simply swaps values to their corresponding natural position, duplicated values ends up wherever space exists.\nThen it iterates over all positions until <code>max(list)</code> is found to check if they belong to the current index, if not, the value is swapped to the end of the slice. This is fast when it does not have to iterate up to <code>len(list)</code></p>\n<p>When it has to allocate, it attempts to be faster by reducing the number of iterations using <code>min</code> / <code>max</code>. The method is a bit different as it uses a struct to build the frequencies and that it outputs duplicated items in sorted order.</p>\n<p>Also because it is a slice it does not require a bunch of allocations like a map can do when it has to grow.</p>\n<p>The benchmark and tests available <a href=\"https://play.golang.org/p/v8fRRLPWBRn\" rel=\"nofollow noreferrer\">here</a> outputs (something like) those results.</p>\n<p>In the benchmark the titles like <code>BenchmarkDedup/withMap____________1-1_________</code>, reads <code>../algorithm __vmax-len__</code>.</p>\n<p>Where <code>vmax</code> and <code>len</code> controls the length of the input slices and the amplitude of its values. Then, <code>rand.Intn</code> is used to generate some sequence to dedup.</p>\n<pre><code>$ go test -v -bench=. | prettybench\nbenchmark iter time/iter bytes alloc allocs\n--------- ---- --------- ----------- ------\nBenchmarkDedup/withMap____________1-1_________-4 24120418 48.90 ns/op 8 B/op 1 allocs/op\nBenchmarkDedup/withSlice__________1-1_________-4 141905514 8.43 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest___________1-1_________-4 133997004 8.77 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap___________10-10________-4 2641770 453.00 ns/op 304 B/op 8 allocs/op\nBenchmarkDedup/withSlice_________10-10________-4 32163962 34.20 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest__________10-10________-4 33589612 36.60 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap__________100-100_______-4 147038 8015.00 ns/op 6203 B/op 27 allocs/op\nBenchmarkDedup/withSlice________100-100_______-4 3641140 315.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest_________100-100_______-4 3614636 295.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap_________1000-1000______-4 17374 68439.00 ns/op 51399 B/op 71 allocs/op\nBenchmarkDedup/withSlice_______1000-1000______-4 232448 5083.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest________1000-1000______-4 395924 2912.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap________10000-10000_____-4 1779 653592.00 ns/op 644594 B/op 302 allocs/op\nBenchmarkDedup/withSlice______10000-10000_____-4 13440 88416.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest_______10000-10000_____-4 14128 87053.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap_______100000-100000____-4 138 8634563.00 ns/op 8690895 B/op 2391 allocs/op\nBenchmarkDedup/withSlice_____100000-100000____-4 1188 994715.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest______100000-100000____-4 1200 985550.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap_____10000000-10000000__-4 1 1562777417.00 ns/op 765453080 B/op 251072 allocs/op\nBenchmarkDedup/withSlice___10000000-10000000__-4 4 263950640.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest____10000000-10000000__-4 4 259640983.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap____100000000-100000000_-4 1 20871837757.00 ns/op 9290520352 B/op 2457520 allocs/op\nBenchmarkDedup/withSlice__100000000-100000000_-4 1 4611359207.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest___100000000-100000000_-4 1 4476460807.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap_________1000-100_______-4 135344 9792.00 ns/op 5457 B/op 27 allocs/op\nBenchmarkDedup/withSlice_______1000-100_______-4 251731 4435.00 ns/op 16384 B/op 1 allocs/op\nBenchmarkDedup/withBest________1000-100_______-4 262458 4228.00 ns/op 16384 B/op 1 allocs/op\nBenchmarkDedup/withMap______1000000-100_______-4 116809 9913.00 ns/op 5419 B/op 25 allocs/op\nBenchmarkDedup/withSlice____1000000-100_______-4 424 2686605.00 ns/op 15228933 B/op 1 allocs/op\nBenchmarkDedup/withBest_____1000000-100_______-4 117105 10059.00 ns/op 5421 B/op 25 allocs/op\nBenchmarkDedup/withMap__________100-1000______-4 26851 44487.00 ns/op 29987 B/op 37 allocs/op\nBenchmarkDedup/withSlice________100-1000______-4 544766 2086.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest_________100-1000______-4 548635 2026.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withMap__________100-1000000___-4 33 36228986.00 ns/op 53197316 B/op 65 allocs/op\nBenchmarkDedup/withSlice________100-1000000___-4 506 2304789.00 ns/op 0 B/op 0 allocs/op\nBenchmarkDedup/withBest_________100-1000000___-4 516 2301701.00 ns/op 0 B/op 0 allocs/op\nok test/d/duplicate 91.888s\n</code></pre>\n<p>Within those results you can find the one case where the map is more efficient than the slice and the branching helps. In practical terms this case happens when <code>max(list)</code> is 100d time bigger than <code>len(list)</code>. This happens because the algorithm cannot work in place and must allocate a slice of length equal to <code>max(list)</code></p>\n<pre><code>BenchmarkDedup/withMap______1000000-100_______-4 116809 9913.00 ns/op 5419 B/op 25 allocs/op\nBenchmarkDedup/withSlice____1000000-100_______-4 424 2686605.00 ns/op 15228933 B/op 1 allocs/op\nBenchmarkDedup/withBest_____1000000-100_______-4 117105 10059.00 ns/op 5421 B/op 25 allocs/op\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T19:54:53.837", "Id": "266458", "ParentId": "266131", "Score": "-1" } }, { "body": "<p>Using your algorithm, there's some memory management tweaks to improve performance:</p>\n<ul>\n<li><code>map[int]bool</code> can be replaced by <code>map[int]struct{}</code> - since only map-key lookup is needed to detect a duplicate</li>\n<li>if you know the output size of a slice before hand, you can pre-allocate the exact size and place values precisely in their various indices - avoiding reallocs with the built-in <code>append</code> function</li>\n</ul>\n<hr />\n<pre><code>func ver2(in []int) (out []int) {\n\n key := make(map[int]struct{}) // use an empty struct - key presence is all we need\n out = make([]int, len(in)) // pre-alloc output slice\n\n var dups []int\n\n j := 0\n for _, v := range in {\n if _, ok := key[v]; !ok {\n key[v] = struct{}{}\n out[j] = v\n j++\n } else {\n dups = append(dups, v)\n }\n }\n\n copy(out[j:], dups) // copy dups in place - rather than append\n return\n}\n</code></pre>\n<p><a href=\"https://play.golang.org/p/5yiqe76Zgu9\" rel=\"nofollow noreferrer\">https://play.golang.org/p/5yiqe76Zgu9</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T22:03:17.100", "Id": "526663", "Score": "0", "body": "Also if you don't care about the order of the duplicates, then they could be placed at the end of the slice working inward - and avoid the need for a `dups` slice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T21:28:20.350", "Id": "266565", "ParentId": "266131", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T14:36:38.793", "Id": "266131", "Score": "1", "Tags": [ "array", "go" ], "Title": "move duplicate items at the end of the array" }
266131
<p>I have a dataframe of cases that score 0-1 on a group of binary attributes.</p> <p>What I want to do is extract all possible ombinations of attribute triplets (e.g. A/B/C, A/B/D... out of A-E) and then sum for each possible combination triplet the number of times a case in the original dataframe matched those attributes.</p> <p>Using <code>dplyr</code> logic as well as <code>lapply</code> I can solve this problem but the performance is very bad, especially for bigger dataframes and more possible attributes. My real dataframe leads to a test matrix of &gt;1000 possible triplets and the function performs very bad on this.</p> <p>Please help me optimize the code while ideally staying within the <code>dplyr</code> framework as much as possible.</p> <pre><code>library(tidyverse) # Create a test data frame and vector of relevant variables test_df &lt;- data.frame(ID = c(1,2,3,4), Target = c(1,1,0,0),F_A = c(1,0,0,1),F_B = c(0,1,0,1),F_C = c(1,1,0,0),F_D = c(0,1,1,0),F_E = c(1,0,0,1)) invars = c(&quot;F_A&quot;,&quot;F_B&quot;,&quot;F_C&quot;,&quot;F_D&quot;,&quot;F_E&quot;) NumOfElements = 3 # Create a full matrix of all relevant variables in NumOfElements-combinations combn(invars,NumOfElements) %&gt;% t() %&gt;% as.data.frame() %&gt;% rowid_to_column(&quot;ID&quot;) %&gt;% select(ID, T1 = V1, T2 = V2, T3 = V3) %&gt;% unite(&quot;Test&quot;,starts_with(&quot;T&quot;),sep = &quot;|&quot;,remove = FALSE,na.rm = TRUE) %&gt;% {.} -&gt; test_matrix # Brute Force Function to calculate number of all IDs that fullfill the test rules bruteForce_size = function(rule_iterator,source_df,invars){ source_df %&gt;% pivot_longer(cols = c(-ID,-Target), names_to = &quot;Affinity&quot;, values_to = &quot;Value&quot;) %&gt;% mutate(Value = ifelse(Value ==1, Affinity,NA_character_)) %&gt;% pivot_wider(names_from = Affinity, values_from = Value) %&gt;% unite(&quot;Test&quot;,invars,sep = &quot;|&quot;,remove = FALSE,na.rm = TRUE) %&gt;% mutate(Size = as.numeric(rule_iterator == Test)) %$% sum(Size) } # Calculate and attach sizes to test_matrix test_matrix %&gt;% mutate(Size = unlist(lapply(Test, bruteForce_size, test_df))) </code></pre>
[]
[ { "body": "<p>Maybe something like this, with <code>base</code> functions:</p>\n<pre><code>rez &lt;- apply(test_matrix[, c('T1', 'T2', 'T3')], 1, function(x) {\n y &lt;- test_df[, x]\n sum(rowSums(y) == 3)\n}, simplify = T)\nrez # vector\n\ntest_matrix$Size &lt;- rez\ntest_matrix\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T13:46:02.650", "Id": "266528", "ParentId": "266132", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T14:36:56.833", "Id": "266132", "Score": "0", "Tags": [ "combinatorics", "r" ], "Title": "Increase speed of lapply function identifying the sum of all existing combinations" }
266132
<p>Here I have a multidimensional list in python. Suppose I take an input, how do I find the number of adjacent elements of that input which are alphabets other than itself? If there are multiple indices at which the element is placed, then we have to print the maximum of all possibility. For example, the number of adjacent elements which are equal to 'R' is 2.</p> <pre><code>z=input() #suppose c='R' #print the number of equal and adjacent elements, for c='R' it is 2 l=[['G', '.', 'B', 'C'], ['A', '.', 'R', 'Z'], ['.', '.', 'R', 'B']] #G.BC #A.RZ #..RB </code></pre> <p>This is how I tried it.</p> <pre><code>from collections import OrderedDict x,y,z=input().split() l=[] c=[] x,y=int(x),int(y) def f(e): ls=[] a=e[0] b=e[1] for i in range(int(x)): for j in range(int(y)): t=l[i][j] if i==a and t!=z and t!='.': if j==b-1 or j==b+1: ls.append(t) if j==b and t!=z and t!='.': if i==a-1 or i==a+1: ls.append(t) ls=list(OrderedDict.fromkeys(ls)) return ls for i in range (0,int(x)): s=&quot;&quot; s=input() sl=list(s) for j in range(int(y)): if z==sl[j]: c.append([i,j]) l.append(sl) d=0 for i in range(len(c)): m=f(c[i]) d=max(d,len(m)) print(d) </code></pre> <p>Here function f is used to create a list of elements which satisfy the conditions. z is the character which the user inputs and x,y is the dimension of the list.</p> <pre><code> 'OO WW WW' #Here if the input is W, then the answer should be one. 'G.B. .RR. TTT.' #Here if input is R, then the answer is 2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T21:09:06.563", "Id": "525712", "Score": "2", "body": "Can you provide extra examples of expected input and output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T13:01:00.000", "Id": "525752", "Score": "2", "body": "Your current wording is unclear. You ask how to find the number of adjacent elements, but then show an implementation. Is this implementation working?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T14:00:05.077", "Id": "525760", "Score": "0", "body": "So if I understand correctly, you are looking for the count of unique letters that are not equal to your target letter, after making a list of all neighbors of all instances of that target letter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:09:06.970", "Id": "525781", "Score": "0", "body": "@Flater Yes, and also it should not be equal to '.'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:29:37.540", "Id": "525788", "Score": "0", "body": "What is this code actually supposed to be doing? Is there a problem that this solves? I think that might help clear up what's going on" } ]
[ { "body": "<ul>\n<li>To be honest, I can't quite confirm what you actually want. Since you ask in <code>Code Review</code>, I assume you want someone to review your code and give some advice.</li>\n</ul>\n<h3>advice</h3>\n<ol>\n<li>Please always use meaningful name to variable and function name, don't use something like <code>a</code>, <code>b</code>, <code>x</code>, <code>y</code>, <code>f</code>. They are confusing to the people who read your code. When you read the code and following advice, you will find it. It is OK use <code>i</code>, <code>j</code> in some simple loop. So I replaced most of them, some of them may be not so proper.</li>\n<li>There is no need to record the adjacent elements in <code>ls</code>(result), just <code>+1</code> to the result of <code>f</code>(find_adjacent_elements).</li>\n<li>There is also no need to check the whole <code>l</code>(map), just check the <code>z</code>(base_char) up\\down\\left\\right 4 direction. It can speed up your code especially the size of map is huge.</li>\n<li>Please read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>, it can make your code more readable. Such as <code>a=e[0]</code> should be <code>a = e[0]</code>.</li>\n<li>I fix some other small issues, please check the difference between my code and your code.</li>\n</ol>\n<h3>fixed code:</h3>\n<pre><code>def find_adjacent_elements(base_pos):\n result = 0\n directions = [[1,0],[-1,0],[0,1],[0,-1]]\n for direction in directions:\n try:\n adjacent_element = map[base_pos[0] + direction[0]][base_pos[1] + direction[1]]\n if adjacent_element != base_char and adjacent_element != &quot;.&quot;:\n result += 1\n except IndexError:\n pass\n return result\n \nprint(&quot;please input the columns,rows and base character&quot;)\ncolumns,rows,base_char = input().split()\nmap = []\nbase_char_pos = []\ncolumns,rows = int(columns),int(rows)\nfor i in range(columns):\n map_line = list(input())\n for j in range(rows):\n if base_char == map_line[j]:\n base_char_pos.append([i,j])\n map.append(map_line)\nans = 0\nfor i in range(len(base_char_pos)):\n ans = max(ans,find_adjacent_elements(base_char_pos[i]))\nprint(ans)\n</code></pre>\n<h3>test:</h3>\n<pre><code>please input the columns,rows and base character\n4 4 R\n..A.\n.BRC\n.DRE\n..F.\n\n3\n\nplease input the columns,rows and base character\n2 2 R\nR.\n.R\n\n0\n\nplease input the columns,rows and base character\n3 2 W\nOO\nWW\nWW\n\n1\n\nplease input the columns,rows and base character\n3 4 R\nG.B.\n.RR.\nTTT.\n\n2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T09:17:24.567", "Id": "525737", "Score": "0", "body": "Thank you very much for your advice, I will keep those points in mind . I understood how you just checked the positions around the base character made it more efficient. Thanks for taking out your time and helping me!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T07:27:49.380", "Id": "266153", "ParentId": "266135", "Score": "2" } } ]
{ "AcceptedAnswerId": "266153", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T14:57:58.870", "Id": "266135", "Score": "-4", "Tags": [ "python" ], "Title": "How to find adjacent elements in multidimensional list in Python?" }
266135
<p>I have this class</p> <pre><code>export class CurrentLanguageService { currentLanguage(loggedUser: User): string { if (sessionStorage.getItem(LanguageStorageKey) !== null) { if (Object.keys(Languages).includes(sessionStorage.getItem(LanguageStorageKey))) { return sessionStorage.getItem(LanguageStorageKey); } else { return Languages[Languages.nl]; } } else { if (loggedUser.language) { return Languages[loggedUser.language]; } else { return Languages[Languages.nl]; } } } } </code></pre> <p>You will see that I have so many conditions, is there a way that some one knows is this is proper coding, thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T16:05:36.537", "Id": "525693", "Score": "5", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T16:10:41.230", "Id": "525695", "Score": "5", "body": "Does the [tag:c#] tag really apply, or is it just typescript? Also, it would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" } ]
[ { "body": "<p>I don't think the logic is correct. Why return the default language if there is a language corresponding to the language storage key but not contained in <code>Object.keys</code>? I'd think the language of the logged user to be the better alternative.</p>\n<pre><code>var language = sessionStorage.getItem(LanguageStorageKey);\nif (language !== null &amp;&amp; Object.keys(Languages).includes(language)) {\n return language;\n} else if (loggedUser.language) {\n return Languages[loggedUser.language];\n} else {\n return Languages[Languages.nl];\n}\n</code></pre>\n<p>This simplification is possible due to these points:</p>\n<ol>\n<li>Combining two conditions into one if-statement with <code>&amp;&amp;</code>. Note that Java Script (and thus TypeScript) uses <a href=\"https://stackoverflow.com/questions/12554578/does-javascript-have-short-circuit-evaluation\">short-circuit-evaluation</a>. I.e., the second condition is only evaluated if the first is <code>true</code> (in the case of <code>&amp;&amp;</code>).</li>\n<li>Testing the conditions in a sequential way instead of using nested if-statements.</li>\n<li>Returning the default language (nl) at one place due to a better logic.</li>\n<li>Storing the result of the call <code>sessionStorage.getItem(LanguageStorageKey)</code> into a temporary variable instead of performing the call three times. This leads not only to a small performance gain but also makes the code more readable.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T16:50:35.817", "Id": "266142", "ParentId": "266140", "Score": "3" } }, { "body": "<h1>Beautify</h1>\n<p>First thing that you need to do: apply refactoring <a href=\"https://refactoring.guru/extract-variable\" rel=\"nofollow noreferrer\">Extract variable</a>.\nThis will make code cleaner &amp; faster.</p>\n<pre><code>const storedLanguage = sessionStorage.getItem(LanguageStorageKey);\nif (storedLanguage !== null) {\n if (Object.keys(Languages).includes(storedLanguage)) {\n return storedLanguage;\n } else {\n return Languages[Languages.nl];\n }\n} else {\n …\n}\n</code></pre>\n<p>After that let's get rid of if-s by applying <a href=\"https://refactoring.guru/replace-nested-conditional-with-guard-clauses\" rel=\"nofollow noreferrer\">Replace Nested Conditional with Guard Clauses\n</a></p>\n<pre><code>const storedLanguage = sessionStorage.getItem(LanguageStorageKey);\nif (storedLanguage !== null &amp;&amp; Object.keys(Languages).includes(storedLanguage)) {\n return storedLanguage;\n}\n\nif (loggedUser.language) {\n return Languages[loggedUser.language];\n}\n\nreturn Languages[Languages.nl];\n</code></pre>\n<p>And now we can use <a href=\"https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing\" rel=\"nofollow noreferrer\">Nullish Coalescing</a> operator to simplify our code</p>\n<pre><code>const storedLanguage = sessionStorage.getItem(LanguageStorageKey);\nif (storedLanguage !== null &amp;&amp; Object.keys(Languages).includes(storedLanguage)) {\n return storedLanguage;\n}\n\nreturn Languages[loggedUser.language ?? Languages.nl];\n</code></pre>\n<p>Now, I would suggest to leverage <code>in</code>-syntax to make things shorter:</p>\n<pre><code>if (storedLanguage !== null &amp;&amp; storedLanguage in Languages) {\n …\n</code></pre>\n<p>Next trick can be considered bad in some code styles. Typically, typescript will deny you to perform check like <code>null in smth</code>, because of typing. But he is wrong here.\nWe can use <a href=\"https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator\" rel=\"nofollow noreferrer\">non-null assertion operator</a></p>\n<pre><code>const storedLanguage = sessionStorage.getItem(LanguageStorageKey);\nif (storedLanguage! in Languages) {\n return storedLanguage;\n}\n\nreturn Languages[loggedUser.language ?? Languages.nl];\n</code></pre>\n<h1>Same level of abstraction</h1>\n<p>Let's make things more clear. You are checking that storedLanguage is in enum.\nLet's build utility function for it</p>\n<pre><code>function keepIfInEnum&lt;T&gt;(\n value: string,\n enumObject: { [key: string]: T }\n) {\n if (Object.values(enumObject).includes((value as unknown) as T)) {\n return (value as unknown) as T;\n } else {\n return undefined;\n }\n}\n</code></pre>\n<p>Now we can write:</p>\n<pre><code>return keepIfInEnum(sessionStorage.getItem(LanguageStorageKey)) \n ?? Languages[loggedUser.language ?? Languages.nl];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T17:32:50.627", "Id": "266144", "ParentId": "266140", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T16:00:57.023", "Id": "266140", "Score": "-2", "Tags": [ "c#", "typescript" ], "Title": "So many if and else conditions" }
266140
<p>I've been doing project euler problems in Haskell, and often I've found the need to get the value that gives the maximum of a function.</p> <p>For example,</p> <pre><code>answer = argmaximum $ map collatzLength [1..10^6] </code></pre> <p>Where collatzLength is a previously defined function.</p> <p>I came up with this code, which is heavily influenced by learning Ocaml. I run a helper function that has variables that keep track of the best value index and best index so far. It works perfectly for positive lists, but it seems like there's a better way.</p> <p>Is there a less clunky way to implement argmaximum?</p> <pre><code>argmaximum :: (Ord a, Num a) =&gt; [a] -&gt; a argmaximum lst = helper lst 0 0 0 where helper (x:xs) current bestVal bestIndex | current &gt; bestVal = helper xs (current + 1) x current | otherwise = helper xs (current + 1) bestVal bestIndex helper null _ _ bestIndex = bestIndex </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T09:47:33.853", "Id": "525743", "Score": "3", "body": "I believe you are looking for `maxmimumBy (comparing collatzLength) [1..10^6]` or `maximumBy (compare \\`on\\` collatzLength) [1..10^6]`. I’m not sure I understand how your function works, unless `current > bestVal` is a typo and meant to be `x > bestVal`. It’s late so I’m afraid I cannot review more thoroughly - I do hope at least one of my suggestions type checks." } ]
[ { "body": "<p>What you have implemented here is strictly speaking not argmaximum, but finding a maximum index in a list. The difference is that your argmaximum will not return the correct value for invocations that don't <code>map</code> from <code>[1..?]</code></p>\n<p>Instead of that, you probably wanted something that's typed as follows:</p>\n<pre><code>argmax :: (Ord a, Num a) =&gt; (b -&gt; a) -&gt; [b] -&gt; b\nargmax f (d:ds) = ...\n</code></pre>\n<p>That way you can write <code>argmax collatzLength [500..10^6]</code> and still get the correct answer :)</p>\n<p>By the way: <a href=\"https://codereview.stackexchange.com/users/183567/cole\">@cole</a> suggested using <code>maximumBy</code> and <code>comparing</code> for the implementation, which I wholeheartedly agree on :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T13:27:45.453", "Id": "266203", "ParentId": "266148", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T01:00:20.400", "Id": "266148", "Score": "1", "Tags": [ "haskell" ], "Title": "Finding the argmaximum of a list in Haskell" }
266148
<p>I created a simple Unicode-based markup language called <em>Incipit</em> and an <code>awk(1)</code> script to convert a text written in Incipit into html or troff -ms.</p> <p>A example of text in incipit is below, the result of which, converted to troff -ms and then to ps and pdf is <a href="https://raw.githubusercontent.com/phillbush/incipit/master/README.pdf" rel="nofollow noreferrer">here</a></p> <pre class="lang-none prettyprint-override"><code> Incipit: A Unicode-based Text Markup Language. Seninha (aka phillbush). The ‘Incipit Markup Language’ (or ‘Incipit’, for short) is a plain text markup language that uses Unicode characters and the structure of the text itself to format documents. ‘Incipit’ is also the name of an ‘awk(1)’ script that converts ‘Incipit’ documents to html or troff. In the ‘Incipit Markup Language’, a paragraph is a block of text delimited by blank lines. A paragraph may be preceded by a section header and succeded by a figure. Enumerations (also knonw as “lists”) are special types of paragraphs (although I interpret a enumeration as the continuation of the paragraph before it). In this document, I call “period” sentences delimited by a period. I also call “colon” a segment of text delimited by a colon or semi-colon. § Punctuation Incipit uses Unicode characters (called “punctuation” in this document), alongside the structure of the text, to format documents. For example, the section character (`§`, U+00A7) is used to markup section headers. The bullet character (`•`, U+2022) is used to markup bulleted lists. Punctuations are mostly used within a paragraph. Those punctuations (called inline punctuation) markup emphases, references, topics or preformated text. Punctuations cannot be nested: a portion of text is either emphasized, or it is preformated, never both. The types of inline punctuations are enumerated below. • Emphasis: Text ‘between single quotes’ is emphasized. It is formated in italic font and the punctuation is removed in the final document. • Topic: Text “between double quotes” is topicalized. It is formated in italic font and the punctuation is kept in the final document. • Reference: Text «between double angle quotes» is reference. More on that in a paragraph below. • Preformated: Text `between grave accents` or {between curly braces} is preformated. It is formated in monospaced font and the punctuation is removed in the final document. • Meta text: Text ⟨between angle braces⟩ is meta text. It is formated in monospaced font and the punctuation is kept in the final document. .Typing punctuation. If you use Unix, you can either configure your keybindings or configure the Compose key to insert punctuation and other characters not found on a regular keyboard. §§ Sections Paragraphs can be grouped in sections, which can be nested. A section is a line whose first characters are section punctuations (`§`, U+00A7). A section can be marked by a one or more section punctuations. The number of time that punctuation occurs represents the level of the section. For example, a first-level section begins with `§`; a second-level section begins with `§§`, and so on. §§ Enumerations An enumeration, also known as list, is a hierarchical grouping of periods, called the enumeration items. Each item begins with zero or more tab characters followed the enumeration punctuation (`•`, U+2022), also knon as ‘bullet’. The number of tabs in the beginning of an item identifies the item level: zero tab for first-level items; one tab for second-level items; and so on. .Enumeration label. When formated, each enumeration item is usually preceded by a bullet. However, it can be changed by following the enumeration punctuation by a string between parentheses. This can be used for ordered lists, when the label is a number or letter. .Enumeration incipit. Each enumeration item can have a incipit colon, which will be explained on the “§ Incipit” section below. The incipit colon is a colon describing the topic of the item. The following is an example of enumeration. • (A) First item: This is the first item of a labeled enumeration. This item also contains an incipit colon. • (B) Second item: This is the second item of a labeled enumeration. It also contains an incipit colon. • (C) Third item. • First subitem of third item. • Second subitem of third item. • Third subitem of third item. • Fourth subitem of third item. • (D) Fourth item. • (E) Fifth item. § Incipit The word “incipit” comes from the Latin and means “it begins”. The incipit of a text is the first few words of the text. In the ‘Incipit Markup Language’, incipits are initial elements of the text used to format the text itself. The incipit of a document is its first paragraph (which contains the title and some meta information); the incipit of a paragraph is its first period (aka sentence); the incipit of a period is its first colon (the part separated by colon). In the ‘Incipit’ Markup Language, a text unit can have no incipit. A document without incipit is a document without title. A paragraph without incipit is a paragraph without its special first period. This implies that certain units of text are made up of two parts: an optional incipit and a body. .The incipit of a document. The first paragraph of a document is its incipit. If the document begins with a blank line or with a figure or enumeration, the document has no incipit. The first period (ie', the first sentence) of the document's incipit is the title. If this period has a incipit colon, this colon is the main title and the rest is the subtitle. For example, this document has an incipit paragraph, which has an incipit period (the full title), which has an incipit colon (the main title). The remaining periods are interpreted depending on the output format. In troff, the second period is the author, the third period is the institution, and the following periods are the abstract of the document. .The incipit of a paragraph. If the first period of a paragraph begins with a period punctuation, this paragraph contains a incipit period. This incipit period, called the title of the paragraph, is formated in bold font. In the source plain text of this document, the incipit of a paragraph is written alone in aline above the rest of the paragraph; but this is not necessary, the incipit period can be written in the same line of the rest of the paragraph. .The incipit of a period. In an enumeration, the first colon of the first period of a enumerated item is the item's incipit colon. This incipit colon, called title of the enumeration, is formated in bold font. The first enumeration of this document, listing the types of inline punctuations, contains incipit colons. § Figures Figures are text delimited between curly brackets. The opening curly bracket must be the last character in a line and the closing curly bracket must be the first character in a line. The most simple example of figure is code listing, an example of which, copied from the second edition of “The C Programming Language” book, is presented below. Code is usually idented with a tab, so the first tab of each code line is removed in the final document. { #include &lt;stdio.h&gt; main() { printf(&quot;hello, world\n&quot;; } } §§ Images TODO. §§ Tables TODO. §§ Quotation TODO. § Script There is an ‘awk(1)’ script (actually, a shell script calling ‘awk(1)’) used for converting text from the ‘Incipit Markup Language’ into troff (using the -ms macro) or html. The manual of this command is presented below. { INCIPIT(1) General Commands Manual INCIPIT(1) NAME incipit - format incipit document SYNOPSIS incipit [-T format] file... DESCRIPTION incipit convert files marked up in the Incipit Markup Language into troff using the -ms format (the default) or into html. The formated file is written to standard output. The options are as follows: -T format Convert to format (either &quot;ms&quot; or &quot;html&quot;). If not supplied, consider &quot;ms&quot; as default. SEE ALSO troff(1), ms(7) } </code></pre> <p>Here's the awk script:</p> <pre><code>#!/bin/sh # show usage and exit usage() { echo &quot;usage: incipit [-T output] [file]&quot; &gt;&amp;2 exit 1 } while getopts 'T:' ch do case &quot;$ch&quot; in T) type=&quot;$OPTARG&quot; ;; *) usage ;; esac done shift $(( OPTIND - 1 )) awk -v &quot;type=$type&quot; ' # unget token function ungettok() { if (!eof) { savedtok = 1 } } # get token function gettok( a, n) { if (eof) return -1 if (savedtok) { savedtok = 0 return 1 } if (length(line) == 0) { if ((getline line) &lt;= 0) { eof = 1 return -1 } else { n = split(line, a) if (n == 0) { toktype = BLANK tok = line line = &quot;&quot; } else if (match(line, /^\t*• *(\([^)]+\))? *([^:]+:)?/)) { toktype = ENUMMARK tok = substr(line, RSTART, RLENGTH) line = substr(line, RSTART + RLENGTH) } else if (match(line, /^(§)+[ \t]*/)) { toktype = SECTIONMARK tok = substr(line, RSTART, RLENGTH) sub(/[ \t]*/, &quot;&quot;, tok) line = substr(line, RSTART + RLENGTH) } else if (line ~ /[ \t]*{$/) { toktype = FIGUREMARK tok = line line = &quot;&quot; } else { toktype = NONE tok = line line = &quot;&quot; } } } else { toktype = NONE tok = line line = &quot;&quot; } return 1 } # get id from string function genid(s) { gsub(/(§)[ \t]*/, &quot;#&quot;, s) gsub(/[ \t]+/, &quot;-&quot;, s) gsub(/[^-#A-Za-z0-9_/]/, &quot;&quot;, s) s = tolower(s) return s } # print code (for code figures) function printcode(s) { sub(/^\t/, &quot;&quot;, s) if (troff) { gsub(/\\/, &quot;\\e&quot;, s) gsub(/&quot;/, &quot;\\(dq&quot;, s) gsub(/'&quot;'&quot;'/, &quot;\\(aq&quot;, s) gsub(/`/, &quot;\\(aa&quot;, s) gsub(/-/, &quot;\\-&quot;, s) sub(/^\./, &quot;\\\\\\&amp;&amp;&quot;, s) } printf &quot;%s\n&quot;, s } # print inline code function printinlinecode(s) { if (troff) { gsub(/\\/, &quot;\\e&quot;, s) gsub(/&quot;/, &quot;\\(dq&quot;, s) gsub(/'&quot;'&quot;'/, &quot;\\(aq&quot;, s) gsub(/`/, &quot;\\(aa&quot;, s) gsub(/-/, &quot;\\-&quot;, s) } printf &quot;%s&quot;, s } # print text function printnormal(s) { sub(/^[ \t]+/, &quot;&quot;, s) printf &quot;%s\n&quot;, s } # do inline punctuation expansion text function expandpunct(after, before, punct) { before = &quot;&quot; punct = &quot;&quot; while (match(after, /\{|\}|⟨|⟩|`|‘|’|“|”/)) { before = before substr(after, 1, RSTART - 1) punct = substr(after, RSTART, RLENGTH) after = substr(after, RSTART + RLENGTH) if (puncttype) { if (puncttype == &quot;{&quot; &amp;&amp; punct == &quot;}&quot;) { before = before markup[type, &quot;PRE&quot;, &quot;END&quot;] puncttype = &quot;&quot; } else if (puncttype == &quot;⟨&quot; &amp;&amp; punct == &quot;⟩&quot;) { before = before markup[type, &quot;META&quot;, &quot;END&quot;] puncttype = &quot;&quot; } else if (puncttype == &quot;`&quot; &amp;&amp; punct == &quot;`&quot;) { before = before markup[type, &quot;PRE&quot;, &quot;END&quot;] puncttype = &quot;&quot; } else if (puncttype == &quot;‘&quot; &amp;&amp; punct == &quot;’&quot;) { before = before markup[type, &quot;EMPHASIS&quot;, &quot;END&quot;] puncttype = &quot;&quot; } else if (puncttype == &quot;“&quot; &amp;&amp; punct == &quot;”&quot;) { before = before markup[type, &quot;TOPIC&quot;, &quot;END&quot;] puncttype = &quot;&quot; } } else if (punct == &quot;{&quot; || punct == &quot;`&quot; || punct == &quot;⟨&quot; || punct == &quot;“&quot; || punct == &quot;‘&quot;) { if (punct == &quot;{&quot;) { before = before markup[type, &quot;PRE&quot;, &quot;BEG&quot;] } else if (punct == &quot;`&quot;) { before = before markup[type, &quot;PRE&quot;, &quot;BEG&quot;] } else if (punct == &quot;⟨&quot;) { before = before markup[type, &quot;META&quot;, &quot;BEG&quot;] } else if (punct == &quot;‘&quot;) { before = before markup[type, &quot;EMPHASIS&quot;, &quot;BEG&quot;] } else if (punct == &quot;“&quot;) { before = before markup[type, &quot;TOPIC&quot;, &quot;BEG&quot;] } puncttype = punct } } return before after } # print text marked up with inline punctuation function printmarkup(s) { sub(/^[ \t]+/, &quot;&quot;, s) printf &quot;%s\n&quot;, expandpunct(s) } # parse document title function title( id) { printf &quot;%s&quot;, markup[type, &quot;TITLE&quot;, &quot;BEG&quot;] printnormal(tok) if (substr(tok, length(tok), 1) == &quot;:&quot;) { if (gettok() &gt; 0) { if (toktype == NONE) { printf markup[type, &quot;SUBTITLE&quot;, &quot;BEG&quot;], genid(tok) printmarkup(tok) printf markup[type, &quot;SUBTITLE&quot;, &quot;END&quot;] } else { ungettok() } } } printf &quot;%s&quot;, markup[type, &quot;TITLE&quot;, &quot;END&quot;] } # parse document incipit (heading) function heading() { printf &quot;%s&quot;, markup[type, &quot;HEADING&quot;, &quot;BEG&quot;] printf &quot;%s&quot;, markup[type, &quot;HEADING1&quot;, &quot;BEG&quot;] printmarkup(tok) printf &quot;%s&quot;, markup[type, &quot;HEADING1&quot;, &quot;END&quot;] if (gettok() &gt; 0) { if (toktype == NONE) { printf &quot;%s&quot;, markup[type, &quot;HEADING2&quot;, &quot;BEG&quot;] printmarkup(tok) printf &quot;%s&quot;, markup[type, &quot;HEADING2&quot;, &quot;END&quot;] } else { ungettok() } } printf &quot;%s&quot;, markup[type, &quot;HEADING&quot;, &quot;END&quot;] } # parse abstract (part of document incipit) function abstract() { printf &quot;%s&quot;, markup[type, &quot;ABSTRACT&quot;, &quot;BEG&quot;] while (!eof &amp;&amp; toktype == NONE) { printmarkup(tok) if (gettok() &gt; 0) { if (toktype == NONE) { printf &quot;%s&quot;, markup[type, &quot;SUBTITLE&quot;, &quot;BEG&quot;] printmarkup(tok) printf &quot;%s&quot;, markup[type, &quot;SUBTITLE&quot;, &quot;END&quot;] } else { ungettok() } } } printf &quot;%s&quot;, markup[type, &quot;ABSTRACT&quot;, &quot;END&quot;] ungettok() } # parse document incipit function docincipit( n) { while (!eof &amp;&amp; toktype == NONE) { if (n == 0) { title() } else if (n == 1) { heading() } else if (n == 2) { abstract() } else { ungettok() return } gettok() n++ } ungettok() } # parse paragraph function paragraph( rem) { printf &quot;%s&quot;, markup[type, &quot;PARAGRAPH&quot;, &quot;BEG&quot;] if (substr(tok, 1, 1) == &quot;.&quot;) { rem = &quot;&quot; printf &quot;%s&quot;, markup[type, &quot;PARATITLE&quot;, &quot;BEG&quot;] tok = substr(tok, 2) match(tok, /^[^.]*[.]? */) rem = substr(tok, RSTART + RLENGTH) tok = substr(tok, RSTART, RLENGTH) printmarkup(tok) printf &quot;%s&quot;, markup[type, &quot;PARATITLE&quot;, &quot;END&quot;] if (rem != &quot;&quot;) printmarkup(rem) gettok() } while (!eof &amp;&amp; toktype == NONE) { printmarkup(tok) gettok() } printf &quot;%s&quot;, markup[type, &quot;PARAGRAPH&quot;, &quot;END&quot;] ungettok() } # parse figure function figure( ret, fig) { if (tok ~ &quot;^IMAGE:[ \t]&quot;) { fig = IMAGE printf &quot;%s&quot;, markup[type, &quot;IMAGE&quot;, &quot;BEG&quot;] } else if (tok ~ &quot;^VIDEO:[ \t]&quot;) { fig = VIDEO printf &quot;%s&quot;, markup[type, &quot;VIDEO&quot;, &quot;BEG&quot;] } else { fig = CODE printf &quot;%s&quot;, markup[type, &quot;CODE&quot;, &quot;BEG&quot;] } line = &quot;&quot; while ((ret = (getline)) == 1) { if ($0 ~ /^}[ \t]*$/) break if (fig == CODE) { printcode($0) } } if (ret != 1) { eof = 1 } if (fig == CODE) { printf &quot;%s&quot;, markup[type, &quot;CODE&quot;, &quot;END&quot;] } else if (fig == IMAGE) { printf &quot;%s&quot;, markup[type, &quot;IMAGE&quot;, &quot;END&quot;] } else if (fig == VIDEO) { printf &quot;%s&quot;, markup[type, &quot;VIDEO&quot;, &quot;END&quot;] } } # parse enumeration function enumeration( lvl, enumlvl, label, colon) { # TODO: we are not using the markup[] array here, but we should # TODO: add support for enumeration in html while (!eof &amp;&amp; (toktype == NONE || toktype == ENUMMARK)) { if (toktype == ENUMMARK) { label = &quot;&quot; colon = &quot;&quot; lvl = 0 while (tok ~ /^\t/) { lvl++ sub(/^\t/, &quot;&quot;, tok) } sub(/^• */, &quot;&quot;, tok) while (enumlvl &gt; lvl) { printf &quot;%s&quot;, markup[type, &quot;ITEM&quot;, &quot;END&quot;] printf &quot;%s&quot;, markup[type, &quot;ENUM&quot;, &quot;END&quot;] enumlvl-- } while (enumlvl &lt; lvl) { printf &quot;%s&quot;, markup[type, &quot;ENUM&quot;, &quot;BEG&quot;] enumlvl++ } if (match(tok, /^\([^\)]+\)/)) { label = substr(tok, RSTART + 1, RLENGTH - 2) tok = substr(tok, RSTART + RLENGTH) sub(/^ +/, &quot;&quot;, tok) } if (match(tok, /^.+:/)) { colon = substr(tok, RSTART, RLENGTH) } if (troff) { if (label != &quot;&quot;) { label = label &quot;.&quot; printf markup[type, &quot;ITEM&quot;, &quot;BEG&quot;], label, 2 + int(length(label) / 2) } else { printf markup[type, &quot;ITEM&quot;, &quot;BEG&quot;], &quot;\\(bu&quot;, 2 } } else { printf &quot;%s&quot;, markup[type, &quot;ITEM&quot;, &quot;BEG&quot;] } if (colon != &quot;&quot;) { printf &quot;%s&quot;, markup[type, &quot;COLON&quot;, &quot;BEG&quot;] printnormal(colon) printf &quot;%s&quot;, markup[type, &quot;COLON&quot;, &quot;END&quot;] } } else { printmarkup(tok) } gettok() } ungettok() while (enumlvl &gt; 0) { printf &quot;%s&quot;, markup[type, &quot;ITEM&quot;, &quot;END&quot;] printf &quot;%s&quot;, markup[type, &quot;ENUM&quot;, &quot;END&quot;] enumlvl-- } } # parse section function section( lvl) { lvl = (type == &quot;html&quot;) ? 1 : 0 while (tok ~ /^(§)/) { lvl++ sub(/^(§)/, &quot;&quot;, tok) } if (gettok() &lt; 0) return printf markup[type, &quot;SECTION&quot;, &quot;BEG&quot;], lvl, genid(tok) printmarkup(tok) printf markup[type, &quot;SECTION&quot;, &quot;END&quot;], lvl } # parse the entire document function document() { printf &quot;%s&quot;, markup[type, &quot;HEADER&quot;] while (gettok() &gt; 0) { if (toktype == SECTIONMARK) { section() } else if (toktype == ENUMMARK) { enumeration() } else if (toktype == FIGUREMARK) { figure() } else if (toktype == NONE &amp;&amp; NR == 1) { docincipit() } else if (toktype == NONE) { paragraph() } } printf &quot;%s&quot;, markup[type, &quot;FOOTER&quot;] } # set constants and call the parser BEGIN { if (type == &quot;&quot;) type = &quot;ms&quot; troff = (type == &quot;ms&quot; || type == &quot;man&quot;) context = &quot;&quot; puncttype = &quot;&quot; tok = &quot;&quot; eof = 0 NONE = 0 # token type BLANK = 1 SECTIONMARK = 2 ENUMMARK = 3 FIGUREMARK = 4 # figure types CODE = 1 IMAGE = 2 VIDEO = 3 # ms markup markup[&quot;ms&quot;, &quot;HEADER&quot;] = &quot;.de VS\n.DS\n.nf\n.ft CW\n..\n.de VE\n.ft P\n.fi\n.DE\n..\n&quot; markup[&quot;ms&quot;, &quot;FOOTER&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;TITLE&quot;, &quot;BEG&quot;] = &quot;.TL\n&quot; markup[&quot;ms&quot;, &quot;TITLE&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;SUBTITLE&quot;, &quot;BEG&quot;] = &quot;.br\n&quot; markup[&quot;ms&quot;, &quot;SUBTITLE&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;HEADING&quot;, &quot;BEG&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;HEADING1&quot;, &quot;BEG&quot;] = &quot;.AU\n&quot; markup[&quot;ms&quot;, &quot;HEADING1&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;HEADING2&quot;, &quot;BEG&quot;] = &quot;.AI\n&quot; markup[&quot;ms&quot;, &quot;HEADING2&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;HEADING&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;ABSTRACT&quot;, &quot;BEG&quot;] = &quot;.AB no\n&quot; markup[&quot;ms&quot;, &quot;ABSTRACT&quot;, &quot;END&quot;] = &quot;.AE\n&quot; markup[&quot;ms&quot;, &quot;PARAGRAPH&quot;, &quot;BEG&quot;] = &quot;.PP\n&quot; markup[&quot;ms&quot;, &quot;PARAGRAPH&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;PARATITLE&quot;, &quot;BEG&quot;] = &quot;.B\n&quot; markup[&quot;ms&quot;, &quot;PARATITLE&quot;, &quot;END&quot;] = &quot;.R\n&quot; markup[&quot;ms&quot;, &quot;SECTION&quot;, &quot;BEG&quot;] = &quot;.NH %d\n&quot; markup[&quot;ms&quot;, &quot;SECTION&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;ms&quot;, &quot;CODE&quot;, &quot;BEG&quot;] = &quot;.VS\n&quot; markup[&quot;ms&quot;, &quot;CODE&quot;, &quot;END&quot;] = &quot;.VE\n&quot; markup[&quot;ms&quot;, &quot;EMPHASIS&quot;, &quot;BEG&quot;] = &quot;\\fI&quot; markup[&quot;ms&quot;, &quot;EMPHASIS&quot;, &quot;END&quot;] = &quot;\\fP&quot; markup[&quot;ms&quot;, &quot;TOPIC&quot;, &quot;BEG&quot;] = &quot;\\(lq\\fI&quot; markup[&quot;ms&quot;, &quot;TOPIC&quot;, &quot;END&quot;] = &quot;\\fP\\(rq&quot; markup[&quot;ms&quot;, &quot;PRE&quot;, &quot;BEG&quot;] = &quot;\\f(CW&quot; markup[&quot;ms&quot;, &quot;PRE&quot;, &quot;END&quot;] = &quot;\\fP&quot; markup[&quot;ms&quot;, &quot;META&quot;, &quot;BEG&quot;] = &quot;\\f(CW\\[la]&quot; markup[&quot;ms&quot;, &quot;META&quot;, &quot;END&quot;] = &quot;\\[ra]\\fP&quot; markup[&quot;ms&quot;, &quot;COLON&quot;, &quot;BEG&quot;] = &quot;.B\n&quot; markup[&quot;ms&quot;, &quot;COLON&quot;, &quot;END&quot;] = &quot;.R\n&quot; markup[&quot;ms&quot;, &quot;ENUM&quot;, &quot;BEG&quot;] = &quot;.RS\n&quot; markup[&quot;ms&quot;, &quot;ENUM&quot;, &quot;END&quot;] = &quot;.RE\n&quot; markup[&quot;ms&quot;, &quot;ITEM&quot;, &quot;BEG&quot;] = &quot;.IP \\fB%s\\fP %d\n&quot; markup[&quot;ms&quot;, &quot;ITEM&quot;, &quot;END&quot;] = &quot;&quot; # html markup markup[&quot;html&quot;, &quot;HEADER&quot;] = &quot;&quot; markup[&quot;html&quot;, &quot;FOOTER&quot;] = &quot;\n&quot; markup[&quot;html&quot;, &quot;TITLE&quot;, &quot;BEG&quot;] = &quot;&lt;h1 id=\&quot;%s\&quot;&gt;&quot; markup[&quot;html&quot;, &quot;TITLE&quot;, &quot;END&quot;] = &quot;&lt;/h1&gt;&quot; markup[&quot;html&quot;, &quot;SUBTITLE&quot;, &quot;BEG&quot;] = &quot;&lt;br/&gt;&quot; markup[&quot;html&quot;, &quot;SUBTITLE&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;html&quot;, &quot;HEADING&quot;, &quot;BEG&quot;] = &quot;&lt;p&gt;&quot; markup[&quot;html&quot;, &quot;HEADING1&quot;, &quot;BEG&quot;] = &quot;&lt;br/&gt;&quot; markup[&quot;html&quot;, &quot;HEADING1&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;html&quot;, &quot;HEADING2&quot;, &quot;BEG&quot;] = &quot;&lt;br/&gt;&quot; markup[&quot;html&quot;, &quot;HEADING2&quot;, &quot;END&quot;] = &quot;&quot; markup[&quot;html&quot;, &quot;HEADING&quot;, &quot;END&quot;] = &quot;&lt;/p&gt;&quot; markup[&quot;html&quot;, &quot;ABSTRACT&quot;, &quot;BEG&quot;] = &quot;&lt;p&gt;&quot; markup[&quot;html&quot;, &quot;ABSTRACT&quot;, &quot;END&quot;] = &quot;&lt;/p&gt;&quot; markup[&quot;html&quot;, &quot;PARAGRAPH&quot;, &quot;BEG&quot;] = &quot;&lt;p&gt;&quot; markup[&quot;html&quot;, &quot;PARAGRAPH&quot;, &quot;END&quot;] = &quot;&lt;/p&gt;&quot; markup[&quot;html&quot;, &quot;PARATITLE&quot;, &quot;BEG&quot;] = &quot;&lt;strong&gt;&quot; markup[&quot;html&quot;, &quot;PARATITLE&quot;, &quot;END&quot;] = &quot;&lt;/strong&gt;&quot; markup[&quot;html&quot;, &quot;SECTION&quot;, &quot;BEG&quot;] = &quot;&lt;h%d id=\&quot;%s\&quot;&gt;&quot; markup[&quot;html&quot;, &quot;SECTION&quot;, &quot;END&quot;] = &quot;&lt;/h%d&gt;&quot; markup[&quot;html&quot;, &quot;CODE&quot;, &quot;BEG&quot;] = &quot;&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&quot; markup[&quot;html&quot;, &quot;CODE&quot;, &quot;END&quot;] = &quot;&lt;/figure&gt;&lt;/pre&gt;&lt;/code&gt;&quot; markup[&quot;html&quot;, &quot;EMPHASIS&quot;, &quot;BEG&quot;] = &quot;&lt;em&gt;&quot; markup[&quot;html&quot;, &quot;EMPHASIS&quot;, &quot;END&quot;] = &quot;&lt;/em&gt;&quot; markup[&quot;html&quot;, &quot;TOPIC&quot;, &quot;BEG&quot;] = &quot;“&lt;em&gt;&quot; markup[&quot;html&quot;, &quot;TOPIC&quot;, &quot;END&quot;] = &quot;&lt;/em&gt;”&quot; markup[&quot;html&quot;, &quot;PRE&quot;, &quot;BEG&quot;] = &quot;&lt;code&gt;&quot; markup[&quot;html&quot;, &quot;PRE&quot;, &quot;END&quot;] = &quot;&lt;/code&gt;&quot; markup[&quot;html&quot;, &quot;META&quot;, &quot;BEG&quot;] = &quot;&lt;code&gt;⟨&quot; markup[&quot;html&quot;, &quot;META&quot;, &quot;END&quot;] = &quot;⟩&lt;/code&gt;&quot; markup[&quot;html&quot;, &quot;COLON&quot;, &quot;BEG&quot;] = &quot;&lt;strong&gt;&quot; markup[&quot;html&quot;, &quot;COLON&quot;, &quot;END&quot;] = &quot;&lt;/strong&gt;&quot; markup[&quot;html&quot;, &quot;ENUM&quot;, &quot;BEG&quot;] = &quot;&lt;ul&gt;&quot; markup[&quot;html&quot;, &quot;ENUM&quot;, &quot;END&quot;] = &quot;&lt;/ul&gt;&quot; markup[&quot;html&quot;, &quot;ITEM&quot;, &quot;BEG&quot;] = &quot;&lt;li&gt;&quot; markup[&quot;html&quot;, &quot;ITEM&quot;, &quot;END&quot;] = &quot;&lt;/li&gt;&quot; document() } ' &quot;$@&quot; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T04:30:58.650", "Id": "525723", "Score": "0", "body": "Also on [github](https://raw.githubusercontent.com/phillbush/incipit/master/README.pdf)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T04:29:14.620", "Id": "266151", "Score": "0", "Tags": [ "awk" ], "Title": "awk script to convert simple markup language to troff or html" }
266151
<p>I have this doubly-linked list data structure that runs all the single-element operations in <span class="math-container">\$\Theta(\sqrt{n})\$</span> time (refer to <a href="http://coderodde.github.io/weblog/#eill" rel="nofollow noreferrer">this post</a> and <a href="https://github.com/coderodde/LinkedList" rel="nofollow noreferrer">this repository</a>).</p> <p>(See <a href="https://codereview.stackexchange.com/questions/266154/indexed-heuristic-doubly-linked-list-data-in-java-benchmark">this</a> for benchmarks.)</p> <p>(See <a href="https://codereview.stackexchange.com/questions/266155/indexed-heuristic-doubly-linked-list-data-structure-in-java-unit-tests">this</a> for unit testing.)</p> <p>I have plans to submit it to the one of the two projects:</p> <ul> <li>OpenJDK; to substitute <code>java.util.LinkedList</code> with my implementations of the same interface(s),</li> <li>Apache Commons Collections4; to complement the lists.</li> </ul> <h1>Critique request</h1> <p>Before I submit it to the two projects, I need to make sure that I am doing mature OpenJDK/Apache Commons code. Tell me about anything that comes to mind: DRY, SOLID, etc.</p> <h1>Code</h1> <p>Here it goes:</p> <pre><code>package com.github.coderodde.util; import java.util.AbstractSequentialList; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Spliterator; import java.util.function.Consumer; /** * * @author Rodion Efremov * @see List * @see ArrayList * @see java.util.LinkedList * @since 17 * @param &lt;E&gt; the type of elements held in this collection */ public class LinkedList&lt;E&gt; extends AbstractSequentialList&lt;E&gt; implements List&lt;E&gt;, Deque&lt;E&gt;, Cloneable, java.io.Serializable { /** * Number of elements in the list. */ private int size = 0; /** * Pointer to first node. */ private transient Node&lt;E&gt; first; /** * Pointer to last node. */ private transient Node&lt;E&gt; last; /** * Stack of fingers. */ private transient FingerStack&lt;E&gt; fingerStack = new FingerStack&lt;&gt;(); /** * Constructs an empty list. */ public LinkedList() { } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public LinkedList(Collection&lt;? extends E&gt; c) { this(); addAll(c); } /** * Appends the specified element to the end of this list. * * &lt;p&gt;This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ public boolean add(E e) { linkLast(e); return true; } /** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index), index); } /** * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the specified * collection's iterator. The behavior of this operation is undefined if * the specified collection is modified while the operation is in * progress. (Note that this will occur if the specified collection is * this list, and it's nonempty.) * * @param c collection containing elements to be added to this list * @return {@code true} if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean addAll(Collection&lt;? extends E&gt; c) { return addAll(size, c); } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element * from the specified collection * @param c collection containing elements to be added to this list * @return {@code true} if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, Collection&lt;? extends E&gt; c) { checkPositionIndex(index); if (c.isEmpty()) return false; if (size == 0) setAll(c); else if (index == 0) prependAll(c); else if (index == size) appendAll(c); else insertAll(c, node(index), index); return true; } /** * Inserts the specified element at the beginning of this list. * * @param e the element to add */ public void addFirst(E e) { linkFirst(e); } /** * Appends the specified element to the end of this list. * * &lt;p&gt;This method is equivalent to {@link #add}. * * @param e the element to add */ public void addLast(E e) { linkLast(e); } /** * Removes all of the elements from this list. * The list will be empty after this call returns. */ public void clear() { fingerStack.clear(); size = 0; // Clearing all of the links between nodes is &quot;unnecessary&quot;, but: // - helps a generational GC if the discarded nodes inhabit // more than one generation // - is sure to free memory even if there is a reachable Iterator for (Node&lt;E&gt; node = first; node != null;) { node.prev = null; node.item = null; Node&lt;E&gt; next = node.next; node.next = null; node = next; } first = last = null; modCount++; } /** * Returns {@code true} if this list contains the specified element. * More formally, returns {@code true} if and only if this list contains * at least one element {@code e} such that * {@code Objects.equals(o, e)}. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) &gt;= 0; } /** * @since 1.6 */ @Override public Iterator&lt;E&gt; descendingIterator() { return new DescendingIterator(); } /** * Retrieves, but does not remove, the head (first element) of this list. * * @return the head of this list * @throws NoSuchElementException if this list is empty * @since 1.5 */ @Override public E element() { return getFirst(); } /** * Returns {@code true} only if the input object is a {@link List}, has the * same size, and whose iterator returns the elements in the same order as * this list. * * @param o the query object. * @return {@code true} only if this list and the input list represent the * same element sequence. */ @Override public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (!o.getClass().equals(o.getClass())) return false; List&lt;?&gt; otherList = (List&lt;?&gt;) o; if (size != otherList.size()) return false; Iterator&lt;?&gt; iterator1 = iterator(); Iterator&lt;?&gt; iterator2 = otherList.iterator(); while (iterator1.hasNext() &amp;&amp; iterator2.hasNext()) { Object object1 = iterator1.next(); Object object2 = iterator2.next(); if (!java.util.Objects.equals(object1, object2)) return false; } boolean iterator1HasMore = iterator1.hasNext(); boolean iterator2HasMore = iterator2.hasNext(); if (iterator1HasMore || iterator2HasMore) throw new IllegalStateException( iterator1HasMore ? &quot;This list has more elements to offer&quot; : &quot;Argument list has more elements to offer&quot;); return true; } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { checkElementIndex(index); return node(index).item; } /** * Returns the first element in this list. * * @return the first element in this list * @throws NoSuchElementException if this list is empty */ public E getFirst() { final Node&lt;E&gt; f = first; if (f == null) throw new NoSuchElementException(); return f.item; } /** * Returns the last element in this list. * * @return the last element in this list * @throws NoSuchElementException if this list is empty */ public E getLast() { final Node&lt;E&gt; l = last; if (l == null) throw new NoSuchElementException(); return l.item; } /** * Returns the smallest index of the input object, or -1, if the object does * not appear in this list. * * @param o the object whose index to return. * @return the index of {@code o}, or -1, if none is present. */ public int indexOf(Object o) { int index = 0; if (o == null) { for (Node&lt;E&gt; x = first; x != null; x = x.next, index++) { if (x.item == null) return index; } } else { for (Node&lt;E&gt; x = first; x != null; x = x.next, index++) { if (o.equals(x.item)) return index; } } return -1; } /** * Returns the basic iterator over this list supporting only traversal and * removal. * * @return the basic iterator. */ @Override public Iterator&lt;E&gt; iterator() { return new BasicIterator(); } /** * Returns the index of the last appearance of the input object {@code o}. * * @param o the object to search for. * @return the largest index of {@code o}, or -1 if none is present. */ public int lastIndexOf(Object o) { int index = size; if (o == null) { for (Node&lt;E&gt; x = last; x != null; x = x.prev) { index--; if (x.item == null) return index; } } else { for (Node&lt;E&gt; x = last; x != null; x = x.prev) { index--; if (o.equals(x.item)) return index; } } return -1; } /** * Returns a list-iterator of the elements in this list (in proper * sequence), starting at the specified position in the list. * Obeys the general contract of {@code List.listIterator(int)}.&lt;p&gt; * * The list-iterator is &lt;i&gt;fail-fast&lt;/i&gt;: if the list is structurally * modified at any time after the Iterator is created, in any way except * through the list-iterator's own {@code remove} or {@code add} * methods, the list-iterator will throw a * {@code ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * * @param index index of the first element to be returned from the * list-iterator (by a call to {@code next}) * @return a ListIterator of the elements in this list (in proper * sequence), starting at the specified position in the list * @throws IndexOutOfBoundsException {@inheritDoc} * @see List#listIterator(int) */ @Override public ListIterator&lt;E&gt; listIterator(int index) { return new EnhancedIterator(index); } /** * Adds the specified element as the tail (last element) of this list. * * @param e the element to add * @return {@code true} (as specified by {@link Queue#offer}) * @since 1.5 */ @Override public boolean offer(E e) { return add(e); } /** * Inserts the specified element at the front of this list. * * @param e the element to insert * @return {@code true} (as specified by {@link Deque#offerFirst}) * @since 1.6 */ @Override public boolean offerFirst(E e) { addFirst(e); return true; } /** * Inserts the specified element at the end of this list. * * @param e the element to insert * @return {@code true} (as specified by {@link Deque#offerLast}) * @since 1.6 */ @Override public boolean offerLast(E e) { addLast(e); return true; } /** * Retrieves, but does not remove, the head (first element) of this list. * * @return the head of this list, or {@code null} if this list is empty * @since 1.5 */ @Override public E peek() { final Node&lt;E&gt; f = first; return (f == null) ? null : f.item; } /** * Retrieves, but does not remove, the first element of this list, * or returns {@code null} if this list is empty. * * @return the first element of this list, or {@code null} * if this list is empty * @since 1.6 */ @Override public E peekFirst() { final Node&lt;E&gt; f = first; return (f == null) ? null : f.item; } /** * Retrieves, but does not remove, the last element of this list, * or returns {@code null} if this list is empty. * * @return the last element of this list, or {@code null} * if this list is empty * @since 1.6 */ @Override public E peekLast() { final Node&lt;E&gt; l = last; return (l == null) ? null : l.item; } /** * Retrieves and removes the head (first element) of this list. * * @return the head of this list, or {@code null} if this list is empty * @since 1.5 */ @Override public E poll() { final Node&lt;E&gt; f = first; return (f == null) ? null : unlinkFirst(); } /** * Retrieves and removes the first element of this list, * or returns {@code null} if this list is empty. * * @return the first element of this list, or {@code null} if * this list is empty * @since 1.6 */ @Override public E pollFirst() { final Node&lt;E&gt; f = first; return (f == null) ? null : unlinkFirst(); } /** * Retrieves and removes the last element of this list, * or returns {@code null} if this list is empty. * * @return the last element of this list, or {@code null} if * this list is empty * @since 1.6 */ @Override public E pollLast() { final Node&lt;E&gt; l = last; return (l == null) ? null : unlinkLast(); } /** * Pops an element from the stack represented by this list. In other * words, removes and returns the first element of this list. * * &lt;p&gt;This method is equivalent to {@link #removeFirst()}. * * @return the element at the front of this list (which is the top * of the stack represented by this list) * @throws NoSuchElementException if this list is empty * @since 1.6 */ @Override public E pop() { return removeFirst(); } /** * Pushes an element onto the stack represented by this list. In other * words, inserts the element at the front of this list. * * &lt;p&gt;This method is equivalent to {@link #addFirst}. * * @param e the element to push * @since 1.6 */ @Override public void push(E e) { addFirst(e); } /** * Retrieves and removes the head (first element) of this list. * * @return the head of this list * @throws NoSuchElementException if this list is empty * @since 1.5 */ @Override public E remove() { return removeFirst(); } /** * Removes the first occurrence of the specified element from this list, * if it is present. If this list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * {@code i} such that * {@code Objects.equals(o, get(i))} * (if such an element exists). Returns {@code true} if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return {@code true} if this list contained the specified element */ public boolean remove(Object o) { int index = 0; if (o == null) { for (Node&lt;E&gt; x = first; x != null; x = x.next, index++) { if (x.item == null) { removeNodeFromList(x, index); return true; } } } else { for (Node&lt;E&gt; x = first; x != null; x = x.next, index++) { if (o.equals(x.item)) { removeNodeFromList(x, index); return true; } } } return false; } /** * Removes the element residing at the given index. * The procedure: * 1. Find the node N to remove * 2. If N is fingered by F, move F left/right * 3. unlink(N) */ public E remove(int index) { checkElementIndex(index); // Loads the removeData! loadRemoveData(index); // Make sure that no finger is on our way pointing to the node to remove if (removedDataFinger.index == index) moveFingerOutOfRemovalLocation(removedDataFinger); // Once here, the list is not empty and has at least one finger! return unlink(removedDataNode, index); } /** * Removes and returns the first element from this list. * * @return the first element from this list * @throws NoSuchElementException if this list is empty */ public E removeFirst() { final Node&lt;E&gt; f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(); } /** * Removes the first occurrence of the specified element in this * list (when traversing the list from head to tail). If the list * does not contain the element, it is unchanged. * * @param o element to be removed from this list, if present * @return {@code true} if the list contained the specified element * @since 1.6 */ @Override public boolean removeFirstOccurrence(Object o) { return remove(o); } /** * Removes and returns the last element from this list. * * @return the last element from this list * @throws NoSuchElementException if this list is empty */ public E removeLast() { final Node&lt;E&gt; l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(); } /** * Removes the last occurrence of the specified element in this * list (when traversing the list from head to tail). If the list * does not contain the element, it is unchanged. * * @param o element to be removed from this list, if present * @return {@code true} if the list contained the specified element * @since 1.6 */ @Override public boolean removeLastOccurrence(Object o) { int index = size - 1; if (o == null) { for (Node&lt;E&gt; x = last; x != null; x = x.prev, index--) { if (x.item == null) { unlink(x, index); if (mustRemoveFinger()) removeFinger(); shiftIndicesToLeftOnce(index + 1); return true; } } } else { for (Node&lt;E&gt; x = last; x != null; x = x.prev, index--) { if (o.equals(x.item)) { unlink(x, index); if (mustRemoveFinger()) removeFinger(); shiftIndicesToLeftOnce(index + 1); return true; } } } return false; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ public int size() { return size; } /** * Creates a &lt;em&gt;&lt;a href=&quot;Spliterator.html#binding&quot;&gt;late-binding&lt;/a&gt;&lt;/em&gt; * and &lt;em&gt;fail-fast&lt;/em&gt; {@link Spliterator} over the elements in this * list. * * &lt;p&gt;The {@code Spliterator} reports {@link Spliterator#SIZED} and * {@link Spliterator#ORDERED}. Overriding implementations should document * the reporting of additional characteristic values. * * @implNote * The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED} * and implements {@code trySplit} to permit limited parallelism.. * * @return a {@code Spliterator} over the elements in this list * @since 1.8 */ @Override public Spliterator&lt;E&gt; spliterator() { return new LinkedListSpliterator&lt;E&gt;(this, first, size, 0, modCount); } @java.io.Serial private static final long serialVersionUID = -8812077630522402934L; // Internal implementation methods begin: private void addFinger(Node&lt;E&gt; node, int index) { final Finger&lt;E&gt; finger = new Finger&lt;&gt;(node, index); fingerStack.push(finger); } private void addFingersAfterAppendAll( Node&lt;E&gt; first, int firstIndex, int collectionSize) { final int numberOfNewFingers = getRecommendedNumberOfFingers() - fingerStack.size(); if (numberOfNewFingers == 0) return; final int distanceBetweenFingers = collectionSize / numberOfNewFingers; final int nodesToSkip = distanceBetweenFingers / 2; int index = firstIndex + nodesToSkip; Node&lt;E&gt; node = first; for (int i = 0; i &lt; nodesToSkip; i++) node = node.next; addFinger(node, index); for (int i = 1; i &lt; numberOfNewFingers; i++) { index += distanceBetweenFingers; for (int j = 0; j &lt; distanceBetweenFingers; j++) { node = node.next; } addFinger(node, index); } } private void addFingersAfterInsertAll(Node&lt;E&gt; headNodeOfInsertedRange, int indexOfInsertedRangeHead, int collectionSize) { final int numberOfNewFingers = getRecommendedNumberOfFingers() - fingerStack.size(); if (numberOfNewFingers == 0) return; final int distanceBetweenFingers = collectionSize / numberOfNewFingers; final int startOffset = distanceBetweenFingers / 2; int index = indexOfInsertedRangeHead + startOffset; Node&lt;E&gt; node = headNodeOfInsertedRange; for (int i = 0; i &lt; startOffset; i++) node = node.next; addFinger(node, index); for (int i = 1; i &lt; numberOfNewFingers; i++) { index += distanceBetweenFingers; for (int j = 0; j &lt; distanceBetweenFingers; j++) node = node.next; addFinger(node, index); } } private void addFingersAfterPrependAll(Node&lt;E&gt; first, int collectionSize) { final int numberOfNewFingers = getRecommendedNumberOfFingers() - fingerStack.size(); if (numberOfNewFingers == 0) return; final int distance = collectionSize / numberOfNewFingers; final int startIndex = distance / 2; int index = startIndex; Node&lt;E&gt; node = first; for (int i = 0; i &lt; startIndex; i++) node = node.next; addFinger(node, index); for (int i = 1; i &lt; numberOfNewFingers; i++) { index += distance; for (int j = 0; j &lt; distance; j++) node = node.next; addFinger(node, index); } } private void addFingersAfterSetAll() { final int numberOfNewFingers = getRecommendedNumberOfFingers(); if (numberOfNewFingers == 0) return; final int distance = size / numberOfNewFingers; final int startIndex = distance / 2; int index = startIndex; Node&lt;E&gt; node = first; for (int i = 0; i &lt; startIndex; i++) node = node.next; addFinger(node, startIndex); for (int i = 1; i &lt; numberOfNewFingers; i++) { index += distance; for (int j = 0; j &lt; distance; j++) node = node.next; addFinger(node, index); } } private void appendAll(Collection&lt;? extends E&gt; c) { Node&lt;E&gt; prev = last; final Node&lt;E&gt; oldLast = last; for (E item : c) { Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = item; newNode.prev = prev; prev.next = newNode; prev = newNode; } last = prev; int sz = c.size(); size += sz; modCount++; addFingersAfterAppendAll(oldLast.next, size - sz, sz); } private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(getOutOfBoundsMessage(index)); } public void checkInvariant() { for (int i = 0, sz = fingerStack.size(); i &lt; sz; i++) { Finger&lt;E&gt; finger = fingerStack.get(i); Node&lt;E&gt; node = getNodeRaw(finger.index); if (finger.node != node) throw new AssertionError( &quot;checkInvariant() failed at finger index (&quot; + finger.index + &quot;), expected node = &quot; + finger.node + &quot;, actual node = &quot; + node); } } private void checkPositionIndex(int index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(getOutOfBoundsMessage(index)); } private Finger&lt;E&gt; getClosestFinger(int index) { int bestDistance = Integer.MAX_VALUE; Finger&lt;E&gt; bestFinger = null; for (int sz = fingerStack.size(), i = 0; i &lt; sz; i++) { Finger&lt;E&gt; finger = fingerStack.get(i); int distance = Math.abs(finger.index - index); if (distance == 0) return finger; if (bestDistance &gt; distance) { bestDistance = distance; bestFinger = finger; } } return bestFinger; } private Node&lt;E&gt; getNodeRaw(int index) { Node&lt;E&gt; node = first; for (int i = 0; i &lt; index; i++) node = node.next; return node; } private String getOutOfBoundsMessage(int index) { return &quot;Index: &quot; + index + &quot;, Size: &quot; + size; } private int getRecommendedNumberOfFingers() { return (int) Math.ceil(Math.sqrt(size / 2.0)); } /*************************************************************************** Computes the recommended number of fingers for {@code size} elements. ***************************************************************************/ private static int getRecommendedNumberOfFingers(int size) { return (int) Math.ceil(Math.sqrt(size / 2.0)); } /*************************************************************************** Inserts the input collection right before the node 'succ'. ***************************************************************************/ private void insertAll( Collection&lt;? extends E&gt; c, Node&lt;E&gt; succ, int succIndex) { final Node&lt;E&gt; pred = succ.prev; Node&lt;E&gt; prev = pred; for (E item : c) { final Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = item; newNode.prev = prev; prev.next = newNode; prev = newNode; } prev.next = succ; succ.prev = prev; int sz = c.size(); modCount++; size += sz; // Shift all the fingers positions past the 'succ' on the right 'sz' // positions to the right: shiftIndicesToRight(succIndex, sz); // 0 1 |10 11 12| 3 4 5 6 7 8 9 // Add fingers: addFingersAfterInsertAll(pred.next, succIndex, sz); } /*************************************************************************** Tells if the argument is the index of an existing element. ***************************************************************************/ private boolean isElementIndex(int index) { return index &gt;= 0 &amp;&amp; index &lt; size; } /*************************************************************************** Tells if the argument is the index of a valid position for an iterator or an add operation. ***************************************************************************/ private boolean isPositionIndex(int index) { return index &gt;= 0 &amp;&amp; index &lt;= size; } /*************************************************************************** Links the input element right before the node 'succ'. ***************************************************************************/ private void linkBefore(E e, Node&lt;E&gt; succ, int index) { shiftIndicesToRightOnce(index); final Node&lt;E&gt; pred = succ.prev; final Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = e; newNode.next = succ; succ.prev = newNode; if (pred == null) { first = newNode; } else { pred.next = newNode; newNode.prev = pred; } size++; modCount++; if (mustAddFinger()) addFinger(newNode, index); } /*************************************************************************** Prepends the input element to the head of this list. ***************************************************************************/ private void linkFirst(E e) { shiftIndicesToRightOnce(0); final Node&lt;E&gt; f = first; final Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = e; newNode.next = f; first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; if (mustAddFinger()) addFinger(newNode, 0); } /*************************************************************************** Appends the input element to the tail of this list. ***************************************************************************/ private void linkLast(E e) { final Node&lt;E&gt; l = last; final Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = e; newNode.prev = l; last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; if (mustAddFinger()) addFinger(newNode, size - 1); } /*************************************************************************** Loads the removal operation related data. ***************************************************************************/ private void loadRemoveData(int index) { Finger&lt;E&gt; finger = getClosestFinger(index); Node&lt;E&gt; node = finger.node; if (index &lt; finger.index) { final int distance = finger.index - index; for (int i = 0; i &lt; distance; i++) node = node.prev; } else { final int distance = index - finger.index; for (int i = 0; i &lt; distance; i++) node = node.next; } removedDataFinger = finger; removedDataNode = node; } /*************************************************************************** Returns a finger that does not point to the element to remove. We need this in order to make sure that after removal, all the fingers point to valid nodes. ***************************************************************************/ private void moveFingerOutOfRemovalLocation(Finger&lt;E&gt; finger) { if (size == 1) { fingerStack.pop(); return; } if (finger.node.prev != null) { // Move the finger one position to the left: finger.node = finger.node.prev; finger.index--; return; } if (finger.node.next != null) { // Move the finger one position to the right: finger.node = finger.node.next; finger.index++; return; } throw new IllegalStateException(&quot;Removing from an empty list.&quot;); } /*************************************************************************** Returns true only if this list requires more fingers. ***************************************************************************/ private boolean mustAddFinger() { // Here, fingerStack.size() == getRecommendedFingerCount(), or, // fingerStack.size() == getRecommendedFingerCount() - 1 return fingerStack.size() != getRecommendedNumberOfFingers(); } /*************************************************************************** Returns true only if this list requires less fingers. /*************************************************************************** ***************************************************************************/ private boolean mustRemoveFinger() { // Here, fingerStack.size() == getRecommendedFingerCount(), or, // fingerStack.size() == getRecommendedFingerCount() + 1 return fingerStack.size() != getRecommendedNumberOfFingers(); } /*************************************************************************** Returns the node at index 'index'. Moves the closest finger to the node. ***************************************************************************/ private Node&lt;E&gt; node(int index) { Finger&lt;E&gt; finger = getClosestFinger(index); int distance = finger.index - index; if (distance &gt; 0) finger.rewindLeft(distance); else finger.rewindRight(-distance); return finger.node; } /*************************************************************************** Prepends the input collection to the head of this list. ***************************************************************************/ private void prependAll(Collection&lt;? extends E&gt; c) { Iterator&lt;? extends E&gt; iterator = c.iterator(); final Node&lt;E&gt; oldFirst = first; first = new Node&lt;&gt;(); first.item = iterator.next(); Node&lt;E&gt; prevNode = first; for (int i = 1, sz = c.size(); i &lt; sz; i++) { Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = iterator.next(); newNode.prev = prevNode; prevNode.next = newNode; prevNode = newNode; } prevNode.next = oldFirst; oldFirst.prev = prevNode; int sz = c.size(); modCount++; size += sz; // Prior to adding new (possible) fingers, we need to shift all the // current fingers 'c.size()' nodes to the larger index values: shiftIndicesToRight(0, sz); // Now, add the missing fingers: addFingersAfterPrependAll(first, sz); } private void removeFinger() { fingerStack.pop(); } private E removeNodeFromList(Node&lt;E&gt; node, int index) { loadRemoveData(index); if (removedDataFinger.index == index) moveFingerOutOfRemovalLocation(removedDataFinger); return unlink(node, index); } /*************************************************************************** Sets the input collection as a list. ***************************************************************************/ private void setAll(Collection&lt;? extends E&gt; c) { Iterator&lt;? extends E&gt; iterator = c.iterator(); first = new Node&lt;&gt;(); first.item = iterator.next(); Node&lt;E&gt; prevNode = first; for (int i = 1, sz = c.size(); i &lt; sz; i++) { Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = iterator.next(); prevNode.next = newNode; newNode.prev = prevNode; prevNode = newNode; } last = prevNode; int sz = c.size(); modCount++; size += sz; addFingersAfterSetAll(); } /*************************************************************************** Subtracts 'steps' positions from each index at least 'startingIndex'. ***************************************************************************/ private void shiftIndicesToLeft(int startingIndex, int steps) { for (int i = 0, sz = fingerStack.size; i &lt; sz; i++) { Finger&lt;E&gt; finger = fingerStack.get(i); if (finger.index &gt;= startingIndex) finger.index -= steps; // substract from index } } /*************************************************************************** Shifts all the indices at least 'startingIndex' one position towards smaller index values. ***************************************************************************/ private void shiftIndicesToLeftOnce(int startingIndex) { shiftIndicesToLeft(startingIndex, 1); } /*************************************************************************** For each finger with the index at least 'startIndex', add 'steps' to the index. ***************************************************************************/ private void shiftIndicesToRight(int startIndex, int steps) { for (int sz = fingerStack.size(), i = 0; i &lt; sz; i++) { Finger&lt;E&gt; finger = fingerStack.get(i); if (finger.index &gt;= startIndex) finger.index += steps; } } /*************************************************************************** Shifts all the indices at least 'startingIndex' one position towards larger index values. ***************************************************************************/ private void shiftIndicesToRightOnce(int startingIndex) { shiftIndicesToRight(startingIndex, 1); } /*************************************************************************** Unlinks the input node and adjusts the fingers. ***************************************************************************/ private E unlink(Node&lt;E&gt; x, int index) { final E element = x.item; final Node&lt;E&gt; next = x.next; final Node&lt;E&gt; prev = x.prev; if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } if (next == null) { last = prev; } else { next.prev = prev; x.next = null; } x.item = null; size--; modCount++; if (mustRemoveFinger()) removeFinger(); shiftIndicesToLeftOnce(index + 1); return element; } /*************************************************************************** Unlinks the head node from this list. ***************************************************************************/ private E unlinkFirst() { shiftIndicesToLeftOnce(1); final E element = first.item; final Node&lt;E&gt; next = first.next; first.item = null; first.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; if (mustRemoveFinger()) fingerStack.pop(); return element; } /*************************************************************************** Unlinks the tail node from this list. ***************************************************************************/ private E unlinkLast() { final E element = last.item; final Node&lt;E&gt; prev = last.prev; last.item = null; last.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; if (mustRemoveFinger()) fingerStack.pop(); return element; } // Caches the removal data: private transient Node&lt;E&gt; removedDataNode; private transient Finger&lt;E&gt; removedDataFinger; /** * Reconstitutes this {@code LinkedList} instance from a stream * (that is, deserializes it). */ @java.io.Serial private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden serialization magic s.defaultReadObject(); int size = s.readInt(); this.size = size; this.fingerStack = new FingerStack&lt;&gt;(); switch (size) { case 0: return; case 1: Node&lt;E&gt; newNode = new Node&lt;&gt;(); newNode.item = (E) s.readObject(); first = last = newNode; addFinger(newNode, 0); return; } Node&lt;E&gt; rightmostNode = new Node&lt;&gt;(); rightmostNode.item = (E) s.readObject(); first = rightmostNode; int numberOfRequestedFingers = getRecommendedNumberOfFingers(size); final int distance = size / numberOfRequestedFingers; int startOffset = distance / 2; // Read in all elements in the proper order. for (int i = 1; i &lt; size; i++) { E item = (E) s.readObject(); Node&lt;E&gt; node = new Node&lt;&gt;(); node.item = item; if ((i - startOffset) % distance == 0) { addFinger(node, i); } rightmostNode.next = node; node.prev = rightmostNode; rightmostNode = node; } last = rightmostNode; } /** * Saves the state of this {@code LinkedList} instance to a stream * (that is, serializes it). * * @serialData The size of the list (the number of elements it * contains) is emitted (int), followed by all of its * elements (each an Object) in the proper order. */ @java.io.Serial private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden serialization magic s.defaultWriteObject(); // Write out size s.writeInt(size); // Write out all elements in the proper order. for (Node&lt;E&gt; x = first; x != null; x = x.next) s.writeObject(x.item); } /*************************************************************************** Implements the doubly-linked list node. ***************************************************************************/ private static class Node&lt;E&gt; { E item; Node&lt;E&gt; prev; Node&lt;E&gt; next; @Override public String toString() { return &quot;[Node; item = &quot; + item + &quot;]&quot;; } } /*************************************************************************** Implements the list node finger. ***************************************************************************/ private static final class Finger&lt;E&gt; { Node&lt;E&gt; node; int index; // Index at which 'node' is located. Finger(Node&lt;E&gt; node, int index) { this.node = node; this.index = index; } @Override public String toString() { return &quot;[Finger; index = &quot; + index + &quot;, item = &quot; + node.item + &quot;]&quot;; } // Moves this finger 'steps' position to the left void rewindLeft(int steps) { for (int i = 0; i &lt; steps; i++) { node = node.prev; } index -= steps; } // Moves this finger 'steps' position to the right void rewindRight(int steps) { for (int i = 0; i &lt; steps; i++) { node = node.next; } index += steps; } } /*************************************************************************** Implements a simple, array-based stack for storing the node fingers. @param &lt;E&gt; the list element type ***************************************************************************/ private static final class FingerStack&lt;E&gt; { private static final int INITIAL_CAPACITY = 8; private Finger&lt;E&gt;[] fingerArray; private int size = 0; FingerStack() { this.fingerArray = new Finger[INITIAL_CAPACITY]; } void push(Finger&lt;E&gt; finger) { enlargeFingerArrayIfNeeded(); fingerArray[size++] = finger; } void pop() { fingerArray[--size] = null; } int size() { return size; } Finger&lt;E&gt; get(int index) { return fingerArray[index]; } // Clears this finger stack: void clear() { for (int i = 0; i &lt; size; i++) { fingerArray[i].node = null; // help GC fingerArray[i] = null; } size = 0; } // Makes sure that the next finger fits in this finger stack: private void enlargeFingerArrayIfNeeded() { if (size == fingerArray.length) { final int nextCapacity = 3 * fingerArray.length / 2; fingerArray = Arrays.copyOf(fingerArray, nextCapacity); } } } /*************************************************************************** This class implements a basic iterator over this list. @param E the element type. ***************************************************************************/ private final class BasicIterator implements Iterator&lt;E&gt; { private Node&lt;E&gt; lastReturned; private Node&lt;E&gt; next = first; private int nextIndex; private int expectedModCount = modCount; @Override public boolean hasNext() { return nextIndex &lt; size; } @Override public E next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } @Override public void remove() { checkForComodification(); if (lastReturned == null) throw new IllegalStateException(); Node&lt;E&gt; lastNext = lastReturned.next; int removalIndex = nextIndex - 1; //checkInvariant(); loadRemoveData(removalIndex); if (removedDataFinger.index == removalIndex) moveFingerOutOfRemovalLocation(removedDataFinger); unlink(lastReturned, removalIndex); if (next == lastReturned) next = lastNext; else nextIndex--; lastReturned = null; expectedModCount++; } @Override public void forEachRemaining(Consumer&lt;? super E&gt; action) { Objects.requireNonNull(action); while (modCount == expectedModCount &amp;&amp; nextIndex &lt; size) { action.accept(next.item); lastReturned = next; next = next.next; nextIndex++; } checkForComodification(); } private final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /*************************************************************************** Implements the list iterator over this list. ***************************************************************************/ private final class EnhancedIterator implements ListIterator&lt;E&gt; { private Node&lt;E&gt; lastReturned; private Node&lt;E&gt; next; private int nextIndex; private int expectedModCount = modCount; EnhancedIterator(int index) { next = (index == size) ? null : node(index); nextIndex = index; } @Override public boolean hasNext() { return nextIndex &lt; size; } @Override public E next() { checkForComdification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } @Override public boolean hasPrevious() { return nextIndex &gt; 0; } @Override public E previous() { checkForComdification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void remove() { checkForComdification(); if (lastReturned == null) throw new IllegalStateException(); Node&lt;E&gt; lastNext = lastReturned.next; int removalIndex = nextIndex - 1; loadRemoveData(removalIndex); if (removedDataFinger.index == removalIndex) moveFingerOutOfRemovalLocation(removedDataFinger); unlink(lastReturned, removalIndex); if (next == lastReturned) next = lastNext; else nextIndex = removalIndex; lastReturned = null; expectedModCount++; } @Override public void set(E e) { if (lastReturned == null) throw new IllegalStateException(); checkForComdification(); lastReturned.item = e; } @Override public void add(E e) { checkForComdification(); lastReturned = null; if (next == null) linkLast(e); else linkBefore(e, next, nextIndex); nextIndex++; expectedModCount++; } @Override public void forEachRemaining(Consumer&lt;? super E&gt; action) { Objects.requireNonNull(action); while (modCount == expectedModCount &amp;&amp; nextIndex &lt; size) { action.accept(next.item); lastReturned = next; next = next.next; nextIndex++; } checkForComdification(); } private final void checkForComdification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } private final class DescendingIterator implements Iterator&lt;E&gt; { private final ListIterator&lt;E&gt; iterator = new EnhancedIterator(size()); @Override public boolean hasNext() { return iterator.hasPrevious(); } @Override public E next() { return iterator.previous(); } @Override public void remove() { iterator.remove(); } } private static final class LinkedListSpliterator&lt;E&gt; implements Spliterator&lt;E&gt; { private static final long MINIMUM_BATCH_SIZE = 1 &lt;&lt; 10; // 1024 items private final LinkedList&lt;E&gt; list; private LinkedList.Node&lt;E&gt; node; private long lengthOfSpliterator; private long numberOfProcessedElements; private long offsetOfSpliterator; private final int expectedModCount; private LinkedListSpliterator(LinkedList&lt;E&gt; list, Node&lt;E&gt; node, long lengthOfSpliterator, long offsetOfSpliterator, int expectedModCount) { this.list = list; this.node = node; this.lengthOfSpliterator = lengthOfSpliterator; this.offsetOfSpliterator = offsetOfSpliterator; this.expectedModCount = expectedModCount; } @Override public boolean tryAdvance(Consumer&lt;? super E&gt; action) { if (action == null) throw new NullPointerException(); if (numberOfProcessedElements == lengthOfSpliterator) return false; numberOfProcessedElements++; E item = node.item; action.accept(item); node = node.next; if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } @Override public void forEachRemaining(Consumer&lt;? super E&gt; action) { if (action == null) throw new NullPointerException(); for (long i = numberOfProcessedElements; i &lt; lengthOfSpliterator; i++) { E item = node.item; action.accept(item); node = node.next; } numberOfProcessedElements = lengthOfSpliterator; if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); } @Override public Spliterator&lt;E&gt; trySplit() { final long sizeLeft = estimateSize(); if (sizeLeft == 0) return null; final long thisSpliteratorNewLength = sizeLeft / 2L; if (thisSpliteratorNewLength &lt; MINIMUM_BATCH_SIZE) return null; final long newSpliteratorLength = sizeLeft - thisSpliteratorNewLength; final long newSpliteratorOffset = this.offsetOfSpliterator; this.offsetOfSpliterator += newSpliteratorLength; this.lengthOfSpliterator -= newSpliteratorLength; Node&lt;E&gt; newSpliteratorNode = this.node; this.node = list.node((int) this.offsetOfSpliterator); return new LinkedListSpliterator&lt;&gt;( list, newSpliteratorNode, newSpliteratorLength, // length newSpliteratorOffset, // offset expectedModCount); } @Override public long estimateSize() { return (long)(lengthOfSpliterator - numberOfProcessedElements); } @Override public long getExactSizeIfKnown() { return estimateSize(); } @Override public int characteristics() { return Spliterator.ORDERED | Spliterator.SUBSIZED | Spliterator.SIZED; } @Override public boolean hasCharacteristics(int characteristics) { switch (characteristics) { case Spliterator.ORDERED: case Spliterator.SIZED: case Spliterator.SUBSIZED: return true; default: return false; } } } } </code></pre>
[]
[ { "body": "<p>After 24 days being asked, just a tiny review, as I actually cannot spend time. It is sad noone found time to do a thorough review on something promising. Probably because of the effort.</p>\n<p>Use <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Objects.html#equals(java.lang.Object,java.lang.Object)\" rel=\"nofollow noreferrer\"><code>Objects.equals</code></a> to compare nullable objects. You do it incidentally and using a qualified <code>java.util.Objects.equals(...)</code> (generated code?) where you actually import it too.</p>\n<pre><code>public int indexOf(Object o) {\n for (Node&lt;E&gt; x = first, int index = 0; x != null; x = x.next, index++) {\n if (Objects.equals(o, x.item)) \n return index;\n }\n return -1;\n}\n</code></pre>\n<p>The list <code>equals</code> should instead of:</p>\n<pre><code> boolean iterator1HasMore = iterator1.hasNext();\n boolean iterator2HasMore = iterator2.hasNext();\n if (iterator1HasMore || iterator2HasMore)\n throw new IllegalStateException(\n iterator1HasMore ?\n &quot;This list has more elements to offer&quot; :\n &quot;Argument list has more elements to offer&quot;);\n\n return true;\n</code></pre>\n<p>do:</p>\n<pre><code> return !iterator1.hasNext() &amp;&amp; !iterator2.hasNext();\n</code></pre>\n<p>or better:</p>\n<pre><code> return true;\n</code></pre>\n<p>As sensibly you did before the loop:</p>\n<pre><code> if (size != otherList.size())\n return false;\n</code></pre>\n<p>There is no difference between lists having a different element at some index, or having different lengths.</p>\n<p>First one should guarantee the same results, before benchmarking. At least unit tests. Probably you did.</p>\n<p>There are microbenchmark libraries that are more reliable (&quot;statistics all lie&quot;). For instance now you are testing your class first. Warmup, garbage collection.</p>\n<p>The output could have been nicer.</p>\n<p>You inherited pre-generic code of java's beginning and use Object where E would be feasible:</p>\n<pre><code> Iterator&lt;?&gt; iterator1 = iterator();\n</code></pre>\n<p>That is understandable, even justifiable as internally one does not do E-ish things, but it <em>is</em> sad.</p>\n<p>To go at some <code>index</code> one could go forwards from <code>first</code> or backwards from <code>last</code>. The latter you do not seem to consider.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T21:26:39.390", "Id": "267901", "ParentId": "266152", "Score": "2" } } ]
{ "AcceptedAnswerId": "267901", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T06:12:05.377", "Id": "266152", "Score": "2", "Tags": [ "java", "performance", "linked-list", "heuristic" ], "Title": "Faster, indexed, heuristic doubly-linked list data structure in Java: implementation" }
266152
<p>I have this benchmark program for my <a href="https://codereview.stackexchange.com/questions/266152/indexed-heuristic-doubly-linked-list-data-in-java-implementation">indexed linked list</a>.</p> <p>It looks like this:</p> <p><code>com.github.coderodde.util.benchmark.LinkedListBenchmarkRunner</code></p> <pre><code>package com.github.coderodde.util.benchmark; public class LinkedListBenchmarkRunner { public static void main(String[] args) { long seed = System.currentTimeMillis(); System.out.println(&quot;&lt;&lt;&lt; LinkedList seed = &quot; + seed + &quot; &gt;&gt;&gt;&quot;); System.out.println(); LinkedListBenchmark benchmark = new LinkedListBenchmark(seed); benchmark.warmup(); System.out.println(); benchmark.benchmark(); } } </code></pre> <p><code>com.github.coderodde.util.benchmark.LinkedListBenchmark</code></p> <pre><code>package com.github.coderodde.util.benchmark; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Random; import java.util.stream.Collectors; import org.apache.commons.collections4.list.TreeList; final class LinkedListBenchmark { private static final int ADD_FIRST_OPERATIONS = 100_000; private static final int ADD_LAST_OPERATIONS = 100_000; private static final int ADD_AT_OPERATIONS = 10_000; private static final int ADD_COLLECTION_AT_OPERATIONS = 4_000; private static final int ADD_LAST_COLLECTION_OPERATIONS = 10_000; private static final int REMOVE_VIA_INDEX_OPERATIONS = 10_000; private static final int REMOVE_OBJECT_OPERATIONS = 1_000; private static final int MAXIMUM_COLLECTION_SIZE = 20; private static final int MAXIMUM_INTEGER = 1_000; private final long seed; private Random randomJavaUtilLinkedList; private Random randomJavaUtilArrayList; private Random randomRoddeList; private Random randomTreeList; private com.github.coderodde.util.LinkedList&lt;Integer&gt; roddeList = new com.github.coderodde.util.LinkedList&lt;&gt;(); private LinkedList&lt;Integer&gt; linkedList = new LinkedList&lt;&gt;(); private ArrayList&lt;Integer&gt; arrayList = new ArrayList&lt;&gt;(); private TreeList&lt;Integer&gt; treeList = new TreeList&lt;&gt;(); private long totalMillisRoddeList = 0L; private long totalMillisLinkedList = 0L; private long totalMillisArrayList = 0L; private long totalMillisTreeList = 0L; LinkedListBenchmark(long seed) { this.seed = seed; } void warmup() { profile(BenchmarkChoice.WARMUP); } void benchmark() { profile(BenchmarkChoice.BENCHMARK); } private static Integer getRandomInteger(Random random) { return random.nextInt(MAXIMUM_INTEGER + 1); } private static List&lt;Integer&gt; createRandomCollection(Random random) { int size = 1 + random.nextInt(MAXIMUM_COLLECTION_SIZE); List&lt;Integer&gt; list = new ArrayList&lt;&gt;(size); for (int i = 0; i &lt; size; i++) { list.add(getRandomInteger(random)); } return list; } private enum BenchmarkChoice { WARMUP, BENCHMARK } private void initRandomGenerators() { randomJavaUtilLinkedList = new Random(seed); randomJavaUtilArrayList = new Random(seed); randomRoddeList = new Random(seed); randomTreeList = new Random(seed); } private void listsEqual() { listsEqual(roddeList, linkedList, arrayList, treeList); } private static void listsEqual(List&lt;Integer&gt;... lists) { if (lists.length &lt; 2) { throw new IllegalArgumentException(&quot;lists.length &lt; 2&quot;); } for (int i = 0; i &lt; lists.length - 1; i++) { if (lists[i].size() != lists[lists.length - 1].size()) { throw new IllegalStateException(&quot;Different size&quot;); } Iterator&lt;Integer&gt; iterator1 = lists[i].iterator(); Iterator&lt;Integer&gt; iterator2 = lists[lists.length - 1].iterator(); int elementIndex = 0; while (iterator1.hasNext() &amp;&amp; iterator2.hasNext()) { Integer integer1 = iterator1.next(); Integer integer2 = iterator2.next(); if (!integer1.equals(integer2)) { throw new IllegalStateException( &quot;Data mismatch: &quot; + integer1 + &quot; vs. &quot; + integer2 + &quot; at list &quot; + i + &quot;, element index: &quot; + elementIndex); } elementIndex++; } if (iterator1.hasNext() || iterator2.hasNext()) { throw new IllegalStateException(&quot;Bad iterators&quot;); } } } private void profile(BenchmarkChoice benchmarkChoice) { printTitle(benchmarkChoice); initRandomGenerators(); profileAddFirst(); profileAddLast(); profileAddViaIndex(); profileAppendCollection(); profileAddCollection(); profileRemoveViaIndex(); profileRemoveObject(); profileListIteratorAddition(); profileListIteratorRemoval(); profileStream(); profileParallelStream(); printTotalDurations(); resetLists(); zeroTimeDurationCounters(); } private void zeroTimeDurationCounters() { totalMillisArrayList = 0; totalMillisLinkedList = 0; totalMillisRoddeList = 0; totalMillisTreeList = 0; } private void resetLists() { roddeList = new com.github.coderodde.util.LinkedList&lt;&gt;(); linkedList = new java.util.LinkedList&lt;&gt;(); arrayList = new ArrayList&lt;&gt;(); treeList = new TreeList&lt;&gt;(); } private void profileAddFirst() { profileAddFirstRoddeList(); profileAddFirstLinkedList(); profileAddFirstArrayList(); profileAddFirstTreeList(); listsEqual(); System.out.println(); } private void profileAddLast() { profileAddLastRoddeList(); profileAddLastLinkedList(); profileAddLastArrayList(); profileAddLastTreeList(); listsEqual(); System.out.println(); } private void profileAddViaIndex() { profileAddIndexRoddeList(); profileAddIndexLinkedList(); profileAddIndexArrayList(); profileAddIndexTreeList(); listsEqual(); System.out.println(); } private void profileAddCollection() { profileAddCollectionRoddeList(); profileAddCollectionLinkedList(); profileAddCollectionArrayList(); profileAddCollectionTreeList(); listsEqual(); System.out.println(); } private void profileAppendCollection() { profileAppendCollectionRoddeList(); profileAppendCollectionLinkedList(); profileAppendCollectionArrayList(); profileAppendCollectionTreeList(); listsEqual(); System.out.println(); } private void profileRemoveViaIndex() { profileRemoveViaIndexRoddeList(); profileRemoveViaIndexLinkedList(); profileRemoveViaIndexArrayList(); profileRemoveViaIndexTreeList(); listsEqual(); System.out.println(); } private void profileRemoveObject() { profileRemoveObjectRoddeList(); profileRemoveObjectLinkedList(); profileRemoveObjectArrayList(); profileRemoveObjectTreeList(); listsEqual(); System.out.println(); } private void profileListIteratorAddition() { profileListIteratorAdditionRoddeList(); profileListIteratorAdditionLinkedList(); profileListIteratorAdditionArrayList(); profileListIteratorAdditionTreeList(); listsEqual(); System.out.println(); } private void profileListIteratorRemoval() { profileListIteratorRemovalRoddeList(); profileListIteratorRemovalLinkedList(); profileListIteratorRemovalArrayList(); profileListIteratorRemovalTreeList(); listsEqual(); System.out.println(); } private void profileStream() { profileStreamRoddeList(); profileStreamLinkedList(); profileStreamArrayList(); profileStreamTreeList(); listsEqual(); System.out.println(); } private void profileParallelStream() { profileParallelStreamRoddeList(); profileParallelStreamLinkedList(); profileParallelStreamArrayList(); profileParallelStreamTreeList(); Collections.sort(treeList); Collections.sort(roddeList); Collections.sort(arrayList); Collections.sort(linkedList); listsEqual(); System.out.println(); } private void printTotalDurations() { System.out.println(&quot;--- Total time elapsed ---&quot;); System.out.println( roddeList.getClass().getName() + &quot; in (ms): &quot; + totalMillisRoddeList); System.out.println( linkedList.getClass().getName() + &quot; in (ms): &quot; + totalMillisLinkedList); System.out.println( arrayList.getClass().getName() + &quot; in (ms): &quot; + totalMillisArrayList); System.out.println( treeList.getClass().getName() + &quot; in (ms): &quot; + totalMillisTreeList); } private long profileAddFirst( List&lt;Integer&gt; list, int operations, Random random) { long startMillis = System.currentTimeMillis(); for (int i = 0; i &lt; operations; i++) { list.add(0, getRandomInteger(random)); } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.addFirst in (ms): &quot; + durationMillis); return durationMillis; } private long profileAddLast( List&lt;Integer&gt; list, int operations, Random random) { long startMillis = System.currentTimeMillis(); for (int i = 0; i &lt; operations; i++) { list.add(list.size(), getRandomInteger(random)); } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.addLast in (ms): &quot; + durationMillis); return durationMillis; } private long profileAddIndex( List&lt;Integer&gt; list, int operations, Random random) { long startMillis = System.currentTimeMillis(); for (int i = 0; i &lt; operations; i++) { int index = random.nextInt(list.size()); Integer value = getRandomInteger(random); list.add(index, value); } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.add(int, E) in (ms): &quot; + durationMillis); return durationMillis; } private long profileAddCollection( List&lt;Integer&gt; list, int operations, Random random) { long startMillis = System.currentTimeMillis(); for (int i = 0; i &lt; operations; i++) { List&lt;Integer&gt; collection = createRandomCollection(random); int index = random.nextInt(list.size()); list.addAll(index, collection); } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.addAll(int, Collection) in (ms): &quot; + durationMillis); return durationMillis; } private long profileAppendCollection( List&lt;Integer&gt; list, int operations, Random random) { long startMillis = System.currentTimeMillis(); for (int i = 0; i &lt; operations; i++) { List&lt;Integer&gt; collection = createRandomCollection(random); list.addAll(collection); } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.addAll(Collection) in (ms): &quot; + durationMillis); return durationMillis; } private long profileRemoveViaIndex( List&lt;Integer&gt; list, int operations, Random random) { long startMillis = System.currentTimeMillis(); for (int i = 0; i &lt; operations; i++) { list.remove(random.nextInt(list.size())); } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.remove(int) in (ms): &quot; + durationMillis); return durationMillis; } private long profileRemoveObject( List&lt;Integer&gt; list, int operations, Random random) { long startMillis = System.currentTimeMillis(); for (int i = 0; i &lt; operations; i++) { list.remove(Integer.valueOf(getRandomInteger(random))); } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.remove(Object) in (ms): &quot; + durationMillis); return durationMillis; } private long profileListIteratorRemoval(List&lt;Integer&gt; list) { long startMillis = System.currentTimeMillis(); Iterator&lt;Integer&gt; iterator = list.iterator(); int counter = 0; while (iterator.hasNext()) { iterator.next(); // Remove every 2nd element: if (counter % 10 == 0) { try { iterator.remove(); } catch (AssertionError ae) { System.err.println(ae.getMessage()); System.exit(1); } } counter++; } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.iterator().remove() in (ms): &quot; + durationMillis); return durationMillis; } private long profileListIteratorAddition( List&lt;Integer&gt; list, Random random) { long startMillis = System.currentTimeMillis(); ListIterator&lt;Integer&gt; iterator = list.listIterator(1); int counter = 0; while (iterator.hasNext()) { iterator.next(); // Remove every 2nd element: if (counter % 10 == 0) { try { Integer integer = Integer.valueOf(random.nextInt(10_000)); iterator.add(integer); } catch (AssertionError ae) { System.err.println(ae.getMessage()); System.exit(1); } } counter++; } long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; System.out.println( list.getClass().getName() + &quot;.iterator().add() in (ms): &quot; + durationMillis); return durationMillis; } private long profileStream(List&lt;Integer&gt; list) { long startMillis = System.currentTimeMillis(); List&lt;Integer&gt; newList = list.stream().map(x -&gt; 2 * x).collect(Collectors.toList()); long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; list.clear(); list.addAll(newList); System.out.println( list.getClass().getName() + &quot;.stream() in (ms): &quot; + durationMillis); return durationMillis; } private long profileParallelStream(List&lt;Integer&gt; list) { long startMillis = System.currentTimeMillis(); List&lt;Integer&gt; newList = list.stream() .parallel() .map(x -&gt; 2 * x) .collect(Collectors.toList()); long endMillis = System.currentTimeMillis(); long durationMillis = endMillis - startMillis; list.clear(); list.addAll(newList); System.out.println( list.getClass().getName() + &quot;.stream().parallel() in (ms): &quot; + durationMillis); return durationMillis; } private void profileAddFirstRoddeList() { totalMillisRoddeList += profileAddFirst( roddeList, ADD_FIRST_OPERATIONS, randomRoddeList); } private void profileAddFirstLinkedList() { totalMillisLinkedList += profileAddFirst(linkedList, ADD_FIRST_OPERATIONS, randomJavaUtilLinkedList); } private void profileAddFirstArrayList() { totalMillisArrayList += profileAddFirst(arrayList, ADD_FIRST_OPERATIONS, randomJavaUtilArrayList); } private void profileAddFirstTreeList() { totalMillisTreeList += profileAddFirst(treeList, ADD_FIRST_OPERATIONS, randomTreeList); } private void profileAddLastRoddeList() { totalMillisRoddeList += profileAddLast(roddeList, ADD_LAST_OPERATIONS, randomRoddeList); } private void profileAddLastLinkedList() { totalMillisLinkedList += profileAddLast( linkedList, ADD_LAST_OPERATIONS, randomJavaUtilLinkedList); } private void profileAddLastArrayList() { totalMillisArrayList += profileAddLast(arrayList, ADD_LAST_OPERATIONS, randomJavaUtilArrayList); } private void profileAddLastTreeList() { totalMillisTreeList += profileAddLast(treeList, ADD_LAST_OPERATIONS, randomTreeList); } private void profileAddIndexRoddeList() { totalMillisRoddeList += profileAddIndex(roddeList, ADD_AT_OPERATIONS, randomRoddeList); } private void profileAddIndexLinkedList() { totalMillisLinkedList += profileAddIndex( linkedList, ADD_AT_OPERATIONS, randomJavaUtilLinkedList); } private void profileAddIndexArrayList() { totalMillisArrayList += profileAddIndex( arrayList, ADD_AT_OPERATIONS, randomJavaUtilArrayList); } private void profileAddIndexTreeList() { totalMillisTreeList += profileAddIndex( treeList, ADD_AT_OPERATIONS, randomTreeList); } private void profileAddCollectionRoddeList() { totalMillisRoddeList += profileAddCollection( roddeList, ADD_COLLECTION_AT_OPERATIONS, randomRoddeList); } private void profileAddCollectionLinkedList() { totalMillisLinkedList += profileAddCollection( linkedList, ADD_COLLECTION_AT_OPERATIONS, randomJavaUtilLinkedList); } private void profileAddCollectionArrayList() { totalMillisArrayList += profileAddCollection( arrayList, ADD_COLLECTION_AT_OPERATIONS, randomJavaUtilArrayList); } private void profileAddCollectionTreeList() { totalMillisTreeList += profileAddCollection( treeList, ADD_COLLECTION_AT_OPERATIONS, randomTreeList); } private void profileAppendCollectionRoddeList() { totalMillisRoddeList += profileAppendCollection( roddeList, ADD_LAST_COLLECTION_OPERATIONS, randomRoddeList); } private void profileAppendCollectionLinkedList() { totalMillisLinkedList += profileAppendCollection( linkedList, ADD_LAST_COLLECTION_OPERATIONS, randomJavaUtilLinkedList); } private void profileAppendCollectionArrayList() { totalMillisArrayList += profileAppendCollection( arrayList, ADD_LAST_COLLECTION_OPERATIONS, randomJavaUtilArrayList); } private void profileAppendCollectionTreeList() { totalMillisTreeList += profileAppendCollection( treeList, ADD_LAST_COLLECTION_OPERATIONS, randomTreeList); } private void profileRemoveViaIndexRoddeList() { totalMillisRoddeList += profileRemoveViaIndex( roddeList, REMOVE_VIA_INDEX_OPERATIONS, randomRoddeList); } private void profileRemoveViaIndexLinkedList() { totalMillisLinkedList += profileRemoveViaIndex( linkedList, REMOVE_VIA_INDEX_OPERATIONS, randomJavaUtilLinkedList); } private void profileRemoveViaIndexArrayList() { totalMillisArrayList += profileRemoveViaIndex( arrayList, REMOVE_VIA_INDEX_OPERATIONS, randomJavaUtilArrayList); } private void profileRemoveViaIndexTreeList() { totalMillisTreeList += profileRemoveViaIndex( treeList, REMOVE_VIA_INDEX_OPERATIONS, randomTreeList); } private void profileRemoveObjectRoddeList() { totalMillisRoddeList += profileRemoveObject( roddeList, REMOVE_OBJECT_OPERATIONS, randomRoddeList); roddeList.checkInvariant(); } private void profileRemoveObjectLinkedList() { totalMillisLinkedList += profileRemoveObject( linkedList, REMOVE_OBJECT_OPERATIONS, randomJavaUtilLinkedList); } private void profileRemoveObjectArrayList() { totalMillisArrayList += profileRemoveObject( arrayList, REMOVE_OBJECT_OPERATIONS, randomJavaUtilArrayList); } private void profileRemoveObjectTreeList() { totalMillisTreeList += profileRemoveObject( treeList, REMOVE_OBJECT_OPERATIONS, randomTreeList); } private void profileListIteratorRemovalRoddeList() { totalMillisRoddeList += profileListIteratorRemoval(roddeList); } private void profileListIteratorRemovalLinkedList() { totalMillisLinkedList += profileListIteratorRemoval(linkedList); } private void profileListIteratorRemovalArrayList() { totalMillisArrayList += profileListIteratorRemoval(arrayList); } private void profileListIteratorRemovalTreeList() { totalMillisTreeList += profileListIteratorRemoval(treeList); } private void profileListIteratorAdditionRoddeList() { totalMillisRoddeList += profileListIteratorAddition(roddeList, randomRoddeList); } private void profileListIteratorAdditionLinkedList() { totalMillisLinkedList += profileListIteratorAddition( linkedList, randomJavaUtilLinkedList); } private void profileListIteratorAdditionArrayList() { totalMillisArrayList += profileListIteratorAddition( arrayList, randomJavaUtilArrayList); } private void profileListIteratorAdditionTreeList() { totalMillisTreeList += profileListIteratorAddition(treeList, randomTreeList); } private void profileStreamRoddeList() { totalMillisRoddeList += profileStream(roddeList); } private void profileStreamLinkedList() { totalMillisLinkedList += profileStream(linkedList); } private void profileStreamArrayList() { totalMillisArrayList += profileStream(arrayList); } private void profileStreamTreeList() { totalMillisTreeList += profileStream(treeList); } private void profileParallelStreamRoddeList() { totalMillisRoddeList += profileParallelStream(roddeList); } private void profileParallelStreamLinkedList() { totalMillisLinkedList += profileParallelStream(linkedList); } private void profileParallelStreamArrayList() { totalMillisArrayList += profileParallelStream(arrayList); } private void profileParallelStreamTreeList() { totalMillisTreeList += profileParallelStream(treeList); } private void printTitle(BenchmarkChoice benchmarkChoice) { switch (benchmarkChoice) { case WARMUP: System.out.println(&quot;=== WARMUP RUN ===&quot;); break; case BENCHMARK: System.out.println(&quot;=== BENCHMARK RUN ===&quot;); break; } } } </code></pre> <p>My output is as follows:</p> <pre><code>&lt;&lt;&lt; LinkedList seed = 1629264992750 &gt;&gt;&gt; === WARMUP RUN === com.github.coderodde.util.LinkedList.addFirst in (ms): 57 java.util.LinkedList.addFirst in (ms): 5 java.util.ArrayList.addFirst in (ms): 493 org.apache.commons.collections4.list.TreeList.addFirst in (ms): 34 com.github.coderodde.util.LinkedList.addLast in (ms): 8 java.util.LinkedList.addLast in (ms): 27 java.util.ArrayList.addLast in (ms): 3 org.apache.commons.collections4.list.TreeList.addLast in (ms): 40 com.github.coderodde.util.LinkedList.add(int, E) in (ms): 40 java.util.LinkedList.add(int, E) in (ms): 1821 java.util.ArrayList.add(int, E) in (ms): 99 org.apache.commons.collections4.list.TreeList.add(int, E) in (ms): 13 com.github.coderodde.util.LinkedList.addAll(Collection) in (ms): 26 java.util.LinkedList.addAll(Collection) in (ms): 22 java.util.ArrayList.addAll(Collection) in (ms): 5 org.apache.commons.collections4.list.TreeList.addAll(Collection) in (ms): 23 com.github.coderodde.util.LinkedList.addAll(int, Collection) in (ms): 37 java.util.LinkedList.addAll(int, Collection) in (ms): 1431 java.util.ArrayList.addAll(int, Collection) in (ms): 74 org.apache.commons.collections4.list.TreeList.addAll(int, Collection) in (ms): 15 com.github.coderodde.util.LinkedList.remove(int) in (ms): 35 java.util.LinkedList.remove(int) in (ms): 4138 java.util.ArrayList.remove(int) in (ms): 181 org.apache.commons.collections4.list.TreeList.remove(int) in (ms): 11 com.github.coderodde.util.LinkedList.remove(Object) in (ms): 12 java.util.LinkedList.remove(Object) in (ms): 10 java.util.ArrayList.remove(Object) in (ms): 39 org.apache.commons.collections4.list.TreeList.remove(Object) in (ms): 22 com.github.coderodde.util.LinkedList.iterator().add() in (ms): 18 java.util.LinkedList.iterator().add() in (ms): 13 java.util.ArrayList.iterator().add() in (ms): 596 org.apache.commons.collections4.list.TreeList.iterator().add() in (ms): 19 com.github.coderodde.util.LinkedList.iterator().remove() in (ms): 69 java.util.LinkedList.iterator().remove() in (ms): 8 java.util.ArrayList.iterator().remove() in (ms): 738 org.apache.commons.collections4.list.TreeList.iterator().remove() in (ms): 28 com.github.coderodde.util.LinkedList.stream() in (ms): 17 java.util.LinkedList.stream() in (ms): 16 java.util.ArrayList.stream() in (ms): 7 org.apache.commons.collections4.list.TreeList.stream() in (ms): 68 com.github.coderodde.util.LinkedList.stream().parallel() in (ms): 41 java.util.LinkedList.stream().parallel() in (ms): 29 java.util.ArrayList.stream().parallel() in (ms): 88 org.apache.commons.collections4.list.TreeList.stream().parallel() in (ms): 123 --- Total time elapsed --- com.github.coderodde.util.LinkedList in (ms): 360 java.util.LinkedList in (ms): 7520 java.util.ArrayList in (ms): 2323 org.apache.commons.collections4.list.TreeList in (ms): 396 === BENCHMARK RUN === com.github.coderodde.util.LinkedList.addFirst in (ms): 37 java.util.LinkedList.addFirst in (ms): 4 java.util.ArrayList.addFirst in (ms): 415 org.apache.commons.collections4.list.TreeList.addFirst in (ms): 15 com.github.coderodde.util.LinkedList.addLast in (ms): 7 java.util.LinkedList.addLast in (ms): 4 java.util.ArrayList.addLast in (ms): 3 org.apache.commons.collections4.list.TreeList.addLast in (ms): 25 com.github.coderodde.util.LinkedList.add(int, E) in (ms): 18 java.util.LinkedList.add(int, E) in (ms): 1410 java.util.ArrayList.add(int, E) in (ms): 95 org.apache.commons.collections4.list.TreeList.add(int, E) in (ms): 6 com.github.coderodde.util.LinkedList.addAll(Collection) in (ms): 9 java.util.LinkedList.addAll(Collection) in (ms): 7 java.util.ArrayList.addAll(Collection) in (ms): 5 org.apache.commons.collections4.list.TreeList.addAll(Collection) in (ms): 2 com.github.coderodde.util.LinkedList.addAll(int, Collection) in (ms): 18 java.util.LinkedList.addAll(int, Collection) in (ms): 1376 java.util.ArrayList.addAll(int, Collection) in (ms): 65 org.apache.commons.collections4.list.TreeList.addAll(int, Collection) in (ms): 16 com.github.coderodde.util.LinkedList.remove(int) in (ms): 22 java.util.LinkedList.remove(int) in (ms): 4055 java.util.ArrayList.remove(int) in (ms): 171 org.apache.commons.collections4.list.TreeList.remove(int) in (ms): 8 com.github.coderodde.util.LinkedList.remove(Object) in (ms): 8 java.util.LinkedList.remove(Object) in (ms): 4 java.util.ArrayList.remove(Object) in (ms): 36 org.apache.commons.collections4.list.TreeList.remove(Object) in (ms): 1 com.github.coderodde.util.LinkedList.iterator().add() in (ms): 32 java.util.LinkedList.iterator().add() in (ms): 7 java.util.ArrayList.iterator().add() in (ms): 595 org.apache.commons.collections4.list.TreeList.iterator().add() in (ms): 73 com.github.coderodde.util.LinkedList.iterator().remove() in (ms): 58 java.util.LinkedList.iterator().remove() in (ms): 4 java.util.ArrayList.iterator().remove() in (ms): 726 org.apache.commons.collections4.list.TreeList.iterator().remove() in (ms): 24 com.github.coderodde.util.LinkedList.stream() in (ms): 4 java.util.LinkedList.stream() in (ms): 4 java.util.ArrayList.stream() in (ms): 5 org.apache.commons.collections4.list.TreeList.stream() in (ms): 7 com.github.coderodde.util.LinkedList.stream().parallel() in (ms): 3 java.util.LinkedList.stream().parallel() in (ms): 22 java.util.ArrayList.stream().parallel() in (ms): 4 org.apache.commons.collections4.list.TreeList.stream().parallel() in (ms): 29 --- Total time elapsed --- com.github.coderodde.util.LinkedList in (ms): 216 java.util.LinkedList in (ms): 6897 java.util.ArrayList in (ms): 2120 org.apache.commons.collections4.list.TreeList in (ms): 206 <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:18:54.663", "Id": "528277", "Score": "0", "body": "I see a lot of redundancy. Why would you have class that handles *all* methods at once? That doesn't look like a good *strategy* to me. Maybe you want to just compare *two* list implementations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:29:01.950", "Id": "528278", "Score": "0", "body": "Currently the code doesn't compile as the implementations are missing. If I try and comment them out then I get lots of compiler errors due to the way the class is setup. That's enough reason for me to leave it to above remark to be honest. Redesign so it just evaluates **one** particular list, possibly using virtual or abstract test methods if you need list-specific code to be run." } ]
[ { "body": "<p>There's a lot of scope for consolidating the benchmark code. Reducing some of the duplication can make it easier to update the code and help focus on core functionality of some of the methods. With that in mind, here's a few suggested refactorings...</p>\n<h2>A List is a List</h2>\n<p>You've got four lists of different types, all with their own variables, that are declared as the specific type of list. The point of your benchmark is to compare how each of your lists does the same action. Declaring the variables as the generic <code>List&lt;&gt;</code> instead would be the first step I'd take. The only line that actually seems to need to know is:</p>\n<blockquote>\n<pre><code>roddeList.checkInvariant();\n</code></pre>\n</blockquote>\n<p>Consider if this really needs to be in your benchmarking, or if it belongs somewhere else in your tests.</p>\n<h2>Benchmark data</h2>\n<p>There're three elements that make up your benchmark data. There's the list itself, the random number generator and the duration counter. Putting these pieces in the same class would allow them to be passed around together, again making it a little bit easier to share the code.</p>\n<h2>Things that are the same can go in lists</h2>\n<p>Once benchmark data is consolidated, all of the items start looking the same, so they can be put into a list. This could look something like this:</p>\n<pre><code>private static class BenchmarkElement {\n Random random;\n List&lt;Integer&gt; list;\n long total;\n\n public BenchmarkElement(List&lt;Integer&gt; list) {\n this.list = list;\n this.total = 0;\n }\n}\n\nBenchmarkElement linkedList = new BenchmarkElement(new LinkedList&lt;&gt;());\nBenchmarkElement arrayList = new BenchmarkElement(new ArrayList&lt;&gt;());\nBenchmarkElement treeList = new BenchmarkElement(new TreeList&lt;&gt;());\nBenchmarkElement roddeList = new BenchmarkElement(new com.github.coderodde.util.LinkedList&lt;&gt;());\n\nList&lt;BenchmarkElement&gt; lists = asList(linkedList, arrayList, treeList, roddeList);\n</code></pre>\n<h2>Lists are iterable..</h2>\n<p>Having separate variables for each list, means that you need to repeat the code, with a different variable name each time you want to do something. Once the benchmark elements are all contained in a list, you can instead iterate over the list instead. So Instead of doing this:</p>\n<blockquote>\n<pre><code>private void profileAddFirst() {\n profileAddFirstRoddeList();\n profileAddFirstLinkedList();\n profileAddFirstArrayList();\n profileAddFirstTreeList();\n\n listsEqual();\n System.out.println();\n}\n</code></pre>\n</blockquote>\n<p>With four slightly different versions of:</p>\n<blockquote>\n<pre><code>private void profileAddFirstRoddeList() {\n totalMillisRoddeList +=\n profileAddFirst(\n roddeList,\n ADD_FIRST_OPERATIONS,\n randomRoddeList);\n}\n</code></pre>\n</blockquote>\n<p>It becomes possible to do something like this:</p>\n<pre><code>private void profileAddFirst() {\n lists.forEach(listElement -&gt;\n listElement.total +=\n profileAddFirst(\n listElement.list,\n ADD_FIRST_OPERATIONS,\n listElement.random));\n\n listsEqual();\n System.out.println();\n}\n</code></pre>\n<h2>Functions are first class citizens</h2>\n<p>Once a few functions have been refactored as above, it becomes clear that there's a common pattern emerging in the code. For each of the benchmark lists, we call a specific profiling function, supplying required parameters and adjusting the running totals for that list. We then check if all the lists are equal and print a blank line to terminate the results. By passing in the method to call, it's possible to share this functionality between the various calls. So, something like this:</p>\n<pre><code>interface TriProfileMethod {\n long accept(List&lt;Integer&gt; list, Integer operations, Random random);\n}\nprivate void profileMethod(TriProfileMethod profilable, Integer operations) {\n lists.forEach(listElement -&gt;\n listElement.total +=\n profilable.methodToProfile(\n profilable.accept(\n listElement.list,\n operations,\n listElement.random));\n\n listsEqual();\n System.out.println();\n}\n</code></pre>\n<p>Allows calls like this:</p>\n<pre><code>profileMethod(this::profileAddFirst, ADD_FIRST_OPERATIONS);\nprofileMethod(this::profileAddLast, ADD_LAST_OPERATIONS);\nprofileMethod(this::profileAddIndex, ADD_AT_OPERATIONS);\n</code></pre>\n<h2>Consider what needs to be a parameter</h2>\n<p>Constants like <code>ADD_FIRST_OPERATIONS</code> are being passed into methods like <code>profileAddFirst</code>, in order to set the number of iterations that the method performs. However no other values are being passed into these methods and the constants are available from within them. Rather than passing in the value, consider removing it from the parameter list and just accessing it from within the methods.</p>\n<h2>Extending into two profiling methods</h2>\n<p>By consolidating the parameters to the profiling functions and continuing to centralise the shared processing, to profiling method patterns appear.</p>\n<ol>\n<li>Standard processing iterates through the list, starting a timer for each element and executing a profiling procedure and checking the elapsed duration, before validating that all the lists are equal.</li>\n<li>Stream processing is almost the same, but the profiling method returns a new list, which needs to be used to create the returned list, after the timer has stopped.</li>\n</ol>\n<p>This gives two methods:</p>\n<pre><code>private void profileMethod(Consumer&lt;BenchmarkElement&gt; method, String name) {\n lists.forEach(listElement -&gt; {\n long startMillis = System.currentTimeMillis();\n\n method.accept(listElement);\n\n long endMillis = System.currentTimeMillis();\n long durationMillis = endMillis - startMillis;\n\n listElement.total += durationMillis;\n\n System.out.println(listElement.list.getClass().getName() +\n &quot;.&quot; + name + &quot; in (ms): &quot; +\n durationMillis);\n });\n\n listsEqual();\n System.out.println();\n}\n\nprivate void profileStreamMethod(Function&lt;BenchmarkElement, List&lt;Integer&gt;&gt; method, String name) {\n lists.forEach(listElement -&gt; {\n long startMillis = System.currentTimeMillis();\n\n List&lt;Integer&gt; newList = method.apply(listElement);\n\n long endMillis = System.currentTimeMillis();\n long durationMillis = endMillis - startMillis;\n\n listElement.list.clear();\n listElement.list.addAll(newList);\n listElement.total += durationMillis;\n\n System.out.println(\n listElement.list.getClass().getName() +\n &quot;.&quot; + name + &quot; in (ms): &quot; + durationMillis);\n\n Collections.sort(listElement.list);\n });\n\n listsEqual();\n System.out.println();\n}\n</code></pre>\n<p>By extracting this timer code, it makes the individual profiling methods much more concise and focused on what it is they're doing:</p>\n<pre><code>private void profileAddFirst(BenchmarkElement element) {\n for (int i = 0; i &lt; ADD_FIRST_OPERATIONS; i++) {\n element.list.add(0, getRandomInteger(element.random));\n }\n}\n</code></pre>\n<h2>Putting it together</h2>\n<p>Combining the above, with a few other minor changes (removal of unnecessary boxing, vararg warnings, using the enum name rather than a switch statement) leads to code that's about a third of the size of the original. There's still work that could be done but I think this is a good first step along that journey.</p>\n<pre><code>package com.github.coderodde.util.benchmark;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.ListIterator;\nimport java.util.Random;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.collections4.list.TreeList;\n\nimport static java.util.Arrays.asList;\n\npublic class LinkedListBenchmark {\n\n private static final int ADD_FIRST_OPERATIONS = 100_000;\n private static final int ADD_LAST_OPERATIONS = 100_000;\n private static final int ADD_AT_OPERATIONS = 10_000;\n private static final int ADD_COLLECTION_AT_OPERATIONS = 4_000;\n private static final int ADD_LAST_COLLECTION_OPERATIONS = 10_000;\n private static final int REMOVE_VIA_INDEX_OPERATIONS = 10_000;\n private static final int REMOVE_OBJECT_OPERATIONS = 1_000;\n\n private static final int MAXIMUM_COLLECTION_SIZE = 20;\n\n private static final int MAXIMUM_INTEGER = 1_000;\n\n private final long seed;\n\n private static class BenchmarkElement {\n Random random;\n List&lt;Integer&gt; list;\n long total;\n\n public BenchmarkElement(List&lt;Integer&gt; list) {\n this.list = list;\n this.total = 0;\n }\n }\n\n BenchmarkElement linkedList = new BenchmarkElement(new LinkedList&lt;&gt;());\n BenchmarkElement arrayList = new BenchmarkElement(new ArrayList&lt;&gt;());\n BenchmarkElement treeList = new BenchmarkElement(new TreeList&lt;&gt;());\n BenchmarkElement roddeList = new BenchmarkElement(new com.github.coderodde.util.LinkedList&lt;&gt;());\n\n List&lt;BenchmarkElement&gt; lists = asList(linkedList, arrayList, treeList, roddeList);\n\n LinkedListBenchmark(long seed) {\n this.seed = seed;\n }\n\n void warmup() {\n profile(BenchmarkChoice.WARMUP);\n }\n\n void benchmark() {\n profile(BenchmarkChoice.BENCHMARK);\n }\n\n private static int getRandomInteger(Random random) {\n return random.nextInt(MAXIMUM_INTEGER + 1);\n }\n\n private static List&lt;Integer&gt; createRandomCollection(Random random) {\n int size = 1 + random.nextInt(MAXIMUM_COLLECTION_SIZE);\n\n List&lt;Integer&gt; list = new ArrayList&lt;&gt;(size);\n\n for (int i = 0; i &lt; size; i++) {\n list.add(getRandomInteger(random));\n }\n\n return list;\n }\n\n private enum BenchmarkChoice {WARMUP, BENCHMARK}\n\n private void initRandomGenerators() {\n lists.forEach(l -&gt; l.random = new Random(seed));\n }\n\n private void listsEqual() {\n if (lists.size() &lt; 2) {\n throw new IllegalArgumentException(&quot;lists.length &lt; 2&quot;);\n }\n\n for (int i = 0; i &lt; lists.size() - 1; i++) {\n if (lists.get(i).list.size() != lists.get(lists.size() - 1).list.size()) {\n throw new IllegalStateException(&quot;Different size&quot;);\n }\n\n Iterator&lt;Integer&gt; iterator1 = lists.get(i).list.iterator();\n Iterator&lt;Integer&gt; iterator2 = lists.get(lists.size() - 1).list.iterator();\n\n int elementIndex = 0;\n\n while (iterator1.hasNext() &amp;&amp; iterator2.hasNext()) {\n Integer integer1 = iterator1.next();\n Integer integer2 = iterator2.next();\n\n if (!integer1.equals(integer2)) {\n throw new IllegalStateException(\n &quot;Data mismatch: &quot; + integer1 + &quot; vs. &quot; +\n integer2 + &quot; at list &quot; + i +\n &quot;, element index: &quot; + elementIndex);\n }\n\n elementIndex++;\n }\n\n if (iterator1.hasNext() || iterator2.hasNext()) {\n throw new IllegalStateException(&quot;Bad iterators&quot;);\n }\n }\n }\n\n private void profile(BenchmarkChoice benchmarkChoice) {\n\n printTitle(benchmarkChoice);\n initRandomGenerators();\n\n profileMethod(this::profileAddFirst, &quot;addFirst&quot;);\n profileMethod(this::profileAddLast, &quot;addLast&quot;);\n profileMethod(this::profileAddIndex, &quot;add(int, E)&quot;);\n profileMethod(this::profileAppendCollection, &quot;addAll(Collection)&quot;);\n profileMethod(this::profileAddCollection, &quot;addAll(int, Collection)&quot;);\n profileMethod(this::profileRemoveViaIndex, &quot;remove(int)&quot;);\n profileMethod(this::profileRemoveObject, &quot;remove(Object)&quot;);\n\n ((com.github.coderodde.util.LinkedList&lt;Integer&gt;) roddeList.list).checkInvariant(); // This doesn't seem to be part of what you want to profile?\n\n profileMethod(this::profileListIteratorAddition, &quot;.iterator().add()&quot;);\n profileMethod(this::profileListIteratorRemoval, &quot;.iterator().remove()&quot;);\n profileStreamMethod(this::profileStream, &quot;stream()&quot;);\n profileStreamMethod(this::profileParallelStream, &quot;stream().parallel()&quot;);\n\n printTotalDurations();\n\n resetLists();\n zeroTimeDurationCounters();\n }\n\n private void zeroTimeDurationCounters() {\n lists.forEach(list -&gt; list.total = 0);\n }\n\n private void resetLists() {\n roddeList.list = new com.github.coderodde.util.LinkedList&lt;&gt;();\n linkedList.list = new java.util.LinkedList&lt;&gt;();\n arrayList.list = new ArrayList&lt;&gt;();\n treeList.list = new TreeList&lt;&gt;();\n }\n\n private void profileStreamMethod(Function&lt;BenchmarkElement, List&lt;Integer&gt;&gt; method, String name) {\n lists.forEach(listElement -&gt; {\n long startMillis = System.currentTimeMillis();\n\n List&lt;Integer&gt; newList = method.apply(listElement);\n\n long endMillis = System.currentTimeMillis();\n long durationMillis = endMillis - startMillis;\n\n listElement.list.clear();\n listElement.list.addAll(newList);\n listElement.total += durationMillis;\n\n System.out.println(\n listElement.list.getClass().getName() +\n &quot;.&quot; + name + &quot; in (ms): &quot; + durationMillis);\n\n Collections.sort(listElement.list);\n });\n\n listsEqual();\n System.out.println();\n }\n\n private void profileMethod(Consumer&lt;BenchmarkElement&gt; method, String name) {\n lists.forEach(listElement -&gt; {\n long startMillis = System.currentTimeMillis();\n\n method.accept(listElement);\n\n long endMillis = System.currentTimeMillis();\n long durationMillis = endMillis - startMillis;\n\n listElement.total += durationMillis;\n\n System.out.println(listElement.list.getClass().getName() +\n &quot;.&quot; + name + &quot; in (ms): &quot; +\n durationMillis);\n });\n\n listsEqual();\n System.out.println();\n }\n\n private void printTotalDurations() {\n System.out.println(&quot;--- Total time elapsed ---&quot;);\n\n lists.forEach(benchmarkElement -&gt;\n System.out.println(\n benchmarkElement.list.getClass().getName() +\n &quot; in (ms): &quot; +\n benchmarkElement.total)\n );\n }\n\n private void profileAddFirst(BenchmarkElement element) {\n for (int i = 0; i &lt; ADD_FIRST_OPERATIONS; i++) {\n element.list.add(0, getRandomInteger(element.random));\n }\n }\n\n private void profileAddLast(BenchmarkElement element) {\n for (int i = 0; i &lt; ADD_LAST_OPERATIONS; i++) {\n element.list.add(element.list.size(), getRandomInteger(element.random));\n }\n }\n\n private void profileAddIndex(BenchmarkElement element) {\n for (int i = 0; i &lt; ADD_AT_OPERATIONS; i++) {\n int index = element.random.nextInt(element.list.size());\n Integer value = getRandomInteger(element.random);\n element.list.add(index, value);\n }\n }\n\n private void profileAddCollection(BenchmarkElement element) {\n for (int i = 0; i &lt; ADD_COLLECTION_AT_OPERATIONS; i++) {\n List&lt;Integer&gt; collection = createRandomCollection(element.random);\n int index = element.random.nextInt(element.list.size());\n element.list.addAll(index, collection);\n }\n }\n\n private void profileAppendCollection(BenchmarkElement element) {\n for (int i = 0; i &lt; ADD_LAST_COLLECTION_OPERATIONS; i++) {\n List&lt;Integer&gt; collection = createRandomCollection(element.random);\n element.list.addAll(collection);\n }\n }\n\n private void profileRemoveViaIndex(BenchmarkElement element) {\n for (int i = 0; i &lt; REMOVE_VIA_INDEX_OPERATIONS; i++) {\n element.list.remove(element.random.nextInt(element.list.size()));\n }\n }\n\n private void profileRemoveObject(BenchmarkElement element) {\n for (int i = 0; i &lt; REMOVE_OBJECT_OPERATIONS; i++) {\n element.list.remove(getRandomInteger(element.random));\n }\n }\n\n private void profileListIteratorRemoval(BenchmarkElement element) {\n Iterator&lt;Integer&gt; iterator = element.list.iterator();\n int counter = 0;\n\n while (iterator.hasNext()) {\n iterator.next();\n\n // Remove every 2nd element:\n if (counter % 10 == 0) {\n try {\n iterator.remove();\n } catch (AssertionError ae) {\n System.err.println(ae.getMessage());\n System.exit(1);\n }\n }\n\n counter++;\n }\n }\n\n private void profileListIteratorAddition(BenchmarkElement element) {\n ListIterator&lt;Integer&gt; iterator = element.list.listIterator(1);\n int counter = 0;\n\n while (iterator.hasNext()) {\n iterator.next();\n\n // Remove every 2nd element:\n if (counter % 10 == 0) {\n try {\n iterator.add(element.random.nextInt(10_000));\n } catch (AssertionError ae) {\n System.err.println(ae.getMessage());\n System.exit(1);\n }\n }\n\n counter++;\n }\n }\n\n private List&lt;Integer&gt; profileStream(BenchmarkElement element) {\n return element.list.stream().map(x -&gt; 2 * x).collect(Collectors.toList());\n }\n\n private List&lt;Integer&gt; profileParallelStream(BenchmarkElement element) {\n return element.list.stream()\n .parallel()\n .map(x -&gt; 2 * x)\n .collect(Collectors.toList());\n }\n\n private void printTitle(BenchmarkChoice benchmarkChoice) {\n System.out.println(&quot;=== &quot; + benchmarkChoice.toString() + &quot; RUN ===&quot;);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T00:07:54.550", "Id": "268606", "ParentId": "266154", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T07:32:58.703", "Id": "266154", "Score": "2", "Tags": [ "java", "performance", "linked-list", "benchmarking" ], "Title": "Faster, indexed, heuristic doubly-linked list data structure in Java: benchmark" }
266154
<p>Here I have the unit tests for the <a href="https://codereview.stackexchange.com/questions/266152/indexed-heuristic-doubly-linked-list-data-in-java-implementation">indexed doubly-linked list</a>.</p> <p>It goes like this:</p> <pre><code>package com.github.coderodde.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Random; import java.util.Spliterator; import java.util.function.Consumer; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; public class LinkedListTest { private final LinkedList&lt;Integer&gt; list = new LinkedList&lt;&gt;(); @Before public void setUp() { list.clear(); } @Test public void testAdd() { assertTrue(list.isEmpty()); assertEquals(0, list.size()); list.add(1); assertEquals(1, list.size()); assertFalse(list.isEmpty()); assertEquals(Integer.valueOf(1), list.get(0)); list.add(2); assertEquals(2, list.size()); assertFalse(list.isEmpty()); assertEquals(Integer.valueOf(1), list.get(0)); assertEquals(Integer.valueOf(2), list.get(1)); } @Test public void testAddFirst() { assertTrue(list.isEmpty()); assertEquals(0, list.size()); list.addFirst(1); assertEquals(1, list.size()); assertFalse(list.isEmpty()); assertEquals(Integer.valueOf(1), list.get(0)); list.addFirst(2); assertEquals(2, list.size()); assertFalse(list.isEmpty()); assertEquals(Integer.valueOf(2), list.get(0)); assertEquals(Integer.valueOf(1), list.get(1)); } @Test(expected = IndexOutOfBoundsException.class) public void testThrowsOnAccessingEmptyList() { list.get(0); } @Test(expected = IndexOutOfBoundsException.class) public void testOnNegativeIndexInEmptyList() { list.get(-1); } @Test(expected = IndexOutOfBoundsException.class) public void testOnNegativeIndexInNonEmptyList() { list.addFirst(10); list.get(-1); } @Test(expected = IndexOutOfBoundsException.class) public void testOnTooLargeIndex() { list.addFirst(10); list.addLast(20); list.get(2); } @Test public void testAddIndexAndElement() { list.add(0, 1); assertEquals(Integer.valueOf(1), list.get(0)); list.add(0, 2); assertEquals(Integer.valueOf(2), list.get(0)); assertEquals(Integer.valueOf(1), list.get(1)); list.add(2, 10); assertEquals(Integer.valueOf(2), list.get(0)); assertEquals(Integer.valueOf(1), list.get(1)); assertEquals(Integer.valueOf(10), list.get(2)); list.add(2, 100); assertEquals(Integer.valueOf(2), list.get(0)); assertEquals(Integer.valueOf(1), list.get(1)); assertEquals(Integer.valueOf(100), list.get(2)); assertEquals(Integer.valueOf(10), list.get(3)); } @Test public void testAddCollectionOneElementToEmptyList() { List&lt;Integer&gt; c = new ArrayList&lt;&gt;(); c.add(100); list.addAll(c); assertFalse(list.isEmpty()); assertEquals(1, list.size()); assertEquals(Integer.valueOf(100), list.get(0)); } @Test public void testAddCollectionThreeElementsToEmptyList() { assertTrue(list.isEmpty()); assertEquals(0, list.size()); List&lt;Integer&gt; c = Arrays.asList(1, 2, 3); list.addAll(c); assertFalse(list.isEmpty()); assertEquals(3, list.size()); for (int i = 0; i &lt; list.size(); i++) { assertEquals(Integer.valueOf(i + 1), list.get(i)); } } @Test public void testAddCollectionAtIndex() { list.addAll(0, Arrays.asList(2, 3)); // setAll list.addAll(0, Arrays.asList(0, 1)); // prependAll list.addAll(4, Arrays.asList(6, 7)); // appendAll list.addAll(4, Arrays.asList(4, 5)); // insertAll for (int i = 0; i &lt; list.size(); i++) { assertEquals(Integer.valueOf(i), list.get(i)); } } @Test public void testRemoveInt() { list.addAll(Arrays.asList(0, 1, 2, 3, 4)); assertEquals(Integer.valueOf(0), list.remove(0)); assertEquals(Integer.valueOf(4), list.remove(3)); assertEquals(Integer.valueOf(2), list.remove(1)); assertEquals(Integer.valueOf(1), list.remove(0)); assertEquals(Integer.valueOf(3), list.remove(0)); } @Test public void testBasicIteratorUsage() { for (int i = 0; i &lt; 1000; i++) { list.add(i); } Iterator&lt;Integer&gt; iterator = list.iterator(); for (int i = 0; i &lt; 1000; i++) { assertTrue(iterator.hasNext()); assertEquals(Integer.valueOf(i), iterator.next()); } assertFalse(iterator.hasNext()); } @Test public void bruteForceAddCollectionAtIndex() { long seed = System.currentTimeMillis(); System.out.println(&quot;- bruteForceAddCollectionAtIndex.seed = &quot; + seed); Random random = new Random(seed); list.addAll(getIntegerList()); java.util.LinkedList&lt;Integer&gt; referenceList = new java.util.LinkedList&lt;&gt;(list); for (int op = 0; op &lt; 100; op++) { int index = random.nextInt(list.size()); Collection&lt;Integer&gt; coll = getIntegerList(random.nextInt(40)); referenceList.addAll(index, coll); list.addAll(index, coll); if (!listsEqual(list, referenceList)) { fail(&quot;Lists not equal!&quot;); } } } @Test public void removeAtIndex() { list.addAll(Arrays.asList(0, 1, 2, 3, 4)); assertEquals(Integer.valueOf(2), list.remove(2)); assertEquals(Integer.valueOf(0), list.remove(0)); assertEquals(Integer.valueOf(4), list.remove(2)); } @Test public void removeObject() { list.addAll(Arrays.asList(0, 1, 2, 3, 4)); assertFalse(list.remove(Integer.valueOf(10))); assertFalse(list.remove(null)); list.add(3, null); assertTrue(list.remove(null)); assertTrue(list.remove(Integer.valueOf(4))); assertTrue(list.remove(Integer.valueOf(0))); assertTrue(list.remove(Integer.valueOf(2))); assertFalse(list.remove(Integer.valueOf(2))); } @Test public void basicIteratorTraversal() { list.addAll(Arrays.asList(0, 1, 2, 3, 4)); Iterator&lt;Integer&gt; iter = list.iterator(); for (int i = 0; i &lt; list.size(); i++) { assertTrue(iter.hasNext()); assertEquals(Integer.valueOf(i), iter.next()); } iter = list.iterator(); class MyConsumer implements Consumer&lt;Integer&gt; { int total; @Override public void accept(Integer t) { total += t; } } MyConsumer myConsumer = new MyConsumer(); list.iterator().forEachRemaining(myConsumer); assertEquals(10, myConsumer.total); } @Test public void basicIteratorRemoval() { list.addAll(Arrays.asList(0, 1, 2, 3, 4)); Iterator&lt;Integer&gt; iter = list.iterator(); iter.next(); iter.next(); iter.remove(); assertEquals(4, list.size()); iter = list.iterator(); iter.next(); iter.remove(); assertEquals(3, list.size()); assertEquals(Integer.valueOf(2), list.get(0)); assertEquals(Integer.valueOf(3), list.get(1)); assertEquals(Integer.valueOf(4), list.get(2)); } @Test public void enhancedIteratorTraversal() { list.addAll(Arrays.asList(0, 1, 2, 3, 4)); ListIterator&lt;Integer&gt; iter = list.listIterator(); assertFalse(iter.hasPrevious()); for (int i = 0; i &lt; list.size(); i++) { assertTrue(iter.hasNext()); assertEquals(Integer.valueOf(i), iter.next()); } assertFalse(iter.hasNext()); for (int i = 4; i &gt;= 0; i--) { assertTrue(iter.hasPrevious()); assertEquals(Integer.valueOf(i), iter.previous()); } iter = list.listIterator(2); assertEquals(Integer.valueOf(2), iter.next()); assertEquals(Integer.valueOf(2), iter.previous()); iter = list.listIterator(3); assertEquals(Integer.valueOf(3), iter.next()); assertEquals(Integer.valueOf(4), iter.next()); assertFalse(iter.hasNext()); assertTrue(iter.hasPrevious()); } @Test public void enhancedIteratorAddition() { list.addAll(Arrays.asList(1, 2, 3)); ListIterator&lt;Integer&gt; iter = list.listIterator(); iter.add(0); while (iter.hasNext()) { iter.next(); } iter.add(4); iter = list.listIterator(); for (int i = 0; i &lt; list.size(); i++) { assertEquals(Integer.valueOf(i), iter.next()); } iter = list.listIterator(2); iter.add(10); assertEquals(Integer.valueOf(10), list.get(2)); } @Test public void findFailingIterat() { list.addAll(getIntegerList(345_850)); Iterator&lt;Integer&gt; iterator = list.iterator(); int counter = 0; while (iterator.hasNext()) { iterator.next(); // Remove every 2nd element: if (counter % 10 == 0) { iterator.remove(); } counter++; } } @Test public void bruteForceIteratorRemove() throws Exception { list.addAll(getIntegerList(1000)); int counter = 0; List&lt;Integer&gt; arrayList = new ArrayList&lt;&gt;(list); Iterator&lt;Integer&gt; iter = list.iterator(); Iterator&lt;Integer&gt; arrayListIter = arrayList.iterator(); int totalIterations = 0; while (iter.hasNext()) { iter.next(); arrayListIter.next(); if (counter % 10 == 0) { try { iter.remove(); } catch (IllegalStateException ex) { throw new Exception(ex); } arrayListIter.remove(); counter = 0; } else { counter++; } if (!listsEqual(list, arrayList)) { throw new IllegalStateException( &quot;totalIterations = &quot; + totalIterations); } totalIterations++; } } @Test public void bruteForceRemoveObjectBeforeIteratorRemove() { LinkedList&lt;String&gt; ll = new com.github.coderodde.util.LinkedList&lt;&gt;(); ll.add(&quot;a&quot;); ll.add(&quot;b&quot;); ll.add(&quot;c&quot;); ll.add(&quot;d&quot;); ll.remove(&quot;b&quot;); ll.remove(&quot;c&quot;); ll.remove(&quot;d&quot;); ll.remove(&quot;a&quot;); } @Test public void findFailingRemoveObject() { java.util.LinkedList&lt;Integer&gt; referenceList = new java.util.LinkedList&lt;&gt;(); list.addAll(getIntegerList(10)); referenceList.addAll(list); Integer probe = list.get(1); list.remove(probe); referenceList.remove(probe); Iterator&lt;Integer&gt; iterator1 = list.iterator(); Iterator&lt;Integer&gt; iterator2 = referenceList.iterator(); Random random = new Random(100L); while (!list.isEmpty()) { if (!iterator1.hasNext()) { if (iterator2.hasNext()) { throw new IllegalStateException(); } iterator1 = list.iterator(); iterator2 = referenceList.iterator(); continue; } iterator1.next(); iterator2.next(); if (random.nextBoolean()) { iterator1.remove(); iterator2.remove(); assertTrue(listsEqual(list, referenceList)); } } assertTrue(listsEqual(list, referenceList)); } @Test public void iteratorAdd() { list.addAll(getIntegerList(4)); ListIterator&lt;Integer&gt; iterator = list.listIterator(1); assertEquals(1, iterator.nextIndex()); assertEquals(0, iterator.previousIndex()); iterator.next(); assertEquals(2, iterator.nextIndex()); assertEquals(1, iterator.previousIndex()); iterator.add(Integer.valueOf(100)); assertEquals(Integer.valueOf(0), list.get(0)); assertEquals(Integer.valueOf(1), list.get(1)); assertEquals(Integer.valueOf(100), list.get(2)); assertEquals(Integer.valueOf(2), list.get(3)); assertEquals(Integer.valueOf(3), list.get(4)); } @Test public void bruteForceIteratorTest() { list.addAll(getIntegerList(100)); List&lt;Integer&gt; referenceList = new java.util.LinkedList&lt;&gt;(list); ListIterator&lt;Integer&gt; iterator1 = list.listIterator(2); ListIterator&lt;Integer&gt; iterator2 = referenceList.listIterator(2); long seed = System.currentTimeMillis(); Random random = new Random(seed); System.out.println(&quot;- bruteForceIteratorTest: seed = &quot; + seed); while (iterator1.hasNext()) { if (!iterator2.hasNext()) { fail(&quot;Iterator mismatch on hasNext().&quot;); } iterator1.next(); iterator2.next(); int choice = random.nextInt(10); if (choice &lt; 2) { Integer integer = Integer.valueOf(random.nextInt(100)); iterator1.add(integer); iterator2.add(integer); assertTrue(listsEqual(list, referenceList)); } else if (choice == 2) { iterator1.remove(); iterator2.remove(); assertTrue(listsEqual(list, referenceList)); } else if (choice &lt; 6) { if (iterator1.hasPrevious()) { iterator1.previous(); } if (iterator2.hasPrevious()) { iterator2.previous(); } } else { if (iterator1.hasNext()) { iterator1.next(); } if (iterator2.hasNext()) { iterator2.next(); } } } if (iterator2.hasNext()) { fail(&quot;Java List iterator has more to offer.&quot;); } } @Test public void indexOf() { list.add(1); list.add(2); list.add(3); list.add(3); list.add(2); list.add(1); assertEquals(0, list.indexOf(1)); assertEquals(1, list.indexOf(2)); assertEquals(2, list.indexOf(3)); assertEquals(3, list.lastIndexOf(3)); assertEquals(4, list.lastIndexOf(2)); assertEquals(5, list.lastIndexOf(1)); } class MyIntegerConsumer implements Consumer&lt;Integer&gt; { List&lt;Integer&gt; ints = new ArrayList&lt;&gt;(); @Override public void accept(Integer t) { ints.add(t); } } @Test @SuppressWarnings(&quot;empty-statement&quot;) public void basicSpliteratorUsage() { list.addAll(getIntegerList(10_000)); Spliterator&lt;Integer&gt; spliterator1 = list.spliterator(); Spliterator&lt;Integer&gt; spliterator2 = spliterator1.trySplit(); //// spliterator 2 : spliterator 1 assertEquals(5000, spliterator1.getExactSizeIfKnown()); assertEquals(5000, spliterator2.getExactSizeIfKnown()); assertTrue(spliterator2.tryAdvance( i -&gt; assertEquals(list.get(0), Integer.valueOf(0)))); assertTrue(spliterator2.tryAdvance( i -&gt; assertEquals(list.get(1), Integer.valueOf(1)))); assertTrue(spliterator2.tryAdvance( i -&gt; assertEquals(list.get(2), Integer.valueOf(2)))); assertTrue(spliterator1.tryAdvance( i -&gt; assertEquals(list.get(5000), Integer.valueOf(5000)))); assertTrue(spliterator1.tryAdvance( i -&gt; assertEquals(list.get(5001), Integer.valueOf(5001)))); assertTrue(spliterator1.tryAdvance( i -&gt; assertEquals(list.get(5002), Integer.valueOf(5002)))); //// spliterator 3 : spliterator 2 : splitereator 1 Spliterator&lt;Integer&gt; spliterator3 = spliterator2.trySplit(); assertEquals(4997, spliterator1.getExactSizeIfKnown()); assertTrue(spliterator3.tryAdvance( i -&gt; assertEquals(list.get(3), Integer.valueOf(3)))); assertTrue(spliterator3.tryAdvance( i -&gt; assertEquals(list.get(4), Integer.valueOf(4)))); assertTrue(spliterator3.tryAdvance( i -&gt; assertEquals(list.get(5), Integer.valueOf(5)))); //// MyIntegerConsumer consumer = new MyIntegerConsumer(); while (spliterator1.tryAdvance(consumer)); for (int i = 0; i &lt; consumer.ints.size(); i++) { Integer actualInteger = consumer.ints.get(i); Integer expectedInteger = 5003 + i; assertEquals(expectedInteger, actualInteger); } } @Test public void spliteratorForEachRemaining() { list.addAll(getIntegerList(10_000)); Spliterator&lt;Integer&gt; split = list.spliterator(); MyIntegerConsumer consumer = new MyIntegerConsumer(); split.forEachRemaining(consumer); for (int i = 0; i &lt; 10_000; i++) { assertEquals(Integer.valueOf(i), consumer.ints.get(i)); } } @Test public void spliteratorForEachRemainingTwoSpliterators() { list.addAll(getIntegerList(10_000)); Spliterator&lt;Integer&gt; splitRight = list.spliterator(); Spliterator&lt;Integer&gt; splitLeft = splitRight.trySplit(); MyIntegerConsumer consumerRight = new MyIntegerConsumer(); MyIntegerConsumer consumerLeft = new MyIntegerConsumer(); splitRight.forEachRemaining(consumerRight); splitLeft.forEachRemaining(consumerLeft); for (int i = 0; i &lt; 5_000; i++) { assertEquals(Integer.valueOf(i), consumerLeft.ints.get(i)); } for (int i = 5_000; i &lt; 10_000; i++) { assertEquals(Integer.valueOf(i), consumerRight.ints.get(i - 5_000)); } } @Test public void spliteratorForEachRemainingWithAdvance() { list.addAll(getIntegerList(10_000)); Spliterator&lt;Integer&gt; rightSpliterator = list.spliterator(); assertTrue( rightSpliterator.tryAdvance( i -&gt; assertEquals(Integer.valueOf(0), i))); Spliterator&lt;Integer&gt; leftSpliterator = rightSpliterator.trySplit(); assertEquals(4_999, rightSpliterator.getExactSizeIfKnown()); assertEquals(5_000, leftSpliterator.getExactSizeIfKnown()); // Check two leftmost elements of the left spliterator: assertTrue(leftSpliterator.tryAdvance( i -&gt; assertEquals(Integer.valueOf(1), i))); assertTrue(leftSpliterator.tryAdvance( i -&gt; assertEquals(Integer.valueOf(2), i))); // Check two leftmost elements of the right splliterator: assertTrue(rightSpliterator.tryAdvance( i -&gt; assertEquals(Integer.valueOf(5_000), i))); assertTrue(rightSpliterator.tryAdvance( i -&gt; assertEquals(Integer.valueOf(5_001), i))); } @Test public void spliterator() { list.addAll(getIntegerList(6_000)); Spliterator split = list.spliterator(); assertEquals(6_000L, split.getExactSizeIfKnown()); assertEquals(6_000L, split.estimateSize()); assertTrue(split.tryAdvance((i) -&gt; assertEquals(list.get((int) i), i))); assertTrue(split.tryAdvance((i) -&gt; assertEquals(list.get((int) i), i))); assertEquals(5998, split.getExactSizeIfKnown()); // 5998 elements left / 2 = 2999 per spliterator: Spliterator leftSpliterator = split.trySplit(); assertNotNull(leftSpliterator); assertEquals(2999, split.getExactSizeIfKnown()); assertEquals(2999, leftSpliterator.getExactSizeIfKnown()); //// leftSpliterator = [1, 2999] for (int i = 2; i &lt; 3000; i++) { Integer integer = list.get(i); assertTrue( leftSpliterator.tryAdvance( (j) -&gt; assertEquals(integer, j))); } //// split = [3001, 5999] assertTrue(split.tryAdvance(i -&gt; assertEquals(2999, i))); assertTrue(split.tryAdvance(i -&gt; assertEquals(3000, i))); assertTrue(split.tryAdvance(i -&gt; assertEquals(3001, i))); while (split.getExactSizeIfKnown() &gt; 0) { split.tryAdvance(i -&gt; {}); } assertFalse(split.tryAdvance(i -&gt; {})); } @Test public void bruteforceSpliterator() { list.addAll(getIntegerList(1_000_000)); Collections.&lt;Integer&gt;shuffle(list); List&lt;Integer&gt; newList = list.parallelStream() .map(i -&gt; 2 * i) .collect(Collectors.toList()); assertEquals(newList.size(), list.size()); for (int i = 0; i &lt; list.size(); i++) { Integer integer1 = 2 * list.get(i); Integer integer2 = newList.get(i); assertEquals(integer1, integer2); } } private static final String SERIALIZATION_FILE_NAME = &quot;LinkedList.ser&quot;; @Test public void serialization() { list.add(10); list.add(13); list.add(12); try { File file = new File(SERIALIZATION_FILE_NAME); FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(list); oos.flush(); oos.close(); FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); com.github.coderodde.util.LinkedList&lt;Integer&gt; ll = (com.github.coderodde.util.LinkedList&lt;Integer&gt;) ois.readObject(); ois.close(); boolean equal = listsEqual(list, ll); assertTrue(equal); if (!file.delete()) { file.deleteOnExit(); } } catch (IOException | ClassNotFoundException ex) { fail(ex.getMessage()); } } @Test public void bruteforceSerialization() { for (int i = 0; i &lt; 20; i++) { list.addAll(getIntegerList(i)); try { File file = new File(SERIALIZATION_FILE_NAME); FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(list); oos.flush(); oos.close(); FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); com.github.coderodde.util.LinkedList&lt;Integer&gt; ll = (com.github.coderodde.util.LinkedList&lt;Integer&gt;) ois.readObject(); ois.close(); boolean equal = listsEqual(list, ll); assertTrue(equal); if (!file.delete()) { file.deleteOnExit(); } } catch (IOException | ClassNotFoundException ex) { fail(ex.getMessage()); } list.clear(); } } private static boolean listsEqual( com.github.coderodde.util.LinkedList&lt;Integer&gt; list1, java.util.List&lt;Integer&gt; list2) { if (list1.size() != list2.size()) { return false; } Iterator&lt;Integer&gt; iter1 = list1.iterator(); Iterator&lt;Integer&gt; iter2 = list2.iterator(); while (iter1.hasNext() &amp;&amp; iter2.hasNext()) { Integer int1 = iter1.next(); Integer int2 = iter2.next(); if (!int1.equals(int2)) { return false; } } if (iter1.hasNext() || iter2.hasNext()) { throw new IllegalStateException(); } return true; } private static List&lt;Integer&gt; getIntegerList() { return getIntegerList(100); } private static List&lt;Integer&gt; getIntegerList(int length) { List&lt;Integer&gt; list = new ArrayList&lt;&gt;(length); for (int i = 0; i &lt; length; i++) { list.add(i); } return list; } } </code></pre> <h2>Critique request</h2> <p>I would love to receive any comments improving my unit tests.</p>
[]
[ { "body": "<p>A few things to consider...</p>\n<h2>Naming</h2>\n<p>Naming is important, code is read a lot more than it is written and anything that makes the code easier to read helps. One element of that is consistency, which is something that your test names don't have. Some of them start with <code>test</code> and some of them don't. Some of them are quite descriptive about what's being tested <code>testAddCollectionThreeElementsToEmptyList</code>, however others aren't (<code>testAdd</code>,<code>spliterator</code>). Try to settle on a style and be consistent with the naming.</p>\n<p>Another example of naming that could be improved in <code>bruteforceSpliterator</code>:</p>\n<blockquote>\n<pre><code>Integer integer1 = 2 * list.get(i);\nInteger integer2 = newList.get(i);\nassertEquals(integer1, integer2);\n</code></pre>\n</blockquote>\n<p>Personally, I'd have just passed the values into the <code>assertEquals</code>, without creating the local variables. However, if you are going to create them, then they should be at least as descriptive as the thing they're replacing, each level of indirection adds unnecessary cognitive processing to understand the code. <code>listValueX2</code> and <code>newListValue</code> may have been better choices.</p>\n<h2>Setup</h2>\n<p>It struct me as odd that you had a <code>list.clear()</code> call in your <code>setUp</code>. I'd expect the list to be clear when it's constructed. Having it in the setup makes it seem as if the list is needs to be cleared before it can be used.</p>\n<h2>Test focus</h2>\n<p>Tests that try to do too much can lose the intention of the test in the noise. In your <code>testAdd</code> method, at the start of the test you verify that the list is empty and has a size of 0. This has nothing to do with testing <code>add</code>. Consider putting them in their own test instead.</p>\n<h2>Test explicitly as in <code>testAddCollectionAtIndex</code></h2>\n<p>Consider being more explicit when you can be. If you know the list should contain 8 items, then using <code>8</code>, rather than <code>list.size()</code> can make the test easier to mentally process.</p>\n<h2>AssertJ - containsExactly</h2>\n<p>There are a few tests that compare the contents of your list against the expected contents of the list. So, for example in <code>testAddCollectionThreeElementsToEmptyList</code> you do:</p>\n<blockquote>\n<pre><code>assertEquals(3, list.size());\n\nfor (int i = 0; i &lt; list.size(); i++) {\n assertEquals(Integer.valueOf(i + 1), list.get(i));\n}\n</code></pre>\n</blockquote>\n<p>I prefer to use <a href=\"https://assertj.github.io/doc/\" rel=\"nofollow noreferrer\">AssertJ</a> for my assertions, because I find the fluent interface easier to read. It has quite a lot of extensions that make working with collections very pleasant. Instead of the above, you can combine the size and element comparison into a single assertion that gives very descriptive feedback on failure:</p>\n<pre><code>assertThat(list).containsExactly(1,2,3);\n</code></pre>\n<h2>Files</h2>\n<p>Where you can, you want to try to avoid using the file system it tends to be a can of worms that can lead to unpredictable failures. Rather than using <code>FileOutputStream</code> and <code>FileInputStream</code> in your <code>serialization</code> test, consider using the <code>Byte</code> versions instead:</p>\n<pre><code>ByteArrayOutputStream bos = new ByteArrayOutputStream();\nObjectOutputStream oos = new ObjectOutputStream(bos);\n\n// ...\n\nByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());\nObjectInputStream ois = new ObjectInputStream(bis);\n</code></pre>\n<h2>Exceptions</h2>\n<p>You don't need to catch exceptions that you want to fail your tests, the testing framework will catch the exceptions and convert them into an appropriate message for you. So, rather than doing this:</p>\n<blockquote>\n<pre><code>} catch (IOException | ClassNotFoundException ex) {\n fail(ex.getMessage());\n}\n</code></pre>\n</blockquote>\n<p>Consider instead just declaring the the method:</p>\n<pre><code>public void serialization() throws IOException, ClassNotFoundException {\n</code></pre>\n<h2>Test coverage</h2>\n<p>I ran test coverage against your the list in your previous question. You're running at about 71% method and line coverage. You may find it useful to run a coverage tool (the community edition of Intellij has a built in one) to see if it gives you some helpful insights about sections of your code that are lacking in coverage.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T00:16:07.463", "Id": "268201", "ParentId": "266155", "Score": "4" } } ]
{ "AcceptedAnswerId": "268201", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T07:38:14.817", "Id": "266155", "Score": "0", "Tags": [ "java", "linked-list", "unit-testing" ], "Title": "Faster, indexed, heuristic doubly-linked list data structure in Java: unit tests" }
266155
<p>So I've made a button in the right-bottom corner of my HTML-page, but I was wondering since it's the first time I've made this, if there is another better way to do this, or if you guys can see anything funky about the way I did this?</p> <p>This post is mostly to learn how to do things the right way, since I'm a beginner at this.</p> <p>Thanks for your help.</p> <p><strong>Here is my code</strong> --&gt; if you want to GOTO: <a href="https://jsfiddle.net/Mungax/7m6gtuk9/" rel="nofollow noreferrer">JSfiddle</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var bottomPage = document.getElementById('bottomPage'); var topPage = document.getElementById('topPage'); var lastScrollTop = 0; bottomPage.addEventListener('click', scrollBottom); topPage.addEventListener('click', scrollTop); // element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element. window.addEventListener('scroll', function(){ // or element.addEventListener('scroll'.... var st = window.pageYOffset || document.documentElement.scrollTop; if (st &gt; lastScrollTop){ bottomPage.style.display = 'none'; topPage.style.display = ''; } else { bottomPage.style.display = ''; topPage.style.display = 'none'; } lastScrollTop = st &lt;= 0 ? 0 : st; }, false); function scrollBottom() { window.scrollTo(0,document.body.scrollHeight); bottomPage.style.display = 'none'; topPage.style.display = ''; } function scrollTop() { window.scrollTo(0, 0); topPage.style.display = 'none'; bottomPage.style.display = ''; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{ height: 3000px; background: white; background: linear-gradient(to bottom, #33ccff 0%, #ff99cc 100%); } .right-corder-container { position: fixed; right: 20px; bottom: 20px; vertical-align: middle; background: #dddddd79; text-align: center; width: 40px; height: 40px; border-radius: 100%; display: inline-flex; flex-direction: column; justify-content: center; align-items: center; font-size: 25px; color: white; font-weight: bold; text-decoration: none } .right-corder-container img { width: 40px; height: 40px; } .right-corder-container:hover { background: #85858579; cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;button class='right-corder-container' id='bottomPage' type='button'&gt;&lt;img src='https://i.postimg.cc/87f0hmm2/scroll-down.png'&gt;&lt;/button&gt; &lt;button class='right-corder-container' style='display: none;' id='topPage' type='button'&gt;&lt;img src='https://i.postimg.cc/Tp4sL4gj/scroll-up.png'&gt;&lt;/button&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h2>Some JS points</h2>\n<ul>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window\" rel=\"nofollow noreferrer\" title=\"MDN Web API's window\">window</a> is the default object. You seldom need to use it. eg <code>window.scrollTo</code> is the same as <code>scrollTo</code> as is <code>window.document</code> same as <code>document</code>.</p>\n</li>\n<li><p>You can use the element's id as a JS variable name to reference an element.</p>\n</li>\n<li><p>For variables that do not change use constants <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. var\">var</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. let\">let</a></p>\n</li>\n<li><p>Avoid setting style values directly to the elements style, rather use CSS rules and selectors to define the styles.</p>\n</li>\n<li><p>Keep your code out of the global scope by wrapping it in a IIFE (Immediately Invoked Function Expression)</p>\n</li>\n</ul>\n<h2>HTML/CSS Design</h2>\n<ul>\n<li><p>There is no need to create two buttons. Use one button to simplify your JS.</p>\n<p>Using CSS selectors to define rules for the buttons content lets you use one class name to switch between the up and down options. Add the class name for up, and remove for down.</p>\n</li>\n<li><p>There is no need for the <code>click</code> events to change the button state as the <code>scroll</code> event will fire when you call <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Window scrollTo\">Window.scrollTo</a> and that function will change the button's state/</p>\n</li>\n<li><p>You added a <code>type</code> attribute to button. This is not needed as the button is not part of a form.</p>\n</li>\n<li><p>Why did you add the <code>document.documentElement.scrollTop</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Element scrollTop\">Element.scrollTop</a> when <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Window pageYOffset\">Window.pageYOffset</a> is zero?? The two values are the same! BTW <code>pageYOffset</code> is an alias for <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Window scrollY\">Window.scrollY</a></p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite tries to keep the JS code a simple as possible.</p>\n<p>I removed much of the custom styling (images, background) which can easily be added via HTML/CSS without needing to change the JavaScript</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>;(()=&gt;{\n var lastPos = 0, scrollToPos = document.body.scrollHeight;\n\n scrollBtn.addEventListener(\"click\", () =&gt; scrollTo(0, scrollToPos));\n addEventListener(\"scroll\", () =&gt; {\n scrollToPos = scrollY &gt; lastPos ? 0 : document.body.scrollHeight;\n lastPos = Math.max(0, scrollY);\n scrollBtn.classList.toggle(\"scrollUp\", scrollToPos === 0);\n }, false);\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body { height: 3000px }\n#scrollBtn {\n position: fixed;\n right: 10px;\n bottom: 10px;\n cursor: pointer; \n}\n#scrollBtn &gt; .top { display: none } \n#scrollBtn.scrollUp &gt; .top { display: initial } \n#scrollBtn.scrollUp &gt; .bottom { display: none } </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> &lt;button id=\"scrollBtn\"&gt;\n &lt;span class=\"top\"&gt;Top&lt;/span&gt;\n &lt;span class=\"bottom\"&gt;Bottom&lt;/span&gt;\n &lt;/button&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": "2021-08-18T22:35:06.977", "Id": "266184", "ParentId": "266156", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T08:53:51.783", "Id": "266156", "Score": "1", "Tags": [ "javascript", "html", "css" ], "Title": "Best way to make a scroll top/bottom button" }
266156
<p>The <a href="https://en.wikipedia.org/wiki/Assignment_problem" rel="nofollow noreferrer">assignment problem</a> is about assigning tasks to workers, where each pair (worker, task) has a cost. The <a href="https://en.wikipedia.org/wiki/Hungarian_algorithm" rel="nofollow noreferrer">Hungarian algorithm</a> builds an optimal solution for this problem. It has two variants, depending on the representation of the cost relationships: one with bipartite graphs, and one with cost matrices. I have implemented the latter form as described <a href="https://brc2.com/the-algorithm-workshop/" rel="nofollow noreferrer">here</a> because I had trouble making Wikipedia's step 3 example into an algorithm. The goal is to produce a library that I can use in another project in which I intend to assign mentors to students based on their likelihood of getting along.</p> <p>In short, the algorithm modifies the cost matrix to make zeroes appear and selects some of them to build an optimal solution. It uses two types of marks, stars (for zeroes belonging to the candidate solution) and primes (for zeroes that could replace starred zeroes in the solution). It moves between 6 steps:</p> <ol> <li>The matrix is preprocessed (validity checks, optional rotation to have at least as many columns than rows, subtraction of the minimum value of each row to all values of the same row and then the same for columns)</li> <li>Greedily prepare a candidate solution by starring zeroes</li> <li>Check if the candidate solution is complete; if yes, return it; else, go to the next step</li> <li>Try to find a zero that could replace a starred one in the candidate solution; if one is found, go to the next step; else, go to step 6</li> <li>Follow an alternating path of primed and starred zeroes to modify the candidate solution, and go back to step 3</li> <li>Modify some values in the matrix to make more zeroes appear, and go back to step 4.</li> </ol> <p>For example, take the following cost matrix.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody> <tr> <td><strong>0</strong></td> <td>1</td> <td>2</td> <td>25</td> <td>13</td> </tr> <tr> <td><strong>1</strong></td> <td>5</td> <td>7</td> <td>25</td> <td>15</td> </tr> <tr> <td><strong>2</strong></td> <td>10</td> <td>13</td> <td>16</td> <td>13</td> </tr> <tr> <td><strong>3</strong></td> <td>17</td> <td>21</td> <td>11</td> <td>18</td> </tr> <tr> <td><strong>4</strong></td> <td>15</td> <td>15</td> <td>15</td> <td>14</td> </tr> </tbody> </table> </div> <p>The algorithm must output the following solution, with a total cost of 2 + 5 + 13 + 11 = 31 (and the last row is not assigned any task because the worker is too expensive).</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody> <tr> <td><strong>0</strong></td> <td></td> <td>X</td> <td></td> <td></td> </tr> <tr> <td><strong>1</strong></td> <td>X</td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>2</strong></td> <td></td> <td></td> <td></td> <td>X</td> </tr> <tr> <td><strong>3</strong></td> <td></td> <td></td> <td>X</td> <td></td> </tr> <tr> <td><strong>4</strong></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>My code in Java 11 works as intended on several hand-made examples and standard edge cases (null input, non-square cost matrix, worst-case matrix for this algorithm). If you find any case that is poorly handled, I would be happy to know but that is not my main concern here.</p> <p>I used junit5 to write unit tests and I feel that the test framework I wrote might be needlessly complex. I wanted to get a separate test result for each run of a test method on each of its input, and several test methods will have the same input. I wrote the TestFrameWork and TestArguments interfaces as a way to use junit5's streams of tests, and each test class must implement the TestFrameWork interface with a utility class implementing the TestArguments interface. Then, most tests only need writing a simple lambda function performing only the actual verification. I wonder if that is a good idea or a terrible one.</p> <p>Additionally, I made three methods package-private rather than private because I wanted to test them specifically, which smells fishy as well: the constructor, reduceInitialMatrix and getState (which only exist to test reduceInitialMatrix, and that seems even worse). I have a bit of trouble setting the balance between encapsulation and testing, I'll gladly take any advice on this point too.</p> <p>All the original code base can be found on <a href="https://github.com/AnabVangun/AssignmentProblem" rel="nofollow noreferrer">my github</a>. For this question, I have edited it a bit: instead of making HungarianSolver extend the abstract Solver and inherit the javadoc, I made the HungarianSolver stand-alone and put the javadoc directly in it. I built and ran the tests on the modified version to make sure that I didn't break anything.</p> <h3>HungarianSolver.java</h3> <pre><code>package AssignmentProblem; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; /** * Implementation of the HungarianAlgorithm. */ class HungarianSolver { final private int[][] costMatrix; final private int[][] assignments; final private int[] rowAssignments; final private int[] colAssignments; final private int nRows; final private int nCols; final private boolean[] coveredRows; final private boolean[] coveredCols; final private int[] starredRows; final private int[] starredCols; final private int[] primedRows; final private int[] primedCols; private int numberCoveredCols; final private boolean transposed; /** * Instantiates a new solver on the given cost matrix. The proper way to get * the solution of the assignment problem with a {@link HungarianSolver} is * to call {@link #initialise(int[][])} rather than directly the constructor. * * @param costMatrix */ HungarianSolver(int[][] costMatrix) { checkMatrixValidity(costMatrix); if (costMatrix.length &gt; costMatrix[0].length){ //flip matrix to have more columns than rows transposed = true; nRows = costMatrix[0].length; nCols = costMatrix.length; this.costMatrix = new int[nRows][nCols]; for (int i = 0; i &lt; nRows; i++) { for (int j = 0; j &lt; nCols; j++) { this.costMatrix[i][j] = costMatrix[j][i]; } } } else { this.costMatrix = costMatrix; nRows = costMatrix.length; nCols = costMatrix[0].length; transposed = false; } assignments = new int[nRows][2]; rowAssignments = new int[transposed ? nCols : nRows]; colAssignments = new int[transposed ? nRows : nCols]; coveredRows = new boolean[nRows]; coveredCols = new boolean[nCols]; starredRows = new int[nRows]; starredCols = new int[nCols]; primedRows = new int[nRows]; primedCols = new int[nCols]; Arrays.fill(starredRows, -1); Arrays.fill(starredCols, -1); Arrays.fill(primedRows, -1); Arrays.fill(primedCols, -1); Arrays.fill(rowAssignments, -1); Arrays.fill(colAssignments, -1); for (int[] assignment : assignments) { Arrays.fill(assignment, -1); } } protected static HungarianSolver initialise(int[][] costMatrix) { HungarianSolver result = new HungarianSolver(costMatrix); result.reduceInitialMatrix(); result.solveReducedMatrix(); return result; } /** * Returns the column index assigned to each row. * @return The result of the assignment problem from the row perspective. * The i-th element of the output is the index of the column assigned to the * i-th row, or -1 if the row has not been assigned. */ public int[] getRowAssignments() { return this.rowAssignments; } public int[] getColumnAssignemnts() { return this.colAssignments; } /** * Returns the pairs of row and column indices of the assignments. * @return The result of the assignment problem as pairs. Each element of * the output is an assigned pair whose first element is the index of the * row and the second element is the index of the column. Unassigned rows * and columns are not included. */ public int[][] getAssignments() { return this.assignments; } /** * Reduces the values of the matrix to make zeroes appear. This * corresponds to the first step of the Hungarian Algorithm. */ void reduceInitialMatrix() { //first part: reduce all rows for (int[] row : costMatrix) { int min = row[0]; for (int val : row) { if (val &lt; min) { min = val; } } for (int j = 0; j &lt; row.length; j++) { row[j] -= min; } } //second part: reduce all columns for (int j = 0; j &lt; nCols; j++) { int min = costMatrix[0][j]; for (int[] row : costMatrix) { if (row[j] &lt; min) { min = row[j]; } } for (int[] row : costMatrix) { row[j] -= min; } } } /** * Performs the main loop of the Hungarian algorithm. */ private void solveReducedMatrix() { //Steps 0 and 1 have been preprocessed //Step 2 : initial zero starring for (int i = 0; i &lt; nRows; i++) { for (int j = 0; j &lt; nCols; j++) { if (costMatrix[i][j] == 0 &amp;&amp; starredCols[j] == -1) { coveredCols[j] = true; numberCoveredCols++; starredRows[i] = j; starredCols[j] = i; break; } } } while (numberCoveredCols &lt; nRows) { int[] position = primeZero(); while (position == null){ //Perform step 6 //Get minimal unmarked value int min = Integer.MAX_VALUE; for (int i = 0; i &lt; nRows; i++) { if (coveredRows[i]) { continue; } for (int j = 0; j &lt; nCols; j++) { if (coveredCols[j]) { continue; } if (costMatrix[i][j] &lt; min) { min = costMatrix[i][j]; if (min == 1){ break; } } if (min == 1){ break; } } } //modify the matrix for (int i = 0; i &lt; nRows; i++) { for (int j = 0; j &lt; nCols; j++) { if (!coveredRows[i]) { /* If the row is uncovered and the column is covered, then it's a no-op: add and subtract the same value. */ if (!coveredCols[j]) { costMatrix[i][j] -= min; } } else if (coveredCols[j]) { costMatrix[i][j] += min; } } } //go back to step 4 position = primeZero(); } //perform step 5 invertPrimedAndStarred(position); } //format the result int assignmentIndex = 0; if (transposed){ for (int i = 0; i &lt; nCols; i++){ rowAssignments[i] = starredCols[i]; if (starredCols[i] != -1){ assignments[assignmentIndex][0] = starredCols[i]; assignments[assignmentIndex][1] = i; assignmentIndex++; } } System.arraycopy(starredRows, 0, colAssignments, 0, nRows); } else { for (int i = 0; i &lt; nRows; i++){ rowAssignments[i] = starredRows[i]; if (starredRows[i] != -1) { assignments[assignmentIndex][0] = i; assignments[assignmentIndex][1] = starredRows[i]; assignmentIndex++; } } System.arraycopy(starredCols, 0, colAssignments, 0, nCols); } } /** * Primes uncovered zeroes in the cost matrix. * Performs the fourth step of the Hungarian Algorithm. * @return the (rowIndex,colIndex) coordinates of the primed zero to star * that has been found, or null if no such zero has been found. */ private int[] primeZero() { Queue&lt;Integer&gt; uncoveredColumnQueue = new LinkedList&lt;&gt;(); for (int i = 0; i &lt; nRows; i++) { if (coveredRows[i]) { continue; } for (int j = 0; j &lt; nCols; j++) { if (coveredCols[j] || costMatrix[i][j] &gt; 0) { continue; } //Found a non-covered zero primedRows[i] = j; primedCols[j] = i; if (starredRows[i] == -1) { return new int[]{i,j}; } else { coveredRows[i] = true; coveredCols[starredRows[i]] = false; numberCoveredCols -= 1; //ignore the rest of the row but handle the uncovered column uncoveredColumnQueue.add(starredRows[i]); break; } } } while (!uncoveredColumnQueue.isEmpty()){ int j = uncoveredColumnQueue.remove(); for (int i = 0; i &lt; nRows; i++){ if(coveredRows[i] || costMatrix[i][j] &gt; 0) { continue; } primedRows[i] = j; primedCols[j] = i; if (starredRows[i] == -1){ return new int[]{i,j}; } else { coveredRows[i] = true; coveredCols[starredRows[i]] = false; numberCoveredCols -= 1; uncoveredColumnQueue.add(starredRows[i]); } } } return null; } /** * Stars selected primed zeroes to increase the line coverage of the matrix. * Performs the fifth step of the Hungarian Algorithm. * @param position array of size 2 containing the row and column indices of * the first primed zero in the alternating series to modify. */ private void invertPrimedAndStarred(int[] position){ int currentRow = position[0]; int currentCol = position[1]; int tmp; starredRows[currentRow] = currentCol; while (starredCols[currentCol] != -1){ //Move star to its new row in the column of the primed zero tmp = starredCols[currentCol]; starredCols[currentCol] = currentRow; currentRow = tmp; //Move star to its new column in the column of the previously //starred zero tmp = primedRows[currentRow]; starredRows[currentRow] = tmp; currentCol = tmp; } //set starredCols of last changed zero and reset primes and lines covering starredCols[currentCol] = currentRow; for (int i = 0; i &lt; coveredRows.length; i++){ coveredRows[i] = false; primedRows[i] = -1; } //in next step, all columns containing a starred zero will be marked //--&gt; do it right away for (int j = 0; j &lt; nCols; j++){ if(!coveredCols[j] &amp;&amp; starredCols[j] != -1){ numberCoveredCols++; coveredCols[j] = true; } //if a column contained a prime zero, it will still contain one //after the inversion, so the case where a column needs to be //uncovered does not arise primedCols[j] = -1; } } /** * @return The internal state of the cost matrix. */ int[][] getState() { return this.costMatrix; } /** * Checks the validity of the input cost matrix. * @param costMatrix the matrix to solve. * @throws IllegalArgumentException if {@code costMatrix } is not * rectangular (e.g. rows do not all have the same length). */ static void checkMatrixValidity(int[][] costMatrix) throws IllegalArgumentException{ if (costMatrix == null){ throw new IllegalArgumentException(&quot;input matrix was null&quot;); } if (costMatrix.length == 0){ throw new IllegalArgumentException(&quot;input matrix was of length 0&quot;); } for (int[] row : costMatrix){ if (row.length != costMatrix[0].length){ throw new IllegalArgumentException(&quot;input matrix was not rectangular&quot;); } } } } </code></pre> <h3>TestArguments.java</h3> <pre><code>package test.tools; /** * Interface defining the general contract that inner classes should implement * to ease the unit testing. * * Concrete classes implementing it should provide a unique constructor similar * to the main one of the class parameter, and override the toString object * method. * * @param &lt;T&gt; class under test: the arguments will be used to generate * instances of that class. */ public interface TestArguments&lt;T&gt; { /** * Initialises an object to use in a test. * @return */ T convert(); } </code></pre> <h3>TestFrameWork.java</h3> <pre><code>package test.tools; import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; import static org.junit.jupiter.api.DynamicTest.dynamicTest; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Stream; import org.junit.jupiter.api.DynamicNode; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.function.Executable; public interface TestFrameWork&lt;T, S extends TestArguments&lt;T&gt;&gt; { /** * @return a {@link Stream} of arguments to initialise an object to test. */ Stream&lt;S&gt; argumentsSupplier(); default String testName(String methodName, S args){ return String.format(&quot;%s.%s on %s&quot;, this.getClass().getCanonicalName(), methodName, args); } /** * Forges a {@link DynamicTest} to run the input test for each element * returned by the implementation of * {@link TestFrameWork#argumentsSupplier()}. * @param methodName to set as the test name. * @param tester to run as the test. * @return a stream of nodes running the test. */ default Stream&lt;DynamicTest&gt; test(String methodName, Consumer&lt;S&gt; tester){ return test(argumentsSupplier(), methodName, tester); } /** * Forges a {@link Stream} of {@link DynamicNode} that runs in independent * {@link DynamicTest} instances each {@link Executable} returned by the * input {@link Function} on each element returned by the implementation of * {@link TestFrameWork#argumentsSupplier()}. * @param methodName to set as the test container's name. * @param testerStream to generate the {@link Stream} of test using for * each element the {@link String} as a suffix in the test name and the * {@link Executable} as the test to run. * @return a stream of nodes running the tests. */ default Stream&lt;DynamicNode&gt; testContainer(String methodName, Function&lt;S, Stream&lt;Map.Entry&lt;String, Executable&gt;&gt;&gt; testerStream){ return testContainer(argumentsSupplier(), methodName, testerStream); } /** * Forges a {@link DynamicTest} to run the input test for each element * of a {@link Stream} of arguments. * @param stream of arguments, the tests will be run on each * element. * @param methodName to set as the test name. * @param tester to run as the test. * @return a stream of nodes running the tests. */ default Stream&lt;DynamicTest&gt; test(Stream&lt;S&gt; stream, String methodName, Consumer&lt;S&gt; tester){ return stream.map(args -&gt; dynamicTest(testName(methodName, args), () -&gt; tester.accept(args))); } /** * Forges a {@link Stream} of {@link DynamicNode} that runs in independent * {@link DynamicTest} instances each {@link Executable} returned by the * input {@link Function} on each element of the input {@link Stream}. * @param stream of arguments, the tests will be run on each * element. * @param methodName to set as the test container's name. * @param testerStream to generate the {@link Stream} of test using for * each element the {@link String} as a suffix in the test name and the * {@link Executable} as the test to run. * @return a stream of nodes running the tests. */ default Stream&lt;DynamicNode&gt; testContainer(Stream&lt;S&gt; stream, String methodName, Function&lt;S, Stream&lt;Map.Entry&lt;String, Executable&gt;&gt;&gt; testerStream){ return stream.map(args -&gt; { String message = testName(methodName, args); return dynamicContainer(message, testerStream.apply(args).map(entry -&gt; dynamicTest(message + entry.getKey(), entry.getValue()))); }); } } </code></pre> <h3>HungarianSolverTest.java</h3> <pre><code>package AssignmentProblem; import java.util.Arrays; import java.util.Comparator; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import test.tools.TestArguments; import test.tools.TestFrameWork; public class HungarianSolverTest implements TestFrameWork&lt;HungarianSolver, HungarianArgument&gt; { @TestFactory public Stream&lt;DynamicTest&gt; testInitialiseValidInput() { //Check that initialise does not crash on valid input. //Correctness of the result is checked in tests linked to the methods getting the results. return test(&quot;initialise (valid input)&quot;, v -&gt; v.convert()); } @TestFactory public Stream&lt;DynamicTest&gt; testInitialiseInvalidInput(){ Stream&lt;HungarianArgument&gt; cases = Stream.of( new HungarianArgument(null, null, null, null, &quot;null cost matrix&quot;), new HungarianArgument(new int[0][0], null, null, null, &quot;size 0 cost matrix&quot;), new HungarianArgument(new int[][]{{0}, {0,1}, {0,1,2},{0,1},{0}}, null, null, null, &quot;non-rectangular cost matrix&quot;)); return test(cases, &quot;initialise (invalid input)&quot;, v -&gt; Assertions.assertThrows(IllegalArgumentException.class, () -&gt; v.convert())); } @TestFactory public Stream&lt;DynamicTest&gt; testGetRowAssignments() { return test(&quot;getRowAssignments&quot;, v -&gt; assertArrayEquals(v.expectedRowAssignment, v.convert().getRowAssignments())); } @TestFactory public Stream&lt;DynamicTest&gt; testGetColumnAssignemnts() { return test(&quot;getColumnAssignments&quot;, v -&gt; assertArrayEquals(v.expectedColAssignment, v.convert().getColumnAssignemnts())); } @TestFactory public Stream&lt;DynamicTest&gt; testGetAssignments() { Comparator&lt;int[]&gt; comparator = (first, second) -&gt; Integer.compare(first[0], second[0]) == 0 ? Integer.compare(first[1], second[1]) : Integer.compare(first[0], second[0]); return test(&quot;getAssignments&quot;, v-&gt; { /* There is no contract on the ordering of the result values. */ int[][] assignments = v.convert().getAssignments(); Arrays.sort(assignments, comparator); Arrays.sort(v.expectedMatrixResult, comparator); assertArrayEquals(v.expectedMatrixResult, assignments); }); } @TestFactory public Stream&lt;DynamicTest&gt; testReduceInitialMatrix() { Stream&lt;HungarianArgument&gt; cases = Stream.of( new HungarianArgument(new int[][]{{25, 40, 35}, {40, 60, 35}, {20, 40, 25}}, new int[][]{{0, 0, 10}, {5, 10, 0}, {0, 5, 5}}, null, null, &quot;square 3*3 matrix&quot;), new HungarianArgument(new int[][]{{150, 400, 450},{200, 600, 350}, {200, 400, 250}}, new int[][]{{0, 50, 250}, {0, 200, 100}, {0, 0, 0}}, null, null, &quot;second square 3*3 matrix&quot;), new HungarianArgument(new int[][]{{70, 40, 20, 55},{65, 60, 45, 90},{30, 45, 50, 75},{25,0,55,40}}, new int[][]{{50, 20, 0, 0},{20, 15, 0, 10},{0, 15, 20, 10},{25, 0, 55, 5}}, null, null, &quot;square 4*4 with initial zeroes matrix&quot;), new HungarianArgument(new int[][]{{1,2,25,13},{5,7,25,15},{10,13,16,13},{17,21,11,18},{15,15,15,14}}, new int[][]{{0,2,9,16,13},{0,3,11,19,12},{14,12,5,0,3},{0,0,0,5,0}}, null, null, &quot;5*4 matrix without initial zeroes&quot;) ); return test(cases, &quot;reduceInitialMatrix&quot;, v -&gt; { HungarianSolver solver = v.convertWithConstructor(); solver.reduceInitialMatrix(); assertArrayEquals(v.expectedMatrixResult, solver.getState()); }); } @Override public Stream&lt;HungarianArgument&gt; argumentsSupplier() { int worstCaseSize = 200; int[][] worstCaseMatrix = new int[worstCaseSize][worstCaseSize]; for (int i = 0; i &lt; worstCaseMatrix.length; i++) { for (int j = 0; j &lt; worstCaseMatrix[i].length; j++){ worstCaseMatrix[i][j] = (i+1)*(j+1); } } int[] worstCaseLinearExpectation = new int[worstCaseSize]; Arrays.setAll(worstCaseLinearExpectation, i -&gt; worstCaseSize-i-1); int[][] worstCaseExpectedAssignments = new int[worstCaseSize][2]; for (int i = 0; i &lt; worstCaseSize; i++){ worstCaseExpectedAssignments[i][0] = i; worstCaseExpectedAssignments[i][1] = worstCaseSize-i-1; } return Stream.of(new HungarianArgument(new int[][]{{2500, 4000, 3500}, {4000, 6000, 3500}, {2000, 4000, 2500}}, new int[][]{{0,1},{1,2},{2,0}}, new int[]{1,2,0}, new int[]{2,0,1}, &quot;simple 3*3 matrix&quot;), new HungarianArgument(new int[][]{{2000,6000,3500},{1500, 4000, 4500},{2000,4000,2500}}, new int[][]{{0,0},{1,1},{2,2}}, new int[]{0,1,2}, new int[]{0,1,2}, &quot;mildly complex 3*3 matrix&quot;), new HungarianArgument(new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}}, new int[][]{{0,0},{1,1},{2,2}}, new int[]{0,1,2}, new int[]{0,1,2,-1}, &quot;complex 4*3 matrix with equality case&quot;), new HungarianArgument(new int[][]{{1,2,25,13},{5,7,25,15},{10,13,16,13},{17,21,11,18},{15,15,15,14}}, new int[][]{{0,1},{1,0},{2,3},{3,2}}, new int[]{1,0,3,2,-1}, new int[]{1,0,3,2}, &quot;first complex 5*4 matrix without equality case&quot;), new HungarianArgument(new int[][]{{1,2,25,13},{5,7,25,15},{10,13,16,14},{17,21,11,18},{15,15,15,13}}, new int[][]{{0,1},{1,0},{2,3},{3,2}}, new int[]{1,0,3,2,-1}, new int[]{1,0,3,2}, &quot;second complex 5*4 matrix without equality case&quot;), new HungarianArgument(worstCaseMatrix, worstCaseExpectedAssignments, worstCaseLinearExpectation, worstCaseLinearExpectation, &quot;worst case &quot; + worstCaseSize + &quot;*&quot; + worstCaseSize + &quot; matrix&quot;) ); } } class HungarianArgument implements TestArguments&lt;HungarianSolver&gt;{ final int[][] costMatrix; final int[][] expectedMatrixResult; final int[] expectedRowAssignment; final int[] expectedColAssignment; private final String name; HungarianArgument(int[][] costMatrix, int[][] expectedMatrixResult, int[] expectedRowAssignment, int[] expectedColAssignment, String name){ this.costMatrix = costMatrix; this.expectedMatrixResult = expectedMatrixResult; this.expectedRowAssignment = expectedRowAssignment; this.expectedColAssignment = expectedColAssignment; this.name = name; } @Override public HungarianSolver convert() { return HungarianSolver.initialise(costMatrix); } public HungarianSolver convertWithConstructor(){ return new HungarianSolver(costMatrix); } @Override public String toString(){ return this.name; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T19:33:14.960", "Id": "528911", "Score": "0", "body": "You still use Solver on line 35 of HungarianSolver." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T20:06:39.773", "Id": "528915", "Score": "0", "body": "Indeed, I missed that one, sorry." } ]
[ { "body": "<p>Your nose is correct. What you smell is the effect of voids that mutate the state of the class, so you need to expose the internals.</p>\n<p>First step would be to split initialization into a factory.</p>\n<pre><code>public class HungarianSolverFactory\n{\n public static HungarianSolver hungarianSolverSolve(int[][] costMatrix)\n {\n HungarianSolver result = hungarianSolver(costMatrix);\n result.reduceInitialMatrix();\n result.solveReducedMatrix();\n\n return result;\n }\n\n public static HungarianSolver hungarianSolver(int[][] costMatrix)\n {\n int[][] costMatrixFinal;\n int nRows;\n int nCols;\n boolean transposed;\n\n HungarianSolver.checkMatrixValidity(costMatrix);\n if (costMatrix.length &gt; costMatrix[0].length)\n {\n //flip matrix to have more columns than rows\n transposed = true;\n nRows = costMatrix[0].length;\n nCols = costMatrix.length;\n costMatrixFinal = new int[nRows][nCols];\n for (int i = 0; i &lt; nRows; i++)\n {\n for (int j = 0; j &lt; nCols; j++)\n {\n costMatrixFinal[i][j] = costMatrix[j][i];\n }\n }\n }\n else\n {\n costMatrixFinal = costMatrix;\n nRows = costMatrix.length;\n nCols = costMatrix[0].length;\n transposed = false;\n }\n\n int[][] assignments = init2DIntArray(nRows, 2, -1);\n int[] rowAssignments = initIntArray(transposed ? nCols : nRows, -1);\n int[] colAssignments = initIntArray(transposed ? nRows : nCols, -1);\n boolean[] coveredRows = new boolean[nRows];\n boolean[] coveredCols = new boolean[nCols];\n int[] starredRows = initIntArray(nRows, -1);\n int[] starredCols = initIntArray(nCols, -1);\n int[] primedRows = initIntArray(nRows, -1);\n int[] primedCols = initIntArray(nCols, -1);\n\n return new HungarianSolver(costMatrixFinal, assignments, rowAssignments,\n colAssignments, nRows, nCols, coveredRows, coveredCols, starredRows,\n starredCols, primedRows, primedCols, transposed\n );\n }\n\n private static int[] initIntArray(\n int length,\n int value\n )\n {\n int[] arr = new int[length];\n Arrays.fill(arr, value);\n return arr;\n }\n\n private static int[][] init2DIntArray(\n int height,\n int width,\n int value\n )\n {\n int[][] arr = new int[height][width];\n for (int[] arr1D : arr)\n {\n Arrays.fill(arr1D, value);\n }\n\n return arr;\n }\n}\n</code></pre>\n<p>The state of the solver is also huge. I would split the algorithm into three parts: HungarianAssignmentOptimizer, HungarianSolver, HungarianMatrixReducer.</p>\n<p>I will show what optimizer would look like approximately. For the other two just reuse what you have and make sure you return things out of methods.</p>\n<pre><code>class HungarianAssignmentOptimizer\n{\n private HungarianSolver hungarianSolver;\n private HungarianMatrixReducer hungarianMatrixReducer;\n\n public HungarianAssignmentOptimiser(\n HungarianSolver hungarianSolver,\n HungarianMatrixReducer hungarianMatrixReducer\n )\n {\n this.hungarianSolver = hungarianSolver;\n this.hungarianMatrixReducer = hungarianMatrixReducer;\n }\n\n// you return assignments\n public int[][] solve(int[][] costMatrix) {\n int[][] reducedCostMatrix = this.hungarianMatrixReducer.reduce(costMatrix);\n return this.hungarianSolver.solveReducedMatrix(reducedCostMatrix);\n }\n}\n</code></pre>\n<p>You can then easily test each part of the algorithm without it feeling weird being public (since it doesn't mutate the state of the object).</p>\n<p>If you feel like you would need more parameters about the matrix, you can create a new class which would hold them (role of java 16 record).</p>\n<pre><code>class CostMatrix {\n public final int[][] costMatrix;\n public final int nRows;\n public final int nCols;\n public final boolean transposed;\n\n public CostMatrix(\n int[][] costMatrix,\n int nRows,\n int nCols,\n boolean transposed\n )\n {\n this.costMatrix = costMatrix;\n this.nRows = nRows;\n this.nCols = nCols;\n this.transposed = transposed;\n }\n}\n</code></pre>\n<p>And then:</p>\n<pre><code>...\n\n public int[][] solve(CostMatrix costMatrix) {\n CostMatrix reducedCostMatrix = this.hungarianMatrixReducer.reduce(costMatrix);\n return this.hungarianSolver.solveReducedMatrix(reducedCostMatrix);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T21:46:38.443", "Id": "528978", "Score": "0", "body": "Thanks! At first sight, it looks like the HungarianMatrixReducer would be a stateless object. Is it really necessary to create an instance and store it in the Optimizer? Shouldn't it simply be a `static` method either in its own class, or in the `costMatrix` class?\nWhat is the purpose of the Optimizer class, what does it optimize?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T00:15:35.260", "Id": "528985", "Score": "0", "body": "Stateless is indeed what you want to achieve. It would be the same with the Solver class. It can be static, but this way you have the optimizer that is a bit more modular (note that Solver and Reducer should be interfaces in this case). You can swap your implementation of either one with some lib for example, without changing anything else. Optimizer is basically your algorithm (what you are doing is assignment optimization, thus optimizer) - it has two steps - reducing a matrix and solving it. The purpose of optimizer is connecting the matrix reduction and matrix solving." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T00:29:46.077", "Id": "528986", "Score": "0", "body": "What you basically want is to call solve multiple times without having to fiddle with the state of the class in between, because it makes it weird to use otherwise. Ideally you just do optimizer.solve(matrix) and get back the pairs. You can then execute solve again with different matrix and still get the correct result. You could have everything be static if you have no intention on experimenting with the parts of the algorithm. Also this way of \"injecting\" parts of the algorithm can also help you when testing, because you can mock slow parts that you do not test and make tests run faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T21:03:42.010", "Id": "529065", "Score": "0", "body": "I think I see what you mean, and I find the idea interesting. Doesn't this somewhat assume that any reducer can be used before any solver, which may not be the case? Or shouldn't the initialisation of the Optimizer somewhat make sure that the two are compatible, either by throwing an exception if that's not the case or by exposing the compatible pairs through an Enum or something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T21:17:44.440", "Id": "529066", "Score": "0", "body": "It assumes that any HungarianReducer can be used before any HungarianSolver, which might be naive because of my lack of knowledge of the domain (all I know is from your code). What I would want to achieve with this is so something like this would be possible: new Optimizer(new Reducer, new Solver).solve(mat) and then new Optimizer(new Reducer, new SolverWithSomeOptimizationToTest).solve(mat). You can solve this problem by creating a factory and ensuring that Optimizer gets the correct parameters. You can also make Optimizer package private to prevent it being initialized without a factory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T19:04:52.250", "Id": "529319", "Score": "0", "body": "Got it! This design eases comparison between different implementations of reducers or solvers while exposing only a factory method using the most efficient implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T19:17:16.510", "Id": "529320", "Score": "0", "body": "Both answers were really helpful but I chose to accept this one as it was the one most focused on the part that was bothering me, the way to expose a simple interface to the user of the library while properly testing the different steps." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T20:51:36.603", "Id": "268235", "ParentId": "266157", "Score": "3" } }, { "body": "<p>This looks very nice, with well named variables and a thought out design, good class and method names. The code is probably only readable if you study the algorithm, but that's OK.</p>\n<p>I'll make some remarks though, starting with <code>HungarianSolver</code>. I might need to post another answer to review the rest, 'cause there is a lot of code to handle.</p>\n<p>The formatting is nice, but it might do with some additional white space between various lines and e.g. <code>return new int[]{i,j};</code>.</p>\n<h2>HungarianSolver</h2>\n<p><strong>Generic remarks</strong></p>\n<p>First of all, this class should probably be made <code>final</code>. It is extremely unlikely that the algorithm itself will be altered, so having it made extendable makes little sense, especially since all the fields are private -\nand thus inaccessible for classes that extend this class - anyway. You would normally only use <code>public</code> and <code>private</code> or default / package only and <code>private</code> in this case, I suppose. Currently it is very much a hodge-podge of access modifiers, without any clear intent (except for everything marked <code>private</code>).</p>\n<p>Second, the class seems to be both <code>HungarianSolver</code> and <code>HungarianSolverResult</code> in one. That can be a (somewhat questionable) design decision, but in that case I would recommend documenting it in the JavaDoc of the class.</p>\n<p>Generally, we prefer <code>private final</code> over <code>final private</code>, it's not the recommended order.</p>\n<p>The value <code>-1</code> is used so much that it could do with a constant declaration to indicate what it means.</p>\n<p><strong>Code specific remarks</strong></p>\n<p>Remarks below the code fragments.</p>\n<pre><code> * Implementation of the HungarianAlgorithm.\n</code></pre>\n<p>Even better if you can <a href=\"https://en.wikipedia.org/wiki/Hungarian_algorithm\" rel=\"nofollow noreferrer\">link to the algorithm</a>; I don't know why HungarianAlgorithm is one word here.</p>\n<pre><code> * ... The proper way to get\n * the solution of the assignment problem with a {@link HungarianSolver} is\n * to call {@link #initialise(int[][])} rather than directly the constructor.\n</code></pre>\n<p>So mark it <code>private</code>...</p>\n<pre><code> * @param costMatrix\n</code></pre>\n<p>Undocumented parameter.</p>\n<pre><code>checkMatrixValidity(costMatrix);\n</code></pre>\n<p>You could make the <code>costMatrix</code> a separate class, so that you don't need to check the matrix in the constructor, and document the right way of constructing the instance in the class documentation instead. Note that it might be more logical to call it from the <code>initialise</code> call.</p>\n<p>This method should probably be <code>public</code>, I don't see why the getters are public while you cannot inititialise the instance at the same level.</p>\n<pre><code>protected static HungarianSolver initialise(int[][] costMatrix) {\n</code></pre>\n<p>This one is now missing the documentation, and it is the preferred way of using the function.</p>\n<pre><code>return this.rowAssignments;\n</code></pre>\n<p>A minor remark is that you sometimes use <code>this</code>, and sometimes you don't.</p>\n<p>A more grievous error is that it exposes the arrays used within the instance. Even if you'd have good reasons for that, you should at the very least document that - or return a deep copy of the array.</p>\n<pre><code>public int[] getColumnAssignemnts() {\n</code></pre>\n<p>This method is missing a JavaDoc comment, maybe it did something wrong, as it has also been misspelled :)</p>\n<pre><code>if (costMatrix[i][j] &lt; min) {\n min = costMatrix[i][j];\n if (min == 1){\n break;\n }\n}\nif (min == 1){\n break;\n}\n</code></pre>\n<p>That first <code>if</code> is spurious, the same check at the end will perform the same break; it is in the same scope of the <code>for</code> loop after all.</p>\n<h2>TestArguments</h2>\n<p>Not sure if this class is necessary.</p>\n<p>This class should be named <code>TestArgumentGenerator</code> or something similar, in itself it is not plural.</p>\n<pre><code> * @return\n</code></pre>\n<p>Undocumented <code>return</code></p>\n<pre><code> * Initialises an object to use in a test.\n</code></pre>\n<p>No, that would pre-suppose that the object exists. It <em>generates a test instance of type <code>T</code></em>, you say so right in the class description.</p>\n<h2>HungarianSolverTest</h2>\n<p>Suddenly there is a loss of whitespace. If you think that it is not worth typing it, then try an formatter, readily available in e.g. Eclipse and probably all other significant IDEs.</p>\n<p>I'm not sure why the constructor itself is not public, the rest seems to be public after all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T21:16:21.153", "Id": "528918", "Score": "0", "body": "I'm not sure if the optimization of having larger columns instead of rows is worth it, to be honest, it probably just confuses things. That kind of optimization is best made *afterwards*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T21:14:44.483", "Id": "528971", "Score": "0", "body": "Thanks for all your comments. I have a few questions to fully understand some of them.\nReading up on `clone()`, I couldn't see how it hides the arrays used internally. To properly hide them (which I should have done), wouldn't I need to deep-copy them before returning them?\nI removed the `public` modifier of the interface, and it breaks the class importing it. I found several examples of \"public interface\" on StackOverflow (e.g. https://stackoverflow.com/questions/7133497/java-public-interface-and-public-class-in-same-file), are you sure about your claim?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T21:30:23.867", "Id": "528973", "Score": "1", "body": "As for the shape of the matrix, the algorithm actually fails if the matrix has more rows than columns, since it assigns all rows. Rotating the column was the easiest way I found to circumvent this issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T21:42:33.817", "Id": "528976", "Score": "0", "body": "Yes, you should deep-copy, that was what I was trying to say, maybe I didn't notice that something was a multi-dimensional array. Note that another way that avoids having to copy is to create an immutable class with the array hiding inside and accessor methods. You are right about the `public interface`, sorry about that, it's the methods inside that are always `public` not the interface itself - and you already got that right. Both fixed now." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T21:14:35.467", "Id": "268239", "ParentId": "266157", "Score": "3" } } ]
{ "AcceptedAnswerId": "268235", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T09:08:04.777", "Id": "266157", "Score": "5", "Tags": [ "java", "unit-testing", "junit" ], "Title": "Hungarian algorithm for optimal assignment" }
266157
<p>I have created two simple classes: <code>resource</code> and <code>container</code>. below is the full code. actually container keeps resources. and in the beganing it will get all the resources and store them in datalist of resources. The other function is simply prints out all the resources in container. Please review my code and see if its ok just review it and let me know what are the wrongs and rights in the code, thanks</p> <pre><code>//// // Created by noone on 18/8/21. // #include &lt;iostream&gt; #include &lt;cstring&gt; #define Max 10 class resource{ private: public: int id; char name[10]; resource(int id,char name1[10]):id(id) { std::memcpy(name,name1,Max); } resource&amp; operator= (const resource&amp; arr2){ if (this == &amp;arr2){ return *this; } //make sure you aren't self-assigning //same as copy constructor from here id=arr2.id; std::memcpy(name,arr2.name,Max); return *this; } }; class container { public: container(resource *new_resource,int i) { size=0; size=i; datalist=(resource *)malloc(sizeof(resource)*i); for(int x=0;x&lt;i;x++) { datalist[x].id=new_resource[x].id; std::memcpy(datalist[x].name,new_resource[x].name,std::strlen(new_resource[x].name)); } } void print_all_resources() { std::cout&lt;&lt; &quot;total &quot;&lt;&lt;size&lt;&lt;&quot; resources found&quot;&lt;&lt;std::endl; for(int i=0;i&lt;size;i++) { std::cout&lt;&lt;&quot;Printintg first resource&quot;&lt;&lt;i+1&lt;&lt;std::endl; std::cout&lt;&lt;datalist[i].name &lt;&lt; &quot; | &quot;&lt;&lt; datalist[i].id&lt;&lt;std::endl; } } private: resource *datalist; int size; }; int main() { resource resource1(10,&quot;abc&quot;); resource resource2(20,&quot;xyz&quot;); resource r[]={resource2,resource1}; container c(r,2); c.print_all_resources(); } </code></pre>
[]
[ { "body": "<p>Your code is a weird mix of C and C++. It's essentially C with classes (which is to say, it's not very good C++ code).</p>\n<hr />\n<ol>\n<li><p>Use <code>constexpr</code> instead of <code>#define</code> to define constants. <code>constexpr</code> retains type information.</p>\n</li>\n<li><p>Use <code>std::string</code> instead of a char array.</p>\n</li>\n<li><p>Implement the rule of <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">0-3-5</a>. Although you have defined a copy assignment operator for <code>resource</code>, you haven't defined a copy constructor, or any move constructors/assignment operators. You also haven't defined any constructors/assignment operators for <code>container</code>.</p>\n</li>\n<li><p>Instead of manually managing memory through <code>malloc</code>, consider using <code>std::vector</code>. It does all the heavy lifting for you and is safer.</p>\n</li>\n<li><p>Even if you want to avoid <code>std::vector</code> and manage memory yourself (to learn), you should use <code>new</code> and <code>delete</code> instead of <code>malloc</code> and <code>free</code>.</p>\n</li>\n<li><p>Speaking of <code>free</code>, I don't see it. You're leaking memory since you don't deallocate memory that you allocated through <code>malloc</code>. Ideally, you'd want to create a destructor that would call <code>free</code> when the <code>container</code> object goes out of scope (gets destroyed). This is a very important concept in C++: <a href=\"https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii\">Resource Acquisition Is Initialization (RAII)</a></p>\n</li>\n<li><p>Instead of defining a method called <code>print_all_resources</code>, a more idiomatic approach would be to overload <code>operator&lt;&lt;</code>.</p>\n</li>\n<li><p>Instead of creating a temporary array and passing it to the <code>container</code> constructor, you can use initializer list to pass an arbitrary amount of <code>resource</code>s to the constructor.</p>\n<pre><code>container(std::initializer_list&lt;resource&gt; rsc)\n{\n resources.insert(resources.end(), rsc);\n}\n private:\n std::vector&lt;resource&gt; resources;\n</code></pre>\n<p>and call it like this:</p>\n<pre><code>resource r1;\nresource r2;\ncontainer c({r1, r2});\n</code></pre>\n</li>\n<li><p>Prefer to use <code>std::copy</code> over <code>memcpy</code>.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T11:56:19.557", "Id": "266161", "ParentId": "266159", "Score": "1" } }, { "body": "<p>If you used a <code>string</code>, you would not need to write the <code>operator=</code> at all. You would not need the copy constructor either, which is missing from your code.</p>\n<p>You ask</p>\n<blockquote>\n<p>can u [sic] show it my resource constructor expect two parameters if I use <code>new</code> then how to call the constructor of resource with two parameters? <code>datalist=new resource[i];</code> &lt;&lt;---error , resource constructor expects two parameter:<code>id</code>,<code>name1</code> what do u say about this?</p>\n</blockquote>\n<p><em>If</em> you needed to use <code>new</code>, you would pass the arguments like this:<br />\n<code>resource* p = new resource(name,id);</code></p>\n<p>However, I think what you really want here is just a <code>vector&lt;resource&gt;</code>. You don't need to write a <code>container</code> class that stores a dynamically allocated array and its size — there are containers ready available in the standard library.</p>\n<p>Here is my take on it:</p>\n<ul>\n<li>there is no <code>Max</code>.</li>\n</ul>\n<pre><code>struct resource {\n std::string name;\n int id;\n };\n\nstd::ostream&amp; operator&lt;&lt; (std::ostream&amp; o, const resource&amp; res); // write this.\n</code></pre>\n<p>You <em>could</em> write <code>using resource_container = std::vector&lt;resource&gt;;</code> but your code can use any kind of container freely with <code>resource</code>, and algorithms don't care which container you used, so this is not a type to be defined at all.</p>\n<p>Note that <code>resource</code> doesn't need the copy constructor, destructor, or assignment operator, since the <code>string</code> already takes care of itself properly. There is <em>no</em> special housekeeping needed: this is the <strong>rule of zero</strong>.</p>\n<p>I don't need a constructor, either. Since all the data members are public, you can just use the aggregate initializer. This is OK since this is, in fact, a simple bag of data, with no special checking that the values are in agreement or anything like that — any values for the individual fields will work.</p>\n<p>Note that with a <code>vector</code> you don't call <code>new</code> at all. You just <code>push_back</code>.</p>\n<p>I think the problem you were asking about is that making an array requires a default constructor. Your use of <code>malloc</code> avoids the issue but does not fix anything: creating a &quot;blank&quot; array of <code>n</code> resources leaves them uninitialized in your code, or default initialized in fixed code, but those array elements are not really ready to use, and you need to assign over them. With the <code>vector</code> you don't have an array of <code>n</code> items in some blank state; you <em>don't</em> have an item at all until you are ready to add it! See the difference? With a <code>vector</code>, at no time do you have extra unused elements at the end of the array; they are all valid values.</p>\n<pre><code>vector&lt;resource&gt; Ct;\nCt.push_back({&quot;name&quot;,27});\nCt.puch_back({&quot;another_with_long_name&quot;,42});\n</code></pre>\n<p>You could also create a vector all at once:</p>\n<pre><code>vector&lt;resource&gt; Container2 {\n {&quot;name&quot;,27}, {&quot;another_with_long_name&quot;,42}\n};\n</code></pre>\n<p>But if you don't plan on adding more entries afterwards, you don't even need a <code>vector</code>. A plain array will do. As you have in the original for <code>r</code>, but without re-copying the values, and even doing it all at compile-time for zero run-time overhead!</p>\n<pre><code>constexpr resource r[] {\n {&quot;name&quot;,27}, {&quot;another_with_long_name&quot;,42}\n};\n</code></pre>\n<p>Notice how this is exactly the same as for the <code>vector</code> example.</p>\n<p>You want a function ready-made for printing the entire collection?<br />\nNote that it doesn't matter what kind of container you use — this works for the plain array, and <code>vector</code>, and many others.</p>\n<pre><code>template &lt;typename R&gt;\nvoid print_all_resources (const R&amp; collection)\n{\n for (auto&amp; r : collection) {\n std::cout &lt;&lt; r.name &lt;&lt; &quot; | &quot;&lt;&lt; r.id &lt;&lt; '\\n';\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T04:49:13.423", "Id": "525820", "Score": "0", "body": "`If you needed to use new, you would pass the arguments like this:\nresource* p = new resource(name,id)` I do not want single object contained in p array. What I wanted was multiple resources to be accessed by p +i where i is index of a resource in p array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T04:51:26.413", "Id": "525821", "Score": "0", "body": "The point I am using not using string and vector so I can create my own container instead of relying on stl containers. Although I like to use the iterator from stl embedded in my container class as struct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T04:57:35.040", "Id": "525823", "Score": "0", "body": "resource* p = new resource(name,id)` I do not want single object contained in p array. What I wanted was multiple resources to be accessed by p +i where i is index of a resource in p array. Need to allocate all received resources and allocate by calling resource constructor so allocate array of sizes i.of resources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T06:37:11.660", "Id": "525831", "Score": "0", "body": "@user786 I explained this in my Answer, \"making an array requires a default constructor....\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T07:12:26.303", "Id": "525832", "Score": "0", "body": "Ok. Can u please tell can i attach my stl iterator with my container class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T07:18:30.977", "Id": "525833", "Score": "0", "body": "*Do not* write your own container class. That is a highly advanced subject and you are not fully understanding containers yet; learn to _use_ them first. There are Boost libraries that help you write iterators for your own containers. But I really can't parse the sentence \"can i [sic] attach my stl iterator with my container class [?]\" You can certainly use iterators with a plain array, `vector`, etc. of `resource`. The built-in ranged `for` loop is defined in terms of iterators, `begin` and `end`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T07:55:13.327", "Id": "525835", "Score": "0", "body": "please understand I will write my own container class so please just give me a good link or something or what help resource on internet I can use. u can guide on this if u can. I think I love 3 rule for resources in T template its so customizable. This is the only reason to ran away from .net and C# so try learning linux and C C++. so if u may just give me a starting point I will do my best" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:28:15.620", "Id": "525863", "Score": "0", "body": "If you are going to write a container class, it should be a _container_, period. That is, not specific to one type of element, but templated. The container has the responsibility for holding the multiple values, and is not specific to the type of value. You need to understand containers better before you have any hope of writing one: see https://en.cppreference.com/w/cpp/named_req/Container for an overview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:33:45.097", "Id": "525864", "Score": "0", "body": "You can also see [Boost.Container](https://www.boost.org/doc/libs/1_77_0/doc/html/container.html) for containers that are not in `std` and containers that are enhanced (relative to older standards anyway). Here you can see some valid reasons for making a container implementation: it does something that the `std` containers do not. What does your container need to do that's not satisfied by `vector`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T05:46:18.397", "Id": "525972", "Score": "0", "body": "`If you are going to write a container class, it should be a container, period. That is, not specific to one type of element, but templated. The container has the responsibility for holding the multiple values, and is not specific to the type of value` is there a repository on github for already implemented container. That can be easy to understand the link is just giving basic info while may be important I need to see it first" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T05:51:03.173", "Id": "525973", "Score": "0", "body": "How about this I think with some efforts not too much I can convert it to tor type T class data https://github.com/bkthomps/Containers/blob/master/src/vector.c" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T14:36:05.373", "Id": "526105", "Score": "0", "body": "That bkthomps code is not C++ and has nothing to do with C++ containers. You need to explicitly construct and destruct elements, and maintain un-constructed memory between the current length and the capacity." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T15:42:33.343", "Id": "266171", "ParentId": "266159", "Score": "1" } } ]
{ "AcceptedAnswerId": "266171", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T10:25:40.230", "Id": "266159", "Score": "0", "Tags": [ "c++" ], "Title": "Class using resource pointer- Resource class with copy constructor and copy assignment operator" }
266159
<p>I have written the following function which works as expected but I still see there is some room for improving its readability</p> <pre><code>def get_claims_to_search(): claims = [] database_priority = DatabasePriority.objects.first() low_priority_claims_databases = ClaimsDatabase.objects.filter( deleted=False, priority=&quot;low&quot; ) normal_priority_claims_databases = ClaimsDatabase.objects.filter( deleted=False, priority=&quot;normal&quot; ) high_priority_claims_databases = ClaimsDatabase.objects.filter( deleted=False, priority=&quot;high&quot; ) low_priority_count = database_priority.low normal_priority_count = database_priority.normal high_priority_count = database_priority.high if not low_priority_claims_databases.count(): low_priority_count = 0 if normal_priority_claims_databases.count(): normal_priority_count += int( database_priority.normal / (database_priority.normal + database_priority.high) * database_priority.low ) if high_priority_claims_databases.count(): high_priority_count += int( database_priority.high / (database_priority.normal + database_priority.high) * database_priority.low ) if not normal_priority_claims_databases.count(): normal_priority_count = 0 if low_priority_claims_databases.count(): low_priority_count += int( database_priority.low / (database_priority.low + database_priority.high) * database_priority.normal ) if high_priority_claims_databases.count(): high_priority_count += int( database_priority.high / (database_priority.low + database_priority.high) * database_priority.normal ) if not high_priority_claims_databases.count(): high_priority_count = 0 if low_priority_claims_databases.count(): low_priority_count += int( database_priority.low / (database_priority.low + database_priority.high) * database_priority.normal ) if normal_priority_claims_databases.count(): normal_priority_count += int( database_priority.normal / (database_priority.normal + database_priority.high) * database_priority.high ) priority_databases = { &quot;low&quot;: low_priority_claims_databases, &quot;normal&quot;: normal_priority_claims_databases, &quot;high&quot;: high_priority_claims_databases, } priority_count = { &quot;low&quot;: low_priority_count, &quot;normal&quot;: normal_priority_count, &quot;high&quot;: high_priority_count, } for priority in priority_count: if priority_count[priority]: priority_count[priority] = int( ( (priority_count[priority] / 100) / priority_databases[priority].count() ) * settings.DEBUNKBOT_SEARCHEABLE_CLAIMS_COUNT ) for claim_database in priority_databases[priority]: claims.append( claim_database.claims.filter(processed=False, rating=False).values( &quot;claim_first_appearance&quot; )[: priority_count[priority]] ) return claims </code></pre> <p>any suggestions on how I can improve/rewrite it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T15:17:16.473", "Id": "525767", "Score": "4", "body": "Please provide sufficient context for reviewers to understand how that code is used. 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>The function seems to be inconsistent; I don't know what is it intended to do, so if you say it works as expected, probably you can lose some functionality on unnecessary &quot;beautification&quot; of the code.</p>\n<p>What inconsistency am I talking about: the central (and the longest) part of the code transforms 6 input values, <code>*_priority_claims_databases.count()</code> and <code>database_priority.*</code> (where * is low, normal and high) into 3 output values, <code>*_priority_count</code>, using something that seems to be one formula. I'll use short names <code>dl</code> for <code>database_priority.low</code> and <code>pl</code> for <code>low_priority_count</code> etc. to make formulas more readable. So we have (omitting conditions):</p>\n<pre><code>pn += int( dn / (dn + dh) * dl )\nph += int( dh / (dn + dh) * dl )\npl += int( dl / (dl + dh) * dn )\nph += int( dh / (dl + dh) * dn )\npl += int( dl / (dl + dh) * dn ) #&lt;--!!!!!\npn += int( dn / (dn + dh) * dh )\n</code></pre>\n<p>At this point it is clear that first two lines (in <code>if low_priority_claims_databases.count() == 0:</code>) end with <code>dl</code>, second two lines - with <code>dn</code>, 6th line - with <code>dh</code>, which corresponds with condition, but 5th line stands out.\nIf we change <code>dh+dh</code> into <code>s-dl</code> (where <code>s=dh+dn+dl</code>), the problem will get even worse:</p>\n<pre><code>pn += int( dn / (s - dl) * dl )\nph += int( dh / (s - dl) * dl )\npl += int( dl / (s - dn) * dn )\nph += int( dh / (s - dn) * dn )\npl += int( dl / (s - dn) * dn ) #&lt;--!!!!!\npn += int( dn / (s - dl) * dh ) #&lt;--!!!!!\n</code></pre>\n<p>Now I see two lines are out of pattern. Sorry, can't help it here without a description.</p>\n<p>Maybe last two lines should be</p>\n<pre><code>pl += int( dl / (s - dh) * dh )\npn += int( dn / (s - dh) * dh )\n</code></pre>\n<p>i.e.</p>\n<pre><code>low_priority_count += int( \n database_priority.low \n / (database_priority.low + database_priority.normal) \n * database_priority.high )\nnormal_priority_count += int( \n database_priority.normal \n / (database_priority.low + database_priority.normal) \n * database_priority.high )\n</code></pre>\n<p>If so, fix the code first.</p>\n<p>Still we can do something with the last portion of the code. Let's create dicts with keys &quot;low&quot;, &quot;normal&quot; and &quot;high&quot; (or list and constants) instead of groups of variables; so we'll have</p>\n<pre><code>if priority_count[&quot;low&quot;]:\n priority_count[&quot;low&quot;] = (\n priority_count[&quot;low&quot;] // priority_claims_databases[&quot;low&quot;].count()\n ) * settings.DEBUNKBOT_SEARCHEABLE_CLAIMS_COUNT\n for claim_database in priority_claims_databases[&quot;low&quot;]:\n claims.append(\n claim_database.claims.filter(processed=False, rating=False).values(\n &quot;claim_first_appearance&quot;\n )[:priority_count[&quot;low&quot;]]\n</code></pre>\n<p>and two other code chunks with the only change &quot;low&quot; to &quot;normal&quot; and &quot;high&quot;. This can be changed into the loop:</p>\n<pre><code>for priority in [&quot;low&quot;,&quot;normal&quot;,&quot;high&quot;]:\n if priority_count[priority]:\n priority_count[priority] = (\n priority_count[priority] // priority_claims_databases[priority].count()\n ) * settings.DEBUNKBOT_SEARCHEABLE_CLAIMS_COUNT\n for claim_database in priority_claims_databases[priority]:\n claims.append(\n claim_database.claims.filter(processed=False, rating=False).values(\n &quot;claim_first_appearance&quot;\n )[:priority_count[priority]]\n</code></pre>\n<p>This is at least as readable as your code but almost 3 times shorter.</p>\n<p>One more question: what happens if all *_priority_claims_databases.count() are greater then zero? Is it intended that the code return empty list?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T01:08:52.267", "Id": "525812", "Score": "0", "body": "Thanks for this. \nFor some more details, the function is supposed to build a list of `claims` based on different priorities. I have 3 database types (low, normal and high) and every level has a specific percentage e.g low might be 15%, normal 35% e.t.c. Incase we don't have a database with low priority, we want to re distribute the 15% to both Normal and High i.e Normal will now be 35+ (35/(35+50)*15) where 50 is the %age of the High priority.\nIf all counts are greater than 0 then all *if *_priority_count:* will be true and thus not an empty list will be returned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T05:23:31.497", "Id": "525824", "Score": "0", "body": "First, we make `*_priority_count = 0`. Next, there are three `if`s for each `*_priority_claims_databases.count() == 0`. If all three will be `False`, `*_priority_count` will stay 0 and next three `if`s on *_priority_count would not execute and `claims` will be empty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T05:25:33.723", "Id": "525825", "Score": "0", "body": "The case we don't have a database with low priority, i.e. `low_priority_claims_databases.count() == 0`, is the first two formulas. Why 5th and 6th are different? Also add this into the description." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T07:40:26.723", "Id": "525834", "Score": "0", "body": "I've updated the code to include some of your suggestions and it's looking good so far." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T15:26:34.390", "Id": "266169", "ParentId": "266162", "Score": "5" } } ]
{ "AcceptedAnswerId": "266169", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T12:19:45.867", "Id": "266162", "Score": "6", "Tags": [ "python", "django" ], "Title": "Get list of claims based on priorities" }
266162
<p>I recently posted a bunch of code of my to-do list application and after getting some very helpful and good suggestions on how to improve, I took a shot at it! Here's a link to the former post I made -&gt; <a href="https://codereview.stackexchange.com/questions/266001/a-to-do-list-application-written-with-java">A to-do list application written with Java</a></p> <p>I have now used the one and the same instance of storage in each of the classes that need it, instead of creating new instances for each class. Namely, the Login-class and the UI-class. I've also created two interfaces and defined methods to deal with the Storage-class. Also I adjusted some of the Storage-classes methods and added new ones, in order to hide the details of the storage-operations from the Login and UI-classes.</p> <p>I think I nailed it with the dependency injection by passing that one instance of Storage on the constructors of Login and UI-classes. In the StorageInstance-class, I have a method which returns that instance of a storage. Is this the correct way to go about the dependency injection? Namely, that I use the method returnStorage() to do storage-related actions?</p> <p>As for the interfaces, I wanted to hide the details of what happens in the Storage-class so the UI and Login wouldn't have any idea what is going on under the surface, except that something is happening that relates to the storage-class. Is this the correct way to go about it? Any and all improvements and help are welcome!</p> <p>I will not post the whole application code in here, only the classes I've changed. The whole project can be viewed from the link above.</p> <pre class="lang-java prettyprint-override"><code>public class Storage { private HashMap&lt;String, ToDoList&gt; toDoLists; private HashMap&lt;String, User&gt; map; private File UsernamesAndPasswords; private File UsersToDoLists; private User user; Storage() { this.UsernamesAndPasswords = new File(&quot;UsernamesAndPasswords.ser&quot;); this.UsersToDoLists = new File(&quot;ToDoLists.ser&quot;); loadUserNamesAndPasswords(UsernamesAndPasswords); loadUsersToDoLists(UsersToDoLists); } public void saveUsersToDoLists() { try { FileOutputStream fosTwo = new FileOutputStream(UsersToDoLists); ObjectOutputStream oosTwo = new ObjectOutputStream(fosTwo); oosTwo.writeObject(this.toDoLists); oosTwo.flush(); oosTwo.close(); fosTwo.close(); } catch (IOException e) { System.out.println(&quot;Exception happened. saveUsersList&quot;); } } public void loadUsersToDoLists(File file) { if (file.length() == 0) { toDoLists = new HashMap&lt;&gt;(); this.saveUsersToDoLists(); } try { FileInputStream fisTwo = new FileInputStream(UsersToDoLists); ObjectInputStream oisTwo = new ObjectInputStream(fisTwo); toDoLists = (HashMap&lt;String, ToDoList&gt;) oisTwo.readObject(); oisTwo.close(); fisTwo.close(); } catch (Exception e) { System.out.println(&quot;Exception happened. loadUsersList&quot;); } } public void saveUserNamesAndPasswords(HashMap&lt;String, User&gt; loginInfo) { try { FileOutputStream fos = new FileOutputStream(UsernamesAndPasswords); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(this.map); oos.flush(); oos.close(); fos.close(); } catch (IOException e) { System.out.println(&quot;Exception happened. saveUsernames&quot;); } } public void loadUserNamesAndPasswords(File file) { //If the file is empty then this method creates a new empty hashmap and saves it //in the file if (file.length() == 0) { map = new HashMap&lt;&gt;(); this.saveUserNamesAndPasswords(map); } try { FileInputStream fis = new FileInputStream(UsernamesAndPasswords); ObjectInputStream ois = new ObjectInputStream(fis); map = (HashMap&lt;String, User&gt;) ois.readObject(); ois.close(); fis.close(); } catch (Exception e) { System.out.println(&quot;Exception happened. loadUserNames&quot;); } } public HashMap&lt;String, User&gt; getUserNamesAndPasswords() { return this.map; } public File getUsernamesAndPasswordsFile() { return this.UsernamesAndPasswords; } public HashMap&lt;String, ToDoList&gt; getToDoLists() { return this.toDoLists; } public File getUsersToDoListsFile() { return this.UsersToDoLists; } public void createUser(String userName, String firstName, String lastName, String password) { this.user = new User(firstName, lastName, password); this.getUserNamesAndPasswords().putIfAbsent(userName, user); this.saveUserNamesAndPasswords(this.getUserNamesAndPasswords()); this.getToDoLists().putIfAbsent(userName, this.user.getUsersToDoList()); this.saveUsersToDoLists(); } public void validateUsername(String username, String password) { if (this.getUserNamesAndPasswords().get(username).passwordEquals(password)) { this.user = getUserNamesAndPasswords().get(username); this.user.setList(this.getToDoLists().get(username)); } } public User returnUser() { return this.user; } } public class UI implements InterfaceUI { private final Scanner reader; private final Storage storage; private Login login; private User user; public UI(StorageInstance si) { this.reader = new Scanner(System.in); this.storage = si.getStorage(); this.login = new Login(si); } public void start() { System.out.println(&quot;Login or register&quot;); String fromUser = reader.nextLine().trim(); if (fromUser.equalsIgnoreCase(&quot;register&quot;)) { System.out.print(&quot;Your username:&quot;); String userName = reader.nextLine(); System.out.print(&quot;Your first name:&quot;); String firstName = reader.nextLine(); System.out.print(&quot;Your last name:&quot;); String lastName = reader.nextLine(); System.out.print(&quot;Your password:&quot;); String password = reader.nextLine(); createUser(userName, firstName, lastName, password); } login.logIn(); this.user = login.returnUser(); this.user.getUsersToDoList().printToDoList(); while (true) { System.out.println(&quot;&quot;); System.out.println(&quot;1: Add a to-do item.&quot;); System.out.println(&quot;2. Remove a to-do item.&quot;); System.out.println(&quot;3. Print a list of my to-do items.&quot;); System.out.println(&quot;4. Quit and save&quot;); System.out.print(&quot;Type the number of desired action: &quot;); String input = reader.nextLine(); if (input.equals(&quot;4&quot;)) { saveUsersList(); System.out.println(&quot;Quitting!&quot;); break; } else if (input.equals(&quot;1&quot;)) { System.out.println(&quot;What would you like to add?&quot;); String add = reader.nextLine(); toDo item = new toDo(add); this.user.getUsersToDoList().addToDo(item); } else if (input.equals(&quot;2&quot;)) { if (this.user.getUsersToDoList().getList().isEmpty()) { System.out.println(&quot;List is empty.&quot;); continue; } System.out.println(&quot;&quot;); this.user.getUsersToDoList().printToDoList(); System.out.print(&quot;Type the index of the item you wish to remove: &quot;); int remove = Integer.parseInt(reader.nextLine()); this.user.getUsersToDoList().removeToDo(remove); } else if (input.equals(&quot;3&quot;)) { System.out.println(&quot;&quot;); this.user.getUsersToDoList().printToDoList(); } } } public void createUser(String userName, String firstName, String lastName, String password) { storage.createUser(userName, firstName, lastName, password); } public void saveUsersList() { storage.getToDoLists().put(login.returnUsername(), this.user.getUsersToDoList()); storage.saveUsersToDoLists(); } } public class Login implements LoginInterface { private User user; private final Storage storage; private Scanner reader; private String username; public Login(StorageInstance si) { this.storage = si.getStorage(); this.reader = new Scanner(System.in); } public void logIn() { System.out.println(&quot;Username:&quot;); this.username = reader.nextLine(); System.out.println(&quot;Password:&quot;); String password = reader.nextLine(); try { validateUser(this.username, password); System.out.println(&quot;Welcome &quot; + user.getFirstName() + &quot;!&quot;); } catch (NullPointerException npe) { System.out.println(&quot;Incorrect username or password. Please try again!&quot;); this.logIn(); } } public User returnUser() { return this.user; } public String returnUsername() { return this.username; } public void validateUser(String username, String password) { storage.validateUsername(username, password); this.user = storage.returnUser(); } } public class StorageInstance { private Storage storage; public StorageInstance() { this.storage = new Storage(); } public Storage getStorage() { return this.storage; } } public interface InterfaceUI { public void createUser(String userName, String firstName, String lastName, String password); public void saveUsersList(); } public interface LoginInterface { public void validateUser(String username, String password); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T14:10:46.177", "Id": "526103", "Score": "0", "body": "Do you have all of these classes inside one file or did you copy everything into the same code block?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T08:36:57.663", "Id": "526495", "Score": "0", "body": "No they're all in the same project folder, but as separate classes. I just copied it into one block for simplicity's sake." } ]
[ { "body": "<p>You improved the program by a lot but then misunderstood some of @TorbenPutkonen's suggestions. As it turns out, the program runs just as fine when you change all <code>StorageInstance</code>s to <code>Storage</code> and remove the interfaces you added.</p>\n<h3>The Storage instance</h3>\n<p>Let's get the <code>StorageInstance</code> out of the way first. Consider a line like this</p>\n<pre><code>Storage store = new Storage();\n</code></pre>\n<p>What happens is that you use the constructor of the <code>Storage</code> class to create a new object, and that object is instance of that class: <em><code>store</code> is an instance of <code>Storage</code></em>.<br />\nThe procedure would then be to create a <code>Storage</code> object at program start and pass that to the constructors of <code>Login</code> and <code>UI</code>, like so:</p>\n<pre><code> // in main()\nStorage s = new Storage();\nnew UI(s).start();\n</code></pre>\n<pre><code>// in the UI class\nprivate final Storage storage;\nprivate Login login;\n\npublic UI(Storage s) {\n this.storage = s;\n this.login = new Login(s);\n}\n</code></pre>\n<pre><code>// in the Login class\nprivate final Storage storage;\n\npublic Login(Storage s) {\n this.storage = s;\n}\n</code></pre>\n<p>This also ensures that every party involved gets the same <code>Storage</code> object/instance. Read <a href=\"https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value\">this question</a> and it should be clear why.</p>\n<h2>The interfaces</h2>\n<p>Using an interface for one class only isn't any different from adding the methods that would be in that interface as public methods to that class. They're only useful if added to multiple different classes. This way the implementing class tells the world: &quot;I promise that I can do everything that this interface defines&quot;. For a common example, look up the <code>Comparable</code> interface.</p>\n<p>Honestly, I'm not sure if you really need to do anything with interfaces or DI here. If you don't plan on adding more features to the whole program, I'd say leave it be because <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>. Keep it short and simple.</p>\n<h2>Other things to note</h2>\n<ul>\n<li>No need to use getters/setters inside the class that implements them. You can directly access the field inside that class.</li>\n<li>The load methods in storage save an empty <code>HashMap</code> to the file and then read that file if that file didn't exist i.e. on the first start. Instead, you could just create an empty <code>HashMap</code> as you do and <code>return</code> right away.</li>\n<li>Classes always start with a capital letter. <code>toDo</code> doesn't.</li>\n<li>Normal class members always start with a non-capital letter. <code>UsersToDoLists</code> and <code>UsernamesAndPasswords</code> don't.</li>\n<li><code>Storage.map</code> should be renamed to something like <code>Storage.allUsers</code>.</li>\n<li><code>fisTwo, oosTwo, fosTwo, oisTwo</code> are suffixed with &quot;Two&quot; for no reason. If there was a reason they should be given better names, but here you can just remove the &quot;-Two&quot; from the name</li>\n<li><code>Storage.saveUserNamesAndPasswords()</code> has an unused argument.</li>\n<li><code>Integer.parseInt()</code> throws an exception when no number is inputted. This should be caught (main UI, option 2).</li>\n<li><code>Login.logIn()</code> uses recursion. A malicious user might spam the interface with garbage, causing the program to crash because it runs out of stack space. It's better to use an infinite loop instead, then you can just <code>break</code> out or <code>return</code> on success</li>\n<li><code>User.passwordEquals()</code> returns a <code>Boolean</code> object when it could also return the <code>boolean</code> primitive. Doesn't make a difference here but there's also no gain in using the object version.</li>\n</ul>\n<p>One last note on the design: It seems odd to me that the <code>Storage</code> also keeps track of the currently logged in user. Make a copy or a branch if you use git and try moving that functionality into the <code>UI</code> or somewhere else, so that the <code>Storage</code>'s only purpose is to load and save your database.</p>\n<h4>EDIT: The Hash map</h4>\n<p>In <code>loadUserNamesAndPasswords</code> (as example, same in <code>loadUserToDoLists</code>) you do this:</p>\n<pre><code> public void loadUserNamesAndPasswords(File file) {\n if (file.length() == 0) {\n map = new HashMap&lt;&gt;();\n this.saveUserNamesAndPasswords(map);\n }\n try {\n FileInputStream fis = new FileInputStream(UsernamesAndPasswords);\n // ...\n } catch (Exception e) {\n // ...\n }\n }\n</code></pre>\n<p>What you're doing is checking if the database file exists and if it doesn't, you create an empty <code>HashMap</code> &quot;map&quot; and save that. The file is always empty in that case, so why bother creating the <code>InputStreams</code> and reading the empty file? Just put a <code>return</code> at the end of the <code>if</code> block. Something that's up for choice IMO is not even saving at that point, i.e. removing the call to <code>saveUserNamesAndPasswords()</code>. There's no data to be saved and you'll save to the file on program exit anyways. The rest of the program only cares about <code>map</code> being non-null. In the end, the method looks something like this:</p>\n<pre><code> public void loadUserNamesAndPasswords(File file) {\n if (file.length() == 0) {\n map = new HashMap&lt;&gt;();\n this.saveUserNamesAndPasswords(map); // optional\n return; // this is what I meant\n }\n try {\n FileInputStream fis = new FileInputStream(UsernamesAndPasswords);\n // ...\n } catch (Exception e) {\n // ...\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T19:39:53.503", "Id": "526474", "Score": "0", "body": "I didn't quite understand what you meant by creating an empty hash map as \"I do\" and \"return\" right away. Could you elaborate a little bit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T21:40:38.860", "Id": "526481", "Score": "1", "body": "See edit for clarification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T08:35:39.007", "Id": "526494", "Score": "0", "body": "Thanks! I didn't realise \"return\" can be used in that way, so I didn't quite get what you meant!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T09:42:05.047", "Id": "266351", "ParentId": "266165", "Score": "2" } }, { "body": "<h3>Prefer interfaces to implementations</h3>\n<blockquote>\n<pre><code> private HashMap&lt;String, ToDoList&gt; toDoLists;\n private HashMap&lt;String, User&gt; map;\n</code></pre>\n</blockquote>\n<p>You should almost never use an implementation as the type. So these should be</p>\n<pre><code> private Map&lt;String, ToDoList&gt; toDoLists;\n private Map&lt;String, User&gt; map;\n</code></pre>\n<p>Then if you change the implementation, you only have to change at initialization. Also, this way, you don't accidentally use a <code>HashMap</code> specific method where one of the <code>Map</code> methods would do.</p>\n<blockquote>\n<pre><code> public void saveUserNamesAndPasswords(HashMap&lt;String, User&gt; loginInfo) {\n</code></pre>\n</blockquote>\n<p>Same feedback.</p>\n<pre><code> public void saveUserNamesAndPasswords(Map&lt;String, User&gt; loginInfo) {\n</code></pre>\n<p>Even more important here, as there's no need to limit this to only accept <code>HashMap</code>. It will work with any <code>Map</code> if declared this way.</p>\n<p>It is good to get in the habit of using the interface as the type. There may be times to break that habit, but I see no reason to do so here.</p>\n<h3><code>try</code>-with-resources</h3>\n<blockquote>\n<pre><code> try {\n FileOutputStream fosTwo = new FileOutputStream(UsersToDoLists);\n ObjectOutputStream oosTwo = new ObjectOutputStream(fosTwo);\n\n oosTwo.writeObject(this.toDoLists);\n oosTwo.flush();\n oosTwo.close();\n fosTwo.close();\n</code></pre>\n</blockquote>\n<p>This could be better written</p>\n<pre><code> try (\n FileOutputStream fosTwo = new FileOutputStream(UsersToDoLists);\n ObjectOutputStream oosTwo = new ObjectOutputStream(fosTwo)) {\n\n oosTwo.writeObject(this.toDoLists);\n oosTwo.flush();\n</code></pre>\n<p>You should not manually manage resources such that an exception will prevent the resource from being closed. You could move the <code>close</code> lines into a <code>finally</code> block, but the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\"><code>try</code>-with-resources</a> form will handle that for you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T22:10:00.097", "Id": "266490", "ParentId": "266165", "Score": "1" } } ]
{ "AcceptedAnswerId": "266351", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T13:09:40.157", "Id": "266165", "Score": "1", "Tags": [ "java", "beginner", "object-oriented", "design-patterns" ], "Title": "Java dependency injection and hiding details of methods in \"Database\"-class" }
266165
<p><a href="https://pchemguy.github.io/SQLiteDB-VBA-Library/" rel="nofollow noreferrer">SQLiteDB VBA Library</a> is a set of VBA helper functions for the SQLite engine. The primary motivation behind this project is to provide convenient access to extended introspection features. Because of its generality, ADODB/ADOX libraries provide only limited metadata information. The <em>Introspection</em> subpackage of this library relies on the generic SQL querying mechanism and specialized SQL queries. It facilitates access to complete information about both the features of the active engine used and objects/attributes of the attached database. The library uses the ADODB package and relies on the Christian Werner's <a href="http://www.ch-werner.de/sqliteodbc/" rel="nofollow noreferrer">SQLiteODBC</a> driver (I use a custom compiled binary that embeds a recent version of SQLite, as described <a href="https://pchemguy.github.io/SQLite-ICU-MinGW/odbc" rel="nofollow noreferrer">here</a>).</p> <p><strong>Class diagram</strong> <img src="https://raw.githubusercontent.com/pchemguy/SQLiteDB-VBA-Library/develop/Assets/Diagrams/Class%20Diagram.jpg" alt="FigClassDiagram" /></p> <p>Note, this post only covers the core functionality. Further documentation is available on <a href="https://pchemguy.github.io/SQLiteDB-VBA-Library/" rel="nofollow noreferrer">GitHub</a>, and complete source code, tests, and examples are available from the <a href="https://github.com/pchemguy/SQLiteDB-VBA-Library" rel="nofollow noreferrer">project repository</a>.</p> <p>The three classes at the top of the diagram form the <em>Introspection</em> subpackage responsible for metadata-related SQL code, with <em>SQLiteSQLDbInfo</em> being the top-level object. It implements a portion of the functionality, proxies functionality provided by <em>SQLiteSQLDbIdxFK</em>, and encapsulates <em>SQLiteSQLEngineInfo</em>.</p> <hr /> <h3>SQLiteSQLDbInfo</h3> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;SQLiteDB.Introspection&quot; '@ModuleDescription &quot;SQL queries for retrieving SQLite database metadata.&quot; '@PredeclaredId '@Exposed '@IgnoreModule ProcedureNotUsed Option Explicit Private Type TSQLiteSQLDbInfo Schema As String Engine As SQLiteSQLEngineInfo End Type Private this As TSQLiteSQLDbInfo Private Sub Class_Initialize() this.Schema = &quot;main&quot; Set this.Engine = SQLiteSQLEngineInfo End Sub Private Sub Class_Terminate() Set this.Engine = Nothing End Sub '''' @ClassMethodStrict '''' This method should only be used on the default instance '''' '@DefaultMember '@Description &quot;Default factory&quot; Public Function Create(Optional ByVal Schema As String = &quot;main&quot;) As SQLiteSQLDbInfo Dim Instance As SQLiteSQLDbInfo Set Instance = New SQLiteSQLDbInfo Instance.Init Schema Set Create = Instance End Function Public Sub Init(ByVal Schema As String) this.Schema = Schema End Sub '@Description &quot;Exposes SQLiteSQLEngineInfo introspection queries&quot; Public Property Get Engine() As SQLiteSQLEngineInfo Set Engine = this.Engine End Property '@Description &quot;Generates a query returning the list of attached databases&quot; Public Property Get Databases() As String Databases = &quot;SELECT name, file FROM pragma_database_list&quot; End Property '''' @Proxy '@Description &quot;Generates a query returning all non-system database objects.&quot; Public Function GetDbSchema(Optional ByVal Schema As String = vbNullString) As String GetDbSchema = SQLiteSQLDbIdxFK.DbSchema(IIf(Len(Schema) &gt; 0, Schema, this.Schema)) End Function '''' @Proxy '@Description &quot;Generates a query returning all non-system database objects, but triggers&quot; Public Function DbSchemaNoTriggers(Optional ByVal Schema As String = vbNullString) As String DbSchemaNoTriggers = SQLiteSQLDbIdxFK.DbSchemaNoTriggers(IIf(Len(Schema) &gt; 0, Schema, this.Schema)) End Function '''' @Proxy '@Description &quot;Generates a query returning triggers&quot; Public Function Triggers(Optional ByVal Schema As String = vbNullString) As String Triggers = SQLiteSQLDbIdxFK.Triggers(IIf(Len(Schema) &gt; 0, Schema, this.Schema)) End Function '''' For some reason, running SELECT * FROM &lt;schema&gt;.pragma_integrity_check '''' with several attached databases gives the result as if &lt;schema&gt; is '''' ignored and all attached databases are checked. Prefer to run this '''' check when the only attached database is the one being checked. '@Description &quot;Generates a query running integrity check.&quot; Public Property Get CheckIntegrity() As String CheckIntegrity = &quot;SELECT * FROM pragma_integrity_check&quot; End Property '''' For some reason, running SELECT * FROM &lt;schema&gt;.pragma_foreign_key_check '''' with several attached databases gives the result as if &lt;schema&gt; is '''' ignored and all attached databases are checked. Prefer to run this '''' check when the only attached database is the one being checked. '@Description &quot;Generates a query running integrity check.&quot; Public Property Get CheckFKs() As String CheckFKs = &quot;SELECT * FROM pragma_foreign_key_check&quot; End Property '''' @Proxy '@Description &quot;Generates a query returning database tables.&quot; Public Function Tables(Optional ByVal Schema As String = vbNullString) As String Tables = SQLiteSQLDbIdxFK.Tables(IIf(Len(Schema) &gt; 0, Schema, this.Schema)) End Function '''' @Proxy '@Description &quot;Generates a query returning all foreing keys in the SQLite database&quot; Public Property Get ForeingKeys() As String ForeingKeys = SQLiteSQLDbIdxFK.ForeingKeys(this.Schema) End Property '''' @Proxy '@Description &quot;Generates a query returning all indices in the SQLite database&quot; Public Function Indices(Optional ByVal NonSys As Boolean = True) As String Indices = SQLiteSQLDbIdxFK.Indices(this.Schema, NonSys) End Function '''' @Proxy '''' See the called class for details '@Description &quot;Generates a query returning child columns for all foreing keys and corresponding indices.&quot; Public Property Get FKChildIndices() As String FKChildIndices = SQLiteSQLDbIdxFK.FKChildIndices(this.Schema) End Property '''' @Proxy '''' See the called class for details '@Description &quot;Generates a query returning similar indices.&quot; Public Property Get SimilarIndices() As String SimilarIndices = SQLiteSQLDbIdxFK.SimilarIndices(this.Schema) End Property '@Description &quot;Generates a query returning table's columns.&quot; Public Function TableColumns(ByVal TableName As String) As String Guard.EmptyString TableName TableColumns = &quot;SELECT * &quot; &amp; _ &quot;FROM &quot; &amp; this.Schema &amp; &quot;.pragma_table_xinfo('&quot; &amp; TableName &amp; &quot;')&quot; End Function '@Description &quot;Generates a query returning table's columns with placeholder columns.&quot; Public Function TableColumnsEx(ByVal TableName As String) As String Guard.EmptyString TableName TableColumnsEx = &quot;SELECT * , 0 AS [unique], '' as [check], '' as [collate] &quot; &amp; _ &quot;FROM &quot; &amp; this.Schema &amp; &quot;.pragma_table_info('&quot; &amp; TableName &amp; &quot;')&quot; End Function '@Description &quot;Generates a query returning table's SQL.&quot; Public Function TableSQL(ByVal TableName As String) As String Guard.EmptyString TableName TableSQL = &quot;SELECT sql &quot; &amp; _ &quot;FROM sqlite_master &quot; &amp; _ &quot;WHERE type = 'table' AND name = '&quot; &amp; TableName &amp; &quot;'&quot; End Function '@Description &quot;Generates a query returning table's foreign keys.&quot; Public Function TableForeingKeys(ByVal TableName As String) As String TableForeingKeys = &quot;SELECT * &quot; &amp; _ &quot;FROM &quot; &amp; this.Schema &amp; &quot;.pragma_foreign_key_list('&quot; &amp; TableName &amp; &quot;')&quot; End Function </code></pre> <hr /> <h3>SQLiteSQLDbIdxFK</h3> <p>Bulky code related to database indices and foreign keys goes into a separate module.</p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;SQLiteDB.Introspection&quot; '@ModuleDescription &quot;SQL queries for retrieving detailed information on database indices and foreign keys.&quot; '@PredeclaredId '''' '''' Logically, this module is a part of SQLiteSQLDbInfo, and this FK/IDX code is '''' placed in a separate module simply to isolate the large amount of SQL code. '''' All methods of this module are exposed by SQLiteSQLDbInfo via composition. '''' This class is not supposed to be used directly, and it does not need to be '''' instantiated: all functionality can be used via the default instance. '''' Option Explicit '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite query returning database tables, skipping '''' system tables (prefixed with &quot;sqlite_&quot;) and ordering by ROWID '''' (in order of creation). If requested, a CTE WITH term is '''' generated. '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' CTEWITH (boolean, optional, False): '''' If True, format as a CTE WITH term '''' '''' Returns: '''' String, containing the query '''' '''' Examples: '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.Tables '''' SELECT name, sql '''' FROM main.sqlite_master '''' WHERE type = 'table' AND (name NOT LIKE 'sqlite_%') '''' ORDER BY ROWID ASC '''' '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.Tables(, True) '''' t AS ( '''' SELECT name, sql '''' FROM main.sqlite_master '''' WHERE type = 'table' AND (name NOT LIKE 'sqlite_%') '''' ORDER BY ROWID ASC '''' ) '''' '@Description &quot;Generates a query returning database tables.&quot; Public Function Tables(Optional ByVal Schema As String = &quot;main&quot;, _ Optional ByVal CTEWITH As Boolean = False) As String Dim Indent As String Dim Query As String Indent = IIf(CTEWITH, &quot; &quot;, vbNullString) Query = Indent &amp; Join(Array( _ &quot;SELECT tbl_name, sql&quot;, _ &quot;FROM &quot; &amp; Schema &amp; &quot;.sqlite_master&quot;, _ &quot;WHERE type = 'table' AND (name NOT LIKE 'sqlite_%')&quot;, _ &quot;ORDER BY ROWID ASC&quot; _ ), vbNewLine &amp; Indent) Tables = IIf(CTEWITH, &quot;t AS (&quot; &amp; vbNewLine &amp; Query &amp; vbNewLine &amp; &quot;)&quot;, Query) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite query returning database views ordered by ROWID '''' (in order of creation). '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' '''' Returns: '''' String, containing the query '''' '''' Examples: '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.Views '''' SELECT tbl_name, sql '''' FROM main.sqlite_master '''' WHERE type = 'view' '''' ORDER BY ROWID ASC '''' '@Description &quot;Generates a query returning database views.&quot; Public Function Views(Optional ByVal Schema As String = &quot;main&quot;) As String Views = Join(Array( _ &quot;SELECT tbl_name, sql&quot;, _ &quot;FROM &quot; &amp; Schema &amp; &quot;.sqlite_master&quot;, _ &quot;WHERE type = 'view'&quot;, _ &quot;ORDER BY ROWID ASC&quot; _ ), vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite query returning database triggers ordered by ROWID '''' (in order of creation). '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' '''' Returns: '''' String, containing the query '''' '''' Examples: '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.Triggers '''' SELECT tbl_name, sql '''' FROM main.sqlite_master '''' WHERE type = 'trigger' '''' ORDER BY ROWID ASC '''' '@Description &quot;Generates a query returning database triggers.&quot; Public Function Triggers(Optional ByVal Schema As String = &quot;main&quot;) As String Triggers = Join(Array( _ &quot;SELECT tbl_name, sql&quot;, _ &quot;FROM &quot; &amp; Schema &amp; &quot;.sqlite_master&quot;, _ &quot;WHERE type = 'trigger'&quot;, _ &quot;ORDER BY ROWID ASC&quot; _ ), vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite query returning all non-system database objects '''' ordered by type (tables, indices, views, triggers) and then by ROWID. '''' The query returns two columns (sql, type_id). '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' '''' Returns: '''' String, containing the query '''' '''' Examples: '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.DbSchema '''' SELECT sql, (CASE type '''' WHEN 'table' THEN 0 '''' WHEN 'index' THEN 1 '''' WHEN 'view' THEN 3 '''' ELSE 4 '''' END) AS type_id '''' FROM main.sqlite_master '''' WHERE name NOT like 'sqlite_%' '''' ORDER BY type_id, _ROWID_ '''' '@Description &quot;Generates a query returning all non-system database objects.&quot; Public Function DbSchema(Optional ByVal Schema As String = &quot;main&quot;) As String DbSchema = Join(Array( _ &quot;SELECT sql, (CASE type&quot;, _ &quot; WHEN 'table' THEN 0&quot;, _ &quot; WHEN 'index' THEN 1&quot;, _ &quot; WHEN 'view' THEN 2&quot;, _ &quot; ELSE 3&quot;, _ &quot; END) AS type_id&quot;, _ &quot;FROM &quot; &amp; Schema &amp; &quot;.sqlite_master&quot;, _ &quot;WHERE name NOT like 'sqlite_%'&quot;, _ &quot;ORDER BY type_id, _ROWID_&quot; _ ), vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite query returning all non-system database objects, '''' except for triggers, ordered by type (tables, indices, views) and '''' then by ROWID. The query returns two columns (sql, type_id). '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' '''' Returns: '''' String, containing the query '''' '''' Examples: '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.DbSchemaNoTriggers '''' SELECT sql, (CASE type '''' WHEN 'table' THEN 0 '''' WHEN 'index' THEN 1 '''' ELSE 2 '''' END) AS type_id '''' FROM main.sqlite_master '''' WHERE (name NOT like 'sqlite_%') AND type &lt;&gt; 'trigger' '''' ORDER BY type_id, _ROWID_ '''' '@Description &quot;Generates a query returning all non-system database objects.&quot; Public Function DbSchemaNoTriggers(Optional ByVal Schema As String = &quot;main&quot;) As String DbSchemaNoTriggers = Join(Array( _ &quot;SELECT sql, (CASE type&quot;, _ &quot; WHEN 'table' THEN 0&quot;, _ &quot; WHEN 'index' THEN 1&quot;, _ &quot; ELSE 2&quot;, _ &quot; END) AS type_id&quot;, _ &quot;FROM &quot; &amp; Schema &amp; &quot;.sqlite_master&quot;, _ &quot;WHERE (name NOT like 'sqlite_%') AND type &lt;&gt; 'trigger'&quot;, _ &quot;ORDER BY type_id, _ROWID_&quot; _ ), vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite query returning base info on database indices ordering '''' by ROWID (in order of creation). If requested, a CTE WITH term is generated. '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' CTEWITH (boolean, optional, False): '''' If True, format as a CTE WITH term '''' '''' Returns: '''' String, containing the query '''' '''' Examples: '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.IndexBase '''' SELECT ROWID AS id, name AS idx_name, tbl_name, sql '''' FROM main.sqlite_master '''' WHERE type='index' '''' ORDER BY ROWID ASC '''' '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.IndexBase(, True) '''' ib AS ( '''' SELECT ROWID AS id, name AS idx_name, tbl_name, sql '''' FROM main.sqlite_master '''' WHERE type='index' '''' ORDER BY ROWID ASC '''' ) '''' '@Description &quot;Generates a query returning indices (base info).&quot; Public Function IndexBase(Optional ByVal Schema As String = &quot;main&quot;, _ Optional ByVal CTEWITH As Boolean = False) As String Dim Indent As String Dim Query As String Indent = IIf(CTEWITH, &quot; &quot;, vbNullString) Query = Indent &amp; Join(Array( _ &quot;SELECT ROWID AS id, name AS idx_name, tbl_name, sql&quot;, _ &quot;FROM &quot; &amp; Schema &amp; &quot;.sqlite_master&quot;, _ &quot;WHERE type = 'index'&quot;, _ &quot;ORDER BY ROWID ASC&quot; _ ), vbNewLine &amp; Indent) IndexBase = IIf(CTEWITH, &quot;ib AS (&quot; &amp; vbNewLine &amp; Query &amp; vbNewLine &amp; &quot;)&quot;, Query) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite CTE WITH term for a foreign key list. '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' '''' Returns: '''' String, containing the CTE WITH term '''' '''' Examples: '''' &gt;&gt;&gt; ?SQLiteSQLDbIdxFK.pForeignKeyList '''' fkl AS ( '''' SELECT tbl_name AS child_table, [from] AS child_col0, '''' [table] AS parent_table, [to] AS parent_col0, '''' on_update, on_delete, id AS fk_id, seq AS fk_seq '''' FROM t '''' Join main.pragma_foreign_key_list(t.tbl_name) '''' ORDER BY child_table, fk_id '''' ) '''' '@Description &quot;Generates a query returning a foreign key CTE WITH term.&quot; Public Function pForeignKeyList(Optional ByVal Schema As String = &quot;main&quot;) As String pForeignKeyList = Join(Array( _ &quot;fkl AS (&quot;, _ &quot; SELECT tbl_name AS child_table, [from] AS child_col0,&quot;, _ &quot; [table] AS parent_table, [to] AS parent_col0,&quot;, _ &quot; on_update, on_delete, id AS fk_id, seq AS fk_seq&quot;, _ &quot; FROM t&quot;, _ &quot; JOIN &quot; &amp; Schema &amp; &quot;.pragma_foreign_key_list(t.tbl_name)&quot;, _ &quot; ORDER BY child_table, fk_id&quot;, _ &quot;),&quot;, _ &quot;fk AS (&quot;, _ &quot; SELECT *, group_concat(child_col0, ', ') AS child_cols,&quot;, _ &quot; group_concat(parent_col0, ', ') AS parent_cols,&quot;, _ &quot; min(fk_seq) AS min_fk_seq&quot;, _ &quot; FROM fkl&quot;, _ &quot; GROUP BY child_table, fk_id&quot;, _ &quot; ORDER BY child_table, fk_id&quot;, _ &quot;)&quot; _ ), vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite CTE WITH term for index info &amp; list. '''' For each index list info and join the tables. Only use &lt;index name&gt; here. '''' For multi-column indices, keep the row with the first column and generates '''' a column list. Generate database-wide list of additional index info columns '''' from the per-table index lists. '''' '''' Args: '''' Schema (string, optional, &quot;main&quot;): '''' Schema name/alias '''' '''' Returns: '''' String, containing the CTE WITH term '''' '@Description &quot;Generates a query returning a CTE WITH term for index info &amp; list.&quot; Public Function pIndexInfoList(Optional ByVal Schema As String = &quot;main&quot;) As String pIndexInfoList = Join(Array( _ &quot;ii AS (&quot;, _ &quot; SELECT ib.idx_name, min(ii.seqno) AS seqno, ii.name AS col0_name, group_concat(ii.name, ', ') AS columns&quot;, _ &quot; FROM ib&quot;, _ &quot; JOIN &quot; &amp; Schema &amp; &quot;.pragma_index_info(ib.idx_name) AS ii&quot;, _ &quot; GROUP BY idx_name&quot;, _ &quot;),&quot;, _ &quot;il AS (&quot;, _ &quot; SELECT name AS idx_name, seq AS idx_seq, [unique], origin, partial&quot;, _ &quot; FROM t&quot;, _ &quot; JOIN &quot; &amp; Schema &amp; &quot;.pragma_index_list(tbl_name)&quot;, _ &quot;)&quot; _ ), vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '@Description &quot;Generates a query returning all foreing keys in the SQLite database&quot; Public Function ForeingKeys(Optional ByVal Schema As String = &quot;main&quot;) As String Dim StmtParts(0 To 5) As String StmtParts(0) = &quot;WITH&quot; '''' List all db tables StmtParts(1) = Tables(Schema, True) &amp; &quot;,&quot; '''' For each table, list foreign keys and join them to get a list of all foreign '''' keys for the DB. Each row contains info on a foreign key for a single column. '''' Yield a single row per foreign key, including multi-column keys. For multi-column '''' keys, keep the row with the first column and generates a column list. StmtParts(2) = pForeignKeyList(Schema) StmtParts(3) = &quot;SELECT *&quot; StmtParts(4) = &quot;FROM fk AS foreign_keys&quot; StmtParts(5) = &quot;ORDER BY child_table, fk_id&quot; ForeingKeys = Join(StmtParts, vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Generates an SQLite query returning database indices, ordering by ROWID. '''' If &quot;NonSys&quot; = True, skip auto indices (prefixed with &quot;sqlite_autoindex_&quot;). '''' '@Description &quot;Generates a query returning all indices in the SQLite database&quot; Public Function Indices(Optional ByVal Schema As String = &quot;main&quot;, _ Optional ByVal NonSys As Boolean = True) As String Dim StmtParts(10 To 26) As String StmtParts(10) = &quot;WITH&quot; '''' List all db tables StmtParts(11) = Tables(Schema, True) &amp; &quot;,&quot; '''' List all db indices StmtParts(12) = IndexBase(Schema, True) &amp; &quot;,&quot; '''' For each index list info and join the tables. Only use &lt;index name&gt; here. For '''' multi-column indices, keep the row with the first column and generates a column list. '''' Generate database-wide list of additional index info columns from the per-table index lists StmtParts(13) = pIndexInfoList(Schema) &amp; &quot;,&quot; '''' After taking care of multi-row descriptions, add aditional columns from index list StmtParts(14) = &quot;idx AS (&quot; StmtParts(15) = &quot; SELECT ib.id, ib.idx_name, ib.tbl_name, ii.col0_name, ii.columns, ib.sql&quot; StmtParts(16) = &quot; FROM ib, ii&quot; StmtParts(17) = &quot; ON ib.idx_name = ii.idx_name&quot; StmtParts(18) = &quot;),&quot; '''' Join additional info columns with index-wise list StmtParts(19) = &quot;iex AS (&quot; StmtParts(20) = &quot; SELECT idx.*, il.idx_seq, il.[unique], il.origin, il.partial&quot; StmtParts(21) = &quot; FROM idx, il&quot; StmtParts(22) = &quot; WHERE idx.idx_name = il.idx_name&quot; StmtParts(23) = &quot;)&quot; StmtParts(24) = &quot;SELECT *&quot; StmtParts(25) = &quot;FROM iex AS indices&quot; StmtParts(26) = IIf(NonSys, _ &quot;WHERE idx_name NOT LIKE 'sqlite_autoindex_%'&quot; &amp; vbNewLine, vbNullString) &amp; _ &quot;ORDER BY id&quot; Indices = Join(StmtParts, vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' Indices on child columns of foreing key relations are not mandatory, '''' but generally should be defined. Database engine does not control whether '''' such indices are defined. This query return a summary table showing all '''' child columns and corresponding indices in the &quot;idx_name&quot; column. If this '''' field is empty for a particular child column, the corresponding index has '''' not been defined. '''' '@Description &quot;Generates a query returning child columns for all foreing keys and corresponding indices.&quot; Public Function FKChildIndices(Optional ByVal Schema As String = &quot;main&quot;) As String Dim StmtParts(10 To 34) As String StmtParts(10) = &quot;WITH&quot; StmtParts(11) = Tables(Schema, True) &amp; &quot;,&quot; StmtParts(12) = IndexBase(Schema, True) &amp; &quot;,&quot; StmtParts(13) = pIndexInfoList(Schema) &amp; &quot;,&quot; StmtParts(14) = &quot;idx AS (&quot; StmtParts(15) = &quot; SELECT ib.id, ib.idx_name, ib.tbl_name, ii.col0_name, ii.columns, ib.sql&quot; StmtParts(16) = &quot; FROM ib, ii&quot; StmtParts(17) = &quot; ON ib.idx_name = ii.idx_name&quot; StmtParts(18) = &quot;),&quot; StmtParts(19) = &quot;iex AS (&quot; StmtParts(20) = &quot; SELECT idx.*, il.idx_seq, il.[unique], il.origin, il.partial&quot; StmtParts(21) = &quot; FROM idx, il&quot; StmtParts(22) = &quot; WHERE idx.idx_name = il.idx_name AND partial = 0&quot; StmtParts(23) = &quot;),&quot; StmtParts(24) = pForeignKeyList(Schema) &amp; &quot;,&quot; '''' Join indices and foreign keys tables to see which child columns do not have indices. '''' Multi-column indices, having the child column set as the &quot;prefix&quot; are accepted. StmtParts(25) = &quot;fki AS (&quot; StmtParts(26) = &quot; SELECT fk.child_table, fk.child_cols, fk.parent_table, fk.parent_cols,&quot; StmtParts(27) = &quot; iex.idx_name&quot; StmtParts(28) = &quot; FROM fk&quot; StmtParts(29) = &quot; LEFT JOIN iex&quot; StmtParts(30) = &quot; ON fk.child_table = iex.tbl_name AND fk.child_cols = substr(iex.columns, 1, length(fk.child_cols))&quot; StmtParts(31) = &quot;)&quot; StmtParts(32) = &quot;SELECT *&quot; StmtParts(33) = &quot;FROM fki AS fkeys_childindices&quot; StmtParts(34) = &quot;ORDER BY child_table, child_cols&quot; FKChildIndices = Join(StmtParts, vbNewLine) End Function '''' @ClassMethod '''' This method can also be used on the default instance '''' '''' If IDX1 indexes columns (A, B) and IDX2 indexes columns (A, B, C), that is '''' IDX1 indexes a &quot;prefix&quot; of IDX2, IDX2 can replace IDX1. On the other hand, '''' depending on statistics (if for any given pair (A, B), there are very few '''' rows), IDX2 may not be justifiable (unless it is the primary key). This '''' query aims to return all such similar (&quot;prefix&quot;) indices, though it has not '''' been thoughroughly verified. It may return some &quot;false&quot; positive. Whether '''' it can miss indices is not clear. '''' '@Description &quot;Generates a query returning similar indices.&quot; Public Function SimilarIndices(Optional ByVal Schema As String = &quot;main&quot;) As String Dim StmtParts(10 To 39) As String StmtParts(10) = &quot;WITH&quot; StmtParts(11) = Tables(Schema, True) &amp; &quot;,&quot; StmtParts(12) = IndexBase(Schema, True) &amp; &quot;,&quot; StmtParts(13) = pIndexInfoList(Schema) &amp; &quot;,&quot; StmtParts(14) = &quot;idx AS (&quot; StmtParts(15) = &quot; SELECT ib.id, ib.idx_name, ib.tbl_name, ii.col0_name, ii.columns&quot; StmtParts(16) = &quot; FROM ib, ii&quot; StmtParts(17) = &quot; ON ib.idx_name = ii.idx_name&quot; StmtParts(18) = &quot;),&quot; StmtParts(19) = &quot;iex AS (&quot; StmtParts(20) = &quot; SELECT idx.*, il.idx_seq, il.[unique], il.origin, il.partial&quot; StmtParts(21) = &quot; FROM idx, il&quot; StmtParts(22) = &quot; WHERE idx.idx_name = il.idx_name&quot; StmtParts(23) = &quot;),&quot; StmtParts(24) = &quot;fdup AS (&quot; StmtParts(25) = &quot; SELECT tbl_name, col0_name, count(*) AS group_size&quot; StmtParts(26) = &quot; FROM iex&quot; StmtParts(27) = &quot; WHERE partial = 0&quot; StmtParts(28) = &quot; GROUP BY tbl_name, col0_name&quot; StmtParts(29) = &quot; HAVING group_size &gt; 1&quot; StmtParts(30) = &quot;),&quot; StmtParts(31) = &quot;idup AS (&quot; StmtParts(32) = &quot; SELECT iex.*, fdup.group_size&quot; StmtParts(33) = &quot; FROM iex&quot; StmtParts(34) = &quot; JOIN fdup&quot; StmtParts(35) = &quot; ON iex.tbl_name = fdup.tbl_name AND iex.col0_name = fdup.col0_name&quot; StmtParts(36) = &quot;)&quot; StmtParts(37) = &quot;SELECT *&quot; StmtParts(38) = &quot;FROM idup AS similar_indices&quot; StmtParts(39) = &quot;ORDER BY tbl_name, col0_name, columns&quot; SimilarIndices = Join(StmtParts, vbNewLine) End Function </code></pre> <hr /> <h3>SQLiteSQLEngineInfo</h3> <p>Engine-related code goes in this module.</p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;SQLiteDB.Introspection&quot; '@ModuleDescription &quot;SQL queries for retrieving information about the engine configuration and available features.&quot; '@PredeclaredId '@Exposed '@IgnoreModule ProcedureNotUsed '''' All methods in this module are class methods and can be safely called on the default instance '''' @ClassModule Option Explicit '@Description &quot;Generates query returning available SQLite collations&quot; Public Property Get Collations() As String Collations = &quot;SELECT * FROM pragma_collation_list AS collations ORDER BY name&quot; End Property '@Description &quot;Generates query returning compile options&quot; Public Property Get CompileOptions() As String CompileOptions = &quot;SELECT * FROM pragma_compile_options AS compile_options&quot; End Property '@Description &quot;Generates query returning available SQLite functions&quot; Public Property Get Functions() As String Functions = &quot;SELECT * FROM pragma_function_list AS functions ORDER BY name&quot; End Property '@Description &quot;Generates query returning available SQLite modules&quot; Public Property Get Modules() As String Modules = &quot;SELECT * FROM pragma_module_list AS modules ORDER BY name&quot; End Property '@Description &quot;Generates query returning available SQLite pragmas&quot; Public Property Get Pragmas() As String Pragmas = &quot;SELECT * FROM pragma_pragma_list AS pargmas ORDER BY name&quot; End Property '@Description &quot;Generates query returning SQLite version&quot; Public Property Get Version() As String Version = &quot;SELECT sqlite_version() AS version&quot; End Property </code></pre> <hr /> <h3>ADOlib.RecordsetToQT</h3> <p>This routine outputs record data from an <em>ADODB.Recordset</em> onto an Excel worksheet via the QueryTable feature. The <em>ADODB.Recordset</em> object is directly provided to the QueryTable constructor keeping the code compact and the process efficient.</p> <pre class="lang-vb prettyprint-override"><code>'@Description &quot;Outputs Recordset to Excel Worksheet via QueryTable&quot; Public Sub RecordsetToQT(ByVal AdoRecordset As ADODB.Recordset, ByVal OutputRange As Excel.Range) Attribute RecordsetToQT.VB_Description = &quot;Outputs Recordset to Excel Worksheet via QueryTable&quot; Guard.NullReference AdoRecordset Guard.NullReference OutputRange Dim QTs As Excel.QueryTables Set QTs = OutputRange.Worksheet.QueryTables '''' Cleans up target area before binding the data. '''' Provided range reference used to indicate the left column and '''' Recordset.Fields.Count determines the width. '''' If EntireColumn.Delete method is used, Range object becomes invalid, so '''' a textual address must be saved to reset the Range reference. '''' However, when multiple QTs are bound to the same worksheet, '''' EntireColumn.Delete shifts columns to the left, so the target range '''' may not be clear. EntireColumn.Clear clears the contents. Dim FieldsCount As Long FieldsCount = AdoRecordset.Fields.Count Dim QTRangeAddress As String QTRangeAddress = OutputRange.Address(External:=True) Dim QTRange As Excel.Range '@Ignore ImplicitActiveSheetReference Set QTRange = Range(QTRangeAddress) QTRange.Resize(1, FieldsCount).EntireColumn.Clear '@Ignore ImplicitActiveSheetReference Set QTRange = Range(QTRangeAddress) Dim WSQueryTable As Excel.QueryTable For Each WSQueryTable In QTs WSQueryTable.Delete Next WSQueryTable Dim NamedRange As Excel.Name For Each NamedRange In QTRange.Worksheet.Names NamedRange.Delete Next NamedRange Set WSQueryTable = QTs.Add(Connection:=AdoRecordset, Destination:=QTRange.Range(&quot;A1&quot;)) With WSQueryTable .FieldNames = True .RowNumbers = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SaveData = False .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = True .EnableEditing = True End With WSQueryTable.Refresh QTRange.Worksheet.UsedRange.Rows(1).HorizontalAlignment = xlCenter End Sub </code></pre>
[]
[ { "body": "<p>Micro-review:</p>\n<pre><code>'@IgnoreModule ProcedureNotUsed\n</code></pre>\n<p>I used to sprinkle this around too, however there are a few reasons not to use it:</p>\n<ol>\n<li>It indicates your integration tests - if held in the same project files - do not hit this code path, which should be fixed or ignored case-by-case IMO.</li>\n<li>The (relatively) new <code>'@EntryPoint</code> annotation is usually a better indication about a public API.</li>\n<li><code>'@IgnoreModule</code> means if you refactor, then different routines may be targeted by this annotation to the ones you had originally intended - that's fine if the module is truly dedicated to just public API and the annotation will always be valid. But sometimes you are ignoring procedures which might not be just API methods.</li>\n</ol>\n<p>For example, in <code>SQLiteSQLDbInfo</code>:</p>\n<blockquote>\n<pre><code>Public Sub Init(ByVal Schema As String)\n this.Schema = Schema\nEnd Sub\n</code></pre>\n</blockquote>\n<p>That could be <code>Friend Sub</code> because it's not public API, and it is <em>vitally</em> important that you do not forget to call this method if you refactor the <code>Create</code> method and accidentally drop the call to <code>Init</code>. ProcedureNotUsed can help with that without having to implement a factory interface.</p>\n<hr />\n<p>Also RD lets you define an ignore reason for each <code>'@Ignore[Module]</code> annotation using a colon:</p>\n<blockquote>\n<pre><code>Dim QTRange As Excel.Range\n'@Ignore ImplicitActiveSheetReference\nSet QTRange = Range(QTRangeAddress)\n</code></pre>\n</blockquote>\n<p>... could be:</p>\n<pre><code>Dim QTRange As Excel.Range\n'@Ignore ImplicitActiveSheetReference: QTRangeAddress is a fully qualified external range\nSet QTRange = Range(QTRangeAddress)\n</code></pre>\n<p>... that said, if this code made its way into <code>SheetX</code>, then <code>Range</code> implicitly refers to <code>SheetX.Range</code> which fails if QTRange is in <code>SheetY</code>, so better be on the safe side and use the fully qualified <code>Application.Range</code></p>\n<p>So for a workbook with 2 sheets Sheet1 and Sheet2, the following code:</p>\n<pre><code>Sub t()\n Debug.Print Range(&quot;[Book1]Sheet1!$A$1&quot;).Address(external:=True)\nEnd Sub\n</code></pre>\n<p>... fails in Sheet2 since it references Sheet1, but:</p>\n<pre><code>Sub t()\n Debug.Print Application.Range(&quot;[Book1]Sheet1!$A$1&quot;).Address(external:=True)\nEnd Sub\n</code></pre>\n<p>... prints &quot;[Book1]Sheet1!$A$1&quot; as expected</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:06:25.010", "Id": "525780", "Score": "0", "body": "I would go a step further and say that `Init` should be converted to a property called `Schema` with the getter scoped as `Public` and setter scoped as `Friend` like so \n\n\n`Public Property Get Schema() As String\n Schema = this.Schema \nEnd Property`\n`Friend Property Let Schema(ByVal value As String ) \n this.Schema = value\nEnd Property`\n\nalong with some `Gaurd.NullReference` statements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T18:22:03.477", "Id": "525792", "Score": "0", "body": "@rickmanalexander actually, I follow the pattern used by RD examples, where the default factory is called *Create*. But I extended it with a parametrized constructor called *Init*. For this reason, I prefer to keep it as a *Sub*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T18:47:54.233", "Id": "525796", "Score": "0", "body": "@Greedo I generally agree that bare *Range* should be avoided. However, please note that I do not use code-behind. This code is in a regular module. In the project repo, there is a workbook *SQLiteDBVBALibrary.xls*. If you run `SQLiteIntropectionExample.Engine`, you should get SQLite engine info placed on the worksheet \"EngineInfo\". And it does not matter which worksheet is active. For that matter, it does not matter, which workbook is active. The information is placed on \"EngineInfo\". I just verified this behavior in Excel 2002 and Excel 2016." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T19:44:21.113", "Id": "525798", "Score": "0", "body": "@PChemGuy Yeah, I didn't mean to suggest there is a bug, it's more a concern if you refactor later on and put the sheet writing code inside a sheet somewhere, but in your situation that's ofc highly unlikely since you implicitly derive the dest sheet from the Range passed in, not a code-behind. My point was more about _\"if RD suggests something and you ignore it, make sure to justify that and leave a comment to remind yourself of the justification later on\"_. I didn't know about the :comments till recently and I see you don't use them in other repos so I thought it might be useful to highlight" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T19:54:16.517", "Id": "525800", "Score": "0", "body": "@Greedo I just learned about :comments from your answer. I like this feature and will try to start using it.\nActually, I should definitely use the *Friend* qualifier more often.\n\nI often make class members *Public* just so that I could unit-test them. I think, the *Friend* qualifier would be more appropriate in such a case." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T16:56:08.097", "Id": "266174", "ParentId": "266166", "Score": "2" } } ]
{ "AcceptedAnswerId": "266174", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T14:03:53.053", "Id": "266166", "Score": "3", "Tags": [ "sql", "vba", "excel", "database", "sqlite" ], "Title": "VBA introspection library for SQLite" }
266166
<p>I'm attempting to integrate with a rather dated API (for work so I can't disclose actual naming, endpoints, etc), and their data models for POST endpoints, very clearly implement an interface that looks similar to:</p> <pre><code>public interface IExternalData { int CallerId { get; set; } string CallerName { get; set; } } </code></pre> <p>When I say they <em>very clearly</em> implement an interface, I can make this assumption based on the fact that <em>all</em> of their data models contain roughly 5 properties that are exactly the same. With that being said, none of the endpoints return data, so all of the models are simply the data expected to be sent to their respective endpoints.</p> <p>Now, I <em>could</em> create an interface to implement that, but, I don't think that it's necessary in this particular case. Instead, what I'm thinking about doing is introducing a packet model that represents the interface, plus a generic property to represent the individual models, <em>and</em> an additional property that translates the structured data back to a flat model, respective to endpoints:</p> <pre><code>public sealed class ApiPacket&lt;T&gt; { public int CallerId { get; set; } public string CallerName { get; set; } public T Data { get; set; } public Dictionary&lt;string, object&gt; KeyValuePairs { get { var dictionary = new Dictionary&lt;string, object&gt; { { &quot;CallerId&quot;, CallerId }, { &quot;CallerName&quot;, CallerName} }; string serializedData = JsonConvert.SerializeObject(Data); var data = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, object&gt;&gt;(serializedData); foreach (string key in data.Keys) dictionary.Add(key, data[key]); return dictionary; } } } </code></pre> <p>The only thing this really saves me from however is having to implement the same ~5 properties across all of the data models (there are about 40 of them that I need to create). So, while it's redundant, it's not really hurting anything to create the interface and refrain from introducing complexity.</p> <hr /> <p>Does my structured implementation raise any concerns over utilizing an interface, given that the use-case is for posting data only, not receiving it?</p> <ul> <li>My educated guess is yes due to unnecessary complexity, and that I should go the interface route, but I'd like some community feedback before I make a hard decision to go either way.</li> </ul> <h4>Q&amp;A from Comments</h4> <p>@iSR5 asked:</p> <blockquote> <p>in basic terms, you need to unify the POST endpoints data models with one model instead of having multiple different models ? if so, why? what advantages and disadvantages that you get doing so ?</p> </blockquote> <p>I wouldn't say that I need to unify them entirely, but I think I understand your point. The advantages, in my mind, are that it's easier to maintain the unified model, expansion is simplified, and most of all, I don't have to copy and paste across 40 models. The biggest disadvantage I can think of is with regards to a new endpoint being added. If myself or someone else comes back to create the new model, will it be known that the structured model exists? If not, then it could potentially duplicate keys in the JSON, but it should explode at runtime in that case.</p> <hr /> <p><em><strong>Note</strong>: To clarify, these models don't exist in my code yet and that's why I'm here.</em></p>
[]
[ { "body": "<p><strong>UPDATE</strong></p>\n<p>Thank you for adding more clarifications. Since you're working with a web service. There are some questions that I've asked myself with your solution.</p>\n<p>If the Web API provider updated their endpoints with new keys, do you need to add them to the current solution as well ? if yes, then what purpose the dictionary serves here ? what you will do on each update ?</p>\n<p>The current solution seems to handle the response (or request body), what happens after that? do you have such handler to handle the generated data elsewhere ? if yes, does this handler scoped to this class or is it used also for different objects ?</p>\n<p>Current solution definitely better than handling 40 different models, however, these questions you should think of them as a way to increase the stability of your chosen solution to know how much time and efforts you need to stabilize this solution.</p>\n<p>Here are some things that I need to mention (just a heads up):</p>\n<ul>\n<li>using <code>object</code> would add more boxing and unboxing, so you'll always need to cast the values to their respective types.</li>\n<li>using <code>JsonConvert</code> will always add <code>Json.NET</code> as a requirement to this solution.</li>\n</ul>\n<p>Lastly, I suggest you change the name of the class to include the provider name and the purpose of this class (e.g. <code>ServiceProviderNameResponseResult</code> ). This would give more clarity to the code, so from its name anyone would know it's related to that provider, and what it handles.</p>\n<hr />\n<p><strong>Old Response</strong></p>\n<p>While your approach is more maintainable, flexible, and also would reduce the code complexity, it would also add more time and efforts to the project itself as code refactoring always has hidden fees!</p>\n<p>When trying to apply a new design change on a tested, and released code, you are actually adding more developing, testing, and maintaining to the new design, and introducing new bugs as well.</p>\n<p>So, it's not only the case that if someone works on it would know about this change or not!\nIt's about the cost of time, efforts, and management as well.</p>\n<p>What I think, and what I would do if I was in your shoes: if refactoring is necessary, I would try to avoid adding new classes, and use what <code>.NET</code> offers - like using the <code>IHttpActionResult</code> or <code>HttpResponseMessage</code> classes instead. This would be easier to maintain, and easy to grasp!</p>\n<p>If there is too much work to do, then <code>DelegatingHandler</code> might be the solution. It's a useful handler, as it intercepts each request/response and delegates them to another handler. So, you can create a handler to handle all requests/responses without changing any controller.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T19:22:05.117", "Id": "525797", "Score": "0", "body": "So I think there *might* be a misunderstanding. I'm not refactoring an existing system (though I can see how you arrived at that conclusion), I'm creating the data models for our system to integrate with an existing system, so the models on our side don't exist yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:17:14.830", "Id": "525803", "Score": "0", "body": "@Tacoタコス so you're working with a web service ? something like `Google API` or similar services ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:29:47.533", "Id": "525804", "Score": "0", "body": "Precisely, and the company that owns it still adds to it while remaining consistent with their current conventions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T19:50:31.680", "Id": "525889", "Score": "0", "body": "@Tacoタコス thank you for this clarification. I updated my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T18:58:10.463", "Id": "266177", "ParentId": "266168", "Score": "3" } } ]
{ "AcceptedAnswerId": "266177", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T15:26:12.967", "Id": "266168", "Score": "1", "Tags": [ "c#" ], "Title": "Adding structure to a flattened data model instead of using an interface?" }
266168
<p>What I'm trying to do is quite simple: my table has pagination. So if I have 12 items to show and my max items per page is 10, I will have 2 pages, one with 10 records and another with just 2. I created a code that works just fine, but it seems rather dirty. What is the best way to have the same outcome as the code below, but with fewer lines and cleaner? I'm looking for less nesting, fewer variables, whatever makes it simpler.</p> <p>Note: props.content contains all items;</p> <pre><code>let pagesContainer = []; let page = []; let i = 0; for (const content of props.content) { if (i &lt; itemsPerPage) { page.push(content); i++; } else { pagesContainer.push(page) page = []; page.push(content) i = 0; } if (props.content.indexOf(content) === props.content.length - 1) { pagesContainer.push(page); } } console.log(pagesContainer); </code></pre> <p>Similar to <a href="https://codereview.stackexchange.com/questions/183417/pagination-algorithm-in-js">this pagination question</a>. What I'm trying to do is to create an array, which each position represents a page and stores its items, not trying to get ranges, pages amounts, etc.</p>
[]
[ { "body": "<h1>Working with your code</h1>\n<h2>Refactor</h2>\n<p>First of all, let's extract clear &amp; separate function</p>\n<pre><code>function getPaged(items, itemsPerPage) {\n let pagesContainer = [];\n let page = [];\n let i = 0;\n for (const content of items) {\n if (i &lt; itemsPerPage) {\n page.push(content);\n i++;\n } else {\n pagesContainer.push(page)\n page = [];\n page.push(content)\n i = 0;\n }\n if (items.indexOf(content) === items.length - 1) {\n pagesContainer.push(page);\n }\n }\n \n return pagesContainer;\n}\n\nconsole.log(getPaged(props.content, itemsPerPage));\n</code></pre>\n<p>Now, you can notice that the variable <code>i</code> always equals to <code>page.length</code>. So we don't need it.\nJust replace usage <code>i</code> with <code>page.length</code>:</p>\n<pre><code>function getPaged(items, itemsPerPage) {\n let pagesContainer = [];\n let page = [];\n for (const content of items) {\n if (page.length &lt; itemsPerPage) {\n page.push(content);\n } else {\n pagesContainer.push(page)\n page = [];\n page.push(content);\n }\n if (items.indexOf(content) === items.length - 1) {\n pagesContainer.push(page);\n }\n }\n \n return pagesContainer;\n}\n\nconsole.log(getPaged(props.content, itemsPerPage));\n</code></pre>\n<p>Condition <code>if (items.indexOf(content) === items.length - 1)</code> is not lovely.\nWe don't really need to add last page inside of cycle. Let's add that page outside:</p>\n<pre><code>function getPaged(items, itemsPerPage) {\n let pagesContainer = [];\n let page = [];\n for (const content of items) {\n if (page.length &lt; itemsPerPage) {\n page.push(content);\n } else {\n pagesContainer.push(page)\n page = [];\n page.push(content);\n }\n }\n \n if (page.length &gt; 0) {\n pagesContainer.push(page);\n }\n \n return pagesContainer;\n}\n\nconsole.log(getPaged(props.content, itemsPerPage));\n</code></pre>\n<p>There is no reason to create a page &amp; push a new item into it. Because we can create a page with the new item inside.</p>\n<pre><code>function getPaged(items, itemsPerPage) {\n let pagesContainer = [];\n let page = [];\n for (const content of items) {\n if (page.length &lt; itemsPerPage) {\n page.push(content);\n } else {\n pagesContainer.push(page)\n page = [content];\n }\n }\n \n if (page.length &gt; 0) {\n pagesContainer.push(page);\n }\n \n return pagesContainer;\n}\n\nconsole.log(getPaged(props.content, itemsPerPage));\n</code></pre>\n<h2>Beautify</h2>\n<p>Let's make some renames in order to make our life shorter:</p>\n<ul>\n<li>itemsPerPage → pageSize</li>\n<li>pagesContainer → pages</li>\n<li>content → item</li>\n</ul>\n<p>Also, we should note that the variable <code>pages</code> (previously <code>pagesContainer</code>) is not modified. So we can use <code>const</code>.</p>\n<pre><code>function getPaged(items, pageSize) {\n const pages = [];\n let page = [];\n for (const item of items) {\n if (page.length &lt; pageSize) {\n page.push(item);\n } else {\n pages.push(page)\n page = [item];\n }\n }\n\n if (page.length &gt; 0) {\n pages.push(page);\n }\n\n return pages;\n}\n\nconsole.log(getPaged(props.content, itemsPerPage));\n</code></pre>\n<h2>Possible enhancement</h2>\n<p>We can build lazy solution via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator\" rel=\"nofollow noreferrer\">generators</a>.</p>\n<pre><code>function* getPaged(items, pageSize) {\n let page = [];\n for (const item of items) {\n if (page.length &lt; pageSize) {\n page.push(item);\n } else {\n yield page;\n page = [item];\n }\n }\n\n if (page.length &gt; 0) {\n yield page;\n }\n}\n\nconsole.log(Array.from(getPaged(props.content, itemsPerPage)));\n</code></pre>\n<p>This is cool only in case if you need to post-process your pages in lazy way.</p>\n<h1>Alternate solution 1</h1>\n<p>Our alternate solution will be based on a functional top-down approach.\nFirstly we will generate all pages from <code>0</code> to <code>pageCount</code>;\nAnd then we will fill each page with its actual content.</p>\n<pre><code>const range = (size) =&gt; [...Array(size).keys()];\n\nfunction getPaged(items, pageSize) {\n const pageCount = Math.ceil(items.length / pageSize);\n \n const getPage = (pageNo) =&gt; range(pageSize)\n .map(noInPage =&gt; items[pageNo * pageSize + noInPage])\n .filter(item =&gt; item !== undefined);\n \n return range(pageCount)\n .map(pageNo =&gt; getPage(pageNo));\n}\n\nconsole.log(getPaged(props.content, itemsPerPage));\n</code></pre>\n<p>Please, note that this solution will be slower. This is because <code>map</code> and <code>filter</code> are slow. But this can be solved with <a href=\"https://github.com/cognitect-labs/transducers-js\" rel=\"nofollow noreferrer\">transducers</a></p>\n<h1>Alternate solution 2</h1>\n<p>Use <a href=\"https://lodash.com/docs/#chunk\" rel=\"nofollow noreferrer\">lodash/chunk</a> and don't write your own function</p>\n<h1>Alternate solution 3</h1>\n<p>Using <a href=\"https://lodash.com/docs/#groupBy\" rel=\"nofollow noreferrer\">lodash/groupBy</a>, group items by page. Then return only values of the resulting dictionary.</p>\n<pre><code>const getPaged = (items, pageSize) =&gt; \n Object.values(_.groupBy(\n items,\n (item, index) =&gt; Math.floor(index / pageSize)\n ));\n\nconsole.log(getPaged(props.content, itemsPerPage));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T01:11:54.803", "Id": "525813", "Score": "1", "body": "Very well described. Loved your answer. Will look into Lodash, it seems like a good framework, otherwise will use the beautified version you provided." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T21:03:48.767", "Id": "266181", "ParentId": "266170", "Score": "3" } } ]
{ "AcceptedAnswerId": "266181", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T15:38:11.007", "Id": "266170", "Score": "2", "Tags": [ "javascript", "algorithm", "array", "pagination" ], "Title": "table pagination" }
266170
<p><a href="https://pchemguy.github.io/ContactEditor/" rel="nofollow noreferrer">ContactEditor</a> uses Excel VBA as a prototyping platform for a personal information manager combining the &quot;Model, View, Presenter&quot; (MVP) pattern and a persistent storage manager.</p> <p><strong>Fig. 1. Data manager application</strong></p> <p><img src="https://raw.githubusercontent.com/pchemguy/ContactEditor/develop/Assets/Diagrams/Data%20Management%20Overview.jpg" alt="FigDataManagerApp" /></p> <p>The design of the MVP part follows the ideas/tutorials/code from the RubberDuck VBA <a href="https://rubberduckvba.wordpress.com" rel="nofollow noreferrer">blog</a> and <a href="https://github.com/rubberduck-vba/examples" rel="nofollow noreferrer">demos</a>. The database contains a single table filled with mock contact data. The GUI has one user form that presents a single record data to the user. The &quot;MVP⇔DB&quot; functionality is implemented as a storage library with a pluggable architecture.</p> <p><strong>Figure 2. DataTable class diagram</strong></p> <p><img src="https://raw.githubusercontent.com/pchemguy/ContactEditor/develop/Assets/Diagrams/Class%20Diagram%20-%20Table.jpg" alt="FigDataTable" /></p> <p>The storage library contains two data model classes: <em>DataTableModel</em> and <em>DataRecordModel</em>. <em>DataTableModel</em> holds a set of rows retrieved from the database (currently, only &quot;SELECT * FROM TABLE_NAME&quot; is supported), and <em>DataRecordModel</em> caches a single record loaded into the user form. Each storage type (such as Excel worksheet or ADODB database) is represented by a single backend class abstracting the storage (e.g., <em>DataRecordWSheet</em> or <em>DataTableADODB</em>) and implementing the associated <em>IDataTableStorage</em> / <em>IDataRecordStorage</em> interface.</p> <p>From the calling code's perspective, the top-level API object is the data manager (<em>DataTableManager</em> / <em>DataRecordManager</em>) encapsulating a data model instance and an associated backend instance. Additionally, data managers implement <em>IDataTableManager</em> / <em>IDataRecordManager</em> interfaces, and abstract factory classes <em>IDataTableFactory</em> / <em>IDataRecordFactory</em> are also defined as illustrated in Fig. 2 (for the <em>DataTableModel</em> family).</p> <p>Note, this post only covers the <em>DataTableModel</em> family. Regarding the <em>DataRecordModel</em> family, please see the <a href="https://pchemguy.github.io/ContactEditor/" rel="nofollow noreferrer">project documentation</a>. Also, complete source code and tests are available from the <a href="https://github.com/pchemguy/ContactEditor" rel="nofollow noreferrer">project repository</a>.</p> <hr /> <p><strong>DataTableModel (model)</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Storage.Table.Model&quot; '@ModuleDescription &quot;Represents a data table.&quot; '@IgnoreModule ProcedureNotUsed, IndexedDefaultMemberAccess '@Exposed Option Explicit Private Type TDataTableModel FieldIndices As Scripting.Dictionary IdIndices As Scripting.Dictionary DirtyRecords As Scripting.Dictionary FieldNames As Variant Values As Variant End Type Private this As TDataTableModel Private Sub Class_Initialize() Set this.FieldIndices = New Scripting.Dictionary this.FieldIndices.CompareMode = TextCompare Set this.IdIndices = New Scripting.Dictionary this.IdIndices.CompareMode = TextCompare Set this.DirtyRecords = New Scripting.Dictionary this.DirtyRecords.CompareMode = TextCompare End Sub Private Sub Class_Terminate() Set this.FieldIndices = Nothing Set this.IdIndices = Nothing Set this.DirtyRecords = Nothing End Sub Public Property Get FieldIndices() As Scripting.Dictionary Set FieldIndices = this.FieldIndices End Property Public Property Get IdIndices() As Scripting.Dictionary Set IdIndices = this.IdIndices End Property Public Property Get DirtyRecords() As Scripting.Dictionary Set DirtyRecords = this.DirtyRecords End Property Public Property Get FieldNames() As Variant FieldNames = this.FieldNames End Property Public Property Let FieldNames(ByVal FieldNamesArg As Variant) this.FieldNames = FieldNamesArg End Property Public Property Get Values() As Variant Values = this.Values End Property Public Property Let Values(ByVal ValuesArg As Variant) this.Values = ValuesArg End Property Public Property Get IsDirty() As Boolean IsDirty = this.DirtyRecords.Count &gt; 0 End Property Public Function RecordIndexFromId(ByVal RecordId As String) As Long RecordIndexFromId = this.IdIndices(RecordId) End Function Public Function RecordValuesFromId(ByVal RecordId As String) As Variant Dim RecordIndex As Long: RecordIndex = this.IdIndices(RecordId) RecordValuesFromId = Application.WorksheetFunction.Index(Values, RecordIndex) End Function Public Function FieldIndexFromName(ByVal FieldName As String) As Long FieldIndexFromName = this.FieldIndices(FieldName) End Function Public Sub IsNotDirty() this.DirtyRecords.RemoveAll End Sub Public Sub UpdateRecordFromDictionary(ByVal Record As Scripting.Dictionary) Const ID_NAME_INDEX As Long = 1 Dim FieldIdName As String: FieldIdName = this.FieldNames(ID_NAME_INDEX) Dim RecordId As String: RecordId = CStr(Record(FieldIdName)) Dim RecordIndex As Long: RecordIndex = RecordIndexFromId(RecordId) this.DirtyRecords(RecordId) = RecordIndex Dim FieldName As Variant Dim FieldIndex As Long For Each FieldName In this.FieldNames FieldIndex = FieldIndexFromName(FieldName) this.Values(RecordIndex, FieldIndex) = Record(CStr(FieldName)) Next FieldName End Sub Public Sub CopyRecordToDictionary(ByVal Record As Scripting.Dictionary, ByVal RecordId As String) Dim RecordIndex As Long: RecordIndex = RecordIndexFromId(RecordId) Dim FieldName As Variant Dim FieldIndex As Long For Each FieldName In this.FieldNames FieldIndex = FieldIndexFromName(FieldName) Record(CStr(FieldName)) = this.Values(RecordIndex, FieldIndex) Next FieldName End Sub </code></pre> <hr /> <p><strong>DataTableADODB (backend)</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Storage.Table.Backend&quot; '@ModuleDescription &quot;Abstracts ADODB backend.&quot; '@PredeclaredId '@Exposed '@IgnoreModule FunctionReturnValueDiscarded, IndexedDefaultMemberAccess Option Explicit Private Const SQLITE_CONNSTR_PREFIX As String = &quot;sqlite:&quot; Implements IDataTableStorage Private Type TDataTable Model As DataTableModel SQL As SQLlib ADO As ADOlib AdoCommand As ADODB.Command ConnectionString As String TableName As String FieldNames() As String FieldTypes() As ADODB.DataTypeEnum FieldMap As Scripting.Dictionary IDs As Variant TypeCast As FieldFormat End Type Private this As TDataTable Private Sub Class_Initialize() Set this.FieldMap = New Scripting.Dictionary this.FieldMap.CompareMode = TextCompare End Sub Private Sub Class_Terminate() Set this.Model = Nothing Set this.SQL = Nothing Set this.ADO = Nothing Set this.FieldMap = Nothing On Error Resume Next this.AdoCommand.ActiveConnection.Close On Error GoTo 0 End Sub '@Ignore ProcedureNotUsed Public Property Get SelfIDataTableStorage() As IDataTableStorage Set SelfIDataTableStorage = Me End Property '@Ignore ProcedureNotUsed '@Description(&quot;Returns class reference.&quot;) Public Property Get Class() As DataTableADODB Set Class = DataTableADODB End Property '@Ignore ProcedureNotUsed Public Property Get AdoCommand() As ADODB.Command If this.AdoCommand Is Nothing Then Set AdoCommand = AdoCommandInit(this.SQL.SelectAll) Else Set AdoCommand = this.AdoCommand End If End Property Public Property Get FieldNames() As Variant FieldNames = this.FieldNames End Property Public Property Get FieldTypes() As Variant FieldTypes = this.FieldTypes End Property Public Property Get FieldMap() As Scripting.Dictionary Set FieldMap = this.FieldMap End Property '@Ignore ProcedureNotUsed Public Sub SetTypeCast(Optional ByVal TypeCast As FieldFormat = FieldFormat.CastAsIs) this.TypeCast = TypeCast End Sub '@Ignore ProcedureNotUsed '@Description &quot;Returns a new IDataTableStorage object.&quot; Public Function Create(ByVal Model As DataTableModel, ByVal ConnectionString As String, ByVal TableName As String) As IDataTableStorage Dim Result As DataTableADODB Set Result = New DataTableADODB Result.Init Model, ConnectionString, TableName Set Create = Result End Function '''' Creates a DataTableADODB instance with default interface, on which .Self can be use to access IDataTableStorage '@Description &quot;Returns a new DataTableADODB object.&quot; Public Function CreateDefault(ByVal Model As DataTableModel, ByVal ConnectionString As String, ByVal TableName As String) As DataTableADODB Dim Result As DataTableADODB Set Result = New DataTableADODB Result.Init Model, ConnectionString, TableName Set CreateDefault = Result End Function Public Sub Init(ByVal Model As DataTableModel, ByVal ConnectionString As String, ByVal TableName As String) Guard.NullReference Model Guard.EmptyString ConnectionString Set this.Model = Model Set this.SQL = SQLlib.Create(TableName) Set this.ADO = ADOlib.Create If LCase$(Left$(ConnectionString, 7)) = SQLITE_CONNSTR_PREFIX Then this.ConnectionString = this.ADO.GetSQLiteConnectionString(ConnectionString)(&quot;ADO&quot;) Else this.ConnectionString = ConnectionString End If this.ADO.SetConnectionString this.ConnectionString this.TableName = TableName this.ADO.GetTableMeta this.TableName, this.FieldNames, this.FieldTypes, this.FieldMap End Sub Public Function AdoCommandInit(ByVal SQLQuery As String, _ Optional ByVal CursorLocation As ADODB.CursorLocationEnum = adUseClient) As ADODB.Command If Not this.AdoCommand Is Nothing Then On Error Resume Next this.AdoCommand.ActiveConnection.Close On Error GoTo 0 End If Dim CommandText As String CommandText = IIf(Len(SQLQuery) &gt; 0, SQLQuery, this.SQL.SelectAll) Set this.AdoCommand = New ADODB.Command With this.AdoCommand .CommandType = ADODB.CommandTypeEnum.adCmdText .CommandText = CommandText .Prepared = True .ActiveConnection = this.ConnectionString .ActiveConnection.CursorLocation = CursorLocation End With Set AdoCommandInit = this.AdoCommand End Function Public Function AdoRecordset(Optional ByVal SQLQuery As String = vbNullString) As ADODB.Recordset Dim Rst As ADODB.Recordset Set Rst = New ADODB.Recordset With Rst Set .Source = IIf(SQLQuery = vbNullString, this.AdoCommand, AdoCommandInit(SQLQuery)) .CursorLocation = this.AdoCommand.ActiveConnection.CursorLocation .CursorType = adOpenStatic .LockType = adLockBatchOptimistic .CacheSize = 10 .Open Options:=adAsyncFetch If .CursorLocation = ADODB.CursorLocationEnum.adUseClient Then Set .ActiveConnection = Nothing End If End With Set AdoRecordset = Rst End Function Public Function Records(Optional ByVal SQLQuery As String = vbNullString) As Variant Dim Rst As ADODB.Recordset Set Rst = AdoRecordset(SQLQuery) Records = ArrayLib.TransposeArray(Rst.GetRows, OutputArrBase:=1) End Function Public Function RecordsAsText() As Variant Dim Rst As ADODB.Recordset Set Rst = AdoRecordset(this.SQL.SelectAllAsText(this.FieldNames, this.FieldTypes)) RecordsAsText = ArrayLib.TransposeArray(Rst.GetRows, OutputArrBase:=1) End Function Private Sub IDataTableStorage_LoadDataIntoModel() With this.Model .FieldIndices.RemoveAll .Values = RecordsAsText .FieldNames = this.FieldNames Dim FieldName As Variant For Each FieldName In this.FieldMap.Keys .FieldIndices(FieldName) = this.FieldMap(FieldName) Next FieldName Dim IDs As Variant IDs = ArrayLib.GetColumn(.Values, ColumnNumber:=1, OutputArrBase:=1) this.IDs = IDs Dim RecordCount As Long RecordCount = UBound(IDs) Dim RecordIndex As Long For RecordIndex = 1 To RecordCount .IdIndices(IDs(RecordIndex)) = RecordIndex Next RecordIndex End With End Sub Private Function IDataTableStorage_GetIds() As Variant IDataTableStorage_GetIds = this.IDs End Function Private Function IDataTableStorage_GetColumnValues(ByVal FieldName As String) As Variant IDataTableStorage_GetColumnValues = ArrayLib.GetColumn( _ this.Model.Values, _ ColumnNumber:=this.FieldMap(FieldName), _ OutputArrBase:=1 _ ) End Function Private Sub IDataTableStorage_SaveDataFromModel() If Not this.Model.IsDirty Then Exit Sub Dim AdoCmd As ADODB.Command Set AdoCmd = AdoCommandInit(this.SQL.UpdateSingleRecord(this.FieldNames)) this.ADO.MakeAdoParamsForRecordUpdate this.FieldNames, this.FieldTypes, AdoCmd Dim RecordsAffected As Long: RecordsAffected = 0 Dim Record As Scripting.Dictionary Set Record = New Scripting.Dictionary Record.CompareMode = TextCompare With this.Model AdoCmd.ActiveConnection.BeginTrans Dim RecordId As Variant For Each RecordId In .DirtyRecords.Keys .CopyRecordToDictionary Record, RecordId this.ADO.RecordToAdoParams Record, AdoCmd AdoCmd.Execute RecordsAffected, , adExecuteNoRecords Next RecordId AdoCmd.ActiveConnection.CommitTrans .IsNotDirty End With End Sub </code></pre> <hr /> <p><strong>IDataTableStorage (backend interface)</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Storage.Table.Backend&quot; '@ModuleDescription &quot;Abstracts storage interfaces for DataTableModel. Implemented by storage backends.&quot; '@Interface '@Exposed Option Explicit Public Sub LoadDataIntoModel() End Sub Public Sub SaveDataFromModel() End Sub Public Function GetIds() As Variant End Function Public Function GetColumnValues(ByVal FieldName As String) As Variant End Function </code></pre> <hr /> <p><strong>DataTableManager (manager)</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Storage.Table.Manager&quot; '@PredeclaredId '@Exposed Option Explicit Implements IDataTableManager Private Type TDataTableManager Model As DataTableModel Storage As IDataTableStorage End Type Private this As TDataTableManager Public Function Create(ByVal ClassName As String, ByVal ConnectionString As String, ByVal TableName As String) As IDataTableManager Dim Result As DataTableManager Set Result = New DataTableManager Result.Init ClassName, ConnectionString, TableName Set Create = Result End Function Public Sub Init(ByVal ClassName As String, ByVal ConnectionString As String, ByVal TableName As String) Set this.Model = New DataTableModel Set this.Storage = DataTableFactory.CreateInstance(ClassName, this.Model, ConnectionString, TableName) End Sub Private Sub Class_Terminate() Set this.Model = Nothing Set this.Storage = Nothing End Sub Private Property Get IDataTableManager_Model() As DataTableModel Set IDataTableManager_Model = this.Model End Property Private Sub IDataTableManager_LoadDataIntoModel() this.Storage.LoadDataIntoModel End Sub Private Sub IDataTableManager_SaveDataFromModel() this.Storage.SaveDataFromModel End Sub </code></pre> <hr /> <p><strong>IDataTableManager (manager interface)</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Storage.Table.Manager&quot; '@ModuleDescription &quot;A composition of a data model and a storage class responsible for loading/saving the model data.&quot; '@Interface '@Exposed Option Explicit Public Property Get Model() As DataTableModel End Property Public Sub LoadDataIntoModel() End Sub Public Sub SaveDataFromModel() End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:41:22.173", "Id": "525789", "Score": "0", "body": "You're using ADODB to Excel. This begs the question: \"Why aren't you using MSAccess to hold the data?\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T18:33:58.413", "Id": "525795", "Score": "0", "body": "@HackSlash I use Excel as a prototyping platform and because I have been using it as my personal database for years. But I do not see any point in migrating from Excel to MS Access." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T15:36:09.333", "Id": "525872", "Score": "0", "body": "Oh, well the biggest reason would be that [Excel is not a database](https://www.safe.com/blog/2021/01/excel-not-database/). It can't be made to preserve relations and enforce rules on data. I'm sure you'll hit the limitations some day, and it will be too late. When that day comes you'll need a solution yesterday." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T18:58:57.270", "Id": "525885", "Score": "0", "body": "I am not using ADODB to access an Excel database. I have an Excel backend in my demo just as an exercise. The whole point is to migrate to an RDBMS; I just have no intentions of dealing with MSAccess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T19:45:24.303", "Id": "525888", "Score": "0", "body": "Then why are you using VBA? The database where you use VBA is Access. If you're going to use a different backend then you want to design the front end in something like C#/WPF. That way you can use Excel or SQL or whatever backend you want, from the same codebase. The code you've written to link form textboxes to data fields is just a feature of Access or WPF Data Binding Source. It's like you're trying to reinvent Access Forms in Excel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T19:54:24.903", "Id": "525890", "Score": "0", "body": "I am under the impression that comments should not be used for this kind of discussion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T12:31:27.960", "Id": "525948", "Score": "1", "body": "@HackSlash OP's intention is use Excel (as the well known user friendly frontend that it is), to interact with any datastore compatible with `ADO` technology. Sure this could be done in Access or WPF, but that's not the point. Using Excel-VBA for something like this is a great learning exercise, as it forces the developer to build everything from the ground up. At the end of the day the developer will have designed something functional, and gained some knowledge along the way. Learning in this way is the premise of codereview.stackexchange.com..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T16:17:47.003", "Id": "266172", "Score": "1", "Tags": [ "sql", "vba", "excel", "database", "adodb" ], "Title": "ContactEditor - Excel VBA db app: Storage Library" }
266172
<p>I've created simple sorting visualizer in c++ using SFML. I'd love some feedback on how can I improve the code and OOP design.<br> Whole project: <a href="https://github.com/AwesomeHunter/Sorting-visualizer/" rel="nofollow noreferrer">GitHub</a><br><br> <strong>main.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;controller.hpp&quot; int main() { Controller app; while (app.isAppRunning()) { app.update(); } } </code></pre> <p><strong>controller.hpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;model.hpp&quot; #include &quot;sort_context.hpp&quot; #include &quot;view.hpp&quot; #include &lt;SFML/Graphics.hpp&gt; #include &lt;memory&gt; class Controller { private: SortContext context; View view; Model model; bool keyPressed; bool algorithmRunning; const unsigned MIN_DELAY = 0; const unsigned MAX_DELAY = 100; unsigned delay; const unsigned MAX_MODEL_SIZE = 1024; const unsigned MIN_MODEL_SIZE = 2; void increaseModelSize(); void decreaseModelSize(); void changeDelay(sf::Event &amp;event); void windowClosed(); void keyPressedEvent(sf::Event &amp;event); void keyReleasedEvent(); void handleEvents(); void runSortingAlgorithm(std::unique_ptr&lt;SortStrategy&gt; algorithm); public: Controller(); void update(); bool isAppRunning() const; bool isAlgorithmRunning() const; }; </code></pre> <p><strong>controller.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;controller.hpp&quot; #include &quot;algorithms/bubble_sort.hpp&quot; #include &quot;algorithms/insertion_sort.hpp&quot; #include &quot;algorithms/merge_sort.hpp&quot; #include &quot;algorithms/selection_sort.hpp&quot; Controller::Controller() : context(SortContext()), view(View(1920, 1080)), model(Model(64)), keyPressed(false), algorithmRunning(false), delay(30) { } void Controller::windowClosed() { this-&gt;algorithmRunning = false; this-&gt;view.closeWindow(); } void Controller::keyReleasedEvent() { this-&gt;keyPressed = false; } void Controller::changeDelay(sf::Event &amp;event) { if (event.mouseWheel.delta &gt; 0) this-&gt;delay = std::min(this-&gt;delay + 10, this-&gt;MAX_DELAY); if (event.mouseWheel.delta &lt; 0) this-&gt;delay = std::max(this-&gt;delay - 10, this-&gt;MIN_DELAY); } void Controller::increaseModelSize() { unsigned newSize = this-&gt;model.size() * 2; if (newSize &lt;= this-&gt;MAX_MODEL_SIZE) this-&gt;model.setSize(newSize); } void Controller::decreaseModelSize() { unsigned newSize = this-&gt;model.size() / 2; if (newSize &gt;= this-&gt;MIN_MODEL_SIZE) this-&gt;model.setSize(newSize); } void Controller::runSortingAlgorithm(std::unique_ptr&lt;SortStrategy&gt; algorithm) { this-&gt;algorithmRunning = true; this-&gt;context.setStrategy(std::move(algorithm)); this-&gt;context.sort(this-&gt;model, *this); this-&gt;algorithmRunning = false; } void Controller::update() { this-&gt;handleEvents(); this-&gt;view.updateScreen(this-&gt;model); this-&gt;view.delay(this-&gt;delay); } bool Controller::isAppRunning() const { return this-&gt;view.isWindowOpened(); } bool Controller::isAlgorithmRunning() const { return this-&gt;algorithmRunning; } void Controller::handleEvents() { sf::Event event; while (this-&gt;view.getEvent(event)) { switch (event.type) { case sf::Event::Closed: this-&gt;windowClosed(); break; case sf::Event::KeyPressed: this-&gt;keyPressedEvent(event); break; case sf::Event::KeyReleased: this-&gt;keyReleasedEvent(); break; case sf::Event::MouseWheelMoved: this-&gt;changeDelay(event); break; default: break; } } } void Controller::keyPressedEvent(sf::Event &amp;event) { if (this-&gt;keyPressed) return; this-&gt;keyPressed = true; if (event.key.code == sf::Keyboard::T) this-&gt;algorithmRunning = false; if (this-&gt;algorithmRunning) return; switch (event.key.code) { case sf::Keyboard::S: this-&gt;model.shuffle(); break; case sf::Keyboard::Hyphen: this-&gt;decreaseModelSize(); break; case sf::Keyboard::Equal: this-&gt;increaseModelSize(); break; case sf::Keyboard::Num1: this-&gt;runSortingAlgorithm(std::make_unique&lt;BubbleSort&gt;()); break; case sf::Keyboard::Num2: this-&gt;runSortingAlgorithm(std::make_unique&lt;SelectionSort&gt;()); break; case sf::Keyboard::Num3: this-&gt;runSortingAlgorithm(std::make_unique&lt;InsertionSort&gt;()); break; case sf::Keyboard::Num4: this-&gt;runSortingAlgorithm(std::make_unique&lt;MergeSort&gt;()); break; default: break; } } </code></pre> <p><strong>model.hpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;algorithm&gt; #include &lt;random&gt; #include &lt;vector&gt; class Model { private: struct Sortable { private: unsigned value; bool highlighted; std::reference_wrapper&lt;Model&gt; container; public: Sortable() = delete; Sortable(unsigned value, Model &amp;model) : value(value), highlighted(false), container(model){}; void highlight() { this-&gt;highlighted = true; } void unhighlight() { this-&gt;highlighted = false; } bool isHighlighted() const { return this-&gt;highlighted; } float heightAsPercentage() const { return static_cast&lt;float&gt;(this-&gt;value) / this-&gt;container.get().size(); } void moveToIndex(size_t index) { this-&gt;container.get().moveToIndex(*this, index); } bool operator&lt;(Sortable const &amp;rhs) const { return this-&gt;value &lt; rhs.value; } bool operator&gt;(Sortable const &amp;rhs) const { return this-&gt;value &gt; rhs.value; } bool operator&gt;=(Sortable const &amp;rhs) const { return this-&gt;value &gt;= rhs.value; } bool operator&lt;=(Sortable const &amp;rhs) const { return this-&gt;value &lt;= rhs.value; } }; static std::default_random_engine rng; std::vector&lt;Sortable&gt; data; void moveToIndex(Sortable const &amp;value, size_t newIndex); public: Model(unsigned initSize = 64); size_t size() const; void setSize(unsigned size); void shuffle(); Sortable operator[](size_t i) const; Sortable &amp;operator[](size_t i); }; </code></pre> <p><strong>model.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;model.hpp&quot; std::default_random_engine Model::rng{std::random_device()()}; Model::Model(unsigned initSize) { this-&gt;setSize(initSize); } size_t Model::size() const { return this-&gt;data.size(); } void Model::setSize(unsigned size) { this-&gt;data.clear(); for (unsigned i = 1; i &lt;= size; i++) { this-&gt;data.emplace_back(Sortable(i, *this)); } } void Model::shuffle() { std::shuffle(this-&gt;data.begin(), this-&gt;data.end(), Model::rng); } Model::Sortable &amp;Model::operator[](size_t i) { return this-&gt;data[i]; } Model::Sortable Model::operator[](size_t i) const { return this-&gt;data[i]; } void Model::moveToIndex(Sortable const &amp;value, size_t newIndex) { auto it = std::find_if(this-&gt;data.begin(), this-&gt;data.end(), [&amp;](Sortable const &amp;el) { return &amp;el == &amp;value; }); if (it == this-&gt;data.end() || newIndex &gt;= this-&gt;size()) return; size_t oldIndex = std::distance(this-&gt;data.begin(), it); if (oldIndex &lt; newIndex) { std::rotate(this-&gt;data.begin() + oldIndex, this-&gt;data.begin() + oldIndex + 1, this-&gt;data.begin() + newIndex + 1); } else { std::rotate(this-&gt;data.begin() + newIndex, this-&gt;data.begin() + oldIndex, this-&gt;data.begin() + oldIndex + 1); } } </code></pre> <p><strong>view.hpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;model.hpp&quot; #include &lt;SFML/Graphics.hpp&gt; class View { private: const unsigned WIDTH, HEIGHT; const unsigned FRAME_RATE = 60; sf::RenderWindow window; void draw(const Model &amp;model); public: View(const unsigned WIDTH, const unsigned HEIGHT); void delay(unsigned time) const; void updateScreen(const Model &amp;model); bool getEvent(sf::Event &amp;event); bool isWindowOpened() const; void closeWindow(); }; </code></pre> <p><strong>view.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;view.hpp&quot; View::View(const unsigned WIDTH, const unsigned HEIGHT) : WIDTH(WIDTH), HEIGHT(HEIGHT), window(sf::VideoMode(WIDTH, HEIGHT), &quot;Sorting visualization&quot;) { window.setFramerateLimit(this-&gt;FRAME_RATE); } void View::delay(unsigned time) const { sf::sleep(sf::milliseconds(time)); } void View::draw(const Model &amp;model) { float width = static_cast&lt;float&gt;(this-&gt;WIDTH) / model.size(); for (size_t i = 0; i &lt; model.size(); i++) { float height = this-&gt;HEIGHT * model[i].heightAsPercentage(); sf::RectangleShape rect({width, height}); rect.setPosition({i * width, this-&gt;HEIGHT - height}); if (model[i].isHighlighted()) rect.setFillColor(sf::Color::Red); else rect.setFillColor(sf::Color::Black); this-&gt;window.draw(rect); } } void View::updateScreen(const Model &amp;model) { this-&gt;window.clear(sf::Color::White); this-&gt;draw(model); this-&gt;window.display(); } bool View::getEvent(sf::Event &amp;event) { return this-&gt;window.pollEvent(event); } bool View::isWindowOpened() const { return this-&gt;window.isOpen(); } void View::closeWindow() { this-&gt;window.close(); } </code></pre> <p><strong>sort_context.hpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;algorithms/sort_strategy.hpp&quot; #include &quot;model.hpp&quot; #include &lt;memory&gt; class Controller; class SortContext { private: std::unique_ptr&lt;SortStrategy&gt; strategy; public: void setStrategy(std::unique_ptr&lt;SortStrategy&gt; newStrategy); void sort(Model &amp;model, Controller &amp;controller); }; </code></pre> <p><strong>sort_context.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;sort_context.hpp&quot; void SortContext::sort(Model &amp;model, Controller &amp;controller) { if (this-&gt;strategy) this-&gt;strategy-&gt;sort(model, controller); } void SortContext::setStrategy(std::unique_ptr&lt;SortStrategy&gt; newStrategy) { this-&gt;strategy = std::move(newStrategy); } </code></pre> <p><strong>sort_strategy.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;../model.hpp&quot; #define HIGHLIGHT_COMPARED_AND_UPDATE(first, second, controller) \ if (!controller.isAlgorithmRunning()) \ return; \ first.highlight(); \ second.highlight(); \ controller.update(); \ first.unhighlight(); \ second.unhighlight(); class Controller; class SortStrategy { public: SortStrategy() = default; virtual void sort(Model &amp;model, Controller &amp;controller) const = 0; virtual ~SortStrategy() = default; }; </code></pre> <p><strong>bubble_sort.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;algorithms/bubble_sort.hpp&quot; #include &quot;controller.hpp&quot; void BubbleSort::sort(Model &amp;model, Controller &amp;controller) const { unsigned changes = 1; while (changes &gt; 0) { changes = 0; for (size_t i = 0; i &lt; model.size() - 1; i++) { if (model[i + 1] &lt; model[i]) { changes++; std::swap(model[i], model[i + 1]); } HIGHLIGHT_COMPARED_AND_UPDATE(model[i], model[i + 1], controller); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T12:54:11.783", "Id": "525853", "Score": "2", "body": "In the future it would be better to add a follow up question with a link back to the original question rather than editing the question. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<pre><code> const unsigned MIN_DELAY = 0;\n const unsigned MAX_DELAY = 100;\n\n</code></pre>\n<p>You don't need to make instance variables since these are the same in any/every instance. So also make them <code>static</code>. But, today use <code>constexpr</code> instead. The adage is <em>constexpr is the new static const</em>.</p>\n<hr />\n<pre><code>void Controller::windowClosed() {\n this-&gt;algorithmRunning = false;\n this-&gt;view.closeWindow();\n}\n</code></pre>\n<p> <em>don't</em> use <code>this-&gt;</code> everywhere. Members are in scope. This is anti-idiomatic in C++.</p>\n<hr />\n<p>Prefer <code>signed</code> values. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es102-use-signed-types-for-arithmetic\" rel=\"nofollow noreferrer\">ES.102</a> and <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es106-dont-try-to-avoid-negative-values-by-using-unsigned\" rel=\"nofollow noreferrer\">ES.106</a></p>\n<hr />\n<pre><code>void Controller::changeDelay(sf::Event &amp;event) {\n if (event.mouseWheel.delta &gt; 0)\n this-&gt;delay = std::min(this-&gt;delay + 10, this-&gt;MAX_DELAY);\n if (event.mouseWheel.delta &lt; 0)\n this-&gt;delay = std::max(this-&gt;delay - 10, this-&gt;MIN_DELAY);\n}\n</code></pre>\n<p>It's idiomatic C++ to write the <code>&amp;</code> <em>with the type</em> not with the variable.<br />\nIn this function, you are not modifying <code>event</code> so why isn't it <code>const</code>?</p>\n<hr />\n<pre><code> bool operator&lt;(Sortable const &amp;rhs) const {\n return this-&gt;value &lt; rhs.value;\n }\n bool operator&gt;(Sortable const &amp;rhs) const {\n return this-&gt;value &gt; rhs.value;\n }\n bool operator&gt;=(Sortable const &amp;rhs) const {\n return this-&gt;value &gt;= rhs.value;\n }\n bool operator&lt;=(Sortable const &amp;rhs) const {\n return this-&gt;value &lt;= rhs.value;\n }\n</code></pre>\n<p>Are you using a current compiler (C++20)? Just write <code>operator&lt;=&gt;</code>. For older compilers, since the only thing you are doing is calling <code>sort</code> you only need <code>operator&lt;</code> (unless your visualizer is calling various others? Like <code>sort</code>, the working of <code>map</code>, etc., it <em>could</em> be written to only ever use <code>&lt;</code>).</p>\n<p>Use <code>noexcept</code> as well for (possibly) better performance.</p>\n<hr />\n<pre><code>#define HIGHLIGHT_COMPARED_AND_UPDATE(first, second, controller) \\\n if (!controller.isAlgorithmRunning()) \\\n return; \\\n first.highlight(); \\\n second.highlight(); \\\n controller.update(); \\\n first.unhighlight(); \\\n second.unhighlight();\n</code></pre>\n<p>Ummm.... yuck?<br />\nThis is in a CPP file and I don't see it mentioned in the few remaining lines of the file, so what's it doing here?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T12:57:59.803", "Id": "525854", "Score": "0", "body": "Thank you for feedback! I created this macro because I was using this part of code in every algorithm implementation and I didn't want to repeat myself. I added an example of such implementation to the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T13:07:57.047", "Id": "525856", "Score": "0", "body": "Sorry, I made a mistake, `sort_strategy` is an hpp file. Every sorting algorithm inherits from this class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:37:13.333", "Id": "525865", "Score": "0", "body": "@Gh0st Why is it a macro, rather than a function? I don't see anything about it that wouldn't work as a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T15:16:55.633", "Id": "525870", "Score": "0", "body": "The only problem is this if statement. Should I just write these two lines in every algorithm or there is a better way to stop a function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T16:37:58.193", "Id": "525877", "Score": "1", "body": "Two lines in each function is clear. Or, if there's nothing else in the function that would contain this, just put the `highlight` etc. inside an `if` block instead so it's skipped if not running." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T23:10:23.633", "Id": "266186", "ParentId": "266175", "Score": "2" } } ]
{ "AcceptedAnswerId": "266186", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:27:09.777", "Id": "266175", "Score": "4", "Tags": [ "c++" ], "Title": "Sorting visualizer" }
266175
<p>In the <a href="https://codereview.stackexchange.com/questions/266172">previous post</a>, I presented my Storage Library. Here, I would like to focus on the integration of the library with the MVP component.</p> <p><strong>Functional class mapping</strong></p> <p><img src="https://raw.githubusercontent.com/pchemguy/ContactEditor/develop/Assets/Diagrams/Overview%20Class%20Map.jpg" alt="FigFunctionalClassMapping" /></p> <p>First of all, the figure shows a new member of the Storage Library, the <em>DataCompositeManager</em> data manager, not discussed in the previous post. Since the user form displays a single record loaded from <em>DataRecordModel</em> and the data is loaded from the database into <em>DataTabelModel</em>, additional code is necessary to transfer the data between the two model classes. For this purpose, the <em>DataCompositeManager</em> manager has been introduced to take care of inter-model transfers.</p> <hr /> <p><strong>DataCompositeManager</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Storage.Manager&quot; '@ModuleDescription &quot;Composite class incorporating one Table and one Record model with backends. Record submodel is used to represent a row from the Table.&quot; '@PredeclaredId '@IgnoreModule ProcedureNotUsed '@Exposed Option Explicit Private Type TDataCompositeManager RecordModel As DataRecordModel RecordStorage As IDataRecordStorage TableModel As DataTableModel TableStorage As IDataTableStorage End Type Private this As TDataCompositeManager Private Sub Class_Initialize() Set this.RecordModel = New DataRecordModel Set this.TableModel = New DataTableModel End Sub Private Sub Class_Terminate() Set this.RecordModel = Nothing Set this.TableModel = Nothing End Sub Public Property Get Record() As Scripting.Dictionary Set Record = this.RecordModel.Record End Property Public Property Get RecordModel() As DataRecordModel Set RecordModel = this.RecordModel End Property Public Property Get TableModel() As DataTableModel Set TableModel = this.TableModel End Property Public Property Get FieldNames() As Variant FieldNames = this.TableModel.FieldNames End Property Public Property Get Values() As Variant Values = this.TableModel.Values End Property Public Property Get IDs() As Variant IDs = this.TableStorage.GetIds End Property Public Sub InitRecord(ByVal ClassName As String, ByVal ConnectionString As String, ByVal TableName As String) Set this.RecordStorage = DataRecordFactory.CreateInstance(ClassName, this.RecordModel, ConnectionString, TableName) End Sub Public Sub InitTable(ByVal ClassName As String, ByVal ConnectionString As String, ByVal TableName As String) Set this.TableStorage = DataTableFactory.CreateInstance(ClassName, this.TableModel, ConnectionString, TableName) End Sub Public Sub LoadDataIntoModel() this.TableStorage.LoadDataIntoModel this.RecordStorage.LoadDataIntoModel End Sub Public Sub SaveDataFromModel() this.RecordStorage.SaveDataFromModel this.TableStorage.SaveDataFromModel End Sub Public Sub SaveRecordDataToRecordStorage() this.RecordStorage.SaveDataFromModel End Sub Public Sub LoadRecordFromTable(ByVal RecordId As String) this.TableModel.CopyRecordToDictionary this.RecordModel.Record, RecordId this.RecordModel.RecordIndex = this.TableModel.RecordIndexFromId(RecordId) this.RecordModel.IsNotDirty End Sub Public Sub UpdateRecordToTable() this.TableModel.UpdateRecordFromDictionary this.RecordModel.Record End Sub </code></pre> <p>The figure also shows the MVP components: <em>ContactEditorModel</em> (Model), <em>ContactEditorForm</em> (View), and <em>ContactEditorPresenter</em> (Presenter). <em>ContactEditorModel</em> encapsulates an instance of <em>DataCompositeManager</em> and exposes it.</p> <hr /> <p><strong>ContactEditorModel</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Forms.Contact Editor&quot; '@IgnoreModule ProcedureNotUsed '@Exposed Option Explicit Public Enum DataPersistenceMode DataPersistenceDisabled DataPersistenceOnApply DataPersistenceOnExit End Enum Private Type TContactEditorModel RecordTableManager As DataCompositeManager PersistenceMode As DataPersistenceMode SuppressEvents As Boolean End Type Private this As TContactEditorModel Private Sub Class_Initialize() Set this.RecordTableManager = New DataCompositeManager this.SuppressEvents = False End Sub Private Sub Class_Terminate() Set this.RecordTableManager = Nothing End Sub Public Property Get RecordTableManager() As DataCompositeManager Set RecordTableManager = this.RecordTableManager End Property Public Property Get PersistenceMode() As DataPersistenceMode PersistenceMode = this.PersistenceMode End Property Public Property Let PersistenceMode(ByVal Mode As DataPersistenceMode) this.PersistenceMode = Mode End Property Public Property Get SuppressEvents() As Boolean SuppressEvents = this.SuppressEvents End Property Public Property Let SuppressEvents(ByVal Mode As Boolean) this.SuppressEvents = Mode End Property </code></pre> <p><em>ContactEditorForm</em> is <em>Modeless</em>, and it defines several custom events handled by the Presenter.</p> <hr /> <p><strong>ContactEditorForm</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Forms.Contact Editor&quot; Option Explicit '''' To avoid issues, populate ComboBox.List with array of strings, '''' cast if necessary (ComboBox.List column elements used for '''' ComboBox.Value must have the same type as ComboBox.Value, '''' otherwise expect runtime errors and glitches. Implements IDialogView Public Event FormLoaded() Public Event LoadRecord(ByVal RecordId As String) Public Event ApplyChanges() Public Event FormConfirmed() Public Event FormCancelled(ByRef Cancel As Boolean) Private Type TView Model As ContactEditorModel IsCancelled As Boolean End Type Private this As TView Private Function OnCancel() As Boolean Dim cancelCancellation As Boolean: cancelCancellation = False RaiseEvent FormCancelled(cancelCancellation) If Not cancelCancellation Then Me.Hide OnCancel = cancelCancellation End Function Private Sub id_Change() If this.Model.SuppressEvents Then Exit Sub RaiseEvent LoadRecord(id.Value) End Sub Private Sub OkButton_Click() Me.Hide RaiseEvent FormConfirmed End Sub Private Sub CancelButton_Click() '@Ignore FunctionReturnValueDiscarded OnCancel End Sub Private Sub ApplyButton_Click() RaiseEvent ApplyChanges End Sub Private Sub UpdateDisabledRadio_Click() this.Model.PersistenceMode = DataPersistenceMode.DataPersistenceDisabled End Sub Private Sub UpdateOnApplyRadio_Click() this.Model.PersistenceMode = DataPersistenceMode.DataPersistenceOnApply End Sub Private Sub UpdateOnExitRadio_Click() this.Model.PersistenceMode = DataPersistenceMode.DataPersistenceOnExit End Sub Private Sub IDialogView_ShowDialog(ByVal viewModel As Object) Set this.Model = viewModel Me.Show vbModeless End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = VbQueryClose.vbFormControlMenu Then Cancel = Not OnCancel End If End Sub Private Sub UserForm_Activate() InitializeId InitializeAge InitializeGender InitializeTableUpdating RaiseEvent FormLoaded End Sub Private Sub InitializeGender() Dim listValues() As Variant listValues = Array(&quot;male&quot;, &quot;female&quot;) Gender.Clear Gender.List = listValues End Sub Private Sub InitializeAge() Dim listValues(18 To 80) As Variant Dim AgeValue As Long For AgeValue = 18 To 80 listValues(AgeValue) = CStr(AgeValue) Next AgeValue Age.Clear Age.List = listValues End Sub Private Sub InitializeId() id.Clear id.List = this.Model.RecordTableManager.IDs End Sub Private Sub InitializeTableUpdating() UpdateDisabledRadio.Value = True End Sub Private Sub FirstName_Change() If this.Model.SuppressEvents Then Exit Sub this.Model.RecordTableManager.RecordModel.SetField &quot;FirstName&quot;, FirstName.Value End Sub Private Sub LastName_Change() If this.Model.SuppressEvents Then Exit Sub this.Model.RecordTableManager.RecordModel.SetField &quot;LastName&quot;, LastName.Value End Sub Private Sub Age_Change() If this.Model.SuppressEvents Then Exit Sub this.Model.RecordTableManager.RecordModel.SetField &quot;Age&quot;, Age.Value End Sub Private Sub Gender_Change() If this.Model.SuppressEvents Then Exit Sub this.Model.RecordTableManager.RecordModel.SetField &quot;Gender&quot;, Gender.Value End Sub Private Sub Email_Change() If this.Model.SuppressEvents Then Exit Sub this.Model.RecordTableManager.RecordModel.SetField &quot;Email&quot;, Email.Value End Sub Private Sub Country_Change() If this.Model.SuppressEvents Then Exit Sub this.Model.RecordTableManager.RecordModel.SetField &quot;Country&quot;, Country.Value End Sub Private Sub Domain_Change() If this.Model.SuppressEvents Then Exit Sub this.Model.RecordTableManager.RecordModel.SetField &quot;Domain&quot;, Domain.Value End Sub </code></pre> <p><em>ContactEditorPresenter</em> initializes the <em>DataCompositeManager</em> member of <em>ContactEditorModel</em> and initiates subsequent operations in event handlers.</p> <hr /> <p><strong>ContactEditorPresenter</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;ContactEditor.Forms.Contact Editor&quot; Option Explicit '@MemberAttribute VB_VarHelpID, -1 Private WithEvents view As ContactEditorForm Private Type TPresenter Model As ContactEditorModel Dialog As IDialogView End Type Private this As TPresenter Public Sub Show(ByVal TableBackEnd As String) Set view = New ContactEditorForm Set this.Dialog = view InitializeModel TableBackEnd '''' Loads data from the backends into the Model this.Model.RecordTableManager.LoadDataIntoModel this.Dialog.ShowDialog this.Model End Sub Private Sub ApplyChanges() this.Model.RecordTableManager.SaveRecordDataToRecordStorage Select Case this.Model.PersistenceMode Case DataPersistenceMode.DataPersistenceOnApply this.Model.RecordTableManager.UpdateRecordToTable this.Model.RecordTableManager.SaveDataFromModel Case DataPersistenceMode.DataPersistenceOnExit this.Model.RecordTableManager.UpdateRecordToTable Case DataPersistenceMode.DataPersistenceDisabled Exit Sub End Select End Sub Private Sub view_ApplyChanges() ApplyChanges End Sub Private Sub view_FormLoaded() LoadFormFromModel End Sub Private Sub LoadFormFromModel() this.Model.SuppressEvents = True Dim FieldName As Variant Dim FieldIndex As Long Dim FieldNames As Variant: FieldNames = this.Model.RecordTableManager.FieldNames For FieldIndex = LBound(FieldNames) To UBound(FieldNames) FieldName = FieldNames(FieldIndex) view.Controls(FieldName).Value = CStr(this.Model.RecordTableManager.RecordModel.GetField(FieldName)) Next FieldIndex this.Model.SuppressEvents = False End Sub Private Sub view_LoadRecord(ByVal RecordId As String) If this.Model.RecordTableManager.RecordModel.IsDirty Then Dim SaveChanges As Boolean SaveChanges = MsgBox(&quot;Apply unsaved changes?&quot;, vbYesNo + vbExclamation + vbDefaultButton2) If SaveChanges Then ApplyChanges End If this.Model.RecordTableManager.LoadRecordFromTable RecordId LoadFormFromModel End Sub Private Sub view_FormCancelled(ByRef Cancel As Boolean) 'setting Cancel to True will leave the form open Cancel = MsgBox(&quot;Cancel this operation?&quot;, vbYesNo + vbExclamation) = vbNo If Not Cancel Then ' modeless form was cancelled and is now hidden. ' ... Set view = Nothing End If End Sub Private Sub view_FormConfirmed() 'form was okayed and is now hidden. '... If this.Model.PersistenceMode &lt;&gt; DataPersistenceDisabled Then this.Model.RecordTableManager.UpdateRecordToTable this.Model.RecordTableManager.SaveDataFromModel Else this.Model.RecordTableManager.SaveRecordDataToRecordStorage End If Set view = Nothing End Sub '@Description &quot;Instantiates model and binds it to the desired backends.&quot; Private Sub InitializeModel(ByVal TableBackEnd As String) Set this.Model = New ContactEditorModel Dim ClassName As String Dim TableName As String Dim ConnectionString As String '''' Binds TableModel to its backend Select Case TableBackEnd Case &quot;ADODB&quot; ClassName = &quot;ADODB&quot; TableName = &quot;Contacts&quot; ConnectionString = &quot;sqlite:&quot; Case &quot;Worksheet&quot; ClassName = &quot;Worksheet&quot; TableName = &quot;Contacts&quot; ConnectionString = ThisWorkbook.Name &amp; &quot;!&quot; &amp; Contacts.Name Case &quot;CSV&quot; ClassName = &quot;CSV&quot; TableName = &quot;Contacts.xsv!sep=,&quot; ConnectionString = ThisWorkbook.Path End Select this.Model.RecordTableManager.InitTable ClassName, ConnectionString, TableName '''' Binds RecordModel to its backend ClassName = &quot;Worksheet&quot; TableName = vbNullString ConnectionString = ThisWorkbook.Name &amp; &quot;!&quot; &amp; ContactBrowser.Name this.Model.RecordTableManager.InitRecord ClassName, ConnectionString, TableName End Sub </code></pre>
[]
[ { "body": "<p>I have realized that it would be preferable to place all operations involving the <em>DataCompositeManager</em> instance within one module (Presenter). I recall that the reason I also kept such operations within <em>CONTROL_Change</em> handlers in the form code-behind was that I thought it would require a &quot;WithEvents&quot; module-level attribute in the Presenter for each control instance. I just realized that I could keep <em>CONTROL_Change</em> handlers in the form code-behind and pass control_name/new_value pairs to Presenter for further processing.</p>\n<p>Within <em>ContactEditorForm</em>, I should have defined a custom form event:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Public Event FieldChanged(ByVal FieldName As String, ByVal NewValue As Variant)\n</code></pre>\n<p>and changed handlers</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub FIELDNAME_Change()\n If this.Model.SuppressEvents Then Exit Sub\n this.Model.RecordTableManager.RecordModel.SetField &quot;FIELDNAME&quot;, FIELDNAME.Value\nEnd Sub\n</code></pre>\n<p>to (see id_Change handler)</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub FIELDNAME_Change()\n If this.Model.SuppressEvents Then Exit Sub\n RaiseEvent FieldChanged(&quot;FIELDNAME&quot;, FIELDNAME.Value)\nEnd Sub\n</code></pre>\n<p>Then, within <em>ContactEditorPresenter</em>, I could do</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub view_FieldChanged(ByVal FieldName As String, ByVal NewValue As Variant)\n this.Model.RecordTableManager.RecordModel.SetField FieldName, NewValue\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T21:06:12.783", "Id": "266182", "ParentId": "266178", "Score": "0" } } ]
{ "AcceptedAnswerId": "266182", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:35:50.443", "Id": "266178", "Score": "1", "Tags": [ "vba", "excel", "database", "mvp" ], "Title": "ContactEditor - Excel VBA db app: Storage Library and MVP" }
266178
<p>I wanted to make a blackjack game to use while bored, but it turned out to be far more complicated than I thought.</p> <pre class="lang-py prettyprint-override"><code>from random import choice, randint MASTER_DECK = [&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;2&quot;, &quot;2&quot;, &quot;2&quot;, &quot;2&quot;, &quot;3&quot;, &quot;3&quot;, &quot;3&quot;, &quot;3&quot;, &quot;4&quot;, &quot;4&quot;, &quot;4&quot;, &quot;4&quot;, &quot;5&quot;, &quot;5&quot;, &quot;5&quot;, &quot;5&quot;, &quot;6&quot;, &quot;6&quot;, &quot;6&quot;, &quot;6&quot;, &quot;7&quot;, &quot;7&quot;, &quot;7&quot;, &quot;7&quot;, &quot;8&quot;, &quot;8&quot;, &quot;8&quot;, &quot;8&quot;, &quot;9&quot;, &quot;9&quot;, &quot;9&quot;, &quot;9&quot;, &quot;10&quot;, &quot;10&quot;, &quot;10&quot;, &quot;10&quot;, &quot;J&quot;, &quot;J&quot;, &quot;J&quot;, &quot;J&quot;, &quot;Q&quot;, &quot;Q&quot;, &quot;Q&quot;, &quot;Q&quot;, &quot;K&quot;, &quot;K&quot;, &quot;K&quot;, &quot;K&quot;] def setup(deck): &quot;&quot;&quot;Sets up all game variables&quot;&quot;&quot; # Initialize all of the hands player_hand, deck = pick_cards(deck) dealer_hand, deck = pick_cards(deck) return deck, player_hand, dealer_hand def pick_cards(deck): &quot;&quot;&quot;Deals two random cards&quot;&quot;&quot; hand = [] if len(deck) &lt;= 6: deck = MASTER_DECK.copy() for card in range(0, 2): chosen_card = choice(deck) hand.append(chosen_card) deck.remove(chosen_card) return hand, deck def print_ui(player_hand, dealer_hand, deck, game_state): &quot;&quot;&quot;Prints out the display that tells the user there cards&quot;&quot;&quot; print() if game_state == &quot;player_dealing&quot;: print(&quot;The dealer has these cards:\n_, &quot; + &quot;, &quot;.join(dealer_hand[1:])) print() print(&quot;You have these cards:\n&quot; + &quot;, &quot;.join(player_hand)) print() print(f&quot;There are {len(deck)} cards left in the deck&quot;) elif game_state == &quot;dealer_dealing&quot;: print(&quot;The dealer has these cards:\n&quot; + &quot;, &quot;.join(dealer_hand)) print() print(&quot;You have these cards:\n&quot; + &quot;, &quot;.join(player_hand)) print() if have_won(player_hand, dealer_hand): print(&quot;You have beaten the dealer.&quot;) else: print(&quot;You have not beaten the dealer.&quot;) else: print(&quot;Something has gone wrong&quot;) while True: pass def have_won(player_hand, dealer_hand): &quot;&quot;&quot;Checks if the player has won&quot;&quot;&quot; numeric_player_hand = numeric_cards(player_hand.copy()) player_hand_total = 0 for card in numeric_player_hand: player_hand_total += card numeric_dealer_hand = numeric_cards(dealer_hand.copy()) dealer_hand_total = 0 for card in numeric_dealer_hand: dealer_hand_total += card if dealer_hand_total &gt; 21: if player_hand_total &gt; 21: return False return True if dealer_hand_total == 21: return False if dealer_hand_total &lt; 21: if dealer_hand_total &lt; player_hand_total &lt;= 21: return True return False def betting_phase(tokens): &quot;&quot;&quot;Takes the users bet&quot;&quot;&quot; print(f&quot;You have {tokens} tokens.&quot;) while True: try: bet = int(input(&quot;Please enter you bet: &quot;)) if int(bet) &gt; 0: if (tokens - bet) &gt;= 0: break print(&quot;Do not bet more than you have.&quot;) else: print(&quot;Please enter a number greater than zero.&quot;) except ValueError: print(&quot;Please enter a number.&quot;) return tokens - bet, bet def player_dealing(deck, player_hand, game_state): &quot;&quot;&quot;Handles dealing to the player&quot;&quot;&quot; if not deck: print(&quot;As there are no more cards left, the round ends.&quot;) game_state = &quot;dealer_dealing&quot; else: while True: user_command = input(&quot;Would you like to hit or to stay? (H/S): &quot;).lower() if user_command == &quot;h&quot;: chosen_card = choice(deck) player_hand.append(chosen_card) deck.remove(chosen_card) break elif user_command == &quot;s&quot;: game_state = &quot;dealer_dealing&quot; break else: print(&quot;Please only enter H for hit or S for stay.&quot;) return deck, player_hand, game_state def dealer_dealing(deck, dealer_hand): &quot;&quot;&quot;Handles dealing to the dealer&quot;&quot;&quot; while True: if not deck: break numeric_dealer_hand = numeric_cards(dealer_hand.copy()) hand_total = 0 for card in numeric_dealer_hand: hand_total += card if hand_total &lt; 16: chosen_card = choice(deck) dealer_hand.append(chosen_card) deck.remove(chosen_card) elif hand_total == 16: if randint(0, 1): chosen_card = choice(deck) dealer_hand.append(chosen_card) deck.remove(chosen_card) else: break elif 11 in numeric_dealer_hand and hand_total &gt; 21: for card_number, card in enumerate(numeric_dealer_hand): if card == 11: numeric_dealer_hand[card_number] = 1 else: break return deck, dealer_hand def numeric_cards(hand): &quot;&quot;&quot;Turns card letters into their number values&quot;&quot;&quot; for card_number, card in enumerate(hand): if card == &quot;J&quot; or card == &quot;Q&quot; or card == &quot;K&quot;: hand[card_number] = 10 elif card == &quot;A&quot;: hand[card_number] = 11 else: hand[card_number] = int(hand[card_number]) hand_total = 0 for card in hand: hand_total += card if hand_total &gt; 21 and 11 in hand: for card_number, card in enumerate(hand): if card == 11: hand[card_number] = 1 return hand def play_again(): &quot;&quot;&quot;Allows user to play again or quit&quot;&quot;&quot; while True: play_again = input(&quot;Do you want to play again? (Y/N): &quot;).lower() if play_again == &quot;y&quot;: break elif play_again == &quot;n&quot;: quit() print(&quot;Please only enter a Y or N&quot;) deck = MASTER_DECK.copy() tokens = 200 while True: game_state = &quot;betting&quot; playing_game = True deck, player_hand, dealer_hand = setup(deck) while playing_game: if game_state == &quot;betting&quot;: tokens, bet = betting_phase(tokens) game_state = &quot;player_dealing&quot; else: print_ui(player_hand, dealer_hand, deck, game_state) deck, player_hand, game_state = player_dealing(deck, player_hand, game_state) if game_state == &quot;dealer_dealing&quot;: deck, dealer_hand = dealer_dealing(deck, dealer_hand) if have_won(player_hand, dealer_hand): tokens += 2 * bet print_ui(player_hand, dealer_hand, deck, game_state) playing_game = False if tokens: play_again() else: input(&quot;You have no more tokens to spend. Hit enter to quit.&quot;) quit() </code></pre> <p>Originally I wanted to add some AI players as well as including the split and double functions, but the code got so complicated that I thought it would be better not to include those unless the code was cleaned up.</p> <p>Is there any way to clean this up and make it easier to add more features? As well, is there anything else that could be made better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T11:54:37.097", "Id": "525945", "Score": "0", "body": "Just a note; you don't seem to be handling the card suits in this, unless it's my mis-understanding of the source. It might therefore be better, as in a more complete game, if the cards were ordered by suit in the master deck; maybe a muti-dimensional array so that you have `MASTER_CARD.HEARTS = [ ... ]` etc...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:13:21.523", "Id": "525955", "Score": "2", "body": "@ShaunBebbers it might not matter for blackjack specifically. As long as you are tracking the correct number of cards as a stand-in for the suit, it's just the values that really have an impact" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:24:59.290", "Id": "525957", "Score": "0", "body": "@C.Nivs - I agree that it might not matter in terms of the script and game logic, but it would be a better experience for the user. The simplest solution is to have each element in the `MASTER_CARD` object as `'AH', 'AD', 'AC', 'AS' ...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T21:20:20.347", "Id": "526205", "Score": "0", "body": "To refine your application. Unicode has [characters for playing cards](https://de.wikipedia.org/wiki/Unicodeblock_Spielkarten), which of course needs to use a font having them." } ]
[ { "body": "<p>A couple of things that I've noticed; for a better player experience, it might be worth allocating a suit per card, the easiest way to do this would be to modify the <code>MASTER_DECK</code> array as follows (with the correct character encoding, you could also have <code>♡♤♧♢</code> but I'm not sure whether your intention was to stick with ASCII/Extended ASCII only or not, I also don't know how Python handles extended character sets):</p>\n<pre><code>MASTER_DECK = [&quot;AH&quot;, &quot;AD&quot;, &quot;AS&quot;, &quot;AC&quot;,\n &quot;2H&quot;, &quot;2D&quot;, &quot;2S&quot;, &quot;2C&quot;,\n ...\n &quot;JH&quot;, &quot;JD&quot;, &quot;JS&quot;, &quot;JC&quot;,\n &quot;QH&quot;, &quot;QD&quot;, &quot;QS&quot;, &quot;QC&quot;,\n &quot;KH&quot;, &quot;KD&quot;, &quot;KS&quot;, &quot;KC&quot;]\n</code></pre>\n<p>In your <code>numeric_cards</code> function, you will then need to convert the values by sub-string, taking the first digit; in this case, the substring <code>1</code> will represent <code>10H</code>, <code>10D</code> etc, so:</p>\n<pre><code>def numeric_cards(hand):\n &quot;&quot;&quot;Turns card letters into their number values&quot;&quot;&quot;\n for card_number, card in enumerate(hand):\n if card[0] == &quot;J&quot; or card [0]== &quot;Q&quot; or card[0] == &quot;K&quot; or card[0] == &quot;1&quot;:\n hand[card_number] = 10\n elif card[0] == &quot;A&quot;:\n hand[card_number] = 11\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T11:07:44.697", "Id": "266322", "ParentId": "266179", "Score": "0" } }, { "body": "<h1>Creating the deck</h1>\n<p>Rather than using <code>copy</code> to clone the deck, it's simple enough to just create a new deck:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def create_deck():\n # need 4 copies of each card, representing each suit\n deck = [face for _ in range(4) for face in 'AJKQ']\n deck.extend([str(i) for _ in range(4) for i in range(2,11)])\n\n # This shuffle happens in-place\n shuffle(deck)\n\n return deck\n</code></pre>\n<p>Also, it might be easier to just shuffle the deck, since that's what you would do in a normal game.</p>\n<h1>Choosing Cards</h1>\n<p>Since we've shuffled the deck, it becomes significantly easier to choose cards. You can treat <code>deck</code> like a <code>stack</code> and just <code>pop</code> cards off of the top of the stack.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pick_cards(deck):\n hand = []\n \n for _ in range(2):\n hand.append(deck.pop())\n\n return hand\n\n</code></pre>\n<p>You <em>could</em> use list comprehension syntax:</p>\n<pre class=\"lang-py prettyprint-override\"><code>hand = [deck.pop() for _ in range(2)]\n</code></pre>\n<p>But personally, I am not a huge fan of the side effect being wrapped into the statement like this.</p>\n<p>I'd also move the length check out of the function, since it's a bit clearer to re-generate the deck, then choose cards:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if len(deck) &lt; 6:\n deck = generate_deck()\n\nhand = pick_cards(deck)\n</code></pre>\n<h1>String Concatenation</h1>\n<p>There are a few places in your code where you have something like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(&quot;The dealer has these cards:\\n&quot; + &quot;, &quot;.join(dealer_hand))\n</code></pre>\n<p>Snippets like this can be replaced by f-strings:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(f&quot;The dealer has these cards:\\n{','.join(dealer_hand)&quot;)\n</code></pre>\n<h1><code>print_ui</code></h1>\n<p>On top of the f-string refactor, the print statements are the same no matter the game state, so print first. Furthermore, the name of the function is to <code>print</code> the ui, so just print:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def print_ui(player_hand, dealer_hand, deck):\n message = '\\n\\n'.join((\n f&quot;The dealer has these cards:\\n{', '.join(dealer_hand)}&quot;,\n f&quot;You have these cards:\\n{', '.join(player_hand)}&quot;,\n f&quot;There are {len(deck)} cards left in the deck&quot;\n ))\n print(message)\n</code></pre>\n<h1>Getting Card Values</h1>\n<p>It is better to check for multiple equality conditions using membership testing:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this\nif card == 'J' or card ==...\n\n# to this\nif card in 'JQK':\n</code></pre>\n<p>Better yet, a dictionary might be best for this:</p>\n<pre class=\"lang-py prettyprint-override\"><code># this can stay in global scope, hence why it\n# is named with ALL_CAPS\nCARD_VALUES = {str(i): i for i in range(2, 11)}\n\nfor face in 'JQK':\n CARD_VALUES[face] = 10\n\nCARD_VALUES['A'] = 11\n\n# Then in your function, it's simply a matter of:\ndef get_hand_total(hand):\n hand_total = sum(CARD_VALUES[card] for card in hand)\n\n if hand_total &lt;= 21:\n return hand_total\n \n aces = hand.count('A')\n\n # if there are any aces to swap, this loop\n # will execute\n while aces and hand_total &gt; 21:\n # swap the value from 11 to 1 by just\n # subtracting 10\n hand_total -= 10\n aces -= 1\n \n return hand_total\n</code></pre>\n<h1>Checking for a Win</h1>\n<p>This gets much simpler now that <code>get_values</code> has been refactored. I'd name it <code>player_won</code>, it's a more descriptive name since you are only returning <code>True</code> if the player wins. Have this function take just the totals:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def player_won(player_total, dealer_total):\n if player_total &gt; 21 and dealer_total &gt; 21:\n return False\n elif player_total &gt; 21 and dealer_total &lt;= 21:\n return False\n elif player_total &lt;= 21 and dealer_total &gt; 21:\n return True\n elif dealer_total &lt; player_total &lt;= 21:\n return True\n else:\n return False\n</code></pre>\n<h1>The Dealer's Turn</h1>\n<p>This looks like it's combining the efforts of <code>get_values</code> and <code>pick_cards</code>. We can at least slim it down via the <code>deck.pop()</code> method:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def dealer_turn(deck, hand):\n while True:\n if not deck:\n # I'll raise an error here so that we can \n # remake the deck, I'll handle that operation\n # shortly\n raise ValueError(&quot;No cards left in deck, regenerating&quot;)\n \n hand_total = get_hand_total(hand=hand)\n\n if hand_total &lt; 16:\n # choose a card\n hand.append(deck.pop())\n elif hand_total == 16 and randint(0, 1):\n hand.append(deck.pop())\n else:\n break\n</code></pre>\n<p>We don't need to <code>return</code> anything, since <code>deck</code> and <code>hand</code> get modified in-place. To use this function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n try:\n dealer_turn(deck=deck, hand=dealer_hand)\n except ValueError:\n hands = dealer_hand + player_hand\n\n deck = []\n for card in create_deck():\n try:\n hands.remove(card)\n except:\n deck.append(cards)\n else:\n break\n</code></pre>\n<p>It's a single-iteration while loop. If an exception is raised, then the deck gets reset, minus the cards in the players' hands, then <code>dealer_turn</code> gets called again. Otherwise, the loop exits. This can be wrapped into a <code>take_turn</code> function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def take_turn(deck, player_hand, dealer_hand, turn):\n &quot;&quot;&quot;Function that wraps turn-taking and recreates the deck if it's emtpy&quot;&quot;&quot;\n if turn == 'player_turn':\n turn_func = player_turn\n hand = player_hand\n else:\n turn_func = dealer_turn\n hand = dealer_hand\n\n while True:\n try:\n turn_func(deck=deck, hand=hand)\n except ValueError:\n hands = dealer_hand + player_hand\n deck = []\n for card in create_deck():\n try:\n hands.remove(card)\n except:\n deck.append(cards)\n else:\n break\n\n return deck\n\n</code></pre>\n<p>We return <code>deck</code> here because if we re-create the deck, that won't carry out of the scope of this function. However, this looks bad, and this is where the suits come in:</p>\n<h1>The Case for Suits</h1>\n<p>The suits make checking for drawn cards easier, because each card is unique. The easy way to create suits for each card is to modify our <code>create_deck</code> function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def create_deck():\n suits = 'HDCS'\n deck = [f&quot;{suit}{face}&quot; for suit in suits for face in 'AJKQ']\n deck.extend([f&quot;{suit}{i}&quot; for suit in suits for i in range(2,11)])\n\n # This shuffle happens in-place\n shuffle(deck)\n\n return deck\n</code></pre>\n<p>Which cleans up the uniqueness check a lot:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def take_turn(deck, player_hand, dealer_hand, turn):\n &quot;&quot;&quot;Function that wraps turn-taking and recreates the deck if it's emtpy&quot;&quot;&quot;\n if turn == 'player_turn':\n turn_func = player_turn\n hand = player_hand\n else:\n turn_func = dealer_turn\n hand = dealer_hand\n\n while True:\n try:\n turn_func(deck=deck, hand=hand)\n except ValueError:\n hands = set(dealer_hand + player_hand)\n deck = [card for card in create_deck() if card not in hands]\n else:\n break\n\n return deck\n</code></pre>\n<p>Though this requires a slight modification of <code>get_hand_total</code> as well:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_hand_total(hand):\n hand_total = sum(\n # use card.strip() to get rid of the suits\n CARD_VALUES[card.strip('DCSH')] for card in hand\n )\n\n if hand_total &lt;= 21:\n return hand_total\n \n aces = sum('A' in card for card in hand)\n\n # if there are any aces to swap, this loop\n # will execute\n while aces and hand_total &gt; 21:\n # swap the value from 11 to 1 by just\n # subtracting 10\n hand_total -= 10\n aces -= 1\n \n return hand_total\n</code></pre>\n<h1>Place your Bets</h1>\n<p>A few things here. First, I think calling the function <code>place_bet</code> is a bit better as far as naming. Second, no need to do the second <code>int</code> conversion on <code>bet</code>, it's already an <code>int</code>. Third, you can just compare if <code>tokens &lt; bet</code> rather than doing the subtraction twice. Last, I don't think you need to do the subtraction in the function, subtract the bet from the tokens after a good bet is chosen:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def place_bet(tokens):\n &quot;&quot;&quot;User places bet&quot;&quot;&quot;\n print(f&quot;You have {tokens} tokens&quot;)\n\n while True:\n try:\n bet = int(input(&quot;Please enter your bet: &quot;))\n except ValueError:\n print(&quot;Please enter a number&quot;)\n continue\n \n if bet &gt; tokens:\n print(&quot;Don't bet more than you have&quot;)\n else:\n break\n \n return bet\n\ntokens = 200\n\ntokens -= place_bet(tokens)\n</code></pre>\n<h1>User's Turn</h1>\n<p>This will wind up looking quite similar to the <code>dealer_turn</code> function. However, the user should be able to hit multiple times, so the <code>break</code> in the <code>while</code> loop will only occur when the <code>stay</code> choice is picked.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def player_turn(deck, hand):\n &quot;&quot;&quot;Player takes their turn&quot;&quot;&quot;\n while True:\n if not deck:\n raise ValueError(&quot;No cards left in deck, regenerating&quot;)\n \n user_command = input(&quot;Would you like to hit or to stay? (H/S): &quot;).lower()\n\n if user_command == 'h':\n player_hand.append(deck.pop())\n elif user_command == 's':\n break\n else:\n print(&quot;Please choose either H for hit or S for stay&quot;)\n continue\n</code></pre>\n<p>Again, no need to return <code>deck</code> or <code>hand</code> because they are modified in-place.</p>\n<h1>Main function</h1>\n<p>I'd wrap your game in a <code>main</code> function, it makes it a bit easier to wrap in the <code>while</code> loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main(deck, tokens):\n player_hand, dealer_hand = pick_cards(), pick_cards()\n\n for state in ('betting', 'player_turn', 'dealer_turn'):\n print_ui(\n player_hand=player_hand, \n dealer_hand=dealer_hand, \n deck=deck\n )\n\n if state == 'betting':\n tokens -= place_bet(tokens)\n else:\n deck = take_turn(\n deck=deck, \n player_hand=player_hand, \n dealer_hand=dealer_hand, \n turn=state\n )\n \n # This will skip the rest of the loop\n # until the dealer's turn is over\n if state != 'dealer_turn':\n continue\n\n player_total, dealer_total = get_hand_total(player_hand), get_hand_total(dealer_total)\n \n if player_won(player_total, dealer_total):\n print(&quot;You won!&quot;)\n tokens += 2 * bet \n break\n else:\n print(&quot;Dealer won&quot;)\n break\n\n return deck, tokens\n\n\nif __name__ == &quot;__main__&quot;:\n deck = create_deck()\n tokens = 200\n\n while True:\n deck, tokens = main(deck, tokens)\n if not tokens:\n input(&quot;You have no more tokens to spend. Hit enter to quit.&quot;)\n quit() \n \n again = input(&quot;Play Again? (y/n) &quot;)\n\n if again == 'y':\n continue\n elif again == 'n':\n quit()\n else:\n print(&quot;Please input either y or n&quot;)\n</code></pre>\n<p>I've kept the <code>main</code> function wrapped in a <code>while</code> as you had it, however, the game itself is a <code>for</code> loop. There are only three stages, and they go in order. Once the dealer has played, a win is checked and the user is asked if they want to play again.</p>\n<h1>What if I want the <em>real</em> suits?</h1>\n<p>You can print the unicode for the suit emojis:</p>\n<pre class=\"lang-py prettyprint-override\"><code>SUITS = [chr(i) for i in range(9828, 9832)]\n\nprint(SUITS)\n['♤', '♥', '♦', '♧']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T20:55:57.870", "Id": "266364", "ParentId": "266179", "Score": "5" } }, { "body": "<p>K00lman, I wanted to chime in with my points too, some of these are covered by other answers. The most obvious problems that jump out with the code:</p>\n<p>Master deck</p>\n<ul>\n<li>No suits and the deck creation is literal - not programmatic.</li>\n</ul>\n<p>Deck Setup</p>\n<ul>\n<li>Lots of duplicated code</li>\n</ul>\n<p>Pick Cards</p>\n<ul>\n<li>Using <code>.copy()</code> to duplicate a deck when card count is low (bad structure)</li>\n<li>Using a loop to remove and append cards</li>\n</ul>\n<p>Printing card status</p>\n<ul>\n<li>Using <code>print()</code> instead of &quot;\\n&quot;</li>\n<li>Using join and slice instead of a function</li>\n</ul>\n<p>Determining Winning hand</p>\n<ul>\n<li>Using <code>.copy()</code></li>\n<li>adding values of the copied structure instead of the original</li>\n<li>using a function to convert strings to values <code>numeric_dealer_hand</code> repeatedly instead of once on a new card received</li>\n<li>early exit if the player busts, instead of confirming for dealer bust too (draw)\n-using only True and False to determine outcomes (draw, loss, win)</li>\n</ul>\n<p>Betting Phase</p>\n<ul>\n<li>not sanitising input/restricting input</li>\n<li>using break (spaghetti code)</li>\n<li>returning multiple values and undefined values (<code>bet</code>) in separate code paths</li>\n</ul>\n<p>Player dealing</p>\n<ul>\n<li>Using <code>While True</code> and <code>break</code> for logic control (spaghetti code)</li>\n<li>3 variables in, 3 variables out - implies this function and the caller both need refactoring</li>\n</ul>\n<p>Dealer dealing:</p>\n<ul>\n<li>2 variables in, 2 variables out (same comment as above - but why only 2 now?</li>\n<li>Using <code>While True</code> and <code>break</code> for logic control (spaghetti code)</li>\n</ul>\n<p>etc. more of the above. Let's run over a few of these to help you understand how you can improve your coding.</p>\n<h2>The Card</h2>\n<p>This is probably the start of the design issues, the intermixing of the physical cards verses intangible values associated with the card.\nTo explain - a card is a card. Representing the card is important, but it has no value until you decide what game to play. The game determines the value of the cards, not the cards themselves. That might be confusing - but here's a perfect example: Aces. What are they? Are they 1 or 11? The answer is it depends on the game situation. And it's THERE where the value determination should take place, not with the card.</p>\n<p>When you program, most of the issues you encounter are due to bad design, data or functions crossing over each domain's barrier, or state (value of variables) changing where it shouldn't.\nEnsuring separating the domains is something you'll learn as you improve your craft. A book named &quot;Code Complete&quot; can help you to recognise common mistakes. It's good for beginners and intermediate coders. After that, &quot;Clean Code&quot; will begin the introduction to improving how you think about coding, but it's quite advanced.</p>\n<p>With that said, let’s construct a proper deck, starting with the card object.</p>\n<pre><code>class Card:\n def __init__(self, rank, suit):\n self._rank, self._suit = rank, suit\n\n @property\n def rank(self):\n return self._rank\n\n @property\n def suit(self):\n return self._suit\n\n def __str__(self):\n return f&quot;{self._rank}{self._suit}&quot;\n</code></pre>\n<p>As we can see, we create the card via the init method, and when the card is printed, it will display its rank and suit. Properties of the card, we can request these individually (.rank or .suit).</p>\n<p>So, we now think about the types of cards. Cards of rank 2-10 in suits Diamonds, Hearts, Clubs and Spades (D/H/C/S) are simple, Face cards are ranked as King (KD, KH, KC, KS), the Queen and the Jack. Lastly, 4 Ace cards, one per suit.\nCards 2-10 will work fine as a Card object, but Face cards and Aces require small modifications.</p>\n<pre><code>class Ace(Card):\n def __init__(self, rank, suit):\n super().__init__(rank, suit)\n\n\nclass FaceCard(Card):\n def __init__(self, rank, suit):\n super().__init__(rank, suit)\n self._rank = [&quot;K&quot;, &quot;Q&quot;, &quot;J&quot;][self.rank]\n</code></pre>\n<p><code>FaceCard(Card)</code> looks different, but <code>Ace(Card)</code> you could reduce down to a simple Card - but we don’t - because Aces are seen as unique by us. It doesn’t cost us any more to represent them separately. Just a quick comment on the <code>FaceCard</code> ranking code:</p>\n<pre><code>&gt;&gt;&gt; [&quot;K&quot;, &quot;Q&quot;, &quot;J&quot;][1]\n'Q'\n</code></pre>\n<p>If that is still confusing, open python and change 1 to either 0 or 2 to understand the indexing.</p>\n<h2>The Deck</h2>\n<p>The deck will be made up of 52 cards. The deck has an action of dealing a card. Does a Blackjack deck have any other actions? Not that I can think of.</p>\n<p>Let's create the deck then. We'll call it BackjackDeck - but you could use this skeleton for different card games, and add Jokers too.</p>\n<pre><code>from random import shuffle\n\nclass BlackjackDeck:\n &quot;&quot;&quot; A set of cards suitable for a Blackjack game which deals a card already shuffled &quot;&quot;&quot;\n\n def __init__(self):\n self.cards = []\n for suit in [&quot;H&quot;, &quot;D&quot;, &quot;C&quot;, &quot;S&quot;]:\n self.cards += [Card(rank, suit) for rank in range(2, 11)]\n self.cards += [FaceCard(rank, suit) for rank in range(3)]\n self.cards += [Ace(&quot;A&quot;, suit)]\n shuffle(self.cards)\n\n def deal(self):\n for card in self.cards:\n yield card\n</code></pre>\n<p>As mentioned previously, cards with face 2-10 are built easily, FaceCards and Aces override their classes when instantiated. Looking at Aces, we have only a single Ace per suit, which is why there's no range(x) for them. We create them independently using &quot;A&quot; to make it obvious.</p>\n<p>We could do some trick, but the next programmer who reads your code will need to mentally deconstruct your trick to understand your code. Tricks cost companies time and money, so try to make your code obvious and easy to read.</p>\n<p>If they don't understand your trick, it's likely they will rewrite your trick. If there are dependencies on the trick, there will be broken code somewhere downstream.</p>\n<h2>The Game</h2>\n<p>After creating the deck like I have, it's now incompatible with your existing code. We will resolve those issues mentioned at the top with changed code.</p>\n<p>Firstly, we have to modify you code to include the entry point. This is a basic step in Python, if it's not there, when another script loads your code, it will start playing automatically, rather than loading the objects (breaking the import system).</p>\n<pre><code>if __name__==&quot;__main__&quot;:\n\n deck = MASTER_DECK.copy()\n tokens = 200\n\n while True:\n</code></pre>\n<p>So, thinking about design. Who, What, When, Where, Why.</p>\n<p>Who plays the game? The player and the dealer.\nWhat wins the game? A better hand than the other players, 21.\nWhen is the hand calculated? After each card.\nWhere? Why? Never mind those two.</p>\n<p>So, we need a player object which is the same - in real life the dealer has a few rules - but they're essentially the same.\nWinning is actually calculated after all the players have played their hands and the dealer finishes theirs - so we have a set method of playing.\nCalculating the hand should be done after a card is given, so we will put the logic for that into the <code>Player.hit()</code> function.</p>\n<p>Okay, with this design, we need a Player object, that can hit (and stand), can calculate, can track tokens obviously. What else? Well, as Player and Dealer are going to be the same but different, we need some way to know who is the dealer and who isn't.</p>\n<pre><code>class Player:\n def __init__(self, name, tokens, is_dealer=None):\n self._name, self._tokens = name, tokens\n self._cards = []\n self._hand_value = 0\n self._is_dealer = True if is_dealer else False\n self._has_busted = False\n</code></pre>\n<p>That looks pretty good. We have what we needed, and added a property if they've busted.</p>\n<p>Now, let's add the <code>.hit()</code> function - when we hit, we're given a new card, we calculate our hand value, and let's set our busted flag if we exceed 21:</p>\n<pre><code>def hit(self, card):\n self._cards.append(card)\n self._hand_value = self._calc_hand_value()\n\n if self._hand_value &gt; 21:\n self._has_busted = True\n</code></pre>\n<p>We need a calculate function, the <code>._calc_hand_value()</code> -</p>\n<pre><code>def _calc_hand_value(self):\n total = 0\n for card in self._cards:\n is_numeric = str(card.rank).isnumeric()\n if is_numeric:\n total += card.rank\n else:\n if card.rank in (&quot;J&quot;, &quot;Q&quot;, &quot;K&quot;):\n total += 10\n for card in self._cards:\n if card.rank == &quot;A&quot;:\n total += 11 if total + 11 &lt;= 21 else 1\n return total\n</code></pre>\n<p>We know that the number cards and the face cards have static values, with the Ace card being variable. So, we calculate the value of Ace after the other cards.\nAdmittedly there is lots more optimisation we can perform in this function, but for this, it's fine.</p>\n<p>But what about code that the dealer has, which the player doesn't? Primarily this comes down to the hidden card when looking at the hand.\nSo, if we need to change the output, let's add a local variable <code>current_cards</code> and loop through them, hiding the first card if the player is a dealer:</p>\n<pre><code> def show_cards(self):\n current_cards = []\n\n for card in self._cards:\n if self._is_dealer:\n if not current_cards:\n current_cards.append(&quot;_&quot;)\n continue\n current_cards.append(str(card))\n print(f&quot;{self._name} currently has cards: {current_cards}&quot;)\n</code></pre>\n<p>Which raises the point, when the dealer flips over his card - the other players are already finished with their hands. So we need a way to revert the dealer back into a player, to use all the standard logic.</p>\n<pre><code> @property\n def is_dealer(self):\n return self._is_dealer\n\n @is_dealer.setter\n def is_dealer(self, value):\n if self._is_dealer and value == False:\n print(&quot;Dealer flips over his hidden card&quot;)\n self._is_dealer = value\n \n</code></pre>\n<p>Here we have the &quot;is this player a dealer?&quot; property, and the &quot;switch dealer to player&quot; setter.\nAdmittedly, you could design a <code>class Player(Gambler):</code> and a <code>class Dealer(Gambler):</code> to both inherit the parent class <code>Gambler</code> - but I'll leave that up to you (for when you create AI players).</p>\n<p>Now, during the game, when we set the dealer to:</p>\n<pre><code>dealer.is_dealer = False\ndealer.show_cards()\n</code></pre>\n<p>the dealer will &quot;flip over the hidden card&quot; and play out the hand like a regular player with the same logic.\nThis is another design issue - when making games - it's important that as much behavior reuses code - except when it's very different. Such as Fighter(Character) and Mage(Character) all using <code>.walk()</code> and <code>.run()</code> from <code>Character</code>. When unique behavior is necessary, those should only appear in the <code>Fighter</code> or <code>Mage</code> objects. In this Blackjack instance, only a single flag differentiates a player from a dealer.\nThe benefit is all the actions are the same, and if any bugs are there, they will appear quickly.</p>\n<h2>Status</h2>\n<p>This is getting rather long, so here we will give a quick status.</p>\n<p>We've covered the points raised in <em>Master deck</em>, <em>Deck Setup</em>, <em>Pick Cards</em>, and <em>Printing card status</em>.</p>\n<p>Next steps are Determining Winning hand, Betting Phase, Player dealing, Dealer dealing.</p>\n<h2>Betting &amp; Determining the Winning Hand</h2>\n<p>Betting consists of asking how many tokens the player wishes to wager, and upon winning, return double, upon losing, return zero - but we also have the scenarios of drawing - both player and dealer having the same - or both busting.</p>\n<p>When we have multiple outcomes - you cannot use True or False. Boolean is for only a single outcome, yes, or no.</p>\n<pre><code> from enum import Enum, auto\n\n class Outcome(Enum):\n Dealer = auto()\n Player = auto()\n Draw = auto()\n Unknown = auto()\n</code></pre>\n<p>The Unknown scenario isn't YAGNI (You Ain't Gonna Need It), there were situations after adjusting your code where the outcome was indeterminate. Hence, it's been left in for that random cosmic ray flipping memory bits (even though I'm pretty sure all the outcomes are now covered).\nThe winning hand is classified here from the status in both player/dealer objects.</p>\n<pre><code> print(&quot;\\nFinal Game State: &quot;)\n print_game_state(player, dealer)\n if dealer.has_busted and player.has_busted:\n print(&quot;\\t\\t\\t\\tBoth Dealer and Player lost. Returning initial bet&quot;)\n return Outcome.Draw\n if dealer.has_busted:\n print(&quot;\\t\\t\\t\\tDealer Busted&quot;)\n return Outcome.Player\n if player.has_busted:\n print(&quot;\\t\\t\\t\\tPlayer busted&quot;)\n return Outcome.Dealer\n if player.hand_value &gt; dealer.hand_value:\n print(&quot;\\t\\t\\t\\tPlayer beats dealer&quot;)\n return Outcome.Player\n if dealer.hand_value &gt; player.hand_value:\n print(&quot;\\t\\t\\t\\tDealer beat the Player&quot;)\n return Outcome.Dealer\n if player.hand_value == dealer.hand_value:\n print(&quot;\\t\\t\\t\\tDealer draws the Player. Returning initial bet&quot;)\n return Outcome.Draw\n\n print(&quot;\\t\\t\\t\\t?Unknown scenario?&quot;)\n return Outcome.Unknown\n</code></pre>\n<p>Now, onto the betting. Let's address user input firstly. We know that there are limited inputs, hit, stand, quit, token amount. Let's put these parameters into the choice function and get a value returned.</p>\n<pre><code>def show_menu_in_game(tokens):\n separator()\n print(f&quot;Your currently have {tokens} tokens remaining.&quot;)\n print(&quot;1. Play another hand&quot;)\n print(&quot;q. Exit to Main Menu&quot;)\n\n....\n\nshow_menu_in_game(tokens)\nchoice = get_user_choice([1, &quot;q&quot;])\nif choice == &quot;q&quot;:\n do_play = False\n\n....\n\ndef get_bet_amount(tokens):\n print(f&quot;How many tokens do you want to bet for this game of Blackjack? 1-{tokens}&quot;)\n return get_user_choice(range(1, tokens + 1), f&quot;between 1 and {tokens}&quot;)\n\ndef get_user_choice(params, display_params=&quot;&quot;):\n is_a_valid_choice = False\n if display_params == &quot;&quot;:\n display_params = params\n while not is_a_valid_choice:\n choice = input(f&quot;\\nPlease select a choice ({display_params}): &quot;)\n if choice.isalpha():\n choice = choice.lower()\n if choice.isnumeric():\n choice = int(choice)\n if choice in params:\n return choice\n\n print(f&quot;That's unfortunately not a selection you can make. Please select one of these: {display_params}&quot;)\n</code></pre>\n<p>Admittedly we don't do anything with <code>is_a_valid_choice</code> - but it does make it clearer to the reader that we're going to continue to loop until the user selects only what is possible.</p>\n<h2>Dealer/Player Dealing</h2>\n<p>I've not bothered to optimise the start of the game (it's not pretty):</p>\n<pre><code>def get_game_result(tokens):\n deck = BlackjackDeck()\n cards = deck.deal()\n player = Player(&quot;Player&quot;, tokens)\n dealer = Player(&quot;Dealer&quot;, 999, True)\n player.hit(next(cards))\n player.hit(next(cards))\n dealer.hit(next(cards))\n dealer.hit(next(cards))\n\n print_game_state(player, dealer)\n print(f&quot;Player's hand calculates to {player.hand_value}&quot;)\n</code></pre>\n<p>But if I was going to make it cleaner, there would be a list of players chosen from the menu (Human, AI, Dealer) and passed into the game function. From that, loop over each and allocate 2 cards from the deck.</p>\n<p>The player phase is much longer than the dealer, due to the inputs, so let's just look at the dealer:</p>\n<pre><code>from time import sleep\n\nif dealer.hand_value &lt; 17:\n playing = True\n while playing:\n print(&quot;Dealer takes another card...&quot;)\n sleep(2)\n dealer.hit(next(cards))\n dealer.show_cards()\n print(f&quot;Dealer's hand calculates to {dealer.hand_value}&quot;)\n\n if dealer.hand_value &gt; 21:\n playing = False\n print(f&quot;Dealer Busted with {dealer.hand_value}&quot;)\n else:\n if 17 &lt;= dealer.hand_value &lt;= 21:\n print(f&quot;Dealer stands according to the rules with {dealer.hand_value}&quot;)\n playing = False\n</code></pre>\n<p>Most casinos have rule that the dealer must hit on a certain value or less to keep the game interesting. I consulted Wikipedia and took the most discussed value, 17.</p>\n<p>Adding the time pauses in, gave it a little more excitement.</p>\n<p>Well, that covers the issues which jumped out at me - and through class objects and their methods being used, demonstrating how to perform other functionality such as hand calculations to reduce chunks of coding.</p>\n<p>I haven't pasted my whole rewrite of your code intentionally, because the last few pieces are reasonably easy to finish off, but I'm happy to answer questions if you do attempt this exercise.</p>\n<p>Keep coding!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T22:45:11.643", "Id": "267642", "ParentId": "266179", "Score": "1" } } ]
{ "AcceptedAnswerId": "267642", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:36:20.630", "Id": "266179", "Score": "5", "Tags": [ "python", "python-3.x", "playing-cards" ], "Title": "Text Based Blackjack" }
266179
<p>So I have done a little program where the goal is trying to teach some cars (red and blue rectangles) to &quot;drive&quot; through genetic algorithm. It works well and I haven't seen any bugs, but the program is painfully slow. As I am pretty much a begginner, I am sure there are tons of things that could be improved.</p> <p>The cars can either stay straight or turn right/left 1 degree. If they touch a black line (called death_lines in the program) they &quot;die&quot;. The collision detection is according to whether the two diagonals of the rectangle/car touch a certain line.</p> <p>The cars are defined by three points and an angle. The blue cars are the ones who did the best in the previous generation.</p> <p>The fitness funtion is calculated according to how many green lines (called checkpoints in the program) the car passed and the distance to the center of the next chekpoint. The part of the neural networks are, well, like most neural network. But I did it from scratch, so any improvement would also be greatly apreciated.</p> <p>These is more or less the whole program described, the rest should be understandable on its own. Please feel free to ask any doubth about the program. I want to specify that I thought of using batches, but it would slow down the process and the whole point of this is to make it as quick as possible. One thing I already added was to take decissions only half of the time, and the other half using the decission made previously.</p> <p>Here is the code (uses the Python 3 and the Pygame library):</p> <p>main.py:</p> <pre class="lang-py prettyprint-override"><code>import pygame import random from neuron import Population from car import Car def sortBests(elem): return elem[1] class Population_cars: def __init__(self, PopNumber,id=0,prevBest=[]): self.id=id self.initialnumber=PopNumber self.still_alive=PopNumber self.actual_score=0 self.death_records=[] self.death_lines=[ [[200, 100], [600, 100],[900, 300],[850, 600],[560, 340],[250, 340],[250,390],[480,390],[500,530],[520,350],[850, 610]], [[200, 250], [600, 250],[750, 300],[750, 400],[600, 290],[200, 290],[200,460],[400,460],[520,650],[560,450],[850, 650]] ] self.checkpoints=[[self.death_lines[0][i],self.death_lines[1][i]] for i in range(len(self.death_lines[0]))] self.brains= Population(PopNumber,[5,4,4,3],prevBest) self.population=[] for i in range(PopNumber): self.population.append(Car(self.brains.population[i])) while True: self.actual_score+=1 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() self.draw() deleted=0 for i in range(len(self.population)): car=self.population[i-deleted] car.advance_car() car.takeDecision(self.death_lines) if car.detectCollision(self.death_lines,self.checkpoints): self.death_records.append((car.brain,car.fitness(self.checkpoints))) self.still_alive-=1 self.population.pop(i-deleted) deleted+=1 if self.still_alive==0: self.nextGeneration() pygame.display.flip() def draw(self, color_car=(255, 0, 0)): global screen screen.fill((255, 255, 255)) for car in self.population: if not car.isAlive: continue full_car = car.positions.copy() last_x = full_car[2][0] + (full_car[0][0] - full_car[1][0]) last_y = full_car[2][1] + (full_car[0][1] - full_car[1][1]) full_car.append([last_x, last_y]) pygame.draw.polygon(screen, color_car, full_car, 0) #pygame.draw.circle(screen,[0,0,0],tuple(map(int,car.getCenter())),100,1) for death_line in self.death_lines: for i in range(len(death_line) - 1): pygame.draw.line(screen, [0, 0, 0], death_line[i], death_line[i+1], 3) for check_line in self.checkpoints: pygame.draw.line(screen, [100, 200, 100], check_line[0], check_line[1], 1) def nextGeneration(self): global pop self.death_records.sort(key=sortBests) thisBests = self.death_records[-5:] print(thisBests) pop=Population_cars(self.initialnumber,self.id+1,thisBests) # -------------------------------------------------------------------------------------------------- WINDOW_WIDTH = 1500 WINDOW_HEIGHT = 750 WINDOW_SIZE = [WINDOW_WIDTH, WINDOW_HEIGHT] pygame.init() screen = pygame.display.set_mode(WINDOW_SIZE) pygame.display.set_caption(&quot;Car AI&quot;) pop=Population_cars(100) </code></pre> <p>car.py:</p> <pre class="lang-py prettyprint-override"><code>import math def ccw(A, B, C): return (C[1] - A[1]) * (B[0] - A[0]) &gt; (B[1] - A[1]) * (C[0] - A[0]) def intersect(A, B, C, D): return ccw(A, C, D) != ccw(B, C, D) and ccw(A, B, C) != ccw(A, B, D) def point_intersect(A, B, C, D): first_vector = (B[0] - A[0], B[1] - A[1]) second_vector = (D[0] - C[0], D[1] - C[1]) dist_x = (A[0] - C[0]) / (second_vector[0] - first_vector[0]) dist_y = (A[1] - C[1]) / (second_vector[1] - first_vector[1]) x = A[0] + first_vector[0] * dist_x y = A[1] + first_vector[1] * dist_y return (x, y) def dist_intersect(A, B, C, D,reach): if not intersect(A,B,C,D): #print(&quot;flag&quot;,A,B,C,D) return 1 first_vector = (B[0] - A[0], B[1] - A[1]) second_vector = (D[0] - C[0], D[1] - C[1]) dist_x = (A[0] - C[0]) / (second_vector[0] - first_vector[0]) dist_y = (A[1] - C[1]) / (second_vector[1] - first_vector[1]) x = first_vector[0] * dist_x y = first_vector[1] * dist_y output = (x**2+y**2)**0.5 return 1-output/reach-0.1 class Car: def __init__(self,brain): #self.positions=[[300, 300], [300, 360], [320, 360]] #self.positions=[[200, 160], [200, 220], [220, 220]] self.positions=[[260, 160], [260, 180], [200, 180]] self.angle=0 self.isAlive=True self.brain=brain self.checkpoints_passed=1 def getCenter(self): return [(self.positions[0][0] + self.positions[2][0]) / 2, (self.positions[0][1] + self.positions[2][1]) / 2] def advance_car(self, speed=1): advance_x = math.cos(math.radians(self.angle)) advance_y = math.sin(math.radians(self.angle)) # print(angle,advance_x,advance_y) for point in self.positions: point[0] += advance_x * speed point[1] -= advance_y * speed def turn_car(self,turn): self.angle-=turn center = self.getCenter() for i in self.positions: i[0] -= center[0] i[1] -= center[1] i[0] = i[0] * math.cos(math.radians(turn)) - i[1] * math.sin(math.radians(turn)) i[1] = i[0] * math.sin(math.radians(turn)) + i[1] * math.cos(math.radians(turn)) i[0] += center[0] i[1] += center[1] def detectCollision(self, death_lines, checklines): last_x = self.positions[2][0] + (self.positions[0][0] - self.positions[1][0]) last_y = self.positions[2][1] + (self.positions[0][1] - self.positions[1][1]) nextCheck=checklines[self.checkpoints_passed] if intersect(self.positions[0], self.positions[2], nextCheck[0], nextCheck[1]) or intersect(self.positions[1], (last_x,last_y), nextCheck[0], nextCheck[1]): self.checkpoints_passed+=1 for death_line in death_lines: if self.checkpoints_passed&gt;1: intersect_prev=intersect(self.positions[0], self.positions[1], death_line[self.checkpoints_passed-2], death_line[self.checkpoints_passed-1]) or intersect(self.positions[2], (last_x,last_y), death_line[self.checkpoints_passed-2], death_line[self.checkpoints_passed-1]) else: intersect_prev=False intersect_next=intersect(self.positions[0], self.positions[1], death_line[self.checkpoints_passed-1], death_line[self.checkpoints_passed]) or intersect(self.positions[2], (last_x,last_y), death_line[self.checkpoints_passed-1], death_line[self.checkpoints_passed]) if intersect_next or intersect_prev: self.isAlive=False self.deathPoint=self.positions[0] return True return False def range_points(self,leng): center=self.getCenter() output=[] for i in range(-2,3): ang=self.angle+i*30 x,y=math.cos(math.radians(ang))*leng , math.sin(math.radians(ang))*leng output.append((int(center[0]+x),int(center[1]-y))) return output def collision_distances(self,death_lines,reach): center=self.getCenter() #print(self.range_points()) out=[] for A in self.range_points(reach): add=1 for death_line in death_lines: for i in range(len(death_line)-1): add=min(add,dist_intersect(A,center,death_line[i],death_line[i+1],reach)) out.append(add) return out def takeDecision(self,death_lines=None,reach=100): data=self.collision_distances(death_lines,reach) decision=self.getMaxResult(self.brain.feedAll(data)) if decision==1: self.turn_car(1) elif decision==2: self.turn_car(-1) def fitness(self,checkpoints): line_to_reach=checkpoints[self.checkpoints_passed] point_to_reach=((line_to_reach[0][0]+line_to_reach[1][0])/2,(line_to_reach[0][1]+line_to_reach[1][1])/2) distance_to_point=((point_to_reach[0]-self.deathPoint[0])**2+(point_to_reach[1]-self.deathPoint[1])**2)**0.5 #print(self.checkpoints_passed , distance_to_point, (self.checkpoints_passed*10)**2-distance_to_point*10) return (self.checkpoints_passed*1000)-distance_to_point def getMaxResult(self,results): return results.index(max(results)) </code></pre> <p>neuron.py:</p> <pre class="lang-py prettyprint-override"><code>import random import math import copy &quot;&quot;&quot; def sigmoid(x): return .5 * (math.tanh(.5 * x) + 1)&quot;&quot;&quot; def sigmoid(x): if x&lt;-100: return 0 if x&gt;100: return 1 return 1 / (1 + math.exp(-4.9*x)) class Neuron: def __init__(self,num_outputs, neuronindex,weights=[]): self.outputWeights=[] self.neuronIndex= neuronindex for i in range(num_outputs): if i&lt;len(weights): self.outputWeights.append(weights[i]) else: self.outputWeights.append(random.uniform(-1,1)) def getOutputWeight(self,i): return self.outputWeights[i] def getOutputFromInputs(self,inputs,inputWeights): output=0 for i in range(len(inputWeights)): output+=inputs[i]*inputWeights[i] if output&lt;-200: print(inputs,inputWeights) return sigmoid(output) class Net: def __init__(self,topology=[],model=False): self.topolgy = topology if model!=False: self.layers=model.layers.copy() else: self.layers=[] for i in range(len(topology)-1): layer=[] numOutputs=topology[i+1] for neuronNum in range(topology[i]): layer.append(Neuron(numOutputs,neuronNum)) self.layers.append(layer) layer = [] for i in range(topology[-1]): layer.append(Neuron(0,i)) self.layers.append(layer) def feedLayer(self,inputs,layerNum): layer=self.layers[layerNum] outputs=[] for i in range(len(layer)): neuronWeights=[] for a in self.layers[layerNum-1]: neuronWeights.append(a.getOutputWeight(i)) outputs.append(layer[i].getOutputFromInputs(inputs,neuronWeights)) return outputs def feedAll(self,inputs): prevOutputs=inputs.copy() for i in range(1,len(self.layers)): prevOutputs=self.feedLayer(prevOutputs,i) return prevOutputs class Population: def __init__(self,PopNumber,topology=[],bestResults=[]): self.topology=topology if len(bestResults)&gt;=1: self.population=[] for i,score in bestResults: self.population.append(copy.deepcopy(i)) prev_brains=[item[0] for item in bestResults] prev_results=[item[1] for item in bestResults] num_mutate=PopNumber-len(bestResults) random_chosen=random.choices(population=prev_brains, weights=prev_results, k=num_mutate) for addNet in random_chosen: mutation = self.mutate(addNet) self.population.append(mutation) for i in range(PopNumber-num_mutate-len(bestResults)): combination=self.combine(random.sample(bestResults, 2)) self.population.append(combination) else: self.population=[] for i in range(PopNumber): self.population.append(Net(self.topology)) def choose(self,options): output=[] numChosen=random.randint(1,len(options)) for i in range(numChosen): output.append(options[random.randint(0,len(options)-1)]) return output def combine(self,chosen): output= copy.deepcopy(chosen[0]) for layer in range(len(output.layers)-1): for neuron in range(len(output.layers[layer])): for weight in range(self.topology[layer+1]): if random.randint(0,10)&gt;=5: output.layers[layer][neuron].outputWeights[weight]=copy.copy(chosen[1].layers[layer][neuron].outputWeights[weight]) return output def mutate(self,chosen): output=copy.deepcopy(chosen) for layer in output.layers[:-1]: for neuron in layer: for weight in range(len(neuron.outputWeights)): rand=random.randint(1,10) if rand==1: neuron.outputWeights[weight]=random.uniform(-1,1) else: neuron.outputWeights[weight] += random.gauss(0,1)/50 if neuron.outputWeights[weight]&gt;1: neuron.outputWeights[weight]=1 elif neuron.outputWeights[weight]&lt;-1: neuron.outputWeights[weight]=1 return output <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T23:28:04.357", "Id": "527790", "Score": "0", "body": "In your testing, do the red cars ever make it around the bottom-most turn?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T16:05:29.893", "Id": "527844", "Score": "0", "body": "No, they didn’t. I thought it was just a matter of leaving it for long. Precisely I thought it would be useful to optimize it first before adding more circuits or more complex ones." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T20:44:27.447", "Id": "266180", "Score": "2", "Tags": [ "python", "performance", "genetic-algorithm" ], "Title": "AI learning to drive (simplistic) needing optimisation" }
266180
<p>I am currently creating a Java console program for a text-based Monopoly game as a personal project. Since this is my first project that I have worked on, I would like to know what kind of object oriented programming principles and designs that I am not following. Specifically, I am wondering if I am not creating enough classes to separate functions of the program.</p> <p>There are quite a few classes so I will show the most important ones here but also link to the GitHub page.</p> <pre><code>import java.util.ArrayList; import java.util.Collections; public class Player { private final String name; public boolean inJail = false; public int turnsInJail = 0; private int position; private int money = 1500; private int numUtilities = 0; private int numRailroads = 0; private ArrayList&lt;Property&gt; properties = new ArrayList&lt;Property&gt;(); public Player(String name){ this.name = name; position = 0; } public int getPosition() { return position; } public String getName() { return name; } public int getMoney() { return money; } public void addMoney(int addMoney){ this.money += addMoney; } public void pay(Player receiving, int amount){ receiving.addMoney(amount); addMoney(-amount); } public void move(int numSquares, Board board){ position += numSquares; //if pass GO if(position &gt;= 40){ System.out.println(name + &quot; passed GO and collected $200&quot;); money += 200; position %= 40; } System.out.println(&quot;Landed on &quot; + board.getCurrentSquare(this)); board.getCurrentSquare(this).doAction(this); } public void moveTo(int position){ this.position = position; } //add property to Player's properties public void buy(Property property){ addMoney(-property.getPrice()); properties.add(property); sortPropertiesByGroup(properties); } private void sortPropertiesByGroup(ArrayList&lt;Property&gt; properties){ ArrayList&lt;Utility&gt; utilities = new ArrayList&lt;&gt;(); ArrayList&lt;Railroad&gt; railroads = new ArrayList&lt;&gt;(); ArrayList&lt;Property&gt; sorted = new ArrayList&lt;&gt;(); for(Property property : properties){ if(property instanceof Utility){ utilities.add((Utility) property); } else if(property instanceof Railroad){ railroads.add((Railroad) property); } else { sorted.add(property); } } Collections.sort(utilities); Collections.sort(railroads); Collections.sort(sorted); sorted.addAll(railroads); sorted.addAll(utilities); } public void listProperties(){ if(properties.isEmpty()){ System.out.println(&quot;You do not own any properties&quot;); } for(Property property : properties){ System.out.println(property); } } public int getNumRailroads(){ int numRailroads = 0; for(Property p : properties){ if(p instanceof Railroad){ numRailroads++; } } return numRailroads; } public int getNumUtilities(){ int numUtilities = 0; for(Property p : properties){ if(p instanceof Utility){ numUtilities++; } } return numUtilities; } //returns list of all properties that Player owns color group public ArrayList&lt;ColorProperty&gt; getOwnColorGroupList(){ ArrayList&lt;ColorProperty&gt; list = new ArrayList&lt;&gt;(); for(Property property: properties){ if(property instanceof ColorProperty &amp;&amp; ownsGroup(((ColorProperty) property).getGroup())){ list.add((ColorProperty) property); } } return list; } //return list of all properties that Player can place house public ArrayList&lt;ColorProperty&gt; getHouseableProperties(){ ArrayList&lt;ColorProperty&gt; houseable = new ArrayList&lt;&gt;(); for(ColorProperty i : getOwnColorGroupList()){ boolean lowestHouses = true; for(ColorProperty j : getOwnColorGroupList()){ if(i.getGroup() == j.getGroup() &amp;&amp; i.getNumHouses() &gt; j.getNumHouses()){ lowestHouses = false; } } if(lowestHouses &amp;&amp; i.getNumHouses() != 5){ houseable.add(i); } } return houseable; } //check if property is in Player's properties private boolean owns(Property property){ return properties.contains(property); } //check if Player owns all of a certain color group public boolean ownsGroup(ColorProperty.Group group){ int count = 0; for(Property property : properties){ if(property instanceof ColorProperty &amp;&amp; ((ColorProperty) property).getGroup() == group){ count++; } } return (count == group.maxInGroup); } } </code></pre> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Game { private Jail jail = new Jail(this); private Dice dice = new Dice(); private final Board board = new Board(jail, dice); private ArrayList&lt;Player&gt; players = new ArrayList&lt;Player&gt;(); public void startGame(int numPlayers){ for(int i = 1; i &lt;= numPlayers; i++){ System.out.print(&quot;Player &quot; + i + &quot; name: &quot;); players.add(new Player(Input.read())); } turn(players.get(0)); } //pass turn to next Player public void turn(Player currentPlayer){ System.out.println(&quot;\n&quot; + currentPlayer.getName() + &quot;'s turn!\nMoney: $&quot; + currentPlayer.getMoney()); if(currentPlayer.inJail){ //if player doesn't escape jail on turn, skips to showOptions if(!jail.jailTurn(currentPlayer, dice, board)) { showOptions(currentPlayer); } } else { //if player is not in jail System.out.println(&quot;Position: &quot; + board.getCurrentSquare(currentPlayer)); int numDoubles = 0; do{ currentPlayer.move(dice.roll(), board); numDoubles++; if(numDoubles == 3){ jail.sendToJail(currentPlayer); } } while (numDoubles &lt; 3 &amp;&amp; dice.isDouble()); } showOptions(currentPlayer); } public void endTurn(Player currentPlayer){ int currentIndex = players.indexOf(currentPlayer); if(currentIndex + 1 == players.size()){ turn(players.get(0)); } else { turn(players.get(currentIndex + 1)); } } //player options after roll and land on a square private void showOptions(Player currentPlayer){ List&lt;PlayerOption&gt; options = Arrays.asList( new ListPropertiesOption(currentPlayer), new BuyHouseOption(currentPlayer), new EndTurnOption(this, currentPlayer) ); PlayerOption selectedOption = (PlayerOption) Input.selectOptions(options, &quot;Additional Actions:&quot;); selectedOption.action(); showOptions(currentPlayer); //when player does not select end turn } } </code></pre> <pre><code>public abstract class Property extends Square { private final int price; private final int rent; protected Player owner = null; public Property(String name, int price, int rent){ super(name); this.price = price; this.rent = rent; } public Player getOwner() { return owner; } public int getPrice(){ return price; } public int getRent(){ return rent; } public void offerBuy(Player currentPlayer){ System.out.println(&quot;Would you like to buy &quot; + name + &quot; for $&quot; + price + &quot;?&quot;); String response = Input.read().toLowerCase(); if(response.contains(&quot;y&quot;)){ currentPlayer.buy(this); owner = currentPlayer; } } @Override public void doAction(Player currentPlayer) { if(currentPlayer == owner); //square is owned by the currentPlayer else if(owner != null) { //square is owned by someone else System.out.println(currentPlayer.getName() + &quot; paid &quot; + owner.getName() + &quot; $&quot; + getRent() + &quot; in rent&quot;); currentPlayer.pay(owner, getRent()); } else { //square can be bought offerBuy(currentPlayer); } } } </code></pre> <p><a href="https://github.com/Dex-Max/Monopoly" rel="noreferrer">https://github.com/Dex-Max/Monopoly</a></p>
[]
[ { "body": "<p>Kudos for this decent-sized, non-trivial project. The general code quality is pretty good. Still, I have some suggestions for what could be done better, in my opinion.</p>\n<p>I will base my code review on the GitHub repository at this commit hash: 2a8709d</p>\n<p>I will make the suggestions for the first occurrence, but some may apply to multiple places.</p>\n<hr />\n<blockquote>\n<p>Specifically, I am wondering if I am not creating enough classes to separate functions of the program.</p>\n</blockquote>\n<p>The number of classes looks good to me, and also the size of each class. However, in my opinion the responsibilites of the classes could be separated a bit better. I will get to that.</p>\n<hr />\n<h2>Monopoly.java</h2>\n<p><strong>Dependencies</strong></p>\n<p>The main method contains this code:</p>\n<pre><code>Dice dice = new Dice();\nJail jail = new Jail();\nArrayList&lt;Player&gt; players = createPlayers(2);\nBoard board = new Board(jail, dice, players);\n\nGame game = new Game(jail, dice, board, players);\njail.setGame(game);\n</code></pre>\n<p>I like that you are injecting the dependencies (<code>dice</code>, <code>jail</code> and <code>players</code>) into the constructors of <code>Game</code> and <code>Board</code>. However, you are injecting almost the same dependencies into both <code>Board</code> and <code>Game</code>, which makes me think: Maybe they are both doing similar things. Whatever it is for which the game needs references to those objects, maybe the <code>Game</code> could just tell the <code>Board</code> to do it instead. We will see when we get to those classes.</p>\n<p>Looking at the last 2 lines, the <code>Game</code> and the <code>Jail</code> directly depend on each other. Both instances hold a reference to the other one. If the <code>Jail</code> requires the <code>Game</code> for anything, maybe the <code>Game</code> could pass itself, or even just a callback method, as an argument when calling a method on <code>Jail</code>, instead of requiring a reference from the start. It also makes sure it is always in a consistent state, because the compiler enforces that you pass a <code>Jail</code> into the constructor of <code>Game</code>, but one might easily forget that <code>jail.setGame(game)</code> must be called, and the errors that would occur later on if you forgot it would not directly indicate what is missing.</p>\n<p>In both cases, I would recommend to try to keep the dependencies of each class to a minimum, and to keep dependencies one-directional (i. e. A depends on B, but not the other way around), because otherwise the risk of spaghetti code might increase.</p>\n<p><strong>Access modifiers and interfaces</strong></p>\n<pre><code>static ArrayList&lt;Player&gt; createPlayers(int numPlayers){\n</code></pre>\n<p>Each member (e. g. methods, fields etc.) should have the most restrictive access modifier possible. In this case, <code>private static ...</code> would be appropriate, to prevent unwanted method calls from other parts of the code which might lead to bugs.</p>\n<p>For collections, like the <code>ArrayList</code> in this case, it is good practice to use the most abstract applicable type, and to prefer interfaces over concrete class types for return values. In this case, you could declare the return type as <code>List&lt;Player&gt;</code>, and still return an <code>ArrayList&lt;Player</code>. This is even more important for public methods, but in any case it can greatly increase the flexibility of your code, because you can simply change the implementation of the method (and the returned type) without needing to change other parts of the code base which depend on that method.</p>\n<p><strong>Formatting/whitespace</strong></p>\n<pre><code>for(int i = 1; i &lt;= numPlayers; i++){\n</code></pre>\n<p>The whitespace around the braces and parentheses is unconventional. At least it is consistent throughout the code base (as far as I've seen), but I would recommend having a look at an &quot;official&quot; style guide (e. g. from Oracle, or <a href=\"https://google.github.io/styleguide/javaguide.html#s4.6.2-horizontal-whitespace\" rel=\"noreferrer\">this one from Google</a>), and following it even if personal preferences might vary in some cases. Even if you are working alone on your own project, it will make it easier for yourself if your code looks like other peoples' code.</p>\n<p><strong>Nested method calls</strong></p>\n<pre><code>players.add(new Player(Input.read()));\n</code></pre>\n<p>The more method calls are nested on a single line, the harder to read it becomes. Just like the computer uses a stack for those method calls, you will have to put them on your &quot;mental stack&quot; when reading the code. The reader's thoughts while reading that line might be similar to &quot;So I add a player, but first I need to create a new player, for that I need to read the input to get the player's name ... and then what do I do with it again?&quot;.</p>\n<p>Instead, I would recommend writing the code in a more &quot;linear&quot; way, i. e. the way you would also read a story, top to bottom, e. g.:</p>\n<pre><code>String playerName = Input.read();\nPlayer player = new Player(playerName);\nplayers.add(player);\n</code></pre>\n<p>It's slightly longer, but each line only does one thing, and you never have to jump back and forth while reading it. You can also consider creating a separate method for those lines, e. g. <code>createPlayer</code>, considering that this is called within the method <code>createPlayers</code>.</p>\n<hr />\n<h2>Board.java</h2>\n<p><strong>Public fields</strong></p>\n<pre><code>public Jail jail;\npublic Dice dice;\npublic ArrayList&lt;Player&gt; players;\n</code></pre>\n<p>Fields (i. e. instance variables) should not be public, since it exposes details of the class's implementation and makes it very difficult to change it if other classes are already depending on them. So those fields should ideally be private, and <em>if</em> you need to allow other classes to access those, it would be better to use a public getter method instead, but that should also be considered twice and avoided if possible.</p>\n<p><strong>Final</strong></p>\n<pre><code>private final Square[] board = new Square[40];\nprivate Deck communityChest = new Deck();\nprivate Deck chance = new Deck();\n</code></pre>\n<p>Some of the fields, in this and other classes, are declared as final, but some that seem like they could also be final are not. I would recommend using final (at least for fields) whenever possible, and rather removing it consciously if something should be non-final. This way you can prevent unwanted changes, and it also communicates that they should not and don't need to be reassigned.</p>\n<p><strong>Responsibilites</strong></p>\n<p>The <code>Board</code> creates the Community Chest and Chance cards. This seems to be a responsibility of the card decks. I would suggest making <code>Deck</code> an interface, and creating two implementations, <code>CommunityChestDeck</code> and <code>ChanceDeck</code>, which both create their own cards.</p>\n<hr />\n<pre><code>public Square getCurrentSquare(Player player){\n return getSquareAt(player.getPosition());\n}\n</code></pre>\n<p>There is a lot of back and forth in these 2 lines of code. The board is asked for the square on which the player is standing, but for that it needs to know from the player at which position they are standing. Whenever classes depend on each other like that, it can become very difficult to change the code without having to change it many places. It would be much simpler to just do <code>getCurrentSquare(int position)</code>. Instead, I would recommend removing the position from the player, and only letting the board know where each player stands. Then, <code>getCurrentSquare(Player player)</code> can look up the position of this player by itself. Alternatively, I would consider simply removing the method, since <code>getSquareAt(int position)</code> is also public and can directly be called with the player's position.</p>\n<p><strong>Naming</strong></p>\n<pre><code>private final Square[] board = new Square[40];\n</code></pre>\n<p>This array named <code>board</code> exists inside of the class <code>Board</code>. This seems counter-intuitive, since the class itself already represents the board. I would suggest renaming it to <code>squares</code>, since that describes exactly what it is.</p>\n<p><strong>Comments</strong></p>\n<pre><code>//creating all squares on the board\nfor(int i = 0; i &lt; 40; i++){\n board[i] = createSquare(i);\n board[i].index = i;\n}\n\n//create community chest/chance deck\nfor(int c = 0; c &lt; 16; c++){\n communityChest.add(createCommunityChestCard(c));\n chance.add(createChanceCard(c));\n}\n</code></pre>\n<p>These comments, each simply describing what a block of code does, could be replaced with methods. Generally, if a for-loop simply does something very simple for each element of a collection (e. g. here <code>createSquare</code>), you can consider creating a method with the plural form (<code>createSquares</code> and <code>createCards</code>), and thus avoid the comment. It will be easier to read, and the constructor here would become much shorter.</p>\n<p>If you implement the methods in a way that they return the array or deck of cards instead of accessing and writing to it, you can even initialize it directly, like this: <code>private final Square[] board = createSquares();</code></p>\n<p><strong>Error handling</strong></p>\n<pre><code>default:\n return null;\n</code></pre>\n<p>This occurs when initializing the cards and squares, in the cases where the index is out of range. I would recommend throwing an <code>IllegalArgumentException</code> instead of returning null, because otherwise you might get a <code>NullPointerException</code> possibly much later, and the cause will be more difficult to find.</p>\n<p><strong>Possible bug</strong></p>\n<pre><code>case 4:\n return new MoveToCard(new int[]{5}, this, &quot;Take a ride on the Reading Railroad&quot;);\ncase 5:\ncase 6:\n return new MoveToCard(new int[]{5, 15, 25, 35}, this, &quot;Advance to nearest Railroad&quot;);\n</code></pre>\n<p>The method <code>createChanceCard</code> contains this piece of code. Case 5 is empty, which might be intended (doing the same as for case 6), but it seems like it may have been forgotten since it is the only empty case of many cases in different methods. If it is intended to do the same as in case 6, it might be better to explicitly do the same (i. e. copy the statement from case 6), or to add a comment.</p>\n<hr />\n<h2>Card.java</h2>\n<p><strong>Consistency</strong></p>\n<pre><code>String text;\n\npublic Card(String message){\n this.text = message;\n}\n</code></pre>\n<p>In one case it is named <code>text</code>, in the other it is named <code>message</code>. I would recommend using the same name in both cases, and <code>message</code> or even <code>description</code> is a bit clearer than <code>text</code> in my opinion.</p>\n<p><strong>Mixing UI and logic</strong></p>\n<pre><code>public void play(Player player){\n doAction(player);\n System.out.println(&quot;You drew: &quot; + text);\n}\n\npublic abstract void doAction(Player player);\n</code></pre>\n<p>I would recommend against outputting text to the player from within an entity like a <code>Card</code>. This seems to be the responsibility of whichever class draws the card. I. e. first you draw it, then you print &quot;You drew: ...&quot;, then you play the card (<code>card.play(player)</code>).</p>\n<p>In case you remove the print statement, I would suggest removing <code>doAction</code> (whose name is very vague), and directly using <code>play</code> as your <code>abstract void</code> method.</p>\n<p><strong>Types</strong></p>\n<p><code>CollectCard</code> declares a field <code>protected Integer amount;</code>. There might be a reason for using <code>Integer</code> which I am missing, but in most cases <code>int</code> should be used, mostly for simplicity, and sometimes also for performance.</p>\n<p><strong>Naming</strong></p>\n<p>It to me a moment to realize what the class <code>CollectEveryCard</code> actually does. It does not &quot;collect every card&quot;, instead it &quot;collects from everyone&quot;. I suggest renaming it to <code>CollectFromEveryoneCard</code> or <code>CollectFromEveryPlayerCard</code>, even if it is slightly longer.</p>\n<p><strong>Non-obvious logic</strong></p>\n<pre><code>int minimumDistance = 40;\n\nfor(int i = 0; i &lt; index.length; i++){\n int distanceToIndex = (40 + index[i] - player.getPosition()) % 40;\n if ((40 + index[i] - player.getPosition()) &lt; minimumDistance) {\n minimumDistance = distanceToIndex;\n }\n}\n\nplayer.move(minimumDistance, board);\n</code></pre>\n<p>This code occurs within the class <code>MoveToCard</code>. It is not immediately obvious what is happening here. It might require a comment to explain it (if the actual algorithm is as complicated as it currently looks), or better, some refactoring to make it more obvious.</p>\n<p>The first step would be to move this code into a private method whose name describes what it does, and to simply call that private method from <code>doAction</code> (if we did not have to override <code>doAction</code>, it would be better to directly rename it instead).</p>\n<p>Contributing to the confusion is that there is an <code>int[]</code> named <code>index</code> defined in this class. Since it is an array of integers, I would assume that it probably should be renamed to <code>indices</code> and that each contained int is an index. However I'm not sure, and might also interpret that the whole array somehow represents an index, although I don't know how it might do that.</p>\n<p>It seems like it moves the player to the closest position out of the given positions. If that is true, then <code>int[] index</code> should probably be named <code>int[] eligibleSquarePositions</code> (and its type should probably be changed to <code>Iterable&lt;int&gt;</code>), and <code>distanceToIndex</code> renamed to <code>distanceToSquare</code>. To make the logic more obvious, you can then extract a method <code>private int minimumDistance(int playerPosition, Iterable&lt;int&gt; squarePositions)</code>.</p>\n<p>There is also a bug: In this line <code>if ((40 + index[i] - player.getPosition()) &lt; minimumDistance)</code> it seems like you forgot the <code>% 40</code> that you did in the line above. This will cause some positions to never be closer than the <code>minimumDistance</code> of 40. What you probably want to do instead is to reuse the calculated distance from above, and do <code>if (distanceToIndex &lt; minimumDistance)</code>.</p>\n<hr />\n<h2>ColorProperty.java</h2>\n<p><strong>Naming</strong></p>\n<pre><code>private int numHouses = 0; //number of houses currently on property\nprivate final int houseCost;\n\n//rent based on number of houses\nprivate final int rent1;\nprivate final int rent2;\nprivate final int rent3;\nprivate final int rent4;\nprivate final int rentH;\n</code></pre>\n<p>The comments already indicate it. These names are not very clear and require additional info in order to be understood. I suggest renaming them like this for clarity:</p>\n<pre><code>private int currentNumberOfHouses = 0;\n\nprivate final int houseCost;\nprivate final int rentWith1House;\nprivate final int rentWith2Houses;\nprivate final int rentWith3Houses;\nprivate final int rentWith4Houses;\nprivate final int rentWithHotel;\n</code></pre>\n<p><strong>Long argument lists</strong></p>\n<pre><code>public ColorProperty(String name, Group group, int price, int rent, int rent1, int rent2, int rent3, int rent4, int rentH){\n</code></pre>\n<p>I would recommend formatting them like this:</p>\n<pre><code>public ColorProperty(\n String name,\n Group group,\n int price,\n int rent,\n // etc.\n){\n</code></pre>\n<p>Generally long argument lists should be avoided, but if they are necessary, then this is usually easier to read.</p>\n<p><strong>Switch statements</strong></p>\n<p>The switch statement in the constructor can be moved to a method <code>private int houseCostByColorGroup(Group group)</code> to keep the constructor short and clean.</p>\n<hr />\n<pre><code>public int getRent() {\n int rent = 0;\n switch(numHouses){\n case 0:\n rent = super.getRent();\n if(getOwner().ownsGroup(group)){\n rent *= 2;\n }\n break;\n case 1:\n rent = rent1;\n break;\n case 2:\n rent = rent2;\n break;\n case 3:\n rent = rent3;\n break;\n case 4:\n rent = rent4;\n break;\n case 5:\n rent = rentH;\n break;\n }\n\n return rent;\n}\n</code></pre>\n<p>This long switch statement can be refactored and simplified by simply returning the value in each case, like this:</p>\n<pre><code>public int getRent() {\n switch(numHouses){\n case 0:\n if (getOwner().ownsGroup(group)) {\n return 2 * super.getRent();\n } else {\n return super.getRent();\n }\n case 1:\n return rent1;\n case 2:\n return rent2;\n case 3:\n return rent3;\n case 4:\n return rent4;\n case 5:\n return rentH;\n default:\n return 0;\n }\n}\n</code></pre>\n<p>This way it is a direct mapping from one value to another value, without having to read the whole method to see if anything else changes it.</p>\n<p>Note that I return 0 in the default case, since that is equivalent to your version, but I would strongly recommend to throw an exception instead, since it is not a valid case, and can only happen in case of a bug.</p>\n<p><strong>Formatting</strong></p>\n<pre><code>public Group getGroup() { return group; }\n\npublic int getNumHouses() { return numHouses; }\n\npublic int getHouseCost() {\n return houseCost;\n}\n</code></pre>\n<p>These methods are not formatted consistently, even though they all do basically the same. I would suggest using the formatting of <code>getHouseCost</code> in all cases.</p>\n<hr />\n<h2>Deck.java</h2>\n<pre><code>//plays top card and puts it on bottom of deck\npublic void playTop(Player player){\n Card topCard = deck.removeFirst();\n add(topCard);\n topCard.play(player);\n}\n\npublic void add(Card card){\n deck.addLast(card);\n}\n</code></pre>\n<p>By directly calling <code>deck.addLast(topCard)</code> instead of <code>add(topCard)</code>, the implementation of <code>playTop</code> becomes clear enough that the comment can be removed. Even as it is now, that very short 3-line method is in my opinion clearer than the comment itself.</p>\n<hr />\n<h2>Game.java</h2>\n<p><strong>Recursion</strong></p>\n<p>It seems like each new turn is a recursive call. This could lead to a stack overflow, and the game crashing, if the game lasts enough rounds. (Maybe the compiler or the JVM optimizes it away, but I wouldn't bet on it.)</p>\n<p>I would suggest looking into how games and game engines implement their so called &quot;game loop&quot;, and using a game loop here as well. In short, you would have an infinite loop as long as your game is running, and process input in each iteration. You might have another infinite loop during a player's turn, which is exited when they choose the <code>EndTurnOption</code>.</p>\n<p><strong>Naming</strong></p>\n<pre><code>//pass turn to next Player\npublic void turn(Player currentPlayer){\n</code></pre>\n<p>This comment indicates that it might be better to rename the method to <code>passTurnToNextPlayer</code> and remove the comment. However, the comment might even be misleading and the name already correct. It seems like this method just executes the current player's turn, and passing it to the next player is actually done in <code>endTurn</code>. I could imagine that the comment was above <code>endTurn</code> some time ago, but wasn't moved when the methods were reordered. This is why comments should generally be avoided, especially if they can be replaced by better names, and in the cases were comments are helpful, they should be maintained with the same diligence as the implementation.</p>\n<p>Better candidates for renaming this method might be <code>executeTurn</code> or <code>playTurn</code>, since turn as a noun is meant, but <code>turn</code> as a verb exists (with a completely different meaning) and in this case a verb would be expected.</p>\n<p><strong>Unnecessary comments</strong></p>\n<pre><code>if(currentPlayer.inJail){ //if player doesn't escape jail on turn, skips to showOptions\n // ...\n} else { //if player is not in jail\n</code></pre>\n<p>These comments don't add any information, they just restate what the code already says. I would suggest simply removing them. However, they might indicate that the code should be refactored and the structure simplified, so you might consider e. g. extracting parts of it to separate methods. For example by extracting 2 methods, the whole thing can be simplified to this:</p>\n<pre><code>if (currentPlayer.inJail) {\n playJailPhase(currentPlayer, dice, board);\n} else {\n playDiceRollPhase(currentPlayer, dice, board);\n}\nshowOptions(currentPlayer);\n</code></pre>\n<hr />\n<pre><code>//player options after roll and land on a square\nprivate void showOptions(Player currentPlayer){\n</code></pre>\n<p>This comment might be true at the moment, but it explains a part of the logic that is defined somewhere else completely. If that changes in the future, the comment will be wrong and misleading. I suggest to simply remove it. The method name is very clear about what it does, and the method should not care about when it is called.</p>\n<hr />\n<pre><code>showOptions(currentPlayer); //when player does not select end turn\n</code></pre>\n<p>This comment is confusing. It is worded like a condition, but the code does not indicate that it contains such a condition. Maybe it tries to explain a piece of code that is defined somewhere else and implied here, or the code already changed and the comment wasn't updated. They way I understand the code, this call <code>showOptions(currentPlayer)</code> always gets executed, even if the player did select &quot;end turn&quot;.</p>\n<hr />\n<h2>Input.java</h2>\n<p><strong>Recursion</strong></p>\n<p><code>selectOptions</code> calls itself whenever the user's input could not be parsed as a number. This could potentially lead to the game crashing if the user inputs invalid text often enough. I would recommend refactoring it to a loop.</p>\n<p><strong>Comments and clarity</strong></p>\n<pre><code>//outputs numbered list of options and returns the selected one\npublic static Object selectOptions(List&lt;?&gt; list, String message){\n</code></pre>\n<p>The comment might actually be needed here, but only because the code is not clear enough about what it does. By changing the return type to <code>PlayerOption</code>, we can already remove part of the comment (and also the cast in the <code>Game</code> class). By replacing <code>List&lt;?&gt; list</code> with <code>List&lt;PlayerOption&gt; options</code>, we can remove the rest of the comment.</p>\n<hr />\n<h2>Jail.java</h2>\n<p>This class does not have any state of its own, but depends on a lot of other classes to execute its logic. I would suggest giving each player their own instance of <code>Jail</code>, and moving the jail-related variables and logic from the player to the jail (e. g. <code>inJail</code> and <code>turnsInJail</code> of <code>Player</code>). The <code>Game</code> would then access it via the player. This way you can avoid this &quot;ask the jail to send this player to jail, which then tells the player they are now in jail&quot; back-and-forth logic, by doing e. g. <code>player.goToJail()</code> and letting the player handle their jail stay.</p>\n<hr />\n<h2>Player.java</h2>\n<p>There are some public fields in this class. Other fields are private and only accessed via methods. I would recommend making all fields private.</p>\n<hr />\n<pre><code>//if pass GO\nif(position &gt;= 40){\n</code></pre>\n<p>You can avoid this comment by using a local variable:</p>\n<pre><code>boolean passedGo = position &gt;= 40;\nif (passedGo) {\n</code></pre>\n<p>Comments are not checked by the compiler, and often overlooked by programmers. In cases like this, code can be equally as or more expressive than a comment.</p>\n<hr />\n<pre><code>//check if property is in Player's properties\nprivate boolean owns(Property property){\n// ...\n\n//check if Player owns all of a certain color group\npublic boolean ownsGroup(ColorProperty.Group group){\n</code></pre>\n<p>The comments do not help unless you look at the method definition. The first one is in my opinion perfectly clear without the comment. The second one can be renamed to make it clearer:</p>\n<pre><code>public boolean ownsAllPropertiesOfGroup(ColorProperty.Group group) {\n</code></pre>\n<p>or</p>\n<pre><code>public boolean ownsWholeGroup(ColorProperty.Group group) {\n</code></pre>\n<hr />\n<h2>Property.java</h2>\n<p>The property knows its owner, but also the owning player knows which properties they own. This can easily lead to inconsistencies and bugs. I would recommend keeping the information at one place, possibly even outside of both classes, e. g. in a <code>Bank</code>. The bank could keep track of which player owns which properties, and allow look-up in both ways (&quot;who owns this property&quot; and &quot;which properties does this player own&quot;).</p>\n<hr />\n<pre><code>public void doAction(Player currentPlayer) {\n if(currentPlayer == owner);\n //square is owned by the currentPlayer\n else if(owner != null) {\n //square is owned by someone else\n if(!mortgaged){\n System.out.println(currentPlayer.getName() + &quot; paid &quot; + owner.getName() + &quot; $&quot; + getRent() + &quot; in rent&quot;);\n currentPlayer.pay(owner, getRent());\n }\n } else {\n //square can be bought\n offerBuy(currentPlayer);\n }\n}\n</code></pre>\n<p>That first if statement (<code>if(currentPlayer == owner);</code>) with the semicolon can be confusing. I would suggest returning early instead (and removing the comment since the code is already clear):</p>\n<pre><code> if (currentPlayer == owner) {\n return;\n } else {\n // ...\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T01:38:02.763", "Id": "528017", "Score": "0", "body": "Thank you for taking the time to take a look at my code! I have an additional question about how to handle the common dependencies that Board and Game have. I would like to move those common dependencies like Dice all to the Board, but would it be better to:\n\n1. Create getters for the dependencies so that Game can retrieve the Dice and roll it or\n2. Create a rollDice method in Board so that Game can call rollDice to roll it instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T09:48:43.403", "Id": "528040", "Score": "1", "body": "I would prefer the second option. It is usually better to tell objects what to do, but let them handle how to do it. In the first option, you would access their internals, and thus basically treat the Board as a \"storage\" for references to other objects. You could also consider removing the Dice from Game and Board. Currently, Game and Board only know about the Dice because they pass them on to other methods and constructors. Considering how simple the Dice class is, I would simply let the utilities, the player, and the jail create their own instance of Dice for each dice roll." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T08:14:01.703", "Id": "267751", "ParentId": "266188", "Score": "5" } } ]
{ "AcceptedAnswerId": "267751", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T00:17:30.250", "Id": "266188", "Score": "5", "Tags": [ "java" ], "Title": "Text-based Monopoly in Java" }
266188
<p>I wrote <a href="https://github.com/albert10jp/deep-learning/blob/main/logistic_regression_for_fashion_mnist.ipynb" rel="nofollow noreferrer">a Logistic Regression for Fashion MNIST</a> to classify T-shirt vs. Shirt.</p> <p>here is the class</p> <pre><code>import numpy as np import time class LogisticRegression: def __init__(self, learning_rate=.05, n_epoch=10, model_w=[], model_b=.0): self.learning_rate = learning_rate self.n_epoch = n_epoch self.model_w = model_w self.model_b = model_b def initialize_params(self, n_x): if len(self.model_w) == 0: self.model_w = np.random.random((n_x, 1)) # forward_propagation # predict_prob def activation(self, x): z = np.dot(x, self.model_w) + self.model_b a = 1 / (1 + np.exp(-z)) return a def predict(self, x): a = self.activation(x) &gt;= 0.5 return np.squeeze(1*a) def evaluate(self, x, y): acc = np.count_nonzero(np.squeeze(self.predict(x)) == np.squeeze(y))/len(y) return acc def backward_propagation(self, x, a, y): m = len(x) dz = a - y dw = np.dot(x.T, dz)/m db = np.mean(dz) return dw, db def update_weights(self, dw, db): self.model_w -= self.learning_rate * dw self.model_b -= self.learning_rate * db def fit(self, x, y, batch_size=10, shuffle=True, verbose=True): start_time = time.time() n_x = x.shape[-1] self.initialize_params(n_x) indices = np.arange(len(x)) for i in range(self.n_epoch): if shuffle: np.random.shuffle(indices) n_batches = int(len(x)/batch_size) batches = np.split(indices[:batch_size*n_batches], n_batches) for batch in batches: a = self.activation(x[batch]) dw, db = self.backward_propagation(x[batch], a, y[batch]) self.update_weights(dw, db) acc = self.evaluate(x, y) if verbose: print('model trained {:.5f} s'.format(time.time() - start_time)) print('train accuracy: {:7f}'.format(acc)) </code></pre> <p>Here is the data</p> <pre><code>import tensorflow as tf (x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() # generate the indices idx_digit_train = np.argwhere((y_train == 0) | (y_train == 6)).flatten() idx_digit_test = np.argwhere((y_test == 0) | (y_test == 6)).flatten() # construct the training set y_train_mnist = y_train[idx_digit_train].reshape(-1,1) x_train_mnist = x_train[idx_digit_train] # construct the test set y_test_mnist = y_test[idx_digit_test].reshape(-1,1) x_test_mnist = x_test[idx_digit_test] # normalization x_train_mnist = x_train_mnist/255. x_test_mnist = x_test_mnist/255. # flatten x_train_mnist = x_train_mnist.reshape(len(x_train_mnist), -1) x_test_mnist = x_test_mnist.reshape(len(x_test_mnist), -1) y_train_mnist[y_train_mnist==6]=1 y_test_mnist[y_test_mnist==6]=1 </code></pre> <p>I trained the model on the data for one epoch</p> <pre><code>classifier = LogisticRegression(.1, 1) classifier.fit(x_train_mnist, y_train_mnist) classifier.evaluate(x_test_mnist, y_test_mnist) </code></pre> <p>Here is the result</p> <pre><code>model trained 0.09662 s train accuracy: 0.828583 0.8125 </code></pre> <p>I'm conscious that I should add some checking, e.g. <code>assert</code> and support for multiclass classification. Beside that, what else I can do to improve this <code>LogisticRegression</code> class.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T00:49:01.237", "Id": "266189", "Score": "1", "Tags": [ "python", "machine-learning" ], "Title": "Logistic Regression for Fashion MNIST T-shirt vs. Shirt" }
266189
<p>I am writing library code to help other developers send messages to a pub-sub event broker.</p> <p>In many cases, the message source will not be &quot;stream-like&quot;. Specifically, most messages are coming from SQL Server change data capture, and are therefore much more efficiently read in sets (batches).</p> <p>Additionally, in most cases the message should be &quot;guaranteed&quot; - ie, if we fail to send the message to the broker then we should send it again, even if the sending application crashes for some reason. This implies letting the source know that a message has been sent. As was the case with reading from the source, acknowledging back to it is also set based, for the same reason.</p> <p>It is acceptable that a message may be &quot;accidentally&quot; sent multiple times in exception-like circumstances, (guaranteed-once-in-order delivery is much too hard a problem for me to solve in my little implementation here!), but this should not occur if everything is running smoothly.</p> <p>Batch sizes might be large, so I don't really want to concurrently execute <code>n</code> publish-to-broker tasks, where <code>n</code> is the number of messages in the batch, because that could potentially be a heck of a lot of <code>Task</code> objects being waited on by something like <code>Task.WhenAll</code>. Therefore I have used <code>DataFlow</code> as a concurrency-limiting mechanism.</p> <p>Here are the Interfaces I have created (I am fairly happy with these so skip over them if you don't need the context, although I do wonder if the <code>AcknowledgeAsync</code> method should accept an <code>IAsyncEnumerable</code> for symmetry). The <code>IGuaranteedBatchProvider</code> does not extend <code>IBatchProvider</code>, because acknowledgement only requires an <code>IMessage</code>, not an <code>IMessage&lt;T&gt;</code>.</p> <pre class="lang-cs prettyprint-override"><code> public interface IMessage { /// &lt;summary&gt; /// Allows a message to be tracked locally through processing pipeline, either on the /// publication or subscription side, but the values sent by a publisher will not be the same /// as those received by a subscriber, since the LocalMessageId values for messages received /// by susbcribers are generated by the broker /// &lt;/summary&gt; public long LocalMessageId { get; init; } } public interface IMessage&lt;T&gt; : IMessage { public T Payload { get; init; } } public interface IBatchProvider&lt;T&gt; { /// &lt;summary&gt; /// Returns a batch of unacknowledged messages from the source. If the provider is also a /// guaranteed provider, then all messages in a batch should be acknowledged prior to reading /// a new batch, otherwise the new batch will contain duplicate messages /// &lt;/summary&gt; IAsyncEnumerable&lt;IMessage&lt;T&gt;&gt; ReadBatchAsync(ushort maxBatchSize, CancellationToken ct); } public interface IGuaranteedBatchProvider { /// &lt;summary&gt; /// informs a guaranteed provider that a set of messages have been successfully transmitted. /// Acknowledged messages will not be returned by subsequent read operations /// &lt;/summary&gt; Task AcknowledgeAsync(IEnumerable&lt;IMessage&gt; messagesToAcknowledge, CancellationToken ct); } public interface IPublication&lt;T&gt; { /// &lt;summary&gt; /// sends a message to the broker, returns true if the payload is successfully published /// &lt;/summary&gt; Task&lt;bool&gt; PublishAsync(T payload); } </code></pre> <p>The code I am interested in having reviewed is in my <code>BatchPublisher</code> class. This helper class understands how to work with the interfaces described above. The <code>Run</code> loop is what follows. I would particularly appreciate feedback for the section of code commented as <code>//ugly?</code>, whether a <code>Channel</code> implementation might be more appropriate (I have not yet used channels), and of course any overall comments about the overall design. Most exception handling removed for brevity.</p> <p>The provider here would typically be a <code>CdcProvider&lt;T&gt; : IBatchProvider&lt;T&gt;, IGuaranteedBatchProvider</code></p> <pre class="lang-cs prettyprint-override"><code>public async Task Run(CancellationToken ct) { var results = new ConcurrentBag&lt;(IMessage msg, bool result)&gt;(); // ugly? Func&lt;IMessage&lt;T&gt;, Task&gt; publish = provider is IGuaranteedBatchProvider ? async (msg) =&gt; results.Add((msg, await publication.PublishAsync(msg.Payload))) : async (msg) =&gt; _ = await publication.PublishAsync(msg.Payload); while (!ct.IsCancellationRequested) { results.Clear(); // channels instead? Newing up the actionblock every batch seems wrong somehow ActionBlock&lt;IMessage&lt;T&gt;&gt; limiter = new ( async (msg) =&gt; { try { await publish(msg); } // if the consuming application as registered an event handler for publication // exceptions, call it (mostly for error logging) catch (Exception x) { PublishFailed?.Invoke(this, (msg, x)); } }, new ExecutionDataflowBlockOptions { CancellationToken = ct, EnsureOrdered = true, MaxDegreeOfParallelism = sendConcurrency } ); await foreach (var message in provider.ReadBatchAsync(maxReadBatchSize, ct)) { limiter.Post(message); } limiter.Complete(); await limiter.Completion; if (!results.IsEmpty &amp;&amp; provider is IGuaranteedBatchProvider p) { await p.AcknowledgeAsync(results.Select(r =&gt; r.msg), ct); } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T01:39:56.020", "Id": "266190", "Score": "1", "Tags": [ "c#", "concurrency", "async-await", "tpl-dataflow" ], "Title": "\"streaming\" messages to a broker from a batch-like source (eg sql database), optionally acknowledge back to the source" }
266190
<p>I was given the problem (called &quot;car plate problem&quot;) to write all the values that go from AAA0001 to ZZZ9999 with the following premises:</p> <ol> <li>Create all the possibilities from AAA0001 to ZZZ9999;</li> <li>Skip all the 0000, ie: AAB0000, AAC0000... ZZZ0000.</li> <li>No repetitions. Once a value is &quot;created&quot; or &quot;found&quot;, whatever, the value cannot repeat. So, once your code generated the AAA0002, it shouldn't generate the AAA0002 again.</li> </ol> <p>So... I found a solution (posted below). It was &quot;short&quot; and &quot;oh boy&quot; it was weak! But I was coding against time so I had to go with that solution. I recognize the solution lacks creativity, better use of O.O. and probably there is a design pattern to be use here. None I could identify but still, there must be a better way to make it work. Is there a solution with better code quality and (if possible) less processing?</p> <pre><code>public class PlateIncrement { private String plate; public PlateIncrement () { } public void setPlate(String thePlate) { plate = thePlate; } public String getIncrementedPlate() { String finalNumber = &quot;&quot;; String finalLetters = &quot;&quot;; String letters = plate.substring(0,3); String numbers = plate.substring(3,7); letters = letters.toUpperCase(); if (Integer.parseInt(numbers) != 9999) { finalNumber = incrementNumber(numbers); finalLetters = letters; } else { finalLetters = getIncrementedLetters(letters); finalNumber = &quot;0001&quot;; } return finalLetters.concat(finalNumber); } private String getIncrementedLetters(String letters) { String[] splittedLetters = letters.split(&quot;&quot;); if( !splittedLetters[2].equalsIgnoreCase(&quot;Z&quot;) ) { incrementLetter(splittedLetters, 2); } else if( !splittedLetters[1].equalsIgnoreCase(&quot;Z&quot;) ) { incrementLetter(splittedLetters, 1); splittedLetters[2] = &quot;A&quot;; } else if( !splittedLetters[0].equalsIgnoreCase(&quot;Z&quot;) ) { incrementLetter(splittedLetters, 0); splittedLetters[2] = &quot;A&quot;; splittedLetters[1] = &quot;A&quot;; } return String.join(&quot;&quot;, splittedLetters); } private void incrementLetter(String[] splittedLetters, int i) { char theChar = splittedLetters[i].charAt(0); char incrementedChar = (char) (theChar + 1); splittedLetters[i] = String.valueOf(incrementedChar); } private String incrementNumber(String numbers) { int number = Integer.parseInt(numbers); number += 1; String value = String.format(&quot;%04d&quot;, number); return value; } } </code></pre> <p>So I pass the value to setPlate(), get the &quot;next plate&quot; from getIncrementedPlate() and that value is passed again to setPlate() to generate the next plate.</p> <p>It works. But it takes a lifetime (from AAA0001 to AAB0001 takes 49 seconds!), consumes 100% of all the processors and as I mentioned before, lacks quality.</p> <p>Could anyone point how to improve it or show me a better improved version?</p> <p>My current idea to improve the code:</p> <ol> <li>Change the entity to have 3 chars, each representing each letter. The entity getPlate will concatenate the chars with the numbers when the getPlate is called.</li> <li>This &quot;PlateIncrement&quot; class will be changed to receive the entity instead of the String. When I request the &quot;nextPlate()&quot;, it will know how to properly increment the chars from the entity.</li> <li>I will hold all the possible numbers in-memory. It will be 0,32MB for all the numbers, so it will be ultra cheap.</li> </ol> <p>All suggestions for improvement are welcome!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:07:08.637", "Id": "525860", "Score": "2", "body": "Could you clarify the exact problem definition? Does your code need to return the next increment for one given plate? Does it need to return all the increments? Or does it simply need to return all possible plates without input?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T19:31:15.670", "Id": "525886", "Score": "8", "body": "Obligatory oneliner `perl -E 'for $w (\"AAA\"..\"ZZZ\") { printf \"$w%04d\\n\", $_ for 1..9999 }'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:24:10.203", "Id": "525894", "Score": "1", "body": "@marcovtwout The code needs to generate ALL plates from AAA0001 to ZZZ9999. What you see in the question is my 99% of the code, where the magic happens. Everything else not here is just a simple loop getting whatever comes out from getIncrementedPlate() and passing it back to setPlate() for the next plate. This is the base of the idea the way I implemented. But in the back, there is a loop where it starts with setPlate(AAA0001) + getIncrementedPlate() alllll the way to if getIncrementedPlate() == ZZZ9999, stop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T12:01:15.643", "Id": "525946", "Score": "0", "body": "@vianna77 Thanks for clarifying. I was about to suggest the exact same approach as https://codereview.stackexchange.com/a/266205/247302, but couldn't figure out why everybody was posting so complicated answers :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T14:35:12.277", "Id": "525960", "Score": "1", "body": "I also want to annoyingly suggest a one-line solution, in Ruby:\n`(\"AAA\"..\"ZZZ\").to_a.product((\"0001\"..\"9999\").to_a).map(&:join)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T06:14:48.037", "Id": "525974", "Score": "0", "body": "Not really worth mentioning, but: “splitted” is not a word. The past tense of “split” is – confusingly – “split”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T11:14:34.490", "Id": "525995", "Score": "0", "body": "Did you get a suite test to check against or did you write tests ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T14:44:59.780", "Id": "526004", "Score": "0", "body": "@Michael Splat is also acceptamable. ;) (to non-English-first-language speakers, this is a joke)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T14:52:28.520", "Id": "526005", "Score": "0", "body": "@Michael thank you! Just fixed the text. Guess that was extra cringe for the people judging the code solution :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T15:37:39.333", "Id": "526009", "Score": "2", "body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>Your problem statement is to create all of the possibilities, not necessarily to support increment from an existing possibility. The difference is very important. It's slow to parse out a position in the license plate space, increment it and format it again.</p>\n<p>Instead, consider</p>\n<ul>\n<li>overriding the <a href=\"https://devdocs.io/openjdk%7E15/java.base/java/util/iterator\" rel=\"noreferrer\">Iterator</a> interface,</li>\n<li>keeping state on the instance that remembers where in the iteration you are, and</li>\n<li>do the cheap increment (the number suffix) 10,000 times more frequently than the expensive increment (the letter prefix).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:54:46.810", "Id": "525901", "Score": "0", "body": "Thanks... I was thinking about splitting the problem into 2. One part to deal with the letters and one to deal with the numbers. Many people suggested Iterator. Maybe just get the letters and append it to the current index that goes from 1 (formatted to 0001) to 9999?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T03:02:08.450", "Id": "266192", "ParentId": "266191", "Score": "9" } }, { "body": "<p>You are using a sledge-hammer to crack a peanut.</p>\n<p>Consider <code>String[] splittedLetters = letters.split(&quot;&quot;);</code>. The <code>split()</code> function takes a regular expression, so you are using the entire regular expression engine to split a string into an array of single character strings. You don't need regular expression here; the overhead of regular expressions is huge!</p>\n<p>Allow me to repeat: <strong>single character strings</strong>. Why are you using strings to store single characters? Java has a <code>char</code> primitive type for storing characters. Moreover, there is a cheap function which turns a string into an array of characters: <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()\" rel=\"noreferrer\"><code>.toCharArray()</code></a>. If you use that, you'll be dealing with a fraction of the number of heap-allocated objects, which will ease the burden on the garbage collector, plus all other manner of speed improvements.</p>\n<p>Reinderien has the right idea. Implement an <code>Iterable</code> class, which can return an <code>Iterator</code>. Furthermore, instead of splitting a string into tiny single character chunks, and reassembling a new plate, you should use a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html\" rel=\"noreferrer\"><code>StringBuilder</code></a> object, which will allow you to efficiently mutate a string-like buffer to create new strings.</p>\n<hr />\n<p>Improved code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Iterator;\n\npublic class Plates implements Iterable&lt;String&gt; {\n \n private final String initial_plate;\n \n public Plates(String first_plate) {\n initial_plate = first_plate;\n }\n \n @Override\n public Iterator&lt;String&gt; iterator() {\n return new PlateIterator(initial_plate);\n }\n \n private static class PlateIterator implements Iterator&lt;String&gt; {\n private final int plate_length;\n private final StringBuilder plate;\n private boolean has_next = true;\n private boolean need_next = false;\n \n PlateIterator(String first_plate) {\n plate_length = first_plate.length();\n plate = new StringBuilder(plate_length);\n plate.append(first_plate);\n has_next = true;\n need_next = false;\n }\n \n private void advance() {\n need_next = false;\n has_next = false;\n for (int i = plate_length - 1; i &gt;= 0; i--) {\n char ch = plate.charAt(i);\n if (ch == '9')\n plate.setCharAt(i, '0');\n else if (ch == 'Z')\n plate.setCharAt(i, 'A');\n else {\n plate.setCharAt(i, (char) (ch + 1));\n has_next = true;\n break;\n }\n }\n if (plate.substring(plate_length - 4).equals(&quot;0000&quot;))\n plate.setCharAt(plate_length - 1, '1');\n }\n \n @Override\n public boolean hasNext() {\n if (has_next &amp;&amp; need_next)\n advance();\n return has_next;\n }\n \n @Override\n public String next() {\n if (need_next)\n advance();\n need_next = true;\n return plate.toString();\n }\n }\n\n public static void main(String[] args) {\n Plates plates = new Plates(&quot;AAA0001&quot;);\n for(String plate : plates) {\n // System.out.println(plate);\n }\n }\n}\n</code></pre>\n<p>Run time: 5 seconds</p>\n<hr />\n<p>It may not be obvious, so I'll point out that in the above implementation, the initial license plate letters/numbers controls the pattern of license plates that are generated.</p>\n<p>For instance, given <code>&quot;A0&quot;</code>, it would generate up to <code>&quot;Z9&quot;</code> (a total of 260 plates). Given <code>&quot;00AAA00&quot;</code> it would generate all the plates up to <code>&quot;99ZZZ99&quot;</code>. (The &quot;skip plates ending in 0000&quot; code only functions properly if the license plate pattern ends in 4 digits; you'd have to modify the code to make it more general, if desired.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T15:41:24.440", "Id": "525873", "Score": "2", "body": "Shouldn't your `next` throw a `NoSuchElementException` in case `has_next` is `false` after the `if`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T15:52:21.573", "Id": "525874", "Score": "0", "body": "@YanickSalzmann Good catch. I'll update when I'm at a computer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T20:19:39.213", "Id": "525892", "Score": "0", "body": "To make it more general you could keep the sum of the digits, and at the end of the loop over the plate, if it’s still 0, you know you need to set the last digit to 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:49:07.780", "Id": "525899", "Score": "0", "body": "@AJNeufeld Responding to \"Why are you using strings to store single characters?\" When I received the values, it was a String with 3 chars and, as stated in the question, I was coding against time. First solution is pretty much permanent, like all \"temporary solutions\" in the world. Now I have time to think, so I'm improving the code.\nI will test your code this weekend, but the main issue is that working around the \"reset middle and rightmost back to A\" really boggled my mind because a bunch of plates went missing... and that plus skipping 0000 is a big part of the problem to solve." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T09:41:33.630", "Id": "525934", "Score": "6", "body": "\"You are using a sledge-hammer to crack a peanut.\" - so here's a much prettier sledge-hammer?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T04:09:27.447", "Id": "266193", "ParentId": "266191", "Score": "15" } }, { "body": "<p>In my answer, I will only suggest an efficiency improvement to the iterator:</p>\n<pre><code>import java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic final class PlateNumberIterable implements Iterable&lt;String&gt; {\n\n @Override\n public Iterator&lt;String&gt; iterator() {\n return new PlateNumberIterator();\n }\n\n private static final class PlateNumberIterator implements Iterator&lt;String&gt; {\n\n private static final int NUMBER_OF_ALL_CANDIDATE_PLATE_NUMBERS = \n 26 * 26 * 26 * 10_000;\n\n private static final int NUMBER_OF_ALL_SKIPPED_PLATE_NUMBERS = \n 26 * 26 * 26;\n\n private static final int NUMBER_OF_TOTAL_LEGAL_PLATE_NUMBERS = \n NUMBER_OF_ALL_CANDIDATE_PLATE_NUMBERS - \n NUMBER_OF_ALL_SKIPPED_PLATE_NUMBERS; \n\n private int numberOfIteratedPlates = 0;\n\n private final char[] chars = \n new char[]{ 'A', 'A', 'A', '0', '0', '0', '1' };\n\n @Override\n public boolean hasNext() {\n return numberOfIteratedPlates &lt; NUMBER_OF_TOTAL_LEGAL_PLATE_NUMBERS;\n }\n\n @Override\n public String next() {\n if (!hasNext()) {\n throw new NoSuchElementException(&quot;Iterator exhausted.&quot;);\n }\n\n numberOfIteratedPlates++;\n String result = new String(chars);\n incrementPlateNumber();\n return result;\n }\n\n private void incrementPlateNumber() {\n for (int i = 6; i &gt;= 3; i--) {\n if (chars[i] &lt; '9') {\n chars[i]++;\n\n for (int j = i + 1; j &lt; 7; j++) {\n chars[j] = '0';\n }\n\n return;\n }\n }\n\n chars[3] =\n chars[4] =\n chars[5] = '0';\n chars[6] = '1';\n\n for (int i = 2; i &gt;= 0; i--) {\n if (chars[i] &lt; 'Z') {\n chars[i]++;\n\n for (int j = i + 1; j &lt; 3; j++) {\n chars[j] = 'A';\n }\n\n return;\n }\n }\n }\n }\n\n public static void main(String[] args) {\n int coderoddePlates = 0;\n long start = System.currentTimeMillis();\n\n for (String plateNumber : new PlateNumberIterable()) {\n coderoddePlates++;\n }\n\n long end = System.currentTimeMillis();\n\n System.out.println(&quot;coderodde iterable computation time: &quot; + \n (end - start) + &quot; ms.&quot;);\n\n int AJNeufeldPlates = 0;\n start = System.currentTimeMillis();\n\n for (String plateNumber : new Plates(&quot;AAA0001&quot;)) {\n AJNeufeldPlates++;\n }\n\n end = System.currentTimeMillis();\n\n System.out.println(&quot;AJNeufeld iterable computation time: &quot; +\n (end - start) + &quot; ms.&quot;);\n\n System.out.println(&quot;coderodde iterable produced &quot; + coderoddePlates +\n &quot; plates.&quot;);\n\n System.out.println(&quot;AJNeufeld iterable produced &quot; + AJNeufeldPlates +\n &quot; plates.&quot;);\n }\n}\n</code></pre>\n<p>(See <a href=\"https://gist.github.com/coderodde/648e30adabe1c3da5031bec2df3aa783\" rel=\"nofollow noreferrer\">this gist</a> for the entire comparison program.)</p>\n<p>The performance figures are something like that:</p>\n<pre><code>coderodde iterable computation time: 1513 ms.\nAJNeufeld iterable computation time: 5086 ms.\ncoderodde iterable produced 175742424 plates.\nAJNeufeld iterable produced 175742424 plates.\n</code></pre>\n<p>The idea is to increment the rightmost character. If it’s already at its maximum value, set it to the minimum value and proceed to the character one step to the left from it. If the new character may be incremented, do that and halt. In case that 2nd character is at its maximum, keep going until a new valid plate number is found. Of course, we need to exclude from consideration every plate number ending in 4 zeros.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T13:07:31.700", "Id": "525855", "Score": "0", "body": "I think this approach is the most efficient. I would argue that you only need a single set of loops. If you need to increment and you are at Z reset to A, 9 resets to 0. And the check for 0000 could be outside the increment and just increment again...just my opinion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:09:54.423", "Id": "525861", "Score": "0", "body": "This would be stronger if you made an observation about the original code, as of course that is the actual requirement. We are reviewing the OP's code, not just writing our own. I.e. your explanation isn't a code *review*; it doesn't explain why your code is better than the OP's code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T08:33:46.390", "Id": "266198", "ParentId": "266191", "Score": "3" } }, { "body": "<p><em>I'm no Java dev, so my snippets use C#, but this should be easily translateable and the focus of this answer is on the class design rather than the specific syntax.</em></p>\n<p><em>Note also that I opted for code that is as readable as possible, rather than tersely efficient. You can squeeze some more performance out of this by refactoring, but the main goal of this answer was to showcase the idea behind the design.</em></p>\n<hr />\n<p>&quot;Computer&quot; is a word meaning &quot;calculator&quot;. The reason I'm mentioning this is because computers are fast at math, but (relatively) slow at other things such as text processing. Breaking the calculation down to simpler mathematics will significantly boost processing speed.</p>\n<p>Your code is written from <em>your</em> point of view on how words can be broken down in letters and put back together. But this is not the most efficient way to think about it in terms of CPU requirements. If we boil it down to a much more mathematical construct, we will be able to leverage the things that the CPU is very good and efficient at.</p>\n<p>Let's look at another way of looking at it, the flip clock (click for animated gif):</p>\n<p><a href=\"https://i.stack.imgur.com/Dosqem.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Dosqem.gif\" alt=\"enter image description here\" /></a></p>\n<p>How does a flip clock work? Well, the rightmost digit increments. When the rightmost digit cycles back to 0, it tells its neighbor to increment once. The process repeats, and eventually the second-to-last digit will also cycle back to 0, at which point it tells <em>its</em> neighbor (the third from the right digit) to increment.</p>\n<p>It's interesting to note here that this doesn't <em>have</em> to use all 10 digits. In a clock, the second-to-last digit only cycles from 0 to 5, because there is no 60th second in a minute.<br />\nThis means that we can use an <strong>arbitrary amount of values</strong> in a given digit, for example 26, just like how many letters there are in the alphabet.</p>\n<p>The snippet I'll show here is effectively going to rebuild that flip clock in code.</p>\n<p><strong>The digit</strong></p>\n<p>First, we'll look at an individual digit. We need to define how many values it can cycle across, and we need to tell it who its neighbor is, so that it can tell the neighbor to increment.</p>\n<p><em>Forget about letters. We're only going to use numbers. In the end, we will translate a number value to a given letter character, but only <strong>after</strong> we've done the calculations.</em></p>\n<pre><code>public abstract class FlipDigit\n{\n private readonly int maxValue;\n private readonly FlipDigit neighbor;\n\n protected int currentValue;\n\n public FlipDigit(int maxValue, FlipDigit neighbor)\n {\n this.maxValue = maxValue;\n this.neighbor = neighbor;\n this.currentValue = 0;\n }\n\n public void Increment()\n {\n // Simple +1 increment\n this.currentValue = this.currentValue + 1;\n\n // If max is reached, cycle back to 0\n if(this.currentValue &gt; this.maxValue)\n {\n this.currentValue = 0;\n \n // If there is a neighbor, increment it.\n if(this.neighbor != null)\n this.neighbor.Increment();\n }\n }\n\n // Ignore for now\n public abstract string PrintValue();\n}\n</code></pre>\n<p>This is really just the code equivalent of how I described how each digit in a flip clock works.</p>\n<p>We need to make some subclasses here. The logic works as is, but some digits will need to be printed as numbers, and others as letters. In the above snippet, I already prepared for this by adding the abstract <code>PrintValue</code> method. Our derived classes are <strong>only</strong> going to implement logic on how to print the correct value. The counting logic itself remains untouched.</p>\n<pre><code>public class NumberDigit : FlipDigit\n{\n public NumberDigit(FlipDigit neighbor) \n : base(9, neighbor) \n {\n\n }\n\n public override string PrintValue()\n {\n return this.currentValue.ToString();\n }\n}\n\npublic class LetterDigit : FlipDigit\n{\n private char[] letters = new char[26] { 'A', 'B', 'C', ..., 'Z' };\n\n public LetterDigit (FlipDigit neighbor) \n : base(25, neighbor) \n {\n\n }\n\n public override string PrintValue()\n {\n return letters[this.currentValue].ToString();\n }\n}\n</code></pre>\n<p>Notice how we've hardcoded the max values (9 for numbers, 25 for letters) in the classes themselves. Maybe you want to change that if you want more custom ranges like that 0-5 digit in a real clock, but for your current case this full range suffices.</p>\n<p><strong>The clock</strong></p>\n<p>Now, we're going to create a clock, which is effectively a group of connected flip digits. I know that you'll be calling this class <code>LicensePlate</code>, but I'm going to stick with <code>Clock</code> for now to stay close to the analogy.</p>\n<pre><code>public class Clock\n{\n private List&lt;FlipDigit&gt; digits;\n private FlipDigit lastDigit;\n\n public Clock()\n {\n this.Digits = new List&lt;FlipDigit&gt;();\n\n GenerateDigits();\n }\n\n private void GenerateDigits()\n {\n // Digit 1 is a letter and has no neighbor to the left\n var digit1 = new LetterDigit(null);\n digits.Add(digit1);\n\n // Digit 2 is a letter and has digit 1 as a neighbor\n var digit2 = new LetterDigit(digit1);\n digits.Add(digit2);\n\n // And so on...\n var digit3 = new LetterDigit(digit2);\n digits.Add(digit3);\n\n var digit4 = new NumberDigit(digit3);\n digits.Add(digit4);\n\n var digit5 = new NumberDigit(digit4);\n digits.Add(digit5);\n\n var digit6 = new NumberDigit(digit5);\n digits.Add(digit6);\n\n var digit7 = new NumberDigit(digit6);\n digits.Add(digit7);\n\n // Digit 7 is also separately kept as a reference\n this.lastDigit = digit7;\n }\n\n public string GetNext()\n {\n // This will set off a chain of flipping digits when needed\n this.lastDigit.Increment();\n\n // Now we generate our output based on our list\n var values = this.digits.Select(digit =&gt; digit.PrintValue()).ToArray(); \n var combinedValue = String.Join(&quot;&quot;, values);\n\n return combinedValue\n }\n}\n</code></pre>\n<p><strong>Using the clock</strong></p>\n<p>We've now built a fully working clock. Its usage is very straightforward:</p>\n<pre><code>var clock = new Clock();\n\nfor(int i = 0; i &lt; 1000000; i++)\n{\n var value = clock.GetNext();\n \n if(!value.EndsWith(&quot;0000&quot;))\n Console.WriteLine(value);\n}\n</code></pre>\n<p>If you want to prevent the entire clock rolling back to its start position, you could throw a custom exception when you've reached the end of the <code>FlipDigit</code> which has no neighbor:</p>\n<pre><code>// If there is a neighbor, increment it.\nif(this.neighbor != null)\n this.neighbor.Increment();\nelse\n throw new ClockOutOfRangeException();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T12:27:41.867", "Id": "525851", "Score": "0", "body": "The only issue I see with this approach is you are making the \"skip 0000\" requirement be part of the `Clock`'s client code. Still, great explanation!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T16:35:58.830", "Id": "525876", "Score": "0", "body": "@m-alorda: I assume must be misunderstanding your comment, because the skip logic is specifically _not_ part of the clock logic, it is up to the consumer of the clock to decide to not do anything with the \"0000\" values that are being generated by the clock just like any other value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T16:58:37.783", "Id": "525878", "Score": "1", "body": "my bad, I actually meant the requirement was NOT part of the `Clock`. From the stated problem, I believe it should be" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:29:44.393", "Id": "525895", "Score": "2", "body": "We can handle that by treating the four numeric positions as a single \"digit\", and giving them a custom class with a `maxValue` of 9998 and a `PrintValue` that adds 1 to that value before formatting it into four string digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T01:10:17.877", "Id": "525906", "Score": "0", "body": "Why not use a loop to create the digits?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T06:19:53.743", "Id": "525918", "Score": "0", "body": "@Karl I think that would be better, yes. It makes it all unbranched as well, added bonus." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T07:50:02.473", "Id": "525924", "Score": "0", "body": "@m-alorda: Whether you shift that logic to `GetNext()` or simply wrap the `Clock` is a developer freedom." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T07:52:19.800", "Id": "525925", "Score": "0", "body": "@KarlKnechtel: Clever solution! But would require some documentation to remain understandable for future readers as that's a non-obvious implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T00:51:06.613", "Id": "525970", "Score": "0", "body": "Maybe \"digit\" is the wrong name in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T02:50:37.797", "Id": "525971", "Score": "0", "body": "@KarlKnechtel The names `Clock` and `Digit` were used to stick close to the analogy which this answer effectively recreated in code. I agree that OP shouldn't use those exact names for their license plate code." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T09:32:44.743", "Id": "266199", "ParentId": "266191", "Score": "4" } }, { "body": "<p>I think the first thing I would say is:</p>\n<p>the data you keep internally doesn't have to be the same as the data you give out.</p>\n<p>In this case you are working on the full String of the car plate and you have to break it apart to increment it. You could just as easily keep it split internally:</p>\n<pre><code>int numberPart = 1;\nchar[] stringPart = { 'A', 'A', 'A' }; \n</code></pre>\n<p>that would let you change the individual characters directly.</p>\n<p>when forming this into the final output you can use something like:</p>\n<pre><code>String.format(&quot;%s%04d&quot;, string, number); \n</code></pre>\n<p>to generate the final string in 1 go.</p>\n<p>keeping the data in an intermediate form makes your code a lot easier to change at a later day. And often this is something you'll do in the future. the format your client expects is not the format it is kept in the database or in code.</p>\n<p>this can work even when you get your data delivered using setPlate. when setPlate is called, transform the data into your internal form.</p>\n<p>I would also keep track of your starting point. (so if setPlate is called with XXX2345 , I would keep this XXX2345 and let hasNext check if that value will be the value returned. you can do this by letting next return the value (and already computing what will be the next value)</p>\n<p>so in pseudocode, please don't use this bad method/variable names if you try this</p>\n<pre><code>String startValue;\npublic void setPlate(String plate) {\n startValue = plate;\n splitIntoParts(plate);\n}\n\nString nextValue;\npublic String next() {\n String result = nextValue;\n nextValue = calculateNext();\n return result;\n}\n</code></pre>\n<p>this allows you to have</p>\n<pre><code>public boolean hasNext() {\n return !startValue.equals(nextValue);\n}\n</code></pre>\n<p>Of course it would work better if you made Plate into a class and use equals on it rather than on the string representation of it but I'm trying to keep each suggestion/option separate from any other suggestions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T15:32:39.903", "Id": "525871", "Score": "2", "body": "`String.format(\"%s%04d\", number, string);` I'm certain you've got the arguments backwards (although to be fair, you did say \"_something like this_\", so I guess having the arguments in the correct order is technically something like it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T09:51:57.673", "Id": "526232", "Score": "0", "body": "Oops :) I'll correct" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T09:43:45.293", "Id": "266200", "ParentId": "266191", "Score": "5" } }, { "body": "<p>You correctly identified that your algorithm is a bit too complicated, so let's start from scratch.</p>\n<p>The problem statement is, at its core, to iterate from AAA0001 to ZZZ9999.</p>\n<p>You should note that the license plate is divided in 2 parts:</p>\n<ul>\n<li>The letters, which will iterate from AAA to ZZZ.</li>\n<li>The digits, which will iterate from 0001 to 9999, for each combination of letters.</li>\n</ul>\n<p>So, to start with, let's imagine that the requirement is to <em>print</em> the license plates. The simplest answer possible is nested loops:</p>\n<pre><code>class LicensePlateEnumerator {\n public static void main(String[] args) {\n for (char a = 'A'; a &lt;= 'Z'; ++a) {\n for (char b = 'A'; b &lt;= 'Z'; ++b) {\n for (char c = 'A'; c &lt;= 'Z'; ++c) {\n for (int i = 1; i &lt; 10000; ++i) {\n String plate = String.format(&quot;%c%c%c%04d&quot;, a, b, c, i);\n System.out.println(plate);\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>That is the core algorithm, and it answers the question from an algorithmic perspective.</p>\n<p>Now, <em>consuming</em> its output is maybe not that easy, so you should consider some way of:</p>\n<ol>\n<li>Expressing the output: <code>String</code>? <code>LicensePlate</code>?</li>\n<li>Passing the output to the caller: <code>Iterator&lt;?&gt;</code>? <code>Stream&lt;?&gt;</code>? Taking a <code>Consumer&lt;?&gt;</code> parameter?</li>\n</ol>\n<p>Depending on your own affinities, you may favor some alternatives over others. Or whoever asked the question may.</p>\n<p>The key, though, is to <em>first</em> work out the algorithm <em>without worrying about the &quot;packaging&quot;</em>. Once you have the algorithm, you have <em>a foundation you can build upon</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:30:12.103", "Id": "525896", "Score": "1", "body": "Just as a comment, when I first wrote the draft of my code, it looked like yours solution above. Then I realized that when char b is increased by 1, char c needs to go back to 'A' or you will miss all the ABA, ABB, ABC... and so on. Same thing for when char a is increased... char b and char c needs to go back to A or else you will miss a bazilion of plates, like BAA, BAB.... The way you suggested locks the rightmost char into Z every time you reach Z for that char." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T22:40:44.827", "Id": "525902", "Score": "24", "body": "@vianna77 I think you have a fundamental misunderstanding of how loops work. Each inner loop will restart when its parent loop increments. I suggest you try to code above with just the first two characters and watch how it creates all combinations from AA to ZZ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T22:53:43.817", "Id": "525903", "Score": "1", "body": "@Turksarama thanks for pointed that out! :) It was great in more than one way. First, to remind me that I have to rest... I really could use some vacation. Also a good way to make me humble... when inner loops are such a challenging problem to solve, I really have to calm down :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T03:57:55.717", "Id": "525913", "Score": "0", "body": "Simple and best solution I have ever seen in the question!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:10:16.567", "Id": "525953", "Score": "4", "body": "@vianna77 if it helps at all, you have almost the exact right attitude to improve quickly - you're gonna make it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T09:49:46.623", "Id": "525984", "Score": "1", "body": "@vianna77: I thought more about the nested loop issue you faced, and you were not \"fully\" wrong. There are 2 kinds of nested loops: the rectangular kind (independent variables: outer from 0 to X and inner from 0 to Y) and the triangular kind (independent variables: outer from 0 to X and inner from _outer_ to Y). Your comment makes me think your brain \"locked in\" on the triangular kind, and when that happens it's really hard to notice because your eyes glaze over the data as the brain goes \"I know what I'm doing, move along\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T14:37:55.173", "Id": "526003", "Score": "0", "body": "@MatthieuM. thanks! That was comforting and heartening to read! I would add to your assessment that I guess I'm also exhausted. :P" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:01:24.940", "Id": "266205", "ParentId": "266191", "Score": "41" } }, { "body": "<p>There is no need for any OO in this topic, and design patterns are totally out of scope for this. Your program is a little complex and could deserve some simplicity.</p>\n<p>I believe that simplicity is always better, and what is simpler in your case than mapping a number to a license plate and simply increase your number to get the next one?</p>\n<p>Basically, as everybody discovered, there is a limited amount of license plates within the rules you set: <code>26 * 26 * 26 * 9999 = 175742424</code>.</p>\n<p>The only question is how to go from a simple number to the expected mapped license plate. As usual, there are various way to do so.</p>\n<p>I suggest here one such way that will allow with simple loop to generate all of your license plates in logical order of the license plate.</p>\n<pre><code> private static final int MIN_PLATE_SEQUENCE = 0;\n private static final int MAX_PLATE_SEQUENCE = 9999 * 26 * 26 * 26 - 1;\n\n static String licensePlateForSequence(int sequence) {\n if (sequence &lt; MIN_PLATE_SEQUENCE || sequence &gt; MAX_PLATE_SEQUENCE) {\n throw new IllegalArgumentException(&quot;sequence &quot; + sequence + &quot; would generate an invalid plate&quot;);\n }\n \n int digits = sequence % 9999 + 1; // digits will always be between 1 and 9999.\n sequence /= 9999;\n\n char[] letters = new char[3];\n for (int i = 2; i &gt;= 0; i--) {\n letters[i] = (char)('A' + sequence % 26);\n sequence /= 26;\n }\n \n return String.format(&quot;%s%04d&quot;, new String(letters), digits);\n }\n</code></pre>\n<p>And now, you can have a controller that calls any number with values between <code>MIN_PLACE_SEQUENCE</code> and <code>MAX_PLACE_SEQUENCE</code> (all inclusive), and just retrieve the appropriate license plate:</p>\n<p>For instance, you could go for all of them:</p>\n<pre><code> public static void main(String[] args) {\n for (int seq = MIN_PLATE_SEQUENCE; seq &lt;= MAX_PLATE_SEQUENCE; seq++) {\n System.out.println(licensePlateForSequence(seq));\n }\n }\n</code></pre>\n<p>Or you could fetch directly the values around some boundaries, just to check that everything works fine:</p>\n<pre><code> public static void main(String[] args) {\n int[] interestingSequences = {\n 0, // AAA0001\n 9998, // AAA9999\n 9999, // AAB0001\n 9999 * 26 - 1, // AAZ9999\n 9999 * 26, // ABA0001\n 9999 * 26 * 26 - 1, // AZZ9999\n 9999 * 26 * 26, // BAA0001\n 9999 * 26 * 26 * 26 - 1, // ZZZ9999\n };\n for (int plateId: interestingSequences) {\n System.out.println(licensePlateForSequence(plateId));\n }\n }\n</code></pre>\n<p>Creating a stream is now extremely easy!</p>\n<pre><code>Stream&lt;String&gt; allPlates = IntStream.range(0, MAX_PLATE_SEQUENCE + 1)\n .mapToObj(Main::licensePlateForSequence);\n</code></pre>\n<p>And an iterator isn't really hard as well!</p>\n<pre><code>class LicensePlateIterator implements Iterator&lt;String&gt; {\n private int sequence = MIN_PLATE_SEQUENCE;\n @Override public boolean hasNext() {\n return sequence &lt;= MAX_PLATE_SEQUENCE;\n }\n @Override public String next() {\n if (!hasNext()) throw new NoSuchElementException();\n String plate = licensePlateForSequence(sequence);\n sequence++;\n return plate;\n // Or the one-liner\n // return licensePlateForSequence(sequence++);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:42:19.050", "Id": "266208", "ParentId": "266191", "Score": "12" } }, { "body": "<p>We know that there are 9999*26**3 possible license plates, so one strategy would be to just generate that many integers, and then translate each integer to a license plate. I don't work with Java much, so there are likely syntax errors, but this should give the gist of it:</p>\n<pre><code>private int num_plates = 9999*26**3;\nfor (int i = 0; i &lt; num_plates; i++) {\n int digits = i%9999+1;\n int remain = (i-digits)/9999;\n int char_n1 = remain%26;\n remain = (remain-char_n1)/26;\n int char_n2 = remain%26;\n int char_n3 = (remain-char_n2)/26;\n String letters = String.fromCharCode(65+char_1, 65+char_n2, 65+char_n3);\n String plate = letters.concat(digits.to_string);\n //output plate to console or store in array\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T22:19:19.827", "Id": "266278", "ParentId": "266191", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T02:20:54.687", "Id": "266191", "Score": "19", "Tags": [ "java", "performance" ], "Title": "The car plate problem: generate from AAA0001 to ZZZ9999 skipping the 0000" }
266191
<p>The question was on Leetcode <a href="https://leetcode.com/problems/min-cost-to-connect-all-points/" rel="nofollow noreferrer">1584. Min Cost to Connect All Points.</a> My answer to this question is:</p> <pre><code>class Solution { public int minCostConnectPoints(int[][] points) { List&lt;int[]&gt; list = new ArrayList&lt;&gt;(); for(int i = 0; i &lt; points.length; i++){ for(int j = 0; j &lt; points.length; j++){ int dist = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]); list.add(new int[]{i,j,dist}); } } list.sort((int a[], int b[]) -&gt; a[2] - b[2]); UnionFindSet uf = new UnionFindSet(points.length); int totalCost = 0; for(int edges[] : list){ if(uf.Find(edges[0]) != uf.Find(edges[1])){ uf.Union(edges[0],edges[1]); totalCost += edges[2]; } } return totalCost; } } class UnionFindSet { public final int[] parents; UnionFindSet(int size) { this.parents = new int[size]; for (int i = 0; i &lt; size; i++) { this.parents[i] = i; } } public int Find(int x) { if (this.parents[x] != x) { this.parents[x] = Find(this.parents[x]); } return this.parents[x]; } public void Union(int x, int y) { this.parents[Find(y)] = Find(x); } } </code></pre> <p>My answer can pass all the test cases but the speed is extremely slow. Any idea how could I improve my code to make it faster? One of my guesses is maybe the nested for loop to calculate the Manhattan Distance is expensive, but I don't know how to omit or replace it. Any idea would be appreciated!</p>
[]
[ { "body": "<p>Your solution already seems to be implemented (rather) efficiently. My only advice is to rename <code>Find</code> and <code>Union</code> to <code>find</code> and <code>union</code>, respectively (Java style prefers lowercase chars at the first verb of a method name).</p>\n<p>In <code>UnionFindSet</code>, you have</p>\n<pre><code>public final int[] parents;\n</code></pre>\n<p>I suggest you hide it by the <code>private</code> keyword instead of <code>public</code>.</p>\n<p>In case you, in fact, seek for greater efficiency, take a look a <a href=\"https://en.wikipedia.org/wiki/Disjoint-set_data_structure\" rel=\"nofollow noreferrer\">this Wikipedia article</a>. Perhaps it makes sense to implement all the discussed implementations of the disjoint set data structure and benchmark them all in order to find the fastest version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T05:36:30.967", "Id": "266195", "ParentId": "266194", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T04:45:51.387", "Id": "266194", "Score": "2", "Tags": [ "java", "algorithm", "union-find" ], "Title": "Leetcode 1584. How to make my Kruskal&Union Find algorithm faster?" }
266194
<p>Which approach to creating repeating Runnables is better?</p> <pre class="lang-java prettyprint-override"><code> private final Handler handler = new Handler(Looper.getMainLooper()); private final Runnable runnable = new Runnable() { @Override public void run() { Timber.d(&quot;Repeating task&quot;); handler.postDelayed(this, REFRESH_DELAY); } }; @Override public void onResume() { handler.postDelayed(runnable, REFRESH_DELAY); super.onResume(); } @Override public void onPause() { handler.removeCallbacks(runnable); super.onPause(); } </code></pre> <p>or</p> <pre class="lang-java prettyprint-override"><code> private Runnable runnable; private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void onResume() { handler.postDelayed(runnable = () -&gt; { Timber.d(&quot;Repeating task&quot;); handler.postDelayed(runnable, REFRESH_DELAY); }, REFRESH_DELAY); super.onResume(); } @Override public void onPause() { handler.removeCallbacks(runnable); super.onPause(); } </code></pre> <p>I don't like the assignment and instant use of the runnable in the second approach but I'm not sure what is the consensus.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T07:47:01.050", "Id": "266196", "Score": "0", "Tags": [ "java", "comparative-review", "android", "lambda" ], "Title": "Chain the same Runnable using Handler in Android" }
266196
<p>I want to check client's browser version, and if it's too old, display a message that the user should update their browser in order to use the website. The website is built using ASP.NET MVC.</p> <p>I have implemented 2 different solutions:</p> <p><strong>Solution 1 - Server side checking:</strong></p> <p>I have created an <code>ActionFilter</code> which checks if the browser is supported? If not it redirects to a static page: NotSupportedBrowser.aspx</p> <pre><code>public class BrowserSupportFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext filterContext) { string browserInfo; if (BrowserHelper.IsOutdatedBrowser(out browserInfo)) { filterContext.Result = new RedirectResult(&quot;/ErrorPages/NotSupportedBrowser.aspx?browserInfo=&quot; + browserInfo); } } public void OnActionExecuted(ActionExecutedContext context) { } } </code></pre> <p>And this is my <code>BrowserHelper</code> class which checks if the browser is supported:</p> <pre><code>public static class BrowserHelper { public static bool IsOutdatedBrowser(out string browserInfo) { bool isOutdated = false; var browser = HttpContext.Current.Request.Browser; if (!string.IsNullOrEmpty(browser.Browser) &amp;&amp; float.TryParse(browser.Version, out float browserVersion)) { switch (browser.Browser) { case &quot;Chrome&quot;: if (browserVersion &lt; 57) { isOutdated = true; } break; case &quot;Edge&quot;: if (browserVersion &lt; 15) { isOutdated = true; } break; case &quot;Safari&quot;: if (browserVersion &lt; 12) { isOutdated = true; } break; case &quot;Mobile Safari&quot;: if (browserVersion &lt; 12) { isOutdated = true; } break; case &quot;Firefox&quot;: if (browserVersion &lt; 50) { isOutdated = true; } break; case &quot;Opera&quot;: if (browserVersion &lt; 50) { isOutdated = true; } break; case &quot;Vivaldi&quot;: if (browserVersion &lt; 1) { isOutdated = true; } break; case &quot;Yandex&quot;: if (browserVersion &lt; 17) { isOutdated = false; } break; case &quot;InternetExplorer&quot;: isOutdated = true; break; default: isOutdated = false; break; } } browserInfo = $&quot;{browser.Browser}{browser.Version}&quot;; return isOutdated; } } </code></pre> <p><strong>Solution 2 - Client side checking</strong></p> <p>In the second solution, I check the browser in the client side and show a popup, letting the user know that their browse is not supported:</p> <p>I have created <em>_BrowserSupport.cshtml</em> PartialView:</p> <p><em>I got the code for testing the browser from <a href="https://stackoverflow.com/questions/35682138/html5-date-picker-doesnt-show-on-safari/68840794#68840794">this stackoverflow question</a>.</em></p> <pre><code>&lt;script&gt; navigator.browserInfo = (function () { alert(navigator.userAgent); var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])) { tem = /\brv[ :]+(\d+)/g.exec(ua) || []; return 'IE ' + (tem[1] || ''); } if (M[1] === 'Chrome') { tem = ua.match(/\b(OPR|Edge)\/(\d+)/); if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera'); } M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]); return M.join(' '); })(); //document.getElementById('printVer').innerHTML=navigator.browserInfo var str = navigator.browserInfo; var browser = str.substring(0, str.indexOf(&quot; &quot;)); var version = str.substring(str.indexOf(&quot; &quot;)); version = version.trim(); version = parseFloat(version); var isOutdated = false; switch (browser) { case &quot;Chrome&quot;: if (version &lt; 57) { isOutdated = true; } break; case &quot;Edge&quot;: if (version &lt; 16) { isOutdated = true; } break; case &quot;Safari&quot;: if (version &lt; 12) { isOutdated = true; } break; case &quot;Mobile Safari&quot;: if (version &lt; 11) { isOutdated = true; } break; case &quot;Firefox&quot;: if (version &lt; 62) { isOutdated = true; } break; case &quot;Opera&quot;: if (version &lt; 50) { isOutdated = true; } break; case &quot;Vivaldi&quot;: if (version &lt; 1) { isOutdated = true; } break; case &quot;Yandex&quot;: if (version &lt; 17) { isOutdated = false; } break; case &quot;IE&quot;: isOutdated = true; break; } if (isOutdated) { alert(&quot;Your browser is not supported:&quot; + browser + version); } &lt;/script&gt; </code></pre> <p>I include the above partial view in the <code>head</code> section of all of my page Layouts, e.g.</p> <p><em>samplePageLayout</em>:</p> <pre><code>&lt;head&gt; @Html.Partial(&quot;Common/_BrowserSupport&quot;) &lt;/head&gt; </code></pre> <p><strong>Trade-offs</strong></p> <p>Both solutions works... I am not sure which one would be better.</p> <ul> <li><p>The advantage of doing the check on the Server side is that my html document becomes smaller and there will be less data to download on every single request.</p> </li> <li><p>The advantage of doing the check on the client side is that I am using the client's processing power to do the check and therefore there is less task for the Server.</p> </li> </ul> <p>I am asking for recommendation to choose the better option.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T12:20:19.280", "Id": "525850", "Score": "0", "body": "I can't speak to which would be the best, but I can point out that your switch statement could be its own function and instead of doing `if (version < 57) { isOutdated = true; } break;` you could just do `return version < 57;` which is a lot less boilerplate code." } ]
[ { "body": "<p>I always go with the version that would be a best fit to the project.</p>\n<p>This means, you need to consider the overall project coding syntax, and how much code in the client side, to know where to focus more.</p>\n<p>Some projects focuses on server side more than using the client side handling, so in this case using the server side would be better to keep the code in harmony.</p>\n<p>For the <code>switch</code> part, it would be more maintainable if you just use <code>Dictionary</code> in the server side, or <code>object</code> in client side.</p>\n<p>Server-Side :</p>\n<pre><code>public static class BrowserHelper\n{\n private static readonly IReadOnlyDictionary&lt;string , int&gt; _browserMinimumSupportedVersions = new Dictionary&lt;string, int&gt;\n {\n {&quot;Chrome&quot;, 57},\n {&quot;Edge&quot;, 15},\n {&quot;Safari&quot;, 12},\n {&quot;Mobile Safari&quot;, 12},\n {&quot;Firefox&quot;, 50},\n {&quot;Opera&quot;, 50},\n {&quot;Vivaldi&quot;, 1},\n {&quot;Yandex&quot;, 17}\n\n };\n\n public static bool IsOutdatedBrowser(out string browserInfo)\n {\n browserInfo = null;\n\n var browser = HttpContext.Current.Request.Browser;\n\n if(browser.Browser == &quot;InternetExplorer&quot;) { return true; }\n\n browserInfo = $&quot;{browser.Browser}{browser.Version}&quot;;\n\n return _browserMinimumSupportedVersions.TryGetValue(browser.Browser , out int minVersion) &amp;&amp; float.TryParse(browser.Version , out float browserVersion) &amp;&amp; browserVersion &lt; minVersion;\n }\n}\n</code></pre>\n<p>you can achieve the same in the client side by doing this :</p>\n<pre><code>function isOutdatedBrowser(name, version) {\n \n if(name == 'IE') { return true; }\n \n const minimumVersions = \n { \n &quot;Chrome&quot;: 57,\n &quot;Edge&quot;: 15, \n &quot;Safari&quot;: 12, \n &quot;Mobile Safari&quot;: 12, \n &quot;Firefox&quot;: 50, \n &quot;Opera&quot;: 50, \n &quot;Vivaldi&quot;: 1, \n &quot;Yandex&quot;: 17 \n };\n \n var browserVersion = minimumVersions[browser];\n\n return browserVersion &amp;&amp; version &lt; browserVersion;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T16:44:06.947", "Id": "266246", "ParentId": "266201", "Score": "3" } } ]
{ "AcceptedAnswerId": "266246", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T10:18:09.663", "Id": "266201", "Score": "1", "Tags": [ "c#", "javascript", "html", "asp.net-mvc", "cross-browser" ], "Title": "Detecting supported browsers in ASP.NET MVC (Server side vs. Client side)" }
266201
<p>I created a watchdog/notifier in C++ and wanted to make it better so it could be used by multiple people. The idea is that there is a timer class and event. client create events and pass a lambda function, timeout in seconds and repeat mode i.e. whether to keep the event active after a timeout or deactivate once the timeout is reached (default mode). The event can be activated and deactivated by the client on-demand or has done in the lambda function.</p> <p><strong>timer.hpp</strong></p> <pre><code>#pragma once #include &lt;functional&gt; #include &lt;chrono&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;set&gt; #include &lt;stack&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; #include &lt;algorithm&gt; struct Event { unsigned int id {0}; std::chrono::time_point&lt;std::chrono::steady_clock&gt; startTimepoint; std::chrono::seconds timeout {std::chrono::seconds::zero()}; std::function&lt;void(unsigned int id)&gt; function {nullptr}; // handler bool isRepeated {false}; bool isActive {false}; bool isExecuted {false}; Event(unsigned int p_id, std::chrono::seconds p_timeout, std::function&lt;void(unsigned int p_id)&gt;&amp;&amp; p_function, bool p_isRepeated) : id(p_id), timeout(p_timeout), function(p_function), isRepeated(p_isRepeated) { } }; struct TimeEvent { std::chrono::time_point&lt;std::chrono::steady_clock&gt; nextTimepoint; unsigned int eventID; }; inline bool operator&lt;(const TimeEvent&amp; l, const TimeEvent&amp; r) { return l.nextTimepoint &lt; r.nextTimepoint; } class Timer { public: Timer(); virtual ~Timer(); unsigned int RegisterEvent(std::function&lt;void(unsigned int p_id)&gt;&amp;&amp; p_function, std::chrono::seconds timeout = std::chrono::seconds::zero(), bool isRepeated = false); bool RemoveEvent(unsigned int id); bool ActivateEvent(unsigned int id, int timeout = 0); bool IsActivated(unsigned int id) const; bool DeactiveEvent(unsigned int id); bool DeactivateAllEvent(); bool IsExecuted(unsigned int id) const; private: void Run(); std::mutex m_mutex {}; std::condition_variable m_condition {}; std::thread m_workerThread {}; bool m_isTimerActive {true}; std::vector&lt;Event&gt; m_eventsList {}; std::set&lt;TimeEvent&gt; m_activeTimeEventSet {}; //Auto ordered due to set std::stack&lt;unsigned int&gt; m_freeEventIds {}; }; </code></pre> <p><strong>timer.cpp</strong></p> <pre><code>#include &quot;timer.hpp&quot; void Timer::Run() { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); while (m_isTimerActive) { if (m_activeTimeEventSet.empty()) { m_condition.wait(lock); } else { TimeEvent te = *m_activeTimeEventSet.begin(); if (std::chrono::steady_clock::now() &gt;= te.nextTimepoint) { m_activeTimeEventSet.erase(m_activeTimeEventSet.begin()); lock.unlock(); m_eventsList[te.eventID].function(te.eventID); lock.lock(); m_eventsList[te.eventID].isExecuted = true; if (m_eventsList[te.eventID].isActive &amp;&amp; m_eventsList[te.eventID].isRepeated) { te.nextTimepoint += std::chrono::duration_cast&lt;std::chrono::seconds&gt;(m_eventsList[te.eventID].timeout); m_activeTimeEventSet.insert(te); } else { m_eventsList[te.eventID].isActive = false; } } else { m_condition.wait_until(lock, te.nextTimepoint); } } } } Timer::Timer() { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); m_workerThread = std::thread([this] { Run(); }); } Timer::~Timer() { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); lock.unlock(); m_isTimerActive = false; m_condition.notify_all(); m_workerThread.join(); m_eventsList.clear(); m_activeTimeEventSet.clear(); while (!m_freeEventIds.empty()) { m_freeEventIds.pop(); } } unsigned int Timer::RegisterEvent(std::function&lt;void(unsigned int p_id)&gt;&amp;&amp; p_function, std::chrono::seconds timeout, bool isRepeated) { unsigned int id; std::unique_lock&lt;std::mutex&gt; lock(m_mutex); if (m_freeEventIds.empty()) { id = m_eventsList.size(); Event e(id, timeout, std::move(p_function), isRepeated); m_eventsList.push_back(std::move(e)); } else { id = m_freeEventIds.top(); Event e(id, timeout, std::move(p_function), isRepeated); m_freeEventIds.pop(); m_eventsList[id] = std::move(e); } lock.unlock(); m_condition.notify_all(); return id; } bool Timer::ActivateEvent(unsigned int id, int timeout) { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); if (m_eventsList.size() == 0 || m_eventsList.size() &lt; id) { return false; } if(timeout) { m_eventsList[id].timeout = std::chrono::seconds(timeout); } if (m_eventsList[id].timeout &gt; std::chrono::seconds::zero()) { m_eventsList[id].isActive = true; m_eventsList[id].isExecuted = false; m_eventsList[id].startTimepoint = std::chrono::steady_clock::now(); auto it = std::find_if(m_activeTimeEventSet.begin(), m_activeTimeEventSet.end(), [&amp;](const TimeEvent &amp; te) { return te.eventID == id; }); if (it != m_activeTimeEventSet.end()) { m_activeTimeEventSet.erase(it); } m_activeTimeEventSet.insert(TimeEvent {m_eventsList[id].startTimepoint + std::chrono::duration_cast&lt;std::chrono::seconds&gt;(m_eventsList[id].timeout), id }); } lock.unlock(); m_condition.notify_all(); return true; } bool Timer::IsActivated(unsigned int id) const { return m_eventsList[id].isActive; } bool Timer::DeactiveEvent(unsigned int id) { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); if (m_eventsList.size() == 0 || m_eventsList.size() &lt; id) { return false; } m_eventsList[id].isActive = false; auto it = std::find_if(m_activeTimeEventSet.begin(), m_activeTimeEventSet.end(), [&amp;](const TimeEvent &amp; te) { return te.eventID == id; }); if (it != m_activeTimeEventSet.end()) { m_activeTimeEventSet.erase(it); } lock.unlock(); m_condition.notify_all(); return true; } bool Timer::RemoveEvent(unsigned int id) { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); if (m_eventsList.size() == 0 || m_eventsList.size() &lt; id) { return false; } m_eventsList[id].isActive = false; auto it = std::find_if(m_activeTimeEventSet.begin(), m_activeTimeEventSet.end(), [&amp;](const TimeEvent &amp; te) { return te.eventID == id; }); if (it != m_activeTimeEventSet.end()) { m_freeEventIds.push(it-&gt;eventID); m_activeTimeEventSet.erase(it); // Note: Do not erase from eventsList, else the other ids becomes invalid } lock.unlock(); m_condition.notify_all(); return true; } bool Timer::IsExecuted(unsigned int id) const { return m_eventsList[id].isExecuted; } bool Timer::DeactivateAllEvent() { std::unique_lock&lt;std::mutex&gt; lock(m_mutex); if (m_eventsList.size() == 0) { return true; } for (unsigned int i = 0; i &lt; m_eventsList.size(); ++i) { m_eventsList[i].isActive = false; m_eventsList[i].isExecuted = false; m_freeEventIds.push(m_eventsList[i].id); } m_activeTimeEventSet.erase(m_activeTimeEventSet.begin(), m_activeTimeEventSet.end()); lock.unlock(); m_condition.notify_all(); return true; } </code></pre> <p><strong>client.cpp</strong></p> <pre><code>#include &quot;timer.hpp&quot; #include &lt;iostream&gt; #include &lt;chrono&gt; #include &lt;thread&gt; using namespace std; int quickFunc(bool &amp;done) { std::this_thread::sleep_for(std::chrono::seconds(10)); std::cout &lt;&lt; &quot;MAIN: quickFunc() executed&quot; &lt;&lt; std::endl; done = true; } int slowFunc(bool &amp;done) { for(size_t i = 0; i &lt; 10; ++i) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout &lt;&lt; &quot;MAIN: slowFunc() executing&quot; &lt;&lt; std::endl; } std::cout &lt;&lt; &quot;MAIN: slowFunc() executed&quot; &lt;&lt; std::endl; done = true; } int main() { Timer* timer = new Timer(); bool quickFuncDone = false; bool slowFuncDone = false; unsigned int id1 = timer-&gt;RegisterEvent([&amp;](unsigned int) { if(quickFuncDone == false) { std::cout &lt;&lt; &quot;MAIN: quickFunc() not executed, will not observe&quot; &lt;&lt; std::endl; } }, std::chrono::seconds(2)); timer-&gt;ActivateEvent(id1); quickFunc(quickFuncDone); unsigned int id2 = timer-&gt;RegisterEvent([&amp;](unsigned int) { if(slowFuncDone == false) { std::cout &lt;&lt; &quot;WATCHDOG: slowFunc() is not yet completed, continue observing&quot; &lt;&lt; std::endl; } else { std::cout &lt;&lt; &quot;WATCHDOG: slowFunc() is completed, deactivating myself&quot; &lt;&lt; std::endl; timer-&gt;DeactiveEvent(id2); } }, std::chrono::seconds(2), true); timer-&gt;ActivateEvent(id2); slowFunc(slowFuncDone); std::this_thread::sleep_for(std::chrono::seconds(30)); delete timer; return 0; } </code></pre> <p>Looking forward to some good edits and suggestions so it becomes generic and can be released to the public for wider use.</p>
[]
[ { "body": "<h1>Move <code>Event</code> and <code>TimeEvent</code> inside <code>class Timer</code></h1>\n<p>These types are just implementation details of your <code>Timer</code> class, and are not part of the public API. So by moving them into <code>class Timer</code>, you avoid polluting the global namespace. It's simply:</p>\n<pre><code>class Timer {\n struct Event {\n ...\n };\n\n struct TimeEvent {\n ...\n };\n\n ...\n};\n</code></pre>\n<p>One issue is the <code>operator&lt;()</code> for <code>TimeEvent</code>s. You can't move that into <code>class Timer</code> like it is, because then it might think it's overloading <code>Timer</code>'s own comparison operator. You can either make it <code>friend</code>, or just move it into <code>struct TimeEvent</code>; there is no reason here why it should be a free function.</p>\n<h1>Consider creating an alias for the clock</h1>\n<p>You are using <code>std::chrono::steady_clock</code> in a few places. It's the right clock to use, but you can avoid typing that long name and make it easier to switch to another clock later by creating an alias for it:</p>\n<pre><code>class Timer {\n using clock = std::chrono::steady_clock;\n\n struct Event {\n ...\n clock::time_point startTimepoint;\n ...\n };\n ...\n};\n</code></pre>\n<h1>Simplify initializing variables to zero</h1>\n<p>You are explicitly writing out the zero value for each variable you initialize, like in this line:</p>\n<pre><code>std::chrono::seconds timeout {std::chrono::seconds::zero()};\n</code></pre>\n<p>But you can use the empty brace syntax to do this:</p>\n<pre><code>std::chrono::seconds timeout {};\n</code></pre>\n<p>The same goes for <code>0</code>, <code>false</code>, <code>nullptr</code> and so on. The benefit is that if you ever change the type of something, you don't need to change the value you initialized it with (unless it was a non-zero value of course).</p>\n<p>Some types like <code>std::mutex</code>, as well as most containers, don't need to be explicitly &quot;zeroed&quot; at all, so these don't even need the <code>{}</code>.</p>\n<h1>No need to explicitly clear containers in the destructor</h1>\n<p>In <code>Timer::~Timer()</code>, you explicitly clear all the containers, but the destructor of those containers will be called automatically after your destructor, and those will take care of clearing themselves.</p>\n<h1>Ensure you handle events with identical expiration times</h1>\n<p>What if two events at some point will have the same value for <code>nextTimePoint</code>? The problem is that this will result in a conflict when trying to add them both to a <code>std::set</code>. Either ensure you disambiguate between two events in the comparison function (for example, check first if the timepoints are equal, if so compare <code>eventID</code> instead), or use <a href=\"https://en.cppreference.com/w/cpp/container/multiset\" rel=\"nofollow noreferrer\"><code>std::multiset</code></a>.</p>\n<h1>Remove useless member variables</h1>\n<p>There are some member variables that are not used at all, or don't seem to have a very useful purpose:</p>\n<ul>\n<li><code>Event::startTimepoint</code> is set at construction time but never read from.</li>\n<li><code>Event::isExecuted</code> is not used by the client code. Is it even necessary? If some flag is necessary, the callback function could set it itself. Also, it is reset in <code>Timer::DeactivateAllEvent()</code>, which is confusing to me: why would deactivating an event that has executed before reset that flag?</li>\n<li><code>Event::isActive</code> is unnecessary, why not just call <code>RemoveEvent()</code> and add it back with <code>RegisterEvent()</code>, or alternatively deactivate it by setting the timeout to effectively infinity.</li>\n</ul>\n<p>Removing unnecessary member variables keeps <code>struct</code>s and <code>class</code>es small, which is especially important if you need lots of them.</p>\n<p>Once you remove the support for registered but inactive events, you could also consider getting rid of <code>Timer::m_eventsList</code>, move <code>nextTimepoint</code> from <code>TimeEvent</code> into <code>Event</code>, so you just have a set of <code>Event</code>s sorted on next expiration time.</p>\n<h1>ID bookkeeping</h1>\n<p>There are some issues having an integer ID for events. You need some way to do the bookkeeping of which IDs are free. If you create a thousand events and then unregister them all, then you suddenly have <code>Timer::m_freeEventIds</code> containing a thousand integers. Also, despite looking up an event by ID in <code>m_eventsList</code> being <span class=\"math-container\">\\$\\mathcal O(1)\\$</span>, you still need to use <code>std::find_if()</code> to find the corresponding element in <code>m_activeTimeEventSet</code> when deregistering an event. This is an <span class=\"math-container\">\\$\\mathcal O(N)\\$</span> operation.</p>\n<p>If you could use C++17, I would just store the <code>Event</code>s this way:</p>\n<pre><code>struct EventCmp {\n bool operator()(const std::unique_ptr&lt;Event&gt; &amp;a, const std::unique_ptr&lt;Event&gt; &amp;b) {\n if (a-&gt;nextTimepoint == b-&gt;nextTimepoint)\n return a.get() &lt; b.get();\n else \n return a-&gt;nextTimepoint == b-&gt;nextTimepoint ? ;\n }\n};\n\nstd::set&lt;std::unique_ptr&lt;Event&gt;, EventCmp&gt; m_events;\n</code></pre>\n<p>And then use the raw pointer as the ID. So to register an event:</p>\n<pre><code>Event *Timer::RegisterEvent(...)\n{\n // Allocate the event\n auto event = std::make_unique&lt;Event&gt;(timeout, p_function, ...);\n\n // Move the event into the set of events\n std::unique_lock&lt;std::mutex&gt; lock(m_mutex);\n m_events.insert(std::move(event));\n\n // Return a pointer to the event\n return event.get();\n}\n</code></pre>\n<p>You could make this safer by wrapping the pointer in a class, possibly named <code>EventHandle</code>, to prevent the caller from modifying the event.</p>\n<p>When you run the event loop, you move the <code>Event</code> out of the set using <a href=\"https://en.cppreference.com/w/cpp/container/set/extract\" rel=\"nofollow noreferrer\"><code>std::set::extract()</code></a> and insert it back in after modifying its <code>nextTimepoint</code>, like so:</p>\n<pre><code>void Timer::Run() {\n ...\n auto node = m_events.extract(m_events.begin());\n Event *event = node.value().get();\n\n if (event-&gt;isRepeated)\n event-&gt;nextTimePoint += event-&gt;timeout;\n else\n event-&gt;nextTimePoint = /* infinity */;\n\n event-&gt;function(event);\n m_events.insert(node);\n ...\n};\n</code></pre>\n<p>This requires C++17 though, as using <code>std::set::extract()</code> is the only way to <a href=\"https://stackoverflow.com/questions/45030932/extracting-move-only-type-from-stdset\">move a <code>std::unique_ptr</code> in and out of a set</a>. You can make it work with C++11 if you store raw pointers instead of <code>std::unique_ptr</code>s in the set, and then you first make a copy of the pointer, then <code>erase()</code> it from the set, and insert it afterwards again:</p>\n<pre><code>std::set&lt;Event *, EventCmp&gt; m_events;\n...\nvoid Timer::Run() {\n ...\n Event *event = *m_events.begin();\n m_events.erase(m_events.begin());\n\n if (event-&gt;isRepeated)\n event-&gt;nextTimePoint += event-&gt;timeout;\n else\n event-&gt;nextTimePoint = /* infinity */;\n\n event-&gt;function(event);\n m_events.insert(event);\n ...\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T16:38:27.033", "Id": "266212", "ParentId": "266202", "Score": "1" } } ]
{ "AcceptedAnswerId": "266212", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T12:07:02.103", "Id": "266202", "Score": "2", "Tags": [ "c++11", "timer" ], "Title": "watchdog for c++11" }
266202
<p><em>This is my very first time here, I am coming from stackoverflow.com thanks to @r2evans. So I apologize in advance if I don't follow all the rules.</em></p> <p>I wrote a code in <code>data.table</code>, doing what I am expected of it. It is not so complicated : mainly sum, group by, or some basic calculations.</p> <p>But my real challenge here is called <strong>performance</strong>. Real datas contain millions of lines, and the calculations are made on dozens and dozens of columns.</p> <p>Now, let me show you the code I wrote (with some options) :</p> <pre><code> library(data.table) library(stringr) library(microbenchmark) library(tictoc) n.row &lt;- 1e5 foo &lt;- data.table(id = 101:(101+n.row-1), crit = rep(c('fr', 'ca', 'al', 'se', 'is'), 5), val_1 = round(runif(n.row, 0.5, 50), digits = 2), val_2 = round(runif(n.row, 1, 20), digits = 0), val_3 = round(runif(n.row, 1, 5), digits = 0), eff = 28500, num = sample(0:1,n.row, replace = TRUE), num_2 = round(runif(n.row, 1, 10), digits = 1), num_17 = round(runif(n.row, 1, 10), digits = 1), num_69 = round(runif(n.row, 0, 1), digits = 2), num_5 = round(runif(n.row, 10, 20), digits = 0), cof = round(runif(n.row, 0.1, 2), digits = 5), ToDo = rep(1, n.row), grp_0 = &quot;TOT&quot;, grp_1 = sample(LETTERS[c(1,3)], n.row, replace = TRUE)) foo[, c(&quot;grp_2&quot;, &quot;grp_3&quot;) := { grp_2 = fcase(grp_1 %in% LETTERS[c(1)], sample(LETTERS[c(5,8,9)], n.row, replace = TRUE), grp_1 %in% LETTERS[c(3)], sample(LETTERS[c(14,16)], n.row, replace = TRUE)) grp_3 = fcase(grp_1 %in% LETTERS[c(1)], sample(LETTERS[c(20:23)], n.row, replace = TRUE), grp_1 %in% LETTERS[c(3)], sample(LETTERS[c(24:26)], n.row, replace = TRUE)) list(grp_2, grp_3) }] # Calcul sd and qa foo[, `:=` ( sd = val_1 * cof, qa = fifelse(num == 1, val_2 * cof, val_3 * cof) )] foo1 &lt;- copy(foo) foo2 &lt;- copy(foo) foo3 &lt;- copy(foo) # calcul of qa_X var.calc &lt;- names(foo)[str_which(names(foo), &quot;^num.\\d+$&quot;)] # 1.1 for (j in var.calc){ foo1[, paste0(&quot;qa_&quot;, str_extract(j, &quot;\\d+$&quot;)) := qa * get(j)] } # 1.2 setDT(foo2)[, paste0(&quot;qa_&quot;, str_extract(var.calc, &quot;\\d+$&quot;)) := lapply(.SD, function(x) x * qa), .SDcols = var.calc ] # 1.3 for (j in var.calc) set(foo3, j = paste0(&quot;qa_&quot;, str_extract(j, &quot;\\d+$&quot;)), value = foo3$qa * foo3[[j]]) # compare mbm &lt;- microbenchmark( Test.for = for (j in var.calc){ foo1[, paste0(&quot;qa_&quot;, str_extract(j, &quot;\\d+$&quot;)) := qa * get(j)] }, Test.set = setDT(foo2)[, paste0(&quot;qa_&quot;, str_extract(var.calc, &quot;\\d+$&quot;)) := lapply(.SD, function(x) x * qa), .SDcols = var.calc ], Test.for.set = for (j in var.calc) set(foo3, j = paste0(&quot;qa_&quot;, str_extract(j, &quot;\\d+$&quot;)), value = foo3$qa * foo3[[j]]), times = 20 ) mbm # calcul by groups var.grp &lt;- names(foo)[str_which(names(foo), &quot;^grp.\\d+$&quot;)] var.calc.2 &lt;- names(foo2)[str_which(names(foo2), &quot;^(sd|qa)&quot;)] # 2.1 for (j in var.grp) { for (k in var.calc.2) { foo1[, paste0(&quot;s.&quot;, k, &quot;_&quot;, j) := sum(get(k)), by = get(j)] } } # 2.2 for (j in var.grp) { setDT(foo2)[, paste0(&quot;s.&quot;, var.calc.2, &quot;_&quot;, j) := lapply(.SD, function(x) sum(x)), .SDcols = var.calc.2, by = j ] } </code></pre> <p>As I said, I am really looking for speed. So if anybody has some advice, some tips, another way to obtain the results, it would be very appreciable.</p> <p>Many thanks.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T13:33:08.263", "Id": "266204", "Score": "1", "Tags": [ "r" ], "Title": "Combine several calculations on several variables" }
266204
<p>A newbie here. I have done this assignment that my university gave.</p> <p><strong>Requirements</strong></p> <ul> <li><p>Participants may enter the tournament as individuals or as part of a team**</p> </li> <li><p>It is expected that will be 4 teams each with 5 members and there will be 20 spaces for individual competitors</p> </li> <li><p>Each team or individual will complete 5 events</p> </li> <li><p>Each event will be defined as a team or individual event</p> </li> <li><p>The events will vary in type, from sporting to academic challenges</p> </li> <li><p>Individuals and teams will be awarded points according to their rank within each event</p> </li> <li><p>The points awarded for each event are as yet undecided and the college are willing to hear any suggestions you may have</p> </li> <li><p>Also the college would like to include the possibility of entering for one event only</p> </li> </ul> <p>I would like to know if my code is good enough or not. Or if there is more to be added and fixed.</p> <p>When reviewing my program, kindly consider the following.</p> <ul> <li>Suitability for audience and purpose of Scoring System</li> <li>Meet criteria</li> <li>Ease of Use</li> <li>Quality of the software solution e.g. reliability, usability, efficiency/performance, maintainability,</li> <li>constraints, , programmer knowledge</li> <li>Strengths and weaknesses of my software</li> <li>Improvements that can be made</li> <li>Optimising software solutions, e.g. improving robustness, improving efficiency of the code, adding additional functionality</li> </ul> <p>CODE</p> <pre class="lang-java prettyprint-override"><code>import java.util.Arrays; import java.util.Scanner; class ScoreSystem { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // explanation of rules to the client to provide what the program is capable of System.out.println(&quot;Scoring System&quot;); System.out.println(&quot;\nScoring System Rules&quot; + &quot;\nNormal Scoring Rules\n&quot; + &quot;Rank 1 gives 20 points for Normal Teams and Participants&quot;); System.out.println(&quot;Rank 2 gives 10 points and Rank 3 gives 5 points&quot;); System.out.println(&quot;Rank 4 and lower will not receive any points\n&quot;); System.out.println(&quot;For Special Teams and Individuals&quot;); System.out.println(&quot;Rank 1 gives 100 points , Rank 2 Gives 80 points and Rank 3 Gives 60 points&quot;); System.out.println(&quot;Rank 4 or lower will not give any points&quot;); System.out.println(&quot;Constant Rules&quot;); System.out.println(&quot;5 Events are set for Normal Teams and Individuals&quot;); System.out.println(&quot;Only 1 event is allowed for Special Teams and Individuals &quot;); System.out.println(&quot;There can only be 5 participants in both normal and special team\n&quot;); System.out.println(&quot;Common Rules&quot;); System.out.println(&quot;Normal Teams and Participants will participate in 5 events&quot;); System.out.println(&quot;Special Teams and Participants will participate in only 1 event&quot;); // the start of teams // number of teams System.out.println(&quot;-----Teams------&quot;); System.out.println(&quot;Enter Amount of Teams Entering 5 EVENTS&quot;); int teamNo = scan.nextInt(); String[] teamName = new String[teamNo]; int[] teamScore = new int[teamNo]; String[] Tevent = new String[5]; String[] teamPart = new String[teamNo * 5]; int teamRank; int eventNo = 5; // condition check for number of teams // skip all of team code if 0 if (teamNo == 0) { } else { // event names for (int i = 0; i &lt; 5; i++) { System.out.println(&quot;Enter Event Name &quot; + (i + 1) + &quot; for the teams&quot;); Tevent[i] = scan.next(); } for (int i = 0; i &lt; teamNo; i++) { // participant names for the teams for (int a = 0; a &lt; 5; a++) { System.out.println(&quot;Enter Participant name &quot; + (a + 1) + &quot; for team &quot; + (i + 1)); teamPart[i] = scan.next(); } } // name and rank of the teams for (int i = 0; i &lt; teamNo; i++) { System.out.println(&quot;Enter Name of team &quot; + (i + 1)); teamName[i] = scan.next(); for (int a = 0; a &lt; eventNo; a++) { System.out.println(&quot;Enter rank of the team on the event &quot; + (a + 1)); teamRank = scan.nextInt(); int tRank = 0; // scoring system for the teams switch (teamRank) { case 3: tRank = 5; break; case 2: tRank = 10; break; case 1: tRank = 20; break; } if (teamRank == 0 || teamRank &gt;= 4) { System.out.println(&quot;This team will not be awarded points&quot;); } else { teamScore[i] += tRank; System.out.println(tRank + &quot; points is granted for this event&quot;); } if (scan.hasNextLine()) { scan.nextLine(); } } } } // the start of individual participants // number of individuals System.out.println(&quot;-----Individuals-----&quot;); int PartNo; do { System.out.println(&quot;Enter the number of individuals participating 5 EVENTS&quot; + &quot; LIMITED SPACE OF 20&quot;); PartNo = scan.nextInt(); } while (PartNo &gt; 20); String[] PartName = new String[PartNo]; int[] PartScore = new int[PartNo]; String[] Pevent = new String[5]; int PartRank; // condition checking // skip all code for individual if 0 if (PartNo == 0) { } else { // event name for the individuals System.out.println(&quot;Enter the 5 event names for participants &quot;); for (int i = 0; i &lt; 5; i++) { System.out.println(&quot;Enter Name of the event &quot; + (i + 1) + &quot; that the individuals are entering&quot;); Pevent[i] = scan.next(); } // name and rank of the individuals for (int i = 0; i &lt; PartNo; i++) { System.out.println(&quot;Enter name of Individual &quot; + (i + 1)); PartName[i] = scan.next(); for (int a = 0; a &lt; 5; a++) { System.out.println(&quot;Enter rank of the individual on the event &quot; + (a + 1)); PartRank = scan.nextInt(); int pRank = 0; // start of scoring system for the individuals switch (PartRank) { case 3: pRank = 5; break; case 2: pRank = 10; break; case 1: pRank = 20; break; } if (PartRank == 0 || PartRank &gt;= 4) { System.out.println(&quot;This team will not be awarded points&quot;); } else { PartScore[i] += pRank; System.out.println(pRank + &quot; points is granted for this event&quot;); } if (scan.hasNextLine()) { scan.nextLine(); } } } } System.out.println(&quot;Special Teams and Individuals Represent Teams and Individuals entering only 1 event&quot;); System.out.println(&quot; If there are no Special Teams or Individuals Enter 0 when the amount is asked&quot;); // the start of special teams // number of special teams System.out.println(&quot;-----Special_Teams-----&quot;); System.out.println(&quot;Enter Amount of Teams Entering only 1 EVENT&quot;); int SpecTeamNo = scan.nextInt(); String[] SpecTeamName = new String[SpecTeamNo]; String[] STevent = new String[1]; int[] SpecTeamScore = new int[SpecTeamNo]; String[] SteamPart = new String[(20 - PartNo) * 5]; int sTeamRank; // condition checking for number of special teams //skip if 0 if (SpecTeamNo == 0) { } else { // event for special team for (int i = 0; i &lt; 1; i++) { System.out.println(&quot;Enter Event Name &quot; + (i + 1) + &quot; for the teams&quot;); STevent[i] = scan.next(); } // participant name for special team for (int a = 0; a &lt; SpecTeamNo; a++) { for (int i = 0; i &lt; 5; i++) { System.out.println(&quot;Enter Participant name &quot; + (i + 1) + &quot; for team &quot; + (a + 1)); SteamPart[i] = scan.next(); } } // name and rank of special teams for (int i = 0; i &lt; SpecTeamNo; i++) { System.out.println(&quot;Enter Name of team &quot; + (i + 1)); SpecTeamName[i] = scan.next(); for (int a = 0; a &lt; 1; a++) { System.out.println(&quot;Enter rank of the team on the event&quot;); sTeamRank = scan.nextInt(); int stRank = 0; // scoring system for special team switch (sTeamRank) { case 3: stRank = 60; break; case 2: stRank = 80; break; case 1: stRank = 100; break; } if (sTeamRank == 0 || sTeamRank &gt;= 4) { System.out.println(&quot;This team will not be awarded points&quot;); } else { SpecTeamScore[i] += stRank; System.out.println(stRank + &quot; points is granted for this event&quot;); } if (scan.hasNextLine()) { scan.nextLine(); } } } } // the start of special individuals // number of special individuals System.out.println(&quot;-----Special_Individuals-----&quot;); if (PartNo == 20) { System.out.println(&quot;No special individuals will be added as only 20 individuals are allowed&quot;); } else { int SpecPartNo; do { System.out.println(&quot;only 20 spaces are available for individuals and special individuals combined &quot;); System.out.println(&quot;Please Enter Appropriate Amount of Participants&quot;); System.out.println(&quot;Enter Number of Individuals only Entering 1 event &quot;); SpecPartNo = scan.nextInt(); } while (SpecPartNo &gt; 20 - PartNo); String[] SpecPartName = new String[SpecPartNo]; String[] SPevent = new String[1]; int[] SpecPartScore = new int[SpecPartNo]; //condition checking number of special individuals //skip all codes for special individuals if 0 if (SpecPartNo == 0) { } else { // event for the special individuals for (int i = 0; i &lt; 1; i++) { System.out.println(&quot;Enter Event Name &quot; + (i + 1) + &quot; for the individuals&quot;); SPevent[i] = scan.next(); } // name and rank input of special individuals for (int i = 0; i &lt; SpecPartNo; i++) { System.out.println(&quot;Enter Name of individual &quot; + (i + 1)); SpecPartName[i] = scan.next(); for (int a = 0; a &lt; 1; a++) { System.out.println(&quot;Enter rank of the individual on the event&quot;); int sPartRank = scan.nextInt(); int spRank = 0; // scoring system for the individuals switch (sPartRank) { case 3: spRank = 60; break; case 2: spRank = 80; break; case 1: spRank = 100; break; } if (sPartRank == 0 || sPartRank &gt;= 4) { System.out.println(&quot;This individual will not be awarded points&quot;); } else { SpecPartScore[i] += spRank; System.out.println(spRank + &quot; points is granted for this event&quot;); } if (scan.hasNextLine()) { scan.nextLine(); } } } } // output for all teams and individuals with their respective events and scores if (teamNo == 0) { System.out.println(&quot;There are no teams&quot;); } else { System.out.println(&quot;Amount of Teams: &quot; + PartNo); System.out.println(&quot;Events Participated : 5&quot;); System.out.println(&quot;\t'Events List for Teams' : &quot; + Arrays.asList(Tevent) + &quot;\n&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); System.out.println(&quot;\tTeam\tParticipants&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); for (int i = 0; i &lt; PartNo; i++) { System.out.println(&quot;| Team': &quot; + teamName[i] + &quot;\n&quot; + &quot;Participants &quot; + teamPart[i] + &quot;\n&quot;); System.out.println(&quot;----------------------------------------------------------------------------\n&quot;); } System.out.println(&quot;Scores are shown respectively &quot;); System.out.println(&quot;All Teams Scores : &quot; + Arrays.toString(teamScore)); System.out.println(&quot;----------------------------------------------------------------------------\n&quot;); } if (PartNo == 0) { System.out.println(&quot;There are no teams\n&quot;); } else { System.out.println(&quot;Amount of Participants: &quot; + PartNo); System.out.println(&quot;Events Participated : 5&quot;); System.out.println(&quot;\t'Events List for Teams' : &quot; + Arrays.asList(Pevent) + &quot;\n&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); System.out.println(&quot;\t\tIndividual\nScore&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); for (int i = 0; i &lt; PartNo; i++) { System.out.println(&quot; | \t'Individual Name': &quot; + PartName[i]); } System.out.println(&quot;Scores are shown respectively &quot;); System.out.println(&quot; All Individual Scores:&quot; + Arrays.toString(PartScore)); System.out.println(&quot;----------------------------------------------------------------------------\n&quot;); } if (SpecTeamNo == 0) { System.out.println(&quot;There is no Special Teams&quot;); } else { System.out.println(&quot;Amount of Special Teams &quot; + SpecTeamNo); System.out.println(&quot;Events Participated : 1&quot;); System.out.println(&quot;\t'Events List for Teams' : &quot; + Arrays.asList(STevent) + &quot;\n&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); System.out.println(&quot;\tSpecial Team\tParticipants\tScore&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); for (int i = 0; i &lt; SpecTeamNo; i++) { System.out.println(&quot;| \t'Special Team Name': &quot; + SpecTeamName[i] + &quot;\n&quot; + &quot;Special Team Participants &quot; + SteamPart[i]); } System.out.println(&quot;Scores are shown respectively &quot;); System.out.println(&quot;ALl Special Team Scores: &quot; + Arrays.toString(SpecTeamScore)); System.out.println(&quot;----------------------------------------------------------------------------\n&quot;); } if (PartNo == 20) { System.out.println(&quot;There are No Special Individuals&quot;); } else { if (SpecPartNo == 0) { System.out.println(&quot;There are no Special Individuals&quot;); } else { System.out.println(&quot;Amount of Special Individuals &quot; + SpecPartNo); System.out.println(&quot;Events Participated : 1&quot;); System.out.println(&quot;\t'Events List for Teams' : &quot; + Arrays.asList(SPevent) + &quot;\n&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); System.out.println(&quot;\tSpecial Individual\tScore&quot;); System.out.println(&quot;----------------------------------------------------------------------------&quot;); for (int i = 0; i &lt; SpecPartNo; i++) { System.out.println(&quot;| \t'Special Individual Name': &quot; + SpecPartName[i]); } System.out.println(&quot;Scores are shown respectively &quot;); System.out.println(&quot;All Special Individuals Scores: &quot; + Arrays.toString(SpecPartScore)); System.out.println(&quot;----------------------------------------------------------------------------\n&quot;); } } } } } </code></pre> <p>I would like to know how the program is and if the output would be to your liking. And if there is anything else I should add.</p>
[]
[ { "body": "<p>Java is an object-oriented language. If I were teaching a Java course and marking an assignment, one of the things I'd be looking at would be whether the student has applied object-oriented principles to their program.</p>\n<p>As it's written, your code is entirely procedural with all the program logic in the <code>main()</code> method. <code>main()</code> should serve only as an entry point to your program, with the rest of the logic separated into classes and methods. I won't try to do the job of your professor by explaining OOP, but a starting point might be to look at the problem statements and list the noun phrases to identify the concepts you might want to represent as classes. This gives us:</p>\n<ul>\n<li><code>Tournament</code></li>\n<li><code>Event</code></li>\n<li><code>Team</code></li>\n<li>Individual (which you might refer to as <code>Competitor</code>)</li>\n</ul>\n<p>Further analysis will give some clues about what methods these classes might contain or how they might be extended:</p>\n<pre><code>class Event {\n // The events will vary in type, from sporting to academic challenges\n EventType eventType;\n}\n\nenum EventType {\n ARCHERY, BOXING, SPELLING_BEE // ...\n}\n\n// Each event will be defined as a team or individual event\nclass TeamEvent extends Event {\n Map&lt;Team, Integer&gt; scores;\n}\n\nclass IndividualEvent extends Event {\n Map&lt;Competitor, Integer&gt; scores;\n}\n</code></pre>\n<p>Note that these are just some ideas, and there's no single correct way to implement these. I won't try to do your homework for you by implementing them fully.</p>\n<p>You've also hard-coded the scoring system, meaning that if a user wanted to run a tournament that was scored differently they'd need to rewrite the code. Instead, consider a method of <code>Tournament</code> which looks at the <code>Event</code>s played and the positions of each <code>Team</code> or <code>Competitor</code> in each, assigning points accordingly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T12:18:17.643", "Id": "266239", "ParentId": "266206", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:35:37.950", "Id": "266206", "Score": "1", "Tags": [ "java", "beginner" ], "Title": "Scoring system for events" }
266206
<p>I am using below code which is comparing three columns values and copy pasting the 4th column data into other column.</p> <p>My code is working fine but it is slow to perform the processing and takes much time and sometimes Not Responding window appears.</p> <p>Any help to fix the problem will be appreciated</p> <pre><code> Sub rowMatch() Dim ws As Worksheet Dim ws2 As Worksheet Set ws = Worksheets(&quot;Sheet3&quot;) Set ws2 = Worksheets(&quot;Sheet2&quot;) Dim a As String, b As String, c As Date For i = 3 To ws.Cells(ws.Rows.Count, 14).End(xlUp).Row a = ws.Cells(i, 14).Value b = ws.Cells(i, 15).Value c = ws.Cells(i, 16).Value For j = 3 To ws2.Cells(ws2.Rows.Count, 98).End(xlUp).Row If ws2.Cells(j, 98).Value = a _ And ws2.Cells(j, 103).Value = b _ And ws2.Cells(j, 114).Value = c _ Then ws2.Cells(j, 120).Value = ws.Cells(j, 18).Value End If Next j Next i End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T04:58:15.670", "Id": "525915", "Score": "0", "body": "What's the size of data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T05:32:36.053", "Id": "525917", "Score": "0", "body": "Its more than 10,000." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T06:49:53.270", "Id": "525919", "Score": "0", "body": "Could you give a sample of the data please? As @PavloSlavynskyy points out, VBA might not be the best option here for performance" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T07:09:46.093", "Id": "525921", "Score": "0", "body": "Sure please here is the [File](https://drive.google.com/file/d/1Ck_8FPHBB-9nJRKW0Hz9iZta3acT7VEp/view?usp=sharing) @Greedo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T07:19:09.313", "Id": "525923", "Score": "0", "body": "@Valiant actually l meant if you could add this info to the question, perhaps as a [markdown table](https://meta.stackexchange.com/q/356997/354801)? Also you haven't included sheet3. Are your tables formatted as real Excel tables? (NB you can create md tables from Excel [automatically](https://thisdavej.com/copy-table-in-excel-and-paste-as-a-markdown-table/))" } ]
[ { "body": "<h3>Indents</h3>\n<p>Always keep the code properly indented. You'll spend much more time fixing some stupid error caused by improperly indented code then you'll save on not indenting it.\nThis code looks like the only line in <code>For i</code> loop is <code>a = ws.Cells(i, 14).Value</code>, but in fact all the code except for the final line is in this loop. Don't make readers struggle to read the code.</p>\n<h3>Variable names</h3>\n<p><code>a</code>, <code>b</code> and <code>c</code> are bad names. If you know what kind of data is in those columns - please, name them according to the content - like <code>name</code>, <code>lastName</code> and <code>dateOfBirth</code>.</p>\n<h3>Magic numbers</h3>\n<p>What are 14, 15, 98, 114? Some cells indices? What if you'll change something in the file - are you going to redo all the code because of that? Creating constants will allow you to make the code more flexible:</p>\n<pre><code>Const wsStartRow As Integer = 3\nConst wsEndCellCol As Integer = 14\n...\nFor i = wsStartRow To ws.Cells(ws.Rows.Count, wsEndCellCol).End(xlUp).Row\n</code></pre>\n<h3>Stop screen updates</h3>\n<p>Well, that's the cause of your problem: the screen updates when you change values, and screen updates are slow. You can easily stop it:</p>\n<pre><code>Application.ScreenUpdating = False\n</code></pre>\n<p>and don't forget to turn it in the end:</p>\n<pre><code>Application.ScreenUpdating = True\n</code></pre>\n<h3>Other ways</h3>\n<p>You can concatenate values in the cells into a new column to make use of built-in functions like VLOOKUP.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T03:54:59.543", "Id": "525912", "Score": "0", "body": "Thank you very much for elaborating and highlighting my mistakes. I used your way but the problem is still same." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T16:17:57.127", "Id": "266210", "ParentId": "266207", "Score": "5" } }, { "body": "<h2>Lookup by Comparing Multiple Columns (Array Loop)</h2>\n<p><strong>Intro</strong></p>\n<ul>\n<li>Although I would agree with most of Pavlo Slavynskyy's points (the screen updating is kind of debatable since you're using the fast\n'copy-by-assignment method' i.e. <code>dCell.Value = sCell.Value</code>, but it's good to know about it; and I have almost never used <code>VLookup</code> since there is the less restricting, brilliant <code>Application.Match</code>), you have made <strong>a crucial mistake</strong> with the loops. But let's keep it slow.</li>\n</ul>\n<p><strong>The Workbook</strong></p>\n<ul>\n<li><p>Your worksheets are not qualified i.e. they 'point' ('belong') to the <code>ActiveWorkbook</code> which could be any workbook.</p>\n</li>\n<li><p>Try the following experiment:</p>\n<ul>\n<li>In <code>Excel</code>, open your workbook.</li>\n<li>Open a new workbook.</li>\n<li>Go to the <code>Visual Basic Editor</code> and run your code.</li>\n<li>It will try to find the worksheets in the new workbook and probably raise<br />\n<code>Run-time error '9': Subscript out of range</code>.</li>\n</ul>\n</li>\n<li><p>In <code>VBA</code>, to reference the workbook containing this code, you use <code>ThisWorkbook</code>:</p>\n<pre><code>Dim wb As Workbook: Set wb = ThisWorkbook\n</code></pre>\n</li>\n<li><p>Since you're dealing with just <strong>one</strong> workbook, <code>wb</code> is just fine. No need for additional characters.</p>\n</li>\n</ul>\n<p><strong>The Worksheets</strong></p>\n<ul>\n<li>First of all, I love <code>ws</code> but only if there is only <strong>one</strong> worksheet. Using <code>ws</code> and <code>ws2</code> is kind of confusing, which is which? Where am I reading from and where am I writing to?</li>\n<li>I've adopted a <code>Source-Destination</code> concept, so I will use <code>sws</code> for the source and <code>dws</code> for the destination worksheets. You can create your own concept but you should be consistent about it.</li>\n<li>From the line <code>ws2.Cells(j, 120).Value = ws.Cells(j, 18).Value</code> it is obvious that <code>ws2</code> is you r <code>Destination</code> worksheet (<code>dws</code>) and <code>ws</code> is your <code>Source</code> worksheet (<code>sws</code>).</li>\n</ul>\n<p><strong>Efficiency: <code>If</code> Statement</strong></p>\n<ul>\n<li><p>If you write an <code>If</code> statement in one line e.g. ...</p>\n<pre><code>If A = 0 And B = 0 And C = 0 Then \n</code></pre>\n<p>... you have shortened the code, but on each loop, the code evaluates all three expressions, even if already <code>A</code> or <code>B</code> is not 0. For this simple example, there will be no practical difference in the efficiency but keep it in mind when you'll have more complex expressions.</p>\n</li>\n</ul>\n<p><strong>Efficiency: The Mistake</strong></p>\n<ul>\n<li><p>To make the code more efficient, you want to access (read from, especially write to) the worksheets as few times as possible, but your loops do the opposite.</p>\n</li>\n<li><p>Firstly, you don't want to first loop through the rows in the columns of the source worksheet because you are trying to write to ('to fill') the cells of the destination worksheet.</p>\n</li>\n<li><p>Secondly, now when you loop through the rows in the columns of the destination worksheet when a value (in this case 3 values are matched) is found, you don't need to loop any longer (it's found), so use <code>Exit For</code>:</p>\n<pre><code>If Something Then ' e.g. value found\n Do Whatever\n Exit For ' stop looping\nEnd If \n</code></pre>\n<p>... to exit the loop.</p>\n</li>\n</ul>\n<p><strong>The <code>Split</code> Function</strong></p>\n<ul>\n<li><p>When you have a list in a string, e.g.,...</p>\n<pre><code>Dim sNamesList As String: sNamesList = &quot;John,Peter,Mary&quot;\n</code></pre>\n<p>... you can easily write the values to an array using the <code>Split</code> function ...</p>\n<pre><code>Dim sNames() As String: sNames = Split(sNamesList, &quot;,&quot;)\n</code></pre>\n<p>... but be careful, any spaces inside will not be truncated.</p>\n</li>\n<li><p>The resulting array is <strong>always</strong> a (1D) <strong>zero-based</strong> array.</p>\n</li>\n</ul>\n<p><strong>Efficiency: Using Arrays</strong></p>\n<ul>\n<li><p>By introducing arrays into your code, you will reduce accessing the worksheets to the minimum.</p>\n</li>\n<li><p>You can read each range into an array (in one go) as simple as:</p>\n<pre><code> Dim rg As Range: Set rg = Range(&quot;A1:A10&quot;)\n Dim Data As Variant: Data = rg.Value\n</code></pre>\n</li>\n<li><p>In this case, the expression <code>rg.Value</code> alone is (has created) already a 2D one-based array with ten rows and one column containing the values of the range.</p>\n</li>\n<li><p><strong>Note</strong> that this is not true if the range contains only one cell (see the <code>GetRange</code> function for details).</p>\n</li>\n<li><p>Knowing this, you can now loop through the elements of the arrays (in memory) instead of the cells of the worksheet and vastly improve the performance of the code.</p>\n</li>\n<li><p>Similarly, you can write the values of a 2D one-based array to the worksheet in one go:</p>\n<pre><code> Dim rg As Range: rg.Resize(Ubound(Data, 1), Ubound(Data, 2)).Value = Data\n</code></pre>\n<p>... or in our case, since there is only one column per 2D array, you can simplify:</p>\n<pre><code> Dim rg As Range: rg.Resize(Ubound(Data, 1)).Value = Data\n</code></pre>\n</li>\n</ul>\n<p><strong>Readability</strong></p>\n<ul>\n<li>To make the code more readable you can create your helper procedures which you may use in some other projects, e.g. <code>RefColumn</code> and <code>GetRange</code>.</li>\n</ul>\n<p><strong>Miscellaneous</strong></p>\n<ul>\n<li>The code is written according to your posted code.</li>\n<li>To use it in your provided sample file, change the following:\n<ul>\n<li><code>&quot;Sheet3&quot;</code> to <code>&quot;Sheet2&quot;</code></li>\n<li><code>&quot;R&quot;</code> to <code>&quot;Q&quot;</code></li>\n<li><code>&quot;Sheet2&quot;</code> to <code>&quot;Sheet1&quot;</code></li>\n</ul>\n</li>\n</ul>\n<p><strong>The Main Code</strong></p>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n\n\nSub LookupMultiColumnsCompare()\n \n Const ProcTitle As String = &quot;Lookup Multi Columns Compare&quot;\n ' Source\n Const sName As String = &quot;Sheet3&quot;\n Const sFirst As String = &quot;N3&quot;\n Const scColsList As String = &quot;N,O,P&quot; ' 14, 15, 16 add more (or less)\n Const svCol As String = &quot;R&quot; ' 18\n ' Destination\n Const dName As String = &quot;Sheet2&quot;\n Const dFirst As String = &quot;CT3&quot;\n Const dcColsList As String = &quot;CT,CY,DJ&quot; ' 98, 103, 114 ' add more\n ' *** Triple-check the following because in this column the data\n ' will be overwritten! Remember, there is no undo.\n Const dvCol As String = &quot;DP&quot; ' 120\n \n ' Create a reference to the workbook containing this code ('ThisWorkbook').\n Dim wb As Workbook: Set wb = ThisWorkbook\n \n Dim WasSuccessful As Boolean\n Dim n As Long ' Compare Columns Arrays Counter (Source, Destination, Loop)\n \n On Error GoTo ClearError\n \n ' Source\n \n Dim sws As Worksheet: Set sws = wb.Worksheets(sName)\n Dim sfCell As Range: Set sfCell = sws.Range(sFirst)\n Dim srg As Range: Set srg = RefColumn(sfCell)\n If srg Is Nothing Then Exit Sub ' no data\n \n Dim srCount As Long: srCount = srg.Rows.Count\n Dim scCols() As String: scCols = Split(scColsList, &quot;,&quot;)\n Dim nUpper As Long: nUpper = UBound(scCols)\n \n Dim sData As Variant: ReDim sData(0 To nUpper)\n \n For n = 0 To nUpper\n sData(n) = GetRange(srg.EntireRow.Columns(scCols(n)))\n Next n\n Dim svData As Variant: svData = GetRange(srg.EntireRow.Columns(svCol))\n \n ' Destination\n \n Dim dws As Worksheet: Set dws = wb.Worksheets(dName)\n Dim dfCell As Range: Set dfCell = dws.Range(dFirst)\n Dim drg As Range: Set drg = RefColumn(dfCell)\n If drg Is Nothing Then Exit Sub ' no data\n \n Dim drCount As Long: drCount = drg.Rows.Count\n Dim dcCols() As String: dcCols = Split(dcColsList, &quot;,&quot;)\n \n Dim dData As Variant: ReDim dData(0 To nUpper)\n \n For n = 0 To nUpper\n dData(n) = GetRange(drg.EntireRow.Columns(dcCols(n)))\n Next n\n Dim dvData As Variant: ReDim dvData(1 To drCount, 1 To 1)\n ' You could speed up the code if the values will always stay the same\n ' once they are written i.e. if you already have found the matches\n ' the first time and you don't need to modify them, by rather reading\n ' the 'Value' column range into the array.\n ' Instead of the previous line use the following...\n 'Dim dvData As Variant: dvData = GetRange(drg.EntireRow.Columns(dvCol))\n ' ... and test the value of each item in the array before looping further\n ' by adding a new 'If' statement below the line 'For dr = 1 To drCount':\n ' 'If Len(dvData(dr, 1)) = 0 Then&quot;'. Don't forget about its 'End If'.\n \n ' Loop\n \n Dim sValue As Variant\n Dim sr As Long\n \n Dim dCell As Range\n Dim dValue As Variant\n Dim dr As Long\n \n For dr = 1 To drCount\n For sr = 1 To srCount\n For n = 0 To nUpper\n dValue = dData(n)(dr, 1)\n ' Dependent on your data, some of the following 'If' statements\n ' may be redundant but they should slow down the code,\n ' so think twice before removing (uncommenting) them.\n If IsError(dValue) Then Exit For ' exclude error values\n If Len(dValue) = 0 Then Exit For ' exclude blanks\n sValue = sData(n)(sr, 1)\n If IsError(sValue) Then Exit For ' exclude error values\n If IsDate(sValue) Then\n If IsDate(dValue) Then\n ' The tricky date part when it contains time.\n If Round(CDbl(sValue), 6) &lt;&gt; Round(CDbl(sValue), 6) Then\n Exit For\n End If\n End If\n Else\n If sValue &lt;&gt; dValue Then Exit For\n End If\n \n Next n\n ' Note that if the loop was not interrupted, 'n = nUpper + 1'.\n If n &gt; nUpper Then\n dvData(dr, 1) = svData(sr, 1)\n End If\n Next sr\n Next dr\n \n ' Overwrite the values in destination with values in the array.\n Dim dvrg As Range: Set dvrg = drg.EntireRow.Columns(dvCol)\n dvrg.Value = dvData\n \n WasSuccessful = True\n \nInfoExit:\n\n If WasSuccessful Then\n MsgBox &quot;Worksheet successfully updated.&quot;, _\n vbInformation, ProcTitle\n Else\n MsgBox &quot;Something went wrong.&quot; &amp; vbLf _\n &amp; &quot;Double-check the values in the constants section of the code.&quot;, _\n vbCritical, ProcTitle\n End If\n\n Exit Sub\nClearError:\n Debug.Print &quot;Run-time error '&quot; &amp; Err.Number &amp; &quot;': &quot; &amp; Err.Description\n Resume InfoExit\nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Creates a reference to the one-column range from the first cell\n' of a range ('FirstCell') to the bottom-most non-empty cell\n' of the first cell's worksheet column.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction RefColumn( _\n ByVal FirstCell As Range) _\nAs Range\n If FirstCell Is Nothing Then Exit Function\n \n With FirstCell.Cells(1)\n Dim lCell As Range\n Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _\n .Find(&quot;*&quot;, , xlFormulas, , , xlPrevious)\n If lCell Is Nothing Then Exit Function\n Set RefColumn = .Resize(lCell.Row - .Row + 1)\n End With\n\nEnd Function\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a range ('rg') in a 2D one-based array.\n' Remarks: If ˙rg` refers to a multi-range, only its first area\n' is considered.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetRange( _\n ByVal rg As Range) _\nAs Variant\n If rg Is Nothing Then Exit Function\n \n If rg.Rows.Count + rg.Columns.Count = 2 Then ' one cell\n Dim Data As Variant: ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value\n GetRange = Data\n Else ' multiple cells\n GetRange = rg.Value\n End If\n\nEnd Function\n</code></pre>\n<p><strong>Some Toys</strong></p>\n<pre class=\"lang-vb prettyprint-override\"><code>''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the Excel column string from a (column) number.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetColumnString( _\n ByVal ColumnNumber As Long) _\nAs String ' only '-2147483648#' crashes it!?\n \n Dim Remainder As Long\n Do\n Remainder = (ColumnNumber - 1) Mod 26\n GetColumnString = Chr(Remainder + 65) &amp; GetColumnString\n ColumnNumber = Int((ColumnNumber - Remainder) \\ 26)\n Loop Until ColumnNumber = 0\n\nEnd Function\n\nSub GetColumnStringTEST()\n Debug.Print GetColumnString(120)\n Debug.Print GetColumnString(16384) ' max for 'Excel'\n Debug.Print GetColumnString(2147483647) ' max for 'Long'\nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the Excel column number from a (column) string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetColumnNumber( _\n ByVal ColumnString As String) _\nAs Long\n On Error GoTo ClearError ' too many chars: &quot;Run-time error '6': Overflow&quot;\n \n Dim ColumnStringLength As Long: ColumnStringLength = Len(ColumnString)\n \n Dim n As Long\n Dim CharNumber As Long\n Dim CharIndex As Long\n Dim ColumnNumber As Long\n For n = ColumnStringLength To 1 Step -1\n CharNumber = Asc(UCase(Mid(ColumnString, n))) - 64\n If CharNumber &gt;= 1 Then\n If CharNumber &lt;= 26 Then\n ColumnNumber = ColumnNumber + CharNumber * 26 ^ CharIndex\n CharIndex = CharIndex + 1\n End If\n End If\n Next\n GetColumnNumber = ColumnNumber\n\nProcExit:\n Exit Function\nClearError:\n Debug.Print &quot;Run-time error '&quot; &amp; Err.Number &amp; &quot;': &quot; &amp; Err.Description\n Resume ProcExit\nEnd Function\n\nSub GetColumnNumberTEST()\n Debug.Print GetColumnNumber(&quot;DP&quot;)\n Debug.Print GetColumnNumber(&quot;XFD&quot;) ' max for 'Excel'\n Debug.Print GetColumnNumber(&quot;FXSHRXW&quot;) ' max for 'Long'\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T11:53:55.307", "Id": "529297", "Score": "4", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T12:33:08.780", "Id": "529300", "Score": "3", "body": "@Toby Speight: Thanks for pointing that out. I never read it on this site. I will edit my answer ASAP, possibly tomorrow." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-26T07:24:20.643", "Id": "268397", "ParentId": "266207", "Score": "3" } } ]
{ "AcceptedAnswerId": "268397", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:41:50.997", "Id": "266207", "Score": "3", "Tags": [ "performance", "vba", "excel" ], "Title": "Comparing Three Columns and Copy Pasting data" }
266207
<p>I am currently using a <code>ThreadedConnectionPool</code> from <code>psycopg2</code> to lease transactions to a PostgreSQL database and would like a review of my current implementation.</p> <h3>Code</h3> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations import logging import threading import traceback from contextlib import contextmanager from dataclasses import dataclass from psycopg2.pool import ThreadedConnectionPool from .settings import CONNECTION_OPEN_WARN_THRESHOLD from .utils import Timer logger = logging.getLogger() class Counter(object): def __init__(self, name): self.name = name self.value = 0 self.max = 0 self._lock = threading.Lock() def increment(self): with self._lock: self.value += 1 if self.value &gt; self.max: self.max = self.value def decrement(self): with self._lock: self.value -= 1 def __str__(self) -&gt; str: return f&quot;{id(self):#02x} - {self.name}: current={self.value}, max={self.max}&quot; @dataclass class PostgreSQLSimplePool: pool: ThreadedConnectionPool counter = Counter(&quot;Active DB connections&quot;) @contextmanager def transact_session(self, commit: bool = False): with Timer() as t: conn = self.pool.getconn() self.counter.increment() logger.debug(self.counter) try: yield conn if commit: conn.commit() except Exception: conn.rollback() raise finally: self.counter.decrement() self.pool.putconn(conn) if t.interval &gt; CONNECTION_OPEN_WARN_THRESHOLD: logger.warning(f&quot;DB Connection was held open for {t.interval} seconds:&quot;) traceback.print_stack() </code></pre> <h3>Config</h3> <pre class="lang-py prettyprint-override"><code> threaded_pool = ThreadedConnectionPool( minconn=1, maxconn=20, dsn=&quot;&quot;, # This relies on standard env vars ) repo = PostgreSQLSimplePool(pool=threaded_pool) </code></pre> <h3>Usage</h3> <pre class="lang-py prettyprint-override"><code>with repo.transact_session() as connection: with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: # do some stuff with the cursor... </code></pre>
[]
[ { "body": "<ul>\n<li><code>Counter</code> should not inherit from <code>object</code> in Python 3</li>\n<li>Add PEP484 type-hinting to <code>name</code>, as well as all of your return values</li>\n<li>I'm not sure what you were hoping to accomplish with a field width of 2 in <code>{id(self):#02x}</code>. IDs will almost certainly be over two characters long when formatted.</li>\n<li><code>counter = Counter(&quot;Active DB connections&quot;)</code> does not do what you think it does. It doesn't make an instance member on the dataclass, it makes a static member. You'll want to use <a href=\"https://docs.python.org/3/library/dataclasses.html#dataclasses.field\" rel=\"nofollow noreferrer\">field</a> passing a default, or perhaps don't write it as a dataclass member at all and instead add it during <a href=\"https://docs.python.org/3/library/dataclasses.html#post-init-processing\" rel=\"nofollow noreferrer\"><code>__post_init__</code></a>.</li>\n<li>You have a counter mechanism that has no knowledge of the pool's size. In my imagination the counter's <code>max</code> and the <a href=\"https://www.psycopg.org/docs/pool.html\" rel=\"nofollow noreferrer\">pool</a>'s <code>maxconn</code> should be the same thing. Currently you have a &quot;statistical&quot; max that only reports on the historical peak connection usage. You could have - instead, or in addition - an &quot;enforced&quot; max. In other words: rather than rolling your own counter with a lock, perhaps you want a <a href=\"https://docs.python.org/3.7/library/threading.html#threading.Semaphore\" rel=\"nofollow noreferrer\">semaphore</a> that blocks if the max count is hit.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T20:08:18.000", "Id": "525891", "Score": "1", "body": "Thank you stranger online for this review!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T19:59:16.217", "Id": "266221", "ParentId": "266209", "Score": "1" } } ]
{ "AcceptedAnswerId": "266221", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T14:44:52.240", "Id": "266209", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "psycopg2 ThreadedConnectionPool implementation" }
266209
<p>I am trying to solve a challenge in which I have to write a function that takes in two numbers as arguments and returns an array containing numbers between them which are prime and their reverse is also prime in JavaScript. This doesn't return numbers which are palindrome such as <code>101</code>.</p> <pre class="lang-javascript prettyprint-override"><code>function backwardsPrime(start, stop) { let arr = []; for (let i = start; i &lt;= stop; i++) { let truth = true; for (let j = 2; j &lt; i; j++) { if (i % j === 0) truth = false; } if (truth) arr.push(i); } return arr.filter(elem =&gt; { let truth = true; let rev = parseInt(elem.toString().split('').reverse().join('')); for (let j = 2; j &lt; rev; j++) { if (rev % j === 0||rev === elem) truth = false; }; return truth; }); } </code></pre> <p>This code works but it is inefficient and takes a long time. So my code isn't being accepted... So can anyone make this code more efficient along with the explanation of how you did it? <em>I am not experienced with optimizing code myself. This is my first post in code review so please kindly forgive if I had made any mistake or if it's off-topic</em>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T15:21:16.733", "Id": "525964", "Score": "0", "body": "Just for fun: https://stackblitz.com/edit/js-3olwhn?file=index.js" } ]
[ { "body": "<blockquote>\n<pre><code> let arr = [];\n</code></pre>\n</blockquote>\n<p>This isn't a generic array, so why not name it <code>primes</code>?</p>\n<blockquote>\n<pre><code> for (let i = start; i &lt;= stop; i++) {\n</code></pre>\n</blockquote>\n<p>Why are you incrementing by one here? There is exactly one even prime (2). All other even numbers are not prime, as they are divisible by 2 and primes are only divisible by themselves and 1. Try</p>\n<pre><code> for (let i = start + (start + 1) % 2; i &lt;= stop; i += 2) {\n</code></pre>\n<p>Now you only have to do half as much work. If you search around on this site, you can see how to also get rid of numbers divisible by 3.</p>\n<blockquote>\n<pre><code> for (let j = 2; j &lt; i; j++) {\n</code></pre>\n</blockquote>\n<p>There's a similar problem here. You would be better off checking 2 separately and changing this to</p>\n<pre><code> for (let j = 3; j &lt;= i / j; j += 2) {\n</code></pre>\n<p>Note that rather than testing to <code>i</code>, I changed it to something that is effectively <code>j &lt;= Math.sqrt(i)</code>. Only I implemented that via simple division. This works because factors come in pairs that multiply to the number. Both factors can't be larger than the square root because then their product would be larger than the number. So at least one is less than or equal to the square root.</p>\n<p>But you're checking a lot of numbers redundantly even then. For example, if a number is not divisible by 3, then it won't be divisible by 9, 15, 21, etc. The truth is that if you know the range of numbers, you can do a lot better with a <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>. Then you can mask out the composite numbers, so you don't have to keep trying them. In this case, you'd use the sieve to find all primes from 2 to <code>stop</code>. Then go through that list from <code>start</code> to <code>stop</code>.</p>\n<p>Note that we have a tag for <a href=\"/questions/tagged/sieve-of-eratosthenes\" class=\"post-tag\" title=\"show questions tagged &#39;sieve-of-eratosthenes&#39;\" rel=\"tag\">sieve-of-eratosthenes</a>, and you can look at just the questions about <a href=\"https://codereview.stackexchange.com/questions/tagged/sieve-of-eratosthenes+javascript\">Javascript</a>. That should get you at least to the point where you can ask another question if it's still not fast enough. It might not be. I can think of some more optimizations that you could do. But they will be easier to explain when your code is further along.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T03:12:37.463", "Id": "525910", "Score": "0", "body": "For a number such as 13 does this part `for (let i = start + start % 2; i <= stop; i += 2) {` work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T03:43:00.830", "Id": "525911", "Score": "0", "body": "13 doesn't get added to the array if it is the `start`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T07:13:08.600", "Id": "525922", "Score": "0", "body": "@Valoruz It looks like that does the reverse of what is intended. Try it as `+ (start + 1) % 2` as shown in [this answer](https://codereview.stackexchange.com/a/266223/71574). Or `+ 1 - (start % 2)`. Although I really think that you would be better off moving to a sieve operation." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T17:01:18.823", "Id": "266214", "ParentId": "266211", "Score": "0" } }, { "body": "<h2>Bug?</h2>\n<p>There may be a bug but this will depend on input range and interpretations.</p>\n<p>When given the range 0 to 10 your function returns <code>[0,1,2]</code> all of which do not match the requirements. The first valid number is 13 as it is a prime, reversed 31 a prime, and not a palindrome <code>13 !== 31</code>.</p>\n<ul>\n<li>0 and 1 are not primes</li>\n<li>2 reversed is 2 and thus is a palindrome</li>\n</ul>\n<p>I would assume that values under 13 should be ignored.</p>\n<h2>Style</h2>\n<ul>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> when a variable does not change. For example the variables <code>arr</code> and <code>rev</code> should be constants</p>\n</li>\n<li><p>Always delimit code blocks (using <code>{}</code>). Eg <code>if (foo) bar = foo</code> is better as <code>if (foo) { bar = foo }</code> This will save you hours of bug hunting when you modify code and forget to add the <code>{}</code> if you extend the block.</p>\n</li>\n<li><p>The closing <code>}</code> of a <code>for</code> loop block does not require a semicolon <code>;</code></p>\n</li>\n<li><p>Spaces between operators.</p>\n</li>\n</ul>\n<h2>Optimizing</h2>\n<p>Code review is not really about &quot;How do I...?&quot; so I will only review optimization in the algorithm you have come up with.</p>\n<ul>\n<li><p>Break out of loops if the condition you are searching for has been meet. You have two loops (the first finding primes and the second filtering found primes.</p>\n<p>Both these loops have an inner loop that will set the semaphore <code>truth</code> to false on some condition. However when you chage the state of <code>truth</code> to <code>false</code> you continue looping. You know when you change <code>truth</code> it will remain so untill the loop is complete so why continue the loop,</p>\n<p>There are many ways to break out of the loop. See rewrite</p>\n</li>\n<li><p>In JS String manipulation is very slow when compared to Numbers.</p>\n<p>The line <code>let rev = parseInt(elem.toString().split('').reverse().join(''));</code> is on average just under 10 times slower (for random values from <code>1</code> to <code>1e8</code>) than the following function</p>\n<pre><code>function reverseNumber(num) {\n var result = 0;\n while (num) {\n result = (result *= 10) + (num % 10);\n num = num * 0.1 | 0;\n }\n return result;\n}\n</code></pre>\n<p>Always avoid converting <code>Number</code>s to <code>String</code>s when performance is critical and the task is mathematical in nature</p>\n</li>\n<li><p>Avoid known steps. Even when using brute force approaches it pays to use what is know to reduce processing</p>\n<p>You know in advance</p>\n<ul>\n<li>that even values can not be prime.</li>\n<li>that. If a <code>number</code> is divisible by a <code>value</code> then it is also divisible by <code>number / value</code>. This means that the max <code>value</code> to check if divisible by is the square root of <code>number</code></li>\n<li>and see hint at bottom of answer.</li>\n</ul>\n<p>Thus you can optimize the first loop by starting at an odd value, stepping over even values, and checking divisors up to the square root of the value you are checking.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite uses your brute force solution with optimizations outlined above.</p>\n<p>The rewrite code is 300 times quicker with input <code>100, 10000</code>. If it can pass the performance requirement I do not know.</p>\n<p>The rewrite breaks the task into smaller parts using functions.</p>\n<pre><code>function backwardsPrime(start, stop) {\n function reverseNumber(num) {\n var result = 0;\n while (num) {\n result = (result *= 10) + (num % 10);\n num = num * 0.1 | 0;\n }\n return result;\n } \n function isPrime(num) { // num must be odd\n var div = 3;\n const max = num ** 0.5 + 1;\n while (div &lt; max) {\n if (num % div === 0) { return false }\n div += 1;\n }\n return true;\n } \n start = Math.max(start, 13);\n var num = start + (start + 1) % 2;\n const primes = [];\n while (num &lt;= stop) {\n isPrime(num) &amp;&amp; primes.push(num);\n num += 2;\n }\n return primes.filter(val =&gt; {\n const rev = reverseNumber(val);\n return rev % 2 &amp;&amp; rev !== val &amp;&amp; isPrime(rev);\n });\n} \n</code></pre>\n<h2>Even faster</h2>\n<p>The function <code>findPrime</code> (in rewrite above) is a brute force approach and can be replace with any one of many better algorithms.</p>\n<p>And a <strong>Hint</strong> All numbers starting with an even digit (2,4,6,8) can not have a reversed prime. That's more than half of all odd numbers can quickly be excluded from the need to test if prime.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:53:20.160", "Id": "266223", "ParentId": "266211", "Score": "0" } } ]
{ "AcceptedAnswerId": "266223", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T16:20:43.443", "Id": "266211", "Score": "1", "Tags": [ "javascript", "node.js", "time-limit-exceeded", "primes" ], "Title": "A function to find all the primes between two numbers whose reverse is also a prime and doesn't include palindrome, in JS" }
266211
<p>There are 2 persons and their already booked meeting schedule is given and also time bound for both the person is given. Now, we want to schedule a meeting between them in an available time that suits both of them. And at the end we want to return the available time slots for the new meeting. Given input:</p> <pre><code>vector&lt;pair&lt;string,string&gt;&gt;p1={{&quot;09:00&quot;,&quot;10:30&quot;},{&quot;12:00&quot;,&quot;13:00&quot;},{&quot;16:00&quot;,&quot;18:00&quot;}}; pair&lt;string,string&gt;b1={&quot;09:00&quot;,&quot;20:00&quot;}; vector&lt;pair&lt;string,string&gt;&gt;p2={{&quot;10:00&quot;,&quot;11:30&quot;},{&quot;12:30&quot;,&quot;14:30&quot;},{&quot;14:30&quot;,&quot;15:00&quot;},{&quot;16:00&quot;,&quot;17:00&quot;}}; pair&lt;string,string&gt;b2={&quot;10:00&quot;,&quot;18:30&quot;}; int d = 30; </code></pre> <p>where p1 is the schedule and b1 is the time bound(only wants the meeting in that bound) for person 1 and p2 and b2 for person 2. d is the duration of the meeting in minutes.</p> <p>Output:</p> <pre><code>[11:30,12:00] , [15:00,16:00] , [18:00,18:30] </code></pre> <p>These are the available time slots for the meeting. I have written the code and i want to know if i have written any duplicate code and if it is a good approach.The code is really long</p> <pre><code>#include&lt;iostream&gt; #include&lt;cstring&gt; #include&lt;vector&gt; #include&lt;algorithm&gt; using namespace std; bool comparator(string s1,string s2){ int hour1 = stoi(s1.substr(0,2)); int min1 = stoi(s1.substr(3,2)); int hour2 = stoi(s2.substr(0,2)); int min2 = stoi(s2.substr(3,2)); if(((hour1*60)+min1)&gt;=((hour2*60)+min2)){ return true; } return false; } int difftime(string s1,string s2){ int ans=0; int hour1 = stoi(s1.substr(0,2)); int min1 = stoi(s1.substr(3,2)); int hour2 = stoi(s2.substr(0,2)); int min2 = stoi(s2.substr(3,2)); ans = (hour2*60)+min2-(hour1*60)+min1; return ans; } vector&lt;pair&lt;string,string&gt;&gt; solve(vector&lt;pair&lt;string,string&gt;&gt;p1,vector&lt;pair&lt;string,string&gt;&gt;p2,pair&lt;string,string&gt;b1,pair&lt;string,string&gt;b2,int time){ vector&lt;pair&lt;string,string&gt;&gt;result; int p1size=p1.size(); int p2size=p2.size(); int i=0,j=0; while(i&lt;p1size &amp;&amp; j&lt;p2size){ // O(n) or o(m) if(comparator(p1[i].first,p2[j].first)){ result.push_back({p2[j].first,p2[j].second}); j++; } else{ result.push_back({p1[i].first,p1[i].second}); i++; } } while(i&lt;p1.size()){ //o(n-m) result.push_back({p1[i].first,p1[i].second}); i++; } while(j&lt;p2.size()){ //o(m-n) result.push_back({p2[j].first,p2[j].second}); j++; } string start_max,end_min; if(comparator(b1.first,b2.first)){ start_max = b1.first; } else{ start_max = b2.first; } if(comparator(b1.second,b2.second)){ end_min= b2.second; } else{ end_min= b1.second; } vector&lt;pair&lt;string,string&gt;&gt;output; i=0; string max_end_time = result[0].second; while(i&lt;result.size()-1){ //o(n+m) if(comparator(result[i].second,result[i+1].first)){ result[i+1].first = result[i].first; } if(comparator(result[i+1].second,max_end_time) &amp;&amp; comparator(end_min,result[i+1].second)){ max_end_time = result[i+1].second; } i++; } for(int i=0;i&lt;result.size()-1;i++){ //o(n+m) if(difftime(result[i].second,result[i+1].first)&gt;=time){ if(comparator(result[i].second,start_max) &amp;&amp; comparator(end_min,result[i+1].first)){ output.push_back(make_pair(result[i].second,result[i+1].first)); } } } if(difftime(max_end_time,end_min)&gt;=time){ output.push_back(make_pair(max_end_time,end_min)); } return output; } int main(){ vector&lt;pair&lt;string,string&gt;&gt;p1={{&quot;09:00&quot;,&quot;10:30&quot;},{&quot;12:00&quot;,&quot;13:00&quot;},{&quot;16:00&quot;,&quot;18:00&quot;},{&quot;19:00&quot;,&quot;20:00&quot;}}; pair&lt;string,string&gt;b1={&quot;09:00&quot;,&quot;20:00&quot;}; vector&lt;pair&lt;string,string&gt;&gt;p2={{&quot;10:00&quot;,&quot;11:30&quot;},{&quot;12:30&quot;,&quot;14:30&quot;},{&quot;14:30&quot;,&quot;15:00&quot;},{&quot;16:00&quot;,&quot;17:00&quot;}}; pair&lt;string,string&gt;b2={&quot;10:00&quot;,&quot;18:30&quot;}; int d = 30; vector&lt;pair&lt;string,string&gt;&gt;a = solve(p1,p2,b1,b2,d); for(auto it:a){ cout&lt;&lt;&quot;[&quot;&lt;&lt;it.first&lt;&lt;&quot;,&quot;&lt;&lt;it.second&lt;&lt;&quot;]&quot;&lt;&lt;&quot; , &quot;; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:07:40.107", "Id": "525952", "Score": "0", "body": "@Edward I have made some changes in the code and i guess it works fine now. I have tried to run it in several test cases and its giving the output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:12:43.863", "Id": "525954", "Score": "0", "body": "As currently in the question, the code produces \"[09:00,10:30] , [09:00,11:30] , [12:00,13:00] , [12:00,14:30] , [12:00,15:00] , [16:00,17:00] , [16:00,18:00] , [19:00,20:00] , [11:30,12:00] , [15:00,16:00] , [18:00,18:30] , \" which is not the given answer, \"[11:30,12:00] , [15:00,16:00] , [18:00,18:30]\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:17:38.977", "Id": "525956", "Score": "0", "body": "@Edward ohh, sorry about that I forgot to comment out some parts. It now just returns the actual answer now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:28:25.527", "Id": "525958", "Score": "0", "body": "OK, now it's working. I've retracted my close vote and look forward to reviewing the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T13:29:44.817", "Id": "525959", "Score": "0", "body": "@Edward ok, thanks man" } ]
[ { "body": "<p>I see a number of things which may help you improve your program.</p>\n<h2>Don't abuse <code>using namespace std</code></h2>\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid.</p>\n<h2>Use more whitespace to enhance readability of the code</h2>\n<p>Instead of crowding things together like this:</p>\n<pre><code>if(difftime(result[result.size()-1].second,end_min)&gt;=time){\n</code></pre>\n<p>most people find it more easily readable if you use more space:</p>\n<pre><code>if (difftime(result[result.size() - 1].second, end_min) &gt;= time) {\n</code></pre>\n<h2>Use descriptive names</h2>\n<p>The use of <code>std::pair</code> is not terrible here, but it would be easier to understand the code if, instead of the somewhat cryptic <code>first</code> and <code>second</code> data items that <code>std::pair</code> provides, we could use <code>starttime</code> and <code>endtime</code>. Also the use of <code>b1</code>, <code>p1</code>, etc. are not at all descriptive and should be replaced with more meaningful names. Also <code>comparator</code> is very vague. I'd probably change the sense and call it <code>IsLessThan</code>. But we can do better as I'll show later.</p>\n<h2>Simplify boolean expressions</h2>\n<p>The last lines of <code>comparator()</code> are these:</p>\n<pre><code>if(((hour1*60)+min1)&gt;=((hour2*60)+min2)){\n return true;\n}\nreturn false;\n</code></pre>\n<p>We can simplify that by using the expression evaluation directly:</p>\n<pre><code>return hour1 * 60 + min1 &gt;= hour2 * 60 + min2;\n</code></pre>\n<h2>Use appropriate <code>#include</code>s</h2>\n<p>The code is using <code>std::string</code> but does not <code>#include &lt;string&gt;</code>. It's good to make sure to include all of the appropriate headers because even though it might compile on your compiler right now (because one of the headers you have listed includes one that you haven't) it isn't going to be portable and could break with the next compiler update.</p>\n<h2>Use a more appropriate object</h2>\n<p>Rather than <code>std::pair&lt;std::string, std::string&gt;</code> what you really need is a start time and end time. C++ includes the <a href=\"https://en.cppreference.com/w/cpp/chrono\" rel=\"nofollow noreferrer\"><code>std::chrono</code></a> library which would make this code much simpler and easier to understand and also more efficient: whenever the code compares two times at the moment, it does the conversion to minutes each time! An alternative would be to use your own custom type for this, which is the approach I'll illustrate here. First a class called <code>mytime</code> handles the conversions to and from text and internally stores the time in minutes. We also define an <code>operator&lt;</code> and an <code>operator-</code> that will be handy later. It would be better to provide some more rigorous error checking for the input strings, but I'll leave that enhancement to you.</p>\n<pre><code>class mytime {\npublic:\n mytime(const std::string&amp; timestring) {\n minute = std::stoi(timestring.substr(0, 2)) * 60 + std::stoi(timestring.substr(3, 2));\n }\n mytime() = default;\n bool operator&lt;(const mytime&amp; other) const { return minute &lt; other.minute; }\n unsigned operator-(const mytime&amp; other) const { return minute - other.minute; }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const mytime&amp; t) {\n return out &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; t.minute / 60\n &lt;&lt; ':' &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; t.minute % 60;\n }\nprivate:\n unsigned minute = 0;\n};\n</code></pre>\n<p>Now instead of the <code>std::pair</code>, let's create a <code>struct timerange</code>:</p>\n<pre><code>struct timerange {\n timerange(const std::string&amp; start, const std::string&amp; finish) : start{start}, finish{finish} {};\n timerange(mytime start, mytime finish) : start{start}, finish{finish} {};\n bool operator&lt;(const timerange&amp; other) const { return start &lt; other.start; }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const timerange&amp; tr) {\n return out &lt;&lt; &quot;[&quot; &lt;&lt; tr.start &lt;&lt; &quot;,&quot; &lt;&lt; tr.finish &lt;&lt; &quot;]&quot;;\n }\n mytime start;\n mytime finish;\n};\n</code></pre>\n<h2>Use a more efficient algorithm</h2>\n<p>We can accomplish the goal while doing only a single traversal through the arrays. First, let's convert <code>b1</code> and <code>b2</code> to appointments span the beginning and the ending of the day. Here's one way to do that:</p>\n<pre><code>static const timerange day{&quot;00:00&quot;, &quot;24:00&quot;};\np1.emplace_back(day.start, b1.start);\np2.emplace_back(day.start, b2.start);\np1.emplace_back(b1.finish, day.finish);\np2.emplace_back(b2.finish, day.finish);\nstd::sort(p1.begin(), p1.end());\nstd::sort(p2.begin(), p2.end());\n</code></pre>\n<p>Note that this explicitly sorts both appointment lists, which also takes care of the problem of unsorted input. Now we can sweep through both vectors using iterators and simply end when either list runs out of appointments.</p>\n<pre><code>std::vector&lt;timerange&gt; solution{};\nauto one{p1.begin()};\nauto two{p2.begin()};\nfor (mytime curr{}; one != p1.end() &amp;&amp; two != p2.end(); ) {\n if (curr &lt; one-&gt;start) { // one is free \n if (curr &lt; two-&gt;start) { // two is also free\n if (std::min(one-&gt;start, two-&gt;start) - curr &gt;= minutes_duration) {\n solution.emplace_back(curr, std::min(one-&gt;start, two-&gt;start));\n\n }\n curr = std::max(one-&gt;finish, two-&gt;finish);\n ++one;\n ++two;\n } else { // two is busy\n // advance curr to end of current appointment\n curr = two-&gt;finish;\n ++two;\n }\n } else { // one is busy\n if (two-&gt;start &lt; curr) { // two is free\n curr = one-&gt;finish;\n } else { // two is busy\n curr = std::max(one-&gt;finish, two-&gt;finish);\n ++two;\n }\n ++one;\n }\n}\nreturn solution;\n</code></pre>\n<p>Note that because we defined <code>operator&lt;</code>, we can easily do the comparisons and sorting and can use <code>std::min</code> and <code>std::max</code> with no further effort or coding. Now the usage in <code>main</code> is extremely simple:</p>\n<pre><code>const auto a = solve(p1, p2, b1, b2, d);\nstd::copy(a.begin(), a.end(), std::ostream_iterator&lt;timerange&gt;(std::cout, &quot;, &quot;));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T17:21:06.813", "Id": "525965", "Score": "0", "body": "Thank you so much. I really appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T16:07:41.613", "Id": "266242", "ParentId": "266215", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T17:55:00.093", "Id": "266215", "Score": "5", "Tags": [ "c++", "strings", "vectors" ], "Title": "Algo to return a vector of available time slots for scheduling a meeting between two persons" }
266215
<p>I created a function that returns the next prime number greater or equal to the number given as an argument. My code works well, but I find it is very slow.</p> <p>The test suite take almost 60s and I want less than 10s. Can the code be optimised to achieve this?</p> <h1>Code</h1> <pre><code>#include &lt;stdio.h&gt; int ft_is_prime(int nb) { int i; i = (int)nb - 1; if (nb &lt;= 1) return (0); while (i &gt; 1) { if (nb % i == 0) return (0); i--; } return (1); } int ft_find_next_prime(int nb) { while (ft_is_prime(nb) == 0) { ft_is_prime(nb); nb++; } return (nb); } </code></pre> <h1>Tests</h1> <pre><code>int main() { printf(&quot;%d -&gt; %d\n&quot;, -1868, ft_find_next_prime(-1868)); printf(&quot;%d -&gt; %d\n&quot;, 0, ft_find_next_prime(0)); printf(&quot;%d -&gt; %d\n&quot;, 1, ft_find_next_prime(1)); printf(&quot;%d -&gt; %d\n&quot;, 2, ft_find_next_prime(2)); printf(&quot;%d -&gt; %d\n&quot;, 7853, ft_find_next_prime(7853)); printf(&quot;%d -&gt; %d\n&quot;, 78989, ft_find_next_prime(78989)); printf(&quot;%d -&gt; %d\n&quot;, 2147483643, ft_find_next_prime(2147483643)); printf(&quot;%d -&gt; %d\n&quot;, 2147483645, ft_find_next_prime(2147483645)); printf(&quot;%d -&gt; %d\n&quot;, 2147483646, ft_find_next_prime(2147483646)); printf(&quot;%d -&gt; %d\n&quot;, 2147483647, ft_find_next_prime(2147483647)); printf(&quot;%d -&gt; %d\n&quot;, 203785, ft_find_next_prime(203785)); printf(&quot;%d -&gt; %d\n&quot;, 14357, ft_find_next_prime(14357)); printf(&quot;%d -&gt; %d\n&quot;, 389654, ft_find_next_prime(389654)); printf(&quot;%d -&gt; %d\n&quot;, 356376, ft_find_next_prime(356376)); printf(&quot;%d -&gt; %d\n&quot;, 111641, ft_find_next_prime(111641)); printf(&quot;%d -&gt; %d\n&quot;, 139803, ft_find_next_prime(139803)); printf(&quot;%d -&gt; %d\n&quot;, 98368, ft_find_next_prime(98368)); printf(&quot;%d -&gt; %d\n&quot;, 172597, ft_find_next_prime(172597)); printf(&quot;%d -&gt; %d\n&quot;, 178697, ft_find_next_prime(178697)); printf(&quot;%d -&gt; %d\n&quot;, 295994, ft_find_next_prime(295994)); printf(&quot;%d -&gt; %d\n&quot;, 66107, ft_find_next_prime(66107)); printf(&quot;%d -&gt; %d\n&quot;, 348224, ft_find_next_prime(348224)); printf(&quot;%d -&gt; %d\n&quot;, 424018, ft_find_next_prime(424018)); printf(&quot;%d -&gt; %d\n&quot;, 182868, ft_find_next_prime(182868)); printf(&quot;%d -&gt; %d\n&quot;, 279638, ft_find_next_prime(279638)); printf(&quot;%d -&gt; %d\n&quot;, 215132, ft_find_next_prime(215132)); printf(&quot;%d -&gt; %d\n&quot;, 130734, ft_find_next_prime(130734)); printf(&quot;%d -&gt; %d\n&quot;, 254567, ft_find_next_prime(254567)); printf(&quot;%d -&gt; %d\n&quot;, 287850, ft_find_next_prime(287850)); printf(&quot;%d -&gt; %d\n&quot;, 101486, ft_find_next_prime(101486)); printf(&quot;%d -&gt; %d\n&quot;, 338034, ft_find_next_prime(338034)); printf(&quot;%d -&gt; %d\n&quot;, 367221, ft_find_next_prime(367221)); printf(&quot;%d -&gt; %d\n&quot;, 352888, ft_find_next_prime(352888)); printf(&quot;%d -&gt; %d\n&quot;, 296057, ft_find_next_prime(296057)); printf(&quot;%d -&gt; %d\n&quot;, 420476, ft_find_next_prime(420476)); printf(&quot;%d -&gt; %d\n&quot;, 337541, ft_find_next_prime(337541)); printf(&quot;%d -&gt; %d\n&quot;, 269965, ft_find_next_prime(269965)); printf(&quot;%d -&gt; %d\n&quot;, 262287, ft_find_next_prime(262287)); printf(&quot;%d -&gt; %d\n&quot;, 298128, ft_find_next_prime(298128)); printf(&quot;%d -&gt; %d\n&quot;, 81045, ft_find_next_prime(81045)); printf(&quot;%d -&gt; %d\n&quot;, 6816, ft_find_next_prime(6816)); printf(&quot;%d -&gt; %d\n&quot;, 200353, ft_find_next_prime(200353)); printf(&quot;%d -&gt; %d\n&quot;, 87717, ft_find_next_prime(87717)); printf(&quot;%d -&gt; %d\n&quot;, 275623, ft_find_next_prime(275623)); printf(&quot;%d -&gt; %d\n&quot;, 20140, ft_find_next_prime(20140)); printf(&quot;%d -&gt; %d\n&quot;, 145069, ft_find_next_prime(145069)); printf(&quot;%d -&gt; %d\n&quot;, 309422, ft_find_next_prime(309422)); printf(&quot;%d -&gt; %d\n&quot;, 288966, ft_find_next_prime(288966)); printf(&quot;%d -&gt; %d\n&quot;, 196808, ft_find_next_prime(196808)); printf(&quot;%d -&gt; %d\n&quot;, 408696, ft_find_next_prime(408696)); printf(&quot;%d -&gt; %d\n&quot;, 308434, ft_find_next_prime(308434)); printf(&quot;%d -&gt; %d\n&quot;, 234200, ft_find_next_prime(234200)); printf(&quot;%d -&gt; %d\n&quot;, 12514, ft_find_next_prime(12514)); printf(&quot;%d -&gt; %d\n&quot;, 363758, ft_find_next_prime(363758)); printf(&quot;%d -&gt; %d\n&quot;, 257776, ft_find_next_prime(257776)); printf(&quot;%d -&gt; %d\n&quot;, 312563, ft_find_next_prime(312563)); printf(&quot;%d -&gt; %d\n&quot;, 757, ft_find_next_prime(757)); printf(&quot;%d -&gt; %d\n&quot;, 398583, ft_find_next_prime(398583)); printf(&quot;%d -&gt; %d\n&quot;, 36608, ft_find_next_prime(36608)); printf(&quot;%d -&gt; %d\n&quot;, 35590, ft_find_next_prime(35590)); printf(&quot;%d -&gt; %d\n&quot;, 174862, ft_find_next_prime(174862)); printf(&quot;%d -&gt; %d\n&quot;, 409874, ft_find_next_prime(409874)); printf(&quot;%d -&gt; %d\n&quot;, 68893, ft_find_next_prime(68893)); printf(&quot;%d -&gt; %d\n&quot;, 87838, ft_find_next_prime(87838)); printf(&quot;%d -&gt; %d\n&quot;, 284334, ft_find_next_prime(284334)); printf(&quot;%d -&gt; %d\n&quot;, 48416, ft_find_next_prime(48416)); printf(&quot;%d -&gt; %d\n&quot;, 32034, ft_find_next_prime(32034)); printf(&quot;%d -&gt; %d\n&quot;, 125232, ft_find_next_prime(125232)); printf(&quot;%d -&gt; %d\n&quot;, 418100, ft_find_next_prime(418100)); printf(&quot;%d -&gt; %d\n&quot;, 312630, ft_find_next_prime(312630)); printf(&quot;%d -&gt; %d\n&quot;, 288568, ft_find_next_prime(288568)); printf(&quot;%d -&gt; %d\n&quot;, 398662, ft_find_next_prime(398662)); printf(&quot;%d -&gt; %d\n&quot;, 46407, ft_find_next_prime(46407)); printf(&quot;%d -&gt; %d\n&quot;, 121678, ft_find_next_prime(121678)); printf(&quot;%d -&gt; %d\n&quot;, 406867, ft_find_next_prime(406867)); printf(&quot;%d -&gt; %d\n&quot;, 61269, ft_find_next_prime(61269)); printf(&quot;%d -&gt; %d\n&quot;, 315739, ft_find_next_prime(315739)); printf(&quot;%d -&gt; %d\n&quot;, 271203, ft_find_next_prime(271203)); printf(&quot;%d -&gt; %d\n&quot;, 192870, ft_find_next_prime(192870)); printf(&quot;%d -&gt; %d\n&quot;, 114535, ft_find_next_prime(114535)); printf(&quot;%d -&gt; %d\n&quot;, 173417, ft_find_next_prime(173417)); printf(&quot;%d -&gt; %d\n&quot;, 248682, ft_find_next_prime(248682)); printf(&quot;%d -&gt; %d\n&quot;, 306029, ft_find_next_prime(306029)); printf(&quot;%d -&gt; %d\n&quot;, 108921, ft_find_next_prime(108921)); printf(&quot;%d -&gt; %d\n&quot;, 210815, ft_find_next_prime(210815)); printf(&quot;%d -&gt; %d\n&quot;, 252289, ft_find_next_prime(252289)); printf(&quot;%d -&gt; %d\n&quot;, 72584, ft_find_next_prime(72584)); printf(&quot;%d -&gt; %d\n&quot;, 297710, ft_find_next_prime(297710)); printf(&quot;%d -&gt; %d\n&quot;, 27544, ft_find_next_prime(27544)); printf(&quot;%d -&gt; %d\n&quot;, 373150, ft_find_next_prime(373150)); printf(&quot;%d -&gt; %d\n&quot;, 219888, ft_find_next_prime(219888)); printf(&quot;%d -&gt; %d\n&quot;, 156579, ft_find_next_prime(156579)); printf(&quot;%d -&gt; %d\n&quot;, 271274, ft_find_next_prime(271274)); printf(&quot;%d -&gt; %d\n&quot;, 295751, ft_find_next_prime(295751)); printf(&quot;%d -&gt; %d\n&quot;, 207022, ft_find_next_prime(207022)); printf(&quot;%d -&gt; %d\n&quot;, 143794, ft_find_next_prime(143794)); printf(&quot;%d -&gt; %d\n&quot;, 390643, ft_find_next_prime(390643)); printf(&quot;%d -&gt; %d\n&quot;, 186808, ft_find_next_prime(186808)); printf(&quot;%d -&gt; %d\n&quot;, 230330, ft_find_next_prime(230330)); printf(&quot;%d -&gt; %d\n&quot;, 175035, ft_find_next_prime(175035)); printf(&quot;%d -&gt; %d\n&quot;, 101832, ft_find_next_prime(101832)); printf(&quot;%d -&gt; %d\n&quot;, 205261, ft_find_next_prime(205261)); printf(&quot;%d -&gt; %d\n&quot;,389070, ft_find_next_prime(389070)); printf(&quot;%d -&gt; %d\n&quot;, 397788, ft_find_next_prime(397788)); printf(&quot;%d -&gt; %d\n&quot;, 6117, ft_find_next_prime(6117)); printf(&quot;%d -&gt; %d\n&quot;, 169448, ft_find_next_prime(169448)); printf(&quot;%d -&gt; %d\n&quot;, 393706, ft_find_next_prime(393706)); printf(&quot;%d -&gt; %d\n&quot;, 286195, ft_find_next_prime(286195)); printf(&quot;%d -&gt; %d\n&quot;, 334329, ft_find_next_prime(334329)); printf(&quot;%d -&gt; %d\n&quot;, 184829, ft_find_next_prime(184829)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T15:03:21.923", "Id": "525961", "Score": "2", "body": "I'm not well known in the C language, but that `main` method looks like it should be made into real automated tests, instead of a long `main`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T14:11:57.830", "Id": "526000", "Score": "2", "body": "In the future it would be better to add a follow up question with a link back to the original question rather than editing the question. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T15:11:18.467", "Id": "526006", "Score": "0", "body": "@SimonForsberg Yeah, you are right I got this from a trackback of the system that evaluated me" } ]
[ { "body": "<p>You was calling <code>ft_is_prime</code> function two times, try:</p>\n<pre><code>int ft_is_prime(int nb)\n{\n int i;\n\n // Validate arguments.\n if (nb &lt;= 1)\n return 0;\n\n for (i = nb - 1; i &gt; 1; --i) {\n if (nb % i == 0)\n return (0);\n }\n return (1);\n}\n\nint ft_find_next_prime(int nb)\n{\n\n while ( ! ft_is_prime(nb)) {\n ++nb;\n }\n return nb;\n}\n</code></pre>\n<p>But I am sure you seek more though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T18:23:51.720", "Id": "266217", "ParentId": "266216", "Score": "0" } }, { "body": "<p>Function <code>ft_is_prime</code> has complexity <code>O(n)</code> which is very slow as your input can be large. Simple optimization is to check divisors up to the square root of the number you are testing. There are <a href=\"https://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow noreferrer\">other algorithms to check primality</a>, but I think it is good enough in this case. I would also make nb <code>long long</code>. It can be implemented this way:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int ft_is_prime(long long nb) {\n if (nb &lt;= 1)\n return 0;\n for(long long i = 2; i*i &lt;= nb; i++){\n if(nb % i == 0){\n return 0;\n }\n }\n return 1;\n}\n</code></pre>\n<p>You can also check at first if 2 divides <code>nb</code> and then it would look like this (it doesn't change complexity):</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(nb % 2 == 0)\n return 0;\nfor(long long i = 3; i*i &lt;= nb; i+=2){\n if(nb % i == 0){\n return 0;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T23:57:18.547", "Id": "525905", "Score": "4", "body": "1) `i*i <= nb` overflows when `nb` is a large prime. Consider `i <= nb/i` 2) Error: `if(nb % 2 == 0) return 0;` should be `if(nb % 2 == 0) return nb == 2;`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T11:33:00.167", "Id": "525996", "Score": "0", "body": "@Gh0st Thank you neverthelessI don't have permission to use a library or a for loop, no externe function **Allowed functions: None** , and `long long` augmented the run time * 4." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T18:44:19.897", "Id": "266218", "ParentId": "266216", "Score": "3" } }, { "body": "<p>You can do much better with ft_find_next_prime().</p>\n<p>First, there is no prime &lt; 2, so if you start there, the prime is 2.</p>\n<p>Second, all primes &gt;2 are odd, so you don't need to consider even numbers.</p>\n<p>A general point, not related to your algorithm, is that it is often unwise to test for equality to your boolean values. Just use the value directly in the conditional test.</p>\n<p>Combined with @Top-Master's point, yields:</p>\n<pre><code>int ft_find_next_prime(int nb)\n{\n if (nb &lt;= 2) return 2; /*early numbers*/\n nb |= 1; /*Ensure it is odd*/\n while (!ft_is_prime(nb))\n {\n nb += 2;\n }\n return nb;\n}\n</code></pre>\n<p>The issue not explicitly raised about <code>ft_is_prime()</code>: You should check from the most probable to the least. I.e. start with 2, not nb-1 (or even <code>sqrt(nb)</code>). While it is O(n) or O(sqrt(n)) for a prime either way, you will get faster results for composites.</p>\n<p>One other odd twist you can do: My implementation of <code>ft_find_next_prime</code> never passes an even number to <code>ft_is_prime</code>. Thus, you could make a <code>ft_is_prime_given_odd</code> function and skip the first tests in @Gh0st's second optimized version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T18:01:10.310", "Id": "266251", "ParentId": "266216", "Score": "3" } }, { "body": "<blockquote>\n<pre><code>int ft_is_prime(int nb)\n</code></pre>\n</blockquote>\n<p>This is a boolean function, so we should document that:</p>\n<pre><code>#include &lt;stdbool.h&gt;\n\nbool ft_is_prime(int nb)\n</code></pre>\n<blockquote>\n<pre><code> int i;\n\ni = (int)nb - 1;\n</code></pre>\n</blockquote>\n<p>We can combine the declaration and assignment, and we don't need to cast (as <code>nb</code> is already of type <code>int</code>):</p>\n<pre><code>int i = nb - 1;\n</code></pre>\n<blockquote>\n<pre><code> return (0);\n</code></pre>\n</blockquote>\n<p>There's no need for parentheses there - plain old <code>return 0;</code> is simpler and more readable.</p>\n<blockquote>\n<pre><code>while (i &gt; 1)\n</code></pre>\n</blockquote>\n<p>Testing primality by trial division is already slow, but we've made it even slower by testing the largest candidate factors first. We'll eliminate numbers much more quickly if we start with the smallest candidates. And we can stop when we reach the square root of <code>nb</code>:</p>\n<pre><code>#include &lt;math.h&gt;\n\nbool ft_is_prime(int nb)\n{\n if (nb &lt; 2)\n return false;\n\n /* add one to ensure round-up */\n const int limit = (int)sqrt(nb) + 1;\n for (int i = 2; i &lt;= limit; ++i) {\n if (nb % i == 0) {\n return false;\n }\n }\n\n /* no factors found =&gt; must be prime */\n return true;\n}\n</code></pre>\n<p>We can go much faster by not considering any even numbers other than 2:</p>\n<pre><code> if (nb % 2 == 0) {\n return false;\n }\n\n /* add one to ensure round-up */\n const int limit = (int)sqrt(nb) + 1;\n for (int i = 3; i &lt;= limit; i += 2) {\n if (nb % i == 0) {\n return false;\n }\n }\n</code></pre>\n<p>That code using <code>sqrt()</code> is a little problematic, because it uses floating-point arithmetic, which is inexact (necessitating that <code>+1</code>) and, on many platforms, much slower than integer arithmetic. However, we can simply use <code>i &lt;= nb / i</code>, which shouldn't cause extra division: a good optimising compiler will use a single operation to compute both this <code>nb / i</code> and the <code>nb % i</code> on the next line.</p>\n<hr />\n<h1>Improved code</h1>\n<p>These changes improve the run time of the test suite from well over 1 minute to under 0.01 seconds (both compiled with <code>gcc -O3</code>).</p>\n<pre><code>#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;math.h&gt;\n\nbool ft_is_prime(int nb)\n{\n if (nb &lt; 2 || nb % 2 == 0 &amp;&amp; nb != 2) {\n return false;\n }\n\n for (int i = 3; i &lt;= nb/i; i += 2) {\n if (nb % i == 0) {\n return false;\n }\n }\n\n /* no factors found =&gt; must be prime */\n return true;\n}\n\nint ft_find_next_prime(int nb)\n{\n if (nb &lt; 2) {\n return 2;\n }\n\n while (!ft_is_prime(nb)) {\n ++nb;\n }\n return nb;\n}\n</code></pre>\n<hr />\n<p>To improve further, we should ditch the trial division and move to a better algorithm, perhaps using a prime number wheel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T11:58:46.850", "Id": "526089", "Score": "0", "body": "New term for me: [prime number wheel](https://en.wikipedia.org/wiki/Wheel_factorization). LSNED." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T12:12:21.173", "Id": "526091", "Score": "1", "body": "A good compiler with `for (int i = 3; i <= nb/i; i += 2) { if (nb % i == 0) { return false; } }` will see the nearby `nb/i` and `nb%i` and calculate both for the price of one. Or use `div()`. `sqrt(nb)` is a problem when `(double) nb` inexact (`int` as 64-bit, `nb` as `long long` ...) or expensive on processors lacking a FP unit. IAC, OP's slowness is solved by code like yours with O(sqrt(n)) time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T12:24:41.083", "Id": "526094", "Score": "0", "body": "Of course - I had completely overlooked the `%` in the same loop. That form is much better, and I'll edit accordingly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T11:05:03.363", "Id": "266321", "ParentId": "266216", "Score": "1" } } ]
{ "AcceptedAnswerId": "266251", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T18:10:12.727", "Id": "266216", "Score": "0", "Tags": [ "performance", "c" ], "Title": "Find the next prime at/after a given integer" }
266216
<p>I'm looking to rework and make it easier to read this handleFilterChange function</p> <p>This is helper being used in the function</p> <pre><code> const getTestableValue = (val: any) =&gt; val?.toString().trim(); </code></pre> <p>Sample for the filter value</p> <pre><code>{ &quot;clock.props.children&quot;: [], &quot;station&quot;: [] } </code></pre> <p>Sample of val being passed</p> <pre><code>clock clearance and tagging </code></pre> <p>Sample of currentFilterMenu being used</p> <pre><code>{ &quot;prop&quot;: &quot;clock.props.children&quot;, &quot;name&quot;: &quot;Clock Name&quot; } </code></pre> <p>This is the actual function I would like reviewed</p> <pre><code> const handleFilterChange = (val: any) =&gt; { const testableValue = getTestableValue(val); let newFilters = JSON.parse(JSON.stringify(filters)); if (currentFilterMenu) { if ( testableValue === 'ALL' &amp;&amp; newFilters[currentFilterMenu.prop].length === filterOptions[currentFilterMenu.prop].length ) { // hide all newFilters[currentFilterMenu.prop] = []; } else if ( testableValue === 'ALL' &amp;&amp; newFilters[currentFilterMenu.prop].length !== filterOptions[currentFilterMenu.prop].length ) { // show all newFilters[currentFilterMenu.prop] = filterOptions[currentFilterMenu.prop]; } else { const foundIdx = newFilters[currentFilterMenu.prop]?.findIndex( (item: any) =&gt; testableValue === getTestableValue(item) ); if (foundIdx !== undefined &amp;&amp; foundIdx &gt;= 0) { // value is being unchecked newFilters[currentFilterMenu.prop].splice(foundIdx, 1); } else { // value is being checked newFilters[currentFilterMenu.prop].push(val); } } } setFilters(newFilters); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T22:54:01.157", "Id": "525904", "Score": "1", "body": "Is this TS or JS? I only see two typings here, both of which are `any` so if it's TS you seem to be vastly underutilizing the tool. I recommend explaining why. Beyond that, I'm not really sure what the function does -- a bit more context and a clearer spec of input/output/behavior would be great. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T18:28:02.877", "Id": "529057", "Score": "0", "body": "What are filterOptions?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T18:45:42.813", "Id": "266219", "Score": "0", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming", "typescript" ], "Title": "Refactor Javascript filter that handles click and changing together dropdown filters" }
266219
<p>I have this code to go from an array of bytes (arbitrarily long) to a &quot;bigint&quot; string (really, an arbitrarily long string composed of integers 0-9), and go from that long integer string into an array of bytes.</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>console.log(bigintStringToBytes('12321232123213213292948428924184')) console.log(bytesToBigintString([ 155, 132, 12, 85, 200, 76, 41, 241, 14, 133, 71, 165, 24 ])) function bigintStringToBytes(str) { let dec = [...str], sum = [] while(dec.length){ let s = 1 * dec.shift() for(let i = 0; s || i &lt; sum.length; i++){ s += (sum[i] || 0) * 10 sum[i] = s % 256 s = (s - sum[i]) / 256 } } return Uint8Array.from(sum.reverse()) } function bytesToBigintString(arr) { var dec = [...arr], sum = [] while(dec.length){ let s = 1 * dec.shift() for(let i = 0; s || i &lt; sum.length; i++){ s += (sum[i] || 0) * 256 sum[i] = s % 10 s = (s - sum[i]) / 10 } } return sum.reverse().join('') }</code></pre> </div> </div> </p> <p>How can these two functions be optimized?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:52:34.407", "Id": "525900", "Score": "3", "body": "Do you have other test cases that need to pass, or some general constraint on how this needs to work? These functions look to me like they're doing something odd (not just a plain old base conversion), but if you're OK with that then sure why not. Also, is using the new-ish built-in `BigInt` allowed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T02:36:04.340", "Id": "525907", "Score": "0", "body": "If BigInt works, yeah you can use that. What other information do you need, I don't have any other test cases to pass, just plugin input and output and make sure they match up with each function. Then you could try optimizing the functions so the inputs/outputs are still the same. It should be any \"digitized\" string, converted to equivalent byte array representation, and back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T02:40:13.287", "Id": "525908", "Score": "0", "body": "Can the string version be hexadecimal? That would avoid the main complicating factor" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T02:44:41.597", "Id": "525909", "Score": "0", "body": "No the string needs to be integers, but if you wanted to share the hexadecimal solution as well that would be a plus :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T21:07:42.433", "Id": "266222", "Score": "3", "Tags": [ "javascript", "performance", "mathematics", "bigint" ], "Title": "converting from byte arrays to strings of integers, and back" }
266222
<p>I have a Python script that runs as a service, like this:</p> <pre class="lang-py prettyprint-override"><code>import time import traceback while True: time.sleep(60) try: main() except Exception: # Print the traceback, but keep running traceback.print_exc() </code></pre> <p>This runs every 60 seconds, and works great. What I want to do is have my code also listen for the <code>USR1</code> kill signal, and if it triggers, run main() right away. This way, my code can monitor something for changes periodically, but it can also get informed when a change happened, so it can react right away without waiting for the <code>time.sleep()</code> to return.</p> <p>What I ended up with is this:</p> <pre class="lang-py prettyprint-override"><code>from threading import Lock import signal import time import traceback MAIN_RUNNING = Lock() def run_main(): if MAIN_RUNNING.acquire(blocking=False): try: main() except Exception: traceback.print_exc() else: print(&quot;main() is already running - couldn't lock it&quot;) signal.signal(signal.SIGUSR1, lambda *_: run_main()) while True: time.sleep(60) run_main() </code></pre> <p>Does that make sense?</p> <p>Any potential problems I might run into with this?</p> <p>Is there a simpler way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T12:12:09.123", "Id": "525947", "Score": "0", "body": "I get an error when running your code `NameError: name 'main' is not defined` before the expected messages `main() is already running - couldn't lock it` appear. I think your code is more suited to StackOverflow and not Code Review. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T15:15:22.863", "Id": "525963", "Score": "0", "body": "@C.Harley that's because `main` is a stand-in for whatever my code is supposed to do, is irrelevant to the question, and is therefore not defined in the example. My real main function is very large" } ]
[ { "body": "<p>Your basic code looks fine, but you may encounter one issue if you start doing more complex work.</p>\n<p>Signals are handled in a different context to the context your program is normally executing in - the OS can suspend your program at any time, while it's running or not, to run a signal handler which then may execute more code from your program (if it's a signal for your process).</p>\n<p>This problem gives rise to the concept of &quot;reentrant functions&quot; which can safely have one thread suspended half way through execution, and have another thread enter it and run - without say, stomping on shared global variables or static allocations. There are surprisingly few reentrant functions in the C standard library, and POSIX libraries - see <a href=\"https://man7.org/linux/man-pages/man7/signal-safety.7.html\" rel=\"nofollow noreferrer\">https://man7.org/linux/man-pages/man7/signal-safety.7.html</a> for more information and a list.</p>\n<p>Expect seriously weird bugs or crashes if you call non-reentrant functions from the signal handler context.</p>\n<p>A safer way of handling this is to have the signal handler set a flag in your program when it's called. A daemon thread in your program can poll this flag and run in your program's regular context, when desired.</p>\n<p>Very naïve pseudocode:</p>\n<pre><code>ShouldRun = False\n\nfunc HandleSigUsr1:\n ShouldRun = True\n \nfunc HandleSigUsr1Daemon:\n while (1):\n if ShouldRun == True:\n ShouldRUn = False\n run_main()\n\nsignal.Signal(SIGUSR1, handleSigUsr1)\n</code></pre>\n<p>A slightly more powerful implementation could sleep for a short time (0.001s? 0.01s?) between daemon loops to avoid constantly sucking up CPU time, or poll a file descriptor rather than a variable, to have the OS sleep the daemon until there's new content.</p>\n<p>As a final disclaimer, I'm not sure if Python's signal handling library already does something like this under the hood - it seems like the kind of detail a high level language and runtime like Python would try to hide.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T01:04:37.600", "Id": "266225", "ParentId": "266224", "Score": "3" } } ]
{ "AcceptedAnswerId": "266225", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T22:58:39.433", "Id": "266224", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Python Service with USR1 kill signal handler" }
266224
<p>I've put together this script to check through various location and pick the next media file to play on an internet radio station:</p> <pre><code>#!/bin/sh dir=/ezstream # processing function play_next() { location=$1 used=$2 last=$3 # check for media available=$(ls -1 $location) if [ -z &quot;$available&quot; ]; then # this is an empty folder; report unsuccessful return 0 else # remove already-used media if [ -f $used ]; then while read remove; do available=$(echo &quot;$available&quot; | grep -v &quot;${remove##*/}&quot;) done &lt; $used elif [ -f $last ]; then remove=$(cat $last) available=$(echo &quot;$available&quot; | grep -v &quot;$remove&quot;) fi # calculate and play next remaining=$(echo &quot;$available&quot; | wc -l) if [ $remaining -eq 1 ]; then rm -f $used next=$location/$available echo $next | tee $last else next=$location/$(echo &quot;$available&quot; | shuf -n 1) echo $next | tee -a $used | tee $last fi echo $(date +&quot;%Y-%m-%d %T&quot;): $next &gt;&gt; $dir/history.log # report success return 1 fi } # Check all the options provided in the cfg. options=$(cat $dir/config/play-next.cfg | jq -c '. |= sort_by(-(.spacing//0)) | .[]') for option in $options; do name=$dir/$(echo $option | jq -j '.name') location=$(echo $option | jq -j '.location') spacing=$(echo $option | jq -j '.spacing//0') # If the tracking file doesn't exist, or it was last touched at # least $spacing minutes ago, then this is the next thing to play. if [ ! -f $name.play ] || [ $(find $name.play -mmin +$spacing | wc -l) -eq 1 ] || [ $(find $name.play -mmin $spacing | wc -l) -eq 1 ]; then play_next $location $name.txt $name.play if [ $? == 1 ]; then break fi fi done </code></pre> <p>If I use a config that intersperses stingers among the episodes, the script takes ~0.8s to run:</p> <pre><code>[ { &quot;name&quot;: &quot;episodes&quot;, &quot;location&quot;: &quot;/run/radio/media/episodes&quot; }, { &quot;name&quot;: &quot;stingers&quot;, &quot;location&quot;: &quot;/run/radio/media/stingers&quot;, &quot;spacing&quot;: 120 } ] </code></pre> <p>However, if I add an empty folder, the time to run this goes up ~50% to ~1.2s:</p> <pre><code>[ { &quot;name&quot;: &quot;episodes&quot;, &quot;location&quot;: &quot;/run/radio/media/episodes&quot; }, { &quot;name&quot;: &quot;stingers&quot;, &quot;location&quot;: &quot;/run/radio/media/stingers&quot;, &quot;spacing&quot;: 120 }, { &quot;name&quot;: &quot;empty&quot;, &quot;location&quot;: &quot;/run/radio/media/empty&quot;, &quot;spacing&quot;: 5 } ] </code></pre> <p>Once it takes that long, my streaming client loses the connection, and I have to reconnect, so I'd like to speed this script up. In the future, there will be more directories / types of media to intersperse. I will obviously avoid having empty directories in the config, but I want to get ahead of the script time-to-run expanding as more locations are added. Any suggestions on how to tune this would be greatly appreciated; I'm fairly new to shell scripting (and linux in general).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T03:20:28.033", "Id": "266226", "Score": "0", "Tags": [ "linux", "shell" ], "Title": "Where and how can I speed up this config-driven ezstream script?" }
266226
<p>I wrote a program that syncs the lyric of an MP3 song and displays the text as a subtitle when playing the song, but my code for this is too Unprofessional and weak. Is there a way to display it more professionally?<br /> I tried this:</p> <pre><code>Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click Dim lines As String() = VTextBox1.Lines lines(lblLineNumber.Text) = AxWindowsMediaPlayer1.Ctlcontrols.currentPositionString &amp; &quot;-&quot; _ &amp; lblLineText.Text VTextBox1.Lines = lines End Sub </code></pre> <p>result this:</p> <pre><code>00:08 - The situation is dire 00:11 - But momma raised up a fighter 00:15 - It's all come down to the wire </code></pre> <p>Display lyric code:</p> <pre><code> Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Label6.Text = AxWindowsMediaPlayer1.Ctlcontrols.currentPositionString End Sub Private Sub Label6_TextChanged(sender As Object, e As EventArgs) Handles Label6.TextChanged For Each T As String In VTextBox1.Lines If T.Contains(Label6.Text) = True Then Dim array As String = T Dim srt As String = array.Substring(array.IndexOf(&quot;-&quot;) + 1) lblDisplayLyric.Text = srt End If Next End Sub </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T05:14:55.787", "Id": "266228", "Score": "1", "Tags": [ "vb.net" ], "Title": "Showing synced lyrics of mp3 music in vb.net" }
266228
<p>The two list have different structure. The list originalPgs is a list of <code>PGRatingConfig</code> and has this structure:</p> <pre><code>class PGRatingConfig { .... Rating rating; } class Rating { String pgId; String value; } </code></pre> <p>pgLookupTable returns List which is of the form: id and name of the product</p> <pre><code>private List&lt;PGRatingConfig&gt; addendumPgs(List&lt;PGRatingConfig&gt; originalPgs) { List&lt;Rating&gt; ratings = pgLookupTable(); List&lt;String&gt; pgIds = ratings.stream().map(a -&gt; a.getPgId()).collect(Collectors.toList()); for(PGRatingConfig rating: new ArrayList&lt;&gt;(originalPgs) ){ for(Rating ratingObj: new ArrayList&lt;&gt;(rating.getRating())){ for(String pg: pgIds){ if(!rating.getRating().stream().map(r-&gt;r.getPgId()).collect(Collectors.toList()).contains(pg)){ rating.getRating().add(new Rating(pg, 3.0)); } } } } log.info(&quot;originalPgs, &quot;+originalPgs); return originalPgs; } </code></pre> <p>How do I improve this code? I had to cycle between Java 8 and pre-8 code just to get this working.</p>
[]
[ { "body": "<p>For starters you should stop putting stream operations on a single line. They should be formatted so that each stream operation is on their own line. It makes following the code much easier:</p>\n<pre><code>if (! rating.getRating()\n .stream()\n .map(r-&gt;r.getPgId())\n .collect(Collectors.toList())\n .contains(pg)) {\n rating.getRating().add(new Rating(pg, 3.0));\n}\n</code></pre>\n<p>Secondly, collecting the results to see if the result contains a single value is unnecessary waste. Especially if oyu use a List instead of <code>Collectors.toSet()</code> The same as above can be achieved with filtering and finding a match:</p>\n<pre><code>if (! rating.getRating()\n .stream()\n .filter(r -&gt; pg.equals(r.getPgId()))\n .findAny()\n .isPresent() {\n rating.getRating().add(new Rating(pg, 3.0));\n}\n</code></pre>\n<p>You are not modifying the <code>originalPgs</code> collection, only the objects in it, so there is no need to create new <code>ArrayList</code> for it. The inner loop that uses the <code>ratingObj</code> variable is unnecessary, because you are not using <code>ratingObj</code> anywhere in your code.</p>\n<pre><code>for (PGRatingConfig rating: originalPgs) {\n for (String pg: pgIds) {\n if (! rating.getRating()\n .stream()\n .filter(r -&gt; pg.equals(r.getPgId()))\n .findFirst()\n .isPresent() {\n rating.getRating().add(new Rating(pg, 3.0));\n }\n }\n}\n</code></pre>\n<p>Now there probably is a way to do this without the inner loop that iterates over <code>pgIds</code> but I don't have the time to explore it now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T07:10:58.407", "Id": "266231", "ParentId": "266229", "Score": "4" } }, { "body": "<p>None of this is going to be directly helpful because we don't have enough visibility into the surrounding code, and it's not clear to what extent you can make changes. It looks like the overall codebase has some severe challenges which you may not have the ability to change.</p>\n<p>This code is very hard to read because the names of various things are not at all helpful.</p>\n<ul>\n<li><code>pgLookupTable()</code> is a method that returns a <code>List</code>, where the reader would expect a <code>Map</code> or some other kind of lookup structure.</li>\n<li><code>getRating</code> is singular, but apparently returns a <code>List&lt;Rating&gt;</code>? &gt; <code>PGRatingConfig</code>, <code>pgId</code>, etc. are totally obtuse because <code>PG</code> is meaningless. &gt; <code>addendumPgs</code> is confusing because <code>addendum</code> does not mean anything close to what this method does.</li>\n<li>calling a <code>PGRatingConfig</code> a <code>rating</code> means the code can't use <code>rating</code> later, when there is an actual rating.</li>\n<li>a <code>pgId</code> should not be stored in a variable named <code>pg</code>.</li>\n</ul>\n<p>Why does a rating take a double value and store it as a String? That's confusing at best.</p>\n<p>I've downvoted this question because <code>PGRatingConfig</code> doesn't provide the methods that <code>addendumPgs</code> clearly expects.</p>\n<p>The <code>ratings</code> property is used only once, on the very next line. Fold it into the stream call.</p>\n<p>In idiomatic java, there is whitespace between <code>for</code> and <code>(</code>, and also between <code>)</code> and <code>{</code></p>\n<p>Since the lists are not modified, there's no point in defensive copies unless the code is in a multithreaded environment, which I doubt given what the rest of the code looks like. Both instances of <code>new ArrayList&lt;&gt;</code> can be removed.</p>\n<p>The code is looping over the Ratings in each <code>PGRatingConfig</code> and then not doing anything with the value it's looping over. This <code>for</code> loop appears to be doing nothing except repeating the inner <code>for</code> loop to no benefit.</p>\n<p>The stream collecting pgIds should be computed once, not once for every pgId. Since it's being used to check for existence, it should be stored in a <code>Set</code> for O(1) lookup, instead of a <code>List</code> with O(n) lookup.</p>\n<p>It would be preferable to hide the <code>Ratings</code> collection from clients of <code>PGRatingConfig</code> and only expose methods that clients care about, such as <code>addRating()</code>.</p>\n<p><code>PGRatingConfig</code> should probably store the Ratings as a <code>Map&lt;Long /* PgId */, Rating&gt;</code>.</p>\n<p>Depending on the codebase, the code could also compute the disjoint ids directly in PgRatingConfig. Or, if the code must expose the collection, it can compute the missing IDs in <code>addendumPgs</code>.</p>\n<p>If you made all these changes, your code might look something like:</p>\n<pre><code>private List&lt;PGRatingConfig&gt; addendumPgs(List&lt;PGRatingConfig&gt; originalPgRatingConfigs) {\n List&lt;String&gt; pgIds = pgLookupTable().stream().map(a -&gt; a.getPgId()).collect(Collectors.toList());\n\n for (PGRatingConfig pgRatingConfig: originalPgRatingConfigs) {\n for (String pgId: pgIds) {\n if (!pgRatingConfig.hasRatingWithPgId(pgId)) {\n pgRatingConfig.addRating(new Rating(pgId, &quot;3.0&quot;));\n }\n }\n }\n return originalPgRatingConfigs;\n}\n\nprivate List&lt;PGRatingConfig&gt; addMissingPgs(List&lt;PGRatingConfig&gt; originalPgRatingConfigs) {\n List&lt;String&gt; pgIds = pgLookupTable().stream().map(a -&gt; a.getPgId()).collect(Collectors.toList());\n\n for (PGRatingConfig pgRatingConfig: originalPgRatingConfigs) {\n for (String missingPgId: pgRatingConfig.findMissingPgIds(pgIds)) {\n pgRatingConfig.addRating(new Rating(missingPgId, &quot;3.0&quot;));\n }\n }\n return originalPgRatingConfigs;\n}\n\nclass PGRatingConfig {\n private Map&lt;String, Rating&gt; ratings;\n\n public Map&lt;String, Rating&gt; getRatings() {\n return ratings;\n }\n\n public boolean hasRatingWithPgId(String pgId) {\n return ratings.containsKey(pgId);\n }\n\n public void addRating(Rating rating) {\n ratings.put(rating.getPgId(), rating);\n }\n\n public Set&lt;String&gt; findMissingPgIds(Collection&lt;String&gt; pgIds) {\n Set&lt;String&gt; missingPgIds = new HashSet&lt;&gt;(pgIds);\n missingPgIds.removeAll(ratings.keySet());\n return missingPgIds;\n }\n}\n\nclass Rating {\n private String pgId;\n private String value;\n\n public Rating(String pg, String value) {\n this.pgId = pg;\n this.value = value;\n }\n\n public String getPgId() {\n return pgId;\n }\n\n public String getValue() {\n return value;\n }\n}\n\npublic List&lt;Rating&gt; pgLookupTable() {\n return null;\n}\n</code></pre>\n<p>If you absolutely can't change any code other than the method you provided, I think the best you can do is:</p>\n<pre><code>private List&lt;PGRatingConfig&gt; addendumPgs2(List&lt;PGRatingConfig&gt; originalPgs) {\n Set&lt;String&gt; pgIds = pgLookupTable().stream().map(a -&gt; a.getPgId()).collect(toSet());\n\n for (PGRatingConfig pgRatingConfig: originalPgs) {\n Set&lt;Rating&gt; missingRatings =\n pgRatingConfig\n .getRating()\n .stream()\n .map(rating -&gt; rating.getPgId())\n .filter(id -&gt; !pgIds.contains(id))\n .map(id -&gt; new Rating(id, 3.0))\n .collect(toSet());\n pgRatingConfig.getRating().addAll(missingRatings);\n }\n\n log.info(&quot;originalPgs, &quot;+originalPgs);\n return originalPgs;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T20:23:22.327", "Id": "266298", "ParentId": "266229", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T05:42:00.690", "Id": "266229", "Score": "1", "Tags": [ "java" ], "Title": "Merge in list from another list that are not present in the former list" }
266229
<p>This is my code:</p> <pre><code>from database_function import * from kiteconnect import KiteTicker import pandas as pd from datetime import datetime, timedelta import schedule import time from multiprocessing import Process def tick_A(): #credentials code here tokens = [x[0] for x in db_fetchquery(&quot;SELECT zerodha FROM script ORDER BY id ASC LIMIT 50&quot;)] #FETCHING FIRST 50 SCRIPTS TOKEN #print(tokens) ##### TO MAKE SURE THE TASK STARTS AFTER 8:59 ONLY ########### t = datetime.today() future = datetime(t.year,t.month,t.day,8,59) if ((future-t).total_seconds()) &lt; 0: future = datetime(t.year,t.month,t.day,t.hour,t.minute,(t.second+2)) time.sleep((future-t).total_seconds()) ##### TO MAKE SURE THE TASK STARTS AFTER 8:59 ONLY ########### def on_ticks(ws, ticks): global ltp ltp = ticks[0][&quot;last_price&quot;] for tick in ticks: print(f&quot;{tick['instrument_token']}A&quot;) db_runquery(f'UPDATE SCRIPT SET ltp = {tick[&quot;last_price&quot;]} WHERE zerodha = {tick[&quot;instrument_token&quot;]}') #UPDATING LTP IN DATABASE #print(f&quot;{tick['last_price']}&quot;) def on_connect(ws, response): #print(f&quot;response from connect :: {response}&quot;) # Subscribe to a list of instrument_tokens (TOKENS FETCHED ABOVE WILL BE SUBSCRIBED HERE). # logging.debug(&quot;on connect: {}&quot;.format(response)) ws.subscribe(tokens) ws.set_mode(ws.MODE_LTP,tokens) # SETTING TOKEN TO TICK MODE (LTP / FULL / QUOTE) kws.on_ticks = on_ticks kws.on_connect = on_connect kws.connect(threaded=True) #####TO STOP THE TASK AFTER 15:32 ####### end_time = datetime(t.year,t.month,t.day,15,32) while True: schedule.run_pending() #time.sleep(1) if datetime.now() &gt; end_time: break #####TO STOP THE TASK AFTER 15:32 ####### def tick_B(): everything remains the same only tokens value changes tokens = [x[0] for x in db_fetchquery(&quot;SELECT zerodha FROM script ORDER BY id ASC OFFSET (50) ROWS FETCH NEXT (50) ROWS ONLY&quot;)] def tick_C(): everything remains the same only tokens value changes tokens = [x[0] for x in db_fetchquery(&quot;SELECT zerodha FROM script ORDER BY id ASC OFFSET (100) ROWS FETCH NEXT (50) ROWS ONLY&quot;)] if __name__ == '__main__': def runInParallel(*fns): proc = [] for fn in fns: p = Process(target=fn) p.start() proc.append(p) for p in proc: p.join() runInParallel(tick_A , tick_B , tick_C) </code></pre> <p>So, currently, I am using multiprocessing to run these 3 functions together.</p> <p>As only tokens changes, is it recommended to switch to multi-threading? (if yes, will it really help in a performance like speed-up and I think memory will be for sure used less)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T23:00:39.037", "Id": "525969", "Score": "0", "body": "A thing to consider is that threads in CPython are limited by the GIL. Multithreading with the standard implementation is best used only for I/O-heavy uses. For database manipulation, that likely depends on the database and what exactly what you're doing with it. Multithreading will work well with disk-access since that isn't CPU intensive, but not processing of the data." } ]
[ { "body": "<p>Yes, in general threads are lighter than process, they consume less memory and less resources. However, you need to measure this in your use case(program or system) and see what works for you. If your program wants to share the same memory space use threads, but bear in mind that you will need to protect the memory with semaphores or some locking system.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T08:10:46.793", "Id": "266232", "ParentId": "266230", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T06:21:06.310", "Id": "266230", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "multithreading", "multiprocessing" ], "Title": "Multithread or multiprocess" }
266230
<p>Here is my attempt to output webscraping results to a <code>bibtex</code> file.</p> <p>I would like to use this format as input to the <a href="https://www.zotero.org" rel="nofollow noreferrer">Zotero</a> database.</p> <p>As <a href="https://retorque.re/zotero-better-bibtex/" rel="nofollow noreferrer">BetterBibtex</a> already has a function to generate customized citation keys, I don't want to reinvent the wheel over here. Therefore, citation keys are generated using the <code>uuid</code> hex string just to avoid errors.</p> <p>Presently, I make use of the <a href="https://bibtexparser.readthedocs.io/en/master/tutorial.html" rel="nofollow noreferrer">BibtexParser</a> library to output search results to a dictionary, then feed that dictionary into a database, and use that database to generate a bibtex file, which is the final output.</p> <p>Just like to know if there is a better and more efficient way of doing this.</p> <h1>main.py</h1> <pre><code>import cnki import json from typing import Iterable, Tuple, List from pathlib import Path import bibtexparser from bibtexparser.bwriter import BibTexWriter from bibtexparser.bibdatabase import BibDatabase DB_DICT = { &quot;cnki&quot;: cnki.search, &quot;fudan&quot;: fudan.search, &quot;wuhan&quot;: wuhan.search, &quot;qinghua&quot;: qinghua.search, } def save_articles(articles: Iterable, file_prefix: str, output_format: str) -&gt; None: file_path = Path(file_prefix).with_suffix(f'.{output_format}') if output_format == &quot;json&quot;: with file_path.open('w') as file: file.write('[\n') first = True for article in articles: if first: first = False else: file.write(',\n') json.dump(article.as_dict(), file, ensure_ascii=False, indent=4) file.write('\n]\n') elif output_format == &quot;bib&quot;: db = BibDatabase() for article in articles: bib_dict = article.as_bib() bib_dict = {k: v for k, v in bib_dict.items() if v is not None} # Remove none values. db.entries.append(bib_dict) writer = BibTexWriter() with file_path.open('w') as bibfile: bibfile.write(writer.write(db)) def db_search(keyword: str, *args: Tuple[str]): if args: for db in args: yield from DB_DICT[db](keyword) else: for key in DB_DICT.keys(): yield from DB_DICT[key](keyword) def search(keywords: List[str], *args: str): for kw in keywords: yield from db_search(kw, *args) if __name__ == '__main__': rslt = search(['尹至'],'cnki') save_articles(rslt, 'search_result', 'bib') </code></pre> <h1>cnki.py</h1> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager from dataclasses import dataclass from datetime import date from pathlib import Path from typing import Generator, Iterable, Optional, List, ContextManager, Dict, Tuple from urllib.parse import unquote import uuid from itertools import chain, count import re import json from math import ceil # pip install proxy.py import proxy from proxy.http.exception import HttpRequestRejected from proxy.http.parser import HttpParser from proxy.http.proxy import HttpProxyBasePlugin from selenium.common.exceptions import ( NoSuchElementException, StaleElementReferenceException, TimeoutException, WebDriverException, ) from selenium.webdriver import Firefox, FirefoxProfile from selenium.webdriver.common.by import By from selenium.webdriver.common.proxy import ProxyType from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait # from urllib3.packages.six import X @dataclass class Result: title: str # Mozi's Theory of Human Nature and Politics title_link: str # http://big5.oversea.cnki.net/kns55/detail/detail.aspx?recid=&amp;FileName=ZDXB202006009&amp;DbName=CJFDLAST2021&amp;DbCode=CJFD html_link: Optional[str] # http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009 author: str # Xie Qiyang source: str # Vocational University News source_link: str # http://big5.oversea.cnki.net/kns55/Navi/ScdbBridge.aspx?DBCode=CJFD&amp;BaseID=ZDXB&amp;UnitCode=&amp;NaviLink=%e8%81%8c%e5%a4%a7%e5%ad%a6%e6%8a%a5 date: date # 2020-12-28 download: str # database: str # Periodical @classmethod def from_row(cls, row: WebElement) -&gt; 'Result': number, title, author, source, published, database = row.find_elements_by_xpath('td') title_links = title.find_elements_by_tag_name('a') if len(title_links) &gt; 1: # 'http://big5.oversea.cnki.net/kns55/ReadRedirectPage.aspx?flag=html&amp;domain=http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009' html_link = unquote( title_links[1] .get_attribute('href') .split('domain=', 1)[1]) else: html_link = None dl_links, sno = number.find_elements_by_tag_name('a') dl_links = dl_links.get_attribute('href') if re.search(&quot;javascript:alert.+&quot;, dl_links): dl_links = None published_date = date.fromisoformat( published.text.split(maxsplit=1)[0] ) return cls( title=title_links[0].text, title_link=title_links[0].get_attribute('href'), html_link=html_link, author=author.text, source=source.text, source_link=source.get_attribute('href'), date=published_date, download=dl_links, database=database.text, ) def __str__(self): return ( f'題名 {self.title}' f'\n作者 {self.author}' f'\n來源 {self.source}' f'\n發表時間 {self.date}' f'\n下載連結 {self.download}' f'\n來源數據庫 {self.database}' ) def as_dict(self) -&gt; Dict[str, str]: return { 'author': self.author, 'title': self.title, 'publication/university': self.source, 'date': self.date.isoformat(), 'download': self.download, 'url': self.html_link, 'database': self.database, } def as_bib(self) -&gt; Dict[str, str]: id = uuid.uuid1() if self.database == &quot;期刊&quot; or self.database == &quot;輯刊&quot;: return { 'ID': str(id.hex), 'ENTRYTYPE': 'article', 'author': self.author, 'title': self.title, 'journaltitle': self.source, 'date': self.date.isoformat(), 'url': self.html_link, # 'file': self.download, } elif self.database == &quot;博士&quot;: return { 'ID': str(id.hex), 'ENTRYTYPE': 'phdthesis', 'author': self.author, 'title': self.title, 'institution': self.source, 'date': self.date.isoformat(), 'url': self.download, # 'file': self.download, } elif self.database == &quot;碩士&quot;: return { 'ID': str(id.hex), 'ENTRYTYPE': 'mastersthesis', 'author': self.author, 'title': self.title, 'institution': self.source, 'date': self.date.isoformat(), 'url': self.download, # 'file': self.download, } class MainPage: def __init__(self, driver: WebDriver): self.driver = driver def submit_search(self, keyword: str) -&gt; None: wait = WebDriverWait(self.driver, 50) search = wait.until( EC.presence_of_element_located((By.NAME, 'txt_1_value1')) ) search.send_keys(keyword) search.submit() def switch_to_frame(self) -&gt; None: wait = WebDriverWait(self.driver, 100) wait.until( EC.presence_of_element_located((By.XPATH, '//iframe[@name=&quot;iframeResult&quot;]')) ) self.driver.switch_to.default_content() self.driver.switch_to.frame('iframeResult') wait.until( EC.presence_of_element_located((By.XPATH, '//table[@class=&quot;GridTableContent&quot;]')) ) def max_content(self) -&gt; None: &quot;&quot;&quot;Maximize the number of items on display in the search results.&quot;&quot;&quot; max_content = self.driver.find_element( By.CSS_SELECTOR, '#id_grid_display_num &gt; a:nth-child(3)', ) max_content.click() # def get_element_and_stop_page(self, *locator) -&gt; WebElement: # ignored_exceptions = (NoSuchElementException, StaleElementReferenceException) # wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions) # elm = wait.until(EC.presence_of_element_located(locator)) # self.driver.execute_script(&quot;window.stop();&quot;) # return elm class SearchResults: def __init__(self, driver: WebDriver): self.driver = driver def number_of_articles_and_pages(self) -&gt; Tuple[ int, # articles int, # pages int, # page size ]: articles_elem = self.driver.find_element_by_css_selector('td.TitleLeftCell td') n_articles = int(re.search(r&quot;\d+&quot;, articles_elem.text)[0]) page_elem = self.driver.find_element_by_css_selector('font.numNow') per_page = int(page_elem.text) n_pages = ceil(n_articles / per_page) return n_articles, n_pages def get_structured_elements(self) -&gt; Iterable[Result]: rows = self.driver.find_elements_by_xpath( '//table[@class=&quot;GridTableContent&quot;]//tr[position() &gt; 1]' ) for row in rows: yield Result.from_row(row) def get_element_and_stop_page(self, *locator) -&gt; WebElement: ignored_exceptions = (NoSuchElementException, StaleElementReferenceException) wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions) elm = wait.until(EC.presence_of_element_located(locator)) self.driver.execute_script(&quot;window.stop();&quot;) return elm def next_page(self) -&gt; None: link = self.get_element_and_stop_page(By.LINK_TEXT, &quot;下頁&quot;) try: link.click() print(&quot;Navigating to Next Page&quot;) except (TimeoutException, WebDriverException): print(&quot;Last page reached&quot;) class ContentFilterPlugin(HttpProxyBasePlugin): HOST_WHITELIST = { b'ocsp.digicert.com', b'ocsp.sca1b.amazontrust.com', b'big5.oversea.cnki.net', } def handle_client_request(self, request: HttpParser) -&gt; Optional[HttpParser]: host = request.host or request.header(b'Host') if host not in self.HOST_WHITELIST: raise HttpRequestRejected(403) if any( suffix in request.path for suffix in ( b'png', b'ico', b'jpg', b'gif', b'css', ) ): raise HttpRequestRejected(403) return request def before_upstream_connection(self, request): return super().before_upstream_connection(request) def handle_upstream_chunk(self, chunk): return super().handle_upstream_chunk(chunk) def on_upstream_connection_close(self): pass @contextmanager def run_driver() -&gt; ContextManager[WebDriver]: prox_type = ProxyType.MANUAL['ff_value'] prox_host = '127.0.0.1' prox_port = 8889 profile = FirefoxProfile() profile.set_preference('network.proxy.type', prox_type) profile.set_preference('network.proxy.http', prox_host) profile.set_preference('network.proxy.ssl', prox_host) profile.set_preference('network.proxy.http_port', prox_port) profile.set_preference('network.proxy.ssl_port', prox_port) profile.update_preferences() plugin = f'{Path(__file__).stem}.{ContentFilterPlugin.__name__}' with proxy.start(( '--hostname', prox_host, '--port', str(prox_port), '--plugins', plugin, )), Firefox(profile) as driver: yield driver def loop_through_results(driver): result_page = SearchResults(driver) n_articles, n_pages = result_page.number_of_articles_and_pages() print(f&quot;{n_articles} found. A maximum of 500 will be retrieved.&quot;) for page in count(1): print(f&quot;Scraping page {page}/{n_pages}&quot;) print() result = result_page.get_structured_elements() yield from result if page &gt;= n_pages or page &gt;= 10: break result_page.next_page() result_page = SearchResults(driver) def save_articles(articles: Iterable, file_prefix: str) -&gt; None: file_path = Path(file_prefix).with_suffix('.json') with file_path.open('w') as file: file.write('[\n') first = True for article in articles: if first: first = False else: file.write(',\n') json.dump(article.as_dict(), file, ensure_ascii=False, indent=4) file.write('\n]\n') def query(keyword, driver) -&gt; None: page = MainPage(driver) page.submit_search(keyword) page.switch_to_frame() page.max_content() def search(keyword): with Firefox() as driver: driver.get('http://cnki.sris.com.tw/kns55') query(keyword, driver) print(&quot;正在搜尋中國期刊網……&quot;) print(f&quot;關鍵字:「{keyword}」&quot;) result = loop_through_results(driver) # save_articles(result, 'cnki_search_result.json') yield from result if __name__ == '__main__': search('尹至') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T15:32:06.960", "Id": "528699", "Score": "0", "body": "This doesn't load? I get `bad gateway` for the website." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T02:08:03.533", "Id": "528721", "Score": "0", "body": "The url has been changed to http://cnki.sris.com.tw/kns55" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T02:10:23.207", "Id": "528722", "Score": "0", "body": "Though you can follow the link above, `driver.get('http://cnki.sris.com.tw/kns55')` still doesn't connect..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T02:12:01.093", "Id": "528723", "Score": "0", "body": "`selenium.common.exceptions.WebDriverException: Message: Failed to decode response from marionette`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T09:24:51.967", "Id": "528736", "Score": "0", "body": "The new url seem to have broken your content filter plugin. So I have to disable it for the code to work..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T09:28:34.987", "Id": "528737", "Score": "0", "body": "The code should be working fine now." } ]
[ { "body": "<blockquote>\n<p>The code should be working fine now</p>\n</blockquote>\n<p>It doesn't; the site dies with a 503. Anyway:</p>\n<ul>\n<li><code>articles: Iterable</code> should specify what it's an iterable of</li>\n<li>don't accept a free string for <code>output_format</code>; use an <code>Enum</code></li>\n<li>for any reasonable size of data, your iterated <code>json.dump</code> should not be necessary and you should be able to combine to a single list and a single <code>dump</code> call</li>\n<li><code>db_search</code>, rather than accepting <code>*args</code>, would be clearer as <code>*databases</code>. Also you only need a single <code>for</code> loop if you conditionally overwrite <code>databases</code> with <code>DB_DICT.keys()</code>.</li>\n<li><code>search</code> should have an <code>Iterable</code> typehint.</li>\n<li>You have several unused imports. Any self-respecting IDE will point these out to you so that you can delete them.</li>\n<li><code>as_bib</code> should factor out the common columns - ID, author, title and date - to a common dictionary and conditionally update it.</li>\n<li><code>self.database == &quot;期刊&quot; or self.database == &quot;輯刊&quot;</code> should use a set membership check.</li>\n<li>Unused methods like <code>get_element_and_stop_page</code> should be deleted. You should be running source control which will make operations like this safe.</li>\n<li>The return typehint for <code>number_of_articles_and_pages</code> is wrong; there should only be two tuple elements.</li>\n<li>Delete all of the proxy stuff if you're not going to use it</li>\n<li><code>loop_through_results</code> should have an <code>Iterable</code> return typehint</li>\n<li>The database names 期刊, 輯刊, 博士 and 碩士 should be saved to English-language constants such as <code>MASTERS</code>, potentially in an <code>Enum</code> if the set of known values is understood.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T07:17:49.143", "Id": "528778", "Score": "0", "body": "I couldn't reproduce your error. Did you run the code via `main.py`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T17:55:20.880", "Id": "268157", "ParentId": "266236", "Score": "2" } } ]
{ "AcceptedAnswerId": "268157", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T09:53:37.340", "Id": "266236", "Score": "2", "Tags": [ "python", "web-scraping" ], "Title": "Output webscraping results to BibTex file" }
266236
<p>I'm really new to code optimization and JS. I would like to ask for help on optimizing my code. Thank you in advance.</p> <p>Here is my code:</p> <pre><code>if(entity_param_connections_products == &quot;PL&quot;) {       if(pl_flex_l1_label === &quot;&quot;){         document.getElementById(&quot;credit_app-flex_l1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l1-label').innerHTML = pl_flex_l1_label;       }             if(pl_flex_n1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n1-label').innerHTML = pl_flex_n1_label;       }             if(pl_flex_t1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t1-label').innerHTML = pl_flex_t1_label;       }             if(pl_flex_l2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_l2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l2-label').innerHTML = pl_flex_l2_label;       }             if(pl_flex_n2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n2-label').innerHTML = pl_flex_n2_label;       }             if(pl_flex_t2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t2-label').innerHTML = pl_flex_t2_label;       }   }else if(entity_param_connections_products == &quot;CC&quot;){       if(cc_flex_l1_label === &quot;&quot;){         document.getElementById(&quot;credit_app-flex_l1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l1-label').innerHTML = cc_flex_l1_label;       }             if(cc_flex_n1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n1-label').innerHTML = cc_flex_n1_label;       }             if(cc_flex_t1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t1-label').innerHTML = cc_flex_t1_label;       }             if(cc_flex_l2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_l2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l2-label').innerHTML = cc_flex_l2_label;       }             if(cc_flex_n2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n2-label').innerHTML = pl_flex_n2_label;       }             if(cc_flex_t2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t2-label').innerHTML = cc_flex_t2_label;       }   }else if(entity_param_connections_products == &quot;II&quot;){       if(ii_flex_l1_label === &quot;&quot;){         document.getElementById(&quot;credit_app-flex_l1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l1-label').innerHTML = ii_flex_l1_label;       }             if(ii_flex_n1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n1-label').innerHTML = ii_flex_n1_label;       }             if(ii_flex_t1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t1-label').innerHTML = ii_flex_t1_label;       }             if(ii_flex_l2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_l2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l2-label').innerHTML = ii_flex_l2_label;       }             if(ii_flex_n2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n2-label').innerHTML = ii_flex_n2_label;       }             if(ii_flex_t2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t2-label').innerHTML = ii_flex_t2_label;       }   }else if(entity_param_connections_products == &quot;EI&quot;){     if(ei_flex_l1_label === &quot;&quot;){         document.getElementById(&quot;credit_app-flex_l1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l1-label').innerHTML = ei_flex_l1_label;       }             if(ei_flex_n1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n1-label').innerHTML = ei_flex_n1_label;       }             if(ei_flex_t1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t1-label').innerHTML = ei_flex_t1_label;       }             if(ei_flex_l2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_l2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l2-label').innerHTML = ei_flex_l2_label;       }             if(ei_flex_n2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n2-label').innerHTML = ei_flex_n2_label;       }             if(ei_flex_t2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t2-label').innerHTML = ei_flex_t2_label;       }   }else if(entity_param_connections_products == &quot;OV&quot;){       if(ov_flex_l1_label === &quot;&quot;){         document.getElementById(&quot;credit_app-flex_l1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l1-label').innerHTML = ov_flex_l1_label;       }             if(ov_flex_n1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n1-label').innerHTML = ov_flex_n1_label;       }             if(ov_flex_t1_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t1&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t1-label').innerHTML = ov_flex_t1_label;       }             if(ov_flex_l2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_l2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_l2-label').innerHTML = ov_flex_l2_label;       }             if(ov_flex_n2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_n2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_n2-label').innerHTML = ov_flex_n2_label;       }             if(ov_flex_t2_label === &quot;&quot;){           document.getElementById(&quot;credit_app-flex_t2&quot;).style.display = 'none';       } else {           document.getElementById('credit_app-flex_t2-label').innerHTML = ov_flex_t2_label;       }   } </code></pre>
[]
[ { "body": "<p>You can use functions and ternary operator logic here to reduce a lot of line and to make it more clear.</p>\n<p>For example</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(pl_flex_t1_label === &quot;&quot;){\n document.getElementById(&quot;credit_app-flex_t1&quot;).style.display = 'none';\n } else {\n document.getElementById('credit_app-flex_t1-label').innerHTML = pl_flex_t1_label;\n }\n</code></pre>\n<p>can be simplified into</p>\n<pre class=\"lang-js prettyprint-override\"><code>var setStyleDisplayToNon = function(id) {\n document.getElementById(id).style.display = 'none';\n};\n\nvar setInnerHTML = function(id, value) {\n document.getElementById(id).innerHTML = value;\n};\n\npl_flex_t1_label === &quot;&quot; ? setStyleDisplayToNon(&quot;credit_app-flex_t1&quot;) : setInnerHTML(&quot;credit_app-flex_t1-label&quot;, pl_flex_t1_label);\n</code></pre>\n<p>With functions <code>setStyleDisplayToNon</code> and <code>setInnerHTML</code> defined only once, all your code can simply call those functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T20:26:55.660", "Id": "525968", "Score": "2", "body": "This will still leave you with 30 lines of nearly identical code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T15:25:28.033", "Id": "266241", "ParentId": "266240", "Score": "1" } }, { "body": "<p>As already suggested, you can abstract common logic to a function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const updateElement = function(idPrefix, value) {\n if (value === &quot;&quot;) {\n document.getElementById(idPrefix).style.display = &quot;none&quot;;\n } else {\n document.getElementById(idPrefix + &quot;-label&quot;).innerHTML = value;\n }\n}\nupdateElement(&quot;credit_app-flex_t1&quot;, pl_flex_t1_label);\n</code></pre>\n<p>Still, this would lead to duplicated code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(entity_param_connections_products === &quot;PL&quot;) {\n updateElement(&quot;credit_app-flex_t1&quot;, pl_flex_t1_label);\n ...\n} else if(entity_param_connections_products == &quot;CC&quot;) {\n updateElement(&quot;credit_app-flex_t1&quot;, cc_flex_t1_label);\n ...\n}\n...\n</code></pre>\n<p>To remove this duplicated code, you could use an object:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const configs = {\n PL: {\n l1: pl_flex_l1_label,\n n2: pl_flex_n2_label,\n ...\n },\n CC: {\n l1: cc_flex_l1_label,\n ...\n },\n ...\n};\nconst config = configs[entity_param_connections_products];\nfor(const [id, value] of Object.entries(config)) {\n updateElement(&quot;credit_app-flex_&quot; + id, value);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T13:34:19.050", "Id": "525999", "Score": "1", "body": "I would also take a good look at the `XX_flex_YY_label` variables and see if those can be restructured into a `flex_label.XX.YY` structure" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T08:45:29.910", "Id": "526036", "Score": "0", "body": "@Dancrumb that would be a great idea, as that could make the code even simpler (in my suggestion it would remove the `configs` object). And we would avoid the idea of accesing the `window` object with formated variables names (as suggested by @Blindman67)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T16:12:26.700", "Id": "266244", "ParentId": "266240", "Score": "6" } }, { "body": "<h2>D.R.Y.ing code</h2>\n<p>To remove repeated code</p>\n<h2>Common unchanging code</h2>\n<p>Locate the common parts of the repetitive code and build functions that contains the repeated code, we replace the changing part by passing arguments to function with the values that are changing.</p>\n<h2>Unique code</h2>\n<p>Next we locate changing parts of the code. We must build names and get values based on the unique values we pass to the functions created in the step above.</p>\n<p>In your case</p>\n<ul>\n<li><p>Label text has the name eg <code>pl_flex_l1_label</code> that consist of two changing parts that is highlighted with <em>&quot;#&quot;</em> <code>#1_flex_#2_label</code></p>\n<ul>\n<li><p><em>&quot;#1&quot;</em> is the same as the value of <code>entity_param_connections_products</code> forced to lowercase</p>\n</li>\n<li><p><em>&quot;#2&quot;</em> is one of 6 values <code>&quot;l1&quot;</code>, <code>&quot;n1&quot;</code>, <code>&quot;t1&quot;</code>, <code>&quot;l2&quot;</code>, <code>&quot;n2&quot;</code> and, <code>&quot;t2&quot;</code> that are the same for each of the values for <em>&quot;#1&quot;</em>. We can build an array to hold these values.</p>\n<pre><code>const labelTypes = &quot;l1,n1,t1,l2,n2,t2&quot;.split(&quot;,&quot;);\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>There are two elements per label, one is contains that label and the second holds the text. They are identified by id <code>&quot;credit_app-flex_#2&quot;</code> and <code>&quot;credit_app-flex_#2-label&quot;</code>. Again <em>&quot;#2&quot;</em> is one of six values common to all values of <em>&quot;#1&quot;</em></p>\n<p>The next function <code>buildLabel</code> gets a label value from the global object <code>window</code> and the label element id returning it as an array. <code>prod</code> is the value <code>entity_param_connections_products</code> and type is one of the six label types.</p>\n<p>For each label type we call buildLabel and put ir in an array. We do this in the function <code>getProductLabels</code> that returns an array of arrays</p>\n<pre><code>const buildLabel = (prod, type) =&gt; [\n window[[prod.toLowerCase(), &quot;flex&quot;, type, &quot;label&quot;].join(&quot;_&quot;)], \n &quot;credit_app-flex_&quot; + type\n]; \nconst getProductLabels = productCon =&gt; labelTypes.map(type =&gt; buildLabel(productCon, type));\n</code></pre>\n</li>\n<li><p>Now we have an array that contains all the unique values associated with a <code>entity_param_connections_products</code> value. The last thing we do is hide or display the associated label for each of the items in the array create by <code>getProductLabels</code></p>\n<p>The function <code>updateLabel</code> takes an array containing the label value and the label id and hides or displays the label depending on the label value. This is called once per label type.</p>\n<pre><code>const updateLabel = ([label, productId]) =&gt; {\n const el = document.getElementById(productId + (label ? &quot;-label&quot; : &quot;&quot;));\n label ? el.textContent = label : el.style.display = &quot;none&quot;;\n}\n</code></pre>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The only part that changes at the top level is the value of <code>entity_param_connections_products</code> which we can use to start the chain of calls of the functions we defined above.</p>\n<p>We put all the code together in a function that encapsulate all the parts and keeps them safely out of the global scope.</p>\n<pre><code>function updateLabels(productName) {\n const labelTypes = &quot;l1,n1,t1,l2,n2,t2&quot;.split(&quot;,&quot;);\n const buildLabel = (prod, type) =&gt; [\n window[[prod.toLowerCase(), &quot;flex&quot;, type, &quot;label&quot;].join(&quot;_&quot;)], \n &quot;credit_app-flex_&quot; + type\n ];\n const getProductLabels = productCon =&gt; labelTypes.map(type =&gt; buildLabel(productCon, type));\n const updateLabel = ([label, productId]) =&gt; {\n const el = document.getElementById(productId + (label ? &quot;-label&quot; : &quot;&quot;));\n label ? el.textContent = label : el.style.display = &quot;none&quot;;\n }\n getProductLabels(productName).forEach(updateLabel);\n}\n</code></pre>\n<p>With just the above function in place we can now replace all your code with</p>\n<pre><code>updateLabels(entity_param_connections_products);\n</code></pre>\n<h2>DRY V original</h2>\n<p>We have taken 180 lines of repetitive code and put it into 14 lines. If names or ids change and the common parts remain the same it is easy to change a value without needing to change each unique value in the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T17:12:07.937", "Id": "266248", "ParentId": "266240", "Score": "2" } } ]
{ "AcceptedAnswerId": "266244", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T14:12:19.770", "Id": "266240", "Score": "5", "Tags": [ "javascript", "performance", "nested" ], "Title": "Refactor JavaScript nested if-else" }
266240
<p>While working on my demo <a href="https://pchemguy.github.io/ContactEditor/" rel="nofollow noreferrer">database manager app</a>, I have coded a <a href="https://codereview.stackexchange.com/questions/266172/contacteditor-excel-vba-db-app-storage-library">previously presented</a> Storage Library. The structure of the library's code and employed design patterns partially follow that of the <a href="https://rubberduckvba.wordpress.com/2020/04/22/secure-adodb/" rel="nofollow noreferrer">Secure ADODB</a> project, which was a great help. For instance, I liked its approach to parametrized class instantiation involving the factory design pattern and predeclared classes, but I used a slightly modified approach.</p> <p>The relevant part of the <a href="https://github.com/pchemguy/ContactEditor/blob/develop/Project/ContactEditor/Storage/Table/Backend/DataTableADODB.cls" rel="nofollow noreferrer">DataTableADODB</a> class is:</p> <pre class="lang-vb prettyprint-override"><code>'@PredeclaredId Implements IDataTableStorage Private Type TDataTableADODB Model As DataTableModel SQL As SQLlib ADO As ADOlib AdoCommand As ADODB.Command AdoRst As ADODB.Recordset ConnectionString As String TableName As String FieldNames() As String FieldTypes() As ADODB.DataTypeEnum FieldMap As Scripting.Dictionary IDs As Variant TypeCast As FieldFormat End Type Private this As TDataTableADODB Public Function Create(ByVal Model As DataTableModel, _ ByVal ConnectionString As String, _ ByVal TableName As String) As DataTableADODB Dim Instance As DataTableADODB Set Instance = New DataTableADODB Instance.Init Model, ConnectionString, TableName Set Create = Instance End Function Friend Sub Init(ByVal Model As DataTableModel, _ ByVal ConnectionString As String, _ ByVal TableName As String) Guard.NullReference Model Guard.EmptyString ConnectionString Set this.Model = Model Set this.SQL = SQLlib.Create(TableName) Set this.ADO = ADOlib.Create If LCase$(Left$(ConnectionString, 7)) = SQLITE_CONNSTR_PREFIX Then this.ConnectionString = this.ADO.GetSQLiteConnectionString(ConnectionString)(&quot;ADO&quot;) Else this.ConnectionString = ConnectionString End If this.ADO.SetConnectionString this.ConnectionString this.TableName = TableName this.ADO.GetTableMeta this.TableName, this.FieldNames, this.FieldTypes, this.FieldMap End Sub </code></pre> <p>The class implements the <em>IDataTableStorage</em> interface and <a href="https://rubberduckvba.wordpress.com/2018/04/25/private-this-as-tsomething/" rel="nofollow noreferrer">encapsulates</a> a set of private attributes. It defines a conventionally named factory method <em>Create</em> used for <a href="https://rubberduckvba.wordpress.com/2018/04/24/factories-parameterized-object-initialization/" rel="nofollow noreferrer">parameterized object instantiation</a>. Here, <em>Create</em> is defined as a Public Function (it should return the new instance), which only news the class (creates an uninitialized instance) and calls the constructor <em>Init</em> on the new instance. <em>Init</em>, having the same parameter signature as <em>Create</em>, is a Sub responsible for initialization and input validation. <em>Init</em> is only called once (from <em>Create</em>), but it needs to be at least <em>Friend</em> to be accessible from the factory.</p> <p>Another interesting matter is whether the factory should return the default interface (DataTableADODB) or the implemented interface (IDataTableStorage). My understanding is that, in general, there is only a subtle difference. One particular example is when, after creation, a method is called on the implemented interface of the new object, and then it is discarded. If the factory returns the implemented interface, then the calls can be chained. Otherwise, the calling code is responsible for switching the interface and must assign the new object reference to a local variable before such a call.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T16:36:40.023", "Id": "266245", "Score": "1", "Tags": [ "object-oriented", "design-patterns", "vba" ], "Title": "VBA OOP design patterns: factory, constructor, returned interface" }
266245
<p><a href="https://www.spoj.com/problems/UPDATEIT/" rel="nofollow noreferrer">UPDATEIT on SPOJ</a>:</p> <blockquote> <h5>UPDATEIT - Update the array !</h5> <p><a href="https://www.spoj.com/problems/tag/bitmasks" rel="nofollow noreferrer">#bitmasks</a><br /> You have an array containing n elements initially all 0. You need to do a number of update operations on it. In each update you specify l, r and val which are the starting index, ending index and value to be added. After each update, you add the 'val' to all elements from index l to r. After 'u' updates are over, there will be q queries each containing an index for which you have to print the element at that index.</p> <h6>Input:</h6> <p>First line consists of t, the number of test cases. (1 &lt;= t &lt;= 10)</p> <p>Each test case consists of &quot;n u&quot;, number of elements in the array and the number of update operations, in the first line (1 &lt;= n &lt;= 10000 and 1 &lt;= u &lt;= 100000)</p> <p>Then follow u lines each of the format &quot;l r val&quot; (0 &lt;= l,r &lt; n, 0 &lt;= val &lt;=10000)</p> <p>Next line contains q, the number of queries. (1 &lt;= q &lt;= 10000)</p> <p>Next q lines contain an index (0 &lt;= index &lt; n)</p> <h5>Output</h5> <p>For each test case, output the answers to the corresponding queries in separate lines.</p> <h5>Example</h5> <blockquote> <p><strong>Input:</strong><br /> 1<br /> 5 3<br /> 0 1 7<br /> 2 4 6<br /> 1 3 2<br /> 3<br /> 0<br /> 3<br /> 4</p> <p><strong>Output:</strong><br /> 7<br /> 8<br /> 6</p> </blockquote> </blockquote> <p><strong>Code:</strong></p> <pre><code>from sys import stdout,stdin arrSum = [0] * 10001 def update(i,n,val): while(i &lt;= n): arrSum[i]+=val i+=(i&amp;(-i)) def query(i): sum = 0 while(i &gt;0): sum+=arrSum[i] i-= (i &amp; (-i)) return sum def range_update(i,j,n,val): update(i,n,val) update(j+1,n,-val) t = int(stdin.readline()) for _ in range(t): n,u = stdin.readline().split() n = int(n) u = int(u) for _ in range(u): l,r,val = stdin.readline().split() l = int(l) r = int(r) val = int(val) range_update(l+1,r+1,n,val) k = int(stdin.readline()) for _ in range(k): index = int(stdin.readline()) print(query(index+1)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T07:25:22.370", "Id": "525975", "Score": "0", "body": "Welcome to Code Review@SE. One advice I give and try to follow: code the way you think about a problem. One observation about problems on platforms like SPOJ: the time limits are carefully crafted such that suboptimal approaches fail, at least for the biggest test case. (Re-)Try \"dry execution\" of the example, but with n and every index multiplied by 42." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T07:25:58.480", "Id": "525976", "Score": "0", "body": "Is there anything in particular you want reviews to shed a light on?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T07:29:59.643", "Id": "525978", "Score": "1", "body": "How does the implementation presented motivate `using Segment tree` in the title?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T04:48:49.600", "Id": "526026", "Score": "0", "body": "I have used 2 power n approach using bit mask" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T17:08:23.513", "Id": "266247", "Score": "0", "Tags": [ "python", "time-limit-exceeded", "bitwise" ], "Title": "UPDATEIT SPOJ problem using Segment tree" }
266247
<p>I am formatting my TV series archive and can not do one by one. I wrote this code and it's working like what I want. I am a beginner and want to improve my knowledge of algorithm. What can you recommend me? Have a nice day to everyone.</p> <p><strong>Variables</strong></p> <ul> <li>inputStr is contains file name.</li> <li>whichOne is contains which character will be replaced.</li> <li>replaceWith is contains what character will be replaced by.</li> <li>lastPos is how many characters will be stay at last side.</li> </ul> <p><strong>replaceStr</strong> function has two loop. First loop counting how many wanted characters inputStr has. Second one is replacing the characters.</p> <pre><code>#include &lt;iostream&gt; #include &lt;filesystem&gt; std::string replaceStr(std::string inputStr, char whichOne, char replaceWith, int lastPos) { int unitCounter = 0; for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1) if (inputStr[Iterator] == whichOne) unitCounter = unitCounter + 1; for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1) if (inputStr[Iterator] == whichOne &amp;&amp; unitCounter-- != lastPos) inputStr[Iterator] = replaceWith; return inputStr; } int main() { std::filesystem::path Path = &quot;D:\\Libraries\\TV Series\\Snowpiercer\\Season 2&quot;; for (const auto&amp; dirEntry : std::filesystem::recursive_directory_iterator(Path)) { const std::string File{ dirEntry.path().filename().string() }; std::filesystem::rename(Path / File, Path / replaceStr(File, '.', ' ', 1)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T09:32:44.723", "Id": "525983", "Score": "1", "body": "Welcome to Code Review@SE. What does `I [am doing something] and can not do one by one` mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T14:32:56.040", "Id": "526043", "Score": "1", "body": "@greybeard I guess the OP meant that it was impractical for them to manually format the files in their TV series archive one by one, so they wrote a program to automate it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T17:10:01.950", "Id": "526052", "Score": "0", "body": "I am sorry. Yes, @L.F. is right. How can I say this correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T06:22:16.430", "Id": "526074", "Score": "0", "body": "(Options include *There are several thousand records, and editing them interactively is not really feasible*. Did you try an online machine translation service?)" } ]
[ { "body": "<blockquote>\n<p>What can you recommend me?</p>\n</blockquote>\n<p>The code you have is quite good already, but the most important thing you can do to improve it is to make use of standard library algorithms.</p>\n<p>These days, it is considered bad practice to write <code>for</code> loops. It probably blows your mind to hear that, but it’s true. For just a sampling of the guidelines in the C++ core guidelines that explicitly or implicitly imply that, see <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#p1-express-ideas-directly-in-code\" rel=\"nofollow noreferrer\">here</a>, <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#p3-express-intent\" rel=\"nofollow noreferrer\">here</a>, <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#f1-package-meaningful-operations-as-carefully-named-functions\" rel=\"nofollow noreferrer\">here</a>, <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#p13-use-support-libraries-as-appropriate\" rel=\"nofollow noreferrer\">here</a>, <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es1-prefer-the-standard-library-to-other-libraries-and-to-handcrafted-code\" rel=\"nofollow noreferrer\">here</a>, <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es3-dont-repeat-yourself-avoid-redundant-code\" rel=\"nofollow noreferrer\">here</a>… and there are probably many more.</p>\n<p>A loop in the middle of a function is <em>usually</em> a sign that the function is over-engineered, and probably buggy. That’s actually the case for your function, but we’ll get to that.</p>\n<p>You should always try to break loops out into their own functions, because they are <em>almost always</em> algorithms in their own right. Better yet, use an existing function that was written by experts and has already been extensively tested. For example, the algorithms in your standard library.</p>\n<p>Let’s take a look at your function:</p>\n<pre><code>std::string replaceStr(std::string inputStr, char whichOne, char replaceWith, int lastPos)\n{\n int unitCounter = 0;\n \n for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1)\n if (inputStr[Iterator] == whichOne) unitCounter = unitCounter + 1;\n\n for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1) \n if (inputStr[Iterator] == whichOne &amp;&amp; unitCounter-- != lastPos) inputStr[Iterator] = replaceWith;\n\n return inputStr;\n}\n</code></pre>\n<p>This function does two things:</p>\n<ol>\n<li>The first part just counts the occurrences of the character <code>whichOne</code>.</li>\n<li>The second part is more complicated because it is doing several things at once, but basically, it replaces all instances of <code>whichOne</code> except the last <code>lastPos</code> few.</li>\n</ol>\n<p>Let’s focus on part 1 for now. It just counts the occurrences of the character <code>whichOne</code>. That’s just <a href=\"https://en.cppreference.com/w/cpp/algorithm/count\" rel=\"nofollow noreferrer\">the standard library algorithm <code>std::count()</code></a>.</p>\n<p>Which means your function is basically:</p>\n<pre><code>std::string replaceStr(std::string inputStr, char whichOne, char replaceWith, int lastPos)\n{\n auto unitCounter = std::count(inputStr.begin(), inputStr().end(), whichOne);\n\n for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1) \n if (inputStr[Iterator] == whichOne &amp;&amp; unitCounter-- != lastPos) inputStr[Iterator] = replaceWith;\n\n return inputStr;\n}\n</code></pre>\n<p>Just doing that has made your function 3 lines shorter, and already fixed 1 bug. <code>std::count()</code> is <em>at least</em> as fast as your hand-rolled loop, <em>but may be faster</em>.</p>\n<p>(Note that if you’re using C++20, you can also use <code>std::ranges::count(inputStr, whichOne);</code> which is shorter, and safer.)</p>\n<p>That’s all for the overview… now for the actual code review.</p>\n<h1>Code review</h1>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;filesystem&gt;\n</code></pre>\n<p>I see <code>std::string</code> in the code, but I don’t see <code>#include &lt;string&gt;</code> here. Your code “works” because one or both of <code>&lt;iostream&gt;</code> and <code>&lt;filesystem&gt;</code> happen to transitively include <code>&lt;string&gt;</code>… but you shouldn’t rely on this. Include the headers for everything you actually use.</p>\n<pre><code>std::string replaceStr(std::string inputStr, char whichOne, char replaceWith, int lastPos)\n</code></pre>\n<p><code>lastPos</code> isn’t a great name for the last parameter, because it isn’t a <em>position</em>. It’s the number of trailing instances of <code>whichOne</code> to leave unchanged.</p>\n<pre><code> for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1)\n if (inputStr[Iterator] == whichOne) unitCounter = unitCounter + 1;\n</code></pre>\n<p>There are a number of problems with this loop.</p>\n<p>First the stylistic issues:</p>\n<ol>\n<li><p><code>Iterator</code> is not a great name for a loop variable. <code>Iterator</code> is far more likely to be a type name in a template function than a variable name. This particular loop variable isn’t actually an iterator in any case, it’s an index.</p>\n</li>\n<li><p>I don’t see a problem with eliding the braces if your loop is a single, simple statement (though other people have religious objections to it). The problem here is that your loop is <em>not</em> a single, simple statement… it’s an <code>if</code> block. It only looks like a single, simple statement because you’ve packed it all into one line. Which brings us to the next point….</p>\n</li>\n<li><p>Don’t pack multiple things onto a single line. It makes your code harder to read, and much easier to hide bugs.</p>\n</li>\n<li><p>Don’t do <code>x = x + 1</code> when <code>++x</code> will do (and yes, <code>++x</code> is <em>always</em> better than <code>x++</code> unless you actually need the latter). Doing it the long way is not only longer—thus making your code noisier and harder to read—it raises red flags for experienced C++ coders, because they will want to do know why you’re doing it the hard way. Doing things that will confuse experienced C++ coders is a great way to hide bugs in your code.</p>\n</li>\n</ol>\n<p>The big issue here, though, is the bug.</p>\n<p><code>Iterator</code> is an <code>int</code>… but <code>inputStr.length()</code> is <em>not</em> an <code>int</code>. It is not only unsigned, it may also be significantly larger than an <code>int</code> (and I believe that is the case on Windows). So when you do <code>Iterator &lt; inputStr.length()</code>, you are comparing mismatched types. If you were compiling with warnings turned on… <strong>and you should always compile with all warnings turned on</strong>… you would have seen warnings about this.</p>\n<p>If you want to do this correctly, you need to get the right type for <code>Iterator</code>. For that, you need to do <code>decltype(inputStr.length())</code>:</p>\n<pre><code> for (decltype(inputStr.length()) index = 0; index &lt; inputStr.length(); ++index)\n {\n if (inputStr[index] == whichOne)\n ++unitCounter;\n }\n</code></pre>\n<p>But this is still terrible in modern of C++. The first step to improvement would be to use a range-<code>for</code>:</p>\n<pre><code> for (auto&amp;&amp; c : inputStr)\n {\n if (c == whichOne)\n ++unitCounter;\n }\n</code></pre>\n<p>But, as mentioned above, much better is to use an actual algorithm. In this case <code>std::count()</code>.</p>\n<pre><code> for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1) \n if (inputStr[Iterator] == whichOne &amp;&amp; unitCounter-- != lastPos) inputStr[Iterator] = replaceWith;\n</code></pre>\n<p>This has all the same problems as the previous loop, so I won’t repeat them. I will point out that this is actually a <code>std::replace_if()</code> algorithm:</p>\n<pre><code> std::replace_if(inputStr.begin(), inputStr.end(),\n [&amp;unitCounter, whichOne, lastPos] (auto c)\n { return c == whichOne and unitCounter-- != lastPos; },\n replaceWith).\n</code></pre>\n<p>But it’s a bad idea to keep decrementing even after you’ve reached the limit, because it could <em>theoretically</em> wrap around.</p>\n<p>Now, onto <code>main()</code>.</p>\n<pre><code> std::filesystem::path Path = &quot;D:\\\\Libraries\\\\TV Series\\\\Snowpiercer\\\\Season 2&quot;;\n</code></pre>\n<p>This could be <code>const</code>.</p>\n<p>You should also consider alternative ways of writing Windows paths, because using <code>\\\\</code> everywhere is ugly and error-prone.</p>\n<p><code>std::filesystem::path</code> works with forward slashes, so you could write <code>&quot;D:/Libraries/TV Series/Snowpiercer/Season 2&quot;</code>.</p>\n<p>You could also use raw strings: <code>R&quot;(D:\\Libraries\\TV Series\\Snowpiercer\\Season 2)&quot;</code>.</p>\n<pre><code> for (const auto&amp; dirEntry : std::filesystem::recursive_directory_iterator(Path))\n {\n const std::string File{ dirEntry.path().filename().string() };\n\n std::filesystem::rename(Path / File, Path / replaceStr(File, '.', ' ', 1));\n }\n</code></pre>\n<p>Are you… <em>sure</em> you’ve really thought this through? Are you sure you don’t mean to use a <em>non</em>-recursive directory iterator? Or maybe you’re just handling the path incorrectly.</p>\n<p>Consider what you’re doing here. Suppose you are currently at the directory entry for <code>D:/Libraries/TV Series/Snowpiercer/Season 2/subdir/file.name.ext</code>. That means <code>File</code> will be <code>file.name.ext</code>. So the rename function is renaming:</p>\n<ul>\n<li>From: <code>D:/Libraries/TV Series/Snowpiercer/Season 2</code> / <code>file.name.ext</code></li>\n<li>To: <code>D:/Libraries/TV Series/Snowpiercer/Season 2</code> / <code>file name.ext</code></li>\n</ul>\n<p>But… what happened to <code>subdir</code>?</p>\n<p>There’s another issue here, and that is that you are modifying the directory tree while traversing it at the same time.</p>\n<p>What you really want to do is just iterate through the filesystem, collecting the paths that need to be changed, and <em>then</em> go through and change them all. Something more like:</p>\n<pre><code>// Note: Untested, and not as efficient as it could be. Should also be\n// rewritten with proper algorithms. This is just to illustrate the idea.\n\nauto files_to_rename = std::vector&lt;std::tuple&lt;std::filesystem::path, std::filesystem::path&gt;&gt;{};\n\nfor (auto&amp;&amp; d : std::filesystem::recursive_directory_iterator(Path))\n{\n auto const old_filename = d.path().filename().string();\n auto const new_filename = replaceStr(old_filename, '.', ' ', 1);\n\n if (old_filename != new_filename)\n {\n auto old_path = d.path();\n\n auto new_path = d.path();\n new_path.replace_filename(new_filename);\n \n files_to_rename.emplace_back(std::move(old_path), std::move(new_path));\n }\n}\n\nfor (auto&amp;&amp; [old_path, new_path] : files_to_rename)\n std::filesystem::rename(old_path, new_path);\n</code></pre>\n<h1>Algorithmic improvements</h1>\n<p>Let’s look at your algorithm again:</p>\n<pre><code>std::string replaceStr(std::string inputStr, char whichOne, char replaceWith, int lastPos)\n{\n int unitCounter = 0;\n \n for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1)\n if (inputStr[Iterator] == whichOne) unitCounter = unitCounter + 1;\n\n for (int Iterator = 0; Iterator &lt; inputStr.length(); Iterator = Iterator + 1) \n if (inputStr[Iterator] == whichOne &amp;&amp; unitCounter-- != lastPos) inputStr[Iterator] = replaceWith;\n\n return inputStr;\n}\n</code></pre>\n<p>Your algorithm makes two passes over the string: one to count, and one to replace.</p>\n<p>Can it be done in one?</p>\n<p>Yes. Yes it can.</p>\n<p>The trick is to step back and look at the problem in a different way. Instead of moving <em>forwards</em> through the string… let’s move <em>backwards</em>.</p>\n<p>If we start at the <em>beginning</em> of the string, the algorithm is pretty complicated, because we want to replace every <code>whichOne</code> character except the last <code>lastPos</code>. In order to do that, we first have to know how many <code>whichOne</code> characters there are, so we know when to stop.</p>\n<p>But if we start at the <em>end</em> of the string, the situation is completely different. What we want do now is <em>skip</em> <code>lastPos</code> occurrences of <code>whichOne</code>… and only <em>then</em> start replacing. This is much easier to do:</p>\n<pre><code>// Note: Untested, buggy, and ugly. Just for illustration.\n\nstd::string replaceStr(std::string s, char c_old, char c_new, int n)\n{\n // start at the end\n auto p = s.data() + s.size();\n\n // skip the last n occurences\n for (; p != s.data() and n &gt;= 0; --p)\n {\n if (*p == c_old)\n --n;\n }\n\n // now one of two things is true:\n // * either p is at the beginning of the string (so we're done)\n // * or p is pointing to the first character we need to replace\n\n // do the replacing\n for (; p != s.data(); --p)\n {\n if (*p == c_old)\n *p = c_new;\n }\n\n return s;\n}\n</code></pre>\n<p>But all of the above would be much better written as an algorithm.</p>\n<pre><code>// Note: Untested.\n\nstd::string replaceStr(std::string s, char c_old, char c_new, int n)\n{\n std::replace_if(\n // Using rbegin and rend moves us *BACKWARDS* through the string\n s.rbegin(), s.rend(),\n // Only replace if this lambda returns true.\n [c_old, &amp;n](auto c) {\n if (c == c_old)\n {\n // Should we skip this occurrence?\n if (n &gt; 0)\n {\n // Yes, so decrement the counter and return false.\n --n;\n return false;\n }\n\n return true;\n }\n },\n c_new);\n\n return s;\n}\n</code></pre>\n<p>That’s one pass through the string, only doing replacements if:</p>\n<ol>\n<li>the original character is the one you wan to replace; and</li>\n<li>you have skipped <code>n</code> instances of the original character already.</li>\n</ol>\n<h1>One more important thing: Test your code</h1>\n<p>This is <strong>the most important thing</strong> you can do as a programmer, in any language. Untested code is garbage code; I will not only refuse to use it in any project I am doing, I won’t even bother to <em>look</em> at it.</p>\n<p>Testing your code properly is an art and a science. The first thing you want to do is use a proper testing library. My favourite is <a href=\"https://www.boost.org/doc/libs/1_77_0/libs/test/doc/html/index.html\" rel=\"nofollow noreferrer\">Boost.Test</a>, but while that is <em>super</em> powerful, it is also <em>super</em> complicated to use. A lot of people like GoogleTest but… meh. You could also check out <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2</a>.</p>\n<p>Once you have a testing library ready, you should <strong>write the tests before the code</strong>. There are a number of reasons to do this, not least being that it forces you to write proper, testable interfaces. If you try to write the code first, you can often end up with untestable code… and that’s <em>bad</em>.</p>\n<p>So, using Catch2, for your function, you might write:</p>\n<pre><code>TEST_CASE(&quot;empty string works&quot;)\n{\n REQUIRE(replaceStr(&quot;&quot;, '.', ' ', 0) == &quot;&quot;);\n}\n\nTEST_CASE(&quot;simple substitution works&quot;)\n{\n auto const data = GENERATE(table&lt;std::string, char, char, std::string&gt;({\n // original string, old char, new char, result\n {&quot;a.b.c&quot;, '.', ' ', &quot;a b c&quot;},\n {&quot;1?2?&quot;, '?', 'x', &quot;1x2x&quot;},\n {&quot;*&quot;, '*', '+', &quot;+&quot;},\n {&quot;**&quot;, '*', '+', &quot;++&quot;},\n // and so on, with any other cases you think may be problematic\n }));\n\n REQUIRE(replaceStr(std::get&lt;0&gt;(data), std::get&lt;1&gt;(data), std::get&lt;2&gt;(data), 0)\n == std::get&lt;3&gt;(data));\n}\n\nTEST_CASE(&quot;no substitution happens if old char is not in string&quot;)\n{\n auto const data = GENERATE(table&lt;std::string, char, char&gt;({\n // original string, old char, new char\n {&quot;a.b.c&quot;, ' ', '.'},\n {&quot;1?2?&quot;, 'x', '?'},\n {&quot;&quot;, '*', '_'},\n // and so on...\n }));\n\n REQUIRE(replaceStr(std::get&lt;0&gt;(data), std::get&lt;1&gt;(data), std::get&lt;2&gt;(data), 0)\n == std::get&lt;0&gt;(data));\n}\n\n// also more tests to take lastPos into account...\n</code></pre>\n<p>Once you have these tests, <em>then</em> you write the function… and keep working on it until all the tests pass.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T12:55:09.387", "Id": "525997", "Score": "0", "body": "Wonderful, wonderful, wonderful. Thank you so much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T13:04:12.407", "Id": "525998", "Score": "0", "body": "I don't know what to say." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T23:06:12.730", "Id": "266255", "ParentId": "266249", "Score": "2" } } ]
{ "AcceptedAnswerId": "266255", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T17:14:08.123", "Id": "266249", "Score": "1", "Tags": [ "c++", "strings", "file-system" ], "Title": "Replacing a char in the file name" }
266249
<p>I have written a python script that generates random rows with a provided array. To better explain</p> <pre><code>input : [1,2,3,4,5] output : [1,2,3,4,5] [5,3,4,2,1] [1,2,4,5,3] [1,2,5,3,4] [5,4,3,2,1] [4,3,2,1,5] </code></pre> <p>I am sharing the function which generates the unique random placement of item in array for now</p> <pre><code>def myscore(self): # setting the values which I want in my output array score_array = array.array('i',[0,1,2,3,4]) score_index_len = len(score_array) score_string = '' loopidx=0 while loopidx &lt; score_index_len: #generate random index between number of array item i=randint(0,len(score_array)-1) score_string = score_string + ',' + str(score_array[i]) #remove the index del score_array[i] loopidx = loopidx + 1 return score_string[1:] </code></pre> <p>Please share your code review comments.</p>
[]
[ { "body": "<h2>Performance</h2>\n<p>Since <a href=\"https://stackoverflow.com/q/38722105/9997212\">f-strings are faster than string concatenation</a>, you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array.pop(i))\n</code></pre>\n<p>with</p>\n<pre><code>score_string = score_string + f',{score_array.pop(i)}'\n</code></pre>\n<hr />\n<p>Since <a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"nofollow noreferrer\"><code>pop</code></a> removes an element from a list given an index and returns it, you can simplify</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array[i])\ndel score_array[i]\n</code></pre>\n<p>to</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array.pop(i))\n</code></pre>\n<h2>Best practices</h2>\n<p>Since <a href=\"https://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\"><code>range</code></a> creates a iterable once in the iteration, you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>loopidx = 0\nscore_index_len = len(score_array)\n\nwhile loopidx &lt; score_index_len:\n ...\n\n loopidx = loopidx + 1 \n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>for loopidx in range(len(score_array)):\n ...\n</code></pre>\n<hr />\n<p>Since <a href=\"https://docs.python.org/3/library/random.html#random.randint\" rel=\"nofollow noreferrer\"><code>randint</code></a> is an alias for <code>randrange(a, b+1)</code>, you can simplify</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = randint(0, len(score_array)-1)\n</code></pre>\n<p>to</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = randrange(len(score_array))\n</code></pre>\n<hr />\n<p>Just for readability, you could replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + f',{score_array.pop(i)}'\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string += f',{score_array.pop(i)}'\n</code></pre>\n<hr />\n<p>To avoid using <code>[1:]</code> when returning, you could create a new list and use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>scores = []\nfor loopidx in range(len(score_array)):\n i = randrange(len(score_array))\n scores.append(f'{score_array.pop(i)}')\n \nreturn ','.join(scores)\n</code></pre>\n<h3>Refactored code:</h3>\n<pre class=\"lang-py prettyprint-override\"><code>def myscore():\n score_array = array.array('i',[0,1,2,3,4])\n \n scores = []\n for loopidx in range(len(score_array)):\n i = randrange(len(score_array))\n scores.append(f'{score_array.pop(i)}')\n\n return ','.join(scores)\n</code></pre>\n<h2>Alternative</h2>\n<p>A simpler alternative is just use <a href=\"https://docs.python.org/3/library/random.html#random.shuffle\" rel=\"nofollow noreferrer\"><code>shuffle</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def myscore():\n score_array = array.array('i',[0,1,2,3,4])\n shuffle(score_array)\n return ','.join(map(str, score_array))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T17:39:56.897", "Id": "526053", "Score": "0", "body": "I would argue that if you need the index out of each iteration you should use enumerate as its more idiomatic:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T03:30:13.717", "Id": "266257", "ParentId": "266250", "Score": "3" } } ]
{ "AcceptedAnswerId": "266257", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T17:41:40.307", "Id": "266250", "Score": "1", "Tags": [ "python-3.x" ], "Title": "create script to convert array to string with array elements uniquely with randomness" }
266250
<p>I recently wrote code to parse lambda expressions written in a lisp like format, using a small hand-rolled parsing library.</p> <h2>The goal</h2> <p>This code was written as a part of <a href="https://codegolf.stackexchange.com/questions/233453/parse-a-lambda-for-correctness">this code-golf challenge</a> not as code-golf, but as a demo for the concept. My goals for this were</p> <ul> <li>It should be simple enough that by looking over it one should be able to understand what is being parsed.</li> <li>It should be self-contained so that if someone wants to dig into the nitty-gritty and understand how it works they can.</li> </ul> <p>I chose Haskell for this because:</p> <ul> <li>In my experience imperative parsers are more difficult to understand than combinator parsers.</li> <li>In my experience combinator parsing has a smaller footprint since it can assemble complex parsers from simple components.</li> <li>In my experience it is a joy to write and read parsers in Haskell.</li> </ul> <p>The code then consists of a minimalist &quot;library&quot; of simple helper functions, and the definition of the actual parser. If it is important, you should be able to see exactly how it is presented via the link above.</p> <p>I'd like to get an idea of how well I achieved these goals and what steps could be taken to better present the idea through code.</p> <h2>Expressions</h2> <p>The goal is to verify that a string is a properly formatted lambda expression, consisting of</p> <ul> <li><code>abs</code> (abstraction) to introduce a new variable.</li> <li><code>var</code> (variable) to use a variable.</li> <li><code>app</code> (application) to apply one lambda to another.</li> </ul> <p>formatted as a lisp list.</p> <p>For example</p> <pre class="lang-lisp prettyprint-override"><code>(abs x (app (var x) (var x))) </code></pre> <p>Is a valid expression representing <span class="math-container">\$\lambda x. x x\$</span>.</p> <p>Additionally we want to verify the expression doesn't use undeclared variables and doesn't shadow any variables.</p> <p>So</p> <pre class="lang-lisp prettyprint-override"><code>(abs y (var x)) </code></pre> <p>is not valid because <code>x</code> is not declared. And</p> <pre class="lang-lisp prettyprint-override"><code>(abs y (abs y (abs x (var x)))) </code></pre> <p>is not valid because <code>y</code> is shadowed.</p> <p>A precise grammar for the valid expressions is given</p> <p><span class="math-container">\$ S\left(C\right) := \left\{ \begin{array}[rr] \ \color{green}{\texttt{(var }}x\color{green}{\texttt{)}} &amp; \textrm{ where } x\in C \\ \color{green}{\texttt{(abs }} x\texttt{ }S(C\cup\{x\})\color{green}{\texttt{)}} &amp; \textrm{ where } x\notin C\\ \color{green}{\texttt{(app }} S(C)\texttt{ }S(C)\color{green}{\texttt{)}} &amp; \end{array} \right. \$</span></p> <p>Where valid expressions are strings spanned by this grammar starting from <span class="math-container">\$S(\{\})\$</span>.</p> <p>There are two extra things to note:</p> <ul> <li>The whitespace is intentionally inflexible in this specification.</li> <li>Our Parse is not producing a parse tree, only confirming whether an expression meets the specifications.</li> </ul> <h2>Library</h2> <pre class="lang-hs prettyprint-override"><code>import Control.Applicative ( liftA2 , Alternative (..) ) import Control.Monad ( guard ) newtype Parser a = Parser (String -&gt; [(String, a)]) apply :: Parser a -&gt; String -&gt; [(String, a)] apply (Parser p) s = p s instance Functor Parser where fmap func (Parser p) = Parser $ fmap (map (fmap func)) p instance Applicative Parser where pure x = Parser ( \ string -&gt; [(string, x)] ) liftA2 f (Parser p1) (Parser p2) = Parser ( \ string -&gt; do (rem1, res1) &lt;- p1 string (rem2, res2) &lt;- p2 rem1 return (rem2, f res1 res2) ) instance Monad Parser where Parser p &gt;&gt;= f = Parser ( \ string -&gt; do (rem1, res1) &lt;- p string apply (f res1) rem1 ) instance Alternative Parser where empty = Parser ( \ _ -&gt; [] ) Parser p1 &lt;|&gt; Parser p2 = Parser $ ( \ string -&gt; p1 string ++ p2 string ) charBy :: (Char -&gt; Bool) -&gt; Parser Char charBy predicate = Parser go where go (a : b) = [ (b, a) | predicate a ] go [] = [] char :: Char -&gt; Parser Char char x = charBy (x==) string :: String -&gt; Parser String string = traverse char choice :: [Parser a] -&gt; Parser a choice = foldr (&lt;|&gt;) empty </code></pre> <h2>Parser</h2> <pre class="lang-hs prettyprint-override"><code>lambda :: [String] -&gt; Parser () lambda variables = do char '(' choice [ do string &quot;abs &quot; name &lt;- some $ charBy (`elem` ['a'..'z']) guard $ notElem name variables char ' ' lambda (name : variables) , do string &quot;var &quot; choice (map string variables) return () , do string &quot;app &quot; lambda variables char ' ' lambda variables ] char ')' return () </code></pre> <h2>Description</h2> <p>This uses monadic parsing to get the job done. I build a parser type implement the necessary type classes and a couple of helper functions. The actual parser follows the same structure as the given grammar.</p> <p>The code does a single pass without any tokenizer. This might be a little odd, but because the domain I think that such would make the code more complex, and we have very rigid white-space rules.</p> <h2>Review</h2> <p>I welcome all feedback on how to make this code more presentable. However the specific questions I would like to prompt are:</p> <ul> <li>Is <code>do</code> notation a good choice given my goals?</li> <li>Was it a good choice to use a single pass method? Might it be more presentable to parse into a tree and then verify certain properties of the tree?</li> <li>Are there any subtle Haskell-isms that I have that could easily be removed to make the more approachable to a general audience?</li> </ul> <p>of course keeping my initial goals in mind.</p>
[]
[ { "body": "<p>Sorry I'm so late to this!</p>\n<blockquote>\n<ul>\n<li>Is <code>do</code> notation a good choice given my goals?</li>\n</ul>\n</blockquote>\n<p>Sure. Anyone who knows monads will understand <code>do</code>. On the other hand, don't assume everyone knows monadic <em>parsers</em>. A simple <a href=\"https://www.cs.tufts.edu/comp/150FP/archive/graham-hutton/monadic-parsing-jfp.pdf\" rel=\"nofollow noreferrer\">link</a> as a comment can go a long way. (Or you could actually comment your code, but that's more work!)</p>\n<blockquote>\n<ul>\n<li>Was it a good choice to use a single pass method? Might it be more presentable to parse into a tree and then verify certain properties of the tree?</li>\n</ul>\n</blockquote>\n<p>It's ok. Building an explicit tree would be more normal, because it's prerequisite to doing <em>anything</em> else besides just checking validity.</p>\n<blockquote>\n<ul>\n<li>Are there any subtle Haskell-isms that I have that could easily be removed to make the more approachable to a general audience?</li>\n</ul>\n</blockquote>\n<p>That's hard to say; I'm probably too familiar with Haskell to count as a general audience.</p>\n<ul>\n<li>Add a few comments.</li>\n<li><em>Maybe</em> get rid of <code>instance Alternative Parser</code>. (Not that it isn't pulling its weight, it's just a thing you could maybe do without?)</li>\n<li>Certainly figure out some other way of writing <code>[ (b, a) | predicate a ]</code>. Probably anyone can <em>guess</em> what it does, but a couple minutes of googling didn't find anything saying it's valid syntax; I had to try it in GHCI to make sure.</li>\n</ul>\n<h3>Other stuff:</h3>\n<ul>\n<li>Are <code>rem</code> and <code>res</code> supposed to be &quot;remainder&quot; and &quot;resolution&quot;? Longer variable names are sometimes easier for new readers.</li>\n<li>On the flip side, in the <code>&gt;&gt;=</code> definition (and elsewhere), <code>string</code> could probably just be <code>s</code>; the advantage being that it doesn't share a name with the function <code>string</code> in the same module.</li>\n<li>Your definition of <code>fmap</code> is really hard to read. Using <code>map</code> to specify which level applies to the <code>[]</code> is ok; why not use <code>.</code> for the function layer? The functor instance of <code>(,)</code> never feels great. If you want to keep it concise, consider importing <a href=\"https://hackage.haskell.org/package/base-4.8.2.0/docs/Data-Bifunctor.html\" rel=\"nofollow noreferrer\">Bifunctor</a> so you can write<br />\n<code>fmap f (Parser p) = Parser $ (map (second f)) . p</code>.<br />\nIf you want it to be easy for a stranger to read it'll probably need to be much more verbose.</li>\n<li>The use of <code>do</code> in <code>liftA2</code> is in the <code>[]</code> monad; note that with a comment.</li>\n<li><code>empty = Parser (const [])</code></li>\n<li>Don't name your parser <code>lambda</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T03:37:59.287", "Id": "268273", "ParentId": "266252", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T18:16:11.283", "Id": "266252", "Score": "4", "Tags": [ "parsing", "haskell", "functional-programming" ], "Title": "Small combinator parsing library in Haskell" }
266252
<p>I want to see if I can find a way to have the system work the same way when it runs, but condense it, as if I don't I will be constantly writing a lot of code that I believe I could just write in a more simple and condensed way.</p> <p>Is there a way to simplify and condense this code?</p> <pre><code>import random aList = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;] bList = random.choice(aList) print(bList) if bList == &quot;1&quot;: # prints 1 aList.pop(0) cList1 = random.choice(aList) print(&quot;This thing happened again&quot;) print(cList1) if cList1 == &quot;2&quot;: # prints 2 in 1 aList.pop(0) dList1 = random.choice(aList) print(&quot;This happened.&quot;) print(dList1) if cList1 == &quot;3&quot;: # prints 3 in 1 aList.pop(1) dList2 = random.choice(aList) print(&quot;That happened.&quot;) print(dList2) else: pass if bList == &quot;2&quot;: aList.pop(1) cList2 = random.choice(aList) print(&quot;Text&quot;) print(cList2) if cList2 == &quot;1&quot;: # prints 1 in 2 aList.pop(0) dList3 = random.choice(aList) print(&quot;Random text&quot;) print(dList3) if cList2 == &quot;3&quot;: # prints 3 in 2 aList.pop(1) dList4 = random.choice(aList) print(&quot;More Random Text&quot;) print(dList4) else: pass if bList == &quot;3&quot;: aList.pop(2) cList3 = random.choice(aList) print(&quot;Here is a random text line&quot;) print(cList3) if cList3 == &quot;1&quot;: # prints 1 in 3 aList.pop(0) dList5 = random.choice(aList) print(&quot;Here is another random text line&quot;) print(dList5) if cList3 == &quot;2&quot;: # prints 2 in 3 aList.pop(1) dList6 = random.choice(aList) print(&quot;Once again, This&quot;) print(dList6) else: pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T20:19:34.850", "Id": "525967", "Score": "5", "body": "Welcome to CodeReview. Your title is a little too broad and applicable to everything on this site. The standard is to have the title describe what your code is trying to do. For that matter, what is your code trying to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T09:07:26.147", "Id": "525981", "Score": "2", "body": "(`I want to see if I can [write concise code]`) does that mean you want hints rather than be spoon-fed examples?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T17:45:55.763", "Id": "526014", "Score": "1", "body": "The code seems to be contrived and full of placeholders. So it seems hypothetical to me. As usual, \"what are you actually doing? because this definitely isn't it.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T05:47:47.213", "Id": "526029", "Score": "0", "body": "(If this *did* occur in a \"real\" project, but the code is not written yet (it does *not* need to be *finished*): Where you \"see\" something untoward, hide it with a suitable abstraction. When it \"works\" and you still have issues with the way it is coded you are welcome to present [actual code from a project](https://codereview.stackexchange.com/help/on-topic).)" } ]
[ { "body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://pep8.org/\" rel=\"noreferrer\">Style Guide for Python Code</a> enumerates a number of rules you should follow.</p>\n<p>Of particular note: variables should be in <code>snake_case</code>, not <code>mixedCase</code>. Therefore, <code>aList</code> should be <code>a_list</code>.</p>\n<h1>Misleading names</h1>\n<p>None of <code>bList</code>, <code>cList1</code>, <code>cList2</code>, <code>cList3</code>, <code>dList1</code>, <code>dList2</code>, <code>dList3</code>, <code>dList4</code>, <code>dList5</code>, <code>dList6</code> are actually lists. They should not be named as if they were as list.</p>\n<h1>If-chain</h1>\n<pre class=\"lang-py prettyprint-override\"><code>if bList == &quot;1&quot;:\n ...\nelse:\n pass\nif bList == &quot;2&quot;:\n ...\nelse:\n pass\nif bList == &quot;2&quot;:\n ...\nelse:\n pass\n</code></pre>\n<p>implies that it is possible for <code>bList</code> to change value so it can match one of the later choices. It does not change values, so the choices are exclusive.</p>\n<p><code>else: pass</code> is unnecessary. If nothing is executed in the else clause, omit it.</p>\n<p>Thus, this could be improved as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if bList == &quot;1&quot;:\n ...\nelif bList == &quot;2&quot;:\n ...\nelif bList == &quot;2&quot;:\n ...\n</code></pre>\n<h1>Select and remove element</h1>\n<p>The <code>.pop()</code> function returns the element it removes. It looks like you want to remove a random element. So, that is what you should actually code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>bList = aList.pop(random.randrange(len(aList)))\n</code></pre>\n<p>The <code>len(aList)</code> determines the length of <code>aList</code>, which is 3. <code>random.randrange(3)</code> generates a random integer in the range <code>0 &lt;= x &lt; 3</code> ... as in 0, 1 or 2. <code>aList.pop(x)</code> removes that randomly selected element from the <code>aList</code> and returns it.</p>\n<p>This eliminates the need for</p>\n<pre class=\"lang-py prettyprint-override\"><code>if bList == &quot;1&quot;:\n aList.pop(0)\n...\nif bList == &quot;2&quot;:\n aList.pop(1)\n...\nif bList == &quot;3&quot;:\n aList.pop(2)\n...\n</code></pre>\n<p>because the element is retrieve and popped in the same operation.</p>\n<h1>Updated code</h1>\n<p>Applying the above changes, we get:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\na_list = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]\n\nb = a_list.pop(random.randrange(len(a_list)))\nc = a_list.pop(random.randrange(len(a_list)))\nd = a_list.pop(random.randrange(len(a_list)))\nprint(b)\nif b == &quot;1&quot;:\n print(&quot;This thing happened again&quot;)\n print(c)\n if c == &quot;2&quot;:\n print(&quot;This happened.&quot;)\n elif c == &quot;3&quot;:\n print(&quot;That happened.&quot;)\nelif b == &quot;2&quot;:\n print(&quot;Text&quot;)\n print(c)\n if c == &quot;1&quot;:\n print(&quot;Random text&quot;)\n elif c == &quot;3&quot;:\n print(&quot;More Random Text&quot;)\nelif b == &quot;3&quot;:\n print(&quot;Here is a random text line&quot;)\n print(c)\n if c == &quot;1&quot;:\n print(&quot;Here is another random text line&quot;)\n elif c == &quot;2&quot;:\n print(&quot;Once again, This&quot;)\nprint(d)\n</code></pre>\n<p>... which is a little simpler, but is still quite verbose.</p>\n<h1>Further Condensed</h1>\n<p>The structure of the code is take 3 samples without replacement, print out the first value, a message depending on the first value, the second value, a message depending on the first two values, and then the third value. We can code exactly that:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\nmessages = {&quot;1&quot;: &quot;This thing happened again&quot;,\n (&quot;1&quot;, &quot;2&quot;): &quot;This happened.&quot;,\n (&quot;1&quot;, &quot;3&quot;): &quot;That happened.&quot;,\n &quot;2&quot;: &quot;Text&quot;,\n (&quot;2&quot;, &quot;1&quot;): &quot;Random text&quot;,\n (&quot;2&quot;, &quot;3&quot;): &quot;More Random Text&quot;,\n &quot;3&quot;: &quot;Here is a random text line&quot;,\n (&quot;3&quot;, &quot;1&quot;): &quot;Here is another random text line&quot;,\n (&quot;3&quot;, &quot;2&quot;): &quot;Once again, This&quot;}\n \na_list = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]\nb, c, d = random.sample(a_list, 3)\nprint(b, messages[b], c, messages[b, c], d, sep=&quot;\\n&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T22:41:24.967", "Id": "266254", "ParentId": "266253", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T19:53:33.000", "Id": "266253", "Score": "1", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Select 3 items from list, print different messages based on selection order" }
266253
<p>I finally got this lexer working. How can the <code>parse</code> function be simplified? The goal is to take a tree of indentation-based text, and convert it into parentheses-based opening/closing text, for easier parsing down the road. But the logic is pretty messy and I'm not sure how to make it elegant.</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>let patterns = [ [/^[a-z]+/, 'id', true], [/^\(/, 'open'], [/^ /, 'open', null, true], [/^\)/, 'close'], ] // format(` // foo bar // `) // format(` // foo bar baz // `) // format(` // foo bar // me a // me b // they c // `) format(` foo bar baz hello world and again then again oh again me again and me then me `) function parse(str) { const tokens = [] tokens.push({ type: 'id', text: 'start' }) tokens.push({ type: 'open' }) let indents = [0] let nesting = 0 let matched = false while (str.length) { if (str[0] == '\n') { str = str.substr(1) while (true) { let match = str.match(/^ *\n/) if (match) { str = str.substr(match[0].length) } else { break } } if (!str) { while (nesting &gt; 1) { tokens.push({ type: 'close' }) nesting-- } while (indents.length) { tokens.push({ type: 'close' }) indents.pop() } break } if (!matched) { continue } let match = str.match(/^ +/) let newIndent = match ? match[0].length : 0 if (match) str = str.substr(match[0].length) if (newIndent % 2 != 0) throw new Error('Indentation error') let oldIndent = indents[indents.length - 1] if (newIndent === oldIndent) { while (nesting) { tokens.push({ type: 'close' }) nesting-- } // foo bar // foo bar // foo bar tokens.push({ type: 'comma' }) } else if (newIndent &gt; oldIndent) { while (nesting &gt; 1) { tokens.push({ type: 'close' }) nesting-- } if (newIndent - oldIndent != 2) throw new Error('Indentation error') // foo bar // foo bar baz // foo bar tokens.push({ type: 'comma' }) indents.push(newIndent) nesting = 0 } else { if (Math.abs(newIndent - oldIndent) % 2 != 0) throw new Error('Indentation error') while (nesting) { tokens.push({ type: 'close' }) nesting-- } let diff = (oldIndent - newIndent) / 2 while (diff) { tokens.push({ type: 'close' }) diff-- indents.pop() } tokens.push({ type: 'comma' }) } } else { x: for (let pattern of patterns) { let match = str.match(pattern[0]) if (match) { matched = true let text = match[0] let attrs = { type: pattern[1] } if (pattern[3]) { nesting++ } if (pattern[2]) attrs.text = text tokens.push(attrs) str = str.substr(text.length) break x } } } } tokens.push({ type: 'close' }) return tokens } function format(str) { let indent = [] let out = [] parse(str).forEach(token =&gt; { switch (token.type) { case `open`: out.push(`(\n`) indent.push(' ') break case `close`: indent.pop() out.push(`\n${indent.join('')})`) break case 'comma': out.push(`,\n`) break case `id`: out.push(`${indent.join('')}${token.text}`) break } }) console.log(out.join('')) }</code></pre> </div> </div> </p> <p>You'll notice it prints out a tree of opening/closing parentheses, which is what was desired. The goal is the <code>parse</code> function, the <code>format</code> function is just for debugging.</p> <p>The second branch of the top-level if statement is clean enough, but the part dealing with the indentation is not. Is there anything repetitive which could be abstracted out or simplified? Or somehow make that first branch clean?</p> <p>Also would be good to know if there is a way to do this without doing <code>str = str.substr(...)</code>, which seems like a performance problem, but that might be tangential to the main question.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T07:28:17.867", "Id": "266258", "Score": "2", "Tags": [ "javascript", "parsing", "lexer" ], "Title": "How could this indentation-based lexer be simplified?" }
266258
<p>I am looking for feedback on the function below to load a png image stored as bytes from a MongoDB into numpy arrays.</p> <pre><code>from PIL import Image import numpy as np def bytes_to_matricies(image_bytes): &quot;&quot;&quot;image bytes into Pillow image object image_bytes: image bytes accessed from Mongodb &quot;&quot;&quot; raw_image = Image.open(io.BytesIO(image_bytes)) greyscale_matrix = np.array(raw_image.convert(&quot;L&quot;)) color_matrix = np.array(raw_image.convert(&quot;RGB&quot;)) n = greyscale_matrix.shape[0] m = greyscale_matrix.shape[1] return greyscale_matrix, color_matrix, n, m </code></pre> <p>I have profiled my code with cProfile and found this function to be a big bottleneck. Any way to optimise it would be great. Note, I have compiled most of the project with Cython, which is why you'll see .pyx files. This hasn't affected much.</p> <pre><code> Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 72 331.537 4.605 338.226 4.698 cleaner.pyx:154(clean_image) 1 139.401 139.401 139.401 139.401 {built-in method builtins.input} 356 31.144 0.087 31.144 0.087 {method 'recv_into' of '_socket.socket' objects} 11253 15.421 0.001 15.421 0.001 {method 'encode' of 'ImagingEncoder' objects} 706 10.561 0.015 10.561 0.015 {method 'decode' of 'ImagingDecoder' objects} 72 5.044 0.070 5.047 0.070 {built-in method scipy.ndimage._ni_label._label} 7853 0.881 0.000 0.881 0.000 cleaner.pyx:216(is_period) 72 0.844 0.012 1.266 0.018 cleaner.pyx:349(get_binarized_matrix) 72 0.802 0.011 0.802 0.011 {method 'convert' of 'ImagingCore' objects} 72 0.786 0.011 13.167 0.183 cleaner.pyx:57(bytes_to_matricies) </code></pre> <p>If you are wondering how the images are encoded before being written into the MongoDB here is that code:</p> <pre><code>def get_encoded_image(filename: str): &quot;&quot;&quot;Binary encodes image. &quot;&quot;&quot; image = filesystem_io.read_as_pillow(filename) # Just reads file on disk into PILLOW Image object stream = io.BytesIO() image.save(stream, format='PNG') encoded_string = stream.getvalue() return encoded_string # This will be written to MongoDB </code></pre> <p>Things I have tried:</p> <ol> <li>As mentioned above I tried compiling with Cython</li> <li>I have tried to use the lycon library but could not see how to load from bytes.</li> <li>I have tried using Pillow SIMD. It made things slower.</li> <li>I am able to use multiprocessing. But I want to optimise the function before I parallalize it.</li> </ol> <p>Thank you!</p> <p><strong>UPDATE:</strong> Answer to questions from Reinderein: The images are photographs of documents. They will eventually be OCR'd. I'm not sure how a lossy compression would affect the OCR quality. DPI is 320. Size on disk ~ 800kb each.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T18:00:11.433", "Id": "526015", "Score": "0", "body": "What is the nature of your input image - size in DB, pixel dimensions, content? Is it something like a graph (lots of continuous colour regions) or a photograph? What is the reason to encode it in PNG? Does your image strictly need to be lossless?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T19:45:11.760", "Id": "526019", "Score": "0", "body": "@Reinderien I have updated the question with answers to the above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T07:12:23.553", "Id": "526030", "Score": "0", "body": "One improvement opportunity, I see is to use YCbCr format rather than RGB. It will save you cost of conversion to grey because Y channel can directly give you grey image." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T15:42:21.490", "Id": "526046", "Score": "1", "body": "I removed my previous answer because the results were misleading. After running your code step by step using the [codetiming](https://realpython.com/python-timer/) lib it seems that the bottleneck lies in the grayscale conversion (`raw_image.convert(\"L\")`). But I believe that test is itself misleading - it is as if subsequent calls to .convert in Pillow were benefiting from some sort of cache. It's also possible the picture I used does not yield representative results. Numpy might be used for grayscale conversion instead of PIL - see: https://e2eml.school/convert_rgb_to_grayscale.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T23:04:29.610", "Id": "528009", "Score": "0", "body": "@Neil for us to test your code (as you have it), we would need some example images. Do you have the code plus sample images, perhaps on github? After we have that, we can run tests in an attempt to optimise. If the images are confidential, see if you can find others similar in form." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T12:33:42.893", "Id": "266261", "Score": "2", "Tags": [ "python", "numpy", "image" ], "Title": "Python loading image into memory (numpy arrays) from database bytes field fast" }
266261
<p>I am searching for a more efficient way to calculate the so called <strong>vec-trick</strong> used in Tensor algebra, see <a href="https://en.wikipedia.org/wiki/Kronecker_product#Matrix_equations" rel="nofollow noreferrer">Wikipedia</a>.</p> <hr /> <p><strong>Introduction:</strong></p> <p>Suppose you have a matrix vector multiplication, where a matrix <strong>C</strong> with size <strong>(np x mq)</strong> is constructed by a Kronecker product of matrices <strong>A</strong> with size <strong>(n x m)</strong> and <strong>B</strong> with size <strong>(p x q)</strong>. The vector is denoted <strong>v</strong> with size <strong>(mp x 1)</strong> or its vectorized version <strong>X</strong> with size <strong>(m x p)</strong> . In two dimensions this operation can be performed with <strong>O(npq+qnm)</strong> operations instead of <strong>O(mqnp)</strong> operations.</p> <p><strong>Expensive variant</strong> (in case of flops):</p> <img src="https://latex.codecogs.com/svg.latex?%5C&space;%20%20%20%5Cmathbf%7Bu%7D%20%20=%5Cunderbrace%7B%5Cleft(%5Cmathbf%7BB%7D%5E%5Ctextsf%7BT%7D%20%5Cotimes%20%5Cmathbf%7BA%7D%5Cright)%7D_%7BC%7D%20%5C,%20%5Cmathbf%7Bv%7D" /> <p><strong>Cheap variant</strong> (in case of flops):</p> <img src="https://latex.codecogs.com/svg.latex?%5C&space;%20%20%20%20%5Cmathbf%7Bu%7D%20=%20%5Coperatorname%7Bvec%7D(%5Cmathbf%7BAXB%7D)%20" title="\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" /> <p>See again <a href="https://en.wikipedia.org/wiki/Kronecker_product#Matrix_equations" rel="nofollow noreferrer">Kronecker properties</a>.</p> <hr /> <p><strong>Main question:</strong></p> <p>I want to perform many of these operations at ones, e.g. 2500000. Example: n=m=p=q=7 with A=size(7x7), B=size(7x7), v=size(49x2500000).</p> <p>I have implemented a <strong>MeX-C version of the cheap variant</strong> which is quite slower than a <strong>Matlab version of the expensive variant</strong>.</p> <p>Is it possible to improve the performance of the C-code in order outperform Matlab?</p> <p><strong>Note that</strong>: The same question was ask some months ago in the <a href="https://www.mathworks.com/matlabcentral/answers/680483-mex-implementation-of-tensorproduct-multiplications" rel="nofollow noreferrer">Matlab Forum</a></p> <hr /> <p><strong>My current MeX-C file implementation:</strong></p> <pre><code>/************************************************* * CALLING: * * out = tensorproduct(A,B,vector) * *************************************************/ #include &quot;mex.h&quot; #include &quot;omp.h&quot; #define PP_A prhs[0] #define PP_B prhs[1] #define PP_vector prhs[2] #define PP_out plhs[0] #define n 7 #define m 7 #define p 7 #define q 7 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { const mwSize *dim; int i,j,k,s,l; double temp[n*q]; double *A = mxGetPr(PP_A); double *B = mxGetPr(PP_B); double *vector = mxGetPr(PP_vector); dim = mxGetDimensions(PP_vector); l = dim[1]; PP_out = mxCreateDoubleMatrix(l*n*p,1,mxREAL); double *out = mxGetPr(PP_out); #pragma omp parallel for private(i,j,k,s,temp) for(k=0; k&lt;l; k++){ for(i=0; i&lt;n; i++){ for(j=0; j&lt;q; j++){ temp[i+j*n]=0; } } for(s=0; s&lt;m; s++){ for(i=0; i&lt;n; i++){ for(j=0; j&lt;m; j++){ temp[i+s*n]+=A[i+j*n]*vector[j+s*m+k*m*p]; } } } for(s=0; s&lt;n; s++){ for(i=0; i&lt;p; i++){ for(j=0; j&lt;q; j++){ out[i*n+s+k*n*p]+=B[i+j*p]*temp[j*n+s]; } } } } } </code></pre> <hr /> <p><strong>The code can be compiled with</strong>:</p> <pre><code>mex CFLAGS='$CFLAGS -fopenmp -Ofast -funroll-loops' ... LDFLAGS='$LDFLAGS -fopenmp -Ofast -funroll-loops' ... COPTIMFLAGS='$COPTIMFLAGS -fopenmp -Ofast -funroll-loops' ... LDOPTIMFLAGS='$LDOPTIMFLAGS -fopenmp -Ofast -funroll-loops' ... DEFINES='$DEFINES -fopenmp -Ofast -funroll-loops' ... tensorproduct.c </code></pre> <hr /> <p>Currently on my Notebook: (Ubuntu 18.04, GCC 7.5.0, 4 Cores)</p> <p><strong>Mex-C file implementation</strong>: Cheap variant with <strong>O(npq+qnm)</strong></p> <pre><code>A = rand(7,7); B = rand(7,7); vector = rand(49,2500000); n = 50; tic for i=1:n vector_out = reshape(tensorproduct(A,B,vector),size(vector)); end toc % Elapsed time is 26.209770 seconds. </code></pre> <p><strong>A quite simple Matlab implementation</strong>: Expensive variant with <strong>O(mqnp)</strong></p> <pre><code>C=kron(B,A); tic for i=1:n vector_out = reshape(C*vector(:,:),size(vector)); end toc % Elapsed time is 38.670186 seconds. </code></pre> <p><strong>Matlab improvement without memory copy</strong>: Expensive variant with <strong>O(mqnp)</strong></p> <pre><code>tic for i=1:n vector_out = reshape(C*reshape(vector,49,[]),size(vector)); end toc % Elapsed time is 15.001515 seconds. </code></pre> <hr />
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T16:57:59.277", "Id": "526011", "Score": "0", "body": "You’re using a .cpp extension, which `mex` interprets as C++ code, but setting C compile flags. I would suggest you start by ensuring you are using an optimized build." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T18:55:53.447", "Id": "526017", "Score": "0", "body": "@Cris Luengo Thank you for your first remark. That's a stupid mistake. I will check, if it influences the results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T21:27:08.713", "Id": "526021", "Score": "0", "body": "@CrisLuengo I made some small changes and fixed the compile flags. This has increased the performance of the C-code a bit (from 33s to 26s). However, the Matlab code is still much faster. Note that the Matlab variant computes much more flops." } ]
[ { "body": "<p>I compiled your MEX-file using just <code>mex tensorproduct.c</code> (no OpenMP, no special optimization flags, nothing). Then I compared running time to the &quot;expensive&quot; variant:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>n = 7;\nm = 7;\np = 7;\nq = 7;\nA = rand(n, m);\nB = rand(p, q);\nN = 1e6;\nX = rand(m, p, N);\n\nB = B.'; % both methods expect a transposed B\n\nR0 = kron(B, A) * reshape(X, m*p, N);\nR1 = tensorproduct(A, B, reshape(X, m*p, N));\nassert(all(R0(:) - R1(:) &lt; 1e-13))\n\ndisp(timeit(@()kron(B.', A) * reshape(X, m*p, N)))\ndisp(timeit(@()tensorproduct(A, B, reshape(X, m*p, N))))\n</code></pre>\n<p>Note several things here:</p>\n<ol>\n<li><p>We're measuring running time using <code>timeit</code>. It is always better to do this than a plain loop with <code>tic</code>/<code>toc</code>, it is much more precise.</p>\n</li>\n<li><p>Your version of the &quot;expensive&quot; code involves all sorts of unnecessary reshaping:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>reshape(C*reshape(vector,49,[]),size(vector))\n</code></pre>\n<p>is the same as</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>C*vector\n</code></pre>\n<p>because the reshapes you perform don't actually change any shapes, the requested shapes are the same as the shapes that the matrices already have.</p>\n</li>\n<li><p>I created a matrix <code>X</code> as suggested in the math, and vectorized it using <code>reshape</code>, so I could compare the results with an explicit implementation in MATLAB.</p>\n</li>\n</ol>\n<p>The timing above yielded 0.1385 s and 0.5168 s. Indeed the C code is quite a bit slower (because I'm not using OpenMP nor explicit loop unrolling, the difference I measure is larger than the difference OP measured).</p>\n<p>Simply swapping the order of the loops over <code>i</code> and <code>j</code> in the C code (for all three loops) improved processing time to 0.4618 s (~10% less). Removing the unnecessary initialization of <code>temp</code> to 0 further improves to 0.4376 s. If you really want to zero out an array, use <code>memset()</code>, which is typically faster than a loop.</p>\n<p>Next, the loop could be reordered to not need all of <code>temp = A*vector</code> computed. It suffices to compute one row to <code>temp</code>, to produce one row of <code>out</code>. Using smaller buffers usually leads to faster compute times.</p>\n<p>Beyond that, it becomes really hard to improve computational efficiency. See for example the Q&amp;A <a href=\"https://stackoverflow.com/questions/6058139/why-is-matlab-so-fast-in-matrix-multiplication\">&quot;Why is MATLAB so fast in matrix multiplication?&quot;</a> on Stack Overflow (especially the most upvoted answer, which is not the accepted answer at the top).</p>\n<hr />\n<p>I did notice some confusion with <code>m</code>, <code>n</code>, <code>p</code> and <code>q</code> in the C code, I suggest you give them each a different value and verify the result is correct (and you don't index out of bounds). If you don't care about getting that right, use a single size variable <code>m=7</code> for all four sizes. This prevents you or someone else in the future modifying the code for different sizes and getting unexpected wrong results, and potentially crashing MATLAB.</p>\n<p>I would also suggest you assert that the input matrices are double-precision floats, and of the right sizes. If I would input the wrong matrices, the MEX-file (and usually all of MATLAB) would crash.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T20:32:24.193", "Id": "526282", "Score": "0", "body": "Thank you for the effort. I found that the Vec-trick is useful only for larger sizes of n,m,p,q. See my related topic on the Matlab Forum. https://de.mathworks.com/matlabcentral/answers/1438154-vec-trick-implementation-multiple-times?s_tid=mlc_ans_email_view" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T20:03:02.697", "Id": "266399", "ParentId": "266262", "Score": "0" } } ]
{ "AcceptedAnswerId": "266399", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T12:48:00.847", "Id": "266262", "Score": "3", "Tags": [ "performance", "c", "matlab", "vectorization" ], "Title": "Matlab vs C: Tensorproduct or Vec-trick (multiple times)" }
266262
<p>Hi there I was hoping to get a better grasp of greddy algorithms while trying to solve this problem: <a href="https://codereview.stackexchange.com/questions/156887/hackerrank-gridland-metro">Hackerrank: Gridland Metro</a> and I was trying to apply an algorithm where each grid could be considered a point, and each track as an interval which cover these points. Would appreciate any feedback in regards to my approach - as I'm failing a couple of test cases, but believe this approach could be applied.</p> <p>Note: some code is missing for clarity:</p> <pre class="lang-js prettyprint-override"><code>function gridlandMetro(n, m, k, track) { // Let's treat the railrods as intervals // And Lampposts as points // Need to figure out number of uncovered points. // Turn Matrix into a line // Such that railroad intervals will be // row * {start, end} const intervals = []; for(let i = 0; i &lt; k; i++){ const [row, start, end] = track[i]; const interval = { // minus 1 since we want start of row start: ((row - 1) * m) + start, end: ((row - 1) * m) + end } intervals.push(interval); } minHeap(intervals) // create a priority queue with earliest start-time first let last = 0; let lamps = 0; while(intervals.length &gt; 0){ let i = deleteMin(intervals) //get railroad with earliest remaining start time if(i.start &gt; last){ //count any lamps inbetween intervals lamps += i.start - last - 1 last = i.end } else if(i.end &gt; last){ last = i.end // can extend the current interval further since some overlap } } lamps += m*n - last // calculate any remaining lampposts. return lamps; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T14:36:55.480", "Id": "526002", "Score": "0", "body": "Welcome to the Code Review Community, unlike Stack Overflow the more code we see the better review you will get. While reducing code for clarity on Stack Overflow is good, it is actually bad on this site. You should also include the text of the programming challenge as a quote." } ]
[ { "body": "<p>Took me some time - but it had to do with how large the Integers were being handled. I refactored the code to instead count consecutive non-railway cells, rather count the number of cells which had a track in them (using the interval merge method). I further had to break it down row by row to handle the big intergers:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function gridlandMetro(n, m, k, track) {\n // Let's treat the railroads as overlapping intervals\n // Need to figure out total number of railroad cells\n // than remove those from final grid.\n \n // Organize tracks by row using a hash table\n const intervals = {};\n for(let i = 0; i &lt; k; i++){\n const [row, start, end] = track[i];\n const interval = {\n start: start,\n end: end\n }\n if(!intervals.hasOwnProperty(row)){\n intervals[row] = [interval]\n } else {\n intervals[row].push(interval);\n }\n }\n\n let tracks = 0;\n //go row-by-row which contain tracks and count number of tracks\n for(let r in intervals){\n //minHeap sorts array by earliest start time first\n minHeap(intervals[r])\n \n let last_end = 0;\n while(intervals[r].length &gt; 0){\n //remove the first interval from the array\n let i = deleteMin(intervals[r])\n\n if(i.start &gt; last_end){\n // if this interval starts after the end of the last\n // activated interval record it and update new last_end\n tracks = i.end - i.start + 1 + tracks\n last_end = i.end\n } else if (i.end &gt; last_end){\n // this interval overlaps a previous interval\n // record non-overlapping portion\n tracks = i.end - last_end + tracks // no +1 since last_end was already counted above\n last_end = i.end\n }\n }\n }\n\n // BigInt is important here otherwise fails some of the testcases.\n let lamps = BigInt(m) * BigInt(n) - BigInt(tracks);\n return lamps;\n}\n</code></pre>\n<p>Helper functions for priority Queue:</p>\n<pre class=\"lang-js prettyprint-override\"><code> function minHeap(arr){\n const t = arr.length &gt;&gt; 1\n for(let i = t; i &gt;=0; i--){\n downHeap(arr,i+1)\n }\n}\nfunction downHeap(arr,t){\n let c = t &lt;&lt; 1;\n if(c &gt; arr.length) return\n //compare child nodes\n if(c &lt; arr.length &amp;&amp; arr[c-1].start &gt; arr[c].start ) c++\n if(arr[c-1].start &lt; arr[t-1].start){\n swap(arr, c-1, t-1)\n downHeap(arr, c)\n }\n}\nfunction swap(arr, l, r){\n const t = arr[l];\n arr[l] = arr[r]\n arr[r] = t\n}\nfunction deleteMin(arr){\n let n = arr.length -1;\n if(n &lt; 0) return n\n const min = arr[0]\n arr[0] = arr[n];\n arr.length = n;\n downHeap(arr,1);\n return min;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T03:31:46.847", "Id": "266284", "ParentId": "266263", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T14:17:41.083", "Id": "266263", "Score": "0", "Tags": [ "javascript", "algorithm", "interview-questions", "interval" ], "Title": "Hackerrank Gridland Metro - using Interval Cover Solution" }
266263
<p>This program reads raw pixels from the pipe/stdin in a loop and set the root window background.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;X11/Xatom.h&gt; #include &lt;X11/Xlib.h&gt; #include &lt;X11/Xutil.h&gt; int main(int argc, char **argv) { Display *dpy; Window root; XImage *ximg; Pixmap pm; GC gc; int scrn, fmt, ret; char *img; unsigned int w, h; Atom aroot, aeroot, atype; unsigned char *data_root, *data_eroot; size_t len, after, siz, nread; ret = EXIT_SUCCESS; dpy = XOpenDisplay(NULL); scrn = DefaultScreen(dpy); root = RootWindow(dpy, scrn); w = DisplayWidth(dpy, scrn); h = DisplayHeight(dpy, scrn); siz = 4 * w * h; img = malloc(siz); ximg = XCreateImage(dpy, CopyFromParent, 24, ZPixmap, 0, img, w, h, 32, 0); pm = XCreatePixmap(dpy, root, w, h, 24); aroot = XInternAtom(dpy, &quot;_XROOTMAP_ID&quot;, True); aeroot = XInternAtom(dpy, &quot;ESETROOT_PMAP_ID&quot;, True); if (aroot != None &amp;&amp; aeroot != None) { XGetWindowProperty(dpy, root, aroot, 0L, 1L, False, AnyPropertyType, &amp;atype, &amp;fmt, &amp;len, &amp;after, &amp;data_root); if (atype == XA_PIXMAP) { XGetWindowProperty(dpy, root, aeroot, 0L, 1L, False, AnyPropertyType, &amp;atype, &amp;fmt, &amp;len, &amp;after, &amp;data_eroot); if (data_root &amp;&amp; data_eroot &amp;&amp; atype == XA_PIXMAP &amp;&amp; *((Pixmap *) data_root) == *((Pixmap *) data_eroot)) XKillClient(dpy, *((Pixmap *) data_root)); } } aroot = XInternAtom(dpy, &quot;_XROOTPMAP_ID&quot;, False); aeroot = XInternAtom(dpy, &quot;ESETROOT_PMAP_ID&quot;, False); if (aroot == None || aeroot == None) { fputs(&quot;atomic disaster\n&quot;, stderr); ret = EXIT_FAILURE; goto exit; } XChangeProperty(dpy, root, aroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *)&amp;pm, 1); XChangeProperty(dpy, root, aeroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *)&amp;pm, 1); XSetCloseDownMode(dpy, RetainTemporary); XFlush(dpy); gc = XCreateGC(dpy, pm, 0, NULL); while ((nread = fread(img, 1, siz, stdin)) == siz) { XPutImage(dpy, pm, gc, ximg, 0, 0, 0, 0, w, h); XKillClient(dpy, AllTemporary); XSetWindowBackgroundPixmap(dpy, root, pm); XClearWindow(dpy, root); XFlush(dpy); XSync(dpy, False); } if (feof(stdin) &amp;&amp; nread != 0) { fputs(&quot;bad input\n&quot;, stderr); ret = EXIT_FAILURE; } else if (ferror(stdin)) { perror(&quot;&quot;); ret = EXIT_FAILURE; } exit: XFreeGC(dpy, gc); XFreePixmap(dpy, pm); XDestroyImage(ximg); XCloseDisplay(dpy); return ret; } </code></pre> <p>How do I handle Xlib function errors? And should I handle all of them? Virtually every function here can return an error, even stdio ones and if I wrap each in an if statement the code would be infinite (<code>if (fputs(&quot;msg&quot;, stderr) == EOF) { if (fputs...</code>).</p> <p>Does setting the buffer size with <code>setvbuf</code> make sense since I know upfront that the input size should be the multiple of <code>4 * w * h</code> which is in the order of megabytes? As per the second answer to <a href="https://stackoverflow.com/questions/5876373/using-setvbuf-with-stdin-stream">similar question</a> improvement would be minimal, but I'm not sure how to verify it.</p> <p>I am using it with <code>stream</code> from ImageMagick, like this:</p> <pre><code>stream -map bgra wallpaper.png - | myprog </code></pre> <p><code>bgra</code> instead of <code>rgba</code> because I couldn't find any proper way around <a href="https://stackoverflow.com/questions/17017432/linux-c-ximage-rgb-bgr">this</a> and unlike the OP I had simpler solution than the slow loop. And <code>a</code> because if I did just <code>rgb</code> bottom 1/4th of the screen looked like it was broken, even though the depth in <code>XCreateImage</code> is set to 24. So only <code>png</code> format works for now, since <code>stream</code> freaks out when I tell it to add alpha to <code>jpg</code> and co.</p>
[]
[ { "body": "<h1>Complexity</h1>\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>You can add a function to provide error handling and pass the result of each call that can fail to the error handling function. The error handling function can either return a status or call the <a href=\"https://en.cppreference.com/w/c/program/exit\" rel=\"nofollow noreferrer\">exit(status) function</a> after reporting the error.</p>\n<h1>Test for Possible Memory Allocation Errors</h1>\n<p>In modern high level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions <code>malloc()</code>, <code>calloc()</code> and <code>realloc()</code> return <code>NULL</code>. Referencing any memory address through a <code>NULL</code> pointer results in <strong>unknown behavior</strong> (UB).</p>\n<p>Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer).</p>\n<p>To prevent this <strong>unknown behavior</strong> a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL.</p>\n<p><strong>Current Code</strong></p>\n<pre><code> siz = 4 * w * h;\n img = malloc(siz);\n ximg = XCreateImage(dpy, CopyFromParent, 24, ZPixmap, 0, img, w, h, 32, 0);\n</code></pre>\n<p><strong>Example of Current Code with Test:</strong></p>\n<pre><code> unsigned int siz = 4 * w * h;\n char *img = malloc(siz);\n if (img == NULL)\n {\n fprintf(stderr, &quot;Malloc of siz failed\\n&quot;);\n exit(EXIT_FAILURE);\n }\n\n ximg = XCreateImage(dpy, CopyFromParent, 24, ZPixmap, 0, img, w, h, 32, 0);\n</code></pre>\n<h1>Magic Numbers</h1>\n<p>The previous code snippet contains two magic numbers (4 and 24), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h1>Declaring and Initializing Variables</h1>\n<p>The C programming language is not friendly and does not provide a default initialization value when a variable is declared. A variable should always be initialized when it is declared. To make it easier to maintain the code each variable should be declared and initialized in its own statement.</p>\n<p>As the suggested code for handling <code>malloc()</code> declare the variables as they are needed rather than putting all the variable declarations at the top of the function. The original version of C required all variables to be declared at the top of the function, but that hasn't been true for over 30 years.</p>\n<p><strong>Current Code</strong></p>\n<pre><code> int scrn, fmt, ret;\n char *img;\n unsigned int w, h;\n</code></pre>\n<p><strong>Suggested Code</strong></p>\n<pre><code> int scrn = 0;\n int fmt = 0;\n int program status = EXIT_SUCCESS;\n char *img = NULL;\n unsigned int width = 0; \n unsigned int height = 0;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T15:20:33.143", "Id": "266266", "ParentId": "266264", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T14:18:53.607", "Id": "266264", "Score": "1", "Tags": [ "performance", "c", "error-handling" ], "Title": "Setting Wallpaper with Xlib and ImageMagick cli" }
266264
<p>I though of defining the following module that I could use to govern the dark mode on/off on a website.</p> <p>Probably I would use it only for that in the whole page, but in the case I don't (i.e. I end up wanting to use it in other places), I'd like to be sure it's reusable enough.</p> <p>I tried to make it geometrically consistent by defining 3 independent variables, <code>--track-height</code>, <code>--track-AR</code> (AR = aspect ratio), and <code>--thumb-diameter-to-track-height</code>, and then defining all the others in terms of those. This should make, if I understand correctly, the geometry of the tool independed from where it's included.</p> <p>What worries me are the colors, which I <em>have</em> hardcoded. On the other hand, if I truly use this toggle to switch dark mode on/off, then it <em>must</em> trigger its own recoloring, so in principle its colors should't be hardcoded but come higher in the hierarchy.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>input.toggle { position: absolute; visibility: visible; margin-left: -1000px; } input.toggle+label { display: block; position: relative; cursor: pointer; } input.toggle+label { padding: 0; background-color: #999999; --track-height: 1em; --track-AR: 2.2; --thumb-diameter-to-track-height: 1.3; --track-width: calc(var(--track-AR) * var(--track-height)); height: var(--track-height); width: var(--track-width); border-radius: calc(0.5 * var(--track-height)); position: relative; box-shadow: inset 0.08em 0.08em 0.2em #333; } input.toggle+label::after { display: block; content: ""; } input.toggle+label::after { --thumb-diameter: calc(var(--thumb-diameter-to-track-height) * var(--track-height)); height: calc(var(--thumb-diameter)); width: calc(var(--thumb-diameter)); border-radius: 100%; background-color: #555555; position: absolute; --leftover: calc(0.5 * (var(--thumb-diameter) - var(--track-height))); bottom: calc(-1 * var(--leftover)); left: calc(-1 * var(--leftover)); transition: all 0.2s; background-image: radial-gradient(2em at 25% 25%, white, #555 60%, black); box-shadow: 0.08em 0.08em 0.2em #333; } input.toggle:checked+label::after { left: calc(var(--track-width) - var(--thumb-diameter) + var(--leftover)); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;input id="toggle" class="toggle" type="checkbox" value="" /&gt; &lt;label for="toggle"&gt;&lt;/label&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T16:21:33.437", "Id": "266267", "Score": "1", "Tags": [ "html", "css", "gui" ], "Title": "Reusable/extensible deisgn of toggle to be used for switching dark mode on/off" }
266267
<p>I made a simple password generator (once again).</p> <pre><code>import random import string import pyperclip class Password: def __init__(self, length, contains_lowercase, contains_uppercase, contains_digits, contains_symbols): self.length = length self.contains_lowercase = contains_lowercase self.contains_uppercase = contains_uppercase self.contains_digits = contains_digits self.contains_symbols = contains_symbols def generate(self): asciii = &quot;&quot; # adding parts of ascii code characters depending on corresponding booleans if self.contains_lowercase: asciii += string.ascii_lowercase if self.contains_uppercase: asciii += string.ascii_uppercase if self.contains_digits: asciii += string.digits if self.contains_digits: asciii += string.punctuation password = &quot;&quot; # appending random characters to an empty string from the ascii string until a its length reaches a certain value while len(password) &lt; self.length: password += asciii[ random.randint(0, len(asciii) - 1) ] return password while True: length = input(&quot;\nEnter the length of your password: &quot;) if length.isdigit() and int(length) &gt; 0 and not length.startswith('0'): length = int(length) break # empty strings converted to booleans are false contains_lowercase = bool(input(&quot;\nWill it contain lowercase characters (a-z)? [ENTER] if not. &quot;)) contains_uppercase = bool(input(&quot;\nWill it contain uppercase characters (A-Z)? &quot;)) contains_digits = bool(input(&quot;\nDigits (0-9)? &quot;)) contains_symbols = bool(input(&quot;\nSymbols? &quot;)) password = Password(length, contains_lowercase, contains_uppercase, contains_digits, contains_symbols).generate() print('\n' + password) pyperclip.copy(password) print(&quot;\nCopied to clipboard!&quot;) input(&quot;Press [ENTER] to quit: &quot;) </code></pre> <p>I kinda dislike the last part, because of similar looking lines...</p> <p>And also <code>if</code> checks in the <code>Password</code> class are repetitive</p> <p>I would like to see some different approaches.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T17:12:49.903", "Id": "526012", "Score": "0", "body": "I presume your previous attempt is here: https://codereview.stackexchange.com/questions/249921/password-generator-crapcode" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T10:06:18.243", "Id": "526234", "Score": "0", "body": "If your class has only two exposed methods, one of which is `__init__`, you don't want a class, but a generic function." } ]
[ { "body": "<h2>Complexity</h2>\n<p>First: enforcing specific requirements around character types in an attempt to promote password complexity is outdated and shown to do <a href=\"https://en.wikipedia.org/wiki/Password_strength#Guidelines_for_strong_passwords\" rel=\"nofollow noreferrer\">more harm than help</a>:</p>\n<blockquote>\n<p>The forcing of lowercase, uppercase alphabetic characters, numbers and symbols in passwords was common policy, but has been found to actually decrease security, by making it easier to crack. Research has shown how very predictable common use of such symbols are, and the USA, UK government cyber security departments advise against forcing their inclusion in password policy. Complex symbols also makes remembering passwords much harder, which increases writing down, password resets and password reuse - all of which lower rather than improve password security. The original author of password complexity rules Bill Burr has apologised and admits they actually decrease security, as research has found, which was widely reported in the media in 2017.</p>\n</blockquote>\n<p>It's a better idea to either:</p>\n<ul>\n<li>more generally measure the entropy of a password and compare that to some minimum (if the password is user-provided);</li>\n<li>use as broad a character set as at all possible if the password is being randomly generated and will be stored in a manager; or</li>\n<li>use a <a href=\"https://en.wikipedia.org/wiki/Passphrase\" rel=\"nofollow noreferrer\">passphrase</a> instead of a password, if it's to be memorized.</li>\n</ul>\n<p>You might need code like yours to accommodate websites with misdesigned password character criteria, but in the general case you should strongly prefer a non-constrained character set.</p>\n<h2>Secure PRNGs</h2>\n<p>You received an analogous comment on your previous password generator last year: the general-purpose random number generator provided by a framework is wholly insufficient for the purposes of secure password generation. Read the big, angry, red <a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\">callout in the documentation</a>:</p>\n<blockquote>\n<p><strong>Warning:</strong> The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the <a href=\"https://docs.python.org/3/library/secrets.html\" rel=\"nofollow noreferrer\"><code>secrets</code></a> module.</p>\n</blockquote>\n<p>You should address these two fundamentals before continuing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T19:57:44.937", "Id": "526020", "Score": "1", "body": "What;s the take-away of your first part, i.e, what changes to the code would you make because of that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T15:53:11.173", "Id": "526048", "Score": "1", "body": "The code doesn't \"enforcing specific requirements around character types\". The code builds a pool of characters to then build from, which you've said to do \"use as broad a character set as at all possible if the password is being randomly generated and will be stored in a manager\". Not all sites support all character sets, which is why password generators allow users to pick which character sets to pool from." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T17:26:49.643", "Id": "266269", "ParentId": "266268", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T16:52:03.960", "Id": "266268", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Password generator - different solutions" }
266268
<p>I'm learning <strong>react-typescript</strong> programming.<br /> Developed a sample application, which supports in multi language.</p> <p>github Souce: <a href="https://github.com/phanivaranasi/sownikbackend.git" rel="nofollow noreferrer">https://github.com/phanivaranasi/sownikbackend.git</a><br /> Review the code and share suggestions, best approaches. I have gone through various blogs, tried my best for developing language context. Below is my work</p> <ul> <li>Created react application by typescript template<br /> <code>npx create-react-app --template typescript</code></li> <li>Implemented react-redux store for login &amp; change language<br /> <code>react-redux redux</code></li> <li>Login &amp; change store are working properly<br /> <code>login component</code></li> <li>Implemented language context<br /> (<em>I'm looking for efficient code by leveraging Typescript - as context is getting called multiple times console logs are available)</em></li> </ul> <p>--English <a href="https://i.stack.imgur.com/kuUTK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kuUTK.png" alt="enter image description here" /></a></p> <p>--Hindi <a href="https://i.stack.imgur.com/zyMnC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zyMnC.png" alt="enter image description here" /></a></p> <p><a href="https://sowintl-backend.herokuapp.com/" rel="nofollow noreferrer">Working Model</a></p> <pre><code>import React, { useReducer } from &quot;react&quot;; import { ILanguageModel, ILanguageProps } from &quot;../model&quot;; import { LangActionType, LangEnumShortName, } from &quot;../state/action-types&quot;; import reducer, { initialState } from '../state/reducer/lang.reducer'; import en from '../locales/en.json'; import hi from '../locales/hi.json'; interface ContextProps { state: ILanguageModel, dispatch: { setLanguage: (lang: ILanguageModel) =&gt; void; translate: (key: string) =&gt; string; } } export const LanguageContext = React.createContext({} as ContextProps); const LanguageProvider: React.FC&lt;ILanguageProps&gt; = ({ children }) =&gt; { const [state, dispatch] = useReducer(reducer, initialState); const setLanguage = (lang: ILanguageModel) =&gt; { console.log('set lanauge', lang); dispatch({ type: LangActionType.CHANGELANG, payload: lang }); } const translate = (key: string): string =&gt; { console.log('translate key', key, &quot;&gt;&quot;, state); let _langData: { [key: string]: string } = {}; switch (state.LangShortName) { case LangEnumShortName.EN: _langData = en break; case LangEnumShortName.HI: _langData = hi; break; } console.log(&quot;_langate&quot;, _langData); return _langData[key]; } return ( &lt;LanguageContext.Provider value={{ state, dispatch: { setLanguage, translate } }}&gt; {children} &lt;/LanguageContext.Provider&gt; ) } export default LanguageProvider; </code></pre> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { BrowserRouter as Router } from 'react-router-dom' import reportWebVitals from './reportWebVitals'; import './index.css'; import App from './App'; import { Store } from './state'; import LanguageProvider from './context/lang.context'; ReactDOM.render( &lt;React.StrictMode&gt; &lt;Provider store={Store}&gt; &lt;LanguageProvider&gt; &lt;Router&gt; &lt;App /&gt; &lt;/Router&gt; &lt;/LanguageProvider&gt; &lt;/Provider&gt; &lt;/React.StrictMode&gt;, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T15:38:17.770", "Id": "526699", "Score": "0", "body": "It would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T17:56:26.123", "Id": "266272", "Score": "0", "Tags": [ "beginner", "react.js", "typescript", "redux" ], "Title": "Multilingual React Application using typescript" }
266272
<p>I wanted to share actions through different places in the component tree like:</p> <pre class="lang-javascript prettyprint-override"><code>// in one component, listen an action useListener(&quot;DELETE&quot;, (payload) =&gt; { console.log(&quot;DELETE EVENT 1&quot;, payload); }); // in another component, dispatch action const dispatch = useDispatch(); dispatch(&quot;DELETE&quot;, payload); </code></pre> <p>This is my implementation :</p> <pre class="lang-javascript prettyprint-override"><code>const globalListener = {}; export const useListener = (actionName = &quot;default&quot;, fn, dependencies = []) =&gt; { const listenerRef = useRef(Symbol(&quot;listener&quot;)); useEffect(() =&gt; { const listener = listenerRef.current; return () =&gt; { delete globalListener[actionName][listener]; }; }, []); useEffect(() =&gt; { const listener = listenerRef.current; if (!globalListener?.[actionName]) { globalListener[actionName] = {}; } globalListener[actionName][listener] = fn; }, dependencies); }; export const useAction = () =&gt; { const dispatch = (actionName, payload) =&gt; { const actionListener = globalListener?.[actionName]; if (!actionListener) { return; } const keys = Reflect.ownKeys(actionListener); keys.forEach((key) =&gt; { actionListener[key]?.(payload); }); }; return dispatch; }; </code></pre> <p>I would like to hear what kind of risks/flaws this implementation can bring. I think I could use useReducer's middleware for such usage but it would be overkill to use the whole useReducer code to do such implementation.</p> <p>What could be other approaches to solve this? With or without any extra library...</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T19:59:44.017", "Id": "266275", "Score": "1", "Tags": [ "react.js" ], "Title": "Dispatch and Listen Action with Hooks in React (without Redux)" }
266275
<p>I have been working on a very simple code where I am I open a given file file which has a format of:</p> <p><strong>proxies.txt</strong></p> <pre><code>hello:12345 hello:12345:apple:orange test:4125 test:53953:hello:world myserver:1337:usertest:passwordtest </code></pre> <p>what I want to do with these lines is that I want to return a format of e.g.</p> <pre><code>{'https': 'http://hello:12345:apple@orange'} {'https': 'http://test:53953:hello@world'} {'https': 'http://hello:12345'} </code></pre> <p>As we can see there is two scenarios where a line can be containing <code>ip:port</code> and <code>ip:port:username:password</code>.</p> <pre><code>import random from typing import List, Dict class ProxyManager(object): def __init__(self, proxy_file_path=None): self.proxies = self.load_proxies(proxy_file_path) if proxy_file_path else {} @staticmethod def load_proxies(proxy_file_path) -&gt; List[Dict[str, str]]: &quot;&quot;&quot; proxy_file_path contains: hello:12345 # ip:port hello:12345:apple:orange # ip:port:username:password test:4125 # ip:port test:53 # ip:port myserver:1337:usertest:passwordtest # ip:port:username:password &quot;&quot;&quot; with open(proxy_file_path) as proxy_file: proxies = [] for proxy in proxy_file.readlines(): split_string = proxy.strip('\n').split(':') proxy_string = f'{split_string[0]}:{split_string[1]}' # If there is 4 : in the file, that means it contains user:pass if len(split_string) == 4: proxy_string = f'{proxy_string}:{split_string[2]}@{split_string[3]}' proxies.append({'https': f'http://{proxy_string}'}) return proxies def random_proxy(self) -&gt; Dict[str, str]: return random.choice(self.proxies) def full_list(self) -&gt; List[Dict[str, str]]: return self.proxies p = ProxyManager(&quot;test.txt&quot;) print(p.full_list()) print(p.random_proxy()) </code></pre> <p>The application does work as intended but I wonder if there is anything I could improve, what I am mostly looking at is the function <code>load_proxies</code> where I believe the splitting could be better and probably more small mistakes I would believe.</p> <p>Looking forward to get some nice review from you! You guys are awesome!</p>
[]
[ { "body": "<h1>Proxy manager to return proxy format</h1>\n<h2>Good points</h2>\n<p>The task of your code is very simple, with main good points:</p>\n<ul>\n<li><p>Using of the <code>typing</code> module</p>\n</li>\n<li><p>Using static methods</p>\n</li>\n<li><p>Using <code>with</code>-statement to operate on a file</p>\n</li>\n</ul>\n<h2>Documentation</h2>\n<p>Your documentation of <code>load_proxies</code> does not describe what the function does. You can also use <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a>s:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef load_proxies(proxy_file_path) -&gt; List[Dict[str, str]]:\n &quot;&quot;&quot;\n Parse proxies into the format `http://ip:port` or `http://ip:port:user@password`.\n\n &gt;&gt;&gt; load_proxies(['hello:12345', 'hello:12345:apple:orange'])\n [{'https': 'http://hello:12345'}, {'https': 'http://hello:12345:apple@orange'}]\n &gt;&gt;&gt; load_proxies(['test:4125', 'myserver:1337:usertest:passwordtest'])\n [{'https': 'http://test:4125'}, {'https': 'http://myserver:1337:usertest@passwordtest'}]\n &quot;&quot;&quot;\n</code></pre>\n<hr />\n<p>In the class constructor, note that <code>proxies</code> will be an empty <strong>dictionary</strong> if <code>proxy_file_path</code> is not passed else it will be a <strong>list</strong> of parsed proxies. Therefore, your declaration of <code>full_list</code> is wrong if <code>proxy_file_path</code> is not passed in the constructor. <a href=\"https://stackoverflow.com/q/1957396/9997212\">Since dictionaries can't be used inside a dictionary</a>, just make the default value a list:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class ProxyManager(object):\n def __init__(self, proxy_file_path=None):\n self.proxies = self.load_proxies(proxy_file_path) if proxy_file_path else []\n</code></pre>\n<p>If you want to use sets, take a look at <a href=\"https://stackoverflow.com/a/8706053/9997212\">frozen sets</a> and change the return type of <code>full_list</code> accordingly (and also its name!).</p>\n<h2>Performance</h2>\n<p>When you do <code>proxy_file.readlines()</code>, you're loading <em>all</em> the file into the memory as a list. If you have a small file, it'll work well, but it may raise a MemoryError for large files. So you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>for proxy in proxy_file.readlines():\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>for proxy in proxy_file:\n</code></pre>\n<h2>Logic</h2>\n<p>Since 1) it's not an action (such as <code>start</code> or <code>create_proxy</code>) and 2) it doesn't receive arguments, you can use <a href=\"https://stackoverflow.com/q/2627002/9997212\">properties</a> instead of methods for <code>full_list</code> and <code>random_proxy</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@property\ndef random_proxy(self) -&gt; Dict[str, str]:\n return random.choice(self.proxies)\n\n@property\ndef full_list(self) -&gt; List[Dict[str, str]]:\n return self.proxies\n</code></pre>\n<p>This allows you to call them</p>\n<pre class=\"lang-py prettyprint-override\"><code>p = ProxyManager(&quot;test.txt&quot;)\nprint(p.full_list)\nprint(p.random_proxy)\n</code></pre>\n<p>Beware the name of <code>full_list</code>: what if you need to change its implementation to another data structure (e.g. a set or a generator)? Existing code that called <code>full_list</code> expecting it to return a list will break. If you want, you can simply name it <code>proxies</code>.</p>\n<hr />\n<p>Since <code>proxy_string</code> will always start with &quot;http://&quot;, you can already initialize the string with it, replacing</p>\n<pre class=\"lang-py prettyprint-override\"><code>proxy_string = f'{split_string[0]}:{split_string[1]}'\n# ...\nproxies.append({'https': f'http://{proxy_string}'})\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>proxy_string = f'http://{split_string[0]}:{split_string[1]}'\n# ...\nproxies.append({'https': proxy_string})\n</code></pre>\n<p>This allows you to evaluate one f-string instead of two.</p>\n<hr />\n<p>Since you will always use the first two elements of <code>split_string</code>, you can use <a href=\"https://stackoverflow.com/a/10532492/9997212\">tuple unpacking</a> to make the code more readable, replacing</p>\n<pre class=\"lang-py prettyprint-override\"><code>split_string = proxy.strip('\\n').split(':')\nproxy_string = f'http://{split_string[0]}:{split_string[1]}'\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>ip, port, *args = proxy.strip('\\n').split(':')\nproxy_string = f'http://{ip}:{port}'\n</code></pre>\n<p>With this, you introduce a new <code>args</code> variable: a list containing all the remaining strings from the split. So, you can check its length and add them to the <code>proxy_string</code>, replacing</p>\n<pre><code>if len(split_string) == 4:\n proxy_string = f'{proxy_string}:{split_string[2]}@{split_string[3]}'\n</code></pre>\n<p>with</p>\n<pre><code>if len(args) == 2:\n user, password = args\n proxy_string += f&quot;:{user}@{password}&quot;\n</code></pre>\n<hr />\n<p>Note that <a href=\"https://softwareengineering.stackexchange.com/q/166884/369544\">you're doing two tasks inside one function</a>: creating proxies strings that can be formatted as 1) <code>ip:port</code> and 2) <code>ip:post:user:password</code>. It's up to you, but you could extract the logic into two (private) separate functions:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef load_proxies(proxy_file_path) -&gt; List[Dict[str, str]]:\n def _load_ip_proxy(value: str) -&gt; str:\n &quot;&quot;&quot;\n Transform a `{ip}:{port}` string into a `http://{ip}:{port}` string.\n &quot;&quot;&quot;\n ip, port = value.split(&quot;:&quot;)\n return f&quot;http://{ip}:{port}&quot;\n\n def _load_ipup_proxy(value: str) -&gt; str:\n &quot;&quot;&quot;\n Transform a `{ip}:{port}:{user}:{password}` string into a `http://{ip}:{port}:{user}@{password}` string.\n &quot;&quot;&quot;\n ip, port, user, password = value.split(&quot;:&quot;)\n return f&quot;http://{ip}:{port}:{user}@{password}&quot;\n \n with open(proxy_file_path) as proxy_file:\n proxies = []\n for proxy in proxy_file:\n if proxy.count(&quot;:&quot;) == 1:\n proxies.append({'https': _load_ip_proxy(proxy.strip('\\n'))})\n elif proxy.count(&quot;:&quot;) == 3:\n proxies.append({'https': _load_ipup_proxy(proxy.strip('\\n'))})\n\n return proxies\n</code></pre>\n<p>A variation of the above code using Python's <a href=\"https://stackoverflow.com/a/103081/9997212\">&quot;switch statements&quot;</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef load_proxies(proxy_file_path) -&gt; List[Dict[str, str]]:\n # ...\n\n # Make a dictionary holding the parsing functions according to their `:` counts\n parsing_functions = {1: _load_ip_proxy, 3: _load_ipup_proxy}\n\n with open(proxy_file_path) as proxy_file:\n proxies = []\n # Use `line` instead of `proxy`\n for line in proxy_file:\n # Define `proxy` here, defining the strip logic in only one place\n proxy = line.strip('\\n')\n\n # Get the parsing function by the number of `:` in the proxy\n parsing_function = parsing_functions.get(proxy.count(&quot;:&quot;))\n if parsing_function is None:\n # Do nothing/raise an exception if proxy does not contain\n # neither one nor three `:` characters\n continue\n \n proxies.append({'https': parsing_function(proxy)})\n\n return proxies\n</code></pre>\n<h2>Refactored code</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nfrom typing import List, Dict, Optional\n\n\n# `class ClassName(object)` is not needed in Python 3.x\n# https://stackoverflow.com/a/1203997/9997212\nclass ProxyManager:\n # What is the type of `proxy_file_path`? You can use Optional\n # https://docs.python.org/3/library/typing.html#typing.Optional\n def __init__(self, proxy_file_path: Optional[str] = None):\n # Make `self.proxies` virtually private by adding a `_` prefix\n # https://stackoverflow.com/a/1641236/9997212\n self._proxies = self.load_proxies(proxy_file_path) if proxy_file_path else []\n\n # Is this method intended to be available to the outside world?\n # If not, make it &quot;private&quot; by adding a `_` prefix.\n @staticmethod\n # What's the type of `proxy_file_path`?\n def load_proxies(proxy_file_path: str) -&gt; List[Dict[str, str]]:\n &quot;&quot;&quot;\n Parse proxies into the format `http://ip:port` or `http://ip:port:user@password`.\n\n &gt;&gt;&gt; load_proxies(['hello:12345', 'hello:12345:apple:orange'])\n [{'https': 'http://hello:12345'}, {'https': 'http://hello:12345:apple@orange'}]\n &gt;&gt;&gt; load_proxies(['test:4125', 'myserver:1337:usertest:passwordtest'])\n [{'https': 'http://test:4125'}, {'https': 'http://myserver:1337:usertest@passwordtest'}]\n &quot;&quot;&quot;\n\n def _load_ip_proxy(value: str) -&gt; str:\n &quot;&quot;&quot;\n Transform a `{ip}:{port}` string into a `http://{ip}:{port}` string.\n &quot;&quot;&quot;\n ip, port = value.split(&quot;:&quot;)\n return f&quot;http://{ip}:{port}&quot;\n\n def _load_ipup_proxy(value: str) -&gt; str:\n &quot;&quot;&quot;\n Transform a `{ip}:{port}:{user}:{password}` string into a `http://{ip}:{port}:{user}@{password}` string.\n &quot;&quot;&quot;\n ip, port, user, password = value.split(&quot;:&quot;)\n return f&quot;http://{ip}:{port}:{user}@{password}&quot;\n \n parsing_functions = {1: _load_ip_proxy, 3: _load_ipup_proxy}\n\n with open(proxy_file_path) as proxy_file:\n proxies = []\n \n for line in proxy_file:\n proxy = line.strip('\\n')\n\n parsing_function = parsing_functions.get(proxy.count(&quot;:&quot;))\n if parsing_function is None:\n continue\n \n proxies.append({'https': parsing_function(proxy)})\n\n return proxies\n\n @property\n def random_proxy(self) -&gt; Dict[str, str]:\n return random.choice(self._proxies)\n\n @property\n def full_list(self) -&gt; List[Dict[str, str]]:\n return self._proxies\n\n# If you import this file, this code will ALWAYS be executed, which \n# may not be intended. Add a module condition:\n# https://stackoverflow.com/q/419163/9997212\nif __name__ == '__main__':\n p = ProxyManager(&quot;test.txt&quot;)\n print(p.full_list)\n print(p.random_proxy)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T13:49:18.023", "Id": "526041", "Score": "0", "body": "In your refactored code you are missing the line about `parsing_functions`: For example:\n\n`parsing_functions = {1: _load_ip_proxy, 3: _load_ipup_proxy}`\n\nIt will throw a: `NameError: name 'parsing_functions' is not defined`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T15:44:15.973", "Id": "526047", "Score": "0", "body": "Yes, I missed that, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T17:00:46.517", "Id": "526050", "Score": "0", "body": "Oh wow! I did not expected such a well code review. I feel very honored to get such a good review and also it was lots of good knowledge that I would never ever taught about at all! I have read everything multiple times and I do like the way you thought about this. Very well done and thanks for the help as well!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T12:26:13.070", "Id": "266293", "ParentId": "266276", "Score": "1" } }, { "body": "<h1>General Comments</h1>\n<p>I will second some of the @enzo comments regarding performance and logic. Additionally you will find the following observations helpful:</p>\n<h2>Compilation error if text file contains extra empty lines</h2>\n<p>When I copy paste your code in my editor and run it with the example file that contains more than 2 extra empty lines, I get an error:</p>\n<pre><code>Traceback (most recent call last):\n File &quot;/uncategorized/proxies.py&quot;, line 43, in &lt;module&gt;\n p = ProxyManager(&quot;test.txt&quot;)\n File &quot;/uncategorized/proxies.py&quot;, line 7, in __init__\n self.proxies = self.load_proxies(proxy_file_path) if proxy_file_path else {}\n File &quot;/uncategorized/proxies.py&quot;, line 26, in load_proxies\n proxy_string = f'{split_string[0]}:{split_string[1]}'\nIndexError: list index out of range\n</code></pre>\n<h2>Returning a mutable proxy list</h2>\n<p>In the <code>full_list</code> method or property or whatever you want to use there, you are returing the original <code>proxies</code> list which is mutable by the client. This means that the client can take this list and modify it and send you for example another list:</p>\n<pre><code>def full_list(self) -&gt; List[Dict[str, str]]:\n return self.proxies\n...\np = ProxyManager(&quot;test.txt&quot;)\nl = p.full_list()\nl.pop()\nl.pop()\nl.pop()\nl.pop()\nprint(p.full_list()) # prints [{'https': 'http://hello:12345'}]\nl.pop()\nl.append({'https': 'http://goodbye:12345'})\nprint(p.full_list()) # prints [{'https': 'http://goodbye:12345'}]\n\n</code></pre>\n<p>This is not good if you want to just return something that the client cannot interfere with. Instead you should either return a frozen set or a copy of the <code>proxies</code> list.</p>\n<h2>Method <code>random_proxy</code> breaks if <code>proxy_file_path</code> is empty</h2>\n<p>This breaks in @enzo answer as well. When you create a new instance of <code>ProxyManager</code> without specifying the <code>proxy_file_path</code> then calling the <code>random_proxy</code> subsequently will throw an error:</p>\n<pre class=\"lang-py prettyprint-override\"><code>p = ProxyManager()\nprint(p.random_proxy()) # Throws KeyError: 0\n</code></pre>\n<p>You should always check if the proxy list has been initialized before usage:</p>\n<pre><code>def random_proxy(self) -&gt; Dict[str, str]:\n return random.choice(self.proxies) if len(self.proxies) &gt; 0 else {}\n</code></pre>\n<h2>Catch exception when opening file</h2>\n<p>It doesn't hurt to catch an exception when opening files when they do not exist. I will let <a href=\"https://stackoverflow.com/questions/713794/catching-an-exception-while-using-a-python-with-statement\">this answer</a> explain it better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T17:03:21.583", "Id": "526051", "Score": "0", "body": "Hello Fanis! Thank you so much for the help as well as I saw you commented @enzo as well. Both was very well written and I do see the improvements you have mentioned as well. However I was not able to reproduce the `Compilation error if text file contains extra empty lines` unless I did something wrong but I added 4 new lines after the last one and it never threw any error. Also do appreciate the review you gave and I agree. The catch exception is something I just added while I read ur review. You both are awesome! <3" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T14:31:03.600", "Id": "266296", "ParentId": "266276", "Score": "1" } } ]
{ "AcceptedAnswerId": "266293", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T20:47:48.040", "Id": "266276", "Score": "0", "Tags": [ "python-3.x" ], "Title": "Proxy manager to return proxy format" }
266276
<p>So I'm staying up for 24 hours watching <a href="https://en.wikipedia.org/wiki/24_Hours_of_Le_Mans" rel="nofollow noreferrer">Le Mans</a> and decided to write something fun.</p> <p>I wrote an implementation of Conway's Game of Life (information <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">here</a> if required).</p> <p>All feedback is welcome (including feature suggestions if you have any).</p> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src=&quot;gameoflife.js&quot;&gt;&lt;/script&gt; &lt;style type=&quot;text/css&quot;&gt; canvas { color: white; background-color: white; width: 750px; display: block; margin-bottom: 10px; } body { background-color: rgb(38, 38, 40); /* dark mode B) */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id=&quot;gameCanvas&quot; width=&quot;250&quot; height=&quot;250&quot;&gt;&lt;/canvas&gt; &lt;button id=&quot;randomSeed&quot;&gt;Random seed&lt;/button&gt; &lt;button id=&quot;reset&quot;&gt;Reset&lt;/button&gt; &lt;button id=&quot;togglePlay&quot;&gt;Pause&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>gameoflife.js</strong> as a stack snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var context; var board; var canvas; var playing = true; var properties = { boardWidth: 250, boardHeight: 250, scale: 3, colours: ["#000000", "#ffffff"] }; function init() { canvas = document.getElementById("gameCanvas"); if(canvas.getContext){ context = canvas.getContext("2d"); initBoard(properties.boardWidth, properties.boardHeight); setInterval(gameLoop, 50); } else{ alert("Couldn't find canvas.") } } function drawOnCanvas(x, y){ board[x][y] = 1 ^ board[x][y]; } function initBoard(width, height){ board = Array.from(Array(width), () =&gt; new Array(height)); for(var x = 0; x &lt; width; x++){ for(var y = 0; y &lt; height; y++){ board[x][y] = 0; } } } function drawBoard(){ for(var x = 0; x &lt; properties.boardWidth; x++){ for(var y = 0; y &lt; properties.boardHeight; y++){ context.fillStyle = properties.colours[board[x][y]]; context.fillRect(x, y, 2, 2); } } } function updateBoard(){ for(var x = 0; x &lt; properties.boardWidth; x++){ for(var y = 0; y &lt; properties.boardHeight; y++){ var numberOfNeighbours = getNumberOfNeighbours(x, y); if(numberOfNeighbours &lt; 2 &amp;&amp; board[x][y] == 1){ //cell dies due to underpopulation board[x][y] = 0; } else if(board[x][y] == 0 &amp;&amp; numberOfNeighbours == 3){ //cell is born board[x][y] = 1; } else if(numberOfNeighbours &gt; 3){ //cell dies due to overpopulation board[x][y] = 0; } } } } function getNumberOfNeighbours(x, y){ var numberOfNeighbours = 0; for(var row = x - 1; row &lt;= x + 1; row++){ for(var col = y - 1; col &lt;= y + 1; col++){ if(row &lt; 0 || row &gt;= properties.boardWidth || col &lt; 0 || col &gt;= properties.boardHeight){ //neighbouring cell is out of bounds. continue; } else if(row == x &amp;&amp; col == y){ //cell shouldn't count itself. continue; } else if(board[row][col] == 0){ //neighbouring cell is dead. continue; } numberOfNeighbours++; } } return numberOfNeighbours; } function gameLoop(){ if(playing){ updateBoard(); } //we still want to draw the board as the player may draw on screen while paused. drawBoard(); } document.addEventListener("DOMContentLoaded", () =&gt; { init(); document.getElementById("reset").addEventListener("click", () =&gt; { initBoard(properties.boardWidth, properties.boardHeight); }); document.getElementById("togglePlay").addEventListener("click", () =&gt; { document.getElementById("togglePlay").innerText = playing ? "Play" : "Pause"; playing = !playing; }); document.getElementById("randomSeed").addEventListener("click", () =&gt; { for(var x = 0; x &lt; properties.boardWidth; x++){ for(var y = 0; y &lt; properties.boardHeight; y++){ //todo: add some sort of chance to this, it just ends in weird tubey static board[x][y] = Math.floor(Math.random() * 2); } } }); canvas.addEventListener("mousemove", (event) =&gt; { if(event.buttons == 1 &amp;&amp; event.button == 0){ var rect = canvas.getBoundingClientRect(); drawOnCanvas( Math.round((event.clientX - rect.left) / properties.scale), Math.round((event.clientY - rect.top) / properties.scale) ); } }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { color: white; background-color: white; width: 750px; display: block; margin-bottom: 10px; } body { background-color: rgb(38, 38, 40); /* dark mode B) */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="gameCanvas" width="250" height="250"&gt;&lt;/canvas&gt; &lt;button id="randomSeed"&gt;Random seed&lt;/button&gt; &lt;button id="reset"&gt;Reset&lt;/button&gt; &lt;button id="togglePlay"&gt;Pause&lt;/button&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T03:11:43.637", "Id": "526024", "Score": "1", "body": "Your `updateBoard` function is wrong. That's not the way Conway's Game of Life is supposed to behave. You're updating the same board, which is causing problems because the neighbors of a cell might be updated before the cell is processed. You need to create an entirely new board instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T18:37:19.817", "Id": "526054", "Score": "1", "body": "[This answer](https://codereview.stackexchange.com/a/263364/120556) implements game of life using double buffered board and fast canvas rendering using typed array. You may find some useful info." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T00:44:15.763", "Id": "266280", "Score": "0", "Tags": [ "javascript", "game", "html5", "game-of-life" ], "Title": "Conway's Game of Life written in JavaScript" }
266280
<p>If the log file is not available, then output the log message to the console. Any improvement or suggestion for this implementation for the logger by the template? Any potiencial problem that I should be aware of?</p> <pre><code>#ifndef _LOGGER_HEADER__ #define _LOGGER_HEADER__ #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;chrono&gt; #include &lt;atomic&gt; #include &lt;mutex&gt; #include &lt;fstream&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include &lt;iomanip&gt; namespace Logger { enum LOG_LEVEL { LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_ERROR, }; enum LOG_MEDIA { CONSOLE, LOG_FILE, }; extern std::atomic&lt;bool&gt; is_enable_log; extern bool is_log_file_ready; extern std::mutex log_mutex; extern enum LOG_MEDIA log_media; extern std::ofstream log_stream; std::string GetCurTime(); void Log(std::stringstream &amp;ss, const char* format); template&lt;typename T, typename... Targs&gt; void Log(std::stringstream &amp;ss, const char* format, T value, Targs... Fargs) { for (; *format != '\0'; format++) { if (('%' == *format) &amp;&amp; ('#' == *(format+1))) { ss &lt;&lt; value; Log(ss, format + 2, Fargs...); // recursive call return; } ss &lt;&lt; *format; } } template&lt;typename... Targs&gt; void Log(LOG_LEVEL level, const char* file, const int line, const char* function, const char* format, Targs... Fargs) { if (!Logger::is_enable_log.load()) { return; } std::stringstream ss; std::string file_path(file); auto loc = file_path.find_last_of(&quot;/\\&quot;); ss &lt;&lt; Logger::GetCurTime() &lt;&lt; &quot; &quot; &lt;&lt; std::setw(11) &lt;&lt; file_path.substr(loc+1) &lt;&lt; &quot;[&quot; &lt;&lt; std::setw(4) &lt;&lt; line &lt;&lt; &quot; | &quot; &lt;&lt; std::this_thread::get_id() &lt;&lt;&quot;] &lt;&quot; &lt;&lt; std::setw(25) &lt;&lt; function &lt;&lt; &quot;()&gt; &quot;; // &quot; Log(ss, format, Fargs...); DOWNGRADE_TO_COUT: if (Logger::LOG_FILE == Logger::log_media) { if (!is_log_file_ready) { try { std::lock_guard&lt;std::mutex&gt; guard(Logger::log_mutex); if (!is_log_file_ready) { Logger::log_stream.open(&quot;sdk.log&quot;, std::ofstream::out | std::ofstream::trunc); is_log_file_ready = true; } } catch (const std::exception&amp; ex) { std::lock_guard&lt;std::mutex&gt; guard(Logger::log_mutex); std::cout &lt;&lt; &quot;encounter exception when open the file to write&quot; &lt;&lt; ex.what() &lt;&lt; std::endl; Logger::log_media = Logger::CONSOLE; goto DOWNGRADE_TO_COUT; } } std::lock_guard&lt;std::mutex&gt; guard(Logger::log_mutex); Logger::log_stream &lt;&lt; ss.str()&lt;&lt;std::endl; Logger::log_stream.flush(); } else { std::lock_guard&lt;std::mutex&gt; guard(Logger::log_mutex); std::cout &lt;&lt; &quot;[SDK] &quot; &lt;&lt; ss.str(); } } void LogDestory(); } #if WIN32 #define LOG_INFO(format, ...) Logger::Log(Logger::LOG_LEVEL_INFO, __FILE__, __LINE__, __FUNCTION__, format, __VA_ARGS__) #define LOG_DEBUG(format, ...) Logger::Log(Logger::LOG_LEVEL_DEBUG, __FILE__, __LINE__, __FUNCTION__, format, __VA_ARGS__) #define LOG_ERROR(format, ...) Logger::Log(Logger::LOG_LEVEL_ERROR, __FILE__, __LINE__, __FUNCTION__, format, __VA_ARGS__) #else #define LOG_INFO(format, arg...) Logger::Log(Logger::LOG_LEVEL_INFO, __FILE__, __LINE__, __FUNCTION__, format, ##arg) #define LOG_DEBUG(format, arg...) Logger::Log(Logger::LOG_LEVEL_DEBUG, __FILE__, __LINE__, __FUNCTION__, format, ##arg) #define LOG_ERROR(format, arg...) Logger::Log(Logger::LOG_LEVEL_ERROR, __FILE__, __LINE__, __FUNCTION__, format, ##arg) #endif #define LOG_INFO_ENTER_FUNCTION LOG_INFO(&quot;enter function:%#&quot;, __FUNCTION__) #define LOG_INFO_LEAVE_FUNCTION LOG_INFO(&quot;leave function:%#&quot;, __FUNCTION__) #endif #include &lt;iomanip&gt; #include &lt;ctime&gt; std::atomic&lt;bool&gt; Logger::is_enable_log{ true }; bool Logger::is_log_file_ready{ false }; std::mutex Logger::log_mutex; enum Logger::LOG_MEDIA Logger::log_media = Logger::LOG_MEDIA::LOG_FILE; std::ofstream Logger::log_stream; void Logger::LogDestory() { Logger::is_log_file_ready = false; Logger::is_enable_log.store(false); Logger::log_stream.close(); } void Logger::Log(std::stringstream &amp;ss, const char* format) { ss &lt;&lt; format; } std::string Logger::GetCurTime() { std::stringstream time_stream; std::chrono::time_point&lt;std::chrono::system_clock&gt; current_time_point = std::chrono::system_clock::now(); time_t tnow = std::chrono::system_clock::to_time_t(current_time_point); std::time_t t = std::time(&amp;tnow); // get time now std::tm* now = std::localtime(&amp;t); time_stream &lt;&lt; (now-&gt;tm_year + 1900) &lt;&lt; '-' &lt;&lt; (now-&gt;tm_mon + 1) &lt;&lt; '-' &lt;&lt; now-&gt;tm_mday &lt;&lt; &quot; &quot; &lt;&lt; now-&gt;tm_hour &lt;&lt; &quot;:&quot; &lt;&lt; std::setw(2) &lt;&lt; now-&gt;tm_min &lt;&lt; &quot;:&quot; &lt;&lt; std::setw(2) &lt;&lt; now-&gt;tm_sec &lt;&lt; &quot;.&quot;; auto current_without_msec = std::chrono::system_clock::from_time_t(std::mktime(now)); time_stream &lt;&lt; std::setw(3) &lt;&lt; std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(current_time_point - current_without_msec).count(); return time_stream.str(); } void TestLogger() { std::cout &lt;&lt; &quot;thread speaking&quot; &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl; for (int i = 0; i &lt; 50; i++) { std::string str = &quot;test&quot;; bool flag = true; LOG_INFO(&quot;%# world %# %# \n&quot;, str, 123, std::this_thread::get_id()); LOG_INFO(&quot;this is %# a test %# %# %#\n&quot;, 1.0, flag, 3, std::this_thread::get_id()); LOG_INFO(&quot;this is %# a test %# %# %#\n&quot;, &quot;go out of my way&quot;, 'h', 3.1415926, std::this_thread::get_id()); } } int main() { std::vector&lt;std::thread&gt; threads; for (int i = 0; i &lt; 3; i++) { threads.push_back(std::thread(TestLogger)); } for (auto &amp;thread : threads) { thread.join(); } return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T15:43:20.250", "Id": "526174", "Score": "0", "body": "Can you use [source_location](https://en.cppreference.com/w/cpp/header/source_location) instead of Macros?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T01:00:56.047", "Id": "526208", "Score": "0", "body": "@JDługosz Thanks for your suggestion. `std::source_location` needs `c++20` support, which's not avaliable for my compiler(i.e `c++17` at most)." } ]
[ { "body": "<ul>\n<li>Having a bunch of global variables grouped by the virtue of spacing in the source file is very rarely a good idea. What you have here is a class in principle (a bunch of data plus methods), not using the class syntax for that is strange.</li>\n<li>Since it is not a class ,there is no notion of what is private and public. As a consequence, you have several Log functions with drastically different parameters. This makes your code difficult to follow.</li>\n<li>The code is not very good with separation of concerns. The code for formatting, opening files, working with file paths and writing is dumped into a single function with a strange <code>goto</code> in it. If you split the formatting from the output, the code will become clearer and this <code>goto</code> will not be needed.</li>\n<li>Your double-check lock is incorrect. Since the variable is non-volatile, the compiler is free to reorder the calls or optimize them away. Being extern does not help.</li>\n<li>It might be better to write exceptions to <code>stderr</code>.</li>\n<li>You should use ISO-8601 as your time format.It will save you a lot of trouble when other people will read it or when you decide to write a script to datamine your logs, or upload them to a database and many other situations.</li>\n<li>under a heavy load write/flush under a mutex might be a bottleneck</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T03:53:39.050", "Id": "526061", "Score": "0", "body": ">What you have here is a class in principle (a bunch of data plus methods), not using the class syntax for that is strange.\n\nReply: If it's a class(i.e class Logger), then when LOG_* macros are called, I have to firstly create a instance for Logger every time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T14:35:08.760", "Id": "526255", "Score": "0", "body": "It is typical to use a Singleton, such as a global variable instance of the logger. This would give you public/private and some other potential benefits for future feature growth, while being logically the same as using a namespace instead of a class. But you _could_ have more than one instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T07:28:17.660", "Id": "526427", "Score": "0", "body": "@vvotan >\"Your double-check lock is incorrect.\" *Reply*: It's to make sure only one thread to create the log file other than two or more threads. How do you think about it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T07:39:04.873", "Id": "526428", "Score": "0", "body": "@vvotan >\"What you have here is a class in principle (a bunch of data plus methods), not using the class syntax for that is strange.\" *Reply*: It's seems that a `class` could be replaced by a `namespace`, why I use a `namespace` here(and function-like macros) is because the functions by the `namespace Logger` is invoked by other persons, which is out of my control." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T08:33:18.767", "Id": "526434", "Score": "0", "body": "\"Your double-check lock is incorrect. Since the variable is non-volatile, the compiler is free to reorder the calls or optimize them away. Being extern does not help.\" Could you please explain that in more detail for me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T09:28:35.013", "Id": "526441", "Score": "0", "body": "@John, from the point of view of the compiler, your two checks for is_log_file_ready are doing the same thing, since the variable is not changed between them. In that case the compiler is free to optimize one of the checks away or reorder the statements in such a way that you would not want. Or if the compiler does not, the processor can. The whole problem is notoriously difficult and I can not explain it in a comment, you can try reading here for example: https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf . Note although that is is slightly outdated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T12:50:54.817", "Id": "526504", "Score": "0", "body": "@vvotan >from the point of view of the compiler, your two checks for is_log_file_ready are doing the same thing, since the variable is **not changed** between them. *Reply*: maybe the said variable is changed by another thread since `Log()` could be called by multiple threads at the same time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T13:31:21.867", "Id": "526513", "Score": "0", "body": "@John, yes, this is exactly the point. You assume that it might be changed, but the compiler does not and can cache it in a register or just optimize the check away because this is how execution model works in C++. To communicate to the compiler that the variable can be changed externally, you should use volatile, however it also needs care, because there are other ways it can go wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T12:03:50.740", "Id": "526616", "Score": "0", "body": "@vvotan Do you think [this code snippet](https://stackoverflow.com/a/68974797/13611002) could solve the double check problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T12:30:44.773", "Id": "526617", "Score": "0", "body": "@John, yes, the answer there is correct. To be extra safe (since even the experts sometimes argue which barriers are correct there) you might want to change ordering to memory_order_seq_cst since the loss of performance would be negligible compared to the file operation anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T17:08:32.170", "Id": "526637", "Score": "0", "body": "Adding `volatile` doesn't fix the problem in C++. It works in Java, which has a completely different memory model, and reused C++'s `volatile` for a different purpose to confuse everyone (also, I guess, because people were already used to it being a keyword and you can't really write interrupt handlers or address I/O mapped memory in Java anyway)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T17:30:34.573", "Id": "526640", "Score": "0", "body": "@Useless, you are correct, I never suggested using volatile as in keyword. I just wanted to avoid the overly long explanation in a question which is not strictly about that and oversimplified a bit." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T21:33:16.463", "Id": "266302", "ParentId": "266282", "Score": "2" } }, { "body": "<ul>\n<li><p>I think you need <code>#if _WIN32</code> not <code>#if WIN32</code> to detect the platform.</p>\n</li>\n<li><p>The log level doesn't seem to be used for anything?</p>\n</li>\n<li><p><code>std::ofstream::open</code> doesn't throw an error unless the failbit <code>exceptions()</code> flag is set. We either need to set the exception flag, or check <code>is_open()</code> instead (probably easier).</p>\n</li>\n<li><p>It seems like a bad idea to hardcode the log file name in the depths of the <code>Log</code> function.</p>\n</li>\n<li><p>It would be nice to allow the program using the log to decide what to do in case it can't open the log file, instead of hard-coding that in the log function.</p>\n</li>\n<li><p><code>flush()</code>ing after every message is likely to be very slow, and probably unnecessary.</p>\n</li>\n<li><p><code>LogDestory()</code> (spelling) is never called!</p>\n</li>\n<li><p>We should probably use perfect forwarding for the template parameter pack (i.e. take the arguments as <code>Targs&amp;&amp;... Fargs</code> and then do <code>std::forward&lt;Targs&gt;(Fargs)...</code> to pass them on.</p>\n</li>\n<li><p>As vvotan says, it would be best to create a class to hold the log state. The macros do force you to either pass the logger around everywhere (probably a bad idea), or use some sort of global, singleton, or <a href=\"https://gameprogrammingpatterns.com/service-locator.html\" rel=\"nofollow noreferrer\">service locator</a> (probably the best option). But one global is still better than five.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T12:54:40.703", "Id": "526507", "Score": "0", "body": "1>>I think you need #if _WIN32 to detect the platform. Reply: I can't see there is either _WIN32 or WIN32 in the aforementioned code snippet indeed. 2.>>flush()ing after every message is likely to be very slow, and probably unnecessary. Reply: I am afraid that some logs may be lost if the program suddenly broke down, so I flush every message. 3.>>std::ofstream::open doesn't throw an error unless the failbit exceptions() flag is set. We either need to set the exception flag, or check is_open()... Reply: Should I check if there is sth going wrong when writing every single message?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T11:42:15.663", "Id": "266378", "ParentId": "266282", "Score": "2" } }, { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Don't use function-like macros</h2>\n<p>Macros don't obey scoping rules and can't enforce typing rules. Avoid them in favor of alternatives, such as templates. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es31-dont-use-macros-for-constants-or-functions\" rel=\"nofollow noreferrer\">ES.31</a> and <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#-es34-dont-define-a-c-style-variadic-function\" rel=\"nofollow noreferrer\">ES.34</a>. In addition, your use of named variadic macro arguments as in <code>arg...</code> in <code>LOG_INFO(format, arg...)</code> is a non-standard extension.</p>\n<h2>Use standard functions to simplify your code</h2>\n<p>The <code>GetCurTime()</code> function is overly long and also doesn't work very well. I tried it at a few minutes past 7AM and here's how it formatted the time:</p>\n<pre><code>2021-8-25 7: 4: 7. 52 \n</code></pre>\n<p>That time should have been <code>7:04:07.052</code> (or better <code>07:04:07.052</code> for consistent width) and we could add some <code>std::setfill('0')</code> to fix that, but there's a better way by using a standard function <code>std::put_time()</code> instead. This rewrite of <code>GetCurTime()</code> is based on <a href=\"https://stackoverflow.com/a/66291527/3191481\">this answer</a>:</p>\n<pre><code>std::string Logger::GetCurTime()\n{\n using namespace std::chrono;\n using clock = system_clock;\n\n std::stringstream out;\n const auto current_time_point{clock::now()};\n const auto current_time{clock::to_time_t(current_time_point)};\n const auto current_localtime{*std::localtime(&amp;current_time)};\n const auto current_time_since_epoch{current_time_point.time_since_epoch()};\n const auto current_milliseconds{duration_cast&lt;milliseconds&gt;(current_time_since_epoch).count() % 1000};\n \n out &lt;&lt; std::put_time(&amp;current_localtime, &quot;%F %T&quot;) &lt;&lt; &quot;.&quot; &lt;&lt; std::setw(3) &lt;&lt; std::setfill('0') &lt;&lt; current_milliseconds;\n return out.str();\n} \n</code></pre>\n<h2>Fix the bug</h2>\n<p>If the log level is ignored, that seems like a bug to me. I think you'll find that the <code>Log</code> templated function does exactly that, so it's a bug that should be fixed.</p>\n<h2>Fix the spelling</h2>\n<p>I suspect that when you wrote <code>LogDestory</code> it really means <code>LogDestroy</code>. Such spelling errors, especially in interface code, looks unprofessional and can be an impediment to others understanding your code. But even simpler, see the next suggestion.</p>\n<h2>Rethink the design</h2>\n<p>As pointed out above, the <code>LOG_LEVEL</code> is ignored anyway, so my inclination would be to simply remove it. We also have, curiously, data and function in a <em>namespace</em> rather than in an object. This is a poor choice because it means that there is no clear delineation between interface (what users use) and implementation (private details on how it does what it does). Using an object would also allow the use of RAII which fixes several other problems, including the need for an explicit <code>LogDestroy()</code> function as mentioned above.</p>\n<h2>Use RAII to initialize an object</h2>\n<p>Assuming we want to use an object, which makes sense here, we can use RAII to eliminate a lot of errors and checking. In the existing code, the code falls back to outputting to the console if the file can't be opened. Further, it checks this every time it's called. Another way to do it is to assure that there is always (barring hardware failure, network disconnect, etc.) a valid output stream. Here's a way to do that. First, we declare two private member variables:</p>\n<pre><code>std::ostream* log_stream{&amp;std::cout};\nstd::ofstream fileout;\n</code></pre>\n<p>Then we create a constructor:</p>\n<pre><code>Logger::Logger(const std::string&amp; filename) : fileout{filename} {\n if (fileout) {\n log_stream = &amp;fileout;\n }\n}\n</code></pre>\n<p>Now if the <code>Logger</code> exists it has a valid <code>ostream</code> that either points to the file or to <code>std::cout</code>. Note, too, that the destructor will automatically close the file but not do anything with <code>std::cout</code> (although the operating system might). This eliminates the need for all of the other variables except the <code>std::mutex</code> since if the log exists at all, it's ready and the file (if any) is already open.</p>\n<h2>Do more thorough error checking</h2>\n<p>If the <code>Log</code> function is given <code>nullptr</code> instead of a valid format string, it will likely crash the program. Better would be to either report that or to simply ignore any such call.</p>\n<h2>Clearly separate implementation and interface</h2>\n<p>It seems as though you've already intended to do this, but a good way to separate the implementation from the interface is to use a header file and a <code>.cpp</code> file to contain the implementation.</p>\n<h2>Results</h2>\n<p>Here's what the refactored code looks like, using all of these suggestions:</p>\n<h2>logger.h</h2>\n<pre><code>#ifndef _LOGGER_HEADER__\n#define _LOGGER_HEADER__\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;chrono&gt;\n#include &lt;mutex&gt;\n#include &lt;fstream&gt;\n#include &lt;thread&gt;\n#include &lt;iomanip&gt;\nclass Logger\n{\nprivate:\n std::ostream* log_stream{&amp;std::cout};\n std::ofstream fileout;\n std::mutex log_mutex;\n\n std::string GetCurTime();\n void Log(std::stringstream &amp;ss, const char* format);\n\n template&lt;typename T, typename... Targs&gt;\n void Log(std::stringstream &amp;ss, const char* format, T value, Targs... Fargs) {\n for (; *format != '\\0'; format++) {\n if (('%' == *format) &amp;&amp; ('#' == *(format+1))) {\n ss &lt;&lt; value;\n Log(ss, format + 2, Fargs...); // recursive call\n return;\n }\n ss &lt;&lt; *format;\n }\n }\n\npublic:\n Logger(const std::string&amp; filename);\n ~Logger() = default;\n\n template&lt;typename... Targs&gt;\n void Log(const char* file, const int line, const char* function, const char* format, Targs... Fargs) {\n if (function == nullptr || format == nullptr) {\n return;\n }\n std::stringstream ss;\n std::string file_path(file);\n auto loc = file_path.find_last_of(&quot;/\\\\&quot;);\n ss &lt;&lt; Logger::GetCurTime() &lt;&lt; &quot; &quot; \n &lt;&lt; std::setw(11) &lt;&lt; file_path.substr(loc+1) \n &lt;&lt; &quot;[&quot; &lt;&lt; std::setw(4) &lt;&lt; line &lt;&lt; &quot; | &quot; &lt;&lt; std::this_thread::get_id() &lt;&lt;&quot;] &lt;&quot; \n &lt;&lt; std::setw(25) &lt;&lt; function &lt;&lt; &quot;()&gt; &quot;; \n Log(ss, format, Fargs...);\n std::lock_guard&lt;std::mutex&gt; guard(Logger::log_mutex);\n *log_stream &lt;&lt; ss.str() &lt;&lt; std::endl;\n }\n};\n\n#endif\n</code></pre>\n<h2>logger.cpp</h2>\n<pre><code>#include &quot;logger.h&quot;\n#include &lt;iomanip&gt;\n#include &lt;ctime&gt;\n\nLogger::Logger(const std::string&amp; filename) : fileout{filename} {\n if (fileout) {\n log_stream = &amp;fileout;\n }\n}\n\nvoid Logger::Log(std::stringstream &amp;ss, const char* format) {\n ss &lt;&lt; format;\n}\n\nstd::string Logger::GetCurTime() {\n using namespace std::chrono;\n using clock = system_clock;\n\n std::stringstream out;\n const auto current_time_point{clock::now()};\n const auto current_time{clock::to_time_t(current_time_point)};\n const auto current_localtime{*std::localtime(&amp;current_time)};\n const auto current_time_since_epoch{current_time_point.time_since_epoch()};\n const auto current_milliseconds{duration_cast&lt;milliseconds&gt;(current_time_since_epoch).count() % 1000};\n \n out &lt;&lt; std::put_time(&amp;current_localtime, &quot;%F %T&quot;) &lt;&lt; &quot;.&quot; &lt;&lt; std::setw(3) &lt;&lt; std::setfill('0') &lt;&lt; current_milliseconds;\n return out.str();\n} \n</code></pre>\n<p>And finally, here's the reworked example code:</p>\n<h2>logtest.cpp</h2>\n<pre><code>#include &quot;logger.h&quot;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;thread&gt;\n#include &lt;vector&gt;\n\nLogger mylog{&quot;sdk.log&quot;};\n// alternatively, try to create a file that can't be opened\n// Logger mylog{&quot;/root/sdk.log&quot;};\n\nvoid TestLogger() {\n std::cout &lt;&lt; &quot;thread speaking &quot; &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;\n const std::string str = &quot;test&quot;;\n const bool flag = true;\n for (int i = 0; i &lt; 50; i++) {\n mylog.Log(__FILE__, __LINE__, __FUNCTION__, \n &quot;%# world %# %#&quot;, str, 123, std::this_thread::get_id());\n mylog.Log(__FILE__, __LINE__, __FUNCTION__, \n &quot;this is %# a test %# %# %#&quot;, 1.0, flag, 3, std::this_thread::get_id());\n mylog.Log(__FILE__, __LINE__, __FUNCTION__, \n &quot;this is %# a test %# %# %#&quot;, &quot;go out of my way&quot;, 'h', 3.1415926, std::this_thread::get_id());\n }\n}\n\nint main() {\n std::vector&lt;std::thread&gt; threads;\n for (int i = 0; i &lt; 3; i++) {\n threads.emplace_back(std::thread(TestLogger));\n }\n for (auto &amp;thread : threads) {\n thread.join();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T13:03:12.040", "Id": "526511", "Score": "0", "body": "I understand the appeal of such a macro, but they have a cost as I enumerated. It's up to you to decide whether the costs are worth it. In my view, they are not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T13:11:51.463", "Id": "526512", "Score": "0", "body": "I see. Thank you so much. `vvotan` told me that \"The double-check lock is incorrect. Since the variable is non-volatile, the compiler is free to reorder the calls or optimize them away.\" I have googled and talked about this advice with other people, but I still don't get an answer. I think your're a expert at C++, could you please shed some light on this matter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T13:42:13.883", "Id": "526516", "Score": "0", "body": "The comment and explanation that vvotan did seem pretty good to me; I'm not sure I could do better, except perhaps with an example: https://godbolt.org/z/Y9P5n6qTT Note that in that simplified example, the `is_log_file_ready` variable is only checked *once* and not twice. This is what vvotan was describing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T14:01:46.650", "Id": "526517", "Score": "0", "body": "There is a difference between my my original code snippet and your demo code. Before checking the `is_log_file_ready` at the second time, the thread need to acquire the `mutex` first. And I think ~Logger() should not be equivalent to default deconstructor. ~Logger() should try to close the opened file. How do you think about it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T14:19:47.537", "Id": "526520", "Score": "0", "body": "The demo shows the effect using simplified code. Also, `~Logger()` *does* close the file if it was opened because it automatically invokes the destructor for `fileout` which has the effect of closing the file. Yet another example of why RAII is so useful!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T14:20:46.693", "Id": "526521", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/129060/discussion-between-edward-and-john)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T15:06:45.750", "Id": "526524", "Score": "0", "body": "Sorry, my network is so poor. Though I tried many times, but I still could not join in the chat. Do you think it's necessary to invoke `flush()` when writing every message to the file to prevent possible data loss when the program crashes?(see [How to protect log from application crash?](https://stackoverflow.com/questions/16267984/how-to-protect-log-from-application-crash) )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T15:14:05.177", "Id": "526525", "Score": "0", "body": "I don't think it's necessary, but if the performance is acceptable, it may provide some small additional measure of safety. Note that I left in `std::endl` which includes a flush; the additional explicit call to `flush` is therefore unnecessary." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T14:31:28.147", "Id": "266384", "ParentId": "266282", "Score": "2" } } ]
{ "AcceptedAnswerId": "266384", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T02:58:12.980", "Id": "266282", "Score": "2", "Tags": [ "c++", "template", "logging" ], "Title": "C++ logger by template" }
266282
<p>Here's my C++ solution for PE 43:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;string&gt; int main() { const int PRIMES[] {2, 3, 5, 7, 11, 13, 17}; std::string digits = &quot;0123456789&quot;; unsigned long long sum = 0; do { bool has_property = true; for (int i = 1; i &lt;= 7; i++) { long substring_num = std::stol(digits.substr(i, 3)); if (substring_num % PRIMES[i - 1] != 0) { has_property = false; break; } } if (has_property) { sum += std::stol(digits); } } while ( std::next_permutation(digits.begin(), digits.end()) ); std::cout &lt;&lt; sum &lt;&lt; &quot;\n&quot;; } </code></pre> <p>Prompt: <img src="https://i.stack.imgur.com/R7OVS.png" alt="1" /></p> <p>AFAIK, my use of STL containers and algorithms is appropriate, but I'd like feedback from someone experienced. There are more optimizations I could do, such as skipping all permutations that have an odd digit in their 3rd (zero-indexed) position, but this already runs in under one second on my beat-up Mac and is therefore &quot;good enough.&quot;</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T07:30:36.703", "Id": "526032", "Score": "1", "body": "Code looks good. I will suggest minor two changes First, Avoiding use of stol by using number array rather than string type for digits, second use of divisibility rules rather than actual division" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T08:11:11.920", "Id": "526033", "Score": "2", "body": "Move backward: first, check 000, 017, 034, 051 etc - divisible by 17. If they have no duplicates, add one of the possible digits at the beginning and check for divisibility by 13, and so on. This will be much faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T00:07:23.363", "Id": "526057", "Score": "0", "body": "@nkvns I chose a string type because of substr, and I was willing to sacrifice a bit of performance for brevity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T07:26:27.457", "Id": "526076", "Score": "0", "body": "The code doesn't really have significant quality issues, so any potential improvements may have to focus on performance anyway. Maybe you can clarify what you want to get out of a code review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T14:23:42.203", "Id": "526104", "Score": "0", "body": "Skipping is easy: https://www.codeproject.com/Articles/1244739/Permutation-Puzzle-sendplusmoreequalsmoney" } ]
[ { "body": "<p>The choice of algorithm seems good, and <code>std::next_permutation()</code> was exactly how I would implement the search.</p>\n<hr />\n<h1>Style review</h1>\n<p>We could separate the loop from the test for the divisibility property:</p>\n<pre><code>static bool has_euler43_property(const std::string&amp; digits)\n{\n static constexpr unsigned int primes[] {2, 3, 5, 7, 11, 13, 17};\n\n for (int i = 0; i &lt; 7; ++i) {\n long substring_num = std::stol(digits.substr(i+1, 3));\n if (substring_num % primes[i] != 0) {\n // failed a test\n return false;\n }\n }\n\n // all tests passed\n return true;\n}\n\nint main()\n{\n std::string digits = &quot;0123456789&quot;;\n unsigned long long sum = 0;\n\n do {\n if (has_euler43_property(digits)) {\n sum += std::stoul(digits);\n }\n } while (\n std::next_permutation(digits.begin(), digits.end())\n );\n\n std::cout &lt;&lt; sum &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<p>That's a little easier to follow than using a <code>has_property</code> variable.</p>\n<p>Note that I changed <code>PRIMES</code> to <code>primes</code> - we normally use upper-case only for preprocessor macros, which need particular care. I also changed the second <code>std::stol</code> to <code>std::stoul</code>, since we are accumulating unsigned values.</p>\n<hr />\n<h1>Performance review</h1>\n<p>I got a substantial speed-up by avoiding the substring creation and the call of <code>std::stoul</code> inside the loop:</p>\n<pre><code> long substring_num =\n (digits[i+1] - '0') * 100 + (digits[i+2] - '0') * 10 + digits[i+3] - '0';\n</code></pre>\n<p>And a little more by changing the type and consolidating the subtraction:</p>\n<pre><code> unsigned int substring_num =\n digits[i+1] * 100 + digits[i+2] * 10 + digits[i+3] - '0' * 111;\n</code></pre>\n<p>I shaved another 10% by prepending quick tests for divisibility by 2 and by 5:</p>\n<pre><code>// quick tests\nif (digits[3] % 2 != '0' % 2) {\n return 0;\n}\nif (digits[5] != '0' &amp;&amp; digits[5] != '5') {\n return 0;\n}\n</code></pre>\n<p>Adding a quick test for multiples of 3 produced only a very small improvement, but allows us to skip the slow path for primes less than 7.</p>\n<p>Reversing the order of testing (as there are fewer multiples of 17 than of 7) produced a tiny improvement too.</p>\n<hr />\n<h1>Improved code</h1>\n<p>On my system, this takes around 0.01 seconds, compared to 0.21 seconds for the original code:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;array&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\n// returns the number itself for digit strings that satisfy the type\n// or zero for digit strings that don't\n// * digits must be a ten-digit string (no bounds checking here)\nstatic unsigned long long euler43_property(const std::string&amp; digits)\n{\n static constexpr std::array primes = {2, 3, 5, 7, 11, 13, 17};\n\n // quick tests\n if (digits[3] % 2 != '0' % 2) {\n return 0;\n }\n if ((digits[2] + digits[3] + digits[4]) % 3 != ('0' + '0' + '0') % 3) {\n return 0;\n }\n if (digits[5] != '0' &amp;&amp; digits[5] != '5') {\n return 0;\n }\n\n // we skip the cases is covered above (i &lt; 3)\n for (auto i = primes.size() - 1; primes[i] &gt; 5; --i) {\n auto substring_num =\n digits[i+1] * 100 + digits[i+2] * 10 + digits[i+3] - '0' * 111;\n if (substring_num % primes[i] != 0) {\n // failed a test\n return 0;\n }\n }\n\n // all tests passed\n return std::stoul(digits);\n}\n\nint main()\n{\n std::string digits = &quot;0123456789&quot;;\n unsigned long long sum = 0;\n\n do {\n sum += euler43_property(digits);\n } while (\n std::next_permutation(digits.begin(), digits.end())\n );\n\n std::cout &lt;&lt; sum &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T12:47:12.537", "Id": "526095", "Score": "1", "body": "Even more fun with primes! (BTW `('0' + '0' + '0') % 3` must be 0, yet I see why one might code as done here.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T13:17:21.747", "Id": "526097", "Score": "0", "body": "And there was me, wondering if any coding that actually exists has an odd value for `'0'` and I never even noticed that! Good catch!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T21:42:26.007", "Id": "526116", "Score": "0", "body": "The test for 11 is that `digits[6]+digits[8]-digits[7]` is 0 or 11, for what that's worth." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T08:01:47.487", "Id": "526142", "Score": "0", "body": "@Teepeemm, that's true, but we're into the realms of diminishing returns there (and we would have to code the test for multiples of 7, or change the way the loop works), so I didn't implement that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T10:38:44.240", "Id": "266320", "ParentId": "266283", "Score": "4" } } ]
{ "AcceptedAnswerId": "266320", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T03:20:22.877", "Id": "266283", "Score": "3", "Tags": [ "c++", "programming-challenge" ], "Title": "Project Euler #43 (C++)" }
266283
<p>I want to scrape 25000 addresses using Column A cell values as search strings. I'm using the following code, it is working fine but it's too slow to extract 25000 results. Is there any way to speed up the process, like opening multiple addresses at once or something else? I'm pretty new to VBA coding. Any help would be appreciated.</p> <pre><code>Sub pullAddresses() Dim IE As Object Dim Doc As HTMLDocument Set IE = CreateObject(&quot;InternetExplorer.Application&quot;) IE.Visible = True For introw = 2 To 10 searchstring = ThisWorkbook.Sheets(&quot;Sheet1&quot;).Range(&quot;A&quot; &amp; introw).Value IE.navigate (&quot;https://www.google.com/search?q=&quot; &amp; searchstring) Do Until IE.readyState = READYSTATE_COMPLETE DoEvents Loop Set ht = IE.document ''Application.Wait (Now() + TimeValue(&quot;00:00:02&quot;)) a = ht.getElementsByClassName(&quot;desktop-title-content&quot;)(0).innerText b = ht.getElementsByClassName(&quot;desktop-title-subcontent&quot;)(0).innerText ThisWorkbook.Sheets(&quot;Sheet1&quot;).Range(&quot;B&quot; &amp; introw).Value = a &amp; &quot;, &quot; &amp; b Next End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T08:13:05.843", "Id": "526034", "Score": "1", "body": "Since you don't need to interact with the web page - click on things, scroll etc. you don't need to load a full web browser just to grab the html content. A much faster method would be to use `\"MSXML2.serverXMLHTTP\"` to query the page - e.g. as I have done in [this answer](https://stackoverflow.com/a/41717235/6609896). Note for multiple requests it's better not to create a whole new serverXMLHTTP object each time (as I'm doing there) and you should just reuse the same one like you are doing in your question for `IE`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T13:13:35.120", "Id": "526038", "Score": "1", "body": "@Greedo Why don't you make the comment into a full answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T14:39:55.347", "Id": "526044", "Score": "0", "body": "Remember that even if your code loops through 25,000 rows and executes in milliseconds, you're still at the mercy of the internet and Google's servers if you're executing a search there. I'd be willing to wager that if you put some timers in your code, the _vast_ majority of your execution time will be in the `Do Until...Loop` line of code. Unfortunately, you cannot parallelize the operation, since VBA doesn't support threading, either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T11:02:30.383", "Id": "526237", "Score": "0", "body": "Your best bet is to make asynchronous MSXML2.ServerXMLHTTP requests. Check out [Retrieve data from eBird API and create multi-level hierarchy of locations](https://codereview.stackexchange.com/a/196922/171419). In my answer create a list of 50 servers. The code loop over the list checking the ready state of each server request. When a request was ready, the result would be processed and the server would be assigned a new request. This approach was 48 times faster then using a single synchronous request." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T07:50:20.577", "Id": "266286", "Score": "2", "Tags": [ "beginner", "vba", "excel", "time-limit-exceeded", "web-scraping" ], "Title": "How to speed up the VBA scraping process" }
266286
<p>I'm new in Ada and made the following Tic Tac Toe implementation. It works as intended.</p> <h2>tictactoe.gpr</h2> <pre><code>project TicTacToe is for Source_Dirs use (&quot;src/**&quot;); for Object_Dir use &quot;obj&quot;; for Exec_Dir use &quot;.&quot;; for Main use (&quot;main.adb&quot;); for Create_Missing_Dirs use &quot;True&quot;; package Compiler is for Default_Switches (&quot;Ada&quot;) use (&quot;-g&quot;); end Compiler; end TicTacToe; </code></pre> <h2>src/main.adb</h2> <pre><code>with Ada.Text_IO; with Board; procedure Main is package IO renames Ada.Text_IO; use Board; Quit : Boolean := False; Current_Player : Board.Player_Type := Board.X; Current_Status : Board.Status_Type; procedure Next_Player is begin Current_Player := (case Current_Player is when Board.X =&gt; Board.O, when Board.O =&gt; Board.X); end Next_Player; procedure Input is User_Input : Character; begin if Current_Player = Board.X then IO.Put (&quot;x&gt;&quot;); else IO.Put (&quot;o&gt;&quot;); end if; IO.Get (User_Input); if User_Input = 'q' then Quit := True; else Current_Status := Board.Play (Current_Player, Board.Position_Type'Value ((1 =&gt; User_Input))); end if; end Input; begin Game: loop Board.Display; IO.Put (ASCII.LF); Input; case Current_Status is when Win =&gt; Quit := True; when Success =&gt; Next_Player; When Error =&gt; IO.Put_Line (&quot;Non playable move. Try again&quot;); end case; exit Game when Quit; IO.Put (ASCII.LF); end loop Game; case Current_Status is when Win =&gt; if Current_Player = Board.X then IO.Put_Line (&quot;x won! Well done.&quot;); else IO.Put_Line (&quot;o won! Well done.&quot;); end if; When others =&gt; null; end case; end Main; </code></pre> <h2>src/board.ads</h2> <pre><code>package Board is type Status_Type is (Success, Error, Win); type Position_Type is range 1 .. 9; type Cell_Type is (None, X, O); subtype Player_Type is Cell_Type range X .. O; function Is_Playable (Position : in Position_Type) return Boolean; function Play (Player : in Player_Type; Position : in Position_Type) return Status_Type; procedure Display; private type Grid_Type is array (Position_Type) of Cell_Type; end Board; </code></pre> <h2>src/board.adb</h2> <pre><code>with Ada.Text_IO; with Ada.Integer_Text_IO; package body Board is package IO renames Ada.Text_IO; package IIO renames Ada.Integer_Text_IO; Grid : Grid_Type := (others =&gt; None); function Is_Playable ( Position : in Position_Type) return Boolean is begin return (case Grid (Position) is when None =&gt; True, when others =&gt; False); end Is_Playable; function Play (Player : in Player_Type; Position : in Position_Type) return Status_Type is function Has_Won return Boolean is Col_Count : Integer := 0; Row_Count : Integer := 0; Diag_Count : Integer := 0; begin for I in Position_Type range 1 .. 3 loop for J in Position_Type range 1 .. 3 loop if Grid ((I - 1) * 3 + J) = Player then Col_Count := Col_Count + 1; end if; if Grid ((J - 1) * 3 + I) = Player then Row_Count := Row_Count + 1; end if; end loop; end loop; if Grid (1) = Player then Diag_Count := Diag_Count + 1; end if; if Grid (5) = Player then Diag_Count := Diag_Count + 1; end if; if Grid (9) = Player then Diag_Count := Diag_Count + 1; end if; return Col_Count = 3 or else Row_Count = 3 or else Diag_Count = 3; end Has_Won; begin if Is_Playable (Position) then Grid (Position) := Player; return (if Has_Won then Win else Success); else return Error; end if; end Play; procedure Display is begin for I in Grid'Range loop case Grid (I) is when X =&gt; IO.Put (&quot; x &quot;); when O =&gt; IO.Put (&quot; o &quot;); when None =&gt; IO.Put (&quot;[&quot;); IIO.Put (Integer(I), Width =&gt; 0); IO.Put (&quot;]&quot;); end case; if I /= 9 and then I mod 3 = 0 then IO.Put (ASCII.LF); end if; end loop; end Display; end Board; </code></pre> <p>I'm looking for any advices on this code. There is certainly a better &quot;ada way&quot; to do it.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T09:36:49.307", "Id": "266287", "Score": "3", "Tags": [ "beginner", "ada" ], "Title": "Tic Tac Toe in Ada" }
266287
<p>I am asked to implement the following part of code into kernel code. Actually, I have tried but not sure about the <code>std::array</code>.</p> <p>This is the original code for the function.</p> <pre><code>int KNN_classifier(array&lt;array&lt;int, 20&gt;, 4344&gt;&amp; array_X_train, array&lt;int, 4344&gt;&amp; array_Y_train, int k, array&lt;int, 20&gt;&amp; data_point) { // Calculate the distance between data_point and all points. int index = 0; static array&lt;pair&lt;int, float&gt;, 4344&gt; array_dist{}; pair&lt;int, float&gt; pair_tmp; //Apply uroll:__attribute__((opencl_unroll_hint(n))) for (size_t i = 0; i &lt; array_X_train.size(); ++i) { pair_tmp = make_pair(i, Euclidean_distance(array_X_train[i], data_point)); // dist_vec.push_back(pair_tmp); array_dist[index] = pair_tmp; index++; } </code></pre> <p>This is the kernel code:</p> <pre><code> #define N1 20 //num of cols #define N2 4344 //num of rows inline float Euclidean_distance(array&lt;int, 20&gt;&amp; array_point_A, array&lt;int, 20&gt;&amp; array_point_B) { float sum = 0.0; static array&lt;float, 20&gt; w = { 0.0847282, 0.0408621, 0.105036, 0.0619821, 0.0595455, 0.0416739, 0.0181147, 0.00592921, 0.040049, 0.0766054, 0.0441091, 0.0376111, 0.0124285, 0.0733558, 0.0587338, 0.0303001, 0.0579207, 0.0449221, 0.0530462, 0.0530462 }; for (size_t i = 0; i &lt; array_point_A.size(); ++i) { int a = array_point_A[i] - array_point_B[i]; float wieghted_distance = w[i] * (static_cast&lt;float&gt; (a) * static_cast&lt;float&gt; (a)); sum += wieghted_distance; } return sqrt(sum); } __kernel int KNN_classifier(__global const int* restrict array_X_train, __global const int* restrict array_Y_train, __global const int* restrict data_point, int k) { int index = 0; static array&lt;pair&lt;int, float&gt;, 4344&gt; array_dist{}; pair&lt;int, float&gt; pair_tmp; for (size_t i = 0; i &lt; array_X_train.size(); ++i) { pair_tmp = make_pair(i, Euclidean_distance(array_X_train[i], data_point)); array_dist[index] = pair_tmp; index++; } </code></pre>
[]
[ { "body": "<h2>Review</h2>\n<p>Welcome to Code Review. There are some suggestions as follows.</p>\n<h3>Const Definition</h3>\n<p>You already define the value <code>N1</code> and <code>N2</code>, why not use that in the array template parameter directly (e.g. <code>array&lt;float, N1&gt;</code>)? Actually, not sure what kind of problem you want to solve with KNN algorithm, you specified the dimension of KNN algorithm in <code>20</code> here. How about the case of the dimension which is different from <code>20</code>?</p>\n<h3>The weight <code>w</code> in <code>Euclidean_distance</code> function</h3>\n<p>Do you have any reason to do this? In general, this <code>w</code> array seems to be a kind of data, which could be passed as a parameter like <code>Euclidean_distance(array&lt;int, 20&gt;&amp; array_point_A, array&lt;int, 20&gt;&amp; array_point_B, array&lt;int, 20&gt;&amp; w)</code> instead and you provide the value of <code>w</code> parameter when you call it. It is not necessary to define the <code>const</code> data in a function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T23:55:36.633", "Id": "266305", "ParentId": "266288", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T09:38:26.850", "Id": "266288", "Score": "0", "Tags": [ "array", "kernel", "opencl" ], "Title": "Implement 2D and 1D std::array in opencl kernel" }
266288
<p>Consider my following code from the <a href="https://www.codewars.com/kata/556deca17c58da83c00002db/train/javascript" rel="nofollow noreferrer">Tribonacci sequence kata</a>.</p> <pre class="lang-javascript prettyprint-override"><code>function tribonacci(signature,n){ if(!n) return []; const sequence = signature; while(sequence.length !== n){ const len = sequence.length - 1; const value = sequence[len] + sequence[len - 1] + sequence[len - 2]; sequence.push(value); } return sequence; } </code></pre> <p>This works fine for all the tests but throws the following Error after completion:</p> <pre><code>&lt;--- Last few GCs ---&gt; [1:0x563377f52000] 78 ms: Scavenge 7.2 (10.9) -&gt; 6.9 (13.4) MB, 1.1 / 0.0 ms allocation failure [1:0x563377f52000] 110 ms: Scavenge 8.7 (13.4) -&gt; 7.9 (14.4) MB, 1.1 / 0.0 ms allocation failure [1:0x563377f52000] 137 ms: Scavenge 9.5 (14.4) -&gt; 8.6 (15.4) MB, 1.0 / 0.0 ms allocation failure [1:0x563377f52000] 140 ms: Scavenge 9.8 (15.4) -&gt; 8.8 (20.4) MB, 0.9 / 0.0 ms allocation failure &lt;--- JS stacktrace ---&gt; ==== JS stack trace ========================================= Security context: 0x81ef6f257c1 &lt;JSObject&gt; 1: tribonacci [/home/codewarrior/index.js:~5] [pc=0x19e540b0b428](this=0x183061e8c211 &lt;JSGlobal Object&gt;,signature=0x13893aa927e1 &lt;JSArray[54539809]&gt;,n=1) 2: /* anonymous */ [/home/codewarrior/index.js:26] [bytecode=0x3ae21c162311 offset=342](this=0x183061e8c211 &lt;JSGlobal Object&gt;) 3: /* anonymous */ [/runner/frameworks/javascript/cw-2.js:152] [bytecode=0x3ae21c15af99 offset=145](this=0... </code></pre> <p>And this STDERR:</p> <pre><code>STDERR FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory </code></pre> <p>I guess this is because the code is using too much memory. So can anyone suggest some improvements in my code so that it uses less memory.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T14:48:29.090", "Id": "526045", "Score": "1", "body": "A quick check with the Kata shows that the failing case is this one:\n`tribonacci([1,1,1],1)`. If you look carefully in your code you do not handle the case when `sequence.length > n`. In that case `sequence.length=3` and `n = 1` so the loop will not stop adding tribonacci numbers in the `sequence` list. Hope that helps." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T09:42:46.650", "Id": "526083", "Score": "0", "body": "Thanks! That helped!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T10:41:43.733", "Id": "266290", "Score": "0", "Tags": [ "javascript", "node.js", "memory-optimization" ], "Title": "Memory Allocation problem in codewars: Improvements to use less memory : Tribonacci sequence" }
266290
<p>This is an implementation of a &quot;string to int&quot; hash table with <a href="https://en.wikipedia.org/wiki/Hash_table#Robin_Hood_hashing" rel="nofollow noreferrer">Robin Hood hashing</a>. I have tested it as thoroughly as I could. It appears to have no bugs/leaks. I would appreciate any comments on correctness/performance/clarity. I have kept it ANSI C for simplicity.</p> <pre><code>/* robin_map.h */ #ifndef ROBIN_MAP_H #define ROBIN_MAP_H #pragma once #include &lt;stddef.h&gt; /* size_t */ typedef struct robin_map { size_t buffer_size; size_t element_count; void *data; } robin_map; #ifdef __cplusplus extern &quot;C&quot; { #endif robin_map rm_init(); /* Initial size must be &gt;= 5. Otherwise it is UB. */ robin_map rm_init_with_size(size_t size); void rm_deinit(robin_map *map); /* `key` and `map` cannot bu null. Null pointer cause UB */ int *rm_get(robin_map *map, char *key); int *rm_put(robin_map *map, char *key, int value); /* Returns removed value. Returns 0 if value not found */ int rm_remove(robin_map *map, char *key); #ifdef __cplusplus } #endif #endif /* ROBIN_MAP_H */ </code></pre> <pre><code>/* robin_map.c */ #include &quot;robin_map.h&quot; #include &lt;assert.h&gt; #include &lt;stddef.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; typedef enum { false = 0, true = 1 } bool; static void *xmalloc(size_t size) { void *p = malloc(size); if (!p) exit(EXIT_FAILURE); return p; } static void *xcalloc(size_t count, size_t size) { void *p = calloc(count, size); if (!p) exit(EXIT_FAILURE); return p; } static char *str_dup(char *str) { size_t len = strlen(str) + 1; char *duplicate = xmalloc(len); memcpy(duplicate, str, len); return duplicate; } /* Type of elements in a robin_map buffer */ typedef struct rm_element { char *key; int value; unsigned psl; /* probe sequence lengths */ } rm_element; static size_t strhash(char *str) { enum { multiplier = 31 }; size_t hash = 0; unsigned char *p = (unsigned char *)str; for (; *p; ++p) hash = multiplier * hash + *p; return hash; } /* Allocates `size` elements and sets all values to null/zero */ static rm_element *alloc_elements(size_t size) { /* calloc is not guaranteed to set pointers to null, * but it does work everywhere **/ return xcalloc(size, sizeof(rm_element)); } static bool slot_is_occupied(rm_element *slot) { return slot-&gt;key != NULL; } static void rehash(robin_map *map) { /* * Since our hash algorithm is good, * a growth factor of 2 should be fine **/ enum { growth_factor = 2 }; rm_element *old_buffer = map-&gt;data; size_t old_buffer_size = map-&gt;buffer_size; size_t i; map-&gt;buffer_size *= growth_factor; map-&gt;data = alloc_elements(map-&gt;buffer_size); for (i = 0; i != old_buffer_size; ++i) { size_t index; if (!slot_is_occupied(old_buffer + i)) continue; old_buffer[i].psl = 0; index = strhash(old_buffer[i].key) % map-&gt;buffer_size; for (;; ++old_buffer[i].psl, index = (index + 1) % map-&gt;buffer_size) { rm_element *slot = ((rm_element *)map-&gt;data) + index; if (!slot_is_occupied(slot)) { *slot = old_buffer[i]; break; } if (old_buffer[i].psl &gt; slot-&gt;psl) { rm_element tmp = old_buffer[i]; old_buffer[i] = *slot; *slot = tmp; } } } free(old_buffer); } static void grow_and_rehash_if_needed(robin_map *map) { double max_load_factor = 0.7; double load_factor = ((double)map-&gt;element_count) / map-&gt;buffer_size; if (load_factor &gt;= max_load_factor) rehash(map); } void rm_deinit(robin_map *map) { rm_element *buffer = map-&gt;data; size_t i; for (i = 0; i != map-&gt;buffer_size; ++i) free(buffer[i].key); free(buffer); } robin_map rm_init() { enum { initial_buffer_size = 47 }; return rm_init_with_size(initial_buffer_size); } robin_map rm_init_with_size(size_t initial_buffer_size) { robin_map map; assert(initial_buffer_size &gt;= 5); map.data = alloc_elements(initial_buffer_size); map.buffer_size = initial_buffer_size; map.element_count = 0; return map; } static rm_element *rm_get_impl(robin_map *map, char *key) { rm_element *buffer = map-&gt;data; size_t index = 0; unsigned psl = 0; index = strhash(key) % map-&gt;buffer_size; for (;; ++psl, index = (index + 1) % map-&gt;buffer_size) { rm_element *slot = buffer + index; if (!slot_is_occupied(slot) || psl &gt; slot-&gt;psl) return NULL; if (strcmp(key, slot-&gt;key) == 0) return slot; } } int *rm_get(robin_map *map, char *key) { rm_element *slot = rm_get_impl(map, key); return slot ? &amp;slot-&gt;value : NULL; } int *rm_put(robin_map *map, char *key, int value) { rm_element new_element; size_t index; /* Hashing _must_ happen after rehashing */ bool key_is_duplicated = false; int *newly_inserted = NULL; grow_and_rehash_if_needed(map); index = strhash(key) % map-&gt;buffer_size; new_element.key = key; new_element.value = value; new_element.psl = 0; for (;; ++new_element.psl, index = (index + 1) % map-&gt;buffer_size) { rm_element *slot = (rm_element *)(map-&gt;data) + index; if (!slot_is_occupied(slot)) { *slot = new_element; ++map-&gt;element_count; if (!key_is_duplicated) { slot-&gt;key = str_dup(slot-&gt;key); newly_inserted = &amp;slot-&gt;value; } break; } if (new_element.psl &gt; slot-&gt;psl) { rm_element tmp = new_element; new_element = *slot; *slot = tmp; if (!key_is_duplicated) { slot-&gt;key = str_dup(slot-&gt;key); key_is_duplicated = true; newly_inserted = &amp;slot-&gt;value; } } if (!key_is_duplicated &amp;&amp; strcmp(slot-&gt;key, new_element.key) == 0) { slot-&gt;value = new_element.value; newly_inserted = &amp;slot-&gt;value; break; } } return newly_inserted; } static void rm_pop_element(robin_map *map, rm_element *slot) { rm_element *buffer = map-&gt;data; size_t i = slot - buffer; free(slot-&gt;key); --(map-&gt;element_count); for (;;) { size_t prev = i; i = (i + 1) % map-&gt;buffer_size; if (buffer[i].psl == 0) { buffer[prev].key = NULL; break; } else { buffer[prev] = buffer[i]; --(buffer[prev].psl); } } } int rm_remove(robin_map *map, char *key) { rm_element *slot = rm_get_impl(map, key); int popped = 0; if (slot) { popped = slot-&gt;value; rm_pop_element(map, slot); } return popped; } </code></pre>
[]
[ { "body": "<p><strong>Hashing Weakness</strong></p>\n<p>If <code>initial_buffer_size</code> is a power-of-2, the index becomes nothing more than a mask of the lower bits of the hash as in <code>% map-&gt;buffer_size</code>. When hash is weak, using only a few bits results in poor overall hashing. When <code>.buffer_size</code> is a prime more than 2, then index uses all the bits of the hash uniformly.</p>\n<p><strong>Consider hiding <code>robin_map</code></strong></p>\n<p>If the initialization functions used a <em>pointer</em>, then the details of <code>robin_map</code> can exist entirely in <code>robin_map.c</code>. This is a <em>good</em> thing. The caller only knows of a pointer to <code>robin_map</code>, not its members.</p>\n<p><strong><code>robin_map.h</code> lacks documentation</strong></p>\n<p>Consider that a user may only see the .h file (or only cares to see the .h file). Functions usage and limitations deserve comments there. Perhaps add the wiki link there too.</p>\n<p><strong><code>double</code> math in an integer problem</strong></p>\n<p>Consider using integer math.</p>\n<pre><code>// double max_load_factor = 0.7;\n// double load_factor = ((double)map-&gt;element_count) / map-&gt;buffer_size;\n// if (load_factor &gt;= max_load_factor)\n// rehash(map);\n\nunsigned long long max_load_factor_n = 7;\nunsigned long long max_load_factor_d = 10;\nif (map-&gt;element_count * max_load_factor_d &gt;= \n map-&gt;buffer_size * max_load_factor_n) {\n rehash(map);\n}\n</code></pre>\n<p><strong>C vs C++</strong></p>\n<p><code>#ifdef __cplusplus</code> is a step towards usage with both C and C++.<br />\nWith <code>#include &lt;stddef.h&gt;</code>, consider <a href=\"https://stackoverflow.com/q/5079325/2410359\">Should I include stddef.h or cstddef for size_t</a>.</p>\n<p><strong>More tolerant <code>rm_deinit()</code></strong></p>\n<p>Allow <code>rm_deinit(&amp;map)</code> with <code>map.data == NULL</code>. Perhaps as below. The point is that calling <code>rm_deinit()</code> deserve to be less prone to UB and cleans up <code>robin_map</code> more.</p>\n<pre><code>void rm_deinit(robin_map *map) {\n if (map) {\n rm_element *buffer = map-&gt;data;\n if (buffer) {\n for (size_t i = 0; i != map-&gt;buffer_size; ++i) {\n free(buffer[i].key);\n } \n free(buffer);\n }\n map-&gt;buffer_size = 0;\n map-&gt;element_count = 0;\n map-&gt;data = NULL;\n }\n}\n</code></pre>\n<p><strong>Spell check</strong></p>\n<pre><code>/* `key` and `map` cannot bu null. Null pointer cause UB */ \n ^\n</code></pre>\n<p><strong>Use <code>stdbool.h</code></strong></p>\n<p>Do not code unconditionally <code>bool, false, true</code>.</p>\n<pre><code>// typedef enum { false = 0, true = 1 } bool;\n#include &lt;stdbool.h&gt;\n</code></pre>\n<p><strong>Other applications: Generalizing <code>x*alloc()</code></strong></p>\n<p>Consider clear defined behavior when <code>size == 0</code>.</p>\n<p><strong><code>unsigned</code> vs. <code>size_t</code></strong></p>\n<p>I'd expect <code>unsigned psl;</code> to use the same type as <code>size_t buffer_size;</code>.</p>\n<p><strong>Overflow check missing</strong></p>\n<pre><code> if (map-&gt;buffer_size &gt; SIZE_MAX/growth_factor) Oops(); // Add like code\n map-&gt;buffer_size *= growth_factor;\n</code></pre>\n<p><strong><code>const</code></strong></p>\n<p>Use <code>const</code> when the reference data does not change. This conveys code intent better, allows for more application and sometimes select optimizations.</p>\n<pre><code> // static size_t strhash(char *str)\n static size_t strhash(const char *str)\n</code></pre>\n<p>Other various functions too.</p>\n<p><strong>Kudos</strong></p>\n<ul>\n<li><p>Good use of name space.</p>\n</li>\n<li><p>Good use of <em>unsigned</em> math.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:03:53.847", "Id": "526063", "Score": "0", "body": "Thank you for the review. A couple points:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:04:00.763", "Id": "526064", "Score": "0", "body": "I did consider hiding robin_map behind a pointer, but that would have been two levels of indirection, so I ended up not doing it. I probably should have gone with it though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:04:13.627", "Id": "526065", "Score": "0", "body": "I did consider replacing floating point math with integer math, but that might cause overflow, so I decided not to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:04:41.510", "Id": "526066", "Score": "0", "body": "I restricted the project to ANSI C, and `<stdbool.h>` and `const` were added in C99 if I recall correctly. So, I intentionally didn't use them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:06:03.013", "Id": "526067", "Score": "0", "body": "\"would have been two levels of indirection\" --> a second level is not needed. Consider how `FILE *` works," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:07:40.317", "Id": "526068", "Score": "0", "body": "With `long long` math, as used in this answer, overflow is not a serious concern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:09:55.897", "Id": "526069", "Score": "0", "body": "\"restricted the project to ANSI C\" Hmm, unclear why one is coding in 2021 to a 1980s standard. Good luck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:20:56.130", "Id": "526070", "Score": "0", "body": "To be honest, just to keep it simple. I find the cognitive load of the annotations a bit overwhelming, especially when learning about a data-structure/algorithm. (`const`, `[[nodiscard]]`, `noexcept`, `[[noreturn]]`, `thread_local`, `[[no_unique_address]]`, `[[maybe_unused]]`, [etc etc](https://en.cppreference.com/w/cpp/language/attributes))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T11:25:55.127", "Id": "526087", "Score": "0", "body": "@AyxanHaqverdili OK, yet better to use [C](https://en.cppreference.com/w/c/language/attributes) documentation than [C++](https://en.cppreference.com/w/cpp/language/attributes) to understand C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T11:08:45.023", "Id": "526158", "Score": "0", "body": "I have one more question: Why is making the deinitialization function more tolerant a good idea? Wouldn’t it simply mask logic errors?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T12:35:23.680", "Id": "526160", "Score": "0", "body": "@AyxanHaqverdili Consider overall error handling, not just in deinitialization. As code cleans up some mess, it needs to free resources, thus deinitialization is more likely purposely called with `NULL`, 0, etc. \"simply mask logic errors\" --> Rather than hoping _undefined behavior_ exposes and error, actively detect trouble. Note `free(NULL)` is OK." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T19:40:48.403", "Id": "528090", "Score": "0", "body": "Turns out `const` was a part of ANSI C. For some reason I was under the impression that it was added later on" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T14:28:01.077", "Id": "266295", "ParentId": "266291", "Score": "1" } } ]
{ "AcceptedAnswerId": "266295", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T11:27:37.697", "Id": "266291", "Score": "2", "Tags": [ "c", "hash-map", "c89" ], "Title": "Robin Hood hashing" }
266291
<p><strong>Problem statement:</strong> Write a function which checks if two triangles intersect or not. Complete containment or tangential contact is not considered intersection.</p> <p><strong>Approach:</strong> I have considered each triangle as collection of three line segments. And then checked if any of the line segment from first triangle intersects segments from segments second triangle. To check line segment intersection, I have used rotation direction of one segment endpoint with respect to another. Assertion is that in case of intersection rotation direction will change( from clockwise to anticlockwise or vice versa). Rotation direction is computed using cross product.</p> <p><strong>Review ask:</strong> Do you see functional glitches? Missing boundary or error cases? Input around use of python</p> <pre><code>import operator def compute_direction(common_point, first_endpoint, second_endpoint): first_vector = tuple(map(operator.sub, first_endpoint, common_point)) second_vector = tuple(map(operator.sub, second_endpoint, common_point)) return first_vector[0]*second_vector[1] - first_vector[1]*second_vector[0] def does_line_segments_intersect(first_segment, second_segment): d1 = compute_direction(first_segment[0], first_segment[1], second_segment[0]) d2 = compute_direction(first_segment[0], first_segment[1], second_segment[1]) d3 = compute_direction(second_segment[0], second_segment[1], first_segment[0]) d4 = compute_direction(second_segment[0], second_segment[1], first_segment[1]) if d1*d2 &lt; 0 and d3*d4 &lt; 0: return True pass def does_triangles_intersect(first_triangle, second_triangle): for first_triangle_side in range(3): first_side = [first_triangle[first_triangle_side], first_triangle[(first_triangle_side+1)%3]] for second_triangle_side in range(3): second_side = [second_triangle[second_triangle_side], second_triangle[(second_triangle_side+1)%3]] if does_line_segments_intersect(first_side, second_side): return True return False print(does_triangles_intersect([(0, 0), (8, 0), (4, 4)], [(0, 0), (8, 0), (8, 4)])) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T11:54:25.190", "Id": "526037", "Score": "0", "body": "\"Complete containment or tangential contact is not considered intersection.\" What if it shares an edge, is touching on point intersecting? Do you have more testcases which you know to work correctly to share with us?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T03:49:09.490", "Id": "526059", "Score": "0", "body": "@Mast: Intersection here means, there must be crossing. Just touching will not be considered intersection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T05:33:32.523", "Id": "526071", "Score": "0", "body": "Or maybe you could say there must be non-zero surface area of the intersection, right?" } ]
[ { "body": "<p>Your code looks mostly good to me. Here are a few comments</p>\n<p><strong>Style details</strong></p>\n<ul>\n<li>Invisible details but there are a few trailing whitespaces that should be cleaned up</li>\n<li>Probably a matter of personal preference but I think that ordinal (&quot;first&quot;, &quot;second&quot;) lead to variables names which are pretty long and could make things harder to understand at first glance. My suggestion would to be use number as suffixes: &quot;segment1&quot;, &quot;segment2&quot;, etc.</li>\n<li>Each function implemented is non-trivial and deserves a bit of explanation regarding what it does, the expected inputs, the algorithm used.</li>\n<li>The code seems to follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> pretty well except for this particular point:</li>\n</ul>\n<blockquote>\n<p>Be consistent in return statements. Either all return statements in a\nfunction should return an expression, or none of them should. If any\nreturn statement returns an expression, any return statements where no\nvalue is returned should explicitly state this as return None, and an\nexplicit return statement should be present at the end of the function\n(if reachable)</p>\n</blockquote>\n<p>Indeed, <code>does_line_segments_intersect</code> returns either True (explicitly) or None (implicitly). It would be better to returns either True or False (explicitly).</p>\n<pre><code>if d1*d2 &lt; 0 and d3*d4 &lt; 0:\n return True\nreturn False\n</code></pre>\n<p>Then, it is a bit clearer that we can have a single return statement:</p>\n<pre><code>return d1*d2 &lt; 0 and d3*d4 &lt; 0\n</code></pre>\n<p><strong>More tests</strong></p>\n<p>Unit-tests could help to:</p>\n<ul>\n<li>explain your code</li>\n<li>check that it works as expected on various cases, in particular edge-cases</li>\n</ul>\n<p>Here is what I wrote using the <code>assert</code> statement but this should probably be done using a proper unit-test framework.</p>\n<pre><code># Tests about compute_direction\n###############################\n\n# An endpoint is the origin\nassert compute_direction((1, 2), (3, 4), (1, 2)) == 0\n# Two endpoints are similar\nassert compute_direction((1, 2), (3, 4), (3, 4)) == 0\n# Two endpoints in the exact same direction\nassert compute_direction((0, 0), (1, 2), (3, 6)) == 0\n\n# More interesting cases\nassert compute_direction((4, 4), (0, 0), (8, 4)) &gt; 0\nassert compute_direction((8, 0), (8, 4), (4, 4)) &gt; 0\nassert compute_direction((8, 0), (4, 4), (8, 4)) &lt; 0\nassert compute_direction((8, 4), (0, 0), (4, 4)) &lt; 0\nassert compute_direction((0, 0), (8, 0), (4, 4)) &gt; 0\nassert compute_direction((0, 0), (8, 0), (8, 4)) &gt; 0\nassert compute_direction((4, 4), (0, 0), (8, 0)) &gt; 0\nassert compute_direction((8, 0), (4, 4), (0, 0)) &gt; 0\nassert compute_direction((8, 0), (8, 4), (0, 0)) &gt; 0\nassert compute_direction((8, 4), (0, 0), (8, 0)) &gt; 0\n\n# Tests about triangles_intersect\n#################################\n\n# Example provided\nassert triangles_intersect([(0, 0), (8, 0), (4, 4)], [(0, 0), (8, 0), (8, 4)])\n\n# No intersection, similar triangle\nassert not triangles_intersect([(0, 0), (1, 0), (0, 1)], [(0, 0), (1, 0), (0, 1)])\n# No intersection, one common point\nassert not triangles_intersect([(0, 0), (1, 0), (0, 1)], [(1, 0), (2, 0), (2, 1)])\n# No intersection, two common points\nassert not triangles_intersect([(0, 0), (1, 0), (0, 1)], [(1, 1), (1, 0), (0, 1)])\n\n# Intersection, one point in other triangle\nassert triangles_intersect([(0, 0), (3, 0), (0, 3)], [(1, 1), (1, 3), (3, 1)])\n# Intersection, two points in other triangle\nassert triangles_intersect([(0, 0), (4, 0), (0, 4)], [(1, 2), (2, 1), (3, 3)])\n# Intersection, three points in other triangle\n# assert triangles_intersect([(0, 0), (4, 0), (0, 4)], [(1, 1), (2, 1), (1, 2)]) # WRONG\n# Intersection but not point in other triangle\nassert triangles_intersect([(0, 1), (4, 1), (2, 3)], [(0, 2), (4, 2), (2, 0)])\n\n# Intersection, two common points, one on side\n# assert triangles_intersect([(0, 0), (2, 0), (1, 1)], [(1, 0), (2, 0), (1, 1)]) # WRONG\n# Intersection, two common points, one inside\n# assert triangles_intersect([(0, 0), (3, 0), (0, 3)], [(1, 1), (3, 0), (0, 3)]) # WRONG\n# Intersection, two common points, one outside\nassert triangles_intersect([(0, 0), (1, 1), (1, 0)], [(0, 1), (1, 1), (1, 0)])\n</code></pre>\n<p>From what I understand, a few cases are not handled properly (flagged &quot;WRONG&quot; above).\nHowever, I am not too sure if the code is incorrect or if my understanding is incorrect.</p>\n<p>My understanding is that 2 triangle intersects if there are points which are (strictly) inside the 2 triangles but it looks like the code expects triangles to intersect if and only if they have sides that intersect.</p>\n<p>I'll let you see if this if what you want.</p>\n<p><em><strong>Edit:</strong></em> a value was wrong in one of my examples. I noticed this (and fixed this) by using some code to generate the corresponding graph. See: <a href=\"https://i.stack.imgur.com/PkdU8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PkdU8.png\" alt=\"graph with examples\" /></a></p>\n<p><em><strong>Second edit:</strong></em></p>\n<p>Now that I understand better the expected behavior, let's continue the review.</p>\n<p>The logic to iterate over the different sides of the triangle is a bit cumbersome. For a start, we could extract it in a function on its own. Also, we could easily write it in a very generic way so that it gives the different sides of any polygon. Using generator, we could have something like:</p>\n<pre><code>def get_sides(polygon):\n last_point = polygon[-1]\n for point in polygon:\n yield (last_point, point)\n last_point = point\n\ndef triangles_intersect(triangle1, triangle2):\n for side1 in get_sides(triangle1):\n for side2 in get_sides(triangle2):\n if segments_intersect(side1, side2):\n return True\n return False\n</code></pre>\n<p>Going further, we could use <code>itertools.product</code> and <code>any</code>.</p>\n<pre><code>def triangles_intersect(triangle1, triangle2):\n return any(segments_intersect(side1, side2)\n for side1, side2 in itertools.product(get_sides(triangle1), get_sides(triangle2)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T17:19:32.623", "Id": "526112", "Score": "0", "body": "Thanks for pointing missing explicit return False from does_line_segments_intersect. The cases you flagged as wrong is expected behaviour because in these cases triangle sides/vertices are touching each other not crossing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T20:43:06.127", "Id": "526115", "Score": "0", "body": "@nkvns I see. I think there can easily be some confusion between triangles intersecting and sides of triangles intersecting. My interpretation is the former while your implementation checks the latter. I've improved my answer to make it easier to understand." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T11:27:12.347", "Id": "266323", "ParentId": "266292", "Score": "2" } } ]
{ "AcceptedAnswerId": "266323", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T11:32:11.157", "Id": "266292", "Score": "1", "Tags": [ "python", "computational-geometry" ], "Title": "Check if two triangles intersect" }
266292
<p><strong>Problem statement:</strong> Assume a high resolution (&gt; 3000 x 3000) image is given as input. The image pixels can be classified into one of the three categories namely text, background and drawing. There is library function which takes a pixel and returns its category. Write a function which takes high resolution image as input and return another image of same resolution where all text pixels are red, background pixels are green and drawing pixels are blue.</p> <p><strong>Approach:</strong> I have currently coded a brute force solution, where I iterate over each pixel in two nested for loops and invoke library method to know its category and accordingly set the colour of the pixel. Functionality wise it runs fine but it is hell slow.</p> <p><strong>Review ask:</strong> How to improve performance? How can I use vectorize this operation? I am currently using opencv but can improve any other library to get performance gain.</p> <pre><code>def generate_image_label(input_image_path, output_image_path): try: print(&quot;Processing image &quot; + input_image_path) image = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED) image_width, image_height, image_channels = image.shape c_b, c_g, c_r, c_a = cv2.split(image) for i in range(image_width): for j in range(image_height): drawing_pixel = is_drawing_pixel(image, j, i) # is_drawing_pixel comes from some other module text_pixel = is_text_pixel(image, j, i) # is_text_pixel comes from some other module if c_a[i][j] != 0 and drawing_pixel: c_b[i][j] = 255 c_g[i][j] = 0 c_r[i][j] = 0 c_a[i][j] = 255 elif c_a[i][j] != 0 and text_pixel: c_b[i][j] = 0 c_g[i][j] = 0 c_r[i][j] = 255 c_a[i][j] = 255 else: c_b[i][j] = 0 c_g[i][j] = 255 c_r[i][j] = 0 c_a[i][j] = 255 img_label = cv2.merge((c_b, c_g, c_r, c_a)) cv2.imwrite(os.path.join(output_image_path, os.path.basename(input_image_path)), img_label) return (True, input_image_path) except: return (False, input_image_path) </code></pre>
[]
[ { "body": "<p>To vectorize code like this we need to know what <code>is_drawing_pixel</code> and <code>is_text_pixel</code> do. Can these be called with many pixels as input? If they need to be called for a single pixel, then there is no way to vectorize this, because you must call the two functions for each pixel. The only obvious speed gain is to not call <code>is_text_pixel</code> if <code>is_drawing_pixel</code> returned true. If you time these two functions, and determine one is faster than the other, then you can run the faster function first, and avoid calling the slower one if you don't need to.</p>\n<p>Because you always set transparent pixels to green, don't call your pixel classification functions for transparent pixels.</p>\n<p>You should avoid using <code>cv2.split</code>, it is not at all necessary, and just complicates your code. If <code>image_channels==4</code>, then you can do <code>image[i][j] = [255,0,0,255]</code>, or equivalently <code>image[i,j,:] = [255,0,0,255]</code>. I personally prefer the second form, I find it more intuitive. I have the idea that it's also more efficient but I don't know for sure. If we don't create the copies to modify using <code>cv2.split</code>, we should create an output image to modify in the loop: I'm pretty sure your pixel classification functions read at least a neighborhood of the pixel they are classifying, so we don't want to modify it.</p>\n<p>If you initialize <code>out</code> to <code>[0,255,0,255]</code>, then you can additionally skip the last <code>else</code> statement.</p>\n<p>It is bad practice to catch exceptions and return an error status. You should use the exception system for error handling. If your function encounters an error, it should raise an exception. It is the calling function that should catch the exception, if it needs to, and attempt to recover from the error. Thus, you should just not catch the exceptions at all.</p>\n<p><code>cv2.imread</code> will return <code>None</code> if it fails to read the image. You should always test for this case and handle the error appropriately. If OpenCV did error handling properly like Python expects, it would raise an exception and you wouldn't have to worry about it. But because it returns an error status instead, you always have to check the error status and handle it if necessary. It is best to raise an exception when <code>cv2.imread</code> returns <code>None</code>.</p>\n<p>The code ends up being something like this (obviously not tested, as I don't have access to the pixel testing functions):</p>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_image_label(input_image_path, output_image_path):\n print(&quot;Processing image &quot; + input_image_path)\n image = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)\n if not image:\n raise RuntimeError('Could not load image')\n if image.ndim != 3\n raise RuntimeError('Cannot process gray-scale images')\n if image.shape(2) == 3:\n # Add an alpha channel if we don't have one\n image = np.pad(image, ((0,0),(0,0),(0,1)), constant_values=255)\n assert(image.shape(2) == 4)\n out = np.zeros(image.shape, dtype=np.int8)\n out[:,:,1] = 255 # default color is green\n out[:,:,3] = 255 # all pixels have alpha = 255\n\n for i in range(image_width):\n for j in range(image_height):\n if image[i,j,3] != 0:\n if is_drawing_pixel(image, j, i):\n out[i,j,:] = [255,0,0,255]\n elif is_text_pixel(image, j, i):\n out[i,j,:] = [0,0,255,255]\n cv2.imwrite(os.path.join(output_image_path, os.path.basename(input_image_path)), out)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T17:21:47.993", "Id": "266390", "ParentId": "266294", "Score": "1" } } ]
{ "AcceptedAnswerId": "266390", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T13:02:28.283", "Id": "266294", "Score": "1", "Tags": [ "python", "performance", "image", "opencv" ], "Title": "Update image pixels based on different criteria" }
266294
<p>I made tic-tac-toe (a common practice).</p> <p><strong>board_and_player.py</strong></p> <pre><code>class Board: def __init__(self): self.cells = {&quot;top_l&quot;: ' ', &quot;top_m&quot;: ' ', &quot;top_r&quot;: ' ', &quot;mid_l&quot;: ' ', &quot;mid_m&quot;: ' ', &quot;mid_r&quot;: ' ', &quot;down_l&quot;: ' ', &quot;down_m&quot;: ' ', &quot;down_r&quot;: ' '} def generate(self): board = self.cells[&quot;top_l&quot;] + '|' + self.cells[&quot;top_m&quot;] + '|' + self.cells[&quot;top_r&quot;] + ' \n'\ &quot;-----&quot; + ' \n' + \ self.cells[&quot;mid_l&quot;] + '|' + self.cells[&quot;mid_m&quot;] + '|' + self.cells[&quot;mid_r&quot;] + ' \n' + \ &quot;-----&quot; + ' \n' + \ self.cells[&quot;down_l&quot;] + '|' + self.cells[&quot;down_m&quot;] + '|' + self.cells[&quot;down_r&quot;] + ' \n' return board board = Board() class Player: def __init__(self, name, symbol): self.name = name self.symbol = symbol def make_turn(self): while True: choice_cell_index = input(f&quot;{self.name}'s turn! Pick an empty cell (a number from 1 to 9): &quot;) if choice_cell_index.isdigit() and ( int(choice_cell_index) &lt;= 9 and int(choice_cell_index) &gt; 0 )\ and not choice_cell_index.startswith('0') and board.cells[ list(board.cells.keys())[int(choice_cell_index) - 1] ] == ' ': board.cells[ list(board.cells.keys())[int(choice_cell_index) - 1] ] = self.symbol break else: print(&quot;\nThis cell is full or your input is wrong.\n&quot;) def player_won(self): # column conditions if board.cells[&quot;top_l&quot;] == board.cells[&quot;mid_l&quot;] == board.cells[&quot;down_l&quot;] == self.symbol or\ board.cells[&quot;top_m&quot;] == board.cells[&quot;mid_m&quot;] == board.cells[&quot;down_m&quot;] == self.symbol or\ board.cells[&quot;top_r&quot;] == board.cells[&quot;mid_r&quot;] == board.cells[&quot;down_r&quot;] == self.symbol: return True # row conditions elif board.cells[&quot;top_l&quot;] == board.cells[&quot;top_m&quot;] == board.cells[&quot;top_r&quot;] == self.symbol or\ board.cells[&quot;mid_l&quot;] == board.cells[&quot;mid_m&quot;] == board.cells[&quot;mid_r&quot;] == self.symbol or\ board.cells[&quot;down_l&quot;] == board.cells[&quot;down_m&quot;] == board.cells[&quot;down_r&quot;] == self.symbol: return True # diagonal conditions elif board.cells[&quot;top_l&quot;] == board.cells[&quot;mid_m&quot;] == board.cells[&quot;down_r&quot;] == self.symbol or\ board.cells[&quot;top_r&quot;] == board.cells[&quot;mid_m&quot;] == board.cells[&quot;down_l&quot;] == self.symbol: return True return False </code></pre> <p><strong>game.py</strong></p> <pre><code>from board_and_player import * print(&quot;Greetings! Welcome to X's and O's!&quot;) player1 = Player(&quot;player 1&quot;, 'X') player2 = Player(&quot;player 2&quot;, 'O') while not player1.player_won() or not player2.player_won(): print('') print(board.generate()) player1.make_turn() if player1.player_won() or player2.player_won(): break print('') print(board.generate()) player2.make_turn() if player1.player_won(): print('') print(board.generate()) print(&quot;\nPlayer 1 Wins!&quot;) elif player2.player_won(): print('') print(board.generate()) print(&quot;\nPlayer 2 Wins!&quot;) else: print(&quot;\nTie!&quot;) </code></pre> <p>Can anybody show more elegant way to make the board?</p> <p>And also I'm kinda doubtful of fitting a single <em>logical line</em> into multiple <em>physical lines</em>. I have heart, that it's a bad habit and that I should avoid using it, but....what if it isn't?...That way I didn't make a line too long and it's more readable.</p>
[]
[ { "body": "<h3>Game Board Data Structure Representation</h3>\n<p>Using a dictionary for the board's cells is a little awkward, as you probably realized, particularly in this line:</p>\n<pre><code>board.cells[ list(board.cells.keys())[int(choice_cell_index) - 1] ] = self.symbol\n</code></pre>\n<p>You really want to use a dictionary only when the data is actually structured in a <code>&lt;Key&gt;: &lt;Value&gt;</code> format. JSON is a great example of this. If you're writing an API and you want your endpoint to reply with a numeric status code and a text description, for example, the result is very naturally expressed using that structure.</p>\n<pre><code>{\n &quot;status&quot;: 429,\n &quot;message&quot;: &quot;Too Many Requests&quot;\n}\n</code></pre>\n<p>In the case of the game board, it's more of an encumbrance than a convenience because it makes iteration over the game board pretty awkward, as you saw.</p>\n<h3>Printing the Board (and Other Objects)</h3>\n<p>Save for the previous point, I don't really have a problem with the way you printed the board, really. I would imagine that a Python expert would recommend using the <code>__str__</code> method, which would allow you to simply call <code>print(board)</code>, rather than defining a custom method. (You can find all of these methods in the <a href=\"https://docs.python.org/3/reference/datamodel.html\" rel=\"nofollow noreferrer\">Python data model documentation</a>.)</p>\n<p>In the sample below, this is what I used to print the game state every turn. Notice that the <code>Board</code> class' <code>__str__</code> method does basically the same thing you did in your <code>Board.generate</code> method.</p>\n<p>The only real difference is that rather than simply representing the board's cells as strings, each cell is a class in and of itself, with a <code>self.player</code> class that defaults to <code>None</code> if the cell is empty. You can see from the <code>Cell</code> class definition below that the <code>__str__</code> method does exactly what you would expect: printing the player's symbol (whatever it is), or a blank if it's empty.</p>\n<pre><code>class Cell():\n\n def __init__(self, player: Player = None):\n self.player = player\n \n def __str__(self):\n return f&quot;{self.player}&quot; if self.player is not None else &quot; &quot;\n</code></pre>\n<p>The <code>Player</code> class is just as simple, basically, with the only real difference being the constructor taking the player's name and desired symbol, just as you had in your version.</p>\n<pre><code>class Player():\n \n def __init__(self, name: str, symbol: str):\n self.name = name\n self.symbol = symbol\n \n def __str__(self):\n return f&quot;{self.symbol}&quot;\n</code></pre>\n<p>Ultimately, the difference is really only superficial, honestly. Again, besides what I said above about using a list over a dictionary, I don't have a problem with the way you printed the game board.</p>\n<h3>Structure</h3>\n<p>If I'm not mistaken, it looks like in the event of a tie, your game would loop forever, since you're main game loop is defined like this:</p>\n<pre><code>while not player1.player_won() or not player2.player_won():\n ...\n</code></pre>\n<p>Even though you're checking for a tie below the main loop, it doesn't look like you can actually get there from the game loop itself.</p>\n<p>I added a check to see how many empty cells there were left in my version below, although I don't actually think this is a complete solution. I believe it's possible for there to be empty cells left without there being winning moves left. You can at least keep filling in the empty cells, though, and the game will recognize the tie (eventually).</p>\n<p>Also, while I like that you actually defined your turn process and winning condition check as their own functions (I didn't do that, but because I was being lazy, not because it's a good idea), I don't think attaching them to the player is a good idea. At least for the purpose of a Tic Tac Toe implementation, I think the player objects should contain only the necessary state (probably only the name and symbol of its player), and everything else should be handled by the game. I used a Game class for this, but you don't have to, especially if you're just going to quit at the end, which I did.</p>\n<p>In a bigger game, you tend to have a main Game class that manages scenes and state, and that gives you the ability to do things like add an options screen, restart, etc., all within the game itself, and especially if you wanted to have different game modes like &quot;Campaign&quot;, &quot;Multiplayer&quot;, etc.</p>\n<p>I added a <code>GameState</code> enum to keep track of the game state of course, but the reason I added a win state for each player rather than simply printing &quot;Player 1 Wins,&quot; for example, is that keeping track of specifically which player won allows you to then do things like update the Elo ratings of each player, if you were making an online multiplayer game, say, since such a calculation obviously requires that you know specifically which player won.</p>\n<h3>Reading Input</h3>\n<p>When you get the user's selection, you actually call <code>isdigit</code> to make sure you got an actual number, which is great. This isn't optimal, though, because the input is a string, and keeping it as a string leads you to either basically parse the input yourself, or potentially misinterpret it. In your version, you check that the number doesn't start with a zero, for example.</p>\n<p>I recommend simply converting the input to an integer, and dealing with the potential <code>ValueError</code> exception if it's not valid instead, for two reasons. One, a numeric string that starts with a zero is correctly interpreted (i.e., &quot;09&quot; is correctly interpreted as <code>9</code>, and is thus valid), and two, you can then simply compare whether the input is simply between 1 and 9, inclusive.</p>\n<p>Parsing and interpreting input strings is complicated; if you're going to do it, do it on purpose. Otherwise, save yourself the headache and deal with data in its native format.</p>\n<pre><code># Get the current player's selection for\n# their next move. We wrap this in a\n# try/catch block because if the user inputs\n# anything other than an integer, the int\n# constructor will throw a ValueError\n# exception.\ntry:\n player_selection = int(input(f&quot;{self.current_player.name}, please enter a number from 1 to 9: &quot;))\nexcept ValueError as e:\n # Notify the user of their error and\n # loop again.\n print(&quot;Please enter only an integer from 1 to 9.&quot;)\n\n # Try again.\n continue\n\n# Rest of input processing in the sample below.\n# ...\n</code></pre>\n<h3>Final Thoughts</h3>\n<p>With regards to your question about long lines and whether to split them, I have two recommendations, one specific and one general. As it specifically relates to Python, I would recommend you follow the <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8 Guidelines</a>, since they specifically define a standard Python code style. Generally speaking, I say focus on writing clean, effective, readable code that you (and whomever you program or work with) can read. What that ends up meaning specifically (i.e.., the specific allowable length of a line of code, etc.) is up to you.</p>\n<p>You should keep in mind, however, that the number of people willing to read your code is inversely proportional to how far you stray from established conventions.</p>\n<h3>Complete Sample</h3>\n<pre><code>from enum import Enum, auto, unique\n\n\nclass Player():\n \n def __init__(self, name: str, symbol: str):\n self.name = name\n self.symbol = symbol\n \n def __str__(self):\n return f&quot;{self.symbol}&quot;\n\nclass Cell():\n\n def __init__(self, player: Player = None):\n self.player = player\n \n def __str__(self):\n return f&quot;{self.player}&quot; if self.player is not None else &quot; &quot;\n\nclass Board():\n\n def __init__(self):\n self.cells = [ Cell() for i in range(9) ]\n\n def __str__(self):\n s = &quot;&quot;\n divider = &quot;-------\\n&quot;\n s += divider\n for i in range(3):\n s += &quot;|&quot;\n for j in range(3):\n s += str(self.cells[i*3+j]) + &quot;|&quot;\n s += &quot;\\n&quot; + divider\n return s\n\n@unique\nclass GameState(Enum):\n IN_PROGRESS = auto()\n PLAYER_ONE_WINS = auto()\n PLAYER_TWO_WINS = auto()\n TIE = auto()\n\nclass Game():\n\n def __init__(self):\n # Initialize the game's players.\n self.players = [ Player('Player One', 'X'), Player('Player Two', 'O') ]\n\n # Initialize the game board.\n self.board = Board()\n\n # Initialize the game state.\n self.state = GameState.IN_PROGRESS\n\n # Set the current player.\n self.current_player = self.players[0]\n\n def start(self):\n\n while self.state == GameState.IN_PROGRESS:\n\n # Display the current state of the board.\n print(self.board)\n \n # This loop handles the process of getting,\n # validating, and processing the current\n # player's selection for their next move.\n while True:\n # Get the current player's selection for\n # their next move. We wrap this in a\n # try/catch block because if the user inputs\n # anything other than an integer, the int\n # constructor will throw a ValueError\n # exception.\n try:\n player_selection = int(input(f&quot;{self.current_player.name}, please enter a number from 1 to 9: &quot;))\n except ValueError as e:\n # Notify the user of their error and\n # loop again.\n print(&quot;Please enter only an integer from 1 to 9.&quot;)\n\n # Try again.\n continue\n\n # Make sure the player's input is a number\n # from 1 to 9.\n if player_selection &lt; 1 or player_selection &gt; 9:\n # Notify them of their mistake and loop.\n print(&quot;Your selection must be a number from 1 to 9.&quot;)\n\n # Try again.\n continue\n\n # Make sure the selected cell actually\n # represents a legal move (i.e., the cell is\n # empty).\n if self.board.cells[player_selection-1].player is not None:\n # Notify the player of their mistake and\n # loop.\n print(&quot;The selected cell is not empty.&quot;)\n\n # Try again.\n continue\n\n # Mark the player's choice on the board.\n self.board.cells[player_selection-1].player = self.current_player\n\n # If the player's choice was successfully\n # processed, go ahead and break out of the\n # loop.\n break\n\n # Check whether the game state has changed,\n # either because someone won or because there\n # are no more legal moves left. We begin by\n # checking rows for a win.\n for i in range(3):\n if self.board.cells[i].player == self.board.cells[i+1].player == self.board.cells[i+2].player == self.current_player:\n self.state = GameState.PLAYER_ONE_WINS if self.current_player == self.players[0] else GameState.PLAYER_TWO_WINS\n \n # Check whether the game state changed so we can\n # skip the rest of the checks. We couldn't use a\n # break in the check because it would have only\n # broken us out of the for loop.\n if self.state != GameState.IN_PROGRESS:\n break\n \n # Check columns for a win.\n for i in range(3):\n if self.board.cells[i].player == self.board.cells[i+3].player == self.board.cells[i+6].player == self.current_player:\n self.state = GameState.PLAYER_ONE_WINS if self.current_player == self.players[0] else GameState.PLAYER_TWO_WINS\n\n # Again, break out of the loop to skip the rest\n # of the checks if the game state changed.\n if self.state != GameState.IN_PROGRESS:\n break\n\n # Check the diagonals for a win.\n if self.board.cells[0].player == self.board.cells[4].player == self.board.cells[8].player == self.current_player:\n self.state = GameState.PLAYER_ONE_WINS if self.current_player == self.players[0] else GameState.PLAYER_TWO_WINS\n break\n elif self.board.cells[2].player == self.board.cells[4].player == self.board.cells[6].player == self.current_player:\n self.state = GameState.PLAYER_ONE_WINS if self.current_player == self.players[0] else GameState.PLAYER_TWO_WINS\n break\n \n # Check for a tie by counting the empty cells\n # left.\n empty_cells = 0\n\n for i in range(3):\n for j in range(3):\n if self.board.cells[i*3+j].player is None:\n empty_cells += 1\n \n # If there are no more empty cells, and no one\n # has won yet, we've ended up with a tie.\n if empty_cells == 0:\n self.state = GameState.TIE\n break\n\n # If the game isn't over yet, move on to the\n # next player's turn.\n if self.state == GameState.IN_PROGRESS:\n self.current_player = self.players[0] if self.current_player is self.players[1] else self.players[1]\n\n # Display the final state of the board.\n print(self.board)\n\n # Handle a tie. You probably want a better message\n # here, but I had nothin'.\n if self.state == GameState.TIE:\n print(&quot;Tie. Game Over.&quot;)\n return\n \n # Handle the case where a player actually won.\n print(f&quot;{self.current_player.name} wins!&quot;)\n\n\n# Initialize and start the game only if the application is\n# being run as a script. Otherwise, we simply import the\n# class definitions.\nif __name__ == '__main__':\n # Initialize the game.\n game = Game()\n\n # Start the game.\n game.start()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T15:22:41.183", "Id": "266328", "ParentId": "266297", "Score": "2" } }, { "body": "<h1><code>list</code> vs <code>dict</code></h1>\n<p>I think this is a good example of when to use a <code>list</code> instead of <code>dict</code>. If you're in Python 3.6+, you <em>could</em> rely on the dictionary being ordered, but I think it makes a bit more sense as a list, since I'm not really going to rely on key access all the time except for maybe choosing a spot on the board for my move.</p>\n<p>If the board is simply a list of empty strings:</p>\n<pre class=\"lang-py prettyprint-override\"><code>board = [['' for _ in range(3)] for _ in range(3)]\n</code></pre>\n<p>It's easy to format the board and check for win conditions. Let's start with displaying the board:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def display_board(board):\n print('\\n---\\n'.join(('|'.join(row) for row in board)))\n</code></pre>\n<p>Now, I can simply rely on the order and join each cell in a row with a pipe character '|', and join each row with the newline-separated dashed line.</p>\n<p>The real benefit is for win-checking. You can simplify it down into three separate cases: diagonals, rows, and columns</p>\n<h2>Check Diagonal Wins</h2>\n<p>To check the diagonal win, we are enumerating the rows and checking the column by using the index. This allows us to very easily check the down-and-right diagonal:</p>\n<pre class=\"lang-py prettyprint-override\"><code>marker = 'x'\nboard = [\n ['x', '', ''],\n ['', 'x', ''],\n ['', '', 'x']\n]\n\nall(row[i] == marker for i, row in enumerate(board))\nTrue\n</code></pre>\n<p>And to check the up-and-left diagonal, we only need to reverse the order of the rows in the board:</p>\n<pre class=\"lang-py prettyprint-override\"><code>board = [\n ['', '', 'x'],\n ['', 'x', ''],\n ['x', '', '']\n]\n\nall(row[i] == marker for i, row in enumerate(reversed(board)))\nTrue\n</code></pre>\n<p>For vertical wins, we need only fix the index in place as we check each column:</p>\n<pre class=\"lang-py prettyprint-override\"><code>all(row[0] == marker for row in board) # check first column\nall(row[1] == marker for row in board) # and so on\n\n# we can condense this down to an any statment\nany(all(row[i] == marker for row in board) for i in range(3))\n</code></pre>\n<p>And horizontal wins are the easiest of them all:</p>\n<pre class=\"lang-py prettyprint-override\"><code>any(all(cell == marker for cell in row) for row in board)\n</code></pre>\n<p>Putting this all together:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def check_win(board, marker):\n # Check horizontal\n if any(all(cell == marker for cell in row) for row in board):\n return True\n # Check vertical\n elif any(all(row[i] == marker for row in board) for i in range(3)):\n return True\n # check diagonals\n elif all(row[i] == marker for i, row in enumerate(board)):\n return True\n elif all(row[i] == marker for i, row in enumerate(reversed(board))):\n return True\n else:\n return False\n</code></pre>\n<h1>User Choice</h1>\n<p>I think displaying the board as a set of available choices might make it a bit easier for the user to pick where to move next. I like your idea of choosing 0-9, so let's build on the <code>display_board</code> function to get a set of available moves:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_available_moves(board):\n # Since we want moves 0-9, we can use a for loop with enumerate\n # to adjust the numbers that get displayed\n k = 0\n moves = {}\n printable_board = []\n\n for i, row in enumerate(board):\n to_print = []\n for j, cell in enumerate(row, start):\n if not cell:\n # The if not cell checks if a cell is taken already\n to_print.append(f'{k}')\n moves[k] = (i, j)\n else:\n to_print.append(cell)\n k += 1\n printable_board.append(to_print)\n\n display_board(printable_board)\n return moves\n\n\n# Now, you can display the available moves and have the user\n# choose directly\nboard = [\n ['x', 'o', ''],\n ['o', '', 'x'],\n ['o', 'x', '']\n]\n\navailable = get_available_moves(board)\n\n# prints this\nx|o|2\n---\no|4|x\n---\no|x|8\n\n# It's easy to check if there are any moves left\nif not available:\n print(&quot;No moves left! Game over!&quot;)\n\n# And also relatively easy to go into a loop to\n# check user input\nwhile True:\n try:\n choice = int(\n input(&quot;Choose a move from {', '.join(available)}: &quot;)\n )\n # this will raise a KeyError if an invalid choice is selected\n move = available[choice]\n except:\n print(&quot;Invalid choice, try again&quot;)\n else:\n break\n</code></pre>\n<p>Last, to actually make the move</p>\n<pre class=\"lang-py prettyprint-override\"><code>row, col = move\nboard[row][col] = player.marker\n</code></pre>\n<h1>Switching from player to player</h1>\n<p>This is easily accomplished by using <code>itertools.cycle</code> while playing the game:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import cycle\n\ndef main():\n board = [['' for _ in range(3)] for _ in range(3)]\n\n players = cycle(\n [Player(name='player1', marker='x'), \n Player(name='player2', marker='o')]\n )\n \n # this is an infinite loop\n for player in players:\n print(f&quot;{player.name}'s turn&quot;)\n \n available = get_available_moves(board)\n \n if not available:\n print(&quot;No moves left, draw!&quot;)\n break\n\n row, col = choose_move(available)\n board[row][col] = player.marker\n\n display_board(board)\n\n if board_has_win(board=board, marker=player.marker):\n print(f&quot;{player.name} wins!&quot;)\n break\n</code></pre>\n<h1>Wrapping Board into a Class</h1>\n<p>You made the right decision by wrapping <code>Board</code> into a class, it gives you a few benefits to do so. First, <code>display_board</code> becomes the <code>__str__</code> dunder method. Next, we can use a few other dunder methods to clean up attribute access:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Board:\n def __init__(self):\n self.board = [[' ' for _ in range(3)] for _ in range(3)]\n\n\n def __str__(self):\n return '\\n---\\n'.join(('|'.join(row) for row in self))\n\n\n def __getitem__(self, attr):\n # allows us to index Board instances\n return self.board[attr]\n\n\n def __len__(self):\n return len(self.board)\n</code></pre>\n<p>And since we've defined <code>__len__</code> and <code>__getitem__</code>, <code>Board</code> is now iterable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>board = Board()\n\nfor row in board:\n print(row)\n</code></pre>\n<p>Then, we can put most of the functions that use board into the class. <code>check_win</code> becomes <code>has_win</code>, since that naming implies that it will return a boolean. We can also include checking for available moves, which cleans up the functions a decent bit:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Board:\n ~snip~\n def get_available_moves(self):\n k = 0\n moves = {}\n # make a copy of the board so that we\n # don't overwrite the actual game board\n printable_board = Board()\n\n for i, row in enumerate(self):\n for j, cell in enumerate(row, start):\n # check if cell is occupied\n if not cell.strip():\n printable_board[i][j] = f&quot;{k}&quot;\n moves[k] = (i, j)\n else:\n printable_board[i][j] = cell\n\n k += 1\n\n print(printable_board)\n return moves\n\n\n def has_win(self, marker):\n &quot;&quot;&quot;\n Check if there is a win present on the board, \n return True if so, otherwise False\n &quot;&quot;&quot;\n # Check horizontal\n if any(all(cell == marker for cell in row) for row in self):\n return True\n # Check vertical\n elif any(all(row[i] == marker for row in self) for i in range(3)):\n return True\n # check diagonals\n elif all(row[i] == marker for i, row in enumerate(self)):\n return True\n elif all(row[i] == marker for i, row in enumerate(reversed(self))):\n return True\n else:\n return False \n</code></pre>\n<h1>Player class</h1>\n<p>I think that you could use <code>namedtuple</code> for <code>Player</code>, since you are just holding the name and marker for each player:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\n\nPlayer = namedtuple('Player', ['name', 'marker'])\n\nplayer1 = Player(name=&quot;John&quot;, marker='x')\nplayer2 = Player(name=&quot;Anne&quot;, marker='o')\n</code></pre>\n<p>The state of each player isn't mutable, so I don't need <code>setattr</code> access on any of the attributes. It gives me a clean dot access to the marker attribute, and it prints nicely, too.</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(player1)\nPlayer(name='John', marker='x')\n\nplayer1.marker\nx\n</code></pre>\n<h1>All together</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\nfrom itertools import cycle\n\n\nPlayer = namedtuple('Player', ['name', 'marker'])\n\nclass Board:\n def __init__(self):\n self.board = [[' ' for _ in range(3)] for _ in range(3)]\n\n\n def __str__(self):\n return '\\n-----\\n'.join(('|'.join(row) for row in self))\n\n\n def __getitem__(self, attr):\n return self.board[attr]\n\n\n def __len__(self):\n return len(self.board)\n\n\n def get_available_moves(self):\n &quot;&quot;&quot;Returns a dictionary of available moves\n and prints an enumerated board&quot;&quot;&quot;\n k = 0\n moves = {}\n # make a copy of the board so that we\n # don't overwrite the actual game board\n printable_board = Board()\n\n for i, row in enumerate(self):\n for j, cell in enumerate(row):\n # check if cell is occupied\n if not cell.strip():\n printable_board[i][j] = f&quot;{k}&quot;\n moves[k] = (i, j)\n else:\n printable_board[i][j] = cell\n k += 1\n\n print(printable_board)\n return moves\n\n\n def has_win(self, marker):\n &quot;&quot;&quot;\n Check if there is a win present on the board, \n return True if so, otherwise False\n &quot;&quot;&quot;\n # Check horizontal\n if any(all(cell == marker for cell in row) for row in self):\n return True\n # Check vertical\n elif any(all(row[i] == marker for row in self) for i in range(3)):\n return True\n # check diagonals\n elif all(row[i] == marker for i, row in enumerate(self)):\n return True\n elif all(row[i] == marker for i, row in enumerate(reversed(self))):\n return True\n else:\n return False \n\n\ndef choose_move(moves):\n &quot;&quot;&quot;Prompt player to choose a move from a set of available spots&quot;&quot;&quot;\n while True:\n try:\n choice = int(\n input(f&quot;Choose a move from {', '.join(map(str, moves))}: &quot;)\n )\n # this will raise a KeyError if an invalid choice is selected\n move = moves[choice]\n except:\n print(&quot;Invalid choice, try again&quot;)\n else:\n break\n return move\n \n\n\ndef main():\n board = Board()\n\n players_iter = cycle(\n [Player(name='player1', marker='x'), \n Player(name='player2', marker='o')]\n )\n\n # this is an infinite loop\n for player in players_iter:\n print(f&quot;{player.name}'s turn&quot;)\n\n available = board.get_available_moves()\n\n # check if there are any spots left\n if not available:\n print(&quot;No moves left, draw!&quot;)\n break\n\n row, col = choose_move(available)\n board[row][col] = player.marker\n\n print(board)\n\n if board.has_win(marker=player.marker):\n print(f&quot;{player.name} wins!&quot;)\n break\n\n\nif __name__ == &quot;__main__&quot;:\n # play the game\n main()\n \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T14:53:46.153", "Id": "266356", "ParentId": "266297", "Score": "2" } } ]
{ "AcceptedAnswerId": "266328", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T20:13:03.367", "Id": "266297", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "tic-tac-toe - alternative ways to make a board, logical and phyiscal lines" }
266297
<p>I'm looking for critiques or different ways I could approach writing a deck builder script. I wrote script to shuffle a deck of cards, then draw cards from the top of deck, drawn cards are then removed from deck and placed into discard.</p> <pre><code>const cardGame = { values: [ 'Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Joker', 'Queen', 'King' ], suits: [ 'Clubs', 'Spades', 'Hearts', 'Diamonds' ], deck: [], discard: [], buildDeck() { const { deck, values, suits } = this; //clear deck and discard pile deck.splice(0, 52); this.discard.splice(0, 52); //regenerate/build deck for (let suit of suits) { for (let value of values) { deck.push({ value, suit }); } } }, shuffle() { const { deck } = this; for (let i = deck.length - 1; i &gt; 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [ deck[i], deck[j] ] = [ deck[j], deck[i] ]; } }, // drawCard(numCards = 1) { // const { deck, discard } = this; // for (let i = 0; i &lt; numCards; i++) { // let card = deck[i]; // deck.splice(i, 1); // console.log(card); // discard.push(card); // } // console.log(deck.length); // }, drawCard(numCards = 1) { const { deck, discard } = this; const removedCards = deck.splice(0, numCards); for (let card of removedCards) { console.log(card); discard.push(card); } console.log(deck.length); }, start() { this.buildDeck(); this.shuffle(); }, shuffleDraw(numCards) { this.drawCard(numCards); this.shuffle(); }; cardGame.start(); </code></pre> <p>I commented out what I thought the ideal way to write the drawCard() method. This was because I could not get it to work. The for loop would skip over every other index, for example:</p> <p><a href="https://i.stack.imgur.com/vHfye.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vHfye.jpg" alt="enter image description here" /></a></p> <p>I am not sure why this is? I tried searching for an explanation, but struggled to find one. If anyone can explain why this is or refer to a source to explain why it is skipping every other index? Thank you</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T21:48:11.447", "Id": "526055", "Score": "2", "body": "Take this question to StackOverflow and with the code working, bring it back here to Code Review. Situations like this is why there are separate forums." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T22:03:35.907", "Id": "526056", "Score": "1", "body": "Do not add or remove items from an array while iterating ( `for`, `forEach`, etc. ) said array. Changing the value of an item is ok, but not adding or removing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T02:52:06.510", "Id": "526058", "Score": "1", "body": "One nice way to draw cards is to map to the unicode range that has cards (take care to skip over \"knight\") and use html entities (`&#0xABCD;` or whatever the number actually is...)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T20:31:10.157", "Id": "266299", "Score": "0", "Tags": [ "javascript" ], "Title": "JavaScript Deck Builder: Shuffle, Draw Cards" }
266299
<p><strong>Desired output:</strong> Animate the wave forms, but use less resources.</p> <p><strong>Any bugs:</strong> There are no bugs that I know of.</p> <p>I tied searching google for &quot;use less setIntervals in my project&quot; and <a href="https://www.thecodeship.com/web-development/alternative-to-javascript-evil-setinterval/" rel="nofollow noreferrer">found this code</a></p> <pre><code>function interval(func, wait, times){ var interv = function(w, t){ return function(){ if(typeof t === &quot;undefined&quot; || t-- &gt; 0){ setTimeout(interv, w); try{ func.call(null); } catch(e){ t = 0; throw e.toString(); } } }; }(wait, times); setTimeout(interv, wait); }; </code></pre> <p><strong>Usage:</strong> This replaces all of the setIntervals but the waves do not look random.</p> <pre><code>interval(function(){ peak_wave( Math.floor((Math.random() * (30) + 1)) , Math.floor((Math.random() * (200) + 150))); peak_wave( Math.floor((Math.random() * (30) + 1)) , Math.floor((Math.random() * (200) + 150))); },1200, 999); </code></pre> <p><strong>Problem:</strong> The code is a resource hog. I am looking for a way to optimize JavaScript (if JavaScript is the issue.)</p> <p>Research: Looked for ways to reduce the number of set intervals I am using.</p> <p>What I’ve tried: Setup a loop that creates the set intervals but I ran into the Issue where javascript blows through all the setintervals and they all start at the time time and fire at once. That is a HUGE resource issue.</p> <p><strong>Inspiration:</strong> YouTube: <a href="https://i.stack.imgur.com/NcXCy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NcXCy.png" alt="enter image description here" /></a> Link to video: <a href="https://www.youtube.com/watch?v=-475XHUgkiQ&amp;t=22782s&amp;ab_channel=APMusic" rel="nofollow noreferrer">https://www.youtube.com/watch?v=-475XHUgkiQ&amp;t=22782s&amp;ab_channel=APMusic</a></p> <p><strong>My Code:</strong> CodePen.io: <a href="https://i.stack.imgur.com/1Gnan.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Gnan.png" alt="enter image description here" /></a> Link to codepen.io: <a href="https://codepen.io/ac0ua/pen/BaReZEx" rel="nofollow noreferrer">https://codepen.io/ac0ua/pen/BaReZEx</a></p> <p>Thank you. Any help would be appreciated. I want to learn.</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"; function peak_wave(wave_id, wave_height) { //console.log(wave_height); var wave = document.getElementsByClassName('w' + wave_id); var wave_height_buffer = wave_height; var a = 0; var i = 0; var counter = 0; var color = "white"; const waveLeftSide_arr = range(wave_id - 10, 10).reverse(); const waveRightSide_arr = range(wave_id + 1, 10); if (wave) { wave[0].style.height = wave_height + "px"; wave[0].style.background = color; wave[0].classList.toggle("l-active"); wave[1].style.height = wave_height + "px"; wave[1].style.background = color; wave[1].classList.toggle("r-active"); } var firstWaveClass = ""; for (let i of waveLeftSide_arr) { if (i &lt;= -1) { i = 0 } counter = counter + 5 wave_height = wave_height - 10 - counter; const targetElement = document.querySelector('.w' + i); if (targetElement) { // var color = "yellowgreen"; document.getElementsByClassName('w' + i)[0].style.height = (wave_height) + "px"; document.getElementsByClassName('w' + i)[0].style.background = color; document.getElementsByClassName('w' + i)[1].style.height = (wave_height) + "px"; document.getElementsByClassName('w' + i)[1].style.background = color; } } wave_height = wave_height_buffer; counter = 0 for (let a of waveRightSide_arr) { if (a &lt;= -1) { a = 0 } counter = counter + 5 wave_height = wave_height - 10 - counter; const targetElement = document.querySelector('.w' + a); if (targetElement) { if (firstWaveClass == "") { firstWaveClass = "w" + a; } // var color = "deeppinnk"; document.getElementsByClassName('w' + a)[0].style.height = (wave_height) + "px"; document.getElementsByClassName('w' + a)[0].style.background = color; document.getElementsByClassName('w' + a)[1].style.height = (wave_height) + "px"; document.getElementsByClassName('w' + a)[1].style.background = color; } } } function doesExist(class_name) { var element = document.getElementsByClassName(class_name) if (element &gt; 0) { return true; } else { return false; } } setInterval(function() { var els = document.getElementsByClassName("wave"); for (var i = 0; i &lt; els.length; i++) { // var NewHeight = els[i].offsetHeight - 10; // if(NewHeight &lt;= 0){NewHeight = 0 } els[i].style.height = 0 + "px"; els[i].style.background = "white"; els[i].classList.remove("l-active"); els[i].classList.remove("r-active"); } }, 500); var circle = document.getElementsByClassName("circle")[0]; setInterval(function() { circle.style.transform = 'rotate(' + Math.floor((Math.random() * (180) + 1)) + 'deg)'; }, 120); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))); }, 1200); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))) }, 1300); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))) }, 1400); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))) }, 1500); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))) }, 100600); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))) }, 100700); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))) }, 100800); setInterval(function() { peak_wave(Math.floor((Math.random() * (30) + 1)), Math.floor((Math.random() * (200) + 150))) }, 100900); //peak_wave(50, 300); function range(start, count) { if (arguments.length == 1) { count = start; start = 0; } var foo = []; for (var i = 0; i &lt; count; i++) { foo.push(start + i); } return foo; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* default template -- enable SCSS*/ html, body { width: 100%; height: 100%; margin: 0; padding: 0; background: #424242; color: white; font-family: bungee; display: flex; flex-direction: column; } html:before, body:before { content: " "; position: absolute; top: -40px; left: -60px; width: 50%; height: 400px; border-radius: 50%; background: linear-gradient(to bottom right, deepskyblue 20%, deepskyblue 50%, white 80%); filter: blur(80px); mix-blend-mode: overlay; } html header, body header { width: 100%; display: grid; place-items: center; } html section, body section { width: 100%; display: grid; place-items: center; } html section #wrapper, body section #wrapper { display: flex; place-items: center; flex-wrap: nowrap; justify-content: center; height: 200px; width: 80%; position: relative; margin-inline: 20px; } html section #wrapper:after, body section #wrapper:after { content: ""; position: absolute; background: white; background: radial-gradient(circle, white 26%, rgba(2, 0, 36, 0) 95%); height: 3px; width: 100%; } html section #wrapper #left-wrapper, body section #wrapper #left-wrapper { display: flex; flex-wrap: nowrap; justify-content: space-around; align-items: center; width: 45%; height: 100px; } html section #wrapper #left-wrapper span, body section #wrapper #left-wrapper span { display: inline-block; width: 5px; background: white; transition: height 0.3s cubic-bezier(0.83, 1.5, 0.63, -0.71); } html section #wrapper #right-wrapper, body section #wrapper #right-wrapper { display: flex; flex-wrap: nowrap; justify-content: space-around; align-items: center; width: 45%; height: 100px; } html section #wrapper #right-wrapper span, body section #wrapper #right-wrapper span { display: inline-block; min-width: 2px; background: white; transition: height 0.3s cubic-bezier(0.83, 1.5, 0.63, -0.71); } html section #wrapper .l-active, body section #wrapper .l-active { position: relative; } html section #wrapper .l-active:before, body section #wrapper .l-active:before { content: ""; margin-left: -100px; position: absolute; top: 50%; transform: translateY(-50%); height: 60%; width: 100px; border-top-left-radius: 25% 10%; border-bottom-left-radius: 25% 10%; background: radial-gradient(circle at 100% 53%, yellow 15%, #00bcd4 34%, rgba(238, 130, 238, 0) 100%); filter: blur(10px); z-index: 1; mix-blend-mode: overlay; transistion: 0.3s ease; } html section #wrapper .l-active:after, body section #wrapper .l-active:after { content: ""; margin-left: -250px; position: absolute; top: 50%; transform: translateY(-50%); height: 30%; width: 200px; border-top-left-radius: 25% 10%; border-bottom-left-radius: 25% 10%; background: radial-gradient(circle at 100% 53%, #ff00ef 15%, #005cd4 34%, rgba(238, 130, 238, 0) 100%); filter: blur(20px); z-index: 1; mix-blend-mode: overlay; transistion: 0.4s ease; } html section #wrapper .r-active, body section #wrapper .r-active { position: relative; } html section #wrapper .r-active:before, body section #wrapper .r-active:before { content: ""; margin-right: 100px; position: absolute; top: 50%; transform: translateY(-50%); height: 60%; width: 100px; border-top-left-radius: 25% 10%; border-bottom-left-radius: 25% 10%; background: radial-gradient(circle at 0% 53%, yellow 34%, #00bcd4 15%, rgba(238, 130, 238, 0) 100%); filter: blur(10px); z-index: 1; mix-blend-mode: overlay; transistion: 0.3s ease; } html section #wrapper .r-active:after, body section #wrapper .r-active:after { content: ""; margin-right: 250px; position: absolute; top: 50%; transform: translateY(-50%); height: 30%; width: 200px; border-top-left-radius: 25% 10%; border-bottom-left-radius: 25% 10%; background: radial-gradient(circle at 0% 53%, #ff00ef 34%, #005cd4 15%, rgba(238, 130, 238, 0) 100%); filter: blur(20px); z-index: 1; mix-blend-mode: overlay; transistion: 0.4s ease; } html section #wrapper .circle, body section #wrapper .circle { box-sizing: border-box; width: 100px; aspect-ratio: 1/1; border-radius: 50%; border: 10px solid white; position: relative; z-index: 2; display: grid; place-items: center; background: conic-gradient(from 90deg at 50% 50%, #ffff00 2%, #00bcd4 7%, #ee82ee 21%, #ffffff 26%, #ffffff 41%, #ffffff 49%, #fffc00 51%, #00bcd4 64%, #ee82ee 72%, #ffffff 77%, #ffffff 100%); transform: rotate(10deg); transition: all 0.2s cubic-bezier(0.83, 1.5, 0.63, -0.71); } html section #wrapper .circle .outter-record, body section #wrapper .circle .outter-record { box-sizing: border-box; width: 65px; height: 65px; border-radius: 50%; border: 5px solid white; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: grid; place-items: center; background: conic-gradient(from 90deg at 50% 50%, #ffff00 2%, #00bcd4 7%, #ee82ee 21%, #ffffff 26%, #ffffff 41%, #ffffff 49%, #fffc00 51%, #00bcd4 64%, #ee82ee 72%, #ffffff 77%, #ffffff 100%); } html section #wrapper .circle .outter-record .inner-record, body section #wrapper .circle .outter-record .inner-record { background: white; box-sizing: border-box; width: 45px; height: 45px; border-radius: 50%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: grid; place-items: center; } html footer, body footer { width: 100%; display: grid; place-items: center; } html h1, body h1 { color: deepskyblue; } html h1 span, body h1 span { color: yellowgreen; } html h1 font, body h1 font { color: yellowgreen; font-family: Montserrat; font-weight: 700; } html h2, body h2 { color: deepskyblue; font-family: Montserrat; } html h2 span, body h2 span { color: yellowgreen; } html h2 font, body h2 font { color: yellowgreen; font-weight: 700; } /* default template end */ .wave { background: deepskyblue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="preconnect" href="https://fonts.googleapis.com"&gt; &lt;link rel="preconnect" href="https://fonts.gstatic.com" crossorigin&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Bungee&amp;display=swap" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;700&amp;display=swap" rel="stylesheet"&gt; &lt;header&gt; &lt;h1&gt;Audio &lt;span&gt;Candy&lt;/span&gt;&lt;/h1&gt; &lt;/header&gt; &lt;Section&gt; &lt;h2&gt;CSS&lt;span&gt; / &lt;/span&gt;Javascript &lt;font&gt; Animation&lt;/font&gt; &lt;/h2&gt; &lt;div id="wrapper"&gt; &lt;div id="left-wrapper"&gt; &lt;span class="wave w50"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w49"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w48"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w47"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w46"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w45"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w44"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w43"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w42"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w41"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w40"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w39"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w38"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w37"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w36"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w35"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w34"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w33"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w32"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w31"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w30"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w29"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w28"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w27"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w26"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w25"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w24"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w23"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w22"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w21"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w20"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w19"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w18"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w17"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w16"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w15"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w14"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w13"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w12"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w11"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w10"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w9"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w8"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w7"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w6"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w5"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w4"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w3"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w2"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w1"&gt;&amp;nbsp;&lt;/span&gt; &lt;/div&gt; &lt;div class="circle"&gt; &lt;div class="outter-record"&gt; &lt;div class="inner-record"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="right-wrapper"&gt; &lt;span class="wave w1"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w2"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w3"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w4"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w5"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w6"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w7"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w8"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w9"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w10"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w11"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w12"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w13"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w14"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w15"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w16"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w17"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w18"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w19"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w20"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w21"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w22"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w23"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w24"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w25"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w26"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w27"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w28"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w29"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w30"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w31"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w32"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w33"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w34"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w35"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w36"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w37"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w38"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w39"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w40"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w41"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w42"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w43"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w44"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w45"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w46"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w47"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w48"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w49"&gt;&amp;nbsp;&lt;/span&gt; &lt;span class="wave w50"&gt;&amp;nbsp;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Section&gt; &lt;footer&gt;James learning &lt;/footer&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T07:26:00.050", "Id": "526491", "Score": "1", "body": "[Posting a follow-up](https://codereview.meta.stackexchange.com/q/1065/71574). [What you can and cannot do after receiving answers](https://codereview.meta.stackexchange.com/a/1765/71574)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T23:51:20.643", "Id": "526552", "Score": "0", "body": "posted a follow-up question: https://stackoverflow.com/questions/68977771/create-random-wave-forms-using-canvas-moveto-and-lineto-left-and-right-side" } ]
[ { "body": "<h2>CSS Animation</h2>\n<p>Complex CSS animation suffers from a performance problem as it is a general-purpose solution to what often is a very optimization-focused problem.</p>\n<p>You have 100 animated elements. From CSS's view point each element represents a separate uncoordinated animation, each of which requires animating, rendering, and compositing. This works against the GPU which is optimized to render a few highly complex items, rather than many simple items.</p>\n<p>Because CSS is such a generalized animation engine you also tend to lose fine control.</p>\n<p>Animation tends to get stuck to a set of static, pre-computed sequences.</p>\n<h2>Review</h2>\n<h3>JavaScript</h3>\n<p>The function <code>peak_wave</code> is preforming very slow DOM queries inside what should be performance-oriented loops.</p>\n<p>Store the result of queries in variables once when you code starts, then use the stored values to reference the elements rather than use the document tree queries inside performance critical code.</p>\n<h3>JS Style</h3>\n<ul>\n<li><p>Good to see that you use strict mode.</p>\n</li>\n<li><p>JS naming convention is to use <code>camelCase</code> not <code>snake_case</code></p>\n</li>\n<li><p>Don't repeat code.</p>\n<ul>\n<li><p>The function <code>peak_wave</code> has two near identical for loops. These loops should be as a separate function</p>\n</li>\n<li><p>The functions in 8 of the <code>setInterval</code> callbacks are identical. They should be one function.</p>\n<p>Example</p>\n<pre><code>const randomLevel = () =&gt; {\n peakWave(Math.random() * 30 + 1 | 0, Math.random() * 200 + 150 | 0);\n}\n[1200,1300,1400,1500,10600,10700,10800,10900].forEach(time =&gt; {\n setInterval(randomLevel, time)\n});\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>You have code that is never called <code>doesExist</code>. Never include silent code.</p>\n</li>\n<li><p>The are many places where you have too many <code>()</code> for example <code>Math.floor((Math.random() * (30) + 1))</code> can be <code>Math.floor(Math.random() * 30 + 1)</code></p>\n</li>\n</ul>\n<h2>Alternative</h2>\n<p>I will not rewrite your code as it is too inefficient. Rather I present an alternative approach that requires no CSS animation at all.</p>\n<h3>Use 2D canvas.</h3>\n<p>Ideally for the best result the animation should be rendered using a WebGL2 context derived from the Canvas element. However WebGL is very verbose and requires a lot of support code just to get started.</p>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D\" rel=\"nofollow noreferrer\" title=\"MDN Web API's CanvasRenderingContext2D\">CanvasRenderingContext2D</a> is an excellent API for animation and can deliver very complex animations well beyond what even the best CSS can deliver.</p>\n<h3>The example</h3>\n<p>Below is an example that is similar to the functionality of your code.</p>\n<p>It adds a canvas and uses the 2D API to render the animation.</p>\n<p>To highlight the addition complexity I have made the level bars as dynamic as possible. There are also dozens of setup options that allow quick and easy modifications that would take a long time if you add to change the CSS, HTML, and JS.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const barsDefault = { // colors Must be 4 char CSS hash color eg `#F00` is red\n count: 60,\n meanSize: 16, // number of bars per mean bucket (mean is used for bg glows)\n glowDecay: 0.3, // pulls down mean bucket values\n glows: [\n [\"#F00\", \"#40F\", \"#00F\", \"#00F\", \"#00F\", \"#00F\"],\n [\"#0F0\", \"#0F8\", \"#06F\", \"#00F\", \"#00F\", \"#00F\"],\n [\"#40F\", \"#00F\", \"#00F\", \"#00F\"],\n ],\n centerRadius: 35,\n decay: 0.1,\n innerHeightPad: 10,\n color: \"#FFF\", // Must be 4 char CSS hash color\n barWidth: 0.6, // fraction of bar space to contain bar\n centerBarWidth: 10,\n centerInset: 0.9, // as fraction of radius\n centerInsetWidth: 0.2, // as fraction of radius\n centerInsetAng: 0.5, // as fraction of 180 deg\n centerRotateMax: 10, // as fraction of 180 deg\n barFeq: 1 / 8, // odds per frame of new position\n barPeakWidth: 10, // max number of bars to spread movement. Must be whole number\n barPeakWidthMin: 2, // min number of bars to spread movement. Must be whole number &gt;= 1\n barPeakSlide: 3, // twice Max rate that level drive slides along bars\n barLevel: 1 / 12, // Max bar volume add\n barLevelComp: 1 / 2, // drives bar volume compressor n. Is logarithmic. Where 0 &lt; n &lt; Infinity, louder as nit gets smaller\n levelDriveDecay: 0.01, // rate that level drivers decay Must be 0 &lt; n &lt;= 1\n levelDriveMin: 0.05, // min level drive. Below this level driver turns off. Must be 0 &lt; n\n glowOffsetRate: 0.001, // as radians per frame\n glowAlpha: 0.3, \n};\n\n// Math Helper util\nconst polarArg = (ang, dist, x = 0, y = 0) =&gt; ([Math.cos(ang) * dist + x, Math.sin(ang) * dist + y]);\nconst eCurve = (v, p = 2, vp) =&gt; v &lt; 0 ? 0 : v &gt; 1 ? 1 : (vp = v ** p) / (vp + (1 - v) ** p);\nconst PI = Math.PI, TAU = PI * 2;\n\nrequestAnimationFrame(renderLoop);\nconst bars = Bars(canvasContainer);\naddEventListener(\"resize\", bars.resize);\nfunction renderLoop() {\n bars.update();\n bars.draw();\n requestAnimationFrame(renderLoop);\n}\n\nfunction Bars(container, config = {}) {\n var bounds, w, h;\n const canvas = document.createElement(\"canvas\")\n const ctx = canvas.getContext(\"2d\");\n container.appendChild(canvas);\n function resize() {\n bounds = container.getBoundingClientRect();\n w = bounds.width;\n h = bounds.height;\n Object.assign(Object.assign(canvas, {\n width: w,\n height: h\n }).style, {\n position: \"absolute\",\n top: \"0px\",\n left:\"0px\"\n });\n ctx.lineCap = ctx.lineJoin = \"round\";\n centerBar = ctx.createLinearGradient(0, 0,w, 0);\n centerBar.addColorStop(0, setup.color + \"0\");\n centerBar.addColorStop(0.2, setup.color + \"A\");\n centerBar.addColorStop(0.4, setup.color + \"F\");\n centerBar.addColorStop(0.6, setup.color + \"F\");\n centerBar.addColorStop(0.8, setup.color + \"A\");\n centerBar.addColorStop(1, setup.color + \"0\");\n }\n const setup = {\n ...barsDefault,\n ...config,\n };\n resize();\n const levels = new Array(setup.count).fill(0);\n const levelDrivers = []; \n const meanSize = setup.count /setup.meanSize | 0;\n const means = new Array(setup.count / meanSize | 0).fill(0);\n var rotate = 0, rotatePos = 0, rotateDelta = 0, totalLevel = 0, glowAng1 = 0, glowAng2 = 0;\n \n // create center bar gradient\n var centerBar;\n \n // create background glow gradients\n const glows = means.map((m, i) =&gt; {\n const g = ctx.createRadialGradient(0, 0, 4, 0, 0, h * 0.5);\n const cols = setup.glows[i % setup.glows.length];\n cols.forEach((col, i) =&gt; {\n const alpha = Math.min(1, Math.max(0, i / (cols.length -1)));\n g.addColorStop(alpha, col + ((1-eCurve(alpha)) * 15 | 0).toString(16));\n });\n return g;\n });\n \n // create center Circle\n const centerCircle = new Path2D();\n {\n const cc = centerCircle;\n const CR = setup.centerRadius, CR1 = CR * setup.centerInset, CR2 = CR * (setup.centerInset - setup.centerInsetWidth);\n const ANG = setup.centerInsetAng * 0.5 * PI;\n cc.arc(0, 0, CR + 1, 0, TAU);\n cc.moveTo(...polarArg(-ANG, CR1))\n cc.arc(0, 0, CR1, -ANG, ANG);\n cc.arc(0, 0, CR2, ANG, -ANG, true);\n cc.moveTo(...polarArg(PI - ANG, CR1))\n cc.arc(0, 0, CR1, PI - ANG, PI + ANG);\n cc.arc(0, 0, CR2, PI + ANG, PI - ANG, true);\n }\n \n return Object.freeze({\n update() {\n updateCenter();\n updateBars();\n },\n draw() {\n ctx.setTransform(1,0,0,1,0,0);\n ctx.clearRect(0, 0, w, h);\n ctx.fillStyle = setup.color;\n drawGlows();\n drawCircle();\n drawBars();\n },\n resize,\n });\n \n \n function updateBars() {\n var i = setup.count, pos, level, move, bPW, head = 0, tail = 0;\n const decay = 1 - setup.decay;\n totalLevel = 0; // global to Bars\n while (i--) {\n means[i / meanSize | 0] += levels[i];\n totalLevel += levels[i];\n levels[i] *= decay;\n }\n if (Math.random() &lt; setup.barFeq) {\n const pos = setup.count * Math.random() | 0;\n const level = Math.random() ** setup.barLevelComp * setup.barLevel;\n levelDrivers.push([\n pos,\n level,\n (Math.random() - 0.5) * setup.barPeakSlide,\n Math.random() * (setup.barPeakWidth - setup.barPeakWidthMin) + setup.barPeakWidthMin | 0,\n ]);\n }\n while (head &lt; levelDrivers.length) {\n const lDrive = levelDrivers[head++];\n [pos, level, move, bPW] = lDrive; // bPW for bar Peak Width\n lDrive[0] = pos += move;\n pos |= 0;\n pos &gt;= 0 &amp;&amp; pos &lt; setup.count &amp;&amp; (levels[pos] = Math.min(1, levels[pos] + level));\n i = 1;\n while (i &lt; bPW) {\n const levelAdd = eCurve(1 - i / bPW) * level;\n pos + i &lt; setup.count &amp;&amp; (levels[pos + i] = Math.min(1, levels[pos + i] + levelAdd));\n pos - i &gt;= 0 &amp;&amp; (levels[pos - i] = Math.min(1, levels[pos - i] + levelAdd));\n i++;\n }\n lDrive[1] = (level *= 1 - setup.levelDriveDecay);\n if (level &gt; setup.levelDriveMin &amp;&amp; pos + bPW &gt;= 0 &amp;&amp; pos - bPW &lt; setup.count) {\n levelDrivers[tail++] = lDrive;\n }\n }\n levelDrivers.length = tail;\n } \n function updateCenter() {\n rotatePos = ((totalLevel / setup.count) - 0.5) * setup.centerRotateMax * PI;\n rotate += (rotateDelta = (rotateDelta += (rotatePos - rotate) * 0.03) * 0.6);\n }\n function drawBars() {\n const cw = w * 0.5, ch = h * 0.5;\n var i = setup.count, j = 0;\n var xl = cw - setup.centerRadius, xr = cw + setup.centerRadius, x = 0;\n const cr = setup.centerRadius;\n const damp = setup.count * 0.3;\n const xs = xl / setup.count, xw = xs * setup.barWidth;\n const hScale = ch - setup.innerHeightPad;\n ctx.fillStyle = centerBar;\n ctx.fillRect(\n 0, \n (h - setup.centerBarWidth) * 0.5, \n cw - setup.centerRadius, \n setup.centerBarWidth\n );\n ctx.fillRect(\n cw + setup.centerRadius, \n (h - setup.centerBarWidth) * 0.5, \n cw - setup.centerRadius, \n setup.centerBarWidth\n );\n ctx.strokeStyle = centerBar;//setup.color;\n ctx.lineWidth = xw;\n ctx.beginPath();\n while (i--) {\n const lh = (j &lt; damp ? 1-((damp-j) / damp) ** 2 : 1) * levels[i] * hScale;\n if(lh &gt; 0.5) {\n const r = x * 4 + cr;\n const lhr = lh / r;\n // add lhr + 0.0001 to start angle to fix miter artifact\n ctx.moveTo(...polarArg(lhr + 0.0001, r, xl + cr - x * 3, ch))\n ctx.arc (xl + cr - x * 3, ch, r, lhr, -lhr, true);\n ctx.moveTo(...polarArg(PI + lhr + 0.0001, r, xr - cr + x * 3, ch))\n ctx.arc (xr - cr + x * 3, ch, r, PI + lhr, PI - lhr, true);\n }\n j ++;\n x += xs;\n }\n ctx.stroke();\n }\n function drawGlows() {\n var i = means.length, j = 1;\n const ch = h * 0.5;\n const xs = w * 0.5 / (means.length + 1);\n var x = 0;\n ctx.globalCompositeOperation = \"lighter\";\n while (i--) {\n var m = Math.min(1, (means[i] / meanSize)) ** 2;\n means[i] *= setup.glowDecay;\n const xx = Math.cos(glowAng1 * (i + 1)) * ch * 0.5;\n const yy = Math.sin((glowAng2 += m * 0.01) * j );\n ctx.setTransform(\n m, 0, 0, m,\n w * 0.5 + xx + x * (i % 2 ? -1 : 1),\n yy * ch * 0.25 + h * 0.5\n );\n ctx.globalAlpha = (1- ((yy * (1-m)) ** 4)) * setup.glowAlpha;\n ctx.fillStyle = glows[i];\n ctx.beginPath();\n ctx.arc(0, 0, h * 0.5, 0, TAU); \n ctx.fill();\n x += xs;\n j += 0.2;\n }\n glowAng1 += 2 * setup.glowOffsetRate;\n glowAng2 += 3 * setup.glowOffsetRate;\n ctx.globalCompositeOperation = \"source-over\";\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n }\n function drawCircle() {\n ctx.fillStyle = setup.color;\n const ax = Math.cos(rotate);\n const ay = Math.sin(rotate);\n ctx.setTransform(ax, ay, -ay, ax, w * 0.5, h * 0.5);\n ctx.fill(centerCircle, \"evenodd\");\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#container { \nbackground-image: radial-gradient(circle at 40px 40px, rgba(157,227,255,1) 0%, rgba(60,152,240,1) 24%, rgba(44,73,105,1) 56%, rgba(12,1,66,1) 94%, rgba(0,0,1,1) 100%);\n font-family: Arial Black;\n position: absolute;\n top: 0px;\n left: 0px;\n width: 100%;\n height: 100%;\n}\nh1, h2 {\n text-align: center;\n font-size: xx-large;\n}\nh1 { color: #8CF;font-size: xxx-large}\nh2 { color: #8F4}\n#canvasContainer { \n position: absolute; \n top: 29%; \n left: 0px; \n height: 70%; \n width: 100%;\n}\ncanvas {\n mix-blend-mode: lighten;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"container\"&gt;\n&lt;h1&gt;Audio &lt;span&gt;Candy&lt;/span&gt;&lt;/h1&gt;\n&lt;h2&gt;2D Canvas Animation&lt;/font&gt;\n&lt;div id=\"canvasContainer\"&gt;&lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T09:58:05.773", "Id": "526305", "Score": "0", "body": "Two things please: It is so smooth, looks great! (1) It looks like you used circles for the bars. Is it possible to use squares? I am going to look at this weekend. (2) I want to do the work but I might need help would I post my help questions here or in Stack Overflow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T11:55:17.603", "Id": "528427", "Score": "0", "body": "Could you take a look at this for me? Same subject modified code. https://stackoverflow.com/questions/69060401/mirror-the-waves-on-the-left-side-with-waves-i-have-already-created-on-the-right" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T03:09:35.667", "Id": "266339", "ParentId": "266300", "Score": "3" } } ]
{ "AcceptedAnswerId": "266339", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T20:43:03.760", "Id": "266300", "Score": "2", "Tags": [ "javascript", "css" ], "Title": "Create random wave forms using JavaScript and CSS" }
266300
<p>I have previously got a review of something similar (but not the same but its related to proxies) which can be found via: <a href="https://codereview.stackexchange.com/questions/266276/proxy-manager-to-return-proxy-format/266296#266296">proxy-manager-to-return-proxy-format</a></p> <p>What I am now trying to do is that I want to lock the proxies when they are in use. When they are in use we block them and whenever they are finished with they supposed to do then another thread can pick it up. I have ended up doing something like this <strong>See AvailableProxies()</strong> as <strong>ProxyManager</strong> has been reviewed:</p> <pre><code>import random import threading import time from typing import List, Dict, Optional from loguru import logger &quot;&quot;&quot; Been reviewed: https://codereview.stackexchange.com/a/266293/223687 &quot;&quot;&quot; class ProxyManager: def __init__(self, proxy_file_path: Optional[str] = None): self._proxies = self._load_proxies(proxy_file_path) if proxy_file_path else [] @staticmethod def _load_proxies(proxy_file_path: str) -&gt; List[Dict[str, str]]: &quot;&quot;&quot; Parse proxies into the format `http://ip:port` or `http://ip:port:user@password`. # &gt;&gt; load_proxies(['hello:12345', 'hello:12345:apple:orange']) # [{'https': 'http://hello:12345'}, {'https': 'http://hello:12345:apple@orange'}] &gt;&gt; load_proxies(['test:4125', 'myserver:1337:usertest:passwordtest']) [{'https': 'http://test:4125'}, {'https': 'http://myserver:1337:usertest@passwordtest'}] &quot;&quot;&quot; def _load_ip_proxy(value: str) -&gt; str: &quot;&quot;&quot; Transform a `{ip}:{port}` string into a `http://{ip}:{port}` string. &quot;&quot;&quot; ip, port = value.split(&quot;:&quot;) return f&quot;http://{ip}:{port}&quot; def _load_ipup_proxy(value: str) -&gt; str: &quot;&quot;&quot; Transform a `{ip}:{port}:{user}:{password}` string into a `http://{ip}:{port}:{user}@{password}` string. &quot;&quot;&quot; ip, port, user, password = value.split(&quot;:&quot;) return f&quot;http://{ip}:{port}:{user}@{password}&quot; parsing_functions = {1: _load_ip_proxy, 3: _load_ipup_proxy} with open(proxy_file_path) as proxy_file: proxies = [] for line in proxy_file: proxy = line.strip('\n') parsing_function = parsing_functions.get(proxy.count(&quot;:&quot;)) if parsing_function is None: continue proxies.append({'https': parsing_function(proxy)}) return proxies @property def random_proxy(self) -&gt; Dict[str, str]: return random.choice(self._proxies) if len(self._proxies) &gt; 0 else {} @property def full_list(self) -&gt; List[Dict[str, str]]: return self._proxies # ------------------------------------------------------------------------- # Proxies path # ------------------------------------------------------------------------- proxies: Dict[str, ProxyManager] = { &quot;rotating&quot;: ProxyManager(&quot;./proxies/rotating.txt&quot;), &quot;test&quot;: ProxyManager(&quot;./proxies/test.txt&quot;) } # ------------------------------------------------------------------------- # Proxies available # ------------------------------------------------------------------------- all_proxies = [proxy['https'] for proxy in proxies[&quot;test&quot;].full_list] proxy_dict = dict(zip(all_proxies, [True] * len(all_proxies))) proxy_lock: threading = threading.Lock() # ------------------------------------------------------------------------- # Initialize availability of proxies # ------------------------------------------------------------------------- class AvailableProxies: def __enter__(self): proxy_lock.acquire() self.proxy = None while not self.proxy: if available := [att for att, value in proxy_dict.items() if value]: self.proxy = random.choice(available) proxy_dict[self.proxy] = False else: logger.info(&quot;Waiting ... no proxies available&quot;) time.sleep(.2) proxy_lock.release() return self.proxy def __exit__(self, exc_type, exc_val, exc_tb): proxy_dict[self.proxy] = True </code></pre> <p>To be able to test it:</p> <pre><code>import threading import threading import time from lib.proxies import AvailableProxies def main(thread_name): while True: with AvailableProxies() as proxies: print(f&quot;Thread name: {thread_name} -&gt; {proxies}&quot;) time.sleep(3) if __name__ == '__main__': for i in range(10): threading.Thread(target=main, args=(i,)).start() time.sleep(0.3) </code></pre> <p>However there is some script where I will use that I will not use the <code>AvailableProxies</code> and only <code>ProxyManager</code> (But the <code>AvailableProxies</code> should be available to import at any time to my scripts of course :) (If thats matters)</p> <p>There is somethings I am concern about is that I am not sure if this method to set a proxy to &quot;available&quot; and &quot;busy&quot; is a valid way to do (but hey, it works!).</p> <p>I am looking forward for any code review and I do hope this time I will not get shocked as I got on my previous review :)</p>
[]
[ { "body": "<h1>Availability of proxies</h1>\n<h2>Documentation</h2>\n<p>The <code>threading</code> name refers to the module, the <code>threading.Lock</code> name refers to a class inside that module. Thus, the type of <code>proxy_lock</code> is wrong, since it's an instance of <code>threading.Lock</code>. You can replace it with</p>\n<pre><code>proxy_lock: threading.Lock = threading.Lock()\n</code></pre>\n<h2>Performance</h2>\n<p>To avoid allocating a list filled with <code>True</code>s, you can use <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.fromkeys\" rel=\"nofollow noreferrer\"><code>dict.fromkeys</code></a> and replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>proxy_dict = dict(zip(all_proxies, [True] * len(all_proxies)))\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>proxy_dict = dict.fromkeys(all_proxies, True)\n</code></pre>\n<h2>Logic</h2>\n<p>You can use a <a href=\"https://docs.python.org/3/library/threading.html#using-locks-conditions-and-semaphores-in-the-with-statement\" rel=\"nofollow noreferrer\">context manager</a> to use your lock. There are two main advantages of using a context manager:</p>\n<ol>\n<li><p>You'll only use your <code>proxy_lock</code> variable once, in the with-block. Currently, you're using twice and it may be prone to errors (e.g. you may change your code in the future and accidentally delete the line where you release the lock).</p>\n</li>\n<li><p>If an error occurs between the lock acquire and the lock release, your lock will not be released. However, the context manager of the <code>threading.Lock</code> class will handle it for you in its internals.</p>\n</li>\n</ol>\n<p>So you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>def __enter__(self):\n proxy_lock.acquire()\n \n # ...\n\n proxy_lock.release()\n return self.proxy\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>def __enter__(self):\n with proxy_lock:\n # ...\n\n return self.proxy\n</code></pre>\n<hr />\n<p>The <code>proxy_lock</code> variable should not be available to the outside world, only <code>AvailableProxies</code> will use it. However, when you import <code>lib.proxies</code>, <code>proxy_lock</code> will come with it. You can make it a private class attribute:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class AvailableProxies:\n _proxy_lock: threading.Lock = threading.Lock()\n\n def __enter__(self):\n with self._proxy_lock:\n # ...\n\n return self.proxy\n</code></pre>\n<h3>Dependency injection</h3>\n<p>You should decide whether or not to use dependency injection. <a href=\"https://stackoverflow.com/a/131766/9997212\">This answer</a> explains it well:</p>\n<blockquote>\n<p>Dependency Injection is a practice where objects are designed in a manner where they receive instances of the objects from other pieces of code, instead of constructing them internally. This means that any object implementing the interface which is required by the object can be substituted in without changing the code, which simplifies testing, and improves decoupling.</p>\n</blockquote>\n<p>Its main goal is to make unit testing easier and one of its rules is to &quot;avoid using mutable global variables&quot;. Your <code>proxy_dict</code> variable is mutable and it's declared in the outermost (global) scope, thus it's against the principles of DI. Think if it's worth it. If it is, here's how to fix it step-by-step:</p>\n<ol>\n<li>Note that, in your driver file, <code>main</code> is creating an instance of <code>AvailableProxies</code>. Let's use DI and pass the dependency to <code>main</code> instead of creating a new one:</li>\n</ol>\n<pre><code>def main(manager, thread_name):\n while True:\n with manager as proxies:\n print(f&quot;Thread name: {thread_name} -&gt; {proxies}&quot;)\n time.sleep(3)\n\n\nif __name__ == '__main__':\n # Only one instance\n manager = AvailableProxies()\n\n for i in range(10):\n threading.Thread(target=main, args=(manager, i)).start()\n time.sleep(0.3)\n</code></pre>\n<p>You can try this change. You'll notice that it will not work: only threads 0-4 will get a proxy, threads 5-9 will <a href=\"https://stackoverflow.com/q/34512/9997212\">deadlock</a> on <code>self.proxy</code> since there's only one instance of <code>AvailableProxies</code>. We can fix this by using <a href=\"https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager\" rel=\"nofollow noreferrer\"><code>contextlib.contextmanager</code></a> instead of using <code>__enter__</code> and <code>__exit__</code>.</p>\n<p>I also like using the latter, but in this case <code>__exit__</code> needs to access the proxy found by <code>__enter__</code>, and the only way for <code>__enter__</code> pass it to <code>__exit__</code> is by creating a instance variable (thus modifying the instance). However, <code>contextlib.contextmanager</code> allows this transfer to occur via a local variable, which does not modify the instance and removes the deadlock threat:</p>\n<pre><code>import contextlib\n\nclass AvailableProxies:\n # ...\n\n @property\n @contextlib.contextmanager\n def proxies(self):\n # Note that we can use `proxy` instead of `self.proxy`\n # Since our goal is to use only one instance of `AvailableProxies`\n # and multiple threads, using a local variable here don't modify \n # the instance in any way, avoiding a possible deadlock\n proxy = None\n\n with self._proxy_lock:\n while not proxy:\n if available := [att for att, value in proxy_dict.items() if value]:\n proxy = random.choice(available)\n proxy_dict[proxy] = False\n else:\n logger.info(&quot;Waiting ... no proxies available&quot;)\n time.sleep(.2)\n\n yield proxy\n\n proxy_dict[proxy] = True\n</code></pre>\n<p>In your driver file:</p>\n<pre><code>def main(manager, thread_name):\n while True:\n # Access the `proxies` property here\n with manager.proxies as proxies:\n print(f&quot;Thread name: {thread_name} -&gt; {proxies}&quot;)\n time.sleep(3)\n</code></pre>\n<p>This now works as expected.</p>\n<ol start=\"2\">\n<li>The <code>proxy_dict</code> dictionary is still mutable and it's still global. Let's create it in the constructor of <code>AvailableProxies</code> as a instance variable:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>class AvailableProxies:\n # ...\n\n # Pass the proxies as a dependency to the constructor (DI)\n def __init__(self, proxies: Dict[str, ProxyManager]):\n all_proxies = [proxy['https'] for proxy in proxies[&quot;test&quot;].full_list]\n self._proxy_dict = dict.fromkeys(all_proxies, True)\n \n @property\n @contextlib.contextmanager\n def proxies(self):\n # Replace `proxy_dict` here with `self._proxy_dict`\n ...\n</code></pre>\n<p>You may ask here: when I do <code>self._proxy_dict[proxy] = True</code>, I'm modifying the <code>AvailableProxies</code> instance, why doesn't a deadlock occur here too? The answer is that the loop inside the lock does not depend on <code>self._proxy_dict</code>, but depended on <code>self.proxy</code>. If you modified <code>self.proxy</code>, it would affect the loop condition, creating the deadlock. Since the loop doesn't depend on <code>self._proxy_dict</code>, you can modify it fine.</p>\n<p>Since now <code>AvailableProxies</code> expects <code>proxies</code> as an argument to its constructor, create <code>proxies</code> as a local variable instead of a global variable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == '__main__':\n proxies: Dict[str, ProxyManager] = {\n &quot;rotating&quot;: ProxyManager(&quot;./proxies/rotating.txt&quot;),\n &quot;test&quot;: ProxyManager(&quot;./proxies/test.txt&quot;)\n }\n\n manager = AvailableProxies(proxies)\n for i in range(10):\n threading.Thread(target=main, args=(manager, i)).start()\n time.sleep(0.3)\n</code></pre>\n<p>Your code is fine now: no more global variables.</p>\n<hr />\n<p>For a final note, I would suggest to add a suffix to <code>AvailableProxies</code>, such as <code>AvailableProxiesProvider</code> or <code>AvailableProxiesManager</code>, but that's up to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T08:32:15.273", "Id": "526145", "Score": "1", "body": "Once again a hero! Oh wow, I honestly cant believe how you managed to change my code totally but also describing every step why and how which I really love. I have read the answer already 5 times and have adapted it into my code. It is indeed very well written. thank you so much! I do indeed have a question. Is it okey to have the `manager = AvailableProxies(proxies)` in a utils.py lib and then just import it to a scripts where you basically want to use it? (e.g. test1.py and test2.py imports `from lib.utils import manager` instead of doing it in a `if __name__ == '__main__':` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T15:16:42.657", "Id": "526173", "Score": "1", "body": "Yes, it's okay! In fact, the approach you mentioned is [the easiest way](https://stackoverflow.com/a/6760821/9997212) of creating [a singleton](https://stackoverflow.com/q/137975/9997212) in Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:34:35.267", "Id": "526186", "Score": "1", "body": "Thank you so much Enzo! I wish you a very good day, week, month, years and all coming years ahead! You are awesome!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T00:45:05.127", "Id": "266338", "ParentId": "266301", "Score": "2" } } ]
{ "AcceptedAnswerId": "266338", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T21:12:11.583", "Id": "266301", "Score": "3", "Tags": [ "python-3.x" ], "Title": "Availability of proxies" }
266301
<p>this is similar to another project I did here: <a href="https://codereview.stackexchange.com/questions/266299/javascript-deck-builder-shuffle-draw-cards">JavaScript Deck Builder: Shuffle, Draw Cards</a> Except this script does not shuffle or draw cards from the top of the deck. Instead the script builds a deck, then will randomly choose a card from the deck. The card that is chosen is then removed from the deck and placed into the discard pile. Like my previous post I am looking for critiques or different ways I could approach writing this script.</p> <pre><code>const cardGame = { values: [ 'Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Joker', 'Queen', 'King' ], suits: [ 'Clubs', 'Spades', 'Hearts', 'Diamonds' ], deck: [], discard: [], pick(arr) { const idx = Math.floor(Math.random() * arr.length); return arr[idx]; }, buildDeck() { const { deck, discard, values, suits } = this; //clear deck and discard pile deck.splice(0, 52); discard.splice(0, 52); //regenerate/build deck for (let suit of suits) { for (let value of values) { deck.push({ value, suit }); } } }, getCard() { const { pick, deck } = this; return pick(deck); }, drawCard(numCards = 1) { const { deck, discard } = this; const drawnCards = []; //draw cards while (drawnCards.length &lt; numCards) { let card = this.getCard(); //check if card has been drawn for (let drawnCard of drawnCards) { let matchSuit = card.suit === drawnCard.suit; let matchValue = card.value === drawnCard.value; if (matchSuit &amp;&amp; matchValue) { card = this.getCard(); } } console.log(card); drawnCards.push(card); } //discard drawn cards from deck for (let drawnCard of drawnCards) { for (let i = 0; i &lt; deck.length; i++) { let card = deck[i]; let matchSuit = card.suit === drawnCard.suit; let matchValue = card.value === drawnCard.value; if (matchSuit &amp;&amp; matchValue) { deck.splice(i, 1); discard.push(card); } } } console.log(deck.length); } }; cardGame.buildDeck(); </code></pre>
[]
[ { "body": "<h2>General points</h2>\n<ul>\n<li>To empty an array use the length property eg. Rather than use <code>deck.splice(0, 52);</code> use <code>deck.length = 0;</code></li>\n<li>You can simplify the card array and use a number 0 to 51 to represent a card. The card suit is the <code>this.suits[(value / 13 | 0) % 4]</code> and the card value <code>this.values[cardId % 13]</code></li>\n<li>the function <code>drawCard</code> lets you draw more than one. It should be called <code>drawCards</code></li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite uses a completely different approach for handling a set (deck of card) of unique items</p>\n<ul>\n<li><p>IIFE (Immediately Invoke Function Expression) to encapsulate the deck so that code using the deck can not break the state of the deck.</p>\n</li>\n<li><p>Cards are stored by id (Number 0 - 51) rather than using object.</p>\n</li>\n<li><p>Adding and removing single cards is done using getters and setters. Eg to get a random card <code>const randomCard = deck.random</code> or to get top card <code>const topCard = deck.card</code></p>\n<p>You can also add a card to the top of the deck <code>deck.card = cardId</code> or add it randomly <code>deck.random = cardId</code></p>\n<p><strong>Note</strong> that cards will not be added if the deck already contains that card.</p>\n<p><strong>Note</strong> that if the deck is out of cards getting cards will return <code>undefined</code></p>\n</li>\n<li><p><code>deck.drawCards</code> can draw random or from the top of the deck.</p>\n</li>\n<li><p>Cards are defined by unique ID. The IIFE has a <code>deckCount</code> argument to define the number of decks used. This means that when adding cards back to the deck only cards handed out will be accepted back.</p>\n<p><strong>Note</strong> max <code>deckCount</code> is set to 12 however this value is arbitrary and can be any value &lt; infinity</p>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const deck = ((deckCount) =&gt; {\n deckCount = Math.min(12, Math.max(1, isNaN(deckCount) ? 2 : deckCount | 0));\n const VALUE = \"A,2,3,4,5,6,7,8,9,10,J,Q,K\".split(\",\");\n const SUITS = \"♣,♠,♥,♦\".split(\",\");\n const deck = [];\n const randIdx = () =&gt; Math.random() * deck.length | 0;\n return (Object.freeze({\n nameCard(id) { return VALUE[id % 13] + \"\" + SUITS[(id / 13 | 0) % 4] },\n handAsStr(hand) { return hand.map(cardId =&gt; this.nameCard(cardId)).join(\", \") },\n set card(id) { !deck.includes(id) &amp;&amp; deck.push(id) },\n set random(id) { !deck.includes(id) &amp;&amp; deck.splice(randIdx(), 0, id) },\n get card() { return deck.pop() },\n get random() { return deck.length ? deck.splice(randIdx(), 1)[0] : undefined },\n newDeck() {\n deck.length = 0;\n while(deck.length &lt; 52 * deckCount) { this.card = deck.length }\n return this;\n },\n drawCards(cards = 1, rand = true) {\n var c;\n const drawn = [];\n while (cards-- &gt; 0 &amp;&amp; deck.length) { \n (c = (rand ? this.random : this.card)) !== undefined &amp;&amp; drawn.push(c);\n }\n return drawn; \n },\n get length() { return deck.length },\n })).newDeck();\n})(\"pho\");\nconsole.log(deck.handAsStr(deck.drawCards(5)));\nconsole.log(deck.handAsStr(deck.drawCards(5)));\nconsole.log(deck.handAsStr(deck.drawCards(5)));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T19:15:09.520", "Id": "526533", "Score": "0", "body": "This is late but I wanted to say thank you for the points you provided in your response and the rewrite. I was unaware of IIFEs, Object.freeze(), getters and setters, and programming concepts such as encapsulation prior to posting my question, but the rewrite you provided made me learn about these different concepts, that I will apply when I write other scripts. The only part of the rewrite which I did not understand was at get random() there is brackets [0] after deck.splice(randIdx(), 1). What are the brackets intended for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T20:11:37.917", "Id": "526535", "Score": "1", "body": "@fire_hydrant `Array.splice(index, count)` returns an array of items spliced from the array. In the example I only remove 1 item `deck.splice(randIdx(), 1)[0]` thus the [0] means the 1st item in the array of spliced items. [Reference `Array.splice` at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T01:18:57.250", "Id": "266307", "ParentId": "266303", "Score": "1" } } ]
{ "AcceptedAnswerId": "266307", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T21:56:08.657", "Id": "266303", "Score": "0", "Tags": [ "javascript" ], "Title": "JavaScript Deck Builder: Build Deck, Draw Random Card from Deck" }
266303
<p>I am trying to implement a priority-based timer where certain events are fired out based on their expiry and the priority.</p> <p>So if there are 3 timers with the following expiry time and priorities</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Timers</th> <th>Expiry Time (s)</th> <th>Priorities</th> </tr> </thead> <tbody> <tr> <td>T1</td> <td>5</td> <td>1</td> </tr> <tr> <td>T2</td> <td>5</td> <td>10</td> </tr> <tr> <td>T3</td> <td>10</td> <td>1</td> </tr> </tbody> </table> </div> <p>The order of timers triggering should be <code>T2, T1, T3</code>.</p> <p>Initially, I thought of creating POSIX timer for each event but priority wouldn't be respected, so then I came up with a priority queue approach where each item is stored in the order of their expiry time and priority. Also creating a timer for each event probably sounds like an overkill.</p> <p>So in the above example, it would be <code>T2 -&gt; T1 -&gt; T3</code>.</p> <p><strong>Implementation:</strong></p> <ul> <li><p>Each node in the list contains the <code>refTime</code> which basically stores the expiry time with an offset to the time recorded at the start of the application <code>(refTime = expiryTime + startTime)</code> so every node is timed is referenced.</p> </li> <li><p>MONOTONIC timer is used to avoid relying on the changes into system clock be it leap year, or day light savings. The idea is make sure the time elapsed from the initial time to current time remains positive and mostly accurate, since that's what would be needed for triggering the timer.</p> </li> <li><p>There would be one main thread that constantly checks if the current time exceeds the time stored in the node and once that's true, it indicates the timer needs to trigger so it would delete the node, and append the same timer in the priority queue with an updated time i.e <strong>current time + expiry time</strong></p> </li> </ul> <p><strong>list.h</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;string.h&quot; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; typedef struct node { struct node *head; char *name; int priority; unsigned int expiry; unsigned int refTime; struct node *nxt; } Node; void push(Node **node, char *name, int expiry, int priority); void popAndPush(Node **node); Node *CreateNode(char *name, unsigned int expiry, int priority); void print(Node *node); </code></pre> <p><strong>list.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;list.h&quot; extern struct timespec startTime; struct timespec endTime; // print the list void print(Node *node) { for (; node != NULL; node = node-&gt;nxt) { printf (&quot;%d (%s,%d,%u) -&gt; &quot;, node-&gt;refTime, node-&gt;name, node-&gt;priority, node-&gt;expiry); } printf (&quot;\n=============================================\n\n&quot;); } Node *CreateNode(char *name, unsigned int expiry, int priority) { Node *node = malloc(sizeof(*node) + strlen(name) + 1); node-&gt;name = name; clock_gettime(CLOCK_MONOTONIC, &amp;endTime); unsigned int timeElapsed = ( endTime.tv_sec - startTime.tv_sec ); node-&gt;refTime = expiry + timeElapsed; node-&gt;expiry = expiry; node-&gt;priority = priority; node-&gt;nxt = NULL; printf (&quot;Create - name: %s, expiry: %u, refTime: %u, priority: %d, timeElapsed: %u\n&quot;, node-&gt;name, node-&gt;expiry, node-&gt;refTime, node-&gt;priority, timeElapsed); return node; } void push(Node **node, char *name, int expiry, int priority) { unsigned int curTime; unsigned int updatedTime; Node *head = *node; Node *tmp = CreateNode(name, expiry, priority); printf (&quot;[Head] name: %s, nxt: %p, headExpiry: %d, refTime: %u\n&quot;, head-&gt;name, head-&gt;nxt, head-&gt;expiry, head-&gt;refTime); printf (&quot;[Temp] name: %s, nxt: %p, headExpiry: %d, refTime: %u, Head&gt;Tmp: %d\n&quot;, tmp-&gt;name, tmp-&gt;nxt, tmp-&gt;expiry, tmp-&gt;refTime, head-&gt;expiry &gt; tmp-&gt;expiry); if (tmp-&gt;refTime &lt;= head-&gt;refTime) // append before head { printf (&quot;New node expiry &lt;= head expiry -- &quot;); if (tmp-&gt;priority &gt; head-&gt;priority || tmp-&gt;refTime &lt; head-&gt;refTime) // append before head only when HIGH priority { printf (&quot;tmp-&gt;priority &gt; head-&gt;priority - append tmp before Head\n&quot;); tmp-&gt;nxt = head; *node = tmp; } else // append after head { printf (&quot;tmp-&gt;priority &lt; head-&gt;priority - append tmp after Head\n&quot;); tmp-&gt;nxt = head-&gt;nxt; head-&gt;nxt = tmp; } } else { while(head-&gt;nxt) { if (tmp-&gt;refTime &lt; head-&gt;nxt-&gt;refTime) { break; } else if (tmp-&gt;refTime == head-&gt;nxt-&gt;refTime) { if (tmp-&gt;priority &gt; head-&gt;nxt-&gt;priority) { break; } } head = head-&gt;nxt; } tmp-&gt;nxt = head-&gt;nxt; head-&gt;nxt = tmp; } printf (&quot;\n&quot;); print(*node); } void popAndPush(Node **node) { Node *tmp = *node; printf (&quot;....Popping node (%s,%d,%d)......\n&quot;, tmp-&gt;name, tmp-&gt;priority, tmp-&gt;expiry); // changing head *node = (*node)-&gt;nxt; printf (&quot;New head: %s\n&quot;, (*node)-&gt;name); char *name = tmp-&gt;name; unsigned int expiry = tmp-&gt;expiry; unsigned int priority = tmp-&gt;priority; // delete the node free(tmp); // pushing new node push(node, name, expiry, priority); } </code></pre> <p><strong>main.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &quot;list.h&quot; #include &lt;time.h&gt; #include &lt;pthread.h&gt; typedef struct { char *type; int expiry; int priority; char *msg; } TimerInfo; TimerInfo timerList[] = { { .type = &quot;taskA&quot;, .expiry = 5, .priority = 10, .msg = &quot;Sending TaskA&quot; }, { .type = &quot;taskB&quot;, .expiry = 4, .priority = 1, .msg = &quot;Sending TaskB&quot; }, { .type = &quot;taskC&quot;, .expiry = 5, .priority = 1, .msg = &quot;Sending TaskC&quot; }, { .type = &quot;taskD&quot;, .expiry = 2, .priority = 11, .msg = &quot;Sending TaskD&quot; } }; Node *head; struct timespec startTime; struct timespec curTime; void someCallback(char *msg) { // do something with msg } void *Scheduler(void *arg) { unsigned int timeElapsed; printf (&quot;&gt;&gt;&gt;&gt;&gt; Scheduler starts &lt;&lt;&lt;&lt;&lt;\n&quot;); while(1) { clock_gettime(CLOCK_MONOTONIC, &amp;curTime); // get current time timeElapsed = curTime.tv_sec - startTime.tv_sec; // time elapsed since startTime if (timeElapsed &gt;= head-&gt;refTime) // timer has triggered { printf (&quot;%s (%d) expires - time elasped: %d\n&quot;, head-&gt;name, head-&gt;refTime, timeElapsed); popAndPush(&amp;head); someCallback(head-&gt;msg); } } } int main(void) { clock_gettime(CLOCK_MONOTONIC, &amp;startTime); // record the time at the start of the app pthread_t tId; head = CreateNode(timerList[1].type, timerList[1].expiry, timerList[1].priority); print(head); push(&amp;head, timerList[2].type, timerList[2].expiry, timerList[2].priority); push(&amp;head, timerList[0].type, timerList[0].expiry, timerList[0].priority); push(&amp;head, timerList[3].type, timerList[3].expiry, timerList[3].priority); pthread_create(&amp;tId, NULL, Scheduler, NULL); pthread_join(tId, NULL); return 0; } </code></pre> <p>If you copy the code into an online compiler, you should be able to run it and see how the output relates to the code in case of any confusion.</p> <p>The program seems to work fine but posting to see if there are any corner cases that I forgot to take into account or any design approach that would work better. Appreciate any help!</p> <p><strong>Edit:</strong></p> <ul> <li>Would having a run queue be beneficial for debugging purposes? If so, what should it store? A generic run queue seems to hold the number of idle and active tasks but in my case, that happens based on the expiry and priority.</li> <li>if the <code>someCallback()</code> writes to a message queue that's read by an external MCU for instance, and there needs to be ACK sent for each request received by the MCU, waiting for some time till the ACK is received in the scheduler might mess up with the logic I suppose? How could that be dealt with given that's a scenario?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T17:04:32.070", "Id": "526531", "Score": "0", "body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T17:05:20.240", "Id": "526532", "Score": "0", "body": "my apologies. only did so cause there was a compilation error as one of the commenters pointed out and anyone attempting to try out the code may run into errors" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T22:34:51.517", "Id": "526542", "Score": "0", "body": "Do you really need expiry *and* priority? It would be simpler just to merge them, but I guess that depends on how many time steps polling takes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T01:14:16.760", "Id": "526562", "Score": "0", "body": "yeah well priority mainly comes into the picture if the timeouts of different nodes are the same. So `NodeA` expiring in 5s and so does `NodeB` except it has a higher priority than `NodeA` therefore the `head` of the queue must be pointing to `NodeB`" } ]
[ { "body": "<blockquote>\n<p>any corner cases that I forgot to take into account</p>\n</blockquote>\n<p><strong>No error handling</strong></p>\n<p>e.g.: <code>malloc()</code> may return <code>NULL</code>.</p>\n<hr />\n<blockquote>\n<p>any design approach that would work better.</p>\n</blockquote>\n<p><strong>Improve name space</strong></p>\n<p><code>list.h</code> defines <code>node, Node, push, popAndPush, CreateNode, print</code>.</p>\n<p>I recommend instead to have <code>node.h</code> to define <code>node, node_push, node_popAndPush, node_create, node_print</code>.</p>\n<p><strong>Missing code guard</strong></p>\n<p>.h files deserve code guard and minimal included .h files.</p>\n<pre><code>#ifndef list_h\n#define list_h\n\n//#include &quot;string.h&quot;\n//#include &lt;stdlib.h&gt;\n//#include &lt;stdio.h&gt;\n//#include &lt;time.h&gt;\n...\n\n#endif \n</code></pre>\n<p><strong>Use <code>const</code></strong></p>\n<p>Greater clarity, application and optimization potential.</p>\n<pre><code>// void print(Node *node)\nvoid print(const Node *node)\n</code></pre>\n<hr />\n<blockquote>\n<p>Appreciate any help!</p>\n</blockquote>\n<p><strong>Wrong size</strong></p>\n<p>With the given <code>struct</code>, there is no need to allocate for the <em>string</em>. <code>Node</code> only saves the pointer to the original string.</p>\n<pre><code>// malloc(sizeof(*node) + strlen(name) + 1);\nmalloc(sizeof *node);\n</code></pre>\n<p>If wanting a copy of the string, consider instead a <em>flexible member array</em>.</p>\n<pre><code>typedef struct node {\n struct node *head;\n int priority;\n unsigned int expiry;\n unsigned int refTime;\n struct node *nxt;\n char name[];\n} Node;\n\nsize_t sz = strlen(name) + 1;\nNode *node = malloc(sizeof *node + sz);\nnode-&gt;... = ...\nstrcpy(node-&gt;name, name);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T04:43:43.310", "Id": "526351", "Score": "0", "body": "Thanks. In response to `malloc` error handling, `CreateNode()` returns `*node` ... so given that, what'd you return in case of a malloc failure? I was thinking of returning an ERROR code ENUM but that's not possible with this..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T08:47:22.200", "Id": "526359", "Score": "1", "body": "@xyf \"what'd you return in case of a malloc failure\" --> `Node *CreateNode(char *name, unsigned int expiry, int priority) { Node *node = malloc(sizeof(*node) + strlen(name) + 1); if (node == NULL) return NULL; ....}`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T01:00:34.560", "Id": "266306", "ParentId": "266304", "Score": "4" } }, { "body": "<p><strong>Code structure</strong>\nThere are three important components here</p>\n<ol>\n<li>Priority queue</li>\n<li>Scheduler</li>\n<li>Timer</li>\n</ol>\n<p>Scheduler picks up timer based on priority queue and fires.</p>\n<p>Should priority queue know about details of Timer? No</p>\n<p>Priority queue node needn't know details about timer. It only needs to know how to compute priority of node representing timer. So name, expiry time and refTime shouldn't be part of priority queue node.</p>\n<pre><code>typedef struct node\n{\n struct node *head;\n char *name; // Shouldn't be part of the struct\n int priority;\n unsigned int expiry; // Shouldn't be part of the struct\n unsigned int refTime; // Shouldn't be part of the struct\n struct node *nxt;\n} Node;\n</code></pre>\n<p>Node should take timer as opaque pointer and a pointer to a function which compares priority of two timers.</p>\n<pre><code>\ntypedef int (*NodeComparator)(void* nodedata_a , void* nodedata_b );\ntypedef struct node\n{\n struct node *head; \n int priority;\n void* nodedata; // Opaque pointer. In OOPS world it could be interface.\n NodeComparator comparator;\n struct node *nxt;\n} \n</code></pre>\n<p>Should Scheduler know timer details? No.\nShould Scheduler know priority queue details? No\nCurrent code is good with respect to these two questions.</p>\n<p><strong>Priority queue</strong></p>\n<p>Heap based implementation will be more efficient than current implementation. We don't need to maintain a sorted list because at any time we need to know which timer is going to be fired next.</p>\n<p><strong>Code review</strong></p>\n<ol>\n<li>Compilation error: head doesn't have msg. Probably you wanted to use name</li>\n</ol>\n<pre><code>someCallback(head-&gt;msg);\n</code></pre>\n<ol start=\"2\">\n<li>In function signature mark input parameters not expected to be changed as const</li>\n</ol>\n<pre><code>typedef struct priority_queue_node\n{\n void *data;\n struct priority_queue_node *nxt;\n} priority_queue_node;\n\n// Checks if priority of nodedata_a is higher than nodedata_b\ntypedef bool (*NodeComparator)(void* nodedata_a, void* nodedata_b); \n\ntypedef struct \n{\n priority_queue_node* head;\n NodeComparator comparator;\n} priority_queue;\n\ntypedef struct TimerInfo\n{\n char* type ;\n int expiry = 0;\n DWORD refTime = 0;\n int priority = 0;\n char* msg;\n} TimerInfo;\n\nbool TimerInfoComparator(void *timerInfo_a, void *timerinfo_b)\n{\n TimerInfo* timer_a = (TimerInfo*)timerInfo_a;\n TimerInfo* timer_b = (TimerInfo*)timerinfo_b;\n\n return (timer_a-&gt;refTime &lt; timer_b-&gt;refTime) ||\n ((timer_a-&gt;refTime == timer_b-&gt;refTime) &amp;&amp;\n (timer_a-&gt;priority &gt; timer_b-&gt;priority));\n}\n\nvoid push(priority_queue *queue, priority_queue_node** node)\n{\n priority_queue_node* head = queue-&gt;head;\n priority_queue_node* tmp = *node;\n\n if (queue-&gt;comparator(tmp, head))\n {\n queue-&gt;head = tmp;\n tmp-&gt;nxt = head;\n }\n else\n {\n while (head &amp;&amp; head-&gt;nxt)\n {\n if (!queue-&gt;comparator(tmp, head-&gt;nxt))\n break;\n head = head-&gt;nxt;\n }\n tmp-&gt;nxt = head-&gt;nxt;\n head-&gt;nxt = tmp;\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T17:57:55.547", "Id": "526398", "Score": "0", "body": "Thanks. Good point about drawling a line between priority queue and other details. 1) so `nodedata` could also be a pointer to a `TimerInfo`, and `void*` since you want to make it sort of generic? 2) regarding the comparator, note that I'm just not doing comparing between two priorities but also the timeouts. other than that, do you please mind elaborating on what really could go inside the comparator? in my logic, for e.g: `push()`, there's a bunch of conditions I'm taking into account to ensure the new node gets pushed at the right place..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T17:59:01.197", "Id": "526399", "Score": "0", "body": "and by heap based implementation, you're referring to something like a binary tree?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T20:51:16.490", "Id": "526537", "Score": "1", "body": "This would be good to store [implicitly](https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T04:05:49.797", "Id": "526563", "Score": "0", "body": "@xyf: Yes nodedata should be pointer to TimerInfo and void* as priority queue needn't know details about pointed data. Aim is have loose coupling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T04:14:53.587", "Id": "526564", "Score": "0", "body": "@xyf: Purpose of priority queue is to give nodes based on increasing/decreasing priority. But priority is not defined by queue. It is property of nodedata. So, priority queue will need a comparator to come up with sorted order. Comaprator may know all relevant details about nodedata and its internal properties. So in current example, comparator needs to know about expiry time and priority value (Because if expiry time is same, we pick timer based on priority)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T04:16:25.777", "Id": "526565", "Score": "0", "body": "Yes, I am referring to binary heap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T04:32:55.850", "Id": "526566", "Score": "0", "body": "@nkvns 1) okay so the idea is you cast the `void*` to `TimerInfo*` upon node instantiation, meaning the node itself is generic and isn't only limited to `TimerInfo` yes? 2) I'm afraid I still can't wrap my head around adjusting the comparator part in my logic where the nodes are arranged as they're pushed and before the scheduler begins...3) binary heap as array? not too familiar with it yet but what makes it more efficient?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T12:13:29.087", "Id": "526585", "Score": "2", "body": "`comparator` should not be part of a `node`; apart from the unnecessary memory overhead, what happens if two nodes have different comparators? Ideally there should be a `struct priority_queue` which has members `NodeComparator comparator` and `struct priority_queue_node *head`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T12:38:42.573", "Id": "526587", "Score": "0", "body": "+1 @G.Sliepen. Keeping separate struct for priority_queue and priority_queue_node will help reduce memory overhead because of comparator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T18:56:18.257", "Id": "526596", "Score": "0", "body": "Do you guys mind providing an example with comparator? I’m having trouble following along…plus I feel it’s hard to also justify void *nodedata unless it’s cast to some data structure that also uses expiration and priority since that’s what the pqueue logic is based on" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T17:20:51.923", "Id": "526638", "Score": "0", "body": "@xyf: Added comparator. TimerInfo will keep reftime, which will set when corresponding node is pushed to the queue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T04:41:17.957", "Id": "526669", "Score": "0", "body": "@nkvns thanks a bunch! some follow ups: 1) shouldn't `if (!queue->comparator(tmp, head->nxt))` be otherwise i.e if true, break out of the loop? 2) how are you populating `void *data` for instance inside `CreateNode()` function? It could take `void *data` as a parameter but it needs to be explicitly cast to `TimerInfo` no? If so, how are you going about it? I used your logic and was able to run the code but I am explicitly casting to `TimerInfo` in most places apart from in `push()` where comparator is taking care of it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T15:13:06.533", "Id": "526695", "Score": "0", "body": "Caller of CreateNode should send correctly populated nodedata as void*. It means caller will create TimerInfo, set refTime and pass this as void* to CreateNode. CreateNode needn't look inside nodedata." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T16:17:32.687", "Id": "526701", "Score": "0", "body": "I see, but currently in CreateNode I populate refTime. Since CreateNode takes void *nodedata, the refTime needs to be set before invoking CreateNode? That doesn’t sound great in this regard cause then I’d have to initiallize refTime myself every time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T16:26:01.980", "Id": "526704", "Score": "0", "body": "Again priority queue is a utility. It needn't know details about its user. User need to send data over which it wants prioritised view." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T17:05:14.170", "Id": "526706", "Score": "0", "body": "That’s what I sort of have right now (not compilable but just the logic. I know it’s not exactly what you’d like to see since im explicitly casting to TimerInfo but it’s just I couldn’t think of making CreateNode and PopAndPush type agnostic - https://cplayground.com/?p=komodo-panther-pangolin" } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T12:50:03.850", "Id": "266444", "ParentId": "266304", "Score": "3" } }, { "body": "<p>There seems to be some confusion between this struct:</p>\n<blockquote>\n<pre><code>typedef struct node\n{\n struct node *head;\n char *name;\n int priority;\n unsigned int expiry;\n unsigned int refTime;\n struct node *nxt;\n} Node;\n</code></pre>\n</blockquote>\n<p>and allocation of its instances:</p>\n<blockquote>\n<pre><code>Node *CreateNode(const char *name, unsigned int expiry, int priority)\n{\n Node *node = malloc(sizeof(*node) + strlen(name) + 1);\n node-&gt;name = name;\n</code></pre>\n</blockquote>\n<p>It looks like you meant to write a <em>flexible array member</em>:</p>\n<pre><code>typedef struct node\n{\n struct node *head;\n int priority;\n unsigned int expiry;\n unsigned int refTime;\n struct node *nxt;\n char name[];\n} Node;\n</code></pre>\n<pre><code>Node *CreateNode(const char *name, unsigned int expiry, int priority)\n{\n Node *node = malloc(sizeof *node + strlen(name) + 1);\n if (!node) return node;\n strcpy(node-&gt;name, name);\n</code></pre>\n<p>Note that we accept pointer to <code>const char</code>, because we're making a copy of the name (and we no longer require the caller to keep the string alive for us), and also that we test the result of <code>malloc()</code> so that we don't attempt to dereference any null pointers.</p>\n<hr />\n<p>Pointers passed to vararg functions such as <code>printf</code> are not auto-converted to <code>void*</code> as they are in other contexts, so we need to explicitly cast them:</p>\n<pre><code> printf (&quot;[Head] name: %s, nxt: %p, headExpiry: %d, refTime: %u\\n&quot;,\n head-&gt;name, (void*)head-&gt;nxt, head-&gt;expiry, head-&gt;refTime);\n printf (&quot;[Temp] name: %s, nxt: %p, headExpiry: %d, refTime: %u, Head&gt;Tmp: %d\\n&quot;,\n tmp-&gt;name, (void*)tmp-&gt;nxt, tmp-&gt;expiry, tmp-&gt;refTime, head-&gt;expiry &gt; tmp-&gt;expiry);\n</code></pre>\n<hr />\n<p>We play fast and loose with integer conversion such as this one:</p>\n<blockquote>\n<pre><code> unsigned int timeElapsed = endTime.tv_sec - startTime.tv_sec;\n</code></pre>\n</blockquote>\n<p>We're truncating a <code>long</code> to <code>unsigned int</code> here, which can corrupt the value (remember that maximum <code>unsigned int</code> can be as low as 65536). Use the correct types throughout (I recommend <code>gcc -Wconversion</code> to help identify these; there's too many to list in this answer).</p>\n<hr />\n<p>Similarly, assigning string literals to <code>char *</code> variables can lead to undefined behaviour. It's fairly easy to fix here, as we want to use <code>const char*</code> in most places (use <code>gcc -Wwrite-strings</code> to catch these).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T20:15:16.373", "Id": "526655", "Score": "0", "body": "Good point about the `unsigned int`; this code would be much longer lasting with the proper types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T06:45:06.427", "Id": "527740", "Score": "0", "body": "Thanks. Also do you see any overflow happening at some point say when timer value goes beyond its size which is long?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T10:17:19.353", "Id": "266525", "ParentId": "266304", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T23:01:41.333", "Id": "266304", "Score": "5", "Tags": [ "c", "timer", "embedded", "scheduled-tasks", "pthreads" ], "Title": "A priority based timer using priority queue" }
266304
<p>The following script derives schemas from varied file formats. Can I get this reviewed? What would the improvements look like:</p> <pre><code> def _null_allowed_in_cols(self): for field in self.fields: field[&quot;type&quot;] = self._field_type_converter(field[&quot;type&quot;]) if type(field[&quot;type&quot;]) == list: if &quot;null&quot; not in field[&quot;type&quot;]: field[&quot;type&quot;].insert(0, &quot;null&quot;) else: field[&quot;type&quot;] = [&quot;null&quot;, field[&quot;type&quot;]] def _field_type_converter(self, field_type) -&gt; Union[str, list]: if type(field_type) is dict or type(field_type) is avro.schema.ImmutableDict: return field_type[&quot;type&quot;] elif type(field_type) is list: return list(map(lambda x: self._field_type_converter(x), field_type)) else: return field_type </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T21:22:27.627", "Id": "526206", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765)*." } ]
[ { "body": "<h1><code>_col_type</code></h1>\n<p>You can use a generator expression here to return either the first match or <code>None</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code> # go from this\n def _col_type(self, column_name):\n for column in self.fields:\n if column[&quot;name&quot;] == column_name:\n return column\n return None\n\n # to this\n def _col_type(self, column_name):\n return next((\n col['name'] for col in self.fields if col['name'] == column_name\n ), None)\n</code></pre>\n<h1>Checking types</h1>\n<p>Use <code>isinstance</code> rather than <code>type(val) == cls</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># instead of this\nif type(field[&quot;type&quot;]) == list:\n # do something\n# or this\nif type(val) is dict:\n # do something\n\n# do this instead\nif isinstance(field['type'], list):\n # do something\n\n# or\nif isinstance(field_type, (dict, avro.schema.ImmutableDict)):\n # do something\n</code></pre>\n<h1>When to use lambda vs function</h1>\n<p>In this statement:</p>\n<pre class=\"lang-py prettyprint-override\"><code>list(map(lambda x: self._field_type_converter(x), field_type))\n</code></pre>\n<p>You don't actually need the lambda:</p>\n<pre class=\"lang-py prettyprint-override\"><code>list(map(self._field_type_converter, field_type))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T16:09:42.077", "Id": "266330", "ParentId": "266308", "Score": "1" } } ]
{ "AcceptedAnswerId": "266330", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T01:51:07.367", "Id": "266308", "Score": "0", "Tags": [ "python", "python-3.x", "json", "apache-kafka" ], "Title": "OOP Refactoring" }
266308
<p>This is an implementation of <a href="https://github.com/ajeetdsouza/zoxide" rel="nofollow noreferrer">zoxide</a> in C, it uses a shell alias to <code>cd</code> between directories it stores(as csv in form of &lt;count,path&gt;) or when the directory is invalid it searches for closest matching directories</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; #if defined(__linux__) #include &lt;linux/limits.h&gt; #else #include &lt;sys/syslimits.h&gt; #endif #include &lt;sys/stat.h&gt; #include &lt;unistd.h&gt; #include &lt;pwd.h&gt; #define PATH_ALLOC_SIZE PATH_MAX typedef struct { char *path; size_t freq; } path_rate_t; const char *easycat(const char *l, const char *r); int main (int argc, char *argv[]){ if(argc&gt;1){ char *data_home = getenv(&quot;XDG_DATA_HOME&quot;); const char *homedir; if ((homedir = getenv(&quot;HOME&quot;)) == NULL) { homedir = getpwuid(getuid())-&gt;pw_dir; } if(data_home==NULL){ data_home=malloc(strlen(homedir)+23); // /.local/share/coxide/\0 = 23 if(data_home==NULL){perror(&quot;malloc() returned NULL&quot;);} strcpy(data_home, homedir); strcat(data_home, &quot;/.local/share/coxide/&quot;); } else{ if(realloc(data_home, strlen(data_home)+9)==NULL) {perror(&quot;realloc returned NULL&quot;);} // /coxide/\0 = 9 strcat(data_home, &quot;/coxide/&quot;); } const char* DBFILE = easycat(data_home, &quot;main.csv&quot;); const char* TMPDBFILE = easycat(data_home, &quot;tmp.csv&quot;); mkdir(data_home, S_IRWXU | S_IRWXG | S_IRWXO); FILE *dbfp = fopen(DBFILE, &quot;r&quot;); bool new_db=false; FILE *tmpdbfp = fopen(TMPDBFILE, &quot;w&quot;); if(dbfp==NULL){ new_db=true; dbfp=fopen(DBFILE, &quot;w+&quot;); } if(tmpdbfp==NULL){ tmpdbfp=fopen(TMPDBFILE, &quot;w&quot;); } if(dbfp==NULL||tmpdbfp==NULL){ fputs(&quot;Unable to open file&quot;, stderr); exit(2); } if(argv[1][0]=='-'){ char *resolved_path = malloc(sizeof(char)*PATH_ALLOC_SIZE); if(resolved_path==NULL){perror(&quot;malloc()&quot;);} realpath(argv[2], resolved_path); if(new_db){ fprintf(dbfp, &quot;1,%s\n&quot;, resolved_path); return 0; } path_rate_t buf = {malloc(sizeof(char)*PATH_ALLOC_SIZE), 1}; bool prev_exist=false; while(fscanf(dbfp, &quot;%zu,%s&quot;, &amp;buf.freq, buf.path)==2){ if(strcmp(buf.path, resolved_path)==0 || buf.path[0]=='\0'){ fprintf(tmpdbfp, &quot;%zu,%s\n&quot;, buf.freq+1, buf.path); prev_exist=true; }else{ fprintf(tmpdbfp, &quot;%zu,%s\n&quot;, buf.freq, buf.path); } } if(!prev_exist){ fprintf(tmpdbfp, &quot;1,%s\n&quot;, resolved_path); } rename(TMPDBFILE, DBFILE); } else{ if(new_db){ fputs(&quot;DBFILE was empty, use valid paths to cache directories&quot;, stderr); return 0; } size_t i=0, li=0; path_rate_t most = {malloc(sizeof(char)*PATH_ALLOC_SIZE), 0}; path_rate_t buf = {malloc(sizeof(char)*PATH_ALLOC_SIZE), 1}; while(fscanf(dbfp, &quot;%zu,%s&quot;, &amp;buf.freq, buf.path)==2){ i++; if(buf.freq&gt;most.freq){ if(strstr(buf.path, argv[1])){ //NOTE: dest is as large as source, do I need to use stpncpy stpcpy(most.path, buf.path); most.freq=buf.freq; li=i; } } } if(li!=0){ i=0; fseek(dbfp, i, SEEK_SET); while(fscanf(dbfp, &quot;%zu,%s&quot;, &amp;buf.freq, buf.path)==2){ i++; if(li==i){ fprintf(tmpdbfp, &quot;%zu,%s\n&quot;, most.freq+1, most.path); } else { fprintf(tmpdbfp, &quot;%zu,%s\n&quot;, buf.freq, buf.path); } } rename(TMPDBFILE, DBFILE); puts(most.path); } else{ puts(homedir); } } free((void *)DBFILE); free((void *)TMPDBFILE); fclose(dbfp); } return 0; } const char* easycat(const char *l, const char *h) { char *comb = malloc(strlen(l) + strlen(h) + 1); if(comb==NULL){perror(&quot;malloc()&quot;);} strcpy(comb, l); strcat(comb, h); return comb; } </code></pre> <p>Since it needs to be almost as fast as regular cd, I would appreciate if there were comments on performance or whether there is any unsafe behaviour</p> <p>The shell wrapper function</p> <pre class="lang-sh prettyprint-override"><code>o(){ if [ &quot;$#&quot; -eq 0 ]; then \builtin cd ~ elif [ &quot;$#&quot; -eq 1 ] &amp;&amp; [ &quot;$1&quot; = '-' ]; then \builtin popd elif [ &quot;$#&quot; -eq 1 ] &amp;&amp; [ -d &quot;$1&quot; ]; then \coxide - &quot;$1&quot; # compile the c named coxide \builtin cd &quot;$1&quot; else \builtin cd $(coxide $1) fi } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code> if(data_home==NULL){perror(&quot;malloc() returned NULL&quot;);}\n strcpy(data_home, homedir);\n</code></pre>\n</blockquote>\n<p>So when <code>data_home</code> is null, we print an error message and then go on to use the null pointer anyway? That's UB.</p>\n<p>We do the same with <code>resolved_path</code> and <code>comb</code>, and worse with <code>buf.path</code> and <code>most.path</code>.</p>\n<blockquote>\n<pre><code> if(realloc(data_home, strlen(data_home)+9)==NULL) {perror(&quot;realloc returned NULL&quot;);} // /coxide/\\0 = 9\n strcat(data_home, &quot;/coxide/&quot;);\n</code></pre>\n</blockquote>\n<p>When <code>realloc()</code> succeeds, and returns a non-null pointer, we go ahead and continue using the <em>old</em> pointer? That's also UB.</p>\n<blockquote>\n<pre><code> fputs(&quot;Unable to open file&quot;, stderr);\n</code></pre>\n</blockquote>\n<p>Message should be a whole line (ending in <code>\\n</code>). We should be more helpful, and say <em>which</em> file couldn't be opened, and why.</p>\n<blockquote>\n<pre><code>const char* DBFILE = easycat(data_home, &quot;main.csv&quot;);\nconst char* TMPDBFILE = easycat(data_home, &quot;tmp.csv&quot;);\n</code></pre>\n</blockquote>\n<p>Don't use all-caps for things that are not macros - that unnecessarily panics readers.</p>\n<blockquote>\n<pre><code> path_rate_t most = {malloc(sizeof(char)*PATH_ALLOC_SIZE), 0};\n path_rate_t buf = {malloc(sizeof(char)*PATH_ALLOC_SIZE), 1};\n</code></pre>\n</blockquote>\n<p><code>sizeof (char)</code> can only be 1, so the multiplication is pointless.</p>\n<blockquote>\n<pre><code>free((void *)DBFILE);\nfree((void *)TMPDBFILE);\n</code></pre>\n</blockquote>\n<p>Don't cast object pointers to <code>void*</code> - that's a valid implicit conversion.</p>\n<p><code>easycat()</code> measures <code>l</code> too much. Since we use <code>strlen()</code> already, we should reuse the result rather than have <code>strcat()</code> measure it again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T09:51:56.513", "Id": "526084", "Score": "0", "body": "Thanks, is there anything I could do to increase the performance? because it takes too long when the csv file is too long. Also what error code do I send on exit() when malloc returns NULL?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T10:42:23.920", "Id": "526086", "Score": "0", "body": "Any non-zero exit status should be fine. The main performance problem you have is that you read the whole file every invocation - that's pretty much unavoidable when we have a separate process involved. To fix that, we'd need to convert to a daemon service or implement as a shell function (caching the data until the file is modified)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T08:17:00.963", "Id": "526143", "Score": "1", "body": "[`EXIT_FAILURE`](https://en.cppreference.com/w/c/program/EXIT_status) would be a good choice. Also, instead of `perror()`, consider using [`err()`](https://linux.die.net/man/3/err), which should be available on Linux and BSDs, and for which you can write a drop-in replacement function to support platforms which don't have this function." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T09:32:28.913", "Id": "266317", "ParentId": "266309", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T03:51:00.100", "Id": "266309", "Score": "1", "Tags": [ "c" ], "Title": "Store all most used directories and query for most used directories containing a string" }
266309
<p>I have below code which is going to copy records from one container in cosmos db to another container in cosmos db. I am just worried on not following the best practices and below code might time out when querying the whole database to get only result with &quot;ClassID&quot;. I would appreciate any suggestion as what should I improve in below code. make it async/sync and how can I enumerate in order to overcome any issues in future. As this is an Azure Function which will run first time from beginning but going forward it will be triggered only when there is any changes in Cosmos Db</p> <pre><code>namespace MigrateDbWithChangeFeed { public static class Function1 { [FunctionName(&quot;Function1&quot;)] public static async Task Run([CosmosDBTrigger( databaseName: &quot;databaseName&quot;, collectionName: &quot;collectionName&quot;, StartFromBeginning = true, ConnectionStringSetting = &quot;&quot;, LeaseCollectionName = &quot;leases&quot;, CreateLeaseCollectionIfNotExists = true )] IReadOnlyList&lt;Document&gt; source, DocumentClient client, ILogger log ) { string continuationToken = null; string collectionUrl = UriFactory.CreateDocumentCollectionUri( &quot;databaseName&quot;, &quot;SourceCollection&quot; ).ToString(); do { var feed = client.CreateDocumentQuery( collectionUrl, new SqlQuerySpec( &quot;select * FROM c WHERE IS_DEFINED(c.ClassId)&quot; ), new FeedOptions { MaxItemCount = 10, EnableCrossPartitionQuery = true, RequestContinuation = continuationToken } ).AsDocumentQuery(); var result = feed.ExecuteNextAsync().Result; var itemCount = result.Count; continuationToken = result.ResponseContinuation; foreach( var doc in result ) { var data = (JObject)JsonConvert.DeserializeObject( doc.ToString() ); string partitionkeyValue = string.Concat( data[&quot;ClassId&quot;].Value&lt;string&gt;(), &quot;|&quot;, data[&quot;Project&quot;].Value&lt;string&gt;() ); data.Add( new JProperty( &quot;PartitionKey&quot;, partitionkeyValue ) ); await client.CreateDocumentAsync( UriFactory.CreateDocumentCollectionUri( &quot;SourceDatabase&quot;, &quot;TargetCollection&quot; ), data ); } } while( continuationToken != null ); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T07:16:05.683", "Id": "526075", "Score": "1", "body": "Welcome to Stack Review, if you think it can be applied to your question you can add the tag `azure-cosmosdb` or another tag related to databases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T06:35:21.023", "Id": "526139", "Score": "0", "body": "implemented await..thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T06:59:57.880", "Id": "526140", "Score": "0", "body": "You are welcome." } ]
[ { "body": "<p>I'm not familiar with Azure Functions and CosmosDb, so I won't review your code from API consumption perspective.</p>\n<p>Here are my observations:</p>\n<ul>\n<li><code>FunctionNameAttribute</code>: Please prefer <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof\" rel=\"nofollow noreferrer\">nameof operator</a> over hard-coded values\n<ul>\n<li>If you rename your class (from <code>Function1</code>) then the hard-coded value will\nnot change with it accordingly</li>\n<li>On the other hand if you need to refer <code>Function1</code> elsewhere in your cloud application then create a <a href=\"https://stackoverflow.com/questions/842590/static-constants-in-c-sharp\">static class where you store your constants</a></li>\n</ul>\n</li>\n<li><code>collectionUrl</code>: I think you don't need to create a separate variable for this, you can simply inline it\n<ul>\n<li><code>CreateDocumentQuery</code> does have an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.documents.idocumentclient.createdocumentquery?view=azure-dotnet#Microsoft_Azure_Documents_IDocumentClient_CreateDocumentQuery_System_Uri_Microsoft_Azure_Documents_SqlQuerySpec_Microsoft_Azure_Documents_Client_FeedOptions_\" rel=\"nofollow noreferrer\">overload which accepts an Uri</a></li>\n</ul>\n</li>\n</ul>\n<pre><code>client.CreateDocumentQuery(\n UriFactory.CreateDocumentCollectionUri(&quot;databaseName&quot;, &quot;SourceCollection&quot;),\n new SqlQuerySpec(&quot;SELECT * FROM c WHERE IS_DEFINED(c.ClassId)&quot;),\n new FeedOptions { ... });\n</code></pre>\n<ul>\n<li><code>feed.ExecuteNextAsync().Result</code>: Please <a href=\"https://stackoverflow.com/questions/27464287/what-is-the-difference-between-await-taskt-and-taskt-result\">prefer async calls over blocking sync calls</a></li>\n<li><code>result.Count</code>: As I said I'm not familiar with this API but I would suggest to do some checks on the <code>FeedResponse</code> <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.documents.client.feedresponse-1?view=azure-dotnet\" rel=\"nofollow noreferrer\">object</a> to make sure that your issued operation has succeeded before you start to consume it</li>\n<li><code>itemCount</code>: As I can see it is unused so you can freely get rid of it</li>\n<li><code>(JObject)JsonConvert.DeserializeObject</code>: Please prefer <a href=\"https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Parse.htm\" rel=\"nofollow noreferrer\">JObject.Parse</a> to semi parse json strings\n<ul>\n<li>Please also bear in mind that this might <a href=\"https://stackoverflow.com/questions/29830198/newtonsoft-jobject-parse-throws-base-exception-how-to-handle/29830612\">throw exception</a> (<code>JsonReaderException</code>) if not valid json is retrieved for whatever reason</li>\n</ul>\n</li>\n<li><code>data[&quot;ClassId&quot;]</code>: Please prefer <a href=\"https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_TryGetValue.htm\" rel=\"nofollow noreferrer\">TryGetValue method</a> over index operator in production code\n<ul>\n<li>You can examine data existence before you start to using it</li>\n</ul>\n</li>\n<li><code>data[&quot;ClassId&quot;].Value&lt;string&gt;()</code>: You can convert the <code>JToken</code> to <code>string</code> with simple casting: <code>(string)data[&quot;ClassId&quot;]</code></li>\n<li><code>string.Concat</code>: Please prefer <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a> over explicit call of concat.</li>\n<li><code>data.Add(new JProperty ...)</code>: I think you don't need to create a <code>JProperty</code> explicitly, there is an other <a href=\"https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_Linq_JObject_Add.htm\" rel=\"nofollow noreferrer\">overload</a>, which accepts the same as the JProperty constructor</li>\n<li><code>var data</code>: Please try to use better naming than this, <code>data</code> is meaningless</li>\n<li><code>continuationToken != null</code>: Please prefer <code>string.IsNullOrEmpty</code> over direct null check against string variable</li>\n</ul>\n<hr />\n<p><strong>UPDATE</strong>: How to use <code>TryGetValue</code></p>\n<p>ZZZSharePoint has pointed out that the provided link for <code>TryGetValue</code> is insufficient to put theory into practice. So, here is my suggestion how to apply that function onto this problem:</p>\n<pre><code>const string classIdFieldName = &quot;ClassId&quot;, projectFieldName = &quot;Project&quot;;\nconst string collectionName = &quot;SourceCollection&quot;, partitionKeyFieldName = &quot;PartitionKey&quot;;\n \nvar semiParsedFetchedRecord = JObject.Parse(doc);\nif(!semiParsedFetchedRecord.TryGetValue(classIdFieldName, out var classIdField))\n throw new MissingFieldException(collectionName, classIdFieldName);\n\nif (!semiParsedFetchedRecord.TryGetValue(projectFieldName, out var projectField))\n throw new MissingFieldException(collectionName, projectFieldName);\n\nsemiParsedFetchedRecord.Add(partitionKeyFieldName, $&quot;{classIdField} | {projectField}&quot;);\n</code></pre>\n<ul>\n<li>I've introduced several constants to make maintenance (and reuse) easier</li>\n<li>I've used <code>JObject.Parse</code> to get a semi-parsed json (I've renamed your <code>data</code> variable to express what's stored inside it)</li>\n<li>I've used <code>TryGetValue</code> to make data retrieval operation safe\n<ul>\n<li>I've used here the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables\" rel=\"nofollow noreferrer\">out var</a> feature of C# to make the code more concise</li>\n<li>otherwise we need to declare a <code>JToken</code> variable before the\n<code>TryGetValue</code> call</li>\n</ul>\n</li>\n<li>I've used <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.missingfieldexception\" rel=\"nofollow noreferrer\"><code>MissingFieldException</code></a> to indicate that something expected is missing\n<ul>\n<li><code>ArgumentException</code> might be a good choice as well</li>\n<li>Or if we can ignore those records where the expected fields are missing then a simple <code>continue</code> might be okay as well</li>\n</ul>\n</li>\n<li>Last but not least I've inlined the <code>partitionKey</code> calculation\n<ul>\n<li>Here I've took advantage of the <a href=\"https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_Linq_JToken_op_Explicit.htm\" rel=\"nofollow noreferrer\">JToken's explicit conversion operators</a></li>\n</ul>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T06:34:35.713", "Id": "526137", "Score": "1", "body": "wow!! people like you are reason why Stack-exchange is so successful. THANKS!!! I did all changes but cant figure out TryGetValue method. How do I do that? I didnt get any idea from the link." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T07:17:00.310", "Id": "526141", "Score": "1", "body": "@ZZZSharePoint I've extended my post with that, please check it again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T14:31:43.697", "Id": "266324", "ParentId": "266313", "Score": "5" } } ]
{ "AcceptedAnswerId": "266324", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T06:29:41.767", "Id": "266313", "Score": "4", "Tags": [ "c#", "azure-cosmosdb" ], "Title": "Enumerating my method to handle any time out issue" }
266313
<h3>description:</h3> <ul> <li>I'm using <code>thrift</code> to save and get data by filter.</li> <li>The data have many types, and the types may increase in the future. So I use <code>switch-case</code> to handle it in <code>save</code>, but it leads to a lot of duplicated code.</li> <li>Then when I wrote <code>getByFilter</code> code (basically the reverse of input-output in <code>save</code>), I tried to use <code>reflection</code> and <code>generics</code> to reduce the duplicated code.</li> </ul> <h3>origin code in <code>save</code>:</h3> <pre><code> public void save(List&lt;ThActInfos&gt; info, long timestamp) throws TException { for (ThActInfos thActInfos : info) { switch (thActInfos.getSetField()) { case IMAGE: saveImage(thActInfos.getImage(), timestamp); break; case INSTALL: saveInstall(thActInfos.getInstall(), timestamp); break; case PID: savePid(thActInfos.getPid(), timestamp); break; case RUN_ACTIVE: saveRunActive(thActInfos.getRunActive(), timestamp); break; case UNINSTALL: saveUninstall(thActInfos.getUninstall(), timestamp); break; case LOGCAT: saveLogcat(thActInfos.getLogcat(), timestamp); break; default: } } } private void saveImage(ThImageInfo info, long timestamp) { if (info.getActionTime() == 0L) {info.setActionTime(timestamp);} ImageInfo imageInfo = ImageInfo.fromThrift(info); imageInfoMapper.insert(imageInfo); } private void saveInstall(ThInstallInfo info, long timestamp) { if (info.getActionTime() == 0L) {info.setActionTime(timestamp);} InstallInfo installInfo = InstallInfo.fromThrift(info); installInfoMapper.insert(installInfo); } private void savePid(ThPidInfo info, long timestamp) { if (info.getActionTime() == 0L) {info.setActionTime(timestamp);} PidInfo pidInfo = PidInfo.fromThrift(info); pidInfoMapper.insert(pidInfo); } private void saveRunActive(ThRunActivity info, long timestamp) { if (info.getActionTime() == 0L) {info.setActionTime(timestamp);} RunActivityInfo runActivityInfo = RunActivityInfo.fromThrift(info); runActivityInfoMapper.insert(runActivityInfo); } private void saveUninstall(ThUninstallInfo info, long timestamp) { if (info.getActionTime() == 0L) {info.setActionTime(timestamp);} UninstallInfo uninstallInfo = UninstallInfo.fromThrift(info); uninstallInfoMapper.insert(uninstallInfo); } private void saveLogcat(ThLogcatInfo info, long timestamp) { if (info.getActionTime() == 0L) {info.setActionTime(timestamp);} LogcatInfo logcatInfo = LogcatInfo.fromThrift(info); logcatInfoMapper.insert(logcatInfo); } </code></pre> <h3>what I have tried in <code>getByFilter</code>:</h3> <pre><code> private Map&lt;String, Object&gt; getTypeMapper() { return new HashMap&lt;String, Object&gt;() {{ put(&quot;image&quot;,imageInfoMapper); put(&quot;install&quot;,installInfoMapper); put(&quot;pid&quot;, pidInfoMapper); put(&quot;runActivity&quot;, runActivityInfoMapper); put(&quot;uninstall&quot;, uninstallInfoMapper); put(&quot;logcat&quot;, logcatInfoMapper); }}; } @Override public List&lt;ThActInfos&gt; getByFilter(Map&lt;String, AnyType&gt; filter) { Map&lt;String, Object&gt; cond = new HashMap&lt;&gt;(); for (Map.Entry&lt;String, AnyType&gt; entry : filter.entrySet()) { cond.put(entry.getKey(), CoreDataUtils.convertAnyToJava(entry.getValue())); } String type = cond.getOrDefault(&quot;type&quot;, &quot;None&quot;).toString(); List&lt;ThActInfos&gt; result = new ArrayList&lt;&gt;(); Map&lt;String, Object&gt; typeMapper = getTypeMapper(); try { Object obj = typeMapper.get(type); String classPath = &quot;com.testing.mapper.&quot; + toUpperCase(type) + &quot;InfoMapper&quot;; Method method = Class.forName(classPath).cast(obj).getClass() .getMethod(&quot;selectByCondition&quot;, Map.class); result = template(Class.forName(&quot;com.thrift.entity.Th&quot; + toUpperCase(type) + (toUpperCase(type).equals(&quot;RunActivity&quot;) ? &quot;&quot; : &quot;Info&quot;)),type,method,obj,cond); } catch (ClassNotFoundException | NoSuchMethodException e) { e.printStackTrace(); } return result; } private &lt;E,T&gt; List&lt;ThActInfos&gt; template(T thType,String type,Method method,Object obj,Map&lt;String, Object&gt; cond){ List&lt;ThActInfos&gt; ans = new ArrayList&lt;&gt;(); try { List&lt;E&gt; results = (List&lt;E&gt;) method.invoke(obj, cond); ans = new ArrayList&lt;&gt;(); for (E result : results) { ThActInfos temp = new ThActInfos(); Method toThriftMethod = result.getClass().getMethod(&quot;toThrift&quot;); Method setMethod = temp.getClass() .getMethod(&quot;set&quot; + ((type.equals(&quot;runActivity&quot;)) ? &quot;RunActive&quot; : toUpperCase(type)) , (Class&lt;T&gt;) thType); setMethod.invoke(temp,toThriftMethod.invoke(result)); ans.add(temp); } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e){ e.printStackTrace(); } return ans; } </code></pre> <ul> <li>It does reduce the duplicated code, but it is obviously much more complicated and hard to read to the co-workers who are not familiar with <code>reflection</code> and <code>generics</code>.</li> </ul> <h3>question:</h3> <ul> <li>Any better solution to deal with this situation?</li> </ul>
[]
[ { "body": "<p>Whenever Java code contains this sort of switch statement and large portions of nearly identical code, then it probably (almost certainly) indicates that you've got your object model wrong.</p>\n<p>I don't know anything about Thrift, so can't comment on that aspect, but I'd expect that a good start would be to make much more use of Abstract classes and/or interfaces.</p>\n<p>Your various info classes that you retrieve from Thrift should either extend an abstract superclass or implement an interface - let's say <code>ThriftInfo</code>. Then your various type mappers could likewise extend a superclass or implement an interface - say 'InfoMapper' - with an insert(ThriftInfo) method.</p>\n<p>Your ThActInfos (perhaps renamed in the singular) class could be an abstract class or implement an interface with a <code>save()</code> method. Subclasses would then be based on the type of data - image, install, etc - they deal with.</p>\n<p>The save method could be passed the map of mappers you've already outlined and the specific implementation could pick out the the mapper it needed.</p>\n<p>On that basis, given the map exists - as <code>Map&lt;String, InfoMapper&gt; typeMappers</code> - your main loop would look something like:</p>\n<pre><code> for (ThActInfos thActInfos : info) {\n thActInfos.save(typeMappers);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T08:28:15.747", "Id": "266371", "ParentId": "266314", "Score": "1" } } ]
{ "AcceptedAnswerId": "266371", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T07:59:23.447", "Id": "266314", "Score": "0", "Tags": [ "java", "generics", "reflection" ], "Title": "How to save/get different type of data with less duplicated code" }
266314
<p>I am a student who wrote logic to theme switcher, but I don't know if everything is ok. I want professionals to estimate my code and will say what is probably mistaken. I accept all recommendations and criticism. Thank you in advance.</p> <p>gitHub: <a href="https://github.com/Alexander-Korniichuk/React_Theme_Switcher/commit/f70f3cceb81c484d4dab0bd7799cd234ee39d4fe" rel="nofollow noreferrer">https://github.com/Alexander-Korniichuk/React_Theme_Switcher/commit/f70f3cceb81c484d4dab0bd7799cd234ee39d4fe</a></p> <p>src/components/ThemeSwitcherApp/</p> <pre><code>import React, {useEffect, useState, useMemo, useCallback} from &quot;react&quot;; import DarkStyles from &quot;../DarkStyles/DarkStyles&quot;; export const ThemeSwitcherApp = () =&gt; { const key = &quot;DARK_THEME&quot;; const saveJSON = (key, data) =&gt; { if (window[`localStorage`] === null) return return localStorage.setItem(key, JSON.stringify(data)); }; const loadJSON = key =&gt; { if (window[`localStorage`] === null) return return key &amp;&amp; JSON.parse(localStorage.getItem(key)); }; const [themeIsActive, setThemeIsActive] = useState(loadJSON(key) ? loadJSON(key).darkMode : false); const [button_text_value, setButton_text_value] = useState(themeIsActive ? &quot;Turn off&quot; : &quot;Turn on&quot;); const theme_data_false = useMemo(() =&gt; ({darkMode: false}), []); const theme_data_true = useMemo(() =&gt; ({darkMode: true}), []); const insertDarkStyles = (where) =&gt; { const style = document.createElement(`style`); style.setAttribute(`id`, `dark-mode`); style.innerHTML = DarkStyles; where.append(style); }; const ActiveDarkTheme = useCallback( () =&gt; { insertDarkStyles(document.getElementsByTagName(`head`)[0]); setButton_text_value(&quot;Turn off&quot;); saveJSON(key, theme_data_true); }, [theme_data_true] ) const DeactivateDarkTheme = useCallback( () =&gt; { const isDarkModeExist = !!document.getElementById(`dark-mode`); if (isDarkModeExist) { document.getElementById(`dark-mode`).remove(); setButton_text_value(&quot;Turn on&quot;); saveJSON(key, theme_data_false); } }, [theme_data_false] ) const ThemeStorageLoading = useCallback( (key, data) =&gt; { if (!localStorage.getItem(key)) { saveJSON(key, data); } else { if (loadJSON(key).darkMode) { ActiveDarkTheme(); } else { DeactivateDarkTheme(); } } }, [ActiveDarkTheme, DeactivateDarkTheme]); useEffect(() =&gt; { // Once Loading ThemeStorageLoading(key, theme_data_false); }, [theme_data_false, ThemeStorageLoading]); const ButtonAction = (bool_value) =&gt; { setThemeIsActive(bool_value); if (bool_value) ActiveDarkTheme(); else DeactivateDarkTheme(); }; return ( &lt;div&gt; &lt;input type=&quot;button&quot; onClick={() =&gt; ButtonAction(!themeIsActive)} defaultValue={button_text_value} style={{cursor: &quot;pointer&quot;}} /&gt; &lt;/div&gt; ); } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<ul>\n<li>variable <code>key</code> can relate to anything. I'd just call this variable <code>theme</code></li>\n<li>I'd also avoid naming the function parameter <code>where</code></li>\n<li>If You are using an arrow function and it has one parameter then You can avoid adding <code>()</code> around it</li>\n<li>Why can't You just use <code>button</code> instead of <code>&lt;input type=&quot;button&quot;&gt;</code>?</li>\n<li><code>style={{cursor: &quot;pointer&quot;}}</code> I'd remove that from the JSX and place that in the css document</li>\n<li>Sometimes you name things with <code>camelCase</code> and sometimes You use <code>such_a_thing</code>. Try to stay consistent</li>\n<li>Function names inside Your component should start with lowercase</li>\n<li>It's a good practice to use <code>{}</code> to wrap the blocks of code in Your <code>if/else</code> statements</li>\n<li>Additionally, I'd change the approach a little bit. If I had the task to do the theme switching functionality, I'd create the toggle which will change the <code>isDarkMode</code> flag to <code>true/false</code>. If the flag is true, then I would add the <code>dark-mode-active</code> on the body element of the page. After that I would create the proper CSS file and put the dark mode related styles to the class we've just attached to the body element.</li>\n<li><code>Once loading</code> this comment is not necessary. Use comments to describe some workarounds / hacks / code tricks but such a fundamental functionality like <code>useEffect</code> does not require any comments :)</li>\n</ul>\n<p>I hope that You will find the above feedback useful. Good job with the above and good luck with the improvements</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T07:39:08.273", "Id": "266518", "ParentId": "266318", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T09:53:40.993", "Id": "266318", "Score": "0", "Tags": [ "javascript", "react.js" ], "Title": "My Theme Switcher App has a need to be criticized" }
266318
<p>I am working on a Data-based application.</p> <p>I wrote a code to filter the table. The table has <code>String</code> and <code>Numbers</code>.</p> <p>I some filter for string, like min word count, max word count, string includes and excludes For Numbers, I also have filters like min, max.</p> <p>This is my code,</p> <pre><code>var props = { rows: [ { keywordIdeaMetrics: { competition: &quot;LOW&quot;, monthlySearchVolumes: [ { month: &quot;JUNE&quot;, year: &quot;2020&quot;, monthlySearches: &quot;60500&quot;, }, { month: &quot;JULY&quot;, year: &quot;2020&quot;, monthlySearches: &quot;49500&quot;, }, { month: &quot;AUGUST&quot;, year: &quot;2020&quot;, monthlySearches: &quot;40500&quot;, }, { month: &quot;SEPTEMBER&quot;, year: &quot;2020&quot;, monthlySearches: &quot;33100&quot;, }, { month: &quot;OCTOBER&quot;, year: &quot;2020&quot;, monthlySearches: &quot;33100&quot;, }, { month: &quot;NOVEMBER&quot;, year: &quot;2020&quot;, monthlySearches: &quot;40500&quot;, }, { month: &quot;DECEMBER&quot;, year: &quot;2020&quot;, monthlySearches: &quot;40500&quot;, }, { month: &quot;JANUARY&quot;, year: &quot;2021&quot;, monthlySearches: &quot;40500&quot;, }, { month: &quot;FEBRUARY&quot;, year: &quot;2021&quot;, monthlySearches: &quot;40500&quot;, }, { month: &quot;MARCH&quot;, year: &quot;2021&quot;, monthlySearches: &quot;40500&quot;, }, { month: &quot;APRIL&quot;, year: &quot;2021&quot;, monthlySearches: &quot;40500&quot;, }, { month: &quot;MAY&quot;, year: &quot;2021&quot;, monthlySearches: &quot;49500&quot;, }, ], avgMonthlySearches: &quot;40500&quot;, competitionIndex: &quot;2&quot;, lowTopOfPageBidMicros: &quot;1537028&quot;, highTopOfPageBidMicros: &quot;31453279&quot;, }, text: &quot;paleo diet&quot;, keywordAnnotations: {}, }, // almost 500 more objects ], }; var filters = [ { property: &quot;avgMonthlySearches&quot;, type: &quot;NUMBER&quot;, min: 100, }, { property: &quot;keyword&quot;, filterType: &quot;INCLUDE&quot;, type: &quot;STRING&quot;, wordFilterType: &quot;Any word&quot;, words: [&quot;how&quot;, &quot;what&quot;], }, ]; var result = props.rows.filter((row) =&gt; { var isPassed = false; var FiltersLen = filters.length; for (var i = 0; i &lt; FiltersLen; i++) { var filter = filters[i]; if (filter.property === &quot;keyword&quot;) { row.keywordIdeaMetrics.keyword = row.text; } if (filter.type === &quot;NUMBER&quot;) { if (filter.min &amp;&amp; filter.max) { if ( Number(row.keywordIdeaMetrics[filter.property]) &gt; filter.min &amp;&amp; Number(row.keywordIdeaMetrics[filter.property]) &lt; filter.max ) { isPassed = true; } } if ( filter.min &amp;&amp; Number(row.keywordIdeaMetrics[filter.property]) &gt; filter.min ) { isPassed = true; } if ( filter.max &amp;&amp; Number(row.keywordIdeaMetrics[filter.property]) &lt; filter.max ) { isPassed = true; } } else if (filter.type === &quot;STRING&quot;) { if (filter.filterType === &quot;INCLUDE&quot;) { if (filter.wordFilterType === &quot;Any word&quot;) { if ( // eslint-disable-next-line no-loop-func filter.words.some(function (v) { return ( row.keywordIdeaMetrics[filter.property] .toLowerCase() .indexOf(v) &gt;= 0 ); }) ) { isPassed = true; } } else if (filter.wordFilterType === &quot;All words&quot;) { if ( // eslint-disable-next-line no-loop-func filter.words.every((item) =&gt; row.keywordIdeaMetrics[filter.property] .toLowerCase() .includes(item) ) ) { isPassed = true; } } } else if (filter.filterType === &quot;EXCLUDE&quot;) { if (filter.wordFilterType === &quot;Any word&quot;) { if ( // eslint-disable-next-line no-loop-func filter.words.some(function (v) { return ( !row.keywordIdeaMetrics[filter.property] .toLowerCase() .indexOf(v) &gt;= 0 ); }) ) { isPassed = true; } } else if (filter.wordFilterType === &quot;All words&quot;) { if ( // eslint-disable-next-line no-loop-func filter.words.every( (item) =&gt; !row.keywordIdeaMetrics[filter.property] .toLowerCase() .includes(item) ) ) { isPassed = true; } } } } if (isPassed) { if (i === FiltersLen - 1) { return true; } else { isPassed = false; } continue; } else { return false; } } }); console.log(result); </code></pre> <p>I want to know is there any better way to perform this filter (performance-wise)?</p> <p><strong>Note:</strong> <em>It's a real-world project.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T02:59:18.787", "Id": "526124", "Score": "1", "body": "Thanks for your feedback, I update the question can you please further look at it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T04:43:19.850", "Id": "526128", "Score": "0", "body": "Looks good, thanks a bunch!" } ]
[ { "body": "<p>Its seems like you have all the logic to filter the <code>rows</code> centralised, and the use the external <code>filters</code> array to decide which filters to apply. This makes your code kind of complex.</p>\n<p>Why not let each of the entries in <code>filters</code> be a function that takes a <code>row</code> as an input, and returns <code>true</code> if it should be filtered? Then, you could simply change the way you filter <code>rows</code> to something like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>rows.filter(row =&gt; filters.some(filter =&gt; filter(row)))\n</code></pre>\n<p>Also, that makes it easier to modify the filters, as each one of them is separated into its own function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T12:49:58.430", "Id": "526161", "Score": "0", "body": "seems nice can you please share the code to create the filter function? Because I am using react with the functional component. How to create and update functions (on user input?)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T19:02:36.260", "Id": "266334", "ParentId": "266326", "Score": "2" } }, { "body": "<p>You have provided limited information in regard to what and how to filter the data. Thus this review looks at just an array (table of records) and how to build complex searches using functions built into the filter object.</p>\n<h2>Complex filters</h2>\n<p>As you have the filter you filter while you parse the filter. This adds overhead to processing the table.</p>\n<p>It also makes the filter function many times more complex than it should be. Adding additional filters will increase that complexity, and as all filters rely on the same parser if you change just part of one you risk breaking all filters.; This makes the code hard to maintain and very susceptible to bugs.</p>\n<p>Defining filters as named functions lets you separate the logic for each filter from any other filters. Defining a new type of filter is then just a matter of adding the filter function.</p>\n<p>The defined function must use a consistent interface, and have access to a state that provides the information needed to perform the filter operation.</p>\n<p>The example filter functions below takes the <code>rec</code> (record AKA row) as an argument and returns a <code>Boolean</code>\nThe filter properties (eg <code>min</code>, <code>max</code>) are bound to the function via the <code>this</code> token</p>\n<p><strong>Note</strong> If the filter function is in an array you will need to bind the function to each items using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Function bind\">Function.bind</a></p>\n<h2>Filter types</h2>\n<p>The following code defines 6 filters by named functions.</p>\n<ul>\n<li><p><code>filters.all</code> Returns true if all filters in an array filters match</p>\n</li>\n<li><p><code>filters.number.minMax</code> Returns true if min &lt;= field &lt;= max</p>\n</li>\n<li><p><code>filter.string.include.all</code> Returns true if all words are included</p>\n</li>\n<li><p><code>filter.string.include.any</code> Returns true if any word is included</p>\n</li>\n<li><p><code>filter.string.exclude.all</code> You get the picture</p>\n</li>\n<li><p><code>filter.string.exclude.any</code> ditto</p>\n</li>\n</ul>\n<pre><code>const filters = {\n all(rec) {\n return this.filters.every(filter =&gt; filter.filter.bind(filter)(rec));\n },\n number: {\n minMax(rec) {\n const val = Number(rec[this.field]);\n return (this.min ?? -Infinity) &lt;= val &amp;&amp; (this.max ?? Infinity) &gt;= val;\n },\n },\n string: {\n include: {\n all(rec) {\n const val = rec[this.field].toLowerCase();\n return this.words.every(str =&gt; val.includes(str.toLowerCase()));\n },\n any(rec) {\n const val = rec[this.field].toLowerCase();\n return this.words.some(str =&gt; val.includes(str.toLowerCase()));\n }\n },\n exclude: {\n all(rec) {\n const val = rec[this.field].toLowerCase();\n return this.words.every(str =&gt; !val.includes(str.toLowerCase()));\n },\n any(rec) {\n const val = rec[this.field].toLowerCase();\n return this.words.some(str =&gt; !val.includes(str.toLowerCase()));\n }\n }\n },\n};\n</code></pre>\n<p>You then define a filter using</p>\n<pre><code>const testFilter = {\n filter: filters.all,\n filters: [{\n filter: filters.number.minMax,\n field: &quot;monthlySearches&quot;,\n min: 40500,\n }, {\n filter: filters.string.include.any,\n field: &quot;month&quot;,\n words: [&quot;A&quot;, &quot;B&quot;],\n },\n ],\n};\n</code></pre>\n<p>And to use the filter you apply the via a function that takes the filter and an array of records</p>\n<pre><code>function applyFilter(filter, table) {\n return table.filter(filter.filter.bind(filter));\n}\nconst result = applyFilter(testFilter, rows);\n\n</code></pre>\n<h2>Encapsulate filter state</h2>\n<p>To encapsulate each filter and ensure that it has the correct state to perform its task you can define the filter function using a function. Example below the function <code>filters.number.minMax</code> returns the filter function with the filter state (<code>field</code>, <code>min</code>, <code>max</code>) encapsulate via closure.</p>\n<p>You can also provide a filter create function. eg</p>\n<pre><code>// define\nconst filters = { \n number: {\n minMax(field, min, max) {\n return (rec) =&gt; {\n const val = Number(rec[field]);\n return (min ?? -Infinity) &lt;= val &amp;&amp; (max ?? Infinity) &gt;= val;\n }\n },\n },\n};\n\n// create\nconst testFilter = {\n filter: filters.number.minMax(&quot;monthlySearches&quot;, 40000),\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T05:53:20.957", "Id": "526212", "Score": "0", "body": "I will definitely follow this! BTW in meanwhile, I just have a question I have 500-1000 rows to filter! Is this work fine? (performance-wise?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T07:53:58.940", "Id": "526221", "Score": "0", "body": "@RohitNishad 1000 rows Yes easy fast, depending on the filter of course. Should do a few hundred thousand + rows per second on a low end device" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T07:55:54.017", "Id": "531376", "Score": "0", "body": "Well, You are calling `.filter` function too many time which. Which causes lag in UI." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T21:10:05.623", "Id": "531437", "Score": "0", "body": "@RohitNishad The example only calls a filter function at most once per filter per record. The order of filters called will make a difference in number of calls. If you experience UI lag you should should move the task to a separate thread or break the task into smaller chunks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T05:28:29.190", "Id": "531452", "Score": "0", "body": "seams complicated :( any blog or link?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T19:09:35.437", "Id": "266361", "ParentId": "266326", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T14:35:44.500", "Id": "266326", "Score": "2", "Tags": [ "javascript", "performance", "object-oriented", "array" ], "Title": "Complex Filter in one Opration" }
266326
<p>I originally posted this on SO, and I know cross-linking is generally frowned upon. But, I am not sure if this falls under question or code review because the code works where I do not know if it is implemented correctly. Anyways, here it is:</p> <p><a href="https://stackoverflow.com/questions/68868685/need-help-demystifying-the-new-feature-introduced-on-microsoft-graph-4-0-0">https://stackoverflow.com/questions/68868685/need-help-demystifying-the-new-feature-introduced-on-microsoft-graph-4-0-0</a></p> <p><strong>Question:</strong></p> <p>Do we need to acquire the access token from <code>Microsoft.Graph</code> using either <code>silent</code> or <code>interactive</code> modes? From what I can tell the answer is, No. (see <strong>Context</strong> below)</p> <p>The new implementation seems to be drastically scaled down with the whole idea of <code>silent</code> and <code>interactive</code> token retrieval being removed. Is this correct?</p> <pre><code>using Azure.Identity; using Microsoft.Graph; using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var scopes = new[] { &quot;User.Read&quot; }; // Multi-tenant apps can use &quot;common&quot;, // single-tenant apps must use the tenant ID from the Azure portal var tenantId = &quot;SomeGuid&quot;; // Value from app registration var clientId = &quot;SomeGuid&quot;; var options = new InteractiveBrowserCredentialOptions { TenantId = tenantId, ClientId = clientId, AuthorityHost = AzureAuthorityHosts.AzurePublicCloud, // MUST be http://localhost or http://localhost:PORT // See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core RedirectUri = new Uri(&quot;http://localhost:1234&quot;), }; // https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential var interactiveCredential = new InteractiveBrowserCredential(options); var graphClient = new GraphServiceClient(interactiveCredential, scopes); // Interactive browser login occurs here. var me = graphClient.Me.Request().GetAsync().Result; // Printing the results Console.WriteLine(&quot;-------- Data from call to MS Graph --------&quot;); Console.Write(Environment.NewLine); Console.WriteLine($&quot;Id: {me.Id}&quot;); Console.WriteLine($&quot;Display Name: {me.DisplayName}&quot;); Console.WriteLine($&quot;Email: {me.Mail}&quot;); //Console.ReadLine(); } } } </code></pre> <p><strong>Context:</strong></p> <p>As part of our routine maintenance, I was tasked with upgrading our NuGet packages on a Winforms desktop application that is running in Azure and whose users are in Azure Active Directory Services (AADS). One of the packages, <code>Microsoft.Graph</code>, had a major version change. <a href="https://www.nuget.org/packages/Microsoft.Graph/4.0.0" rel="nofollow noreferrer">https://www.nuget.org/packages/Microsoft.Graph/4.0.0</a></p> <p>The documentation on it indicated a new feature for handling the <code>TokenCredentialClass</code>. <a href="https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/4.0.0/docs/upgrade-to-v4.md#new-capabilities" rel="nofollow noreferrer">https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/4.0.0/docs/upgrade-to-v4.md#new-capabilities</a></p> <p>From what I can tell, there is a separate and distinct break on how the token is retrieved. Previously, we followed the method provided here: <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-windows-desktop#add-the-code-to-initialize-msal" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-windows-desktop#add-the-code-to-initialize-msal</a></p> <p>Old way:</p> <pre><code>using Microsoft.Graph; using Microsoft.Graph.Auth; using Microsoft.Identity.Client; using System; using System.Linq; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { _PublicClientApp = PublicClientApplicationBuilder.Create(ClientId) .WithRedirectUri(&quot;http://localhost:1234&quot;) .WithAuthority(AzureCloudInstance.AzurePublic, TenantId) .Build(); // We sign the user in here bolIsAutorizeSSO = CallMicrosoftSSO().GetAwaiter().GetResult(); InteractiveAuthenticationProvider = new InteractiveAuthenticationProvider(PublicClientApp, Scopes); GraphServiceClient = new Microsoft.Graph.GraphServiceClient(InteractiveAuthenticationProvider); if (bolIsAutorizeSSO) { // We also signt the user in here. var User = GraphServiceClient.Me.Request().GetAsync().Result; // Printing the results Console.WriteLine(&quot;-------- Data from call to MS Graph --------&quot;); Console.Write(Environment.NewLine); Console.WriteLine($&quot;Id: {User.Id}&quot;); Console.WriteLine($&quot;Display Name: {User.DisplayName}&quot;); Console.WriteLine($&quot;Email: {User.Mail}&quot;); } else { // signout Console.ReadLine(); } } public static async Task&lt;bool&gt; CallMicrosoftSSO() { AuthenticationResult authResult = null; var app = PublicClientApp; var accounts = await app.GetAccountsAsync(); try { authResult = await app.AcquireTokenInteractive(Scopes) .WithAccount(accounts.FirstOrDefault()) .WithPrompt(Microsoft.Identity.Client.Prompt.ForceLogin) .ExecuteAsync(); } catch (MsalUiRequiredException _Exception) { // A MsalUiRequiredException happened on AcquireTokenSilent. // This indicates you need to call AcquireTokenInteractive to acquire a token. Console.WriteLine(_Exception.Message); } catch (MsalException msalex) { if (msalex.ErrorCode != &quot;authentication_canceled&quot;) { Console.WriteLine(msalex.Message); } } catch (Exception _Exception) { Console.WriteLine(_Exception.Message); } if (authResult != null) { return true; } return false; } private static string ClientId = &quot;SomeGuid&quot;; private static string TenantId = &quot;SomeGuid&quot;; private static string[] Scopes = new string[] { &quot;User.Read&quot; }; private static Microsoft.Graph.GraphServiceClient GraphServiceClient; private static bool bolIsAutorizeSSO = false; private static InteractiveAuthenticationProvider InteractiveAuthenticationProvider; private static IPublicClientApplication _PublicClientApp; public static IPublicClientApplication PublicClientApp { get { return _PublicClientApp; } } } } </code></pre> <p>I am struggling to make sense of it. Partly because the feature is brand new and there are very few code samples up on the internet that say <code>do it this way</code>. What I have found seems to point me back to what we already are using (more on that in a bit). So, the examples may not yet be fully updated.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T17:55:11.023", "Id": "266332", "Score": "1", "Tags": [ "c#", "security", "authentication", "active-directory", "azure" ], "Title": "Verify implementing Microsoft Graph 4.0.0 for SSO in Azure is implemented correctly" }
266332
<p>I wrote this method which I think is not effective as it doesn't respond to the missing method when I use the PORO Class.</p> <p><strong>BalanceService</strong></p> <pre><code>class BalanceService INITIAL_MULTIPLIER = 1 HUMUS_EFFECT = 1.3 instance_methods.each do |m| undef_method m unless m.to_s =~ /^__|method_missing|respond_to?/ end def initialize(field_data) @field_data = field_data end def method_missing(name, *args) super unless respond_to?(name) # If I remove this line it works. @field_data.map do |field| previous_value = nil multiplier = INITIAL_MULTIPLIER field[:humus_balance] = field[:crops].inject(0) do |balance, crop| (crop[:crop][:value] == previous_value) ? multiplier = multiplier * HUMUS_EFFECT : previous_value = crop[:crop][:value] balance + (crop[:crop][:humus_delta] * field[:area] * multiplier) end field end end def respond_to?(method) @field_data.respond_to?(&quot;get_#{method}_info&quot;) || super end end </code></pre> <p>When I call it in the <code>fetch_field</code> method below I get <code>undefined method &quot;field_data&quot; for #&lt;BalanceService:0x00007fda9c190e28&gt;</code>. However, if I remove <code>super unless respond_to?(name)</code> from BalanceService class above, it works. I indeed want BalanceService to respond to missing methods.</p> <p><strong>FieldService</strong></p> <pre><code>class FieldsService include Singleton def fetch_fields value = BalanceService.new(field_data) value.field_data end private def field_data # some JSON end end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T23:39:17.100", "Id": "526119", "Score": "3", "body": "What do you want to accomplish with this code. It's incredible difficult to understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T10:46:46.340", "Id": "526500", "Score": "0", "body": "Does or doesn't a version with `super unless respond_to?(name)` removed [*work as intended*](https://codereview.stackexchange.com/help/on-topic)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T17:10:14.503", "Id": "527849", "Score": "0", "body": "This is not a PORO. There's nothing Plain about it, it is incredibly complex." } ]
[ { "body": "<p>You balance class does not have a <code>field_data</code> method.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def fetch_fields\n value = BalanceService.new(field_data) \n value.field_data # this method does not exist\nend\n</code></pre>\n<p>So you could implement a <code>attr_reader :field_data</code> but that would be undefined with <code>undef_method</code> (which I don't really get what this is for).</p>\n<p>This should work</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class BalanceService\n INITIAL_MULTIPLIER = 1\n HUMUS_EFFECT = 1.3\n\n instance_methods.each do |m|\n undef_method m unless m.to_s =~ /^__|method_missing|respond_to?/\n end\n\n attr_reader :field_data\n\n def initialize(field_data)\n @field_data = field_data\n end\n\n def method_missing(name, *args)\n super unless respond_to?(name) # If I remove this line it works.\n\n @field_data.map do |field|\n previous_value = nil\n multiplier = INITIAL_MULTIPLIER\n\n field[:humus_balance] = field[:crops].inject(0) do |balance, crop|\n (crop[:crop][:value] == previous_value) ? multiplier = multiplier * HUMUS_EFFECT : previous_value = crop[:crop][:value]\n balance + (crop[:crop][:humus_delta] * field[:area] * multiplier)\n end\n\n field\n end\n end\n\n def respond_to?(method)\n @field_data.respond_to?(&quot;get_#{method}_info&quot;) || super\n end\nend\n\nBalanceService.new({}).field_data\n</code></pre>\n<p>The meta programming here makes it incredible hard to understand what this class is supposed to do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T23:48:15.727", "Id": "266337", "ParentId": "266333", "Score": "2" } }, { "body": "<p>Your &quot;method missing&quot; implementation responds to every method with the same result, ignoring the method name. Essentially you're letting someone call <code>BalanceService.new(data).this_method_does_not_exist == BalanceService.new(data).neither_does_this_one</code> and get <code>true</code>.</p>\n<p>I cannot imagine a reason to do this. Do you mean to call <code>@ field_data .get_#{method}_info</code> somewhere?</p>\n<p>Also, your method call mutates the input data (destructively) which can cause hard-to-understand bugs.</p>\n<p>I'd recommend restructuring to something like:</p>\n<pre><code>class BalanceService\n INITIAL_MULTIPLIER = 1\n HUMUS_EFFECT = 1.3\n \n attr_reader :crops, :area\n def initialize(crops:, area:)\n # Using kwargs throws an error if the expected values are not\n # provided or if you pass in anything unexpected.\n @crops = crops\n @area = area\n end\n\n # This method is still way too complex\n def calculate_humus_balance\n previous_value = nil\n multiplier = INITIAL_MULTIPLIER\n crops.inject(0) do |balance, crop|\n # I'd normally pull the inner loop code out into a method...\n # but we can't easily do this because of \n # the side-effects on previous_value and multiplier \n crop_value, humus_delta = crop[:crop].values_at(:value, :humus_delta)\n if crop_value == previous_value\n multiplier = multiplier * HUMUS_EFFECT\n else\n previous_value = crop_value\n end\n balance + (humus_delta * area * multiplier)\n end\n end\nend\n</code></pre>\n<p>then call the service like</p>\n<pre><code>class FieldsService\n include Singleton\n\n def fetch_fields\n field_data = build_field_data\n field_data.merge(humus_balance: BalanceService.new(**field_data).calculate_humus_balance)\n end\n\n private\n\n def build_field_data\n # some JSON \n end\nend\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T00:27:49.447", "Id": "266436", "ParentId": "266333", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T18:40:02.737", "Id": "266333", "Score": "-2", "Tags": [ "ruby" ], "Title": "How can I make BalanceService PORO I wrote better of any code smell?" }
266333
<p>I have this implementation of Grep where I use <code>re.search</code>:</p> <pre class="lang-py prettyprint-override"><code>#!/bin/python &quot;&quot;&quot; A grep implementation on Python &quot;&quot;&quot; from re import search from sys import argv def grep(word, file): for line in file: if search(word, line): print(line.strip()) if __name__ == &quot;__main__&quot;: try: grep(argv[1], open(argv[2])) except FileNotFoundError: print(&quot;That's not a vaild file.&quot;) except IndexError: print(&quot;Params missing!&quot;) </code></pre> <p>But if instead of using search I:</p> <pre class="lang-py prettyprint-override"><code>def grep(word, file): for line in file: if word in line: print(line.strip()) </code></pre> <p>Which is better or faster? I think the more Pythonic way is the second one.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T00:55:16.847", "Id": "526120", "Score": "4", "body": "why would you reinvent grep? And if you want to reinvent grep, why would you avoid it's regular expression support?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T01:00:14.560", "Id": "526121", "Score": "0", "body": "You're correct, the second one is better [and it's also faster](https://stackoverflow.com/q/19911508/9997212)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T02:01:01.587", "Id": "526122", "Score": "0", "body": "@Vogel612 It's just a programming challenge, I've already passed the tests. I'd just like to know which one is better and why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T06:16:23.530", "Id": "526135", "Score": "0", "body": "@enzo How is it better? It's not even trying to do the job it's supposed to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T13:29:08.873", "Id": "526163", "Score": "0", "body": "@KellyBundy It is not a true Grep implementation, it was just for a challenge that I found on a platform. I just wanted to know which method was more appropriate to take it into account in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T13:41:46.810", "Id": "526168", "Score": "0", "body": "@EliazBobadilla Well, what's more appropriate depends on what you're doing. And it makes absolutely no sense to consider one of them more Pythonic than the other." } ]
[ { "body": "<p>You should use <code>re.escape(...)</code> in the first version, to match behaviour of the second. Without it, special characters in <code>word</code> could be interpreted as regex patterns.</p>\n<p>Catching <code>IndexError</code> only ensures the user has given enough arguments; it does not protect against too many. <code>grep.py hello world file.txt</code> will search file <code>world</code> for the word <code>hello</code>, if it exists, instead of searching <code>file.txt</code> as expected. Check the actual <code>argv</code> length, or better, use the <code>argparse</code> module.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T06:31:51.113", "Id": "526136", "Score": "1", "body": "I disagree with your first paragraph. The \"re\" in \"grep\" even stands for \"regular expression\". If you take that away, you don't have grep anymore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T16:44:45.840", "Id": "526176", "Score": "0", "body": "@KellyBundy The first paragraph says, \"_to match behaviour of the second._\" The programming challenge is clearly not about regular expressions, so the point of using `re.escape(...)` to match behaviour of the second implementation stands. Your complaint is purely the code uses the name \"grep\" where it should be something else like \"find_string\", which is a valid point, but does not invalidate my point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T16:53:29.083", "Id": "526177", "Score": "0", "body": "*\"The programming challenge is clearly not about regular expressions\"* - I don't think that's clear. And it's not just in the code, their text also says \"implementation of Grep\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T04:48:09.130", "Id": "266343", "ParentId": "266336", "Score": "1" } }, { "body": "<p><a href=\"https://en.wikipedia.org/wiki/Grep\" rel=\"nofollow noreferrer\">From Wikipedia</a>:</p>\n<blockquote>\n<p>grep is a command-line utility for searching plain-text data sets for lines that match a <strong>regular expression</strong>. Its name comes from the ed command g/re/p (<strong>g</strong>lobally search for a <strong>r</strong>egular <strong>e</strong>xpression and <strong>p</strong>rint matching lines)</p>\n</blockquote>\n<p>So your second grep implementation really actually isn't one at all. Disqualified, case closed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T06:12:43.477", "Id": "266345", "ParentId": "266336", "Score": "1" } } ]
{ "AcceptedAnswerId": "266343", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T22:50:51.027", "Id": "266336", "Score": "1", "Tags": [ "python", "python-3.x", "programming-challenge", "comparative-review", "console" ], "Title": "Search for text in a file" }
266336
<p>I have <a href="http://coderodde.github.io/weblog/" rel="nofollow noreferrer">this blog</a> lurking around in the web. It's just static HTML, but I was interested to keep track of all the views on that blog. Finally, I end up with the following web application:</p> <p>(The Java backend resides entirely <a href="https://github.com/coderodde/WeblogViewCounter" rel="nofollow noreferrer">here</a>.)</p> <p><strong><code>com.github.coderodde.weblog.viewcounter.CountViewServlet.java</code></strong></p> <pre><code>package com.github.coderodde.weblog.viewcounter; import com.github.coderodde.weblog.viewcounter.exceptions.CannotAddViewException; import com.github.coderodde.weblog.viewcounter.exceptions.CannotCreateMainTableException; import static com.github.coderodde.weblog.viewcounter.Utils.objs; import com.github.coderodde.weblog.viewcounter.exceptions.CannotGetMostRecenetViewTimeException; import com.github.coderodde.weblog.viewcounter.exceptions.CannotGetNumberOfViewsException; import com.google.gson.Gson; import java.io.IOException; import java.io.PrintWriter; import java.time.ZonedDateTime; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This servlet is responsible for storing the IP-address and the timestamp of * a view in at &lt;a href=&quot;http://coderodde.github.io/weblog/&quot;&gt;coderodde's weblog&lt;/a&gt;. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Aug 21, 2021) * @since 1.6 (Aug 21, 2021) */ @WebServlet(name=&quot;CountViewServlet&quot;, urlPatterns={&quot;/countView&quot;}) public final class CountViewServlet extends HttpServlet { private static final Gson GSON = new Gson(); private static final Logger LOGGER = Logger.getLogger(CountViewServlet.class.getName()); @Override protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { // Allow the weblog page to get the response from this servlet: httpServletResponse.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;coderodde.github.io&quot;); DataAccessObject dataAccessObject = DataAccessObject.getInstance(); JSONResponseObject jsonResponseObject = new JSONResponseObject(); jsonResponseObject.succeeded = false; try { dataAccessObject.createTablesIfNeeded(); ZonedDateTime mostRecentViewTime = dataAccessObject.getMostRecentViewTime(); if (mostRecentViewTime != null) { jsonResponseObject.mostRecentViewTime = mostRecentViewTime.toString(); } dataAccessObject.addView(httpServletRequest); jsonResponseObject.numberOfViews = dataAccessObject.getViewCount(); // Mark as successful: jsonResponseObject.succeeded = true; } catch (CannotCreateMainTableException ex) { LOGGER.log( Level.SEVERE, &quot;Could not create the main table: {0}, caused by: {1}&quot;, objs(ex.getCause().getMessage(), ex.getCause().getCause())); } catch (CannotAddViewException ex) { LOGGER.log( Level.SEVERE, &quot;Could not add a view: {0}, caused by: {1}&quot;, objs(ex.getCause().getMessage(), ex.getCause().getCause())); } catch (CannotGetMostRecenetViewTimeException ex) { LOGGER.log( Level.SEVERE, &quot;Could not get the most recent view time: {0}, &quot; + &quot;caused by: {1}&quot;, objs(ex.getCause().getMessage(), ex.getCause().getCause())); } catch (CannotGetNumberOfViewsException ex) { LOGGER.log( Level.SEVERE, &quot;Could not get the number of views: {0}, caused by: {1}&quot;, objs(ex.getCause().getMessage(), ex.getCause().getCause())); } try (PrintWriter printWriter = httpServletResponse.getWriter()) { printWriter.print(GSON.toJson(jsonResponseObject)); } } } </code></pre> <p><strong><code>com.github.coderodde.weblog.viewcounter.DataAccessObject.java</code></strong></p> <pre><code>package com.github.coderodde.weblog.viewcounter; import com.github.coderodde.weblog.viewcounter.sql.SQLStatements; import com.github.coderodde.weblog.viewcounter.exceptions.CannotAddViewException; import com.github.coderodde.weblog.viewcounter.exceptions.CannotCreateMainTableException; import com.github.coderodde.weblog.viewcounter.exceptions.CannotGetMostRecenetViewTimeException; import com.github.coderodde.weblog.viewcounter.exceptions.CannotGetNumberOfViewsException; import static com.github.coderodde.weblog.viewcounter.Utils.objs; import java.net.URI; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.apache.tomcat.jdbc.pool.DataSource; /** * This class implements the data access object for the view counter. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Aug 22, 2021) */ public final class DataAccessObject { private static final Logger LOGGER = Logger.getLogger(DataAccessObject.class.getName()); private static final String EUROPE_HELSINKI_ZONE_ID = &quot;Europe/Helsinki&quot;; private static final ZoneId ZONE_ID = ZoneId.of(EUROPE_HELSINKI_ZONE_ID); private static final String DB_URL_ENVIRONMENT_VARIABLE_NAME = &quot;CLEARDB_DATABASE_URL&quot;; private static final DataSource dataSource = new DataSource(); private static final DataAccessObject INSTANCE = new DataAccessObject(); public static DataAccessObject getInstance() { return INSTANCE; } /** * Makes sure that the main table is created. * * @throws CannotCreateMainTableException if cannot create the table. */ public void createTablesIfNeeded() throws CannotCreateMainTableException { try (Connection connection = getConnection()) { connection.createStatement() .executeUpdate(SQLStatements .ViewTable .Create .CREATE_MAIN_TABLE); } catch (SQLException cause) { LOGGER.log( Level.SEVERE, &quot;The SQL layer failed: {0}, caused by: {1}&quot;, objs(cause.getMessage(), cause.getCause())); throw new CannotCreateMainTableException(cause); } catch (URISyntaxException cause) { LOGGER.log( Level.SEVERE, &quot;URI failed: {0}, caused by: {1}&quot;, objs(cause.getMessage(), cause.getCause())); throw new CannotCreateMainTableException(cause); } } /** * Adds a new view data to the database. * * @param httpServletRequest the request object. * @throws com.github.coderodde.weblog.viewcounter.exceptions.CannotAddViewException * if adding a view data fails. */ public void addView(HttpServletRequest httpServletRequest) throws CannotAddViewException { String host = httpServletRequest.getRemoteHost(); int port = httpServletRequest.getRemotePort(); String remoteAddress = httpServletRequest.getHeader(&quot;X-FORWARDED-FOR&quot;); if (remoteAddress == null) { remoteAddress = httpServletRequest.getRemoteAddr(); } try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement( SQLStatements.ViewTable.Insert.INSERT_VIEW)) { statement.setString(1, remoteAddress); statement.setString(2, host); statement.setInt(3, port); ZonedDateTime nowZonedDateTime = ZonedDateTime.now(ZONE_ID); Timestamp nowTimestamp = Timestamp.from(nowZonedDateTime.toInstant()); statement.setTimestamp(4, nowTimestamp); statement.executeUpdate(); } catch (Exception cause) { throw new CannotAddViewException(cause); } } /** * Returns the total number of views. * @return the total number of views so far. * @throws com.github.coderodde.weblog.viewcounter.exceptions.CannotGetNumberOfViewsException * if cannot get the number of views. */ public int getViewCount() throws CannotGetNumberOfViewsException { try (Connection connection = getConnection(); Statement statement = connection.createStatement()) { try (ResultSet resultSet = statement.executeQuery( SQLStatements .ViewTable .Select .GET_NUMBER_OF_VIEWS)) { if (!resultSet.next()) { throw new IllegalStateException( &quot;Could not read the number of views.&quot;); } return resultSet.getInt(1); } } catch (Exception ex) { throw new CannotGetNumberOfViewsException(ex); } } /** * Returns the most recent view time stamp. * @return the most recent view time. * @throws CannotGetMostRecenetViewTimeException if reading the most recent * view time fails. */ public ZonedDateTime getMostRecentViewTime() throws CannotGetMostRecenetViewTimeException { try (Connection connection = getConnection(); Statement statement = connection.createStatement()) { try (ResultSet resultSet = statement.executeQuery( SQLStatements .ViewTable .Select .GET_MOST_RECENT_VIEW_TIME)) { if (!resultSet.next()) { return null; } Timestamp mostRecentViewTimestamp = resultSet.getTimestamp(1); if (mostRecentViewTimestamp == null) { return null; } ZonedDateTime mostRecentViewZonedDateTime = ZonedDateTime.ofInstant( mostRecentViewTimestamp.toInstant(), ZONE_ID); return mostRecentViewZonedDateTime; } } catch (SQLException | URISyntaxException ex) { throw new CannotGetMostRecenetViewTimeException(ex); } } private static void loadJDBCDriverClass() { try { Class.forName(&quot;com.mysql.cj.jdbc.Driver&quot;).newInstance(); } catch (ClassNotFoundException ex) { LOGGER.log( Level.SEVERE, &quot;com.mysql.cj.jdbc.Driver class not found: {0}, &quot; + &quot;caused by: {1}&quot;, objs(ex, ex.getCause())); throw new RuntimeException( &quot;com.mysql.cj.jdbc.Driver not found.&quot;, ex); } catch (InstantiationException ex) { LOGGER.log( Level.SEVERE, &quot;com.mysql.cj.jdbc.Driver could not be instantiated: {0},&quot; + &quot; caused by: {1}&quot;, objs(ex, ex.getCause())); throw new RuntimeException( &quot;com.mysql.cj.jdbc.Driver could not be instantiated.&quot;, ex); } catch (IllegalAccessException ex) { LOGGER.log( Level.SEVERE, &quot;com.mysql.cj.jdbc.Driver could not be accessed: {0}, &quot; + &quot;caused by: {1}&quot;, objs(ex, ex.getCause())); throw new RuntimeException( &quot;com.mysql.cj.jdbc.Driver could not be accessed.&quot;, ex); } } static { loadJDBCDriverClass(); } private Connection getConnection() throws SQLException, URISyntaxException { URI databaseURI = new URI(System.getenv(DB_URL_ENVIRONMENT_VARIABLE_NAME)); String username = databaseURI.getUserInfo().split(&quot;:&quot;)[0]; String password = databaseURI.getUserInfo().split(&quot;:&quot;)[1]; String databaseURL = &quot;jdbc:mysql://&quot; + databaseURI.getHost() + databaseURI.getPath(); return DriverManager.getConnection(databaseURL, username, password); } } </code></pre> <p><strong><code>com.github.coderodde.weblog.viewcounter.JSONResponseObject.java</code></strong></p> <pre><code>package com.github.coderodde.weblog.viewcounter; /** * This POJO class type defines a simple object for reporting to the front-end. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Aug 22, 2021) * @since 1.6 (Aug 22, 2021) */ public final class JSONResponseObject { public boolean succeeded; public int numberOfViews; public String mostRecentViewTime; } </code></pre> <p><strong><code>com.github.coderodde.weblog.viewcounter.sql.SQLDefinitions.java</code></strong></p> <pre><code>package com.github.coderodde.weblog.viewcounter.sql; /** * This class defines the database table schemas. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Aug 22, 2021) * @since 1.6 (Aug 22, 2021) */ public final class SQLDefinitions { /** * This class defines the structure of the main table. */ public static final class ViewTable { /** * The name of the main table. */ public static final String NAME = &quot;view&quot;; /** * This class defines the ID column. */ public static final class Id { public static final String NAME = &quot;id&quot;; public static final String TYPE = &quot;INT NOT NULL AUTO_INCREMENT&quot;; } /** * This class defines the IP address column. */ public static final class IPAddress { // 16 chars, 15 colons: public static final int IPV6_ADDRESS_STRING_LENGTH = 16 + 15; public static final String NAME = &quot;ip_address&quot;; public static final String TYPE = &quot;VARCHAR(&quot; + IPV6_ADDRESS_STRING_LENGTH + &quot;) NOT NULL&quot;; } /** * This class defines the host name column. */ public static final class HostName { public static final int MAXIMUM_LENGTH = 253; public static final String NAME = &quot;host_name&quot;; public static final String TYPE = &quot;VARCHAR(&quot; + MAXIMUM_LENGTH + &quot;)&quot;; } /** * This class defines the port number column. */ public static final class PortNumber { public static final String NAME = &quot;port&quot;; public static final String TYPE = &quot;INT NOT NULL&quot;; } public static final class UserName { public static final String NAME = &quot;user_name&quot;; public static final String TYPE = &quot;VARCHAR(256)&quot;; } /** * This class defines the view timestamp. */ public static final class ViewTimestamp { public static final String NAME = &quot;viewed_at&quot;; public static final String TYPE = &quot;TIMESTAMP NOT NULL&quot;; } } } </code></pre> <p><strong><code>com.github.coderodde.weblog.viewcounter.sql.SQLStatements.java</code></strong></p> <pre><code>package com.github.coderodde.weblog.viewcounter.sql; /** * This class defines all the SQL statements in the application. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Aug 22, 2021) * @since 1.6 (Aug 22, 2021) */ public final class SQLStatements { /** * The statements for the main table. */ public static final class ViewTable { /** * The create table statements. */ public static final class Create { /** * Creates a table for storing the views unless there is one already * in the database. */ public static final String CREATE_MAIN_TABLE = &quot;CREATE TABLE IF NOT EXISTS &quot; + SQLDefinitions.ViewTable.NAME + &quot; (\n&quot; + SQLDefinitions.ViewTable.Id.NAME + &quot; &quot; + SQLDefinitions.ViewTable.Id.TYPE + &quot;,\n&quot; + SQLDefinitions.ViewTable.IPAddress.NAME + &quot; &quot; + SQLDefinitions.ViewTable.IPAddress.TYPE + &quot;,\n&quot; + SQLDefinitions.ViewTable.HostName.NAME + &quot; &quot; + SQLDefinitions.ViewTable.HostName.TYPE + &quot;,\n&quot; + SQLDefinitions.ViewTable.PortNumber.NAME + &quot; &quot; + SQLDefinitions.ViewTable.PortNumber.TYPE + &quot;,\n&quot; + SQLDefinitions.ViewTable.UserName.NAME + &quot; &quot; + SQLDefinitions.ViewTable.UserName.TYPE + &quot;,\n&quot; + SQLDefinitions.ViewTable.ViewTimestamp.NAME + &quot; &quot; + SQLDefinitions.ViewTable.ViewTimestamp.TYPE + &quot;,\n&quot; + &quot;PRIMARY KEY (&quot; + SQLDefinitions.ViewTable.Id.NAME + &quot;)) &quot; + &quot;ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE &quot; + &quot;utf8_unicode_ci;;&quot;; } /** * The insert data statements. */ public static final class Insert { /** * Inserts a new view into the database. */ public static final String INSERT_VIEW = &quot;INSERT INTO `&quot; + SQLDefinitions.ViewTable.NAME + &quot;` (&quot; + SQLDefinitions.ViewTable.IPAddress.NAME + &quot;, &quot; + SQLDefinitions.ViewTable.HostName.NAME + &quot;, &quot; + SQLDefinitions.ViewTable.PortNumber.NAME + &quot;, &quot; + SQLDefinitions.ViewTable.ViewTimestamp.NAME + &quot;) &quot; + &quot;VALUES (?, ?, ?, ?);&quot;; } /** * The select data statements. */ public static final class Select { /** * Returns the total number of views. */ public static final String GET_NUMBER_OF_VIEWS = &quot;SELECT COUNT(*) FROM `&quot; + SQLDefinitions.ViewTable.NAME + &quot;`;&quot;; /** * Returns the most recent view time. */ public static final String GET_MOST_RECENT_VIEW_TIME = &quot;SELECT MAX(&quot; + SQLDefinitions.ViewTable.ViewTimestamp.NAME + &quot;) FROM &quot; + SQLDefinitions.ViewTable.NAME + &quot;;&quot;; } } } </code></pre> <p>At the frontend side, I had to do something like this:</p> <p><strong><code>viewCounter.js</code></strong></p> <pre><code>function processViewCounter() { let span = document.getElementById(&quot;view_count_span&quot;); let xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4 &amp;&amp; this.status === 200) { renderResults(this.responseText, span); } }; xhttp.open(&quot;POST&quot;, &quot;https://weblog-view-counter.herokuapp.com/countView&quot;); xhttp.send(); } function getDateString(dateString) { const event = new Date(dateString); const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', minute: 'numeric', second: 'numeric', hour: 'numeric'}; return event.toLocaleDateString(&quot;en-US&quot;, options); } function renderResults(jsonText, textElement) { const responseObject = JSON.parse(jsonText); if (responseObject[&quot;succeeded&quot;]) { const numberOfViews = responseObject[&quot;numberOfViews&quot;]; if (numberOfViews) { textElement.innerHTML = &quot;Total views: &quot; + numberOfViews + &quot;.&quot;; } else { textElement.innerHTML = &quot;Total views: N/A.&quot;; } let mostRecentViewTime; if (responseObject[&quot;mostRecentViewTime&quot;]) { mostRecentViewTime = responseObject[&quot;mostRecentViewTime&quot;].replace(&quot;[Europe/Helsinki]&quot;, &quot;&quot;); mostRecentViewTime = getDateString(mostRecentViewTime); } else { mostRecentViewTime = &quot;N/A&quot;; } textElement.innerHTML += &quot; Last visit time: &quot; + mostRecentViewTime + &quot;.&quot;; } else { textElement.innerHTML = &quot;Total views: N/A. Last visit time: N/A.&quot;; } } </code></pre> <h2>Critique request</h2> <p>Please, tell me anything that comes to mind.</p>
[]
[ { "body": "<p>As you are no beginner, just the terse style I'd also use in my team:</p>\n<ul>\n<li>Singleton anti-pattern in the DAO. Isn't there a DI container around somewhere?</li>\n<li>Too verbose with different exception types. The handling is exactly the same apart from different messages, therefore one exception with a message should be enough. (Always be alert if your error handling is longer than the actual code.)</li>\n<li><code>final</code> classes. Why? How can you tell today that there <em>never</em> will be a reason to extend the class? (Hint: you can't) Bad idea™.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T09:29:49.843", "Id": "526152", "Score": "0", "body": "Good points, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T08:54:18.773", "Id": "266348", "ParentId": "266344", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T05:09:38.833", "Id": "266344", "Score": "0", "Tags": [ "java", "javascript", "mysql", "servlets" ], "Title": "A Java EE7 web application for counting views in a static HTML page" }
266344
<p>PROBLEM: I need to merge the columns by identifying the headernames and they work as desired by using the below code.</p> <p>The code is very inefficient as I am using an eval to accomplish the job and I believe it makes unnecessay multiple passes which is not recommended. Is there a way I can optimize my code to merge the columns? My code works good only for one item fruits since &quot;CriteriaMatchArray&quot; for many items I need to pass the result again as input and run it making inefficient.</p> <p><a href="https://docs.google.com/spreadsheets/d/18FSwIDZ5H5nqrbwq-VIMoHouW6f0cSZ7sTIgN9RxBc0/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/18FSwIDZ5H5nqrbwq-VIMoHouW6f0cSZ7sTIgN9RxBc0/edit?usp=sharing</a></p> <p>Here is the image : <a href="https://i.stack.imgur.com/A2d6d.png" rel="nofollow noreferrer">https://i.stack.imgur.com/A2d6d.png</a></p> <p>Hence the end result is nothing but 2d array as shown in the image</p> <p>I have code below</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-html lang-html prettyprint-override"><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;script&gt; var table = [ ["Sl.no","fruits 1", "fruits 2", "fruits 3", "fruits 4", "fruits 5", "vegetables 1", "vegetables 2"], ["1","banana", "apple", "orange", "", "", "carrot", "cabbage"], ["2","watermelon", "apple", "orange", "", "", "beans", ""] ] //document.write(JSON.stringify(table)) var str = [], m = []; var firstJoiningPosition = -1; CriteriaMatchArray = ["fruits"] //this is the input (currently processes only 1 item in list) and user can change or add more for (var i = 0; i &lt; table[0].length; i++) { if (table[0][i].indexOf(CriteriaMatchArray[0]) == -1) { str.push("table[i][" + i + "]") } else { if (firstJoiningPosition == -1) firstJoiningPosition = i m.push("table[i][" + i + "]") } } str[firstJoiningPosition] = m.join("+ '#' +") evalstring = str.join(",") document.write('&lt;pre&gt;Given table ' + JSON.stringify(table, null, 4) + '&lt;/pre&gt;') var result = [] for (var i = 0; i &lt; table.length; i++) { eval("result.push(" + "[" + evalstring + "]" + ")") } document.write('&lt;pre&gt;Result after joining ' + JSON.stringify(result, null, 4) + '&lt;/pre&gt;') &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T08:34:41.520", "Id": "526146", "Score": "0", "body": "is this a task for university? seems rather unusual and far from a reality case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T08:58:21.227", "Id": "526150", "Score": "1", "body": "This is not an assignment from University. But it is something related to a prototype project research. This is a problem for generating the CSV from the fetched results of API, The API provides more detailed columns and we need to join the column data like we have in gmail contacts, the groups are being merged and separated by::: symbol, similarly the system we build needs to have some data to be concatenated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T08:19:18.357", "Id": "266347", "Score": "2", "Tags": [ "javascript", "array" ], "Title": "Combining columns based on header names of an array" }
266347
<p>I'm writing an app meant to have similar functionality to LucidChart - drawing shapes/diagrams. I'm using React with Typescript (Create React App) and am trying to follow OOP/polymorphic patterns I've been learning about from watching videos by Uncle Bob Martin and elsewhere on the internet - factory, singleton, state patterns, etc. I'm mainly writing this app to learn more about OOP and these kinds of design patterns.</p> <p>The architecture of my app is one that I've made up as I've been trying to use these OOP patterns and trying to get them to work with React. A simplified explanation of the main design is as follows:</p> <ol> <li>The main component stores all the state of the app, which are my my shape classes (and relations, operation, other classes in the non-simplified version of app).</li> <li>The abstract shape class has an abstract <code>GetComponent():JSX.Element</code> that each concrete class has to implement and that the main class calls in its <code>render()</code> method.</li> <li>In order to change the state of the shapes using <code>setState()</code> so that react will detect the state change and rerender, I am passing down an object containing <code>setState</code>-calling callbacks to the <code>Shape</code> instances (as would be done in a standard React architecture), so that they can refresh the app's react state with their new state after updating it internally - this can be seen in the <code>MoveToPosition()</code> implementations below. (Really this is done in separate <code>Operation</code> classes which operate on the <code>Shape</code> classes - I just tried to simplify the code for the example here - but the idea is the same: a non-React class changes the React state with a callback passed from the React component).</li> </ol> <p>Code:</p> <pre><code>//Manchas.tsx import React from &quot;react&quot;; import { Shape, Rectangle, Circle } from &quot;./shapes&quot;; import { StateUtilities } from &quot;./state_utilities&quot;; import &quot;./Manchas.css&quot;; import logger from &quot;./logger&quot;; export type ManchasState = { shapes: Shape[]; }; export class Manchas React.Component&lt;{}, ManchasState&gt; { constructor(props = {}) { super(props); const stateUtilities = { RefreshShapesState: this.UpdateShapes, }; //dummy shapes just in example - really these are created with //factories at runtime const dummy1 = new Rectangle(2000, 2000, stateUtilities); const dummy2 = new Rectangle(1, 1, stateUtilities); const dummy3 = new Circle(1000, 1000, stateUtilities); this.state = { shapes: [dummy1, dummy2, dummy3], }; this.UpdateShapes = this.UpdateShapes.bind(this); } UpdateShapes() { // called by Shape instances (or Operation instances in real app) after they // modify their own state, just so React state is changed to trigger rerender logger.Debug(&quot;Updating shapes state&quot;); this.setState({ shapes: this.state.shapes }); } render() { return ( &lt;div className=&quot;App&quot;&gt; {this.state.shapes.map((shape, index) =&gt; { return shape.GetComponent(index); })} &lt;/div&gt; ); } } export default Manchas; </code></pre> <pre><code>//shapes.tsx import React from &quot;react&quot;; import config from &quot;./config&quot;; import { Position } from &quot;./geometry&quot;; import { ConvertScreenNumberIntoAbsolutePx } from &quot;./utilities&quot;; import { StateUtilities } from &quot;./state_utilities&quot;; export abstract class Shape { public abstract GetComponent(index: number): JSX.Element; public abstract MoveToPosition(destinationPosition: Position): void; } export class Rectangle extends Shape { private height: number; private width: number; private topLeftCoordinate: Position; private stateUtilities: StateUtilities; constructor( topLeftX: number, topLeftY: number, stateUtilities: StateUtilities ) { super(); this.topLeftCoordinate = { X: topLeftX, Y: topLeftY }; this.height = config.GetDefaultRectangleHeight(); this.width = config.GetDefaultRectangleLength(); this.stateUtilities = stateUtilities; } MoveToPosition(destinationPosition: Position): void { // some operation will call this method this.topLeftCoordinate = destinationPosition; this.stateUtilities.RefreshShapesState(); } GetComponent(index: number): JSX.Element { return ( &lt;RectangleFC key={index} topLeftCoordinate={this.topLeftCoordinate} height={this.height} width={this.width} /&gt; ); } } type RectangleProps = { topLeftCoordinate: Position; height: number; width: number; }; const RectangleFC = ({ topLeftCoordinate, height, width, }: RectangleProps): JSX.Element =&gt; ( &lt;div style={{ position: &quot;absolute&quot;, left: `${ConvertScreenNumberIntoAbsolutePx(topLeftCoordinate.X)}px`, top: `${ConvertScreenNumberIntoAbsolutePx(topLeftCoordinate.Y)}px`, width: `${ConvertScreenNumberIntoAbsolutePx(width)}px`, height: `${ConvertScreenNumberIntoAbsolutePx(height)}px`, border: &quot;3px solid black&quot;, zIndex: 3, }} &gt;&lt;/div&gt; ); //CIRCLE export class Circle extends Shape { private diameter: number; private centerCoordinate: Position; private stateUtilities: StateUtilities; constructor( centerX: number, centerY: number, stateUtilities: StateUtilities ) { super(); this.stateUtilities = stateUtilities; this.diameter = config.GetDefaultCircleDiameter(); this.centerCoordinate = { X: centerX, Y: centerY }; } MoveToPosition(destinationPosition: Position): void { // some operation will call this method this.centerCoordinate = destinationPosition; this.stateUtilities.RefreshShapesState(); } GetComponent(index: number): JSX.Element { return ( &lt;CircleFC key={index} centerX={this.centerCoordinate.X} centerY={this.centerCoordinate.Y} diameter={this.diameter} /&gt; ); } } type CircleProps = { centerX: number; centerY: number; diameter: number; }; const CircleFC = ({ centerX, centerY, diameter }: CircleProps): JSX.Element =&gt; { const radius = diameter / 2; const left = centerX - radius; const top = centerY - radius; return ( &lt;div style={{ position: &quot;absolute&quot;, left: `${ConvertScreenNumberIntoAbsolutePx(left)}px`, top: `${ConvertScreenNumberIntoAbsolutePx(top)}px`, width: `${ConvertScreenNumberIntoAbsolutePx(diameter)}px`, height: `${ConvertScreenNumberIntoAbsolutePx(diameter)}px`, border: &quot;3px solid black&quot;, borderRadius: 90, zIndex: 3, }} &gt;&lt;/div&gt; ); }; </code></pre> <p>I have my shapes as their own <code>Shape</code> classes as opposed to React components as I want to write the application as one that uses polymorphism and OOP design patterns in a traditional sense. Therefore I want to use my own non-React vanilla TypeScript classes as opposed to trying to force my components to inherit from each other or implement interfaces which seems like an antipattern and not how React is supposed to work (I believe <a href="https://reactjs.org/docs/composition-vs-inheritance.html" rel="nofollow noreferrer">this link</a> supports this belief).</p> <p>Concerns/Questions about the architecture:</p> <ul> <li>Passing down <code>setState</code>-calling callbacks down to my <code>Shape</code> classes feels very ugly and also and is also leading to bugs when I have to call several of these <code>setState</code>-calling functions one after another within the same function where the state isn't updating in the way I want it to. What I think I want is to not have to pass this all down and for the shapes to not have to explicitly call these functions - if changes to the state of the <code>Shape</code> instances, which are held in the React's state, were just detected and triggered rerenders. The idea of using Redux seems like it adds code that doesn't really fit into my architecture thus far - having to write reducers and dispatch actions seems like way too much if I want my <code>Shape</code> classes to update their own state internally.</li> <li>Is there a better model for modifying the state of the app? How would an app like this be structured if it was a non-React or non-browser-based app written in Java for example?</li> <li>Is trying to make this app which tries to use these traditional OOP patterns work with React a bad idea? How else would you make an application like this without using this kind of polymorphism?</li> </ul> <p>Feedback on the above or any other aspects of the code would be appreciated! Thanks!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T09:30:40.260", "Id": "266350", "Score": "0", "Tags": [ "object-oriented", "design-patterns", "react.js", "typescript" ], "Title": "React Typescript Project Using Traditional OOP Patterns" }
266350
<p>I recently started programming and chose C# as my first language. After a couple of weeks/month now I tried to make my own Sudoku solver in a console application. I'm happy with the result, and tried to clean up my code.</p> <p>But I'm not sure what I can do better at this point. I was uncertain if I created too many functions? Some of them I actually only call once (like <code>ValidateNumber()</code>, <code>ValidateSquare()</code> &amp; <code>ValidateDimension()</code>), simply because I thought the code look cleaner.</p> <p>Any suggestions for improvements or if something is bad practice?</p> <pre><code>static void Main(string[] args) { int[,] puzzle = {{0,0,0,8,0,0,4,2,0}, {5,0,0,6,7,0,0,0,0}, {0,0,0,0,0,9,0,0,5}, {7,4,0,1,0,0,0,4,0}, {0,0,9,0,3,0,7,0,0}, {0,0,0,0,0,7,0,4,8}, {8,0,0,4,0,0,0,0,0}, {0,0,0,0,9,8,0,0,3}, {0,9,5,0,0,3,0,0,0}}; PrintSudoku(puzzle); Console.WriteLine(&quot;Press 'enter' to solve.&quot;); Console.ReadLine(); Console.WriteLine(&quot;Solving... This may take a second. \n&quot;); SolveSudoku(puzzle); } private static void SolveSudoku(int[,] puzzle) { //Copy input sudoku to a new solution array int[,] solution = new int[9, 9]; Array.Copy(puzzle, 0, solution, 0, puzzle.Length); //Loop through each cell in the sudoku for (int column = 0; column &lt; 9; column++) { for (int row = 0; row &lt; 9;) { if (puzzle[column, row] == 0) //If original cell != 0, It's already a difined number and should not be changed. { for (int i = 0; i &lt; 10; i++) { //Increment cell with 1 solution[column, row]++; //If cell = 10, all tested numbers failed, reset to 0 and go back to previous cell which originally had a 0 value if (solution[column, row] == 10) { solution[column, row] = 0; do { if (row == 0) { row += 8; column -= 1; } else { row -= 1; } } while (puzzle[column, row] != 0); break; } //Else if number does not collide with any other row/column/square, continue with next cell else if (ValidateNumber(solution, column, row)) { row++; break; } else //If cell != 10 and number validation failed, continue with the next number. { continue; } } } // original cell != 0, continue with next cell. else { row++; } } } PrintSudoku(solution); Console.ReadLine(); } private static bool ValidateNumber(int[,] arr, int row, int column) { //Validate that both 3x3 square and dimension(row/column) have no other cell with the same value as current array number if (ValidateSquare(arr, row, column) &amp;&amp; ValidateDimension(arr, row, column)) { return true; } return false; } private static bool ValidateDimension(int[,] arr, int row, int column) { //Check if the current cell match any other cell in the same row, if so return false for (int a = 0; a &lt; 9; a++) { if (column == a) //don't compare the cell with itself { continue; } if (arr[row, column] == arr[row, a]) { return false; } } //Check if the current cell match any other cell in the same column, if so return false for (int b = 0; b &lt; 9; b++) { if (row == b) { continue; } if (arr[row, column] == arr[b, column]) //don't compare the cell with itself { return false; } } //if no other cell with same value, return true return true; } private static bool ValidateSquare(int[,] arr, int row, int column) { //Compare that the current cells 3x3 grid doesn't contain the same number as current cell. int rowSquare = CurrentSquare(row); int columnSquare = CurrentSquare(column); for (int i = rowSquare; i &lt; rowSquare + 3; i++) { for (int j = columnSquare; j &lt; columnSquare + 3; j++) { if (arr[i, j] == arr[row, column]) { if (i == row &amp;&amp; j == column) //don't compare the cell with itself { continue; } return false; } } } return true; } private static int CurrentSquare(int coordinate) { //Give the coordinate of input dimension (row/column/depth), and defines which 3x3 square of the puzzle it belongs to in the 9x9 grid. int square = 0; switch (coordinate) { case 0: case 1: case 2: square = 0; //Square1 in grid, Square1 start at index 0 break; case 3: case 4: case 5: square = 3; //Square2 in grid, Square2 start at index 3 break; case 6: case 7: case 8: square = 6; //Square3 in grid, Square3 start at index 6 break; } return square; } private static void PrintSudoku(int[,] sudoku) { for (int i = 0; i &lt; 9; i++) { for (int j = 0; j &lt; 9; j++) { if (j % 3 == 0 &amp;&amp; j != 0) { Console.Write(&quot;| &quot;); } Console.Write(sudoku[i, j] + &quot; &quot;); } if (i % 3 == 2 &amp;&amp; i != 8) { Console.WriteLine(); Console.Write(&quot;------+-------+------&quot;); } Console.WriteLine(); } Console.WriteLine(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T22:32:55.573", "Id": "526207", "Score": "2", "body": "You may want to consider storing your puzzle in a single array (size 81), which will make it easier to loop through the all values. Determining the row index is simply cell index / 9 and the column is cell index % 9, finding which square is similarly simple." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T14:45:03.307", "Id": "526256", "Score": "0", "body": "Seems like an attempt at brute-forcing the result (check all the possible solutions and discard those), but it seems that it can only backtrack one step back. If you cannot find a valid number for the current cell, you go to the previous one and change it again. But what if a change two steps removed makes all the available solutions invalid? Do you have proof that this approach will work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T17:49:19.057", "Id": "526271", "Score": "0", "body": "@SteveFord That's a nice idea! I tried the concept out now and it simplified `SolveSudoku()` quite a lot. Just need to adjust the `ValidateNumber()` methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T17:49:49.203", "Id": "526272", "Score": "0", "body": "@SJuan76 It only backtrack one step back at a time. But the logic that backtrack is if a cell reach number 10, it reset to 0 and go to previous cell. Then increment that cell with 1. If that cell were to reach 10 as well, it will go back an additional cell. So it will try every possible combination out. Though.. as Zachary Vance pointed out, if an invalid sudoku puzzle is inserted the code will fail. So I will need to fix that too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T18:28:12.150", "Id": "526273", "Score": "0", "body": "To complete the review you may accept the most useful answer with a green mark." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T23:04:10.453", "Id": "526290", "Score": "0", "body": "This medium.com/@eneko/… shows an approach to solving hard Sudokus using a number of techniques that works well, unfortunately it is written in Swift but the approach is well documented describing the logic. It uses a slightly different approach of starting with all possible values in every cell then removes them until only one is left in each cell. It describes several advanced ideas, look at identical Sibling Solvers" } ]
[ { "body": "<p>Functions are not just about reusing code. I thing the way you &quot;cut&quot; the code using specific functions is quite clean.</p>\n<p>I would strongly suggest using summaries above functions to describe things, even if your function names are quite explicatives</p>\n<p>At last, I would probably have a GetSolution() method returning a string that the main function could print, instead of a void PrintSudoku() method. I think that letting the main function responsible of all inputs/outputs is cleaner.</p>\n<p>But I really think your code is clean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T17:59:28.793", "Id": "526179", "Score": "0", "body": "Thanks for the feedback! Yeah that sounds reasonable, returning the solution makes more sense now that you mention it, I will try that out. Good to know I didn't overuse functions as well!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T12:56:49.910", "Id": "266354", "ParentId": "266353", "Score": "4" } }, { "body": "<p>For a beginner this is actually quite good.</p>\n<p>For future reference, we can provide better reviews when the entire program is included. This code does not include the <code>Using</code> statements nor does it provide the class declaration.</p>\n<p>You might also want to consider some of the heuristics of Sudoku, such as solve for the number that appears the most in the puzzle first.</p>\n<h1>Functions</h1>\n<p>As @Ouch42 indicated, functions are not just about reusable code.</p>\n<p>Good programming is the art or science of breaking problems down into smaller problems until they are very easy to solve. They make maintaining code (adding features, fixing bugs) easier. Quite possibly you could use one or two more functions because the function <code>SolveSudoku(int[,] puzzle)</code> is too complex which means it does too much. The first thing I would do is move the last 2 lines of the function into <code>Main()</code>.</p>\n<pre><code> PrintSudoku(solution);\n Console.ReadLine();\n</code></pre>\n<p>These 2 lines are not part of solving the Sudoku puzzle. This would mean returning the solution matrix rather than returning void.</p>\n<p>Other considerations about the number of functions to create:</p>\n<ul>\n<li>Readability: Is each function easy to read and understand.</li>\n<li>Length of the function: a function should be no more than a single screen in your IDE or editor.</li>\n<li>The depth of indentation: if you find yourself indenting more than 3 times you may want to add a function. This can improve readability and comprehension.</li>\n</ul>\n<h1>The Single Responsibility Principle</h1>\n<p>There is a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>As your programs get more complex you will want to learn about object oriented programming and some core principles of object oriented programming which is called <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"noreferrer\">SOLID programming</a>. The Single Responsibility Principle is the First pillar of SOLID programming.</p>\n<h1>Next Steps</h1>\n<p>Read the puzzle from a file so that the program is more generic and can be reused.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:19:14.553", "Id": "526181", "Score": "0", "body": "Great feedback! I will adjust to return the solution and keep each function to its dedicated purpose. I think it make more sense as well after hearing you and Ouch42 out. Will also try to simplify `SolveSudoku(int[,] puzzle)`. I agree, that part is a bit complex to read even for me. Not the best sign when I'm the one who wrote it. Maybe I can split it into more defined functions.\n\nI will read up on SOLID programming as well! Then attempt your next steps suggestion.\nThank you for taking time reviewing this :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T16:29:55.133", "Id": "266357", "ParentId": "266353", "Score": "10" } }, { "body": "<p>Overall, your solver is reasonable. All your functions look well-defined and they should exist. The worst-looking function is <code>SolveSudoku</code>, so that's the one I'll talk about some improvements for. It's OK (very explicit and self-contained, which is nice), but it could be much more readable.</p>\n<p>FYI The logic you're using is called &quot;backtracking&quot; -- fill in something that looks good, and if it fails, &quot;back track&quot; to the last choice you made and try making a different one. It's a very common pattern for solvers. Ultimately, your program will be slower if you only use backtracking, because you'll re-do a lot of the work over and over when you backtrack.</p>\n<p>The only functionality I'd add (aside from reading the sudoku from a file as suggested by another reviewer) is to deal with sudokus that don't have a valid solution. Just print &quot;no solution&quot; or something. Right now your backtracking logic will blow up and try to access a negative column.</p>\n<h2>Remove Nesting</h2>\n<p>Things can be hard to read with this level of nesting. On the one hand, all the logic is in one place. On the other hand, it's hard to understand. I'll talk about some specific ways to take out layers below.</p>\n<h2>Separate cell traversal</h2>\n<p>Consider whether to add a <code>NextCell</code> and <code>PrevCell</code> helper function which takes in a row/col, and returns a row/col. This does remove a little nesting, but more importantly, it makes the intent clearer. Right now you have a lot of scattered Row++ and break lines, and it's hard for the reader. The downside is that it splits up the logic a bit.</p>\n<h3>Switch to single-dimensional coordinates</h3>\n<ul>\n<li>One suggestion (which goes well with your iteration/backtracking method) might be to keep track of the current cell as a number 0-80 (or 1-81). That would remove a level of nesting, and it would also make the backtracking logic easier.</li>\n<li>Alternatively, you could initialize an array of all non-zero coordinates at the start, and use an index into this array. This makes going forward and back VERY easy--you always increment/decrement the index by exactly one. You can optionally use a 3D coordinate (row, column, square) which might be easier in some ways. Make sure to check how the run time changes. And array also allows you to try filling in squares in various orders to see if one order works better.</li>\n</ul>\n<h3>Use &quot;continue&quot; and &quot;return&quot;</h3>\n<p>One common trick to remove nesting is to replace:</p>\n<pre><code>if (puzzle[column, row] == 0) { //If original cell != 0, It's already a difined number and should not be changed.\n ...main logic...\n} else {\n row++;\n}\n</code></pre>\n<p>with</p>\n<pre><code>if (puzzle[column, row] != 0) { //If original cell != 0, It's already a difined number and should not be changed.\n row++;\n continue;\n}\n...main logic...\n</code></pre>\n<p>This has the downside of being less explicit (the reader has to think about logic more), but removing nesting does help readers a lot.</p>\n<h2>Separate out the backtracking logic.</h2>\n<p><code>SolveSudoku</code>'s basic logic is to, in a loop:</p>\n<ul>\n<li>Look at the current cell</li>\n<li>Try filling in each number, skipping impossible ones</li>\n<li>If this is possible, we're done. Go to the next cell, skipping clues (pre-filled-in cells)</li>\n<li>If this is impossible, we're done. Backtrack to the last cell, skipping clues</li>\n</ul>\n<p>However, the actual logic is filled with continue, break, and increments/decrements to row. It would be better if each case visually looked the same. There are a few options.</p>\n<p>One option is to pull out a helper, which I call <code>GuessCell</code> in the pseudocode below:</p>\n<pre><code>private static bool GuessCell(int[,] puzzle, int row, int col) {\n // returns True if we should go to the next cell, and False if we should backtrack to the previous cell.\n // Modifies puzzle in place like now.\n}\nprivate static void SolveSudoku(int[,] puzzle, int row, int col) {\n while (int row=0, int col=0; col &lt;=9 &amp;&amp; row &lt;=9; ) {\n if (GuessCell(row, col)) {\n // go to next free cell\n } else {\n // go to previous free cell\n }\n }\n // Solved!\n}\n</code></pre>\n<p>Another common option for backtracking solvers is to solve the problem recursively, but this looks radically different. It's basically no longer a change at this point, it's a rewrite, but I think it's interesting to share this approach too.</p>\n<pre><code>private static Nullable&lt;int[,]&gt; SolveSudoku(int[,] puzzle) {\n int[,] solution = new int[9, 9];\n return SolveSudokuFromCell(puzzle, solution, 0, 0);\n}\nprivate static Nullable&lt;int[,]&gt; SolveSudokuFromCell(int[,] puzzle, int[,] solution, int row, int col) {\n int nextRow = row + 1, nextCol = col;\n if (nextRow == 10) {\n nextRow=0; nextCol++;\n }\n if (nextCol == 10) return solution; // Done!\n\n if (puzzle[row][col] != 0) {\n solution[row][col] = puzzle[row][col];\n return SolveSudokuFromCell(puzzle, solution, nextRow, nextCol);\n }\n for (int number=1; number&lt;=9; number++) {\n puzzle[row][col] = number;\n if (ValidateNumber(solution, column, row)) {\n // Try filling in the rest of the cells\n Nullable&lt;int[,]&gt; res = SolveSudokuFromCell(puzzle, nextRow, nextCol);\n if (res != null) return res;\n }\n // If that number didn't work, try the next\n }\n return null; // If no number work, backtrack\n}\n</code></pre>\n<p>P.S. I wrote this last one to demonstrate the logic, but [please treat it as pseudocode. I don't know C# and haven't tried running it, sorry! (<code>Nullable&lt;int[,]&gt;</code> probably isn't a real thing?)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T07:16:36.777", "Id": "526215", "Score": "0", "body": "Yeah, `Nullable<T>` is specifically for value types ;) `int[,]` is a reference type and so will accept `null` already, though with [nullable reference types](https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references) enabled you would indicate that it is expected to be null by writing `int[,]?` (and the `?` suffix also works on value types to create a `Nullable<T>`, so you don't see the latter much)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T12:28:20.300", "Id": "526245", "Score": "0", "body": "For a beginning programmer who is teaching themselves, recursion may be a bit much. I would use recursion to solve the problem myself. Good review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T01:05:39.670", "Id": "526291", "Score": "0", "body": "I think a backtracking solver is a great place to learn recursion. It's how I discovered it myself (for tic-tac-toe)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T23:16:46.223", "Id": "266368", "ParentId": "266353", "Score": "5" } }, { "body": "<p>A possible addition to the other answers (which I fully agree with) is to design this using classes instead. C# works fine as a procedural language but really is designed with OO in mind.</p>\n<p>I think it's easier to get into a SOLID mindset for a beginner like that. A short sketch of that:</p>\n<p>We can start with a definition of a partially solved Sudoku &quot;board&quot;</p>\n<pre><code>class PartialSudoku {\n int[,] Values;\n}\n</code></pre>\n<p>It should probably have a constructor that checks that the number of rows and columns are correct and so on to fail early.\nFurther we can either overload the ToString() method or add a SudokuPrinter.</p>\n<pre><code>class SudokuPrinter {\n string SudokuAsString(PartialSudoku sudoku) { ... }\n}\n</code></pre>\n<p>Then we may have many different solvers, so we would add an interface:</p>\n<pre><code>interface SudokuSolver {\n PartialSudoku Solve(PartialSudoku sudoku)\n}\n</code></pre>\n<p>Now each possible solver just have to implement this solver specification, and they automatically gets forced into the same structure and into a single responsibility.</p>\n<p>Here, we also can have a discussion about the return type - what is the result of solving?</p>\n<p>Should we have a different class <code>FullSudoku</code>?</p>\n<p>Maybe some <code>SolveResult</code> class with a <code>status</code> that we can check?</p>\n<p>If we use a fairly modern C#, we should perhaps enable reference nullability and call it <code>PartialSudoku?</code> instead?</p>\n<p>Should we do the same for the printer? Maybe we want one printer to print 0 on unsolved, but another just leaving them empty? Maybe one where we draw boxes the way you did, or another with thin boxes around each digit and thick around each block, or one completely plain?</p>\n<p>With this approach we can combine many such ideas.</p>\n<p>The resulting main function is very similar:</p>\n<pre><code>static void Main(string[] args)\n{\n int[,] puzzle = {{0,0,0,8,0,0,4,2,0},\n {5,0,0,6,7,0,0,0,0},\n {0,0,0,0,0,9,0,0,5},\n {7,4,0,1,0,0,0,4,0},\n {0,0,9,0,3,0,7,0,0},\n {0,0,0,0,0,7,0,4,8},\n {8,0,0,4,0,0,0,0,0},\n {0,0,0,0,9,8,0,0,3},\n {0,9,5,0,0,3,0,0,0}};\n PartialSudoku sudoku = new PartialSudoku(puzzle)\n ISudokuSolver solver = GetSolver(); //maybe select between different from config\n SudokuPrinter printer = new SudokuPrinter();\n\n Console.WriteLine(printer.SudokuAsString(sudoku)); \n Console.WriteLine(&quot;Press 'enter' to solve.&quot;);\n Console.ReadLine();\n Console.WriteLine(&quot;Solving... This may take a second. \\n&quot;);\n \n PartialSudoku solved = solver.Solve(sudoku);\n Console.WriteLine(printer.SudokuAsString(solved )); \n}\n</code></pre>\n<p>Not everybody likes this style, and it absolutely adds code, but for say, being able to switch between several solvers and adding new easily, it really shines. Personally I find it not too enterprisey.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T21:51:57.103", "Id": "266402", "ParentId": "266353", "Score": "1" } } ]
{ "AcceptedAnswerId": "266357", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T12:14:35.887", "Id": "266353", "Score": "9", "Tags": [ "c#", "beginner", "sudoku" ], "Title": "Criticize my Sudoku solver for improvements (C# beginner)" }
266353
<p>I have this code that generates a random line and a random circle.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def random_2D_position(c_bx, c_by, r, region_side): while True: v_pt = region_side * np.random.random((2, )) if np.linalg.norm(v_pt - np.array([c_bx, c_by])) &gt; r: return v_pt return def plot_region(c_bx, c_by, r, v_l_1, v_l_2, region_side): plt.plot(v_l_1[0], v_l_1[1], 's') plt.plot(v_l_2[0], v_l_2[1], 'o') circle = plt.Circle((c_bx, c_by), r, fill=False) plt.gca().add_artist(circle) plt.plot([v_l_1[0], v_l_2[0]],[v_l_1[1], v_l_2[1]], '-') plt.xlim((0, region_side)) plt.ylim((0, region_side)) return region_side = 500 c_bx = region_side / 3 + region_side / 3 * np.random.random() c_by = region_side / 3 + region_side / 3 * np.random.random() r = region_side / 4 + region_side / 30 * np.random.random() v_l_1 = random_2D_position(c_bx, c_by, r,region_side) v_l_2 = random_2D_position(c_bx, c_by, r, region_side) plot_region(c_bx, c_by, r, v_l_1, v_l_2, region_side) plt.show() </code></pre> <p>I need to find the portion of the line that is inside the circle if the line intersects the circle. I tried to solve it as follows:</p> <p>First, find the line equation :</p> <pre><code>def Find_line_eq(points): #https://stackoverflow.com/a/21566184/6214597 x_coords, y_coords = zip(*points) A = np.vstack([x_coords,np.ones(len(x_coords))]).T m, c = np.linalg.lstsq(A, y_coords)[0] return m,c </code></pre> <p>Then, I used the following code to get the roots of the quadratic formula:</p> <pre><code>m,c_l=Find_line_eq(points=[v_l_1,v_l_2]) a=1+m**2 b=2*c_l*m c=c_l**2-r**2 coeff=[a, b, c] x1,x2= np.roots(coeff) </code></pre> <p>Questions:</p> <p>1- Given the two points of the line, the circle center, and radius (v_l_1, v_l_2, c_bx, c_by,r), how to obtain the portion of the line that is inside the circle? Most of the time x1,x2 are not real, Numpy returns a complex number, even if the line is intersecting the circle?</p> <p>2- How can we generalize this code to obtain these intersection points for 3D circle and line (the two points of the line are not at the same level )?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:13:50.857", "Id": "526180", "Score": "0", "body": "Are you sure this code is working as intended? My editor gives me a bunch of indentation errors and missing brackets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:24:53.033", "Id": "526183", "Score": "0", "body": "@N3buchadnezzar it works, I copied it from my Jupyter Notebook . The first function ‘’return\" was not in place. I have edited it now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:40:49.150", "Id": "526190", "Score": "0", "body": "@N3buchadnezzar You can check now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T07:13:14.347", "Id": "526214", "Score": "1", "body": "(@N3buchadnezzar: Did you intend *working as indented*?;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T07:31:05.960", "Id": "526217", "Score": "0", "body": "With code presented that produces the result/effect required, CodeReview@SE is ready to provide insights about and opinions on the source code. Questions about how to achieve a result are off topic, with those asking how to achieve something additional close to the border between [on- and off-topic with Code Review](https://codereview.stackexchange.com/help/on-topic)." } ]
[ { "body": "<p>Are you asking for feedback on your code, or do you just want someone to fix your two bullet points? Asking for extensions to the code outside of (is there a better algorithm/can this be done in a better way), is outside the scope of this site and is better suited for stack overflow.</p>\n<p>Lets just quickly address some missing points from your code</p>\n<h2>Your code is very hard to read</h2>\n<ul>\n<li>Avoid using single letter variable names</li>\n<li>Structure your code better using more functions and a <code>if name == &quot;__main__&quot;</code> guard.</li>\n<li>Add comments and docstrings to explain what the heck is going on.</li>\n<li>Add typing hints to hint at what the variables mean (but first improve their names).</li>\n<li>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> and run a linter over your code. Even better get some help from a language server like pyright.</li>\n</ul>\n<h3>Lack of detail</h3>\n<pre><code>def random_2D_position(c_bx, c_by, r, region_side):\n while True:\n v_pt = region_side * np.random.random((2, ))\n if np.linalg.norm(v_pt - np.array([c_bx, c_by])) &gt; r:\n return v_pt\n return\ndef plot_region(c_bx, c_by, r, v_l_1, v_l_2, region_side):\n plt.plot(v_l_1[0], v_l_1[1], 's')\n</code></pre>\n<p>The second <code>return</code> statement in <code>random_2D_position</code> will never be reached. Secondly you should always have two spaces between functions in the outer scope. This line has trailing whitespace</p>\n<pre><code>region_side = 500 \n</code></pre>\n<p>For instance the lines</p>\n<pre><code>m,c_l=Find_line_eq(points=[v_l_1,v_l_2])\na=1+m**2\nb=2*c_l*m\nc=c_l**2-r**2\ncoeff=[a, b, c]\nx1,x2= np.roots(coeff)\n</code></pre>\n<p>Is better formated as</p>\n<pre><code>m, c_l = Find_line_eq(points=[v_l_1, v_l_2])\na = 1 + m ** 2\nb = 2 * c_l * m\nc = c_l ** 2 - r ** 2\ncoeff = [a, b, c]\nx1, x2 = np.roots(coeff)\n</code></pre>\n<p>Notice how you have inconsistent spacing around the <code>=</code> symbols for instance. All of this is solved by running a proper formater over your code.</p>\n<h3>Magic numbers</h3>\n<p>Your code is littered with <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a> what does any of this mean?</p>\n<pre><code>c_bx = region_side / 3 + region_side / 3 * np.random.random()\nc_by = region_side / 3 + region_side / 3 * np.random.random()\nr = region_side / 4 + region_side / 30 * np.random.random()\n</code></pre>\n<p>These should ideally be</p>\n<ol>\n<li>Extracted to their own function</li>\n<li>The magic numbers should be defined as global constants (the standard way of doing this in Python is UPPERCASE)</li>\n<li>Some docstrings / typing hints would go a long way explaining what is going on.</li>\n<li>As a last resort add some comments.</li>\n</ol>\n<h3>Nitpicking</h3>\n<p>There is a new way of getting random numbers in numpy, your method is supported because of legacy reasons, but the newer syntax should be prefered. See <a href=\"https://numpy.org/doc/stable/reference/random/generator.html?highlight=default_rng#numpy.random.default_rng\" rel=\"nofollow noreferrer\">https://numpy.org/doc/stable/reference/random/generator.html?highlight=default_rng#numpy.random.default_rng</a></p>\n<p>If you copy code from Stack Overflow you should link to it or at the very least explain it. Now this is just a hunch, but I would never naturally write this</p>\n<pre><code>np.linalg.norm(v_pt - np.array([c_bx, c_by]))\n</code></pre>\n<p>for calculating the euclidean distance between two points. Yet it is the first result that shows up when googling &quot;How do I calculate the euclidian distance in numpy&quot;, it might be a coincidence but at the very least extract this piece of code into it's own code and source it</p>\n<pre><code>def euclidian_distance(A, B):\n &quot;&quot;&quot;Calculates the euclidian distance between two points\n\n See https://stackoverflow.com/a/1401828/1048781 for details\n &quot;&quot;&quot;\n return np.linalg.norm(A - B)\n</code></pre>\n<p>Using <code>add_artist</code> but it's not recommended see <a href=\"https://stackoverflow.com/questions/9215658/plot-a-circle-with-pyplot\">here</a> for a more modern way.</p>\n<h3>Revised code</h3>\n<p>The following code works for any higher dimension and calculates the orthogonal projection to figure out if the line and the circle intersects. I will leave it to you to figure out how to compute the intersections. Adding typing hints and fleshing out the docstrings is also left as homework =)</p>\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng()\n\nSIDE = 500\nDIMENSIONS = 2\nEPSILON = 1\n\n\ndef get_random_point(start, stop=None):\n if stop is None:\n start, stop = 0, start\n return (stop - start) * rng.random((DIMENSIONS,)) + start\n\n\ndef get_random_circle():\n pointA = get_random_point(SIDE)\n max_radius = distance_2_closest_side(pointA)\n radius = max_radius * rng.random()\n return (pointA, radius)\n\n\ndef distance_2_closest_side(A):\n return min(min(a, SIDE - a) for a in A)\n\n\ndef euclidian_distance(A, B):\n &quot;&quot;&quot;Calculates the euclidian distance between two points\n\n See https://stackoverflow.com/a/1401828/1048781 for details\n &quot;&quot;&quot;\n return np.linalg.norm(A - B)\n\n\ndef get_line_outside_circle(circle, radius):\n A = B = circle\n while euclidian_distance(A, circle) &lt; radius:\n A = get_random_point(SIDE)\n in_circle = euclidian_distance(B, circle) &lt; radius\n AB_too_close = euclidian_distance(A, B) &lt; EPSILON\n while in_circle and AB_too_close:\n B = get_random_point(SIDE)\n in_circle = euclidian_distance(B, circle) &lt; radius\n line = [A, B]\n return line\n\n\ndef projection(b, a):\n &quot;&quot;&quot;orthogonal projection of a onto a straight line parallel to b\n\n See https://en.wikipedia.org/wiki/Vector_projection for further details\n &quot;&quot;&quot;\n return ((b @ a) / (b @ b)) * b\n\n\ndef orthogonal_projection(A, B, circle):\n &quot;&quot;&quot;Calculates the orthogonal projection from circle onto the line AB\n\n See https://stackoverflow.com/a/9368901/1048781 for further details\n &quot;&quot;&quot;\n AB = B - A\n AC = circle - A\n # projection = AC - AB * ((AB @ AC) / (AB @ AB))\n proj = AC - projection(AB, AC)\n\n orthogonal_circle_line = circle - proj\n return orthogonal_circle_line\n\n\ndef plot_results(A, B, circle, radius):\n\n # now make a circle with no fill, which is good for hi-lighting key results\n circle1 = plt.Circle(circle, radius, color=&quot;r&quot;, fill=False)\n\n ax = plt.gca()\n ax.cla() # clear things for fresh plot\n\n # change default range so that new circles will work\n ax.set_xlim((0, SIDE))\n ax.set_ylim((0, SIDE))\n # some data\n ax.scatter([A[0], B[0]], [A[1], B[1]], color=&quot;blue&quot;)\n ax.axline(A, B, color=&quot;blue&quot;)\n ax.scatter([circle[0]], [circle[1]], color=&quot;red&quot;)\n # key data point that we are encircling\n ax.plot((5), (5), &quot;o&quot;, color=&quot;y&quot;)\n\n ax.add_patch(circle1)\n plt.show()\n\n\ndef main():\n circle, radius = get_random_circle()\n A, B = get_line_outside_circle(circle, radius)\n\n proj = orthogonal_projection(A, B, circle)\n if euclidian_distance(circle, proj) &lt; radius:\n print(&quot;We have an intersection!&quot;)\n\n plot_results(A, B, circle, radius)\n\n\nif __name__ == &quot;__main__&quot;:\n\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T01:31:04.837", "Id": "526209", "Score": "0", "body": "First, thank you very much. We assume that the line could be inside or outside the circle, in case the line intersects with the circle, what is the length of the line that is inside the circle according to the code above? Does this code return the intersection points (x1,x2),(y1,y2)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T06:24:31.623", "Id": "526213", "Score": "0", "body": "@Paulo \"_Asking for extensions to the code outside of (is there a better algorithm/can this be done in a better way), is outside the scope of this site and is better suited for stack overflow._\" Your method works for finding the intersection points fine and can be extended to arbitrary dimensions, see for instance https://math.stackexchange.com/a/2536095/18908. The distance can be computed from the inner product (or our function `euclidian_distance`) see https://math.stackexchange.com/a/2981910/18908. Again, you have to do some work yourself." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T21:08:51.407", "Id": "266365", "ParentId": "266358", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T17:43:38.047", "Id": "266358", "Score": "0", "Tags": [ "python", "python-3.x", "numpy" ], "Title": "line-circle intersection" }
266358
<p>I have been looking at the Fisher Yates randomizing suggestions on StackOverflow after ruling out <code>arr.sort(v =&gt; Math.random() - 0.5)</code> due to lack of randomness in the latter.</p> <p>The Fisher Yates functions look OK, but used while loops etc. Alternately, the javascript array functions (map, reduce, etc) have the obvious problem of going forward, so you keep on needing to access the length of the array to impliment it (which obviously drains a bit of time).</p> <p>So I wrote my own Fisher Yates using reduce.</p> <p>I wanted it to</p> <ol> <li><p>Alter the original array, as sort does.</p> </li> <li><p>Return the original array, so I could put it at the start of a chain of array functions, eg <code>let myarr = [1, 2, 3, 4, 5]; let newARR = fyRandArr(myarr).filter(v =&gt; v !== 3);</code></p> </li> <li><p>The last iteration of the reduce does not need to do anything, because that element is already randomly in position.</p> </li> </ol> <p>My function works and does everything above.</p> <p>I am a hobby programmer so am not sure if this is considered well written. I have no one to ask. How can it be improved?</p> <pre><code> const fyRandArr = arr =&gt; arr.reduce((A, v, i, a) =&gt; { let r; return i === A.lM1 ? a : (r = i + Math.floor(Math.random() * (A.l - i)), [a[i], a[r]] = [a[r], a[i]], A); }, {l: arr.length, lM1: arr.length -1}); </code></pre> <p>Obviously, if you want a pure function, ie producing a new array in the shuffle, you can just extract the reduce bit and not bother with the <code>fyRandArr</code>.</p> <p>The ones I did not like:</p> <p><a href="https://stackoverflow.com/questions/39989317/fisher-yates-shuffle-in-javascript">This one used while and splice</a></p> <p><a href="https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array/12646864#12646864">The ticked answer I liked, but still used a while loop</a></p> <p>Conclusion:</p> <p>So from the comments, it appears</p> <ol> <li>the comma operator is not liked</li> <li>different type accumulators are frowned upon</li> <li>persistently passing length in an object accumulator is more 'expensive' than calculating the length at each iteration.</li> </ol> <p>With all that, it appears the following is better:</p> <pre><code>const fyRandArr = arr =&gt; arr.reduce((a, v, i) =&gt; { let r, l = a.length; [a[i], a[r = (i + Math.random() * (l - i)) | 0]] = [a[r], a[i]]; return a; }, arr); </code></pre> <p>or</p> <pre><code>const fyRandArr = arr =&gt; { arr.map((v, i, a) =&gt; { let r, l = a.length; [a[i], a[r = (i + Math.random() * (l - i)) | 0]] = [a[r], a[i]]; return a[i]; }); return arr; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:24:33.203", "Id": "526182", "Score": "1", "body": "\"*The Fisher Yates functions look OK*\" - which ones did you look at? It might help to see the code that you started from (or at least links to it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:25:38.707", "Id": "526184", "Score": "2", "body": "Am I missing something or does the accumulator never change?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:34:24.423", "Id": "526185", "Score": "0", "body": "@Bergi - yep, the accumulator never changes. It is just there to store length and (length minus 1), so I do not have to keep on accessing it. I have been told in the past that accessing `arr.length` in a `for` loop is bad due to added time. As for links, I have put a few in the main question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:37:59.223", "Id": "526188", "Score": "1", "body": "\"*I have been told in the past that accessing `arr.length` in a `for` loop is bad*\" - well, that's a thing of the past, modern engines optimise such code just fine. But even then, you should just use a local constant `const l = arr.length;` in your function, not an accumulator. The cost of accessing `.length` on an array is nothing compared to creating an object and passing it to lots of function calls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:40:38.083", "Id": "526189", "Score": "0", "body": "The length/object passing info is very useful. (Note: I use the local constant for loops now.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:45:19.347", "Id": "526191", "Score": "0", "body": "Why does everyone gip the comma operator (your comment on StackOverflow)? For example if I have to calculate the distance between 2 vectors, it is so much easier to write `let l = (x = v1.x - v2.x, y = v1.y - v2.y, Math.pow(x * x + y * y, 0.5));` to show that bit of code is self contained and nothing to do with the rest of the function it is in and to reduce the number of function calls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:52:11.017", "Id": "526192", "Score": "2", "body": "Mostly because it *isn't* self-contained - it needs some extra declarations for the variables `x` and `y`. And once you add those, you might as well just write `const x = v1.x-v2.x, y = v1.y-v2.y, l = Math.sqrt(x*x+y*y);` anyway. Doing assignments as side effects inside other statements just makes for unreadable code in general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:56:28.550", "Id": "526193", "Score": "0", "body": "Btw your second link (\"*the ticked answer …*\") doesn't actually link the [accepted answer](https://stackoverflow.com/a/2450976/1048572) with the `while` loop, but the (imo better) [second-ranked answer](https://stackoverflow.com/a/12646864/1048572) with a `for` loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T18:57:41.023", "Id": "526194", "Score": "0", "body": "Ok, I see what you are saying for the vectors. But in my main post, I want to return the array in the final iteration of reduce, OR do the busy-work. If I do not use the comma operator I have to have extra bytes of text in my js file to wrap the busy-work in a `if` statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T19:00:05.607", "Id": "526195", "Score": "3", "body": "Yes, but you were asking for well-written code not for code with the minimum number of bytes :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T19:00:30.040", "Id": "526196", "Score": "0", "body": "Yes, the second-ranked answer is better in that link. I can see that, but again extra text in a js file to use a for loop instead of the built in iteration of reduce." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T19:02:20.927", "Id": "526197", "Score": "0", "body": "So the question arises again, why is the comma operator considered not well written? It is something in javascript. Just because it is not used much does not make it bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T19:03:21.097", "Id": "526198", "Score": "1", "body": "Also, returning the array in the final iteration and the differently-shaped accumulator object in other iterations is yet another antipattern that makes the code unclear. `reduce` is meant to be used with the type of the accumulator (and return value) being the same. As a proof, your code is actually broken: it doesn't work with an empty array. Notice you can achieve the same much easier by doing `return arr.reduce(…), arr` or `arr.reduce(…); return arr`, simply ignoring the return value of the `reduce` call. No extra precautions for \"the last iteration\" necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T21:02:33.677", "Id": "526285", "Score": "0", "body": "\"why is the comma operator considered not well written\" I feel it has its places (eg. set object property, return object), but often it can add mental overhead for human parsing. One can mitigate that somewhat by splitting lines in such way that the comma is at the beginning of line. But again, that might look alien to other readers." } ]
[ { "body": "<p>This code is overly terse, clever and (in the bottom two examples) broken. The versions with loops are far more readable, correct/verifiable, efficient and intuitive to understand.</p>\n<h3>Don't cache <code>array.length</code></h3>\n<p>I recommend reading Eric Lippert's <a href=\"https://ericlippert.com/2012/12/17/performance-rant/\" rel=\"nofollow noreferrer\">performance rant</a>. One key point is that if there's no performance problem that's affecting users, don't sacrifice code quality by default.</p>\n<p>Another key point is never to assume there's a performance problem until you've established it empirically through accurate benchmarking and profiling.</p>\n<p>You might be surprised how often something looks one way on paper from a performance or time complexity standpoint, but compiler optimizations, CPU optimization, cache performance and/or garbage collection winds up giving radically different results on a real machine and workload. In fact, the <a href=\"https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array\">most popular post on Stack Overflow</a> is about this exact phenomenon.</p>\n<p>Caching <code>array.length</code> in a variable is a classic premature optimization that can lead to bugs and makes code harder to understand in exchange for only a (generally) negligible performance improvement.</p>\n<p><code>.length</code> isn't the same as <a href=\"https://stackoverflow.com/questions/3388029/is-using-strlen-in-the-loop-condition-slower-than-just-checking-for-the-null-c\"><code>strlen()</code></a> in C which walks over each element of the list from start to end. <code>.length</code> is an O(1) property lookup, a hash table access, the same as any other object property access you'd never think to cache, like the accesses in your <code>reduce</code> accumulator object.</p>\n<p>The overhead of making a function call to your <code>.reduce</code> callback is likely many factors more overhead than the <code>.length</code> access, but I haven't profiled so this isn't definitive or the only reason to avoid <code>.reduce</code>. Compilers can do amazing things; trust them and use the right tool (in this case, <code>.reduce</code> is the wrong tool for semantic reasons, as I'll explain later).</p>\n<p>Similarly, creating unnecessary objects as in destructuring, <code>[a[r], a[i]]</code>, tends to have high overhead due to heap allocations and garbage collection (although a transpiler will convert this to a classical three-step assignment with a temporary variable, giving you the best of both worlds -- this is only something to bear in mind if the code won't be transpiled for compatibility).</p>\n<p>Furthermore, your <code>.reduce</code> accumulator object introduces potential constant-time memory overhead that wasn't in the original <code>for</code> loop algorithm. Caching <code>.length</code> but also allocating objects and making extra function calls inside a loop is penny wise and pound foolish.</p>\n<p>Anyway, after all the pains taken, <code>A.l</code> (and the confusingly-named <code>A.lM1</code> -- I'd just do <code>array.length - 1</code> instead of caching a simple math operation) still does an object access to get the length, so there's no performance improvement, even with the extra hoop to jump through. You might as well just use <code>a.length</code> directly.</p>\n<p>From an engineering perspective, detaching <code>.length</code> from the array it's called on means you've introduced more state. More state leads to more bugs -- that's another piece of data, another abstraction the programmer needs to carry in their mental working set to understand the program. More state leads to cognitive overload, making code harder to grasp at a glance.</p>\n<p>It's all too easy to forget you've cached the length, mutate an array and wind up with a stale length. If multiple arrays are in scope, it's all too easy to forget <em>which</em> array's length is associated with which cached variable, especially with a name like <code>l</code>. Always using <code>array.length</code> guarantees the most up-to-date length for <code>array</code>, is completely readable and robust to refactoring and extension.</p>\n<p>Only cache <code>.length</code> if it a accomplishes a particular programmatic goal or you've profiled extensively and found that caching it gives you enough of a speedup that it outweighs the software engineering cost of detaching the property and regressing back to lower-level C, where native arrays don't have built-in lengths. It's highly unlikely that <code>.length</code> is your app's bottleneck preventing it from delivering value, so you basically never need to do this.</p>\n<p>Sure, you can argue this is no problem in a 3-line function, but there's no reason to write 3-line functions any different than the rest of the codebase. Might as well get in the habit of making all code as comprehensible as possible, regardless of size. Small functions can still hide bugs, as is the case in the bottom two code snippets.</p>\n<h3>Don't return a value for in-place functions</h3>\n<p>JS offers at least two library functions that operate <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" rel=\"nofollow noreferrer\">in-place</a> but return their argument for chaining purposes: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\"><code>.sort()</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse\" rel=\"nofollow noreferrer\"><code>.reverse()</code></a>. I use <code>.sort()</code> frequently, so I generally remember to call <code>.slice()</code> in the chain before it, but I don't know how many times I've forgotten to do the same for <code>.reverse()</code> and wound up with a bug. Usually, I'll catch it right away, but why take the risk of a silent and potentially subtle logical error like this making it into an app?</p>\n<p>If a function is in-place, returning undefined/null as Python does (&quot;<code>None</code>&quot;) is the safest approach -- it's <a href=\"https://stackoverflow.com/a/12699808/6243352\">less elegant</a>, but it avoids more problems than the benefits chainability offers. Python has a separate function, <code>sorted</code>, that's the immutable, value-returning version.</p>\n<p>Besides, standard library functions like <code>.sort()</code> and <code>.reverse()</code> have well-known and ubiquitously-documented specifications, so their quirks and gotchas are common knowledge. Someone reading your code won't have the luxury of knowing the contract for your function, so I always err on the side of least surprise.</p>\n<p>If a programmer really needs a chainable version, they can opt-in to the impure code by writing a wrapper with a clear name. As an example, Ruby uses the bang method syntax <code>.shuffle!</code> to indicate a dangerous in-place operation even though it returns a value. You could follow this pattern by naming the wrapper <code>shuffleInPlace()</code> or similar, or provide a version that makes a copy before sorting, <code>shuffleCopy()</code>. <code>shuffleInPlace(foo).map(...)</code> seems less likely to hide a bug than <code>shuffle(foo).map(...)</code>. Seeing this code, however, begs the question why you'd need to chain a shuffle anyway.</p>\n<p>Since your function isn't attached to the prototype of <code>Array</code> (<a href=\"https://stackoverflow.com/questions/23807805/why-is-mutating-the-prototype-of-an-object-bad-for-performance\">a good thing</a>), it can't be truly chained without an abstraction like <a href=\"https://ramdajs.com/docs/#chain\" rel=\"nofollow noreferrer\">Ramda's <code>chain</code></a>.</p>\n<h3>Avoid inline assignments</h3>\n<p>The code</p>\n<pre><code>[a[i], a[r = (i + Math.random() * (l - i)) | 0]] = [a[r], a[i]]\n</code></pre>\n<p>is very difficult to read and is buggy. A minimal reproduction of the cause of the bug is:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>[[][console.log(\"hi\")]] = [console.log(\"bye\")];</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You'll see that <code>&quot;bye&quot;</code> is logged, then <code>&quot;hi&quot;</code>. This shows that the right-hand side is evaluated first, then the left, meaing <code>a[r]</code> is always <code>a[undefined]</code>, which evaluates to <code>undefined</code>.</p>\n<p>Instead of trying to push the boundaries of order of evaluation sensibility, spread this into multiple lines, use unabbreviated variable names and prefer <code>Math.floor</code> to bitwise <code>| 0</code>. I sometimes use <code>~~(x)</code> to floor -- it's not the best habit, but what I like over <code>| 0</code> is that it looks like a function call, so I find it visually easier to follow.</p>\n<p>Creating wrappers on <code>Math.random()</code> that offer higher-level interfaces into random integers and picking random elements from arrays is a great way to clean up the code.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const randomInt = n =&gt; Math.floor(n * Math.random());\n\n// ...\nconst j = randomInt(a.length);\n[a[j], a[i]] = [a[i], a[j]];\n</code></pre>\n<p>is much cleaner and easy to reason about.</p>\n<h3>Only use <code>.reduce</code> for reduction and <code>.map</code> for mapping</h3>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>Array#reduce</code></a> is very easy to abuse in JS. It's an inherently confusing function that should be used only when the accumulator structure is simple and doesn't have state other than the result itself. For example, summing an array or building a frequency counter for elements in an array are good uses for <code>reduce</code>. These really are reduction operations, but shuffling an array isn't. Almost always, <code>map</code>, <code>filter</code>, <code>forEach</code> or <code>flatMap</code> is more appropriate than <code>reduce</code>.</p>\n<p>In this case, <code>.map</code> is also inappropriate because the callback causes a mutation <a href=\"https://en.wikipedia.org/wiki/Side_effect_(computer_science)\" rel=\"nofollow noreferrer\">side-effect</a>. This breaches one of the key ideals of functional programming, <a href=\"https://en.wikipedia.org/wiki/Immutable_object\" rel=\"nofollow noreferrer\">immutability</a>. <code>.map</code>'s callback should never do anything but statelessly return the new value for the <code>i</code>-th element -- it should definitely not mutate other elements in the array or external state elsewhere, and ideally shouldn't read external data other than <code>a[i]</code> itself.</p>\n<p>I hate to keep bringing up Python, but they <a href=\"https://stackoverflow.com/questions/181543/what-is-the-problem-with-reduce\">got it right in relegating <code>reduce</code> to a second-class citizen</a>. Python and JS are similar in that they're both imperative languages with functional influence. Some programmers prefer to emphasize the functional influence to a greater or lesser extent. In my view, trying too hard to shoehorn functional programming into imperative languages usually lands flat on its face and just makes a mess, except for rare occasions when someone really knows what they're doing.</p>\n<p>The best application of functional paradigms in JS for me is using the correct high-level iteration abstractions as appropriate and the immutability, the program safety. Without immutability, the high-level abstractions tend to collapse.</p>\n<h2>Avoid the comma operator for multiple expressions</h2>\n<p>Continuing the themes throughout, there's basically never any reason to use the comma operator to separate expressions, including declarations, in JS. It only leads to pain: expensive eye doctor bills and bugs. Just write every statement on its own line. Save minification to the bundler.</p>\n<p>Following up with this and a few other points, keep lines to no more than 80 characters wide, preferably 60-70. This policy forces you to write more readably and spread things into multiple, vertical statements rather than long, stream-of-consciousness comma-delimited expressions that mutate state used by other expressions in the chain, wreaking havoc.</p>\n<h2>Avoid forward-delarations</h2>\n<p>Continuing with commas, the idiom:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let foo, bar;\n\n// ... later on ...\nfoo = 42;\nbar = 43;\n</code></pre>\n<p>is an antipattern. Just do:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const foo = 42;\nconst bar = 43;\n</code></pre>\n<p>at the point in the code where the variables are needed.</p>\n<p>If you always declare everything with <code>const</code>, scope it as tightly to where the variable was used, and initialize on the spot, dangerous programming habits like assignments in expressions are prohibited.</p>\n<p>If you basically never use <code>let</code> (okay, seems fine in <code>for</code> loop counters and other specific use cases, but we already agree we don't like counter-based <code>for</code> loops and will probably barely use them), code quality is forced into improving.</p>\n<h2>Use linters</h2>\n<p>A good linter will give you many errors about code like this. Go ahead and drop it into <a href=\"https://eslint.org/demo\" rel=\"nofollow noreferrer\">https://eslint.org/demo</a>, then turn on all rules. Some are fairly spurious or innocuous, but others instantly tell you most of the same things humans will tell you on this site manually.</p>\n<h2>Conclusion</h2>\n<p>Use the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm\" rel=\"nofollow noreferrer\">code from Wikipedia that uses a <code>for</code> loop</a>. This code is pretty much straight from the algorithm master Donald Knuth's bible, TAOCP.</p>\n<p>Algorithms are tricky, and my philosophy is to basically copy them verbatim from the smart people that came up with them (usually via Wikipedia, which <em>can</em> have errors but usually doesn't; cross-reference to be sure), with as few &quot;clever improvements&quot; as possible. It's so easy to do it wrong and miss some minor detail.</p>\n<p>If you're using a linter that <a href=\"https://github.com/buildo/eslint-plugin-no-loops\" rel=\"nofollow noreferrer\">prohibits loops</a>, add a comment to silence linting for this one occasion where a traditional loop makes sense: <code>// eslint-disable-next-line no-loops/no-loops</code>. I'm against counter loops too, but this is an appropriate time to use one (you basically never need <code>while</code> though).</p>\n<h2>My version</h2>\n<pre class=\"lang-js prettyprint-override\"><code>const randInt = n =&gt; Math.floor(Math.random() * n);\n\nconst shuffle = a =&gt; {\n for (let i = a.length - 1; i &gt; 0; i--) {\n const j = randInt(i + 1);\n [a[i], a[j]] = [a[j], a[i]];\n }\n};\n</code></pre>\n<p>Transpiled for compatibility and performance (no destructuring):</p>\n<pre class=\"lang-js prettyprint-override\"><code>function randInt(n) {\n return Math.floor(Math.random() * n);\n}\n\nfunction shuffle(a) {\n for (var i = a.length - 1; i &gt; 0; i--) {\n var j = randInt(i + 1);\n var x = a[i];\n a[i] = a[j];\n a[j] = x;\n }\n}\n</code></pre>\n<p>If you absolutely must chain, write a wrapper with a clear name like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const shuffleInPlace = a =&gt; {\n shuffle(a);\n return a;\n};\n\n// or\n\nconst shuffleCopy = a =&gt; {\n a = a.slice();\n shuffle(a);\n return a;\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T19:54:59.207", "Id": "526274", "Score": "1", "body": "This is useful, not least because it is contrary to stuff I have read and been misguided by recently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T20:04:09.567", "Id": "526277", "Score": "0", "body": "Two questions: 1. why don't you **ultimately** use arrow functions on randInt and shuffle? 2. I have read using map, reduce, etc is more readable than using for and while loops . Who is right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T20:05:37.457", "Id": "526278", "Score": "0", "body": "Can you show what you've read recently? I'm betting these weren't shuffles. I'm not saying don't use `map` and `reduce` -- I use `map` constantly, and `reduce` probably slightly more often, or about as often, as traditional counter loops (not very often). This is a rare occasion where these functions are inappropriate. Swapping elements is not a clear-cut mapping or a reduction operation, so it's best to stick to the classical loop. I do use arrow functions, but if you transpile the code or write directly for browser compatibility, you'd use `function`, so I show the transpiled code as well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T16:17:39.853", "Id": "266389", "ParentId": "266359", "Score": "5" } } ]
{ "AcceptedAnswerId": "266389", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T17:54:32.577", "Id": "266359", "Score": "0", "Tags": [ "javascript", "shuffle" ], "Title": "Fisher Yates Shuffle, but using Javascript Array Functions" }
266359