body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am working on a relatively simple binning program, where I take a 5D array and bin it based on two 3D arrays to create a contour plot. See the sample code below. In actuality, my arrays are of size <code>[27, 150, 20, 144, 288]</code>, so running a 4-nested for loop as shown below takes a LONG time.</p> <p>Is there any way to speed up this loop and ideally avoid the need for all these loops? Apologies in advance if this isn't clear - I am new to all this!</p> <pre><code>S_mean = np.random.rand(5,10,10,10) T_mean = np.random.rand(5,10,10,10) Volume_mean = np.random.rand(2,5,10,10,10) T_bins = np.linspace(0,1,36) S_bins = np.linspace(0,1,100) int_temp = [] int_sal = [] for i in range(5): int_temp.append(np.digitize(np.ndarray.flatten(T_mean[i,:,:,:]), T_bins)) int_sal.append(np.digitize(np.ndarray.flatten(S_mean[i,:,:,:]), S_bins)) volume_sum = np.zeros((2,5,S_bins.size,T_bins.size)) # This is the problem loop for k in range(2): for l in range(5): for i in range(T_bins.size): for j in range(S_bins.size): volume_sum[k,l,j,i]=(np.nansum(np.ndarray.flatten(Volume_mean[k,l,:,:,:]) [np.argwhere(np.logical_and(int_temp[l] == i, int_sal[l] == j))])) # The output I am trying to get plt.pcolormesh(T_bins, S_bins, volume_sum[0,0,:,:]) plt.show() </code></pre>
[]
[ { "body": "<p>\"Relatively simple\" is in the eye of the beholder. Some ideas though:</p>\n\n<p>This code</p>\n\n<blockquote>\n<pre><code>int_temp = []\nint_sal = []\n\nfor i in range(5):\n int_temp.append(np.digitize(np.ndarray.flatten(T_mean[i,:,:,:]), T_bins))\n int_sal.append(np.digitize(np.ndarray.flatten(S_mean[i,:,:,:]), S_bins))\n</code></pre>\n</blockquote>\n\n<p>can be transformed into two list comprehesions</p>\n\n<pre><code>int_temp = np.array([np.digitize(T_mean[i, :, :, :].flatten(), T_bins) for i in range(5)])\nint_sal = np.array([np.digitize(S_mean[i, :, :, :].flatten(), S_bins) for i in range(5)])\n</code></pre>\n\n<p>I also converted the results into numpy arrays, for reasons that I'll refer to later. Also take note that <code>np.ndarray.flatten(T_mean[i,:,:,:])</code> was rewritten as <code>T_mean[i, :, :, :].flatten()</code> which is the usual way to use <code>np.ndarray.&lt;fun&gt;</code>: call <code>whatever.&lt;fun&gt;()</code> (<code>&lt;fun&gt;</code> is meant to be a placeholder here, not actual code).</p>\n\n<p>The next part of the code that caught my eye was</p>\n\n<blockquote>\n<pre><code>np.ndarray.flatten(volume_mean[k, l, :, :, :])\n [np.argwhere(np.logical_and(int_temp[l] == i, int_sal[l] == j))])\n</code></pre>\n</blockquote>\n\n<p>This line is very hard to read, but can easily be rewritten as:</p>\n\n<pre><code>indices = np.argwhere(np.logical_and(int_temp[l] == i, int_sal[l] == j))\nvolume_sum[k, l, j, i] = nansum(volume_mean[k, l, :, :, :].flatten()[indices])\n</code></pre>\n\n<p>which looks muss less frightening. You can even get rid of <code>np.argwhere</code> and use <code>np.logical_and(int_temp[l] == i, int_sal[l] == j)</code> directly as binary mask:</p>\n\n<pre><code>mask = np.logical_and(int_temp[l] == i, int_sal[l] == j)\nvolume_sum[k, l, j, i] = (\n np.nansum(volume_mean[k, l, :, :, :].flatten()[mask])\n)\n</code></pre>\n\n<p>To see if there is a difference in performance, I put the original code and the refactored version into functions:</p>\n\n<pre><code>def compute_volume_sum(volume_mean, s_mean, t_mean, s_bins, t_bins):\n \"\"\"Original implementation\"\"\"\n int_temp = []\n int_sal = []\n for i in range(5):\n int_temp.append(np.digitize(np.ndarray.flatten(t_mean[i,:,:,:]), t_bins))\n int_sal.append(np.digitize(np.ndarray.flatten(s_mean[i,:,:,:]), s_bins))\n\n volume_sum = np.zeros((2, 5, s_bins.size, t_bins.size))\n for k in range(2):\n for l in range(5):\n for i in range(t_bins.size):\n for j in range(s_bins.size):\n volume_sum[k, l, j, i] = (np.nansum(\n np.ndarray.flatten(volume_mean[k, l, :, :, :])[np.argwhere(\n np.logical_and(int_temp[l] == i, int_sal[l] == j))]))\n\n return volume_sum\n\n\ndef compute_volume_sum_ref(volume_mean, s_mean, t_mean, s_bins, t_bins):\n \"\"\"Refactored implementation\"\"\"\n int_temp = np.array([np.digitize(t_mean[i, :, :, :].flatten(), t_bins) for i in range(5)])\n int_sal = np.array([np.digitize(s_mean[i, :, :, :].flatten(), s_bins) for i in range(5)])\n\n volume_sum = np.zeros((2, 5, s_bins.size, t_bins.size))\n for k in range(2):\n for l in range(5):\n for i in range(t_bins.size):\n for j in range(s_bins.size):\n mask = np.logical_and(int_temp[l] == i, int_sal[l] == j)\n volume_sum[k, l, j, i] = (\n np.nansum(volume_mean[k, l, :, :, :].flatten()[mask])\n )\n\n return volume_sum\n</code></pre>\n\n<p>BTW: You can confirm that both functions return the same value using <code>np.allclose</code></p>\n\n<p>I then measured how long it takes to run each function ten times. The results were as follows:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>original: 16.860085s\nrefactored: 11.849922s\n</code></pre>\n\n<p>Not bad, but those loops still hurt.</p>\n\n<p>Enter <a href=\"http://numba.pydata.org/\" rel=\"nofollow noreferrer\"><code>numba</code></a>, a just-in-time Python compiler. It works nicely with numpy and can make loops quite a bit faster since they are compiled to native code. I recommend to use a scientific Python distribution like <a href=\"https://www.anaconda.com/distribution/\" rel=\"nofollow noreferrer\">Anaconda</a> if you want to try/use it.</p>\n\n<p>Unfortunately, numba does not support the full feature set of Python (e.g. list comprehensions are not supported), so I had to resort to a little bit of trickery to get it working:</p>\n\n<pre><code>import numba\n\ndef compute_volume_sum_nb(volume_mean, s_mean, t_mean, s_bins, t_bins):\n \"\"\"numba version\"\"\"\n int_temp = np.array([np.digitize(t_mean[i, :, :, :].flatten(), t_bins) for i in range(5)])\n int_sal = np.array([np.digitize(s_mean[i, :, :, :].flatten(), s_bins) for i in range(5)])\n\n return _numba_inner(volume_mean, s_bins, t_bins, int_temp, int_sal)\n\n@numba.njit()\ndef _numba_inner(volume_mean, s_bins, t_bins, int_temp, int_sal):\n volume_sum = np.zeros((2, 5, s_bins.size, t_bins.size))\n for k in range(2):\n for l in range(5):\n for i in range(t_bins.size):\n for j in range(s_bins.size):\n mask = np.logical_and(int_temp[l] == i, int_sal[l] == j)\n volume_sum[k, l, j, i] = (\n np.nansum(volume_mean[k, l, :, :, :].flatten()[mask])\n )\n\n return volume_sum\n</code></pre>\n\n<p><code>numba.njit()</code> is a decorator that can be used on functions to mark their function body for jit-compilation. The first time <code>compute_volume_sum_nb</code> is called, numba triggers the compilation process so be sure to exclude the first call from any timings you do.</p>\n\n<p>Let's see how the timings now look like:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>original: 16.860085s\nrefactored: 11.849922s\nnumba: 0.833529s\n</code></pre>\n\n<p>That's quite a bit faster, isn't it?</p>\n\n<p>I'm almost sure that some of the loops could be replaced by clever indexing and use of vectorized functions in numpy, but I don't have the time to dive deeper into the problem.</p>\n\n<hr>\n\n<p>A few non-performance related notes: be sure so have a look at the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code (aka PEP 8)</a>. The code sometimes already follows those guidelines, but sometimes also doesn't, e.g. when using uppercase letters in variable names.</p>\n\n<p>Maybe also think about how you can modularize your code, e.g by using functions. Those separated parts are also easier to document. You want to write <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>\"\"\"\"documentation\"\"\"</code></a> to save future you some headache, don't you?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T05:31:46.080", "Id": "468324", "Score": "0", "body": "This is great. Just wanted to point out that numpy.searchsorted is faster than numpy.digitize for large datasets. See [here for more information](https://github.com/numpy/numpy/issues/2656)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T16:12:25.607", "Id": "468488", "Score": "1", "body": "@allthemikeysaretaken: [That was fixed in 2014](https://github.com/numpy/numpy/pull/5101), which is also mentioned at the end of the issue you linked." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:07:07.037", "Id": "238776", "ParentId": "238749", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T04:14:19.817", "Id": "238749", "Score": "5", "Tags": [ "python", "performance", "numpy" ], "Title": "Binning whilst avoiding the need for for-loops in Python?" }
238749
<p>I did create a function which loops through the colors of a product and outputs a div with the specific color. After that it finds the image for the available colors. But I think the code can be a lot smarter.</p> <p>Can someone optimize my code?</p> <pre><code>&lt;?php $brand_terms = get_the_terms($post, 'pa_kleur'); $brand_string = ''; // Reset string foreach ($brand_terms as $term) : ?&gt; &lt;div style="display: block; margin-bottom: 50px;"&gt;&lt;?php if (($term-&gt;name) == 'Roze') { echo '&lt;div style="width: 20px; height: 20px; background-color: pink;" class="roze-kleur"&gt;&lt;/div&gt;'; $variations = $product-&gt;get_available_variations(); foreach ( $variations as $key =&gt; $value ) { ?&gt; &lt;?php if ($value['attributes']['attribute_pa_kleur'] == 'roze') { ?&gt; &lt;li&gt; &lt;span&gt;&lt;?php echo $value['image']['url']; }?&gt;&lt;/span&gt; &lt;/li&gt;&lt;/div&gt; &lt;?php } } if (($term-&gt;name) == 'Grijs') { echo '&lt;div style="width: 20px; height: 20px; background-color: grey;" class="grijze-kleur"&gt;&lt;/div&gt;'; $variations = $product-&gt;get_available_variations(); foreach ( $variations as $key =&gt; $value ) { ?&gt; &lt;?php if ($value['attributes']['attribute_pa_kleur'] == 'grijs') { ?&gt; &lt;li&gt; &lt;span&gt;&lt;?php echo $value['image']['url']; }?&gt;&lt;/span&gt; &lt;/li&gt;&lt;/div&gt; &lt;?php } } endforeach; ?&gt; </code></pre> <p>Thanks for your time!</p>
[]
[ { "body": "<ul>\n<li>keeping separate actions on a different line and tabbing your code will go a long way with making your code readable.</li>\n<li>avoid declaring single-use variables </li>\n<li>I don't see <code>$brand_string</code> being used, so that declaration can be omitted.</li>\n<li>I do not prefer the <code>endforeach</code> syntax. Despite being declarative, I find it unnecessarily verbose. Good tabbing is always enough to help me track the nesting of control structures and functions.</li>\n<li>move all inline styling to an external stylesheet. Using meaningful class names to assign appropriate colors is most logical here.</li>\n<li>I expect all <code>&lt;div&gt;</code> tags are <code>display: block;</code> by default -- I doubt this style declaration is necessary.</li>\n<li>use a lookup array to swiftly translate <code>$term-&gt;name</code> values into <code>class</code> attribute values and eliminate the mostly redundant <code>if</code> blocks.</li>\n<li>don't declare <code>$key</code> if you never intend to use it.</li>\n<li>filter the variations array based on the lowercase value of <code>$term-&gt;name</code> and use a conditional <code>break</code> for best efficiency. I am confidently assuming that there will only be one match in your variations array based on the trailing <code>&lt;/div&gt;</code></li>\n<li>your list item should be nested inside of a list tag (e.g. <code>&lt;ul&gt;</code>)</li>\n<li>remove the <code>&lt;span&gt;</code> tags -- they are unnecessary markup. If you need to style the list items, style the <code>&lt;li&gt;</code> tags</li>\n<li>if you must have your data processing in the same script as your content outputting, then I recommend doing your processing first, then keeping your markup readable by referencing the generated variables</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>$colorClasses = [\n 'Roze' =&gt; 'roze-kleur',\n 'Grijs' =&gt; 'grijze-kleur',\n];\nforeach (get_the_terms($post, 'pa_kleur') as $term) {\n $lowerColor = lcfirst($term-&gt;name);\n $colorUrl = 'you_decide_the_url';\n foreach ($product-&gt;get_available_variations() as $row) {\n if ($row['attributes']['attribute_pa_kleur'] === $lowerColor) {\n $colorUrl = $value['image']['url'];\n break;\n }\n }\n\n echo '&lt;div&gt;\n &lt;div class=\"' , ($colorClasses[$term-&gt;name] ?? 'default-kleur') , '\"&gt;&lt;/div&gt;\n &lt;ul&gt;&lt;li&gt;' , $colorUrl , '&lt;/li&gt;&lt;/ul&gt;\n &lt;/div&gt;';\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T10:07:43.200", "Id": "238817", "ParentId": "238753", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T09:00:58.417", "Id": "238753", "Score": "3", "Tags": [ "php" ], "Title": "PHP color and image loop" }
238753
<p>When report writing, sometimes getting the data you need can be quite straightforward in SQL, but getting the data in the exact format you'll need it in for the specific report can be quite tricky. It's this format step of report writing that I'm not sure whether it's best to do in SQL side or PHP side; manipulating the data in such a way that it is easily looped through in the templating language (twig in this case) can be quite complex.</p> <p>Example of more logic done in MySql and less in PHP:</p> <p>MySql:</p> <pre class="lang-sql prettyprint-override"><code>SELECT r.id room_id, r.name room_name, r.capacity room_capacity, r_parent.name parent_name, count(bb.id) as beds_in_use_count, group_concat(distinct bb.gender) as gender, td.date as stay_date, GROUP_CONCAT( DISTINCT COALESCE( -- booking_beds CONCAT( CASE WHEN bb_previous_day.booking_id IS NULL THEN 'IN: ' ELSE '' END, CASE WHEN bb_next_day.booking_id IS NULL THEN 'OUT: ' ELSE '' END, COALESCE( co.name, IF((c.first_name IS NULL OR c.first_name = ''), c.second_name, CONCAT(c.first_name,' ',c.second_name)) ) ) , -- new coalesce group -- exclusive rooms CONCAT( 'EXCLUSIVE: ', COALESCE( co2.name, IF((c2.first_name IS NULL OR c2.first_name = ''), c2.second_name, CONCAT(c2.first_name,' ',c2.second_name)), -- if course, then co2 and c2 won't join as that's on a booking. CONCAT(course.course_name, ' - ', cr.reference) ) ) ) -- end coalesce SEPARATOR ', ' ) description FROM resource r JOIN resource r_parent ON r.parent_id = r_parent.id AND r_parent.company_id = 58 JOIN time_dimension td ON td.`date` BETWEEN DATE(:startDate) AND (DATE(:endDate) - INTERVAL 1 DAY) LEFT JOIN booking_beds bb ON bb.resource_id = r.id AND DATE(bb.date) = DATE(td.date) LEFT JOIN booking_beds bb_previous_day ON bb_previous_day.resource_id = r.id AND DATE(bb_previous_day.date) = DATE(DATE(td.date) - INTERVAL 1 DAY) AND bb.booking_id = bb_previous_day.booking_id LEFT JOIN booking_beds bb_next_day ON bb_next_day.resource_id = r.id AND DATE(bb_next_day.date) = DATE(DATE(td.date) + INTERVAL 1 DAY) AND bb.booking_id = bb_next_day.booking_id LEFT JOIN booking_visitor_name bvn ON bb.booking_visitor_name_id = bvn.id LEFT JOIN guest g ON bb.guest_id = g.id LEFT JOIN booking b on bb.booking_id = b.id LEFT JOIN contact c ON c.id = b.contact_id LEFT JOIN contact_organisation co ON co.id = b.organisation_id -- exclusive rooms LEFT JOIN booking_resources br ON r.id = br.resource_id AND DATE(td.date) BETWEEN DATE(br.start_date) AND DATE_SUB(DATE(br.end_date), INTERVAL 1 DAY) LEFT JOIN course_run cr ON br.course_run_id = cr.id LEFT JOIN course course ON cr.course_id = course.id LEFT JOIN booking exclusive_booking ON br.booking_id = exclusive_booking.id LEFT JOIN contact c2 ON c2.id = exclusive_booking.contact_id LEFT JOIN contact_organisation co2 ON co2.id = exclusive_booking.organisation_id WHERE r.centre_id = :centreId AND r.company_id = :companyId AND r.is_bedlistable = 1 AND r.removed = 0 AND r_parent.removed = 0 GROUP BY room_id, td.date ORDER BY r_parent.weight, r_parent.name, r.weight, td.date ASC </code></pre> <p>PHP:</p> <pre class="lang-php prettyprint-override"><code>foreach ($result as $row) { $data[$row['parent_name']][$row['room_name']][$row['stay_date']] = $row; } </code></pre> <p>Example of more logic done in PHP and less in MySql:</p> <p>MySql:</p> <pre class="lang-sql prettyprint-override"><code>SELECT b.id AS booking_id, gv.id as visit_id, g.id as group_id, gv.start_date, gv.end_date, gv.eta, GROUP_CONCAT(bvdr.requirements) as dietary, GROUP_CONCAT(m.med_con) as med_con, GROUP_CONCAT(m.med_taking) as med_taking FROM groups_visit gv LEFT JOIN groups g on g.id = gv.groups_id LEFT JOIN booking b on b.id = g.booking_id LEFT JOIN booking_visitor_name bvn ON bvn.booking_id = b.id LEFT JOIN booking_visitor_dietary_requirements bvdr ON bvdr.booking_visitor_name_id = bvn.id LEFT JOIN medical m ON m.visitor_id = bvn.id WHERE ( (gv.start_date &gt;= :start AND gv.start_date &lt; :end) OR (gv.end_date &gt;=:start AND gv.end_date &lt; :end) OR (gv.start_date &lt; :start AND gv.end_date &gt; :end) ) AND b.company_id = :company_id AND b.deleted = 0 AND b.removed = 0 AND b.centre_id=:centre_id GROUP BY b.id ORDER BY start_date ASC </code></pre> <p>PHP:</p> <pre class="lang-php prettyprint-override"><code>$collection = array(); foreach ($groups as $g) { $row = $g; $row['booking'] = $this-&gt;em-&gt;getRepository(Booking::class)-&gt;find($g['booking_id']); $row['group'] = $this-&gt;em-&gt;getRepository(Groups::class)-&gt;find($g['group_id']); $row['visit'] = $this-&gt;em-&gt;getRepository(GroupsVisit::class)-&gt;find($g['visit_id']); $row['start_date'] = new \DateTime($g['start_date']); $row['end_date'] = new \DateTime($g['end_date']); $collection[] = $row; } $date = clone($startDate); foreach ($collection as $g) { $dayArriving = new \DateTime($g['start_date']-&gt;format("Y-m-d") . " 00:00:00"); $dayDeparting = new \DateTime($g['end_date']-&gt;format("Y-m-d") . " 00:00:00"); $daysOfStay = $dayArriving-&gt;diff($dayDeparting)-&gt;d; $row = array( 'reference' =&gt; $g['booking']-&gt;getReference(), 'arrival' =&gt; $g['start_date']-&gt;format("H:i D jS M y "), 'departure' =&gt; $g['end_date']-&gt;format("H:i D jS M y "), 'eta' =&gt; isset($g['eta']) ? date("H:i", strtotime($g['eta'])) : "", 'daysOfStay' =&gt; ($dayArriving-&gt;diff($date)-&gt;d + 1) . " of " . ($daysOfStay + 1), 'participantcount' =&gt; $g['group']-&gt;getTotalParticipants(), 'totalguests' =&gt; $g['booking']-&gt;getTotalGuests(), 'gendersplit' =&gt; $g['group']-&gt;getFemaleParticipants() . " Female, " . $g['group']-&gt;getMaleParticipants() . " Male", 'notes' =&gt; $g['booking']-&gt;getNotes(), 'dietary' =&gt; $g['dietary'], 'med_con' =&gt; $g['med_con'], 'med_taking' =&gt; $g['med_taking'], ); if ($g['booking']-&gt;getContact() &amp;&amp; $g['booking']-&gt;getContact()-&gt;getContactOrganisation() &amp;&amp; $g['booking']-&gt;getContact()-&gt;getContactOrganisation()-&gt;getName() != "None") { $row['organisationname'] = $g['booking']-&gt;getContact()-&gt;getContactOrganisation()-&gt;getName(); } else { $row['organisationname'] = ''; } if ($g['booking']-&gt;getContact()) { $row['contact'] = $g['booking']-&gt;getContact()-&gt;getName(); } else { $row['contact'] = ''; } $row['leaders'] = $g['group']-&gt;getLeadersName(); $data[] = $row; } </code></pre> <p>Is there a generally more preferred approach, or does it just depend on the situation i.e. which is more performant, which skillsets do you have at the company etc?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T10:19:26.313", "Id": "468343", "Score": "0", "body": "**Off-topic: Generic best practices are outside the scope of this site.** As a general tip, I'd say let MySQL do what it does best joining/grouping/sorting/etc and bias (if your skills allow) toward MySQL when it reduces the overall size of a result set versus php processing. That said, there is a sensible threshold to what a maintainable query looks like and if you are using platform helpers / query builders, then big queries turn into huge code blocks that can be unwieldy. Unfortunately, this is a hypothetical question about what is generally best, so an answer is inappropriate to provide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T10:21:11.080", "Id": "468344", "Score": "0", "body": "Sorry to have to close vote. I see that you have spent some time crafting a clear and complete question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T11:02:35.377", "Id": "468346", "Score": "0", "body": "Oh, I thought generic best practices was the scope of this site, which is why I put on here and not stack overflow! Ah well, thanks for the explanation :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T00:18:19.360", "Id": "468419", "Score": "0", "body": "Reviews are expected to include advice based on best practice, but this needs to be focused on specific script(s) for an isolated task. What you _could_ do is pick a single script, identify what it does in your title, provide the necessary table schema/data, explain that you would like that isolated script to be reviewed. We certainly do code comparisons too (mysql-centric vs php-centric). In other words, your submission is Too Broad/Generalized to be properly reviewed. When you isolate a single specific task, it is possible that a third option may be presented." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T10:05:09.593", "Id": "238757", "Score": "0", "Tags": [ "php", "mysql", "comparative-review", "twig" ], "Title": "Report writing, do the formatting work on database or non-database language?" }
238757
<p>I want to use the <a href="https://data.stackexchange.com/" rel="nofollow noreferrer">Stack exchange data explorer</a> in order to display some basic information about the top tags.</p> <p>The query should print the number of questions and answers, the average number of answers per question and the average score of posts(questions and answers under such questions). The query is ordered by the total number of questions.</p> <p>This is my SQL code:</p> <pre><code>SELECT TOP(10) Tags.TagName, COUNT(DISTINCT Questions.Id) AS 'Number of Questions', COUNT(Answers.Id) AS 'Number of Answers', (COUNT(Answers.Id)+0.0)/COUNT(DISTINCT Questions.Id) AS 'Answers per question', ( SELECT AVG(post.Score+0.0) FROM Posts post,PostTags tag WHERE ( post.Id=tag.PostId OR post.ParentId=tag.PostId ) AND tag.TagId=Tags.Id ) AS 'average score of posts under this tag(questions and answers)' FROM Posts Questions LEFT JOIN Posts Answers ON Answers.ParentId = Questions.Id INNER JOIN PostTags ON Questions.Id=PostTags.PostId INNER JOIN Tags ON PostTags.TagId=Tags.Id GROUP BY Tags.Id,Tags.TagName ORDER BY COUNT(*) DESC </code></pre> <p>You can look at the script in the data explorer <a href="https://data.stackexchange.com/stackoverflow/query/1209456/idk-lul" rel="nofollow noreferrer">here</a>.</p> <p>The problem is that the script times out(in around 100 seconds). If I remove the <strong><code>OR post.ParentId=tag.PostId</code></strong>, it still takes around 25 seconds to run (for Stack Overflow) but it does not time out. </p> <p>If I <a href="https://data.stackexchange.com/superuser/query/1209456/idk-lul" rel="nofollow noreferrer">run my script on Super User</a>, it does not time out. (It runs around 4 seconds, I think it is because Super User is smaller than Stack Overflow)</p> <p><strong>Is there a way to run optimize the script so that it does not time out on Stack Overflow without losing functionality and why does that simple <code>OR</code> decrease the performance that much?</strong></p> <p>The OR is that answers do also count for the average score.</p> <p>I've added the execution plan files <a href="https://gist.github.com/danthe1st/65c2703530e9995b1e9a2bdc8df2f427" rel="nofollow noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T10:58:56.783", "Id": "468260", "Score": "0", "body": "Could you please include query execution plan for both queries (with and without the OR)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T10:59:47.240", "Id": "468261", "Score": "0", "body": "The current question title of your question is too generic to be helpful. 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)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T11:16:05.140", "Id": "468263", "Score": "0", "body": "@slepic I've added them as a GitHub Gist in an edit." } ]
[ { "body": "<p>Oh well, I didnt notice the sql-server tag...</p>\n\n<p>What a detailed execution plan they have :)</p>\n\n<p>But anyway the answer may be as simple as that there is more answers than there are questions. </p>\n\n<p>And because you are making another subselect for the column and you are selecting what you already have in the outer select, this may get expensive quite fast.</p>\n\n<p>So I would move the subquery from columns to source tables.</p>\n\n<p>Something like this (sorry, I'm not familiar with sql server syntax):</p>\n\n<pre><code>SELECT TOP(10)\n Tags.Id,\n Tags.TagName,\n COUNT(Questions.Id) AS 'numOfQuestions',\n SUM(Answers.AnswerCount) AS 'numOfAnswers',\n (SUM(Answers.AnswerCount) + 0.0) / COUNT(Questions.Id) AS 'answersPerQuestion',\n (SUM(Questions.Score) + SUM(Answers.ScoreSum) + 0.0) / (COUNT(Questions.Id) + SUM(Answers.AnswerCount)) AS 'averageScore'\nFROM Tags\nINNER JOIN PostTags\n ON PostTags.TagId = Tags.Id\nINNER JOIN Posts Questions\n ON Questions.Id = PostTags.PostId\nLEFT JOIN (\n SELECT\n Question.Id AS QuestionId,\n COUNT(Answer.Id) AS AnswerCount,\n Sum(Answer.Score) AS ScoreSum\n FROM Posts Question\n INNER JOIN Posts Answer\n ON Question.Id = Answer.ParentId\n GROUP BY Question.Id\n) AS Answers\n ON Answers.QuestionId = Questions.Id\nGROUP BY Tags.Id, Tags.TagName\nORDER BY COUNT(Questions.Id) + SUM(Answers.AnswerCount) DESC\n</code></pre>\n\n<p>Few notes: </p>\n\n<p>I'm intentionally doing left join with the subquery and then inner join in the subquery itself to limit the size of the subquery result. But this means that the outer query must handle possible nulls and replace them with zeroes, which I have not done (because idk sql server syntax), but you should know what I mean.</p>\n\n<p>There is a lot of aggregations going on, but only top 10 are selected in the end. It is possible that the above approach may still not be the most performant. In which case I would recommend to split the query into few separate queries. First extract top 10 using only what is needed for this decision. Then aggregate the other stuff on subset of all posts limited to those 10 tags.</p>\n\n<p>EDIT: I have now noticed that in your question you state:</p>\n\n<blockquote>\n <p>The query is ordered by the total number of questions</p>\n</blockquote>\n\n<p>But your query is not doing that. It orders by <code>COUNT(*)</code> which means that a question without answers is counted as <code>+1</code> and question with N (N>0) answers is counted as <code>+N</code>.</p>\n\n<p>At first I made my query sort it by number of questions and answers together. Which is yet something different. But to comply with your statement, it should be <code>ORDER BY COUNT(Questions.Id) DESC</code> only. And should have been <code>COUNT(DISTINCT Questions.Id)</code> in your original query...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:54:57.753", "Id": "468275", "Score": "0", "body": "It worked but I had to adapt 2 things: It is `Tags.TagName` instead of `Tags.Name` and I had to change the score to support decimals (because SQL Server would do an integer division instead): `(SUM(Answers.AnswerCount)+0.0) / COUNT(Questions.Id)` and `(SUM(Questions.Score) + SUM(Answers.ScoreSum)+0.0)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:57:58.877", "Id": "468276", "Score": "0", "body": "@dan1st aah, sure, thanks for the feedback. I have fixed it in my answer... Just of curiosity, what is the running time now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T15:04:13.683", "Id": "468278", "Score": "0", "body": "12,58 seconds, see https://data.stackexchange.com/stackoverflow/query/1210063/basic-info-about-tag" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T15:37:10.280", "Id": "468281", "Score": "0", "body": "@dan1st That's nice. Thanks. And btw there is a bug in the ordering. Check my edit!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T15:47:00.870", "Id": "468282", "Score": "0", "body": "Yes, I already fixed that" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:17:53.103", "Id": "238772", "ParentId": "238758", "Score": "2" } } ]
{ "AcceptedAnswerId": "238772", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T10:44:58.600", "Id": "238758", "Score": "1", "Tags": [ "performance", "sql", "time-limit-exceeded", "sql-server", "stackexchange" ], "Title": "Get average post score of TOP 10 tags on StackOverflow using Stack Exchange Data Explorer" }
238758
<p>I've completed the Reddit challenge #383.</p> <p>Please find a a summary of the challenge and the test cases below:</p> <blockquote> <p>Reddit Challenge #383 Necklace Matching</p> <h1>challenge:</h1> <p>In this challenge, we should imagine a necklace with many beads. Each bead has a letter engraved onto it. If you push the letters around the string, you can rearrange the letters.</p> <p>So 'word' can become 'ordw' or 'dwor' and continue that movement until it turns back into the original word:</p> <p>'word'</p> <p>'ordw'</p> <p>'rdwo'</p> <p>'dwor'</p> <p>'word'</p> <p>The challenge is to detect if the original word can turn into the changed word.</p> <p>For example: 'letters' can turn into 'ttersle' but can't turn into 'terstle' because the two 't' should be stringed > together.</p> <p>Here is the test cases for the challenge:</p> <p>(original, changed) => expected response</p> <p>("nicole", "icolen") => true</p> <p>("nicole", "lenico") => true</p> <p>("nicole", "coneli") => false</p> <p>("aabaaaaabaab", "aabaabaabaaa") => true</p> <p>("abc", "cba") => false</p> <p>("xxyyy", "xxxyy") => false</p> <p>("xyxxz", "xxyxz") => false</p> <p>("x", "x") => true</p> <p>("x", "xx") => false</p> <p>("x", "") => false</p> <p>("", "") => true</p> <h1>challenge 2:</h1> <p>Some words such as 'mama' can turn into the original word without looping all the way through the necklace.</p> <p>'mama'</p> <p>'amam'</p> <p>'mama'</p> <p>'amam'</p> <p>'mama'</p> <p>In this challenge, you need to count how many times the original word appears when cycling the necklace. This includes the final form of the necklace. so in 'mama', the word is seen twice while 'read' has the word only appear once.</p> <p>Here is the test cases for this challenge:</p> <p>(original) => expected response</p> <p>("abc") => 1</p> <p>("abcabcabc") => 3</p> <p>("abcabcabcx") => 1</p> <p>("aaaaaa") => 6</p> <p>("a") => 1</p> <p>("") => 1</p> <h1>challenge 3:</h1> <p>This challenge involves the enable1 word list found here:<a href="https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt" rel="nofollow noreferrer">https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt</a></p> <p>In this challenge, we need to find the words that form other words when cycled through. The results should be one set of four words. The correct result should be: ['estop', 'pesto', 'stope', 'topes']</p> </blockquote> <h1>Code explanation</h1> <p>In my code I created a class called necklace that manages a necklace. In this case, a necklace is a string with a particular order. This class is used to get the results for challenge 1 and 2. Two external functions exists that are used to solve challenge 3 which uses the necklace class to determine if they are the same necklace.</p> <p>Please find my code below:</p> <pre class="lang-py prettyprint-override"><code>''' This modules contains code that solves the Reddit exercise #383 ''' class Necklace(): ''' Necklace class Create a theoretical string necklace which you can manipulate ''' def __init__(self, word): ''' Sets up the necklace using a word. Stores the word as original. Stores all possible positions. ''' self.original = word self.cycles_list = self.get_cycle() @staticmethod def cycle_left(word): ''' move the word one letter to the left. Example: 'word' =&gt; 'ordw' ''' return word[1:]+word[0] def get_cycle(self): ''' Get every possible combination of the necklace ''' word = self.original cycles = [word] i = 0 while i &lt; len(word): word = self.cycle_left(word) cycles.append(word) i = i + 1 return cycles def is_same_necklace(self, changed_word): ''' Check if the changedWord is the same necklace but in a different position returns false if it is another combination of words ''' return changed_word in self.cycles_list def count_repeats(self): ''' Counts how many times the original position of the necklace is repeated when cycling through all possible positions of the necklace ''' count = self.cycles_list.count(self.original) if count &gt; 1: return count-1 return count def print_cycle(self): ''' Prints all the possible positions the necklace has ''' print(self.cycles_list) def get_words_from_file(file_name): ''' Reads all the words from a specific file ''' file = open(file_name, "r") return file.read().split("\n") def find_similar_words(): ''' Get all the words from the enable1.txt file and finds all words that are the same necklace Returns the first set of words that has four combination but are all the same necklace ''' all_words = get_words_from_file("enable1.txt") similar = {} words_dict = {} for word in all_words: if len(word) in words_dict: words_dict[len(word)].append(word) else: words_dict[len(word)] = [word] for key in words_dict: print('Finding all similar words with a length of '+str(key)) words = words_dict[key] for word in words: necklace = Necklace(word) index = words.index(word)+1 for word2 in words[index:]: if necklace.is_same_necklace(word2): if word in similar: similar[word].append(word2) else: similar[word] = [word2] for key in similar: if len(similar[key]) &gt;= 3: return [key]+similar[key] return None if __name__ == "__main__": #challenge 1 test cases print("Challenge 1 Test Cases Results:") NECKLACE = Necklace("nicole") print(NECKLACE.is_same_necklace("icolen")) print(NECKLACE.is_same_necklace("lenico")) print(NECKLACE.is_same_necklace("coneli")) print(Necklace("aabaaaaabaab").is_same_necklace("aabaabaabaaa")) print(Necklace("abc").is_same_necklace("cba")) print(Necklace("xxyyy").is_same_necklace("xxxyy")) print(Necklace("xyxxz").is_same_necklace("xxyxz")) print(Necklace("x").is_same_necklace("x")) print(Necklace("x").is_same_necklace("xx")) print(Necklace("x").is_same_necklace("")) print(Necklace("").is_same_necklace("")) #challenge 2 test cases print("Challenge 2 Test Cases Results:") print(Necklace("abc").count_repeats()) print(Necklace("abcabcabc").count_repeats()) print(Necklace("abcabcabcx").count_repeats()) print(Necklace("aaaaaa").count_repeats()) print(Necklace("a").count_repeats()) print(Necklace("").count_repeats()) #challenge 3 result print("Challenge 3 is starting:") result = find_similar_words() print("Challenge 3 Test Cases Results:") print(result) </code></pre> <h1>Things that could be done to improve code quality</h1> <ol> <li><p>Storing the cycles (self.cycles) Not sure if it should have been stored or retrieved when needed. I changed it to store the cycles so it could speed up challenge three however I'm not sure it makes much of a difference.</p></li> <li><p>count_repeats function I tried to use self.cycle.counts however for results with no combination, it came out as '0' instead of '1' however I don't know if there was a better way</p></li> <li><p>find_similar_words function I tried to optimise it as best as I can however it still seems really slow. A lot of redditors put restriction on the word length (>=5) however it should include a search on all words. </p></li> </ol>
[]
[ { "body": "<ul>\n<li>Your docstrings are not compliant, they should use <code>\"\"\"</code> not <code>'''</code>. You currently have discouraged unless multiline string literals.</li>\n<li>If you are inheriting from nothing <code>()</code>, then you can just remove the brackets and make your code cleaner.</li>\n<li>The <code>Necklace</code> class is largely over complicated.</li>\n<li>The <code>Necklace</code> class is even more redundant when you do <code>self.cycles_list = self.get_cycle()</code>.<br>\nThis also signals to me that the Necklace is actually performing two jobs, and not the one i would intuitively think.</li>\n<li>It's un-Pythonic to use <code>while</code> loops when you can easily use a <code>for i in range</code> loop.</li>\n<li>You can change <code>self.get_cycle()</code> to a simple list comprehension and merge <code>cycle_left</code> into it.</li>\n<li>To handle the <code>solution_1(\"\", \"\") is True</code> test case, we can default the <code>range</code> to 1 if the length is 0.</li>\n<li><code>is_same_necklace</code> is a really poor name, even more so that a simple <code>in</code> is more readable and better understood. You can allow a class to utilize this operator by defining the <code>__contains__</code> dunder method.</li>\n<li>You can simplify the logic of <code>count_repeats</code> by removing the last value.</li>\n<li>Your tests would better be described as <a href=\"https://docs.pytest.org/en/latest/\" rel=\"nofollow noreferrer\">pytest</a> tests.</li>\n</ul>\n\n<p>So far this would get:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def necklace_cycle(beads):\n return [\n beads[i:] + beads[:i]\n for i in range(len(beads) or 1)\n ]\n\n\ndef solution_1(original, changed):\n return changed in necklace_cycle(original)\n\n\ndef solution_2(original):\n return necklace_cycle(original).count(original)\n\n\ndef test_solution_1():\n for original, changed, expected in [\n (\"nicole\", \"icolen\", True),\n (\"nicole\", \"lenico\", True),\n (\"nicole\", \"coneli\", False),\n (\"aabaaaaabaab\", \"aabaabaabaaa\", True),\n (\"abc\", \"cba\", False),\n (\"xxyyy\", \"xxxyy\", False),\n (\"xyxxz\", \"xxyxz\", False),\n (\"x\", \"x\", True),\n (\"x\", \"xx\", False),\n (\"x\", \"\", False),\n (\"\", \"\", True),\n ]:\n assert solution_1(original, changed) is expected\n\n\ndef test_solution_2():\n for original, expected in [\n (\"abc\", 1),\n (\"abcabcabc\", 3),\n (\"abcabcabcx\", 1),\n (\"aaaaaa\", 6),\n (\"a\", 1),\n (\"\", 1),\n ]:\n assert solution_2(original) == expected\n</code></pre>\n\n<ul>\n<li>You should always wrap <code>open</code> in a <code>with</code>. This is so the file is closed correctly. Currently you're not closing the file, which can lead to problems.</li>\n<li>You can just use <code>file.read_lines()</code> and strip the newlines.</li>\n<li><p>You can use <code>setdefault</code> to set a dictionaries key to a list and then append to that list.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for word in all_words:\n words_dict.setdefault(len(word), []).append(word)\n</code></pre></li>\n<li><p>Personally I would move this grouping code into its own function. This will allow us to use it twice if we need to.</p></li>\n<li><p>You can use <code>for key, words in words_dict.items():</code> rather than:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>for key in words_dict:\n words = words_dict[key]\n</code></pre>\n</blockquote></li>\n<li><p>If you remove the <code>print</code> then you can use <code>for words in words_dict.values():</code> instead.</p></li>\n<li><p>You can use <code>for index, word in enumerate(words, start=1):</code> rather than:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>for word in words:\n index = words.index(word)+1\n</code></pre>\n</blockquote>\n\n<p><strong>Note</strong>: These are technically different operations if there are duplicates in <code>words</code>. However <code>enumerate</code> is the solution that you want to use.</p></li>\n<li><p>You can update the <code>similar</code> to be appended to using <code>dict.setdefault</code>.</p></li>\n<li>I would change the default to <code>[word]</code> rather than <code>[]</code>.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_words(file_name):\n with open(file_name) as f:\n return map(str.rstrip, f.readlines())\n\n\ndef grouper(values, transformation):\n output = {}\n for value in values:\n output.setdefault(transformation(value), []).append(value)\n return output\n\n\ndef find_similar_words(words):\n similar = {}\n for grouped_words in grouper(words, len).values():\n for index, word in enumerate(grouped_words, start=1):\n necklace = necklace_cycle(word)\n for word2 in grouped_words[index:]:\n if word2 in necklace:\n similar.setdefault(word, [word]).append(word2)\n return similar.values()\n\n\ndef solution_3():\n four_words = (\n words\n for words in find_similar_words(get_words(\"enable1.txt\"))\n if len(words) &gt;= 4\n )\n return next(four_words, None)\n\n\ndef test_solution_3():\n assert solution_3() == [\"estop\", \"pesto\", \"stope\", \"topes\"]\n</code></pre>\n\n<p>It's much easier to read, and also runs in 5:20 rather than 10:30. This includes the time it takes to run all tests. But since the other tests take 0.05s I'm fine with this. Now we can focus on improving performance.</p>\n\n<h1>Anagrams</h1>\n\n<p>You should group by anagrams. This is because you're currently checking if <code>four</code> and <code>cats</code> are similar. And I think them not sharing a single character in common <em>might</em> just indicate that they are not.</p>\n\n<p>To do this you can just sort the value and group by that. This makes your <span class=\"math-container\">\\$O(n^2)\\$</span> code perform better because <span class=\"math-container\">\\$n\\$</span> is now <em>much</em> smaller than it was before. This is because <span class=\"math-container\">\\$a^2 + b^2 &lt;= (a + b)^2\\$</span> when a and b are natural numbers - which is what we're working with.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def by_anagram(word):\n return tuple(sorted(word))\n\n\ndef find_similar_words(words):\n similar = {}\n for grouped_words in grouper(words, by_anagram).values():\n ...\n</code></pre>\n\n<p>This runs in 1.04s rather than 5:20.</p>\n\n<h1>Sets</h1>\n\n<p>You can further improve the performance and readability of the code by using sets. We know that the updated <code>find_similar_words</code> should return the intersection of the necklace and the grouped words. Since you are already returning duplicates this means we can just use <a href=\"https://docs.python.org/3/library/stdtypes.html#frozenset.intersection\" rel=\"nofollow noreferrer\"><code>set.intersection</code></a>. The performance increase from this is likely due to the fact that we're returning early, and so don't consume the entire of the grouper.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def find_similar_words(words):\n for words_ in grouper(words, by_anagram).values():\n words_ = set(words_)\n for word in words_:\n yield words_ &amp; set(necklace_cycle(word))\n</code></pre>\n\n<p>This runs in 0.62s rather than 1.04s.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T17:07:02.480", "Id": "468303", "Score": "0", "body": "can you explain why if the necklace class is overcomplicated and does two jobs? Isn't a class suppose to be used in multiple ways? Also the while loop was originally a for loop however pylint kicked up a fuss as the 'x' wasn't being used, do i still change it to a for loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T17:11:04.373", "Id": "468304", "Score": "1", "body": "@Meerfallthedewott No a class is meant to have one job and one job only. Yours was building and interacting, very poorly, with a 'necklace'. It was over complicated because of this. Additionally why use a class when three really dumb functions is all you need. Have you read the above code, I use a for loop, and pylint won't complain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T17:14:08.550", "Id": "468305", "Score": "0", "body": "I've read your code a bit deeply now, it makes a lot of sense." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:53:51.767", "Id": "238782", "ParentId": "238761", "Score": "2" } } ]
{ "AcceptedAnswerId": "238782", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T12:04:18.123", "Id": "238761", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "reddit" ], "Title": "Reddit Challenge #383 Python" }
238761
<p><a href="https://leetcode.com/problems/network-delay-time/" rel="nofollow noreferrer">https://leetcode.com/problems/network-delay-time/</a></p> <blockquote> <p>There are N network nodes, labelled 1 to N.</p> <p>Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.</p> <p>Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.</p> </blockquote> <pre><code>Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2 Output: 2 </code></pre> <p><a href="https://i.stack.imgur.com/9ylAr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ylAr.png" alt="enter image description here"></a></p> <p>Please review for performance and C# style. I already implemented this as DFS. <a href="https://codereview.stackexchange.com/questions/238685/leetcode-network-delay-time-dfs-solution-c">LeetCode: Network Delay Time DFS solution C#</a></p> <pre><code> namespace GraphsQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/network-delay-time/ /// &lt;/summary&gt; [TestClass] public class NetworkDelayTimeTest { [TestMethod] public void ExampleTest() { int N = 4; int K = 2; int[][] times = { new[] { 2, 1, 1 }, new[] { 2, 3, 1 }, new[] { 3, 4, 1 } }; NetworkDelayTimeDijkstra dijkstra = new NetworkDelayTimeDijkstra(); Assert.AreEqual(2, dijkstra.NetworkDelayTime(times, N, K)); } } public class NetworkDelayTimeDijkstra { private Dictionary&lt;int, int&gt; _dist; public int NetworkDelayTime(int[][] times, int N, int K) { var graph = new Dictionary&lt;int, List&lt;List&lt;int&gt;&gt;&gt;(); //we build a dictionary // key = from vertex // values - destination and wight - NOT LIKE DFS foreach (var edge in times) { if (!graph.TryGetValue(edge[0], out var temp)) { temp = graph[edge[0]] = new List&lt;List&lt;int&gt;&gt;(); } temp.Add(new List&lt;int&gt; { edge[1], edge[2] }); } // all the edges get max value _dist = new Dictionary&lt;int, int&gt;(); for (int i = 1; i &lt;= N; ++i) { _dist.Add(i, int.MaxValue); } // we set the origin _dist[K] = 0; bool[] visited = new bool[N + 1]; while (true) { int candNode = -1; int candDist = int.MaxValue; // find a vertex which is not visited // and has the lowest distance from all unvisited vertices for (int i = 1; i &lt;= N; ++i) { if (!visited[i] &amp;&amp; _dist[i] &lt; candDist) { candDist = _dist[i]; candNode = i; } } // if canNode == -1 there are no more unvisited nodes if (candNode &lt; 0) { break; } //mark the node as visited and Update the distance to all of the neighbors visited[candNode] = true; if (graph.ContainsKey(candNode)) { foreach (var info in graph[candNode]) { _dist[info[0]] = Math.Min(_dist[info[0]], _dist[candNode]+info[1]); } } } // we compute the max distance. // if one of the edges equals int.max // we can't reach it so we return -1; int ans = 0; foreach (var cand in _dist.Values) { if (cand == int.MaxValue) { return -1; } ans = Math.Max(ans, cand); } return ans; } } } </code></pre>
[]
[ { "body": "<p>Instead of the list-list value in</p>\n\n<blockquote>\n <p><code>var graph = new Dictionary&lt;int, List&lt;List&lt;int&gt;&gt;&gt;();</code></p>\n</blockquote>\n\n<p>you could use a named tuple:</p>\n\n<pre><code>var graph = new Dictionary&lt;int, List&lt;(int V, int W)&gt;&gt;();\n\nforeach (var edge in times)\n{\n if (!graph.TryGetValue(edge[0], out var temp))\n {\n temp = graph[edge[0]] = new List&lt;(int V, int W)&gt;();\n }\n\n temp.Add((edge[1], edge[2]));\n}\n</code></pre>\n\n<p>which will make it more clear what the elements in the graph represent.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // find a vertex which is not visited\n // and has the lowest distance from all unvisited vertices\n for (int i = 1; i &lt;= N; ++i)\n {\n if (!visited[i] &amp;&amp; _dist[i] &lt; candDist)\n {\n candDist = _dist[i];\n candNode = i;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>I think the above will be a bottleneck for larger graphs, because you repeatedly check all distances even if the node has been visited. A priority queue would probably be a better choice. </p>\n\n<hr>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code> int ans = 0;\n foreach (var cand in _dist.Values)\n {\n if (cand == int.MaxValue)\n {\n return -1;\n }\n ans = Math.Max(ans, cand);\n }\n return ans;\n</code></pre>\n</blockquote>\n\n<p>can be simplified to:</p>\n\n<pre><code> int ans = _dist.Values.Max();\n return ans == int.MaxValue ? -1 : ans;\n</code></pre>\n\n<p>But it may not be a performance improvement because of your early return if you find a <code>int.MaxValue</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T17:11:42.503", "Id": "468493", "Score": "0", "body": "i really appreciate the review thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T20:22:14.090", "Id": "238792", "ParentId": "238762", "Score": "3" } } ]
{ "AcceptedAnswerId": "238792", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T12:32:32.733", "Id": "238762", "Score": "2", "Tags": [ "c#", "programming-challenge", "dijkstra" ], "Title": "LeetCode: Network Delay Time Dijkstra's Algorithm C#" }
238762
<p>I'm trying to create pages for multiple content types in Gatsby and I was wondering if this is the right approach:</p> <p>My gatsby-node.js file:</p> <pre class="lang-js prettyprint-override"><code>const path = require(`path`) const { createFilePath } = require("gatsby-source-filesystem") exports.onCreateNode = ({ node, actions, getNode }) =&gt; { const { createNodeField } = actions // Is this OK? if ( node.internal.type === "Mdx" &amp;&amp; node.fileAbsolutePath.includes(`content/posts`) ) { const value = createFilePath({ node, getNode }) createNodeField({ name: "slug", node, value: `/blog${value}`, }) } if ( node.internal.type === "Mdx" &amp;&amp; node.fileAbsolutePath.includes(`content/projects`) ) { const value = createFilePath({ node, getNode }) createNodeField({ name: "slug", node, value: `/project${value}`, }) } } exports.createPages = async ({ graphql, actions, reporter }) =&gt; { const { createPage } = actions const blogPostTemplate = path.resolve(`./src/templates/template-blog-post.js`) const projectEntryTemplate = path.resolve( `./src/templates/template-project-entry.js` ) const result = await graphql(` query { posts: allMdx( sort: { order: DESC, fields: [frontmatter___date, fields___slug] } limit: 10000 filter: { fileAbsolutePath: { regex: "/content/posts/" } } ) { edges { node { id fields { slug } frontmatter { title } } } } projects: allMdx( sort: { order: DESC, fields: [frontmatter___date, fields___slug] } limit: 1000 filter: { fileAbsolutePath: { regex: "/content/projects/" } } ) { edges { node { id fields { slug } frontmatter { title } } } } } `) if (result.errors) { reporter.panicOnBuild( ' ERROR: Loading "createPages" query.' ) } const posts = result.data.posts.edges const projects = result.data.projects.edges posts.forEach(({ node }) =&gt; { createPage({ path: node.fields.slug, component: blogPostTemplate, context: { id: node.id }, }) }) projects.forEach(({ node }) =&gt; { createPage({ path: node.fields.slug, component: projectEntryTemplate, context: { id: node.id }, }) }) } </code></pre> <p>My (redacted) gatsby-config.js file:</p> <pre class="lang-js prettyprint-override"><code>module.exports = { plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `posts`, path: `${__dirname}/content/posts/`, }, }, { resolve: "gatsby-source-filesystem", options: { name: `projects`, path: `${__dirname}/content/projects/`, }, }, ], } </code></pre> <p>Although this works fine and I'm not getting any errors, I'm not sure using two if-statements in gatsby-node.js is the right approach to generating pages for multiple content types. I've searched online and I have not yet found a guide or 'best-practices' when it comes to handling multiple content types with GatsbyJS. Please share if you have!</p> <p>Could you guys help me out? Am I on the right track or is there improvement to be found?</p> <p>Cheers!</p>
[]
[ { "body": "<p>There's definitely a lot of duplicate code in those 2 <code>if</code>s. I'd extract it into function and pass different things as parameters.</p>\n\n<p>Then code would look let's say:</p>\n\n<pre><code>//not sure about name of function and parameters\nfunction nodeFieldPerType(filePath, getNodePath) {\n if (\n node.internal.type === \"Mdx\" &amp;&amp;\n node.fileAbsolutePath.includes(filePath)\n ) {\n const value = createFilePath({ node, getNode })\n createNodeField({\n name: \"slug\",\n node,\n value: getNodePath(value),\n })\n }\n}\n</code></pre>\n\n<p>Then you call it like like:</p>\n\n<pre><code>nodeFieldPerType(`content/posts`, value =&gt; `/blog${value}`);\nnodeFieldPerType(`content/projects`, value =&gt; `/project${value}`);\n</code></pre>\n\n<p>This cleans it up a bit. If you keep adding more possible branches, you may need to add more parameters. You can go further to make this as a static configuration and put this into configuration structure, that you fill in advance. Then in your code you just pick the one you need and call it.\nEx: </p>\n\n<pre><code>config = {\n`content/posts`: { getNodePath: value =&gt; `/blog${value}` }, //object on purpose so that you can add more parameters later\n`content/projects`: { getNodePath: value =&gt; `/project${value}` },\n}\n</code></pre>\n\n<p>And then instead of your <code>if</code>s you check if filePath exists in this config and if it does, you call function with parameters in config.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:16:46.593", "Id": "468271", "Score": "0", "body": "This is great, thank you so much! I reduced the two if-statements with the code you provided and this helped me a lot and gave me more insight into refactoring! Thanks! :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T13:32:54.360", "Id": "238766", "ParentId": "238765", "Score": "6" } }, { "body": "<p>I know this is a couple weeks old, and you already have a good solution. I just wanted to point out a method that is a bit more deterministic/declarative.</p>\n\n<p>You are already using multiple instances of <code>gatsby-source-filesystem</code>, and they each have their own <code>name</code> property. That becomes <code>sourceInstanceName</code> on the <code>File</code> nodes. You can use that value to simplify your code, while also making it more flexible and efficient.</p>\n\n<p>For example</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const path = require(`path`)\n\nconst { createFilePath } = require(\"gatsby-source-filesystem\")\nexports.onCreateNode = ({ node, actions, getNode }) =&gt; {\n const { createNodeField } = actions\n if (node.internal.type === \"Mdx\") {\n const value = createFilePath({ node, getNode })\n const file = getNode(node.parent)\n createNodeField({\n name: \"slug\",\n node,\n value: `/${file.sourceInstanceName}${value}`,\n })\n createNodeField({\n name: \"instance\",\n node,\n value: file.sourceInstanceName,\n })\n }\n}\n</code></pre>\n\n<p>Now, you can create a more abstract page creation process, which as a bonus is less queries, and less arrays to process:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>exports.createPages = async ({ graphql, actions, reporter }) =&gt; {\n const { createPage } = actions\n\n const result = await graphql(`\n query {\n allMdx(\n sort: { order: DESC, fields: [frontmatter___date, fields___slug] }\n limit: 10000\n ) {\n edges {\n node {\n id\n fields {\n slug\n instance\n }\n frontmatter {\n title\n }\n }\n }\n }\n `)\n if (result.errors) {\n reporter.panicOnBuild(\n ' ERROR: Loading \"createPages\" query.'\n )\n }\n\n const posts = result.data.allMdx.edges\n const templates = {}\n posts.forEach(({ node }) =&gt; {\n const instance= node.fields.instance\n if (!templates[instance]) {\n templates[instance] = require.resolve(`./src/templates/${instance}`)\n }\n createPage({\n path: node.fields.slug,\n component: templates[instance],\n context: {\n id: node.id,\n instance,\n },\n })\n })\n}\n</code></pre>\n\n<p>All you have to do is make sure your template names match your <code>sourceInstanceName</code> properties, and that your <code>sourceInstanceName</code> properties match what you want your routes to be. You can also use the instance that each node belongs to in your page queries.</p>\n\n<p>Notice that I use <code>require.resolve()</code> for the templates, too. That will resolve it to the correct extension, but it will also fail early if the template doesn't exist. Might make troubleshooting easier down the road.</p>\n\n<hr>\n\n<p>This is more deterministic because you don't have to do any <code>fileAbsolutePath</code> matching, which can be unstable if your route schemes grow. Instead, you can match the <code>$instance</code> GraphQL variable against the <code>fields.instance</code> property in your page query filters.</p>\n\n<p>It's more declarative because all I have to do is declare another <code>gatsby-source-filesystem</code> instance, then build the template and the content if I want to add a new group.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-30T14:50:26.833", "Id": "470123", "Score": "0", "body": "Hi Jeremy, thank you so much! I like your approach, and it inspired me to rewrite my createPages using parts of your code. I'm writing an answer with how I approached it and the changes I've made so far. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-15T08:03:02.740", "Id": "478776", "Score": "0", "body": "Exactly what the Gatsby docs were missing. Thanks for this pattern, Jeremy. I've linked to it from a related [documentation issue](https://github.com/gatsbyjs/gatsby/issues/24978) I opened against Gatsby here in mid-2020 after struggling for hours to get a simple set of blog posts added to a site I'm working on." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-27T23:46:10.433", "Id": "239532", "ParentId": "238765", "Score": "5" } }, { "body": "<p>Thank you so much for the input! It gave me great insight into solving this problem.</p>\n\n<p>Thanks <a href=\"https://codereview.stackexchange.com/users/220915/jeremy-albright\">@Jeremy Albright</a> for your insight and advice. It inspired me to rewrite my node.js file.</p>\n\n<p>My setup so far:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>\n// gatsby-node.js\n\nexports.createPages = require(\"./gatsby/node/createPages\")\nexports.onCreateNode = require(\"./gatsby/node/onCreateNode\")\n\n</code></pre>\n\n<p>I'm still learning react I find it helpful to split up the code into groups, to get a better understanding of the process and how they function; I split up my gatsby-node.js file into a dedicated folder.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>\n// creatPages.js\n\nconst path = require(`path`)\nconst query = require(\"../data/data-query\")\n\nmodule.exports = async ({ graphql, reporter, actions }) =&gt; {\n const { createPage } = actions\n\n const templatesDirectory = path.resolve(__dirname, \"../../src/templates/\")\n\n const templates = {\n blog: path.resolve(templatesDirectory, \"template-blog-post.js\"),\n projects: path.resolve(templatesDirectory, \"template-project-entry.js\"),\n }\n\n const result = await graphql(query.local.content)\n\n if (result.errors) {\n reporter.panicOnBuild(\n ' ERROR: Loading \"createPages\" query.'\n )\n }\n\n const mdxContent = result.data.allMdx.edges\n\n mdxContent.forEach(({ node }) =&gt; {\n const instance = node.fields.instance\n createPage({\n path: node.fields.slug,\n component: templates[instance],\n context: {\n id: node.id,\n instance,\n },\n })\n })\n}\n</code></pre>\n\n<p>I like the approach of letting gatsby-source-filesystem define the templates and content types. What I don't like is the strict naming. I would need to name the template files to something that also works well within the URL structure. Here is where I hit a snag.</p>\n\n<p>I want the name of the file to say something about it. Naming a blog template file just \"blog\" seems a bit vague. The approach I came up with requires a little more work, but it gave me the chance to name my templates how I want to and use my 'weird' naming scheme.</p>\n\n<p>I used <code>templatesDirectory</code> to get the template path and <code>templates</code> to get the instance and combine the actual template name to the instance name</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>\n// onCreateNode.js\n\nconst { createFilePath } = require(\"gatsby-source-filesystem\")\nmodule.exports = ({ node, actions, getNode }) =&gt; {\n const { createNodeField } = actions\n\n if (node.internal.type === \"Mdx\") {\n const value = createFilePath({ node, getNode })\n const file = getNode(node.parent)\n createNodeField({\n name: \"slug\",\n node,\n value: `/${file.sourceInstanceName}${value}`,\n })\n createNodeField({\n name: \"instance\",\n node,\n value: file.sourceInstanceName,\n })\n }\n}\n\n\n</code></pre>\n\n<p>My onCreateNode.js file is copy-paste from Jeremy.</p>\n\n<hr>\n\n<p>What is your opinion on this approach? I'm struggling with finding 'best practices' and documentation for working with multiple content types. So many people approach this entirely differently.</p>\n\n<p>I would like to know what you guys think about this!</p>\n\n<p>Cheers!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-30T15:27:26.370", "Id": "239664", "ParentId": "238765", "Score": "1" } } ]
{ "AcceptedAnswerId": "238766", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T13:10:51.120", "Id": "238765", "Score": "3", "Tags": [ "javascript", "node.js", "react.js" ], "Title": "Is this a good approach for creating pages for multiple content typs with GatsbyJS?" }
238765
<p>So for a class project, I have to figure out the most efficient way to draw on a canvas.</p> <p>First thing that came to mind was using moveTo and lineTo repeatedly following mouse cursor, and thats exactly what I did.</p> <p>I also added a strange "liner" pen which draws lines outwards from a point (side effect of bug, which I then turned into a tool)</p> <p>Furthermore I added a coloring and sizing option, so you can be creative with it.</p> <p>Sizing option, Spray tool, and Color Options are all non-functional rn.</p> <p>I'm not really sure how to get the color or sizing option working if anyone wants to take a crack at it.</p> <p><strong>I want to know if anyone sees any bad practice uses that I have created, or has any improvements/tips that I should keep in mind as I continue development on the canvas.</strong></p> <p><strong>Also the GUI and Buttons and everything, its all temporary, my main job is to actually finish the project.</strong></p> <p><a href="https://repl.it/@skylerspark/Dynamic-Drawing-Utility-DDU" rel="nofollow noreferrer">https://repl.it/@skylerspark/Dynamic-Drawing-Utility-DDU</a></p> <p>Heres the live development version, and heres the current version as of posting this code review:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const query = document.querySelector.bind(document); // Config let curLine = [0, 0], curColor = "#000000", curSize = 2; // Cursor Coords function drawingBoardGetMouse(cvs, e) { let rect = cvs.getBoundingClientRect(), scaleX = cvs.width / rect.width, scaleY = cvs.height / rect.height; return { x: (e.clientX - rect.left) * scaleX, y: (e.clientY - rect.top) * scaleY }; } // Dynamic Drawing Utility (DDU) class drawingBoard { constructor(canvas) { // Generate a dynamic canvas selector, or manually select it yourself via the main args this.cvs = canvas || document.querySelector("canvas"); this.ctx = this.cvs.getContext("2d"); this.cvs.addEventListener("mousedown", e =&gt; { let m = drawingBoardGetMouse(this.cvs, e); curLine = [m.x, m.y]; this.mouseDown = true; }); this.cvs.addEventListener("mouseup", e =&gt; { this.mouseDown = false; }); this.cvs.addEventListener("mousemove", this.onMouseMove.bind(this)); } draw(e) { // Free Draw Pen let m = drawingBoardGetMouse(this.cvs, e); this.ctx.beginPath(); this.ctx.fillStyle = curColor; this.ctx.lineWidth = curSize; this.ctx.moveTo(curLine[0], curLine[1]); this.ctx.lineTo(m.x, m.y); this.ctx.stroke(); curLine = [m.x, m.y]; } draw2(e) { // Line Draw Pen let m = drawingBoardGetMouse(this.cvs, e); this.ctx.beginPath(); this.ctx.fillStyle = curColor; this.ctx.lineWidth = curSize; this.ctx.moveTo(curLine[0], curLine[1]); this.ctx.lineTo(m.x, m.y); this.ctx.stroke(); } onMouseMove(event) { // Detect movement if (!this.mouseDown) { return; // If mouse isnt held down, dont draw } if (this.drawingMode == 1) { return this.draw(event); // Free-draw } else if (this.drawingMode == 2) { return this.draw2(event); // Line-draw } else if (this.drawingMode == 3) { return this.draw3(event); // Spray-draw } } dragAndDraw() { this.drawingMode = 1; } dragAndLine() { this.drawingMode = 2; } dragAndSpray() { this.drawingMode = 3; } } // API Usage const draw = new drawingBoard(); // Initialize new board query(".color").addEventListener("input", e =&gt; { curColor = e.target.value; }); query(".drawer").addEventListener("click", () =&gt; { draw.dragAndDraw(); }); query(".liner").addEventListener("click", () =&gt; { draw.dragAndLine(); }); query(".sprayer").addEventListener("click", () =&gt; { draw.dragAndSpray(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { text-align: center; vertical-align: top; box-sizing: border-box; } .canvas { display: inline-block; border: 1px solid black; } .buttons { display: inline-block; } button, input { width: 8em; margin-bottom: 2px; margin-left: -2px; } input { text-align: left; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas class="canvas" width="300" height="300"&gt;&lt;/canvas&gt; &lt;div class="buttons"&gt; &lt;input type="color" class="color"&gt;&lt;br&gt; &lt;input type="text" class="size" placeholder="Size"&gt;&lt;br&gt; &lt;button class="drawer"&gt;Free Draw&lt;/button&gt;&lt;br&gt; &lt;button class="liner"&gt;Line Draw&lt;/button&gt;&lt;br&gt; &lt;button class="sprayer"&gt;Spray Draw&lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>First, draw and draw2 looks pretty similar to me, you can DRY them</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class drawingBoard {\n\n // ...\n\n draw (e) {\n this.draw2(e)\n let m = drawingBoardGetMouse(this.cvs, e)\n curLine = [m.x, m.y]\n }\n draw2 (e) {\n let m = drawingBoardGetMouse(this.cvs, e)\n this.ctx.beginPath()\n this.ctx.fillStyle = curColor\n this.ctx.lineWidth = curSize\n this.ctx.moveTo(curLine[0], curLine[1])\n this.ctx.lineTo(m.x, m.y)\n this.ctx.stroke()\n }\n\n // ...\n\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Then, there is a \"not so useful\" if statement</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>if (this.drawingMode == 1) {\n return this.draw(event) // Free-draw\n} else if (this.drawingMode == 2) {\n return this.draw2(event) // Line-draw\n} else if (this.drawingMode == 3) {\n return this.draw3(event) // Spray-draw\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Here is how you can replace it, which will improve the readability and elegance of the code</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// ...\n\nclass drawingBoard {\n\n // ...\n\n onMouseMove (event) {\n if (!this.mouseDown) {\n return // If mouse isnt held down, dont draw\n }\n if (this.drawingMode in this) {\n this[this.drawingMode](event)\n }\n }\n\n dragAndDraw (e) {\n this.dragAndLine(e)\n let m = drawingBoardGetMouse(this.cvs, e)\n curLine = [m.x, m.y]\n }\n\n dragAndLine (e) {\n let m = drawingBoardGetMouse(this.cvs, e)\n this.ctx.beginPath()\n this.ctx.fillStyle = curColor\n this.ctx.lineWidth = curSize\n this.ctx.moveTo(curLine[0], curLine[1])\n this.ctx.lineTo(m.x, m.y)\n this.ctx.stroke()\n }\n\n dragAndSpray () {\n // TODO ?\n }\n}\n\n\n// ...\n\n\nquery('.drawer').addEventListener('click', () =&gt; {\n draw.drawingMode = 'dragAndDraw'\n})\n\nquery('.liner').addEventListener('click', () =&gt; {\n draw.drawingMode = 'dragAndLine'\n})\n\nquery('.sprayer').addEventListener('click', () =&gt; {\n draw.drawingMode = 'dragAndSpray'\n})</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You can move the global variables into instance variables so you can create multiple instances of drawingBoard if you want</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class drawingBoard {\n\n constructor (canvas) {\n\n // ...\n\n this.curLine = [0, 0]\n this.curColor = '#000000'\n this.curSize = 2\n\n\n this.cvs.addEventListener('mousedown', e =&gt; {\n let m = drawingBoardGetMouse(this.cvs, e)\n this.curLine = [m.x, m.y]\n this.mouseDown = true\n })\n\n // ...\n \n }\n\n dragAndDraw (e) {\n this.dragAndLine(e)\n this.curLine = [m.x, m.y]\n }\n \n dragAndLine (e) {\n // ...\n\n this.ctx.fillStyle = this.curColor\n this.ctx.lineWidth = this.curSize\n this.ctx.moveTo(this.curLine[0], this.curLine[1])\n\n // ...\n }\n \n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>Here is my final take with some flavor adjustments</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class DrawingBoard {\n\n constructor (canvas) {\n\n this.canvas = canvas || document.querySelector('canvas')\n this.ctx = this.canvas.getContext('2d')\n\n this.currentLine = {x: 0, y: 0}\n this.color = '#000000'\n this.size = 2\n\n registerMouseEvents(this)\n }\n\n draw (mouseEvent) {\n if (!this.mouseDown) {\n return\n }\n\n if (this.drawingMode in this) {\n this[this.drawingMode](mouseEvent)\n }\n }\n\n dragAndDraw (e) {\n this.dragAndLine(e)\n this.currentLine = getMouseCoords(this.canvas, e)\n }\n\n dragAndLine (e) {\n let coords = getMouseCoords(this.canvas, e)\n this.ctx.beginPath()\n this.ctx.fillStyle = this.color\n this.ctx.lineWidth = this.size\n this.ctx.moveTo(this.currentLine.x, this.currentLine.y)\n this.ctx.lineTo(coords.x, coords.y)\n this.ctx.stroke()\n }\n\n dragAndSpray () {\n // TODO ?\n }\n}\n\n\n\nfunction registerMouseEvents (drawingBoard) {\n\n const canvas = drawingBoard.canvas\n\n canvas.addEventListener('mousedown', e =&gt; {\n drawingBoard.currentLine = getMouseCoords(canvas, e)\n drawingBoard.mouseDown = true\n })\n\n canvas.addEventListener('mouseup', e =&gt; {\n drawingBoard.mouseDown = false\n })\n\n canvas.addEventListener('mousemove', e =&gt; {\n drawingBoard.draw(e)\n })\n\n}\n\n\n\nfunction getMouseCoords (canvas, e) {\n\n let rect = canvas.getBoundingClientRect()\n let scaleX = canvas.width / rect.width\n let scaleY = canvas.height / rect.height\n\n return {\n x: (e.clientX - rect.left) * scaleX,\n y: (e.clientY - rect.top) * scaleY\n }\n\n}\n\n\n\n// USAGE\n\nconst query = document.querySelector.bind(document)\nconst drawingBoard = new DrawingBoard()\n\n\nquery('.color').addEventListener('input', e =&gt; {\n drawingBoard.color = e.target.value\n})\n\nquery('.drawer').addEventListener('click', () =&gt; {\n drawingBoard.drawingMode = 'dragAndDraw'\n})\n\nquery('.liner').addEventListener('click', () =&gt; {\n drawingBoard.drawingMode = 'dragAndLine'\n})\n\nquery('.sprayer').addEventListener('click', () =&gt; {\n drawingBoard.drawingMode = 'dragAndSpray'\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n text-align: center;\n vertical-align: top;\n box-sizing: border-box;\n}\n\n.canvas {\n display: inline-block;\n border: 1px solid black;\n}\n\n.buttons {\n display: inline-block;\n}\n\nbutton,\ninput {\n width: 8em;\n margin-bottom: 2px;\n margin-left: -2px;\n}\n\ninput {\n text-align: left;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas class=\"canvas\" width=\"300\" height=\"300\"&gt;&lt;/canvas&gt;\n&lt;div class=\"buttons\"&gt;\n &lt;input type=\"color\" class=\"color\"&gt;&lt;br&gt;\n &lt;input type=\"text\" class=\"size\" placeholder=\"Size\"&gt;&lt;br&gt;\n &lt;button class=\"drawer\"&gt;Free Draw&lt;/button&gt;&lt;br&gt;\n &lt;button class=\"liner\"&gt;Line Draw&lt;/button&gt;&lt;br&gt;\n &lt;button class=\"sprayer\"&gt;Spray Draw&lt;/button&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": "2020-03-16T00:51:20.320", "Id": "468629", "Score": "0", "body": "Thankyou! This is very informing, I didnt realise some of these issues up front, thanks a ton!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T14:59:57.257", "Id": "238946", "ParentId": "238768", "Score": "2" } } ]
{ "AcceptedAnswerId": "238946", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:03:07.410", "Id": "238768", "Score": "2", "Tags": [ "javascript", "performance", "html", "css" ], "Title": "Reviewing a Canvas Drawing Utility in plain Javascript" }
238768
<p>I wrote this function to fill a list with object based on the desired index they should have.</p> <p>Here the func:</p> <pre><code>def fill(lst, index, add, fillvalue=None): '''Fills a list with the add value based on desired index''' '''Let the value in place if present''' for n in range(index): try: if lst[n]: pass except Exception: lst.append(fillvalue) try: if lst[index]: pass else: lst[index]=add except Exception: if index==len(lst): #This if check probably not mandatory lst.append(add) return lst </code></pre> <p>edit: here's an usage example that would for example happen in a for loop</p> <pre><code>&gt;&gt;&gt; my_list = [1, 7, 14] &gt;&gt;&gt; fill(my_list, 5, 6) [1, 7, 14, None, None, 6] &gt;&gt;&gt; fill(my_list, 6, 12) [1, 7, 14, None, None, 6, 12] &gt;&gt;&gt; fill(my_list, 3, 25) [1, 7, 14, 25, None, 6, 12] &gt;&gt;&gt; fill(my_list, 4, 18) [1, 7, 14, 25, 18, 6, 12] </code></pre> <p>Note:</p> <pre><code>&gt;&gt;&gt; my_list = [1, 7, 14] &gt;&gt;&gt; fill(my_list, 1, 6) #returns the list not modified, my_list[1] is already taken [1, 7, 14] </code></pre> <p>It works good for my purpose (matrix generating). My matrixes are generated with many "for loops" passes, because the data I convert to is unordered. This is why the "None" elements are important in order to fill them out on a subsequent loop pass.</p> <p>My questions are:</p> <ul> <li><p>I'm wondering if I made everything as simple as possible? Or if there were a lib, that would do the same job?</p></li> <li><p>For now the matrixes aren't so long but I guess, if I go further in my development, they will become big (1000+ lines). Should I somehow better use itertools?</p></li> <li><p>I also somehow thought of first using a dict {index: value} and convert it to a list when filled up. Would it be better practice?</p></li> </ul> <p>Edit: Now that I pasted the code in here I notice the arg name "add" is blued. My Vim-editor didn't told me that... Is it a name already taken by the python core?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:43:35.900", "Id": "468274", "Score": "0", "body": "Hey, welcome to Code Review! Can you add a usage example? it is not quite clear to me how to use your function properly and what exactly it should do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T15:01:45.827", "Id": "468277", "Score": "0", "body": "@Graipher Thank you ! I edited the question with an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:03:43.287", "Id": "468412", "Score": "0", "body": "Using `except Exception:` like that is a bad idea, see https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except." } ]
[ { "body": "<ul>\n<li><p><code>if lst[n]</code> is not sufficient to determine if the value at index <code>n</code> is <code>None</code>, <code>0</code> will also not pass the test. Use <code>if lst[n] is not None</code> or <code>if lst[n] is None</code>, depending on which one you want.</p></li>\n<li><p>The whole first loop is just trying to determine if you need to extend the list, but you could just do that:</p>\n\n<pre><code>lst.extend([fill_value] * (index - len(lst) + 1))\n</code></pre>\n\n<p>If the list is already long enough this does nothing, as a list multiplied by an integer smaller than one is the empty list, and extending with an empty list does nothing. It even works when you use negative indices.</p></li>\n<li><p>This also guarantees that the index exists, so you don't need the <code>try..except</code> anymore. But if you use <code>try</code> and <code>except</code>, always try to catch the narrowest exception possible. This way you make sure you don't catch an unexpected exception. In this case it would be an <code>IndexError</code> instead of the more generic <code>Exception</code>.</p></li>\n<li><p>The convention in Python is for functions to only do one of two things: either do not mutate the inputs and return a new output or mutate (some of) the input and return <code>None</code> (potentially implicitly). Your function falls into the second category.</p></li>\n</ul>\n\n<p>With these changes your function could be a lot shorter:</p>\n\n<pre><code>def fill(lst, index, value, fill_value=None):\n \"\"\"Place the `value` at index `index`,\n but only if the value already there is `None`.\n Extends the list with `fill_value`, if necessary.\n \"\"\"\n # No-op if list long enough or index negative\n lst.extend([fill_value] * (index - len(lst) + 1))\n if lst[index] is None:\n lst[index] = value\n\nmy_list = [1, 7, 14]\n# my_list = [1, 7, 14]\nfill(my_list, 5, 6)\n# my_list = [1, 7, 14, None, None, 6]\nfill(my_list, 6, 12)\n# my_list = [1, 7, 14, None, None, 6, 12]\nfill(my_list, 3, 25)\n# my_list = [1, 7, 14, 25, None, 6, 12]\nfill(my_list, 4, 18)\n# my_list = [1, 7, 14, 25, 18, 6, 12]\n</code></pre>\n\n<p>Note that you will not directly see the result anymore in an interactive session, since the list is no longer returned. But that's a feature, not a bug, as mentioned above.</p>\n\n<p>Of course, if you need to do this multiple times directly after each other, you might want to define a function that needs to extend only once:</p>\n\n<pre><code>def fill_multiple(lst, indices, values, fill_value=None):\n lst.extend([fill_value] * (max(indices) - len(lst) + 1))\n for index, value in zip(indices, values):\n if lst[index] is None:\n lst[index] = value\n</code></pre>\n\n<p>Then you can use e.g a dictionary:</p>\n\n<pre><code>my_list = [1, 7, 14]\nupdates = {5: 6, 6: 12, 3: 25, 4: 18}\nfill_multiple(my_list, updates.keys(), updates.values())\n# my_list = [1, 7, 14, 25, 18, 6, 12]\n</code></pre>\n\n<p>I kept the indices and values separate so you can also just pass lists or anything else, not just a mapping. Depending on your usecase you might want to pass the dictionary to the function instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:29:40.910", "Id": "468286", "Score": "0", "body": "Thanks a lot for your complete answer. I like the way advanced coders are able to divide by 4 the line amount of some amateur code. Side question: from where comes this convention on functions? Or where could I read more about those conventions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T07:00:48.840", "Id": "468328", "Score": "0", "body": "@Halavus It's actually surprisingly hard to find an authorative source for this, it is just conventional wisdom that it should be this way :). Even the [canonical StackOverflow question](https://stackoverflow.com/questions/26027694/correct-style-for-python-functions-that-mutate-the-argument) about this has no sources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T12:34:39.980", "Id": "468349", "Score": "1", "body": "@Halavus \"[You might have noticed that methods like `insert`, `remove` or `sort` that only modify the list have no return value printed – they return the default `None`. 1 This is a design principle for all mutable data structures in Python.](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)\" - Python docs. It doesn't really explain why tho." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T15:44:20.270", "Id": "238774", "ParentId": "238769", "Score": "6" } } ]
{ "AcceptedAnswerId": "238774", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:11:14.680", "Id": "238769", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Python function to fill a list based on index number" }
238769
<p><strong>Terminology:</strong></p> <p>Host - Spectator and summoner of players involved in the 1v1 matches</p> <p>Player - A player who is participating in the 1v1 matches</p> <p>Phantom - A player summoned for a 1v1 (present in the host's game)</p> <p>Summon - Bringing a player into the host's game (where the host can spectate the match)</p> <p><strong>Concept:</strong></p> <p>The goal of this program is to allow a host to summon players in a fair order. Starting off there will be zero players in the summon queue. Each time a player is summoned the host will type their name into the program which will do either:</p> <ol> <li>Detect this player has not been summoned before and add their name to the bottom of the queue</li> <li><p>Detect this player has been summoned before:</p> <p>a. Player was summoned in the expected order - cycle the queue as normal</p> <p>b. Player 'jumped' the queue - move player to bottom of the queue then cycle</p></li> </ol> <p><strong>Note:</strong></p> <p>I know there are unused functions - I plan on using them in the future. I am posting this code for your review at it's earliest stage, so that I can rectify problems and not continue to use bad programming practices.</p> <p>In the future I would like to add priority ordering for players who have joined the play session later using the <code>PLAYER-&gt;Fights</code></p> <p>The game is Dark Souls by the way.</p> <p><strong>Code:</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define MAX_NAME_LENGTH 32 typedef unsigned int bool; typedef struct DLINKED_LIST { struct _DLINKED_LIST *pPrev; struct _DLINKED_LIST *pNext; } DLINKED_LIST; typedef struct PLAYER { DLINKED_LIST Header; char *Player; unsigned int *Fights; unsigned int *Wins; unsigned int *Losses; } PLAYER; // Pointer to the player who was summoned last struct PLAYER* Last; // Function Declarations void* forEachElement(PLAYER* Start, void (*func)(struct PLAYER*)); char* handleInput(); struct PLAYER* lookupPlayer(char* player); void printSummonOrder(struct PLAYER* pCurrent); void printElementContent(struct PLAYER* pCurrent); struct PLAYER* createPlayer(char* player); bool insertElementBefore(struct PLAYER* pCurrent, struct PLAYER* pNew); bool insertElementAfter(struct PLAYER* pCurrent, struct PLAYER* pNew); // Could be implemented as a wrapper for 'insertElementBefore' bool removeElement(struct PLAYER* pCurrent); bool swapTwoElements(struct PLAYER* pSwapFirst, struct PLAYER* pSwapSecond); bool moveElementAfter(struct PLAYER* pToMove, struct PLAYER* pStatic); // Function Definitions void* forEachElement(PLAYER* Start, void (*func)(struct PLAYER*)) { if(!Start) Start = Last; PLAYER* pWorking = Start; do { func(pWorking); pWorking = pWorking-&gt;Header.pNext; } while(pWorking != Start); return 0; } char* handleInput() { printf("Who has just been summoned? : "); // Removing newline character from input string char* input = (char*)malloc(MAX_NAME_LENGTH); fgets(input, MAX_NAME_LENGTH, stdin); if(input[strlen(input)-1] == '\n') { input[strlen(input)-1] = '\0'; } // Debug Functions if(input[0] == '#') { forEachElement(Last, printElementContent); printf("Special Function #\n"); return 0; } if(input[0] == 'L') { printElementContent(Last); return 0; } // TODO ability to remove players from the queue // TODO ability to update 'Fights', 'Wins' and 'Losses' // Use return value to choose between restarting the while(1) loop or continuing return input; } PLAYER* lookupPlayer(char* player) { PLAYER* pWorking = Last; do { if(!strcmp(player, pWorking-&gt;Player)) return pWorking; pWorking = pWorking-&gt;Header.pNext; } while(pWorking != Last); return 0; } void printSummonOrder(struct PLAYER* pCurrent) { signed int short order = 1; PLAYER* pWorking = pCurrent-&gt;Header.pNext; PLAYER* pHolding = pWorking; do { printf("[%d] - %s\n", order, pWorking-&gt;Player); pWorking = pWorking-&gt;Header.pNext; order++; } while(pWorking != pHolding); return; } void printElementContent(struct PLAYER* pCurrent) { // TODO tidy this function printf("------\n"); printf("%s Element\n", pCurrent-&gt;Player); PLAYER* pNext = pCurrent-&gt;Header.pNext; printf("pNext = %s\n", pNext-&gt;Player); PLAYER* pPrev = pCurrent-&gt;Header.pPrev; printf("pPrev = %s\n", pPrev-&gt;Player); printf("Fights = %d\n", pCurrent-&gt;Fights); printf("Wins = %d\n", pCurrent-&gt;Wins); printf("Losses = %d\n", pCurrent-&gt;Losses); printf("------\n"); return; } struct PLAYER* createPlayer(char* player) { PLAYER* NewPlayer = (PLAYER*)malloc(sizeof(PLAYER)); NewPlayer-&gt;Player = (char*)malloc(strlen(player)); strcpy(NewPlayer-&gt;Player, player); NewPlayer-&gt;Fights = 0; NewPlayer-&gt;Wins = 0; NewPlayer-&gt;Losses = 0; return NewPlayer; } bool insertElementBefore(struct PLAYER* pCurrent, struct PLAYER* pNew) { // Get the pointer to the previous element PLAYER* pBefore = (PLAYER*)pCurrent-&gt;Header.pPrev; // Update element before pCurrent (pBefore) to have it's pNext point to pNew pBefore-&gt;Header.pNext = pNew; // Update pNew to have it's pPrev point to pBefore pNew-&gt;Header.pPrev = pBefore; // Update pNew to have it's pNext point to pCurrent pNew-&gt;Header.pNext = pCurrent; // Finally update pCurrent to have it's pPrev point to pNew pCurrent-&gt;Header.pPrev = pNew; return 1; } bool insertElementAfter(struct PLAYER* pCurrent, struct PLAYER* pNew) { // Get the pointer to the following element PLAYER* pAfter = (PLAYER*)pCurrent-&gt;Header.pNext; // Update element after pCurrent (pAfter) to have it's pPrev point to pNew pAfter-&gt;Header.pPrev = pNew; // Update pNew to have it's pNext point to pAfter pNew-&gt;Header.pNext = pAfter; // Update pNew to have it's pPrev point to pCurrent pNew-&gt;Header.pPrev = pCurrent; // Finally update pCurrent to have it's pNext point to pNew pCurrent-&gt;Header.pNext = pNew; return 1; } bool removeElement(struct PLAYER* pCurrent) { PLAYER* pNext = (PLAYER*)pCurrent-&gt;Header.pNext; PLAYER* pPrev = (PLAYER*)pCurrent-&gt;Header.pPrev; // Update pPrev's pNext to be pNext pPrev-&gt;Header.pNext = pNext; // Likewise update pNext's pPrev to be pPrev (removing references to pCurrent from surrounding elements) pNext-&gt;Header.pPrev = pPrev; return 1; } bool swapTwoElements(struct PLAYER* pSwapFirst, struct PLAYER* pSwapSecond) { // Is the first element BEFORE and ADJACENT to the second? if(pSwapFirst-&gt;Header.pPrev == pSwapSecond) { pSwapFirst-&gt;Header.pNext = pSwapSecond-&gt;Header.pNext; // Updates pSwapFirst's pNext to be pSwapSecond's pNext pSwapFirst-&gt;Header.pPrev = pSwapSecond; pSwapSecond-&gt;Header.pPrev = pSwapFirst-&gt;Header.pPrev; // Updates pSwapSecond's pPrev to be pSwapFirst's pPrev pSwapSecond-&gt;Header.pNext = pSwapFirst; return 1; } // Is the first element AFTER and ADJACENT to the second? if (pSwapFirst-&gt;Header.pNext == pSwapSecond) { pSwapFirst-&gt;Header.pPrev = pSwapSecond-&gt;Header.pPrev; // Updates pSwapFirst's pPrev to be pSwapSeconds's pPrev pSwapFirst-&gt;Header.pNext = pSwapSecond; pSwapSecond-&gt;Header.pNext = pSwapFirst-&gt;Header.pPrev; // Updates pSwapSeconds's pNext to be pSwapFirst's pNext pSwapSecond-&gt;Header.pPrev = pSwapFirst; return 1; } // Update (pSwapFirst-&gt;Header.pPrev)-&gt;Header.pNext to point to pSwapSecond PLAYER* pBeforeSwapFirst = pSwapFirst-&gt;Header.pPrev; pBeforeSwapFirst-&gt;Header.pNext = pSwapSecond; // Update (pSwapFirst-&gt;Header.pNext)-&gt;Header.pPrev to point to pSwapSecond PLAYER* pAfterSwapFirst = pSwapFirst-&gt;Header.pNext; pAfterSwapFirst-&gt;Header.pPrev = pSwapSecond; // Update (pSwapSecond-&gt;Header.pPrev)-&gt;Header.pNext to point to pSwapFirst PLAYER* pBeforeSwapSecond = pSwapSecond-&gt;Header.pPrev; pBeforeSwapSecond-&gt;Header.pNext = pSwapFirst; // Update (pSwapSecond-&gt;Header.pNext)-&gt;Header.pPrev to point to pSwapFirst PLAYER* pAfterSwapSecond = pSwapSecond-&gt;Header.pNext; pAfterSwapSecond-&gt;Header.pPrev = pSwapFirst; return 1; } bool moveElementAfter(struct PLAYER* pToMove, struct PLAYER* pStatic) { // Step 1: Update pStatic-&gt;Header.pNext to point to pToMove PLAYER* pOriginalAfterStatic = pStatic-&gt;Header.pNext; pStatic-&gt;Header.pNext = pToMove; // Step 2: Update pOriginalAfterStatuc-&gt;Header.pPrev to point to pToMove pOriginalAfterStatic-&gt;Header.pPrev = pToMove; // Info: This has inserted pToMove after pStatic and before pOriginalAfterStatic (from the perspective on pStatic and pOriginalAfterStatic) // Step 3: Stitch up the elements before and after pToMove's original position PLAYER* pBeforeToMove = pToMove-&gt;Header.pPrev; PLAYER* pAfterToMove = pToMove-&gt;Header.pNext; pBeforeToMove-&gt;Header.pNext = pAfterToMove; pAfterToMove-&gt;Header.pPrev = pBeforeToMove; // Step 4: Finally update the Header for pToMove pToMove-&gt;Header.pPrev = pStatic; pToMove-&gt;Header.pNext = pOriginalAfterStatic; return 0; } int main() { printf("Summon Cycles\n"); char* first = handleInput(); if(!first) return -1; PLAYER *Head = createPlayer(first); printSummonOrder(Head); // Initialise the pointer to the last USED element Last = Head; while(1) { char* input = handleInput(); if(!input) continue; PLAYER* Exists = lookupPlayer(input); if(Exists) { if(Last-&gt;Header.pNext != Exists) { printf("%s jumped the queue\n", Exists-&gt;Player); moveElementAfter(Exists, Last); } else continue; Exists-&gt;Fights += 1; Last = Exists; // Important to update this printSummonOrder(Last); continue; } else { PLAYER* New = createPlayer(input); // Insert player into linked last (after most recent element) insertElementAfter(Last, New); //printLinkedList(Head); printSummonOrder(New); // Set the Last element to the newly added one Last = New; } } return 1; } </code></pre> <p>I am compiling this using the following Makefile:</p> <pre><code>all: gcc main.c -o main.elf </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:09:21.187", "Id": "468284", "Score": "1", "body": "I suggest you compile this with the `-wall` switch that you get all the warning messages. Have you run this code and does it work. You might also want to see if there is a `lint` program available for your system." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:14:05.337", "Id": "468285", "Score": "0", "body": "@pacmaninbw Yes, I've compiled and executed the binary - it does work as intended. The functionality is very basic at the moment though. I get alot of warning messages with and without that flag. Most of them are due to assigning pointers to incompatable types. I've Googled 'lint' and for sure it's available on my system (Kubuntu). I will mess around with it :) Thanks for your comment!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:34:29.373", "Id": "468287", "Score": "1", "body": "To be honest with you, this code only \"works\" because it does nothing so far. The warning messages about `incompatable type` is a clear indication that this code will crash and burn in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:44:41.810", "Id": "468294", "Score": "0", "body": "@pacmaninbw It's only because I'm casting _DLINKED_LIST pointers as PLAYER pointers. I think replacing the DLINKED_LIST pointers in the DLINKED_LIST structure to PLAYER pointers might fix it. \"Crash and burn in the future\" - hence why I'm posting the code at this early stage so I don't continue to write bad code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T17:00:52.247", "Id": "468298", "Score": "1", "body": "The rules of the site says the code has to work as expected, it also says the code has to do something. Unfortunately this code just isn't ready for review on this web-site. Some suggestions, separate the code for PLAYER and DLINKED_LIST into their own files PLAYER.h, PLAYER.c, DLINKED_LIST.h DLINKED_LIST.c, keep the concepts separate. DLINKED_LIST might need a data field that is PLAYER, although since PLAYER currently contains a DLINKED_LIST pointer I'm not sure how that would work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T17:02:07.977", "Id": "468300", "Score": "0", "body": "Get as much functionality as you can going and then once it is basically working with a few bugs ask for help on stackoverflow.com, but make sure to follow their rules." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T17:15:46.833", "Id": "468306", "Score": "0", "body": "It does work as expected, just my expectations are rather low. Currently it does exactly what I decribed in the \"Concept\" part of my post. However, what's done is done - remove my post.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T08:53:04.300", "Id": "468332", "Score": "0", "body": "If you can sort out the specific compiler warnings and create a minimal example focusing only on those, then you can ask how to fix those on SO. At a glance, it seems that you should re-design the structs and keep linked list logic separate from data. For example you could create a simple, stand-alone linked list ADT in a separate file, that uses void pointers to data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T13:42:30.313", "Id": "468570", "Score": "0", "body": "I don't agree with this being irreparably broken, but I do agree that it doesn't do enough to be reviewable. VTC." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T15:45:28.063", "Id": "238775", "Score": "1", "Tags": [ "c" ], "Title": "Helper for matching players in a video game" }
238775
<h2>INTRO</h2> <p><a href="https://www.digitalocean.com/community/tutorials/an-introduction-to-snmp-simple-network-management-protocol" rel="nofollow noreferrer"><strong>About SNMP</strong></a></p> <blockquote> <p><strong>SNMP</strong> stands for simple network management protocol. It is a way that servers can share information about their current state, and also a channel through which an administer can modify pre-defined values. SNMP is a protocol that is implemented on the application layer of the networking stack (click here to learn about networking layers). The protocol was created as a way of gathering information from very different systems in a consistent manner.</p> </blockquote> <p>You can read more about <em>SNMP</em>, <em>OIDs</em> and <em>SNMP methods</em> in the above link. As a summary, this script uses:</p> <ul> <li>snmp version 2c</li> <li><em>snmpwalk</em> as the main <em>snmp method</em> to get the data</li> <li>the data fetched from a device is fetched from a specific <em>OID</em> (more LLDP OIDs can be found <a href="http://www.mibdepot.com/cgi-bin/getmib3.cgi?win=mib_a&amp;i=1&amp;n=LLDP-MIB&amp;r=cisco&amp;f=LLDP-MIB-V1SMI.my&amp;v=v1&amp;t=tree#LldpPortNumber" rel="nofollow noreferrer">here</a>)</li> </ul> <p><a href="https://wiki.wireshark.org/LinkLayerDiscoveryProtocol" rel="nofollow noreferrer"><strong>About LLDP</strong></a></p> <blockquote> <p>The Link Layer Discovery Protocol (<strong>LLDP</strong>) is a vendor neutral layer 2 protocol that can be used by a station attached to a specific LAN segment to advertise its identity and capabilities and to also receive same from a physically adjacent layer 2 peer.</p> </blockquote> <hr /> <h3>Combining SNMP and LLDP using python</h3> <p>The purpose of my program is, by using Python3.6 and provided a file of switches data (community string, snmp port and switch ip), to return the neighbours data (local and remote port + name of the neighbours) for all the switches in the file.</p> <p>Example config file:</p> <pre><code>community_string1, snmp_port1, ip1 community_string2, snmp_port2, ip2 community_string3, snmp_port3, ip3 </code></pre> <p>Example output:</p> <pre><code>[ { &quot;name1&quot;: { &quot;ip&quot;: &quot;ip1&quot;, &quot;neighbours&quot;: [ { &quot;neighbour_name1&quot;: &quot;neighbour_name1&quot;, &quot;local_port1&quot;: &quot;local_port1&quot;, &quot;remote_port1&quot;: &quot;remote_port1&quot; }, { &quot;neighbour_name2&quot;: &quot;neighbour_name2&quot;, &quot;local_port2&quot;: &quot;local_port2&quot;, &quot;remote_port2&quot;: &quot;remote_port2&quot; }, { &quot;neighbour_name3&quot;: &quot;neighbour_name3&quot;, &quot;local_port3&quot;: &quot;local_port3&quot;, &quot;remote_port3&quot;: &quot;remote_port3&quot; }, ] }, &quot;name2&quot;: {data here}, &quot;name3&quot;: {data here}, } ] </code></pre> <p><strong>Explaining the output</strong></p> <ul> <li><code>name1</code> represents the name of the switch from the first line of the config file (which is retrieved by doing a snmp walk for <code>PARENT_NAME_OID</code>)</li> <li><code>ip1</code> represents the ip of the switch from the first line of the config file (this is taken as is from the config file)</li> <li>the neighbours are all retrieved via snmp using specific OIDs (see code below).</li> </ul> <p>I thought this JSON output format is the most relevant but if you have better ideas, I'd like to hear.</p> <hr /> <p><strong>The code</strong></p> <p>Now, the code is a bit messy but it does its job using the <a href="https://github.com/etingof/pysnmp" rel="nofollow noreferrer"><code>pysnmp</code></a> library which can be easily installed via <code>pip</code>. It receives the config file as a CLI argument, parses it and the processes the info in it.</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; Parse a file which contains switches information (community, snmp_port, ip) and query those devices (neighbours information) via LLDP. Return the data as a JSON object. &quot;&quot;&quot; import argparse import itertools import pprint import os import re from pysnmp.hlapi import * NEIGHBOUR_PORT_OID = '1.0.8802.1.1.2.1.4.1.1.8.0' NEIGHBOUR_NAME_OID = '1.0.8802.1.1.2.1.4.1.1.9' PARENT_NAME_OID = '1.0.8802.1.1.2.1.3.3' class MissingOidParameter(Exception): &quot;&quot;&quot; Custom exception used when the OID is missing. &quot;&quot;&quot; pass def is_file_valid(filepath): &quot;&quot;&quot; Check if a file exists or not. Args: filepath (str): Path to the switches file Returns: filepath or raise exception if invalid &quot;&quot;&quot; if not os.path.exists(filepath): raise ValueError('Invalid filepath') return filepath def get_cli_arguments(): &quot;&quot;&quot; Simple command line parser function. &quot;&quot;&quot; parser = argparse.ArgumentParser(description=&quot;&quot;) parser.add_argument( '-f', '--file', type=is_file_valid, help='Path to the switches file' ) return parser def get_switches_from_file(): &quot;&quot;&quot;Return data as a list from a file. The file format is the following: community_string1, snmp_port1, ip1 community_string2, snmp_port2, ip2 community_string3, snmp_port3, ip3 The output: [ {&quot;community&quot;: &quot;community_string1&quot;, &quot;snmp_port&quot;: &quot;snmp_port1&quot;, &quot;ip&quot;: &quot;ip1&quot;}, {&quot;community&quot;: &quot;community_string2&quot;, &quot;snmp_port&quot;: &quot;snmp_port2&quot;, &quot;ip&quot;: &quot;ip2&quot;}, {&quot;community&quot;: &quot;community_string3&quot;, &quot;snmp_port&quot;: &quot;snmp_port3&quot;, &quot;ip&quot;: &quot;ip3&quot;}, ] &quot;&quot;&quot; args = get_cli_arguments().parse_args() switches_info = [] with open(args.file) as switches_info_fp: for line in switches_info_fp: line = line.rstrip().split(',') switches_info.append({ 'community': line[0].strip(), 'snmp_port': line[1].strip(), 'ip': line[2].strip(), }) return switches_info def parse_neighbours_ports_result(result): &quot;&quot;&quot; One line of result looks like this: result = iso.0.8802.1.1.2.1.4.1.1.8.0.2.3 = 2 Where the last &quot;2&quot; from the OID is the local port and the value after '=' is the remote port (2) &quot;&quot;&quot; if not result: raise MissingOidParameter('No OID provided.') value = result.split(' = ') if not value: return 'Missing entire value for OID={}'.format(result) else: oid, port = value local_port = re.search(r'{}\.(\d+)'.format(NEIGHBOUR_PORT_OID[2:]), oid).group(1) if port: remote_port = re.search(r'(\d+)', port).group(1) else: remote_port = 'Unknown' return 'local_port', local_port, 'remote_port', remote_port def parse_parent_name(result): &quot;&quot;&quot; One line of result looks like this: result = iso.0.8802.1.1.2.1.3.3.0 = Switch01 The name of the parent is &quot;Switch01&quot; &quot;&quot;&quot; if not result: raise MissingOidParameter('No OID provided.') value = result.split(' = ') if not value: return 'Missing entire value for OID={}'.format(result) else: return 'Unknown' if not value[-1] else value[-1] def parse_neighbour_names_results(result): &quot;&quot;&quot; One line of result looks like this: result = iso.0.8802.1.1.2.1.4.1.1.9.0.2.3 = HP-2920-24G The name of the parent is &quot;Switch01&quot; &quot;&quot;&quot; if not result: raise MissingOidParameter('No OID provided.') value = result.split(' = ') if not value: return 'Missing entire value for OID={}'.format(result) else: return ('name', 'Unknown') if not value[-1] else ('name', value[-1]) def main(): data = {} switches_filedata = get_switches_from_file() for switch in switches_filedata: community = switch.get('community') snmp_port = switch.get('snmp_port') ip = switch.get('ip') name = '' for (error_indication, error_status, error_index, var_binds) in nextCmd( SnmpEngine(), CommunityData(community), UdpTransportTarget((ip, snmp_port)), ContextData(), ObjectType(ObjectIdentity(PARENT_NAME_OID)), lexicographicMode=False ): # this should always return one result name = parse_parent_name(str(var_binds[0])) if not name: print('Could not retrieve name of switch. Moving to the next one...') continue neighbour_names = [] neighbour_local_remote_ports = [] for (error_indication, error_status, error_index, var_binds) in nextCmd( SnmpEngine(), CommunityData(community), UdpTransportTarget((ip, snmp_port)), ContextData(), ObjectType(ObjectIdentity(NEIGHBOUR_NAME_OID)), lexicographicMode=False ): for var_bind in var_binds: neighbour_names.append( parse_neighbour_names_results(str(var_bind)) ) for (error_indication, error_status, error_index, var_binds) in nextCmd( SnmpEngine(), CommunityData(community), UdpTransportTarget((ip, snmp_port)), ContextData(), ObjectType(ObjectIdentity(NEIGHBOUR_PORT_OID)), lexicographicMode=False ): for var_bind in var_binds: neighbour_local_remote_ports.append( parse_neighbours_ports_result(str(var_bind)) ) neighbours = [] for a, b in itertools.zip_longest( neighbour_names, neighbour_local_remote_ports, fillvalue='unknown' ): neighbours.append({ a[0]: a[1], b[0]: b[1], b[2]: b[3] }) data[name] = { 'ip': ip, 'neighbors': neighbours } return data if __name__ == '__main__': all_data = main() pprint.pprint(all_data, indent=4) </code></pre> <p><strong>What I'm especially looking after:</strong></p> <ul> <li>better / more performant ways of using <code>pysnmp</code>'s functionality (perhaps I can do only one SNMP walk to store all the data and then from there get the needed data for all the OIDs) - kinda like we're doing when parsing <code>lxml</code>s html tree.</li> <li>better ways of structuring my code</li> <li>improvements regarding the names of the functions/names</li> <li>I tried to stick to PEP8 but I didn't really focused on it. I'm familiar with almost everything related to it and so I would like you guys not to focus on this too much.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:45:21.913", "Id": "468295", "Score": "0", "body": "*NOTE*: Unless you have access to some switches within a network this can hardly be tested and I'm sorry that I can't provide a test environment where you can play with it. I hope you guys will still have the pleasure to review this ^^" } ]
[ { "body": "<h2>Type hints</h2>\n\n<p>PEP484 type hints will help; an example:</p>\n\n<pre><code>def is_file_valid(filepath: str) -&gt; bool:\n</code></pre>\n\n<h2>Function contracts</h2>\n\n<p><code>is_file_valid</code> isn't actually what's happening. You're using this function to do two things:</p>\n\n<ul>\n<li>Cast an input string to whatever the program needs through the argparse system</li>\n<li>Verify that the input string is correct</li>\n</ul>\n\n<p>The <a href=\"https://docs.python.org/3.8/library/argparse.html#type\" rel=\"nofollow noreferrer\">documentation</a> shows how this should actually be done:</p>\n\n<pre><code>parser.add_argument('bar', type=open)\n</code></pre>\n\n<p>This will call <code>open</code> and give you back a file object, or fail if the file doesn't exist.</p>\n\n<h2>Parsing</h2>\n\n<p>The <code>get_switches_from_file</code> can use tuple unpacking:</p>\n\n<pre><code>community, port, ip = (t.strip() for t in line.split(','))\n</code></pre>\n\n<p>This has the added advantage that irregular lines with more than three parts will cause an error rather than being silently ignored.</p>\n\n<p>Better yet, delegate this to a class:</p>\n\n<pre><code>class Switch:\n def __init__(self, line: str):\n self.community, self.port, self.ip = (\n field.strip() for field in line.split(',')\n )\n</code></pre>\n\n<h2>Avoid iterative concatenation</h2>\n\n<p>Rather than maintaining <code>switches_info</code>, simply <code>yield</code> each dictionary from the inner loop. This will cause your method to go from O(n) memory to O(1) memory, at a probable slight cost to runtime.</p>\n\n<p>If you use the <code>Switch</code> class above, this could look like</p>\n\n<pre><code> args = get_cli_arguments().parse_args()\n with args.file as switches_info_fp:\n for line in switches_info_fp:\n yield Switch(line)\n</code></pre>\n\n<h2>Separation of concerns</h2>\n\n<p><code>parse_neighbours_ports_result</code> has an odd return format. It's not clear that the first and third string are useful. Either return a 2-tuple with the actual port values, or return a named tuple or class instance.</p>\n\n<h2>Implicit tuple unpacking</h2>\n\n<pre><code>for (error_indication, error_status, error_index, var_binds)\n</code></pre>\n\n<p>can lose the parens.</p>\n\n<h2>Imports</h2>\n\n<p>To abbreviate your code, do some <code>from x import y</code>:</p>\n\n<pre><code>from argparse import ArgumentParser\nfrom itertools import zip_longest\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:11:58.080", "Id": "468589", "Score": "0", "body": "Those are some nice suggestions but the `is_file_valid ` has to return something since it's used in one of `parser.add_argument`s params. I'd also love to hear some other suggestions regarding the structure of the whole project :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T19:46:54.443", "Id": "468600", "Score": "0", "body": "_is_file_valid has to return something_ - Sure; I've edited my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:13:38.967", "Id": "468604", "Score": "0", "body": "_I'd also love to hear some other suggestions regarding the structure of the whole project_ - use a helper class for named parse elements; edited" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T19:08:19.417", "Id": "238896", "ParentId": "238781", "Score": "5" } } ]
{ "AcceptedAnswerId": "238896", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T16:42:47.850", "Id": "238781", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Find neighbours of a switch using Python and SNMP (LLDP)" }
238781
<p>I'm writing the following program for a school assignment. The prompt is as follows:</p> <blockquote> <p>A magic square is square grid filled with distinct positive integers such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal.</p> </blockquote> <p>My task is to make a boolean method, named <code>magical()</code> that is passed a 2d array, and will return <code>true</code> if those criteria are met. This is the code I wrote:</p> <pre><code>private static boolean magical(int[][] square) { int length = square.length; //This loop checks for duplicate values for (int i = 0; i &lt; length; i++){ for (int j = 0; j &lt; length; j++){ int x = square[i][j]; for (int a = 0; a &lt; length; a++){ for (int b = 0; b &lt; length; b++){ if (a == i &amp;&amp; b == j) continue; if (x == square[a][b]) return false; } } } } ArrayList&lt;Integer&gt; sums = new ArrayList&lt;&gt;(); //This loop finds the sums of the rows and columns for (int i = 0; i &lt; length; i++){ int sum = 0; int sum2 = 0; for (int j = 0; j &lt; length; j++){ sum += square[i][j]; sum2 += square[j][i]; } sums.add(sum); sums.add(sum2); } //The next two loops find the sums of each diagonal. int x = 0; int y = 0; int sum = 0; while (x &lt; length &amp;&amp; y &lt; length){ sum += square[x][y]; x++; y++; } sums.add(sum); sum = 0; x = 0; y = length - 1; while (x &lt; length &amp;&amp; y &gt;= 0){ sum += square[x][y]; x++; y--; } sums.add(sum); return sums.stream().allMatch(s -&gt; s.equals(sums.get(0))); } </code></pre> <p>Here are my questions:</p> <ol> <li><p>Is there any way to confirm that there are no duplicate values in the array without having to nest four for loops? This seems like an incredibly inefficient system.</p></li> <li><p>Is there any way to combine the two loops in the end that are used to make sure that the sum of values in each diagonal are the same? I am currently using two loops, but seeing as I am iterating through the same array, it seems inefficient to do it twice.</p></li> </ol> <p>I am also open to any other suggestions you may have. Please note, it is given in the prompt that all arrays passed as parameters will be squares, and it is not required to test for this.</p>
[]
[ { "body": "<p>Note, using Sets, is the way to go. My answer is based upon the assumption that you didn't learn about Sets and you can only use arrays.</p>\n<h1>duplicated values</h1>\n<pre><code>A1 A2 A3\nA4 A5 A6\nA7 A8 A9\n</code></pre>\n<p>your loop:</p>\n<pre><code>for (int i = 0; i &lt; length; i++){\n for (int j = 0; j &lt; length; j++){\n int x = square[i][j];\n for (int a = 0; a &lt; length; a++){\n for (int b = 0; b &lt; length; b++){\n if (a == i &amp;&amp; b == j) continue;\n if (x == square[a][b]) return false;\n }\n }\n }\n}\n</code></pre>\n<p>In this loop, you will check everything twice...<br />\nFor example:<br />\n<code>square[i][j]</code> will point to <code>A9</code> and <code>square[a][b]</code> will point to <code>A1</code>.<br />\nbut, also reversed: <code>square[a][b]</code> will point to <code>A9</code> and <code>square[i][j]</code> will point to <code>A1</code>.<br />\nTherefor, you check <code>A1</code> with <code>A9</code> twice (and every other combination as well).</p>\n<h1>diagonals</h1>\n<p>You can use one variable instead of both <code>x</code> and <code>y</code></p>\n<h1>Answer</h1>\n<ol>\n<li>for every coordinate (2 loops) you want to check the other coordinates (2 loops). This means you need 4 loops.<br />\nYou could store the fields in a 1 dimensional array first, but to my knowledge, this wouldn't be any quicker.</li>\n<li>after rewriting using 1 variable, you can answer this question yourself.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T09:36:11.617", "Id": "468336", "Score": "1", "body": "Even without Sets he could use a `c = bool[len*len]` and loop once over the whole square and first check if the corresponding entry is already true and then set `c[square[i][j]] = true` - effectively using a simple array as a more efficient Set for this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T20:06:34.237", "Id": "468507", "Score": "0", "body": "@Falco, if you're refering to duplicated values, you're correct. (Didn't provide implementation because it's a homework excercise...). But, what it square has very big numbers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T12:55:18.313", "Id": "469075", "Score": "0", "body": "What if I store the fields in a one dimensional array,call ```Arrays.sort()``` and then iterate to determine if any consecutive values are equal? Is that what you were referring to in your answer, and would that be faster than the system I'm using now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T13:08:50.523", "Id": "469078", "Score": "0", "body": "My first suggesiton... Go with the other answers as their algorithms are way better. \n\nI was sugesting how you could improve your alorithm a little bit: If your first coordinate == your second coordinate, you don't need to check that first coordinate anymore any further. So in short, you can update your `continue` to continue the 2nd loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T20:48:12.007", "Id": "238793", "ParentId": "238783", "Score": "6" } }, { "body": "<p>Answering your first question, yes there is a better way. Efficiency doesn't matter in your case but in this instance the more efficient thing is also easier on the eyes.</p>\n\n<p>The usual idea would be to make a hash set of the elements, then you have O(1) look up of whether you have already inserted an elements, making the task O(n^2).</p>\n\n<p>I'm not that familiar with Java sadly so to answer your second question I just propose the fairly imperative thing of doing everything in one traversal (I think probably it can be done with the functional constructs that Java has), like so.</p>\n\n<pre><code>private static boolean magical(int[][] square) {\n Set&lt;Integer&gt; seenInts = new HashSet&lt;&gt;();\n var leftDiagonalSum = 0;\n var rightDiagonalSum = 0;\n var rowSums = new int[square.length];\n var colSums = new int[square.length];\n\n for(var i = 0; i &lt; square.length; i++) {\n for(var j = 0; j &lt; square.length; j++) {\n var currentElement = square[i][j];\n\n seenInts.add(currentElement);\n leftDiagonalSum += (i == j) ? currentElement : 0;\n rightDiagonalSum += (i == square.length - 1 - j) ? currentElement : 0;\n rowSums[i] += currentElement;\n colSums[j] += currentElement;\n }\n }\n\n Set&lt;Integer&gt; sumSet = new HashSet&lt;&gt;();\n\n sumSet.add(leftDiagonalSum);\n sumSet.add(rightDiagonalSum);\n\n for(var i = 0; i &lt; square.length; i++) {\n sumSet.add(rowSums[i]);\n sumSet.add(colSums[i]);\n }\n\n var noDuplicates = seenInts.size() == square.length * square.length;\n var allSameSums = sumSet.size() == 1;\n\n return noDuplicates &amp;&amp; allSameSums;\n}\n</code></pre>\n\n<p>Edit - While I may not know much Java, there's no reason to specify the implementation of Set used, so the type of seenInts and sumSet can just be Set</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T21:22:54.920", "Id": "238795", "ParentId": "238783", "Score": "10" } }, { "body": "<p>I'll have a go at your first question, using a Set:</p>\n\n<pre><code>Set&lt;Integer&gt; seenNumbers = new HashSet&lt;Integer&gt;();\nfor (int i = 0; i &lt; length; ++i) {\n for (int j = 0; j &lt; length; ++j) {\n if (!seenNumbers.add(square[i][j])) {\n\n return false;\n }\n }\n}\n\n... rest of method\n</code></pre>\n\n<p>It keeps adding elements to the Set until it finds a duplicate (Set.add() returns false when the element is already in the Set).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T20:36:58.120", "Id": "468396", "Score": "0", "body": "Would this use less processing power? Perhaps the underlying code in the ```Set.add()``` method uses a for loop? I'm not sure, I really don't know how all this Hash stuff works, but this question thread has given me a lot to Google about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T23:22:35.407", "Id": "468615", "Score": "0", "body": "@a p, yes. Your solution is O(n^4) and this one is O(n^2). I'm pretty sure the underlying code does not use a loop (haven't checked though, I leave that for the flat-earthers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T01:17:10.247", "Id": "468634", "Score": "0", "body": "I just want to make sure we're not crossing wires. As @Clearer pointed out, my solution is O(n^4) in terms of ```n = length```, however, based on the absolute length of the array, it is only O(n^2). With that in mind, would the new method suggested here still be faster? In terms of absolute length, is it O(n)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T05:50:15.337", "Id": "468643", "Score": "1", "body": "Yes. HashSet.add() is O(1). Whichever way you measure the outer loops, a hash will always be faster in O() terms than a loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T08:34:20.277", "Id": "484730", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) *in the answer* so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T04:15:43.677", "Id": "238806", "ParentId": "238783", "Score": "3" } }, { "body": "<p>My java is a bit rusty, so my answer is going to be more generic than just java.</p>\n\n<p>For 1., as @tieskedh points out, you want to use sets. If you don't have to available, you can emulate one by creating a list containing all the elements, sorting it and checking that none of the values has a neighbour that is identical to itself. This will be effecient and easy to understand; the cost is O(n) for the copy, O(n log n) for the sort and O(n) for the comparison. In terms of big-O notation, you won't do better than that. In contrast, your current solution is O(n^2).</p>\n\n<p>For 2. I probably wouldn't do it. Expressiveness is very important to code quality and combining two loops to save a few cycles may not be a good idea. It might also decrease performance if you end up trashing your cache. This particular problem seems like a prime candidate for poor performance, due to caching issue if you do combine the loops. Others have already pointed out that you only need one variable to access the elements you want. You should replace your <code>while</code>-loops with <code>for</code>-loops. Both because a <code>for</code>-loop expresses your intent better, but also because you can remove a lot of the polution your variables introduce. Consider how you might be able to move it into a function, that will allow you to do both loops with the same code (hint; use step variables for x and y as parameters to your function).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:50:53.243", "Id": "468384", "Score": "0", "body": "Although I use four nested for loops, each set of two iterates through the array once, because it is a 2D array. Therefore, unless I am mistaken, the cost is O(n^2). Either way, your point is valid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T21:43:10.810", "Id": "468402", "Score": "1", "body": "I was thinking in terms of n = length, but yes, you're right. I didn't use n = length for the other examples :-) I fixed it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T15:19:04.297", "Id": "238831", "ParentId": "238783", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T17:33:33.703", "Id": "238783", "Score": "16", "Tags": [ "java", "beginner", "array" ], "Title": "Determining if a given square is a magic square" }
238783
<p>I have created the below code which works for me, but I feel there might be a better way to accomplish this in a new Pythonic way or better Python syntactic way.</p> <h2>Code snippet:</h2> <p><code>bondCheck.py</code></p> <pre><code>#!/usr/bin/python # Port bonding checker. # cat /proc/net/bonding/bond0 import sys import re def usage(): print '''USAGE: %s [options] [bond_interface] Options: --help, -h This usage document Arguments: bond_interface The bonding interface to query, eg. 'bond0'. Default is 'bond0'. ''' % (sys.argv[0]) sys.exit(1) # Parse arguments try: iface = sys.argv[1] if iface in ('--help', '-h'): usage() except IndexError: iface = 'bond0' # Grab the inf0z from /proc try: bond = open('/proc/net/bonding/%s' % iface).read() except IOError: print "ERROR: Invalid interface %s\n" % iface usage() # Parse and output active = 'NONE' Link = 'NONE' slaves = '' state = 'OK' links = '' bond_status = '' for line in bond.splitlines(): m = re.match('^Currently Active Slave: (.*)', line) if m: active = m.groups()[0] m = re.match('^Slave Interface: (.*)', line) if m: s = m.groups()[0] slaves += ', %s' % s m = re.match('^Link Failure Count: (.*)', line) if m: l = m.groups()[0] links += ', %s' % l m = re.match('^MII Status: (.*)', line) if m: s = m.groups()[0] if slaves == '': bond_status = s else: slaves += ' %s' % s if s != 'up': state = 'FAULT' print "%s: %s (%s), Active Slave: %s, PriSlave: %s (%s), SecSlave: %s (%s), LinkFailCountOnPriInt: %s, LinkFailCountOnSecInt: %s" % (iface, state, bond_status, active, slaves.split(',')[1].split()[0], slaves.split(',')[1].split()[1], slaves.split(',')[2].split()[0], slaves.split(',')[2].split()[1], links.split(',')[1], links.split(',')[2]) </code></pre> <h2>Code Returned Result:</h2> <pre><code>$ ./bondCheck.py bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LinkFailCountOnPriInt: 0, LinkFailCountOnSecInt: 0 </code></pre> <p>Edit:</p> <h2>Bond config</h2> <pre><code>cat /proc/net/bonding/bond0 Bonding Mode: fault-tolerance (active-backup) Primary Slave: ens3f0 (primary_reselect always) Currently Active Slave: ens3f0 MII Status: up MII Polling Interval (ms): 100 Up Delay (ms): 2500 Down Delay (ms): 300 Slave Interface: ens3f0 MII Status: up Speed: 20000 Mbps Duplex: full Link Failure Count: 0 Permanent HW addr: 5a:19:bb:00:00:48 Slave queue ID: 0 Slave Interface: ens3f1 MII Status: up Speed: 20000 Mbps Duplex: full Link Failure Count: 0 Permanent HW addr: 5a:19:bb:00:00:49 Slave queue ID: 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T15:25:35.160", "Id": "468367", "Score": "0", "body": "Even making it Python3.x complaint will be okay." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:02:24.977", "Id": "468411", "Score": "0", "body": "_Even making it Python3.x complaint will be okay._ Is there a particular reason you're using Python 2, though?" } ]
[ { "body": "<p>As a rule I don't like to trigger exceptions, even controlled ones. One reason is that they are more expensive to handle, and as the name implies they should remain exceptions.</p>\n\n<p>So rather than doing this:</p>\n\n<pre><code>try:\n bond = open('/proc/net/bonding/%s' % iface).read()\nexcept IOError:\n print \"ERROR: Invalid interface %s\\n\" % iface\n usage()\n</code></pre>\n\n<p>I would have something like this:</p>\n\n<pre><code>import sys, os\n\niface = 'bond0'\nbond = ('/proc/net/bonding/%s' % iface)\n\nif not os.path.exists(bond):\n print \"ERROR: Invalid interface %s\\n\" % iface\n sys.exit(1)\n\n# continue\n</code></pre>\n\n<p>NB: seeing that you are using Python 2.x I have tried to provide compatible code.</p>\n\n<p>Rather than blindly trying to read a file that may not be there in the first place, I simply use <a href=\"https://docs.python.org/2/library/os.path.html#os.path.exists\" rel=\"nofollow noreferrer\">os.path</a> to ascertain its existence (could use the <code>isfile</code> function as well).</p>\n\n<p>I also <strong>return an exit code</strong>, which could be useful if you will be calling this script from another bash script, then you might like to know if the output was as expected or if there is a possible error like a broken network link. Rather than just return 0 (success) or 1 (failure) you could adjust the value depending on the kind of error encountered. Then it's useful to have the <a href=\"https://tldp.org/LDP/abs/html/exitcodes.html\" rel=\"nofollow noreferrer\">special codes</a> in mind.</p>\n\n<p><em>I see that you are already using <code>sys.exit(1)</code> in your code, which is excellent, but it is in the <code>usage</code> function, where it's the least useful. Consider returning an exit code in the other parts of the code including exceptions. One way of doing it would be to have a main <code>try catch</code> block with a <code>finally</code> so that an exit code is always returned, which could be 0 by default.</em></p>\n\n<p>You can still have exception handling in this block though, because you might run into some permission issue, depending on the user and perhaps the OS. It's just that I would avoid raising exceptions for situations that are easily anticipated and tested.</p>\n\n<hr>\n\n<p>Consider <strong>logging exceptions</strong> and even console output or debugging information. A recent discussion on the topic: <a href=\"https://codereview.stackexchange.com/a/238459/219060\">Custom exception handling function or logging library?</a></p>\n\n<p>This is especially important for unattended scripts. In this case, it's probably less important if the script will always be run interactively. But it's good to have a trace on file when you are working in some tiny SSH or screen terminal session with a small buffer size and difficulty scrolling text.</p>\n\n<hr>\n\n<p>Regarding semi-constant variables like <code>/proc/net/bonding/</code> or <code>bond0</code> I try to regroup them together on top of the script. The paths and interface names may vary from an OS to another and porting code to another platform is easier when essential variable names are not <strong>scattered</strong> all over the place. Obviously, they should be defined only once and repetition is to be avoided absolutely. I develop scripts for servers that run on at least 3 different flavors of Linux and I sometimes have surprises...</p>\n\n<hr>\n\n<p>Regarding the code proper: the final line doing the <code>print</code> is quite hard to read. All that splitting is unnecessary and even unsafe. If the output of <code>/proc/net/bonding/bond0</code> changes, or the number of slaves is less than 2, your code could fail.</p>\n\n<p>Ideally, you should have ready-to-use variables and just print them. All the processing, parsing, validation etc has to take place before.</p>\n\n<p>Let's take this snippet as an example:</p>\n\n<pre><code> m = re.match('^Slave Interface: (.*)', line)\n if m:\n s = m.groups()[0]\n slaves += ', %s' % s\n</code></pre>\n\n<p>Your code iterates twice. At the first iteration the value of <code>slaves</code> is: <code>, ens3f0</code>. At the second iteration it is: <code>, ens3f0 up, ens3f1</code>. Note the leading comma.\nIt seems that you are not yet familiar with Python structures such as lists or dictionaries, so you are resorting to string manipulations techniques that are superfluous. \nHere how I would do it, using a simple <strong>list</strong>:</p>\n\n<p>First add this somewhere in your code, for example before the <code>for</code> loop:</p>\n\n<pre><code>slave_interfaces = []\n</code></pre>\n\n<p>We simply define an empty list. Then your code becomes:</p>\n\n<pre><code> m = re.match('^Slave Interface: (.*)', line)\n if m:\n slave_interfaces.append(m.group(1).strip()) \n</code></pre>\n\n<p>When a match if found, the value is appended to the list, which means adding an element. Note the addition of <code>strip()</code> to <strong>trim whitespace</strong> that may surround the interface name.</p>\n\n<p>The regular expression can not only match but <strong>capture</strong> as well. Since <code>m.group(1)</code> already contains the name of the interface you can use it. Now, at the first iteration the value of <code>slave_interfaces</code> is: <code>['ens3f0']</code>. At the second iteration it is: <code>['ens3f0', 'ens3f1']</code>. You have a <strong>list</strong> of two elements, and you can address each of them by index number, thus <code>slave_interfaces[0]</code> = <code>'ens3f0'</code> and <code>slave_interfaces[1]</code> = <code>'ens3f1'</code>. You can check the number of elements: <code>len(slave_interfaces)</code> will return 2. So you know in advance that using an index number greater then 1 will result in an error (IndexError: list index out of range).</p>\n\n<p>Producing a comma-separated list is as easy as <strong>join</strong>ing:</p>\n\n<pre><code>','.join(slave_interfaces)\n</code></pre>\n\n<p>=> <code>'ens3f0,ens3f1'</code></p>\n\n<hr>\n\n<p>On a final note, for parsing arguments and if you have Python 2.7 at least, the <a href=\"https://docs.python.org/2/library/argparse.html\" rel=\"nofollow noreferrer\">argparse library</a> provides more flexibility. Have a look at the <code>add_help</code> function too. When you develop more sophisticated scripts with multiple arguments that may be in no particular order, your way of doing it will not scale well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T17:34:27.667", "Id": "468388", "Score": "0", "body": "Many thanks indeed for the detailed answer @Anonymous , However, i need the output results in a similar format which is in my original post, can you club your suggested code as one piece. +1 already." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T17:07:06.783", "Id": "238839", "ParentId": "238786", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T18:06:27.870", "Id": "238786", "Score": "2", "Tags": [ "python", "python-2.x" ], "Title": "Linux bonding status check" }
238786
<p>Here is a simple web crawler I wrote in Python 3 that counts the words in each page in a domain, displays word count per page, and sums them up.</p> <p>Tested on a multitude of web pages, works correctly so far.</p> <p>What do you think of my code?</p> <pre><code>import requests from urllib.request import urlopen from bs4 import BeautifulSoup base_url = "https://independencerpgs.com/" html = urlopen(base_url) bsObj = BeautifulSoup(html.read(), features="html.parser"); urls=[] for link in bsObj.find_all('a'): if link.get('href') not in urls: urls.append(link.get('href')) else: pass print(urls) words=0 for url in urls: if url not in ["NULL", "_blank", "None", None, "NoneType"]: if url[0] == "/": url=url[1:] if base_url in url: if base_url == url: pass if base_url != url and "https://"in url: url=url[len(base_url)-1:] if "http://" in url: specific_url=url elif "https://" in url: specific_url = url else: specific_url = base_url + url r = requests.get(specific_url) soup = BeautifulSoup(r.text, features="html.parser") for script in soup(["script", "style"]): script.extract() text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = '\n'.join(chunk for chunk in chunks if chunk) text_list = text.split() print(f"{specific_url}: {len(text_list)} words") words += len(text_list) else: pass print(f"Total: {words} words") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T22:54:56.867", "Id": "468409", "Score": "0", "body": "How resilient/correct of a program are you aiming for? The main difficulty I see is finding and validating all the URLs. Also, what do you mean by _domain_, exactly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:27:20.023", "Id": "468416", "Score": "0", "body": "I might have chosen the wrong term; the idea is to scan a whole site, find all the htm/html pages on it, and count the words in each." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:31:22.530", "Id": "468417", "Score": "1", "body": "_the idea is to scan a whole site_ Your code appears to be parsing the links found on a single page, though. _all the htm/html pages on it_ Can you be more specific still? _count the words in each_ The issue of defining what a word is still stands." } ]
[ { "body": "<p>It's readable and gets the job done as a script, but there is some redundancy in your if cases. Here's a streamlined version:</p>\n\n<pre><code>import requests\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nbase_url = \"https://independencerpgs.com/\"\nhtml = urlopen(base_url)\nbsObj = BeautifulSoup(html.read(), features=\"html.parser\");\n\n# Sets handle duplicate items automatically\nurls=set()\nfor link in bsObj.find_all('a'):\n urls.add(link.get('href'))\nprint(urls)\n\nwords=0\nfor url in urls:\n # Having the logic this way saves 4 spaces indent on all the logic\n if url in [\"NULL\", \"_blank\", \"None\", None, \"NoneType\", base_url]:\n continue\n\n # The == base_url case is handled in the above `if`\n if url[0] == \"/\":\n specific_url = base_url + url # requests.get does not care about the num of '/'\n else:\n specific_url = url\n\n r = requests.get(specific_url)\n soup = BeautifulSoup(r.text, features=\"html.parser\")\n for script in soup([\"script\", \"style\"]):\n # Use clear rather than extract\n script.clear()\n # text is text you don't need to preprocess it just yet.\n text = soup.get_text()\n print(f\"{specific_url}: {len(text)} words\")\n words += len(text)\n\n\nprint(f\"Total: {words} words\")\n</code></pre>\n\n<p>Depending on what you intend to do with that code, you might want to put it into functions or even create a class around it too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T07:39:02.663", "Id": "468329", "Score": "0", "body": "Thanks! Will probably include it in a function once I create a UI for it, where the user enters the URL rather than have it coded into the script itself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T23:07:49.510", "Id": "238798", "ParentId": "238787", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T18:38:24.127", "Id": "238787", "Score": "1", "Tags": [ "python" ], "Title": "Python web crawler counting words in all pages in a domain" }
238787
<p>The function below is part of an overall chunk of code to partition an array of size M into sub-arrays of size N. The function in question is written to handle the case: what if M isn't divisible by N? Then, the way the rest of the code works, the last element in the partitioned array might have fewer than N items. (E.g., if N = 3, there might be an array like <code>[[A, B, C], [D, E, F], [G, H]]</code>. </p> <p>There are two reasonable solutions: (a) just accept a shorter array at the end (maybe with padding, depending on use case), or (b) take the shorter array and distribute it among the remaining arrays. This code implements solution (b). </p> <pre><code>function mushInLittleArray(arrs, size){ var correctSize = arrs[arrs.length - 1].length == size; if (correctSize) { return arrs; } var last = arrs.pop(); var len = last.length; var j = 0; var div = false; var arrlen = arrs.length; for (var i = 0; i &lt; len; i++) { div = divisible(j, arrlen); if (div) { j = 0; } arrs[j].push(last[i]); j++; } return arrs; } </code></pre> <p>This code just feels awkward and hackish to me. In particular, the sleight of hand in the conditional toward the end beginning <code>if (div)</code> smells bad. It's meant to deal with the edge case where leftover group is larger than number of other groups, for example, where N = 5 and we have something like <code>[[A, B, C, D, E], [F, G, H, I, J], [K, L, M, N]]</code>, and hence the iteration over the large array needs to reset. The code as written seems to work fine, but having two loop variables and modifying one of them manually within the block seems like dirty pool to me. Surely there must be a better way?</p>
[]
[ { "body": "<p>Based on your constraints, which are:</p>\n\n<ul>\n<li>Single loop variable</li>\n<li>No restarting of iteration over large arrays </li>\n</ul>\n\n<p>You could calculate your looping step sizes first, then go over the array only once.</p>\n\n<pre><code> const mushedArr = [];\n const remainderSize = arr.length % size\n const numberOfChunks = Math.floor(arr.length / size);\n let remainderStepSize = Math.floor(remainderSize / numberOfChunks);\n\n</code></pre>\n\n<p>I'm going to define the remainder with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\" rel=\"nofollow noreferrer\">negative index slicing</a>, so there has to be a guard against calculating a remainder even when division is exact.</p>\n\n<pre><code>let remainder = remainderSize ? arr.slice(-remainderSize) : []\n</code></pre>\n\n<p>Second edge case is where the remainder is smaller than the chunk size, which would cause my step size to evaluate to 0 and not loop through the remainder properly.</p>\n\n<pre><code>if(remainderStepSize === 0) remainderStepSize ++;\n</code></pre>\n\n<p>Finally, loop over the array and the remainder:</p>\n\n<pre><code> let i = 0;\n while(i &lt; numberOfChunks){\n let remainderPortion = remainder\n .slice(i*remainderStepSize, i*remainderStepSize+remainderStepSize);\n\n let arrayPortion = arr.slice(i*size, i*size+size);\n\n mushedArr.push([...arrayPortion, ...remainderPortion]);\n i++;\n };\n return mushedArr;\n};\n</code></pre>\n\n<p>Variable names here could be shorter, and the slice can be simplified to\nsomething like <code>arr.slice(size*i, size*(i+1)</code>, but the idea is to loop over the array and copy the items in sizes that are equal to the chunk size. </p>\n\n<p>Testing for both inputs in your question yielded:</p>\n\n<pre><code>Calling function with input: [A,B,C,D,E,F,G,H,I,J,K,L,M,N]\n chunk size: 5\n[ [ 'A', 'B', 'C', 'D', 'E', 'K', 'L' ],\n [ 'F', 'G', 'H', 'I', 'J', 'M', 'N' ] ]\nCalling function with input: [A,B,C,D,E,F,G,H]\n chunk size: 3\n[ [ 'A', 'B', 'C', 'G' ], [ 'D', 'E', 'F', 'H' ] ]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T00:10:53.293", "Id": "468320", "Score": "1", "body": "Welcome to Code Review! Thanks for supplying an answer! I'd suggest you utilize [markdown formatting](https://codereview.stackexchange.com/editing-help) instead of HTML since it requires fewer keystrokes and not all HTML tags are supported." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T00:42:01.580", "Id": "468321", "Score": "0", "body": "Thanks for the pointer. Updated the post to md format." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T23:13:02.873", "Id": "238799", "ParentId": "238790", "Score": "2" } }, { "body": "<p>For solution </p>\n\n<blockquote>\n <p>(a) - just accept a shorter array at the end</p>\n</blockquote>\n\n<p>code can be very short</p>\n\n<pre><code>function mushInLittleArray(arr, size) {\n let resultArr = [];\n for (let i = 0; i &lt; (arr.length / size); i++ ) {\n resultArr.push( arr.slice( i * size, (i+1) * size ) );\n }\n return resultArr;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T21:59:35.403", "Id": "238852", "ParentId": "238790", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T20:02:33.240", "Id": "238790", "Score": "2", "Tags": [ "javascript", "array", "iteration" ], "Title": "Divide the last element in an array of arrays among the remaining elements" }
238790
<p>I have a table called tblStudent having data as</p> <p><a href="https://i.stack.imgur.com/h3na8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h3na8.png" alt="Student table"></a></p> <p>I want to retrieve records having single value compared against multiple columns. For example -<br> find all students having Grade 'C' in any of the subjects.<br> One way could be - </p> <pre><code>SELECT * FROM tblStudent WHERE Grade_Maths = 'C' OR Grade_Science = 'C' OR Grade_English = 'C' </code></pre> <p>Another (cleaner/shorter) way of achieving same is </p> <pre><code>SELECT * FROM tblStudent WHERE 'C' IN (Grade_Maths, Grade_Science, Grade_English) </code></pre> <p>Because the table data can be considerably huge in real-time, I am not sure whether second method will always return correct result. Can please suggest if there could be any potential issue with using second approach.</p> <p>Thanks a lot!</p>
[]
[ { "body": "<p>The queries are the same except potentially the second won't use index if any exists on grade_* columns. And this flipped approach Is rather uncommon (at least i see it for first time). Possibly because you wouldnt need such approach if you had a better tables structure.</p>\n\n<p>What if suddently students can study history or biology? You Will need to create new columns And Alter all related queries.</p>\n\n<p>Instead there should be a \"subjects\" table and an M:N relation table between subjects and students. Your query wont contain any ORs or INs the way it does now. And adding new subjects Is matter of merely inserting new row to subjects table.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T09:38:44.483", "Id": "468337", "Score": "0", "body": "Thank you for reply and giving the alternative to avoid using IN. For now, I am making changes to some legacy database stored proc so not in a position to change database structure. I checked there are no index on grade columns, so I feel I can safely make the change without breaking it..fingers crossed it's a massive stored proc with 1400 lines." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T05:46:31.673", "Id": "238808", "ParentId": "238797", "Score": "2" } }, { "body": "<p>It depends on database that you are using. In case of MySQL database <code>IN</code> will have better performance. For oracle, internally it will use <code>OR</code> <a href=\"https://stackoverflow.com/questions/3074713/in-vs-or-in-the-sql-where-clause\">1</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T06:58:11.807", "Id": "238810", "ParentId": "238797", "Score": "0" } } ]
{ "AcceptedAnswerId": "238808", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T22:37:46.267", "Id": "238797", "Score": "1", "Tags": [ "sql" ], "Title": "SQL to match string value against multiple columns" }
238797
<p>I am learning graph theory and I have implemented a Directed Graph with weights in Java. My next objective with this class is to learn more about algorithms like Dijkstra, Bellman-Ford, etc. I have split the implementation into two classes - GraphNode and DirectedGraphWithWeights.</p> <p>GraphNode.java</p> <pre><code>public class GraphNode { private int nodeValue; private Integer weight = Integer.MAX_VALUE; GraphNode(int nodeValue) { this.nodeValue = nodeValue; } public int getNodeValue() { return this.nodeValue; } public Integer getWeight() { return this.weight; } public void setWeight(int weight) { this.weight = weight; } @Override public int hashCode() { return new Integer(this.nodeValue).hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GraphNode other = (GraphNode) obj; if(nodeValue != other.getNodeValue()) return false; return true; } } </code></pre> <p>DirectedGraphWithWeights.java</p> <pre><code>import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; public class DirectedGraphWithWeights { private HashMap&lt;GraphNode, LinkedList&lt;GraphNode&gt;&gt; adjacentVerticesByVertex; private Set&lt;GraphNode&gt; allNodesSet; /** * Constructor */ DirectedGraphWithWeights() { adjacentVerticesByVertex = new HashMap&lt;&gt;(); allNodesSet = new HashSet&lt;&gt;(); } /** * Returns the number of vertices in the Graph * @return Returns the number of vertices */ public int getNumberOfVertices() { return this.allNodesSet.size(); } /** * Returns if the graph is directed * @return */ public boolean isDirected() { return true; } /** * Returns the number of edges * @return Returns the number of edges */ public int getNumberOfEdges() { int numberOfEdges = 0; for(var vertices : this.adjacentVerticesByVertex.values()) { numberOfEdges += vertices.size(); } return numberOfEdges; } /** * Adds a node to the graph. VertexA -&gt; VertexB, adding a node creates an * edge between VertexA and VertexB with the specified weight * @param vertexA Vertex A * @param vertexB Vertex B * @param weight Weight of the edge */ public void addNode(int vertexA, int vertexB, int weight) { GraphNode vertexANode = new GraphNode(vertexA); GraphNode vertexBNode = new GraphNode(vertexB); allNodesSet.add(vertexANode); allNodesSet.add(vertexBNode); if(!adjacentVerticesByVertex.containsKey(vertexANode)) adjacentVerticesByVertex.put(vertexANode, new LinkedList&lt;GraphNode&gt;()); vertexBNode.setWeight(weight); adjacentVerticesByVertex.get(vertexANode).add(vertexBNode); } /** * Returns all the vertices of the graph * @return All the vertices of the graph */ public Iterable&lt;Integer&gt; getAllVertices() { Set&lt;Integer&gt; vertices = new HashSet&lt;&gt;(); for(var key : adjacentVerticesByVertex.keySet()) { vertices.add(key.getNodeValue()); } return vertices; } /** * Returns all the adjacent nodes * @param source Source node * @return Returns all the adjacent nodes */ public Iterable&lt;GraphNode&gt; getAdjacentVertices(int source) { GraphNode tempNode = new GraphNode(source); return adjacentVerticesByVertex.get(tempNode); } public void printAllVertices() { for(GraphNode it : adjacentVerticesByVertex.keySet()) { System.out.print(it.getNodeValue() + " -&gt; "); for(var node : getAdjacentVertices(it.getNodeValue())) { System.out.print("value: " + node.getNodeValue() + "; weight: " + node.getWeight() + " -&gt; "); } System.out.println(); } } } </code></pre> <p>I would highly appreciate feedback on my idea of implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T10:02:30.080", "Id": "468339", "Score": "0", "body": "`hashCode()` use default, why? its tried and tested (unless you have different case)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T11:10:59.890", "Id": "468347", "Score": "0", "body": "Sorry I did not understand. Can you please re-phrase?" } ]
[ { "body": "<p>My computer theory classes have been a couple of decades ago, so I may be wrong, but you seem to be confusing the terms \"node\", \"vertex\", \"edge\" and some more. </p>\n\n<p>Unless I'm mistaken \"node\" and \"vertex\" are the same thing, so I'd suggest to use one or the other, but not both. You also seem to sometimes call the value assigned to a vertex \"node\". Use a consistent term such as \"value\" instead.</p>\n\n<p>Also nodes (usually) don't have weights, vertices do.</p>\n\n<p>Then the method <code>addNode</code> actually adds an edge, so it should be named accordingly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T17:35:08.510", "Id": "468389", "Score": "0", "body": "Thanks, RoToRa! I have changed the names for the variables and the functions.\nIn terms of functionality of the class, do you think it is constructed fine?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:34:06.210", "Id": "468756", "Score": "0", "body": "As I wrote: Edges have weights, not nodes, so this code can't work, espeically since the way it is written, the \"weight\" of the node is overwritten and lost if two edges go to same node." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T12:38:04.037", "Id": "238823", "ParentId": "238800", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T23:40:15.490", "Id": "238800", "Score": "4", "Tags": [ "java", "graph" ], "Title": "Directed Graph With Weights in Java" }
238800
<p>I was given the exercise of refactoring the following code, thus ensuring it was following the SOLID design principles. It refers to an Animal Park, where there are a couple of different species of animals, and it defines the rules in which these animals can eat other animals. The Animal Park class processes a polymorphic array of the represented animals. </p> <pre><code> public abstract class Animal { public Size Size { get; set; } public bool IsDead { get; set; } public Animal(Size size) { this.Size = size; this.IsDead = false; } public abstract void Eat(Animal obj); } public enum Size { Small, Medium, Big }; public class Lion : Animal { public Lion(Size size) : base(size) { } public override void Eat(Animal animal) { if (animal is Lion &amp;&amp; this.Size &gt; animal.Size) { animal.IsDead = true; } if (animal is Hyena &amp;&amp; this.Size &gt;= animal.Size) { animal.IsDead = true; } } } public class Hyena : Animal { public Hyena(Size size) : base(size) { } public override void Eat(Animal animal) { if (animal is Hyena &amp;&amp; this.Size &gt; animal.Size) { animal.IsDead = true; } } } public static class AnimalPark { public static void Process(IList&lt;Animal&gt; animals) { int length = animals.Count; for (int i = 1; i &lt; length; i++) { animals[i - 1].Eat(animals[i]); } } } </code></pre> <p>The code above breaks the Open/Closed Principle because every time I would need to add a new animal, I would not be able to do it just by extending the existing classes or by adding new ones: I would have to modify the existing classes. But I am struggling a lot to fix it properly. I came up with a solution (below), but not only I rely on Reflection, which I think can be avoided, it won't work in the cases where the Eat() method is not implemented, thus ending calling the Eat() method in the base class in a loop.</p> <pre><code>public interface IEater { public void Eat(IEater obj); } public abstract class Animal : IEater { public Size Size { get; set; } public bool IsDead { get; set; } public Animal(Size size) { this.Size = size; this.IsDead = false; } public void Eat(IEater obj) { if ( this.IsDead ) { return; } var method = this.GetType().GetMethod("Eat", new Type[] { obj.GetType() }); method.Invoke(this, new object[] { obj }); } } public enum Size { Small, Medium, Big }; public class Lion : Animal { public Lion(Size size) : base(size) { } public void Eat(Hyena hyena) { if (this.Size &gt;= hyena.Size) { hyena.IsDead = true; } } public void Eat(Lion lion) { if (this.Size &gt; lion.Size) { lion.IsDead = true; } } } public class Hyena : Animal { public Hyena(Size size) : base(size) { } public void Eat(Hyena hyena) { if (this.Size &gt; hyena.Size) { hyena.IsDead = true; } } } public static class AnimalPark { public static void Process(IList&lt;IEater&gt; animals) { int length = animals.Count; for(int i=1; i&lt;length; i++) { animals[i - 1].Eat(animals[i]); } } } </code></pre> <p>What are your thoughts on my solution? How would you handle this case?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:07:59.423", "Id": "468414", "Score": "2", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2" } ]
[ { "body": "<blockquote>\n <p>every time I would need to add a new animal, I would not be able to do it just by extending the existing classes or by adding new ones: I would have to modify the existing classes.</p>\n</blockquote>\n\n<p>The problem exists in both your approaches. It is because the eating preferences of individual species is mutualy dependent on all other existing animals. If you add new animal, you define what existing animals it likes to eat, but unless you modify existing animals, no existing animal will ever be interested in eating the new animal.</p>\n\n<p>Generally relying on object being of a specific type is not polymorphism, it's a rape.</p>\n\n<p>You need to abstract and centralize the eating preferences somehow.</p>\n\n<pre><code>public enum AnimalKind\n{\n Lion,\n Hyena\n}\n\npublic interface IDinner\n{\n public AnimalKind Kind {get;}\n public Size Size {get;}\n}\n\npublic interface IEater\n{\n public bool Likes(IDinner dinner); \n}\n\npublic interface IAnimal : IEater, IDinner\n{\n bool IsDead {get;}\n void Kill();\n}\n\nclass Animal : IAnimal\n{\n public AnimalKind Kind {get;}\n public Size Size {get;}\n public bool IsDead {get;}\n\n private IDictionary&lt;AnimalKind, Size&gt; Preferences {get;}\n\n public Animal(AnimalKind kind, Size size, IDictionary&lt;AnimalKind, Size&gt; preferences)\n {\n this.Kind = kind;\n this.Size = size;\n this.Preferences = preferences;\n }\n\n public bool Likes(IDinner dinner)\n {\n var maxSize = this.Preferences[dinner.Kind];\n return maxSize != null &amp;&amp; dinner.Size &lt;= maxSize;\n }\n\n public void Kill()\n {\n IsDead = true;\n }\n}\n\npublic interface IAnimalFactory\n{\n public IAnimal CreateAnimal(AnimalKind kind, Size size);\n}\n\npublic class AnimalFactory : IAnimalFactory\n{\n // centralized place for all animals and their eating preferences\n}\n\npublic static class AnimalPark\n{\n public static void Process(IList&lt;IAnimal&gt; animals)\n {\n int length = animals.Count;\n for(int i=1; i&lt;length; i++)\n {\n var eater = animals[i - 1];\n var dinner = animals[i];\n if (!dinner.IsDead &amp;&amp; !eater.IsDead &amp;&amp; eater.Likes(dinner)) {\n dinner.Kill();\n }\n }\n }\n}\n</code></pre>\n\n<p>Adding new animal now means just extending AnimalKind enum and modifying AnimalFactory class to be aware of the new kind.</p>\n\n<p>Although you might object that having the enum is also not nice. And I kinda agree, but I didn't want to invent an abstraction of the dinner description that was not provided by you. Maybe dinner description could instead be something like a description of how big teeth and paws the dinner has, how aggresive and vicious they look, if they have colors that imply being venomous, etc... If you impleent something like this and get rid of the AnimalKind enum, you will need to change the factory to contain a method per existing animal, but I would not consider it a problem, it may actually be so even with the enum existing...</p>\n\n<p>Also notice I have moved the actual killing of the animal to the AnimalPark class, because that would be the same for all animals. An animal is always killed when eaten and stays alive when not eaten, right?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T13:59:16.633", "Id": "468358", "Score": "0", "body": "Yes, your assumption is right. Thank you so much for taking the time to answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:05:20.373", "Id": "468413", "Score": "0", "body": "I am wondering if the Preferences at the Animal level is the best: why have the preferences in every animal instance, knowing that animals of the same kind and size will have the same preferences? Shouldn't we pass that logic to the centralized component that deals with all the preferences? I came up with a new solution by creating the centralized module you suggested, and I also addressed the issue I just mentioned (maybe it is not really a issue, you will tell me!) I also took out some of the logic from the Animal, and ended up getting rid of IEater (as well as IDinner) interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T05:18:23.083", "Id": "468438", "Score": "0", "body": "@rsy \"knowing that animals of the same kind and size will have the same preferences\". Will they? I didnt make this assumption. What if an anorectic Lion doesnt want to eat anything? What If a crazy hyena Will attept to eat anyone? My approach allows to eventually have extra ordinary individuums. And when asking an animal object for preferences it does not need to search in dictionary, this was done just once at creation..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T16:29:14.173", "Id": "468490", "Score": "0", "body": "It definitely makes sense what you are saying, didn't think about it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T07:18:45.370", "Id": "238811", "ParentId": "238801", "Score": "5" } }, { "body": "<p>After reading the answer given by <em>slepic</em>, I decided to take a different approach. I came up with the following solution, which I think doesn't violate neither the Open-Closed Principle nor the remaining SOLID premises. The main change I have made was to pass the \"eating preferences\" logic to a centralized component.</p>\n\n<pre><code>public abstract class Animal\n{\n public AnimalKind Kind { get; set; }\n public Size Size { get; set; }\n public bool IsDead { get; set; }\n\n protected Animal(Size size)\n {\n this.Size = size;\n }\n}\n\npublic enum AnimalKind\n{\n Error = 0,\n Hyena = 1,\n Lion = 2\n}\n\npublic class Lion : Animal\n{\n public Lion(Size size) : base(size)\n {\n Kind = AnimalKind.Lion;\n }\n\n // Some more logic, which the exercise had, but I omitted because it was not necessary for this question\n}\n\npublic class Hyena : Animal\n{\n public Hyena(Size size) : base(size)\n {\n Kind = AnimalKind.Hyena;\n }\n\n // Some more logic, which the exercise had, but I omitted because it was not necessary for this question\n}\n\npublic enum Size\n{\n Error = 0,\n Small = 1,\n Medium = 2,\n Big = 3\n}\n\npublic static class EatingPreferencesFactory\n{\n public static IDictionary&lt;AnimalKind, Size&gt; GetEatingPreferences(Animal animal)\n {\n Size biggestPreySizeExclusive;\n IDictionary&lt;AnimalKind, Size&gt; animalPreys = new Dictionary&lt;AnimalKind, Size&gt;();\n\n switch(animal.Kind)\n {\n case AnimalKind.Lion: \n animalPreys.Add(AnimalKind.Hyena, animal.Size);\n\n biggestPreySizeExclusive = animal.Size;\n if(biggestPreySizeExclusive &gt; Size.Small &amp;&amp; biggestPreySizeExclusive &lt; animal.Size)\n {\n animalPreys.Add(AnimalKind.Lion, biggestPreySizeExclusive);\n }\n break;\n\n case AnimalKind.Hyena:\n biggestPreySizeExclusive = animal.Size;\n if (biggestPreySizeExclusive &gt; Size.Small &amp;&amp; biggestPreySizeExclusive &lt; animal.Size)\n {\n animalPreys.Add(AnimalKind.Hyena, animal.Size);\n }\n break;\n\n default: break;\n }\n\n\n return animalPreys;\n }\n}\n\npublic interface IEatingPreferencesService\n{\n public bool CanEat(Animal eater, Animal animal);\n}\n\npublic class EatingPreferencesService : IEatingPreferencesService\n{\n public bool CanEat(Animal eater, Animal prey)\n {\n if (eater.IsDead || prey.IsDead) return false;\n\n var eatingPreferences = EatingPreferencesFactory.GetEatingPreferences(eater);\n if (eatingPreferences.TryGetValue(prey.Kind, out Size ediblePreySize))\n {\n if(ediblePreySize&gt;=prey.Size)\n {\n return true;\n }\n }\n\n return false;\n }\n}\n\npublic class AnimalPark\n{\n private readonly IEatingPreferencesService _eatingPreferencesService;\n private readonly IList&lt;Animal&gt; _animals = new List&lt;Animal&gt;();\n\n public AnimalPark(IEatingPreferencesService eatingPreferencesService)\n {\n _eatingPreferencesService = eatingPreferencesService;\n }\n\n public void AddAnimal(Animal animal)\n {\n if(animal != null)\n {\n _animals.Add(animal);\n }\n }\n\n public void Process()\n {\n int length = _animals.Count;\n for(int i=1; i&lt;length; i++)\n {\n if( _eatingPreferencesService.CanEat(_animals[i - 1], _animals[i]) )\n {\n _animals[i].IsDead = true;\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T07:30:53.183", "Id": "468443", "Score": "1", "body": "This is worth posting as a new question for a comparative review. And please include concrete animals, as I don't understand why Animal is now abstract." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T16:05:25.220", "Id": "468487", "Score": "0", "body": "The code for the animals has been posted. I had omitted because it is not relevant for the exercise.\n\nOk, I will post this as a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T16:26:59.387", "Id": "468489", "Score": "0", "body": "@slepic : https://codereview.stackexchange.com/questions/238890/make-it-solid-simple-simulation-of-animals-eating-other-animals-improved" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:20:50.307", "Id": "238855", "ParentId": "238801", "Score": "1" } } ]
{ "AcceptedAnswerId": "238811", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T23:56:08.143", "Id": "238801", "Score": "4", "Tags": [ "c#", "object-oriented" ], "Title": "Simple simulation of animals eating other animals" }
238801
<p>I think the algorithm implementation itself is reasonably efficient, but I'm not sure about proper use of good practices in software development in the code (variable naming, idioms, comments, error handling in inputs etc).</p> <p>I'm attempting to get a first developer job, and since interviewers also evaluate how "clean" the code is, the main point of the question is what is considered good practice, but efficiency improvements are also welcome.</p> <pre><code>mergeSortedArrays = function(arr1, arr2){ if(!(Array.isArray(arr1) &amp;&amp; Array.isArray(arr2))){ throw new TypeError("Need two arrays to merge") }; if(arr2.length === 0 &amp;&amp; arr1.length === 0){ throw new RangeError("Cannot merge empty arrays") }; let i = 0; let j = 0; const targetSize = arr1.length + arr2.length; const mergedArray = []; // main loop while(mergedArray.length &lt; targetSize){ /** * Works until completion for arrays of the same size */ if(arr1[i] &lt; arr2[j]){ valueToPush = arr1[i] i++ }else{ valueToPush = arr2[j] j++ } /** * For arrays with different sizes, it is safe to push the remainder to the sorted array, given that both inputs are sorted. */ if(valueToPush === undefined){ const remainingItems = j &gt; arr2.length ? arr1.slice(i) : arr2.slice(j) mergedArray.push(...remainingItems) break } mergedArray.push(valueToPush) } return mergedArray; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T09:07:24.763", "Id": "468334", "Score": "0", "body": "Both in the title of the post as well as in the code comments, you suggest that this problem were different if the arrays had the same size. However this is not true. Such statements may suggest to interviewers that you didn't completely understand the task." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T14:40:16.800", "Id": "468359", "Score": "0", "body": "Thanks for the comment. That is because a portion of the code that doesn't look right to me was added to handle arrays of different sizes. I was getting `[1, 2, 3, undefined]` and had to work around it. The size of inputs issue is specific to this implementation, not to the problem itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:46:36.493", "Id": "468757", "Score": "1", "body": "I'm sorry, but your thinking is wrong. This algorithm you wrote (nor any other reasonable other algorithm) would be different if the arrays had the same size. If you start with one array `[1, 2]` then it does't matter if the second array is `[]`, `[3]`, `[3, 4]`, or `[3, 4, 5]`. Any reasonable algorithm would first place the elements `1` and `2` in the result array and then the elements of the seond array. The sizes of the arrays never play any role at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T05:08:39.937", "Id": "468788", "Score": "0", "body": "I know it is wrong. That is the point of asking for the code review. The code and the comments look too focused on something that should not have been an issue. A good rephrasing of the question would be: Merge two sorted arrays. And then, on the description: My code reads like I'm solving two separate problems, so I think I'm missing something. Is there a better way to implement it?" } ]
[ { "body": "<p>I think considering approach that you chose, your code is alright. A few points:</p>\n\n<ul>\n<li><p>What I don't like is that you get error when passing 2 empty arrays? Why would you do that? Imagine I am generating arrays of different sizes and using your code to merge and sometimes I would pass 2 empty arrays. Should I really need to handle that as special case in my code? No, just return empty array too.</p></li>\n<li><p>I'd eliminate <code>targetSize</code> variable and check for <code>j &lt; arr2.length &amp;&amp; i &lt; arr1.length</code> instead.</p></li>\n<li><p>Checking <code>valueToPush</code> for <code>undefined</code> feels a bit off for me. It works, but doesn't really feel right. In many languages you would get something like IndexOutOfRange error or something. Maybe it's idiomatic in Javascript (probably not), but I think nicer and cleaner would be to check if you are still in range of array, ex <code>j &lt; arr2.length</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T15:06:47.720", "Id": "468364", "Score": "1", "body": "Thanks for the comments. 1 and 2 are good points. 3 is what made me post this code here. It works, but doesn't look right to me too. I could not come up with a cleaner solution. Checking for `if(! ValueToPush)` fails because the number 0 evaluates to false in JS, so the code breaks if any of the arrays has a 0. Eliminating the target size and using your index based condition could help me remove this ugly `break` statement and do the remainder operation after the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T15:22:53.687", "Id": "468366", "Score": "0", "body": "Just to be clear, I don't mean just `valueToPush == undefined`, but whole `valueToPush = array1[i]`. Your condition basically checks for \"is one array already done\". I would just do it by checking `i` against array size instead of checking if you got \"undefined\" from array. Also your code won't work if there is actually `undefined` in the array, because your code will recognise it as end of array." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T08:33:16.617", "Id": "238814", "ParentId": "238802", "Score": "4" } }, { "body": "<pre><code>const mergeSortedArrays = (arr1, arr2) =&gt; [...arr1, ...arr2].sort((a,b) =&gt; a-b);\n\nconst ar1 =[-7, 2, 4, 22, 66, 99];\nconst ar2 = [1, 5, 9, 88];\n\nconsole.log( mergeSortedArrays(ar1, ar2) );\n// [ -7, 1, 2, 4, 5, 9, 22, 66, 88, 99 ]\n</code></pre>\n\n<p>I don't know if it's not too simple solution, but one-line Arrow function solves this problem...</p>\n\n<p>OR</p>\n\n<p>in your code instead of IF / ELSE \"Works until completion for arrays of the same size\" you can: </p>\n\n<ul>\n<li>use shorter form ternary operator <code>? :</code></li>\n<li>instantly <code>i++</code> and <code>j++</code> - that means you take element <code>arr[i]</code> and <code>arr[j]</code> and </li>\n</ul>\n\n<p>incrementation follows after this operation</p>\n\n<p><code>valueToPush = ( arr1[i] &lt; arr2[j] ) ? arr1[i++] : arr2[j++]</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T14:57:50.277", "Id": "468363", "Score": "0", "body": "Thanks for the comment. It's algorithm interview practice, so using standard functions kind of misses the point, even though on a real life setting, I'd probably be using the arrow function, spread operator and built in sort too.\n\nThe valueToPush one-liner is pretty cool, didn't know I could increment values inside of array index like this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T11:34:12.483", "Id": "238821", "ParentId": "238802", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T00:20:51.283", "Id": "238802", "Score": "1", "Tags": [ "javascript", "performance", "array", "interview-questions" ], "Title": "Merge two sorted arrays that can be of different sizes" }
238802
<p>I'm a C Beginner and I am looking for feedback on my implementation of a singly linked list. The code is split between <code>list.c</code> and <code>list.h</code>.</p> <p><strong>list.h</strong>:</p> <pre class="lang-c prettyprint-override"><code>#ifndef LIST #define LIST #include &lt;stddef.h&gt; typedef struct List { int val; struct List* next; } List; int list_len(List* head); void list_insert(List* head, int val, int index); void list_insert_end(List* head, int val); void list_insert_all(List* head, int* vals, size_t size); List* array_to_list(int* vals, size_t size); int list_get(List* head, int index); void list_set(List* head, int val, int index); void list_remove(List* head, int index); int list_indexof(List* head, int val); int list_rindexof(List* head, int val); void free_list(List* head); void print_list(List* head); #endif </code></pre> <p><strong>list.c</strong>:</p> <pre class="lang-c prettyprint-override"><code>#include "list.h" #include &lt;assert.h&gt; #include &lt;stddef.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int list_len(List* head) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; int i = 1; while (curr-&gt;next) { curr = curr-&gt;next; i++; } return i; } void list_insert_end(List* head, int val) { assert(head != NULL &amp;&amp; "Empty List"); List* item = malloc(sizeof(List)); item-&gt;val = val; item-&gt;next = NULL; List* curr = head; while (curr-&gt;next) { curr = curr-&gt;next; } curr-&gt;next = item; } void list_insert(List* head, int val, int index) { assert(head != NULL &amp;&amp; "Empty List"); List* item = malloc(sizeof(List)); item-&gt;val = val; if (index == 0) { item-&gt;next = head; head = item; return; } List* prev; List* curr = head; for (int i = 0; i &lt; index; i++) { prev = head; assert(!curr-&gt;next &amp;&amp; "Index Out of Bounds"); curr = curr-&gt;next; } prev-&gt;next = item; item-&gt;next = curr; return; } void list_insert_all(List* head, int* vals, size_t size) { assert(head != NULL &amp;&amp; "Empty List"); for (size_t i = 0; i &lt; size; i++) { list_insert_end(head, vals[i]); } } List* array_to_list(int* vals, size_t size) { List* list = malloc(sizeof(List)); list-&gt;val = vals[0]; list-&gt;next = NULL; list_insert_all(list, vals + 1, size - 1); return list; } int list_get(List* head, int index) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; for (int i = 0; i &lt; index; i++) { assert((curr-&gt;next) != 0 &amp;&amp; "Index Out of Bounds"); curr = curr-&gt;next; } printf("%i", curr-&gt;val); return curr-&gt;val; } void list_set(List* head, int val, int index) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; for (int i = 0; i &lt; index; i++) { assert((curr-&gt;next) != 0 &amp;&amp; "Index Out of Bounds"); curr = curr-&gt;next; } curr-&gt;val = val; } void list_remove(List* head, int index) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; if (index == 0) { head = head-&gt;next; free(curr); return; } for (int i = 0; i &lt; index - 1; i++) { assert((curr-&gt;next) != 0 &amp;&amp; "Index Out of Bounds"); curr = curr-&gt;next; } List* next = curr-&gt;next-&gt;next; free(curr-&gt;next); curr-&gt;next = next; } int list_indexof(List* head, int val) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; int i = 0; while (curr-&gt;next) { if (curr-&gt;val == val) { return i; } i++; curr = curr-&gt;next; } return -1; } int list_rindexof(List* head, int val) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; int i = 0, j = -1; while (curr-&gt;next) { if (curr-&gt;val == val) { j = i; } i++; curr = curr-&gt;next; } return j; } void free_list(List* head) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; List* next; while (curr-&gt;next) { next = curr-&gt;next; free(curr); curr = next; } head = NULL; } void print_list(List* head) { assert(head != NULL &amp;&amp; "Empty List"); List* curr = head; fputs("[", stdout); printf("%i", curr-&gt;val); while (curr-&gt;next) { curr = curr-&gt;next; printf(", %i", curr-&gt;val); } fputs("]", stdout); } int main() { List list = *array_to_list((int[]){1, 2, 3, 4}, 4); list_insert_all(&amp;list, (int[]){1, 2, 3, 4}, 4); list_set(&amp;list, 10, 2); print_list(&amp;list); list_remove(&amp;list, 7); print_list(&amp;list); printf("%i ", list_get(&amp;list, 3)); printf("%i", list_len(&amp;list)); printf(" %i", list_rindexof(&amp;list, 1)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T20:21:06.833", "Id": "468395", "Score": "0", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2" } ]
[ { "body": "<p>in this function:</p>\n\n<pre><code>void list_remove(List* head, int index)\n</code></pre>\n\n<p>there is the statement:</p>\n\n<pre><code>head = head-&gt;next;\n</code></pre>\n\n<p>is a problem as this changes the parameter on the stack, not the actual list</p>\n\n<p>in function: <code>main()</code> this statement:</p>\n\n<pre><code>List list = *array_to_list((int[]){1, 2, 3, 4}, 4);\n</code></pre>\n\n<p>will result in the variable <code>list</code> containing the contents of the first instance of the struct, NOT a pointer to the head of the list</p>\n\n<p>in function: <code>main()</code>, this function call:</p>\n\n<pre><code>list_insert_all(&amp;list, (int[]){1, 2, 3, 4}, 4);\n</code></pre>\n\n<p>results in all the parameters being inserted into the list, however; the earlier call to:</p>\n\n<pre><code>List list = *array_to_list((int[]){1, 2, 3, 4}, 4);\n</code></pre>\n\n<p>also called: <code>list_insert_all()</code>, so the parameters are now in the list twice</p>\n\n<p>in function: <code>list_insert()</code> in the <code>for()</code> loop, this statement:</p>\n\n<pre><code>prev = head;\n</code></pre>\n\n<p>is executed <code>index</code> number of times, however; when <code>index</code> is 0, then that statement is never executed, so the following code:</p>\n\n<pre><code>prev-&gt;next = item;\n</code></pre>\n\n<p>is working with an uninitialized variable <code>prev</code></p>\n\n<p>it is a very poor programming practice to name variables the same as a struct type with the only difference being capitalization. The compiler will not have a problem, but the humans reading the code will have a problem.</p>\n\n<p>I have not examined the rest of the code, but the above should be enough to get you pointed in the right direction</p>\n\n<p>EDIT:</p>\n\n<p>in the function: <code>free_list()</code> the body of the function tries to <code>free()</code> the first entry in the list, however; that first entry is an actual instance of the list node, on the stack in the <code>main()</code> function. Trying to <code>free()</code> something on the stack will result in a crash. This is another good reason to have a 'head' pointer on the stack that points to the first list 'node'</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:48:41.140", "Id": "468382", "Score": "0", "body": "Isn't the 1st instance of the struct equal to the head of the list? Also, there is an if statement to handle index == 0. In OOP languages, I believe it is perfectly fine to have a variable named as the class lowercased. Does C have different naming conventions in this regard?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T20:59:08.143", "Id": "468398", "Score": "0", "body": "in general, there will be a 'head' pointer of type 'your struct node name' which is initialized to NULL. When the first node is added, then the 'head' is modified to point to that first 'node'" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T02:46:59.887", "Id": "238804", "ParentId": "238803", "Score": "2" } }, { "body": "<blockquote>\n <p>looking for feedback on my implementation of a singly linked list.</p>\n</blockquote>\n\n<p><strong>Not enough info in the .h</strong></p>\n\n<p>Consider that the .c file is opaque to the user - they cannot see it. The .h file is a good place to document and provide simply usage notes. Looking at this .h file, I do not know how to properly define a <code>List</code> variable.</p>\n\n<p><strong><code>const</code></strong></p>\n\n<p>Referenced data not changed is best as <code>const</code>. It allows for some additional uses, optimizations and conveys the code's intention.</p>\n\n<pre><code>// int list_len(List* head);\n// List* array_to_list(int* vals, size_t size);\n// void print_list(List* head);\nint list_len(const List* head);\nList* array_to_list(const int* vals, size_t size);\nvoid print_list(const List* head);\n</code></pre>\n\n<p><strong>What happens when ...</strong></p>\n\n<p>Some functions are self documented by name: <code>list_insert_end()</code>. Yet <code>list_insert()</code> deserves more detail. What happens when the index is <em>much</em> more than the list length? </p>\n\n<p>This applies to a number of functions: what do they do?</p>\n\n<p>IOWs, some light documentation in the .h file helps a lot.</p>\n\n<p><strong><code>int</code> or <code>size_t</code></strong></p>\n\n<p>Choose <em>one</em> type, recommend <code>size_t</code>, to handle list size.</p>\n\n<pre><code>vvv\nint list_len(List* head);\nList* array_to_list(int* vals, size_t size);\n ^^^^^^\n</code></pre>\n\n<hr>\n\n<p>.c</p>\n\n<p><strong>Consider allocating to the size of the referenced type</strong></p>\n\n<p>Easier to write correctly, review and maintain.</p>\n\n<pre><code>// list = malloc(sizeof(List));\nlist = malloc(sizeof *list);\n</code></pre>\n\n<p><strong>Good use of first #include is this file's .h</strong> </p>\n\n<pre><code>#include \"list.h\"\n</code></pre>\n\n<p><strong>Size 0</strong></p>\n\n<p><code>array_to_list(int* vals, size_t size)</code> does not handle <code>size == 0</code>. Most (all?) of the code has trouble with an empty list. IMO, this is a fatal design flaw.\nA <code>list</code> should be allowed to be initially empty.</p>\n\n<p>The <code>List list = *array_to_list((int[]){1, 2, 3, 4}, 4);</code> is a novel, yet unclear way to initialize.</p>\n\n<p><strong><code>main()</code></strong></p>\n\n<p>Better to have <code>main()</code> in another file than list.c.</p>\n\n<hr>\n\n<p><strong>Well formatted code</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T23:24:18.063", "Id": "242230", "ParentId": "238803", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T01:13:32.790", "Id": "238803", "Score": "4", "Tags": [ "c", "linked-list" ], "Title": "C Singly Linked List Implementation" }
238803
<p>I've been working on a parser for shop receipts which extracts data about the payment. Here is the text that I'm parsing:</p> <pre> * Vic107Payment Text: PINNEN TicketData: POI: 12345678 KLANTTICKET -------------------------------- Terminal: ABC123 Merchant: 123456 Periode: 1234 Transactie: 12345678 MAESTRO (A0000000012345) MAESTRO Kaart: xxxxxxxxxxxxxxx1234 Kaartserienummer: 0 BETALING Datum: 01/01/2020 04:15 Autorisatiecode: 123ABC Totaal: 1,00 EUR Leesmethode: NFC Chip CardTypeId: 1234 CardTypeText: MAESTRO ReceiptNumber: DrawerAmount: 1,00 Number: 1 DrawerId: drawers/default DrawerNumber: 1 Amount: 1,00 IsCancelable: True ===</pre> <p>Here is the code that parses this fragment from the receipt. Now my concern is that people will find it difficult to read and/or difficult to maintain, so I was wondering whether it could be improved in any way?</p> <pre><code>def parse_card_payment(product): # cp stands for card payment cp_poi = None cp_terminal = None cp_merchant = None cp_period = None cp_transaction = None cp_card = None cp_card_serial_number = None cp_date = None cp_authorisation_code = None cp_total = None cp_card_type_id = None cp_card_type_text = None cp_drawer_id = None cp_drawer_amount = None cp_cancelable = None cp_card_type = None for line in product.strip().split('\n'): if 'POI' in line: cp_poi = line.split(':')[1].strip() elif 'Terminal' in line: cp_terminal = line.split(':')[1].strip() elif 'Merchant' in line: cp_merchant = line.split(':')[1].strip() elif 'Periode' in line: cp_period = line.split(':')[1].strip() elif 'Transactie' in line: cp_transaction = line.split(':')[1].strip() elif 'Kaart:' in line: cp_card = line.split(':')[1].strip() elif 'Kaartserienummer' in line: cp_card_serial_number = line.split(':')[1].strip() elif 'Datum' in line: cp_date = line.split(':')[1].strip() elif 'Autorisatiecode' in line: cp_authorisation_code = line.split(':')[1].strip() elif 'Totaal' in line: cp_total = line.split(':')[1].strip() elif 'CardTypeId' in line: cp_card_type_id = line.split(':')[1].strip() elif 'CardTypeText' in line: cp_card_type_text = line.split(':')[1].strip() elif 'DrawerAmount' in line: cp_drawer_amount = line.split(':')[1].strip() elif 'DrawerId' in line: cp_drawer_id = line.split(':')[1].strip() elif 'Cancelable' in line: cp_cancelable = line.split(':')[1].strip() elif 'Leesmethode' in line: cp_card_type = line.split(':')[1].strip() cp = {'cp_poi': cp_poi, 'cp_terminal': cp_terminal, 'cp_merchant': cp_merchant, 'cp_period': cp_period, 'cp_transaction': cp_transaction, 'cp_card': cp_card, 'cp_card_serial_number': cp_card_serial_number, 'cp_date': cp_date, 'cp_authorisation_code': cp_authorisation_code, 'cp_total': cp_total, 'cp_card_type_id': cp_card_type_id, 'cp_card_type_text': cp_card_type_text, 'cp_drawer_id': cp_drawer_id, 'cp_drawer_amount': cp_drawer_amount, 'cp_cancelable': cp_cancelable, 'cp_card_type': cp_card_type} return cp </code></pre>
[]
[ { "body": "<h1>bugs</h1>\n\n<p>Due to the extra <code>:</code> in the lines, <code>POI</code> and <code>Datum</code> are parsed incorrectly </p>\n\n<pre><code>{'cp_poi': 'POI',\n 'cp_terminal': 'ABC123',\n 'cp_merchant': '123456',\n 'cp_period': '1234',\n 'cp_transaction': '12345678',\n 'cp_card': 'xxxxxxxxxxxxxxx1234',\n 'cp_card_serial_number': '0',\n 'cp_date': '01/01/2020 04',\n 'cp_authorisation_code': '123ABC',\n 'cp_total': '1,00 EUR',\n 'cp_card_type_id': '1234',\n 'cp_card_type_text': 'MAESTRO',\n 'cp_drawer_id': 'drawers/default',\n 'cp_drawer_amount': '1,00',\n 'cp_cancelable': 'True',\n 'cp_card_type': 'NFC Chip'}\n</code></pre>\n\n<h1>alternate approach</h1>\n\n<p>Instead of a giant <code>if-elseif-if</code> tree, I would as a function that parses a line, and returns the type of line with the value.</p>\n\n<pre><code>def parse_line(line):\n \"\"\"\n parses a line on a receipt. \n\n Returns the datafield and value as a tuple \n or tuple with the original text if there is no data on the line\n \"\"\"\n return tuple(part.strip() for part in line.split(': ')[-2:])\n</code></pre>\n\n<p>Note that I split on <code>\": \"</code>. The space makes the parsing of the date correct. The <code>[-2:]</code> selects the last 2 items, making the POI parse correctly.</p>\n\n<pre><code>parsed_results = {\n result[0]: result[1]\n for result in (parse_line(line) for line in text.split(\"\\n\"))\n if len(result) &gt; 1\n}\n</code></pre>\n\n<blockquote>\n<pre><code>{'Text': 'PINNEN',\n 'POI': '12345678',\n 'Terminal': 'ABC123',\n 'Merchant': '123456',\n 'Periode': '1234',\n 'Transactie': '12345678',\n 'Kaart': 'xxxxxxxxxxxxxxx1234',\n 'Kaartserienummer': '0',\n 'Datum': '01/01/2020 04:15',\n 'Autorisatiecode': '123ABC',\n 'Totaal': '1,00 EUR',\n 'Leesmethode': 'NFC Chip',\n 'CardTypeId': '1234',\n 'CardTypeText': 'MAESTRO',\n 'ReceiptNumber': '',\n 'DrawerAmount': '1,00',\n 'Number': '1',\n 'DrawerId': 'drawers/default',\n 'DrawerNumber': '1',\n 'Amount': '1,00',\n 'IsCancelable': 'True'}\n</code></pre>\n</blockquote>\n\n<p>Or you can use regular expressions</p>\n\n<pre><code>import re\n\nPATTERN = re.compile(r\"(?:.*:\\s*)?(\\w+?):\\s+(.*?)\\s*$\")\n\ndef parse_line2(line):\n return PATTERN.findall(line)\n\nparsed_results2 = {\n result[0][0]: result[0][1]\n for result in (parse_line2(line) for line in text.split(\"\\n\"))\n if result\n}\n</code></pre>\n\n<p>In this simple case I would use the first parser method. If the patterns get a little more complicated, You can change to the <code>re</code>.</p>\n\n<h1>translation:</h1>\n\n<p>Here I would use a dictionary that links all keywords in your return dictionary to the keys in the parsed lines:</p>\n\n<pre><code>data_translation = {\n \"cp_poi\": \"POI\",\n \"cp_terminal\": \"Terminal\",\n \"cp_merchant\": \"Merchant\",\n \"cp_period\": \"Periode\",\n \"cp_total\": \"Totaal\",\n \"cp_date\": \"Datum\"\n # ...\n}\n\nresult = {\n keyword: parsed_results.get(key_value, None)\n for keyword, key_value in data_translation.items()\n}\n</code></pre>\n\n<blockquote>\n<pre><code>{'cp_poi': '12345678',\n 'cp_terminal': 'ABC123',\n 'cp_merchant': '123456',\n 'cp_period': '1234',\n 'cp_total': '1,00 EUR',\n 'cp_date': '01/01/2020 04:15'}\n</code></pre>\n</blockquote>\n\n<h1>further parsing.</h1>\n\n<p>Since functions can be values in a dictionary, you can add functions to further process the values. For example convert thetotal to a tuple of <code>value, currency</code>, transform the date from a string to a <code>datetime object,...</code></p>\n\n<pre><code>import decimal\n\ndef parse_amount(amount):\n \"\"\"converts an amount to a tuple of amount, currency\"\"\"\n value, currency = amount.split(\" \")\n value = value.replace(\",\", \".\")\n context = decimal.Context(prec=2, rounding=decimal.ROUND_HALF_UP)\n value_decimal = decimal.Decimal(value, context=context).quantize(\n decimal.Decimal(\"0.01\")\n )\n return value_decimal, currency\n\ndef parse_date(date_str):\n return datetime.datetime.strptime(date_str, \"%d/%m/%Y %H:%M\")\n\nconverters = {\n \"cp_date\": parse_date,\n \"cp_total\": parse_amount\n}\nconverted_result = {\n key: converters.get(key, lambda x: x)(value)\n for key, value in results.items()\n}\n</code></pre>\n\n<blockquote>\n<pre><code>{'cp_poi': '12345678',\n 'cp_terminal': 'ABC123',\n 'cp_merchant': '123456',\n 'cp_period': '1234',\n 'cp_total': (Decimal('1.00'), 'EUR'),\n 'cp_date': datetime.datetime(2020, 1, 1, 4, 15)}\n</code></pre>\n</blockquote>\n\n<h1>other remarks:</h1>\n\n<h2>docstring</h2>\n\n<p>Use a docstring to describe what the method does</p>\n\n<h1>formatting</h1>\n\n<p>I don't like this style of dict literal</p>\n\n<pre><code>cp = {'cp_poi': cp_poi,\n 'cp_terminal': cp_terminal,\n 'cp_merchant': cp_merchant,\n # ...\n 'cp_cancelable': cp_cancelable,\n 'cp_card_type': cp_card_type}\n</code></pre>\n\n<p>I use <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\"><code>black</code></a> with a line length of 79 as automatic formatter</p>\n\n<p>Which turns this into </p>\n\n<pre><code>cp = {\n \"cp_poi\": cp_poi,\n \"cp_terminal\": cp_terminal,\n \"cp_merchant\": cp_merchant,\n # ...\n \"cp_cancelable\": cp_cancelable,\n \"cp_card_type\": cp_card_type,\n}\n</code></pre>\n\n<p>This minimizes the hassle if I want to remove or add a line, also in the git diffs.</p>\n\n<h1>Data structures</h1>\n\n<p>In general, if you needa lot of variables, each only differing in a slight amount, you can use a better data structure. In this case, this is with dicts, instead of the dozen variables and lone if-else tree. Get to know the python data structures, and the different looping arrangements in Python. Almost never is a dozen variables the best solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T10:59:58.587", "Id": "468345", "Score": "0", "body": "Ah, I just noticed the bug as well, but since you already pointed it out, I don't have to anymore :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T13:56:51.313", "Id": "468356", "Score": "0", "body": "I wouldn't even split on the colon or colon-space. Find the first colon, grab everything after that. Splitting on colons, or colon-space, is the wrong thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T13:58:46.663", "Id": "468357", "Score": "0", "body": "for POI the part before the first colon is not needed, and the second colon separates key and value. For date, the second colon is part of the value, so I don't see how your approach would work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T14:54:02.720", "Id": "468360", "Score": "0", "body": "Thank you for pointing out the bug with parsing the lines with double colons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T14:55:40.863", "Id": "468361", "Score": "1", "body": "I combined your approach and the one provided by @Graipher into something that looks more readable. I've just defined the keywords that the parser should be looking for then I translate them to elements in the dictionary." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T10:56:09.183", "Id": "238818", "ParentId": "238805", "Score": "5" } }, { "body": "<p>In programming there is the general principle <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself (DRY)</a>. Your code is a lot of repetition of exactly the same pattern, with only the string changing.</p>\n\n<p>So, just put those strings into a dictionary, with the final variable name as keys:</p>\n\n<pre><code>RECEIPT_ITEMS = {\"cp_poi\": \"POI\", \"cp_terminal\": \"Terminal\",\n \"cp_merchant\": \"Merchant\", \"cp_period\": \"Periode\",\n \"cp_transaction\": \"Transactie\", \"cp_card\": \"Kaart\",\n \"cp_card_serial_number\": \"Kaartserienummer\", \"cp_date\": \"Datum\",\n \"cp_authorisation_code\": \"Autorisatiecode\",\n \"cp_total\": \"Totaal\", \"cp_card_type_id\": \"CardTypeId\", \n \"cp_card_type_text\": \"CardTypeText\",\n \"cp_drawer_amount\": \"DrawerAmount\", \"cp_drawer_id\": \"DrawerId\",\n \"cp_cancelable\": \"Cancelable\", \"cp_card_type\": \"Leesmethode\"}\n\ndef parse_card_payment(product):\n cp = dict.fromkeys(RECEIPT_ITEMS.keys())\n for line in product.splitlines():\n for key, value in RECEIPT_ITEMS.items():\n if value in line:\n cp[key] = line.split(\":\")[1].strip()\n break\n return cp\n</code></pre>\n\n<p>This has the advantage that if you ever have receipts in another language than Dutch (but with the same structure), you only need to localize the values of this dictionary and not change your whole code.</p>\n\n<p>Note that I used <a href=\"https://docs.python.org/3/library/stdtypes.html#str.splitlines\" rel=\"nofollow noreferrer\"><code>str.splitlines</code></a>, which automatically ignores trailing newlines.</p>\n\n<p>A different approach might be to use a multi-line RegEx to perform the search directly, but that will probably be more complicated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T14:56:06.040", "Id": "468362", "Score": "0", "body": "Loved this approach, looks succinct and easily readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T05:39:42.800", "Id": "468439", "Score": "0", "body": "Keep in mind that if more than one variable name appears in the same line, only the \"first\" (where \"first\" is determined by what order Python decides to retrieve the key/value pairs in) will be seen. If any variable names are a subset of another, that could be a problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T10:58:35.460", "Id": "238819", "ParentId": "238805", "Score": "10" } } ]
{ "AcceptedAnswerId": "238819", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T03:12:54.633", "Id": "238805", "Score": "4", "Tags": [ "python", "parsing" ], "Title": "Parsing a shop receipt" }
238805
<p>Im making an application that i want to have the ability to send report emails with a frequency. daily, weekly or monthly. </p> <p>Now i want those emails to be sent only if the app is running and if the user is using it (in my app you use the mobile as a kiosk, you open the app and leave it running all the time, screen will not close)</p> <p>I have write this code in the MainActivity where if someone has enabled the frequently email feature, the activity will try to send the email (<strong>SendStatisticsToEmailBySchedule()</strong> will run forever and will use <strong>SendStatisticsToEmail()</strong> from time to time to send an email):</p> <pre><code>public async void SendStatisticsToEmail(string subject, string address, int port, string from, string to, bool useSSL, bool saveDateSent = false, string username = "", string password = "", bool sendNowButtonUsed = false) { var fileName = System.IO.Path.Combine( GetString(Resource.String.Statistics_ExportAllExportPrefix, firstResult.ToString("MM-dd-yyyy"), DateTime.Today.ToString("MM-dd-yyyy"))); var message = new MimeMessage(); message.From.Add(new MailboxAddress(from)); message.To.Add(new MailboxAddress(to)); message.Subject = subject + " " + fileName; var statistics = new Statistics(); var reportsForXML = statistics.ConvertRecordsForExport(MyData); MemoryStream stream = new MemoryStream(); var builder = new BodyBuilder(); var image = BitmapFactory.DecodeResource(Resources, Resource.Drawable.get_started); byte[] imgbyte; using (var bitmap = image) { var streamByte = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 100, streamByte); bitmap.Recycle(); imgbyte = streamByte.ToArray(); } var imageAttach = builder.LinkedResources.Add(@"get_started.png", imgbyte); imageAttach.ContentId = MimeUtils.GenerateMessageId(); builder.HtmlBody = string.Format(@"&lt;p align=""center""&gt;&lt;center&gt;&lt;img height=""150"" width=""328"" src=""cid:{0}""&gt;&lt;/center&gt;&lt;/p&gt;&lt;p align=""center""&gt;{1}&lt;/p&gt;&lt;p align=""center""&gt;{2}&lt;/p&gt;&lt;p align=""center""&gt;{3}&lt;/p&gt;", new object[] { imageAttach.ContentId, GetString(Resource.String.EmailExportSettings_MessageBodyLine1), GetString(Resource.String.EmailExportSettings_MessageBodyLine2), GetString(Resource.String.EmailExportSettings_MessageBodyLine3) }); using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream)) { reportsForXML.WriteXml(writer, XmlWriteMode.WriteSchema, false); stream.Position = 0; builder.Attachments.Add(fileName, stream); } message.Body = builder.ToMessageBody(); try { using (var client = new SmtpClient()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) =&gt; true; if (useSSL) await client.ConnectAsync(address, port, SecureSocketOptions.SslOnConnect); else await client.ConnectAsync(address, port, false); // Note: only needed if the SMTP server requires authentication if (!string.IsNullOrEmpty(username) &amp;&amp; !string.IsNullOrEmpty(password)) client.Authenticate(username, password); await client.SendAsync(message); await client.DisconnectAsync(true); if (saveDateSent) { Preferences.Set(Settings.ExportToEmailLastEmailSentKey, DateTime.Now); ScheduleNextEmailForSend(DateTime.Now, Preferences.Get(Settings.ExportToEmailEmailFrequencyPositionKey, Settings.ExportToEmailEmailFrequencyPositionDefault) ); } if (sendNowButtonUsed) Toast.MakeText(this, GetString(Resource.String.Statistics_EmailSendSuccess), ToastLength.Long).Show(); } } catch //(Exception exception) { if (sendNowButtonUsed) Toast.MakeText(this, GetString(Resource.String.Statistics_EmailSendFailure), ToastLength.Long).Show(); } } private void ScheduleNextEmailForSend(DateTime nextScheduledEmailDate, int frequency) { nextScheduledEmailDate = DateTime.Now; frequency = Preferences.Get(Settings.ExportToEmailEmailFrequencyPositionKey, Settings.ExportToEmailEmailFrequencyPositionDefault); switch (frequency) { case 0: Preferences.Set(Settings.ExportToEmailNextEmailForKey, nextScheduledEmailDate.AddDays(1)); break; case 1: Preferences.Set(Settings.ExportToEmailNextEmailForKey, nextScheduledEmailDate.AddDays(7)); break; case 2: Preferences.Set(Settings.ExportToEmailNextEmailForKey, nextScheduledEmailDate.AddDays(30)); break; } } </code></pre> <p>This the the code that will run forever</p> <pre><code>private async void SendStatisticsToEmailBySchedule() { do { if (MyData.Count != 0) { var currentConnectivity = Connectivity.NetworkAccess; NextScheduledDateForReport = Preferences.Get(Settings.ExportToEmailNextEmailForKey, CurrentDateSettings.ExportToEmailNextEmailForDefault); if (DateTime.Now &gt; NextScheduledDateForReport) { if (currentConnectivity == NetworkAccess.Internet) { try { SendStatisticsToEmail(Preferences.Get(Settings.ExportToEmailSubjectKey, Settings.ExportToEmailSubjectDefault), Preferences.Get(Settings.ExportToEmailServerAddressKey, Settings.ExportToEmailServerAddressDefault), Preferences.Get(Settings.ExportToEmailPortKey, Settings.ExportToEmailPortDefault), Preferences.Get(Settings.ExportToEmailFromKey, Settings.ExportToEmailFromDefault), Preferences.Get(Settings.ExportToEmailToKey, Settings.ExportToEmailToDefault), Preferences.Get(Settings.ExportToEmailUseSSLKey, Settings.ExportToEmailUseSSLDefault), true, Preferences.Get(Settings.ExportToEmailUsernameKey, Settings.ExportToEmailUsernameDefault), Preferences.Get(Settings.ExportToEmailPasswordKey, Settings.ExportToEmailPasswordDefault) ); } catch { } } } } await Task.Delay(21600); } while (true); } </code></pre> <p>From what i have read here <a href="https://developer.android.com/guide/components/services#Choosing-service-thread" rel="nofollow noreferrer">https://developer.android.com/guide/components/services#Choosing-service-thread</a> if you want to run some code only while the user is using your app, you should not use a service.</p> <p>Is my code on <strong>SendStatisticsToEmailBySchedule()</strong> efficient? </p> <p>Is there any situation that will stop working or should i somehow check that it is still working?</p>
[]
[ { "body": "<p>It's better to use a <strong>System.Timers.Timer</strong> for this job and the best way is to create it on <strong>OnCreate</strong>, pause it on <strong>OnPause</strong> and resume it on <strong>OnResume</strong></p>\n\n<pre><code>protected override void OnCreate()\n{\nif(Timer_Is_Needed)\n SendStatisticsToEmailBySchedule();\n}\n\nprotected override void OnResume()\n {\n StartSendStatisticsToEmailByScheduleTimer();\n}\n\nprivate void SendStatisticsToEmailBySchedule()\n {\n SendStatisticsToEmailByScheduleTimer = new System.Timers.Timer\n {\n Interval = 3600000,\n Enabled = true,\n AutoReset = true,\n };\n SendStatisticsToEmailByScheduleTimer.Elapsed +=\n new System.Timers.ElapsedEventHandler(OnSendStatisticsToEmailByScheduleTimerEvent);\n SendStatisticsToEmailByScheduleTimer.Start();\n }\n\n private void StopSendStatisticsToEmailByScheduleTimer()\n {\n if (SendStatisticsToEmailByScheduleTimer != null)\n if (SendStatisticsToEmailByScheduleTimer.Enabled == true)\n SendStatisticsToEmailByScheduleTimer.Stop();\n }\n\n private void StartSendStatisticsToEmailByScheduleTimer()\n {\n if (SendStatisticsToEmailByScheduleTimer != null)\n if (SendStatisticsToEmailByScheduleTimer.Enabled == false)\n SendStatisticsToEmailBySchedule();\n }\n protected override void OnPause()\n {\n StopSendStatisticsToEmailByScheduleTimer();\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T09:54:22.557", "Id": "238877", "ParentId": "238815", "Score": "1" } }, { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p><code>SendStatisticsToEmail()</code> is a <em>75 line</em> method with almost <em>a dozen arguments</em> and it does waaay too much. Split this method up into smaller methods -- for instance: one that gets the fileName, one that composes the body, etc. -- that do one single thing, and instead of passing so many arguments, pass a single class that has all these arguments as properties. </p>\n\n<p>(See for instance <a href=\"https://softwareengineering.stackexchange.com/q/27798/123339\">https://softwareengineering.stackexchange.com/q/27798/123339</a> on the \"ideal\" method length. Sure, this is personal and debatable, but once you need to scroll to read through the contents of a method you're probably on the wrong path and you'll need to refactor things.)</p>\n\n<p>Case in point: your method contains ten lines that are dedicated to converting an image into bytes. This should clearly be a method of its own instead of being chucked in the middle of this overlong mess. Another example: on line 17 you say <code>var builder = new BodyBuilder();</code> and then you don't use <code>builder</code> until line 27. This indicates a severe lack of structure and program flow.</p>\n\n<p>Even better: consider converting <code>SendStatisticsToEmail()</code> into a class with one <code>public</code> method and several <code>private</code> ones, instead of it being one method among many. You might even consider converting some of those <code>private</code> methods into classes of their own.</p></li>\n<li><p>One of the lines in <code>SendStatisticsToEmail()</code> is 450 characters long. This is unreadable and impossible to maintain. Even if you were to introduce some line-breaks, it would still be far too hard to maintain. Also, your email's body should really contain better HTML than what you currently offer. </p>\n\n<p>Instead, consider moving your email template to an embedded HTML file, with its variables to be filled in replaced by placeholders like <code>_ContentId_</code>. You read the embedded file into a string, and then have a method that loops through a <code>Dictionary&lt;string, string&gt;</code> where the keys are those placeholders and the values are the actual values.</p></li>\n<li><p>Why is the <code>if (saveDateSent)</code> logic inside the <code>using (var client = new SmtpClient())</code> block? Ditto <code>if (sendNowButtonUsed)</code>. These do not belong there. The whole <code>using (var client = new SmtpClient())</code> should be a method or even a class of its own, and that should return a <code>bool</code> to indicate success or failure, and that <code>bool</code> should then be used to trigger the logic the <code>if (saveDateSent)</code> logic and the <code>if (sendNowButtonUsed)</code> logic (and the UI logic now residing in the <code>catch</code> block).</p></li>\n<li><p>Avoid mixing UI elements into methods that should stay free of them. Sure, you need to report back on the success of sending an email to the user, but not from <em>inside</em> a convoluted method. Things like sending emails, calling the API etc. should be part of a service layer.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T20:51:44.793", "Id": "471702", "Score": "0", "body": "thank you very much for your comment, i had recently participate in MVC programming in a company and all those suggestions you said was among the first things i notice, I have a question however, you said in the first paragraph, i should make a class and pass all those arguments in the class. Why is this approach better from passing arguments to the method? i guess because all the needed code will be in a new class.\n\nAlso i have too tried to split better the code but i was getting a lot of exceptions i think because of the Context the android need to pass. I might was doing something wrong" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T07:19:00.210", "Id": "471728", "Score": "0", "body": "Because that way you're less likely to make mistakes, and it makes it easier to adapt the method. New argument? Simply add it to the class, no need to update all use of the method. You're also less likely to confuse the various arguments. See also: https://softwareengineering.stackexchange.com/a/145066/123339" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T16:54:54.100", "Id": "240453", "ParentId": "238815", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T08:36:46.927", "Id": "238815", "Score": "1", "Tags": [ "c#", "android" ], "Title": "Android - Running endless code in Foreground while using the app" }
238815
<p>Here is a simple variant type I have made. For simplicity, it only can handle two different values. I am planning on using this to create a variadic variant template, using inheritance and recursion.</p> <p>The requirements for my variant type:</p> <ul> <li>It must have performance similar to <code>std::variant</code></li> <li>It must not dynamically allocate memory</li> <li>There must be no undefined behavior</li> <li>It should check as much as possible at compile-time, and throw an exception if access is attempted to the wrong type</li> <li>It must support nontrivial types</li> </ul> <p>Here is the source:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstddef&gt; #include &lt;typeindex&gt; #include &lt;optional&gt; #include &lt;algorithm&gt; #include &lt;stdexcept&gt; #include &lt;functional&gt; /** A variant (sum type) that can contain one of two different types at any one time**/ template&lt;typename T1, typename T2&gt; class Either { using Bigest = std::conditional_t&lt;sizeof(T1) &lt;= sizeof(T2), T1, T2&gt;; alignas(sizeof(Bigest)) std::byte storage[sizeof(Bigest)]; std::optional&lt;std::type_index&gt; conatinedType; std::function&lt;void(std::byte*)&gt; destructor; public: Either() : conatinedType(std::nullopt) {} template&lt;typename T&gt; Either(const T&amp; value) : conatinedType(typeid(T)) { static_assert(std::is_same&lt;T1,T&gt;::value || std::is_same&lt;T2,T&gt;::value, "Either cannot contain type T"); const auto src = reinterpret_cast&lt;const std::byte*&gt;(&amp;value); for(size_t i = 0; i &lt; sizeof(T); i++) { storage[i] = src[i]; } destructor = [](std::byte* data){ (*reinterpret_cast&lt;T*&gt;(data)).~T(); }; } class BadVariantAccess : public std::exception {}; template&lt;typename T&gt; const T&amp; getAs() const { static_assert(std::is_same&lt;T1,T&gt;::value || std::is_same&lt;T2,T&gt;::value, "Either cannot contain type T"); if(conatinedType == typeid(T)) { const auto ptr = reinterpret_cast&lt;const T*&gt;(&amp;storage); return *ptr; } else throw BadVariantAccess(); }; }; </code></pre> <p>And a test:</p> <pre><code>struct MyInt { int val; MyInt(const int&amp; val) : val(val) { std::cout &lt;&lt; "making int!" &lt;&lt; std::endl; } ~MyInt() { std::cout &lt;&lt; "destructing int!" &lt;&lt; std::endl; } }; struct MyDouble { double val; MyDouble(const double&amp; val) : val(val) { std::cout &lt;&lt; "making double!" &lt;&lt; std::endl; } ~MyDouble() { std::cout &lt;&lt; "destructing double!" &lt;&lt; std::endl; } }; int main() { Either&lt;MyInt, MyDouble&gt; e = MyDouble(5.0987); try{ std::cout &lt;&lt; e.getAs&lt;MyDouble&gt;().val &lt;&lt; std::endl; } catch(...) { std::cerr &lt;&lt; "Bad Variant Access" &lt;&lt; std::endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T12:51:27.580", "Id": "468350", "Score": "1", "body": "You can of course name your variables as you like, but personally, it would annoy me to see misspellings all the time: `conatinedType` -> `containedType`, `Bigest` -> `Biggest`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T07:42:20.367", "Id": "468447", "Score": "0", "body": "Welcome to Code Review! Can you tag the question will the revision of the C++ standard you are using (c++17, etc.)? I'll write a review for you when I have time. You can take the [tour] and visit our [FAQs](https://codereview.meta.stackexchange.com/questions/tagged/faq?tab=Votes) to further familiarize yourself our community." } ]
[ { "body": "<h1>Construction and destruction of non-trivial types</h1>\n\n<p>Unfortunately, your class does not really support non-trivial types, because your class copies the <em>representation</em> of the supplied values and instead of invoking the proper copy constructor. In other words, you create no object in the <code>Either</code> class, so the behavior of <code>reinterpret_cast</code>ing the storage and calling the destructor is undefined.</p>\n\n<p>Interestingly, you store the <code>destructor</code> function object but never actually call it, so the class ends up working for trivial types, which do not require invocations to the corresponding constructor or destructor. However, making your code work by letting two errors cancel out each other is not really a good idea.</p>\n\n<p>The copy and move semantics of your class is also broken. We'll try to fix this problem later.</p>\n\n<h1>Use of runtime type information (<code>typeid</code>)</h1>\n\n<p>The usage of <code>typeid</code> is a bit overkill here and not optimal, because it forces the user to pass exactly the same type as one of the stored types, disallowing conversions. In fact, simply storing an index seems to suffice.</p>\n\n<p><code>std::variant</code> <a href=\"https://timsong-cpp.github.io/cppwp/n4659/variant.ctor#12\" rel=\"nofollow noreferrer\">uses overload resolution</a> to deduce the type, which is hard to implement. You may consider supporting <code>in_place</code> construction. (On the other hand, <code>std::variant</code> is typically implemented with unions because of <code>constexpr</code> requirements.)</p>\n\n<h1>The storage</h1>\n\n<blockquote>\n<pre><code>using Bigest = std::conditional_t&lt;sizeof(T1) &lt;= sizeof(T2), T1, T2&gt;;\nalignas(sizeof(Bigest)) std::byte storage[sizeof(Bigest)];\nstd::optional&lt;std::type_index&gt; conatinedType;\nstd::function&lt;void(std::byte*)&gt; destructor;\n</code></pre>\n</blockquote>\n\n<p>Consider using <a href=\"https://en.cppreference.com/w/cpp/types/aligned_storage\" rel=\"nofollow noreferrer\"><code>std::aligned_storage</code></a>. As I said above, we can simply store an index.</p>\n\n<pre><code>using storage_type = std::aligned_storage_t&lt;std::max( sizeof(T1), sizeof(T2)),\n std::max(alignof(T1), alignof(T2))&gt;;\nstorage_type storage;\nstd::size_t index;\n</code></pre>\n\n<p>For valueless variants, we can provide a special index:</p>\n\n<pre><code>static constexpr std::size_t npos = std::numeric_limits&lt;std::size_t&gt;::max();\n</code></pre>\n\n<h1>The constructors</h1>\n\n<p>The default constructor of <code>std::variant</code> default-constructs the first alternative type. You can go into the valueless state instead:</p>\n\n<pre><code>Either() noexcept\n : index{npos}\n{\n}\n</code></pre>\n\n<p>Here's how you'd support in place constructors:</p>\n\n<pre><code>template &lt;std::size_t I, typename... Args&gt;\nexplicit Either(std::in_place_t&lt;I&gt;, Args&amp;&amp;... args)\n{\n construct&lt;I&gt;(std::forward&lt;Args&gt;(args)...);\n}\n\ntemplate &lt;std::size_t I, typename U, typename... Args&gt;\nexplicit Either(std::in_place_t&lt;I&gt;, std::initializer_list&lt;U&gt; ilist, Args&amp;&amp;... args)\n{\n construct&lt;I&gt;(ilist, std::forward&lt;Args&gt;(args)...);\n}\n</code></pre>\n\n<p>where the private member function template <code>construct</code> is defined like</p>\n\n<pre><code>template &lt;std::size_t I&gt;\nstruct alternative_type {\n static_assert(I &lt; 2);\n using type = std::conditional_t&lt;I == 0, T1, T2&gt;;\n};\ntemplate &lt;std::size_t I&gt;\nusing alternative_type_t = typename alternative_type&lt;I&gt;::type;\n\n// not exception safe\ntemplate &lt;std::size_t I, typename... Args&gt;\nvoid construct(Args&amp;&amp;... args)\n{\n index = I;\n ::new (static_cast&lt;void*&gt;(&amp;storage))\n alternative_type_t&lt;I&gt;(std::forward&lt;Args&gt;(args));\n}\n</code></pre>\n\n<h1>Special member functions</h1>\n\n<p>As I said before, you need to implement the copy/move/destruction operations. Here's the copy constructor for example: (SFINAE and <code>explicit</code> issues are omitted for simplicity.)</p>\n\n<pre><code>Either(const Either&amp; other)\n{\n if (other.index == 0) {\n construct&lt;T1&gt;(other.get&lt;0&gt;());\n } else if (other.index == 1) {\n construct&lt;T2&gt;(other.get&lt;1&gt;());\n } else {\n index = npos;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T10:00:56.017", "Id": "238878", "ParentId": "238820", "Score": "2" } } ]
{ "AcceptedAnswerId": "238878", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T11:28:44.370", "Id": "238820", "Score": "3", "Tags": [ "c++", "c++17", "variant-type" ], "Title": "C++ My implementation of a simple sum type (variant)" }
238820
<p><strong><em>Short and sweet...</em></strong></p> <p>I wrote a cross-thread method that displays the countdown [in seconds] of a delay on a label.</p> <p>I'm fairly confident it's far from optimal, so I'm in need of that glorious optimization advice.</p> <pre><code>private async Task SnoozeAsync(int seconds) { for (var i = 0; i &lt; seconds; i++) { Invoke((MethodInvoker)(() =&gt; statusLabel.Text = $"Waiting {seconds - i} seconds...")); await Task.Delay(1000); } } await SnoozeAsync(60); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T20:11:38.957", "Id": "468896", "Score": "0", "body": "Is using a timer an option ?" } ]
[ { "body": "<p><code>Invoke</code> is a <em>blocking</em> call that returns only <em>after</em> that call has competed. </p>\n\n<p>That means your loop is also including the time it takes to marshal over to the GUI thread and complete. You probably don't want that.</p>\n\n<p>I would use <code>BeginInvoke</code> instead, which does not wait for the method to complete on the GUI thread.</p>\n\n<p>This is also the difference between <code>SynchronizationContext</code> methods <code>Post</code> and <code>Send</code>.</p>\n\n<p>I would also prevent <code>await</code> from potentially capturing the current <code>SynchronizationContext</code> using <code>ConfigureAwait(false)</code>.</p>\n\n<p>To protect against exceptions if the control is disposed of (happens on form close and for other reasons) I'd add an <code>IsDisposed</code> check.</p>\n\n<p>Finally I would allow this <code>Task</code> to be <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads\" rel=\"nofollow noreferrer\">cancelled</a> as a matter of best practices using a <code>CancellationToken</code>.</p>\n\n<pre><code>private async Task SnoozeAsync(int seconds, CancellationToken token)\n{\n for (var i = 0; i &lt; seconds; i++)\n {\n if (token.IsCancellationRequested)\n break;\n BeginInvoke((MethodInvoker)(() =&gt; \n {\n if (!statusLabel.IsDisposed)\n statusLabel.Text = $\"Waiting {seconds - i} seconds...\";\n }));\n await Task.Delay(1000, token).ConfigureAwait(false);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-24T02:46:28.480", "Id": "469448", "Score": "0", "body": "You should add in the missing closing parenthesis for BeginInvoke." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-25T01:30:15.243", "Id": "469507", "Score": "0", "body": "@Owen Fixed, thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:59:16.470", "Id": "239066", "ParentId": "238825", "Score": "4" } } ]
{ "AcceptedAnswerId": "239066", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T13:00:28.637", "Id": "238825", "Score": "2", "Tags": [ "c#", "performance", "multithreading", "async-await" ], "Title": "Cross-thread label countdown" }
238825
<p>Peter loves dices and some special numbers. Therefore he thrown dice n times and concatenate the numbers. Compute the probability that if he throws 6 to 27 seven times dice and concatenate the numbers, the sequence contains at least one subsequence of number sequence </p> <pre><code>1, 2, 3, 4, 5, 6 1, 1, 2, 2, 3, 3 4, 4, 5, 5, 6, 6 1, 1, 1, 2, 2, 2 3, 3, 3, 4, 4, 4 5, 5, 5, 6, 6, 6 1, 1, 1, 1, 1, 1 2, 2, 2, 2, 2, 2 3, 3, 3, 3, 3, 3 4, 4, 4, 4, 4, 4 5, 5, 5, 5, 5, 5 6, 6, 6, 6, 6, 6 </code></pre> <p>I saw that there is a way to do it by Markov chains. Is there any way to write the code more elegantly, like using inclusion-exclusion principle?</p> <p>My code that uses Markov chains:</p> <pre><code>from sets import Set def matMul(a,b): zip_b = zip(*b) return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b)) for col_b in zip_b] for row_a in a] """Matrix power for positive integer power""" def matPow(a, n): if n&lt;1: return None if n==1: return a if n%2==0: aToHalfN = matPow(a, n/2) return matMul(aToHalfN, aToHalfN) else: return matMul(matPow(a, n-1), a) def getProbSomeSeqIsSub(symbols, seqs, n, exactRational=False): def cleanSeqs(arr): ret = list(arr) changed = True while changed: changed = False for x in ret: hadADelete = False for y in ret: if x!=y and y in x: ret.remove(x) hadADelete = True changed = True break if hadADelete: break return ret seqs = cleanSeqs(seqs) symbolsLen = len(symbols) prefixes = Set([""]) #first state is '' empty start state for seq in seqs: for i in xrange(1, len(seq)): prefixes.add(seq[0:i]) prefixes = sorted(list(prefixes)) M = len(prefixes)+1 #last state (index M-1) is the absorbing one def findFallsBackTo(appendedRun): for i in xrange(0,len(appendedRun)): if appendedRun[i:] in prefixes: return appendedRun[i:] return "" def incrState(stateDict, state): if state in stateDict: stateDict[state] += 1 else: stateDict[state] = 1 def someEndInSeqs(s): for i in xrange(len(s)): if s[i:] in seqs: return True return False def getToStateVals(stateStr): ret = {} for i in symbols: stPlusI = stateStr+str(i) if someEndInSeqs(stPlusI): incrState(ret, M-1) elif stPlusI in prefixes: incrState( ret, prefixes.index(stPlusI) ) else: fallsToPrefix = findFallsBackTo(stPlusI) incrState(ret, prefixes.index(fallsToPrefix)) return ret a = [] aInts = [] for i in xrange(M): a += [[]] aInts += [[]] for j in xrange(M): a[i] += [0] aInts[i] += [0] for i in xrange(M-1): ps = getToStateVals(prefixes[i]) for toI in ps: a[toI][i] = float(ps[toI])/symbolsLen aInts[toI][i] = ps[toI] a[M-1][M-1] = 1.0 aInts[M-1][M-1] = symbolsLen if exactRational: return str(matPow(aInts, n)[M-1][0])+" / "+str(symbolsLen**n) else: return matPow(a, n)[M-1][0] for i in range(6,28): a = getProbSomeSeqIsSub([1,2,3,4,5,6], ["123456", "112233", "445566", "111222", "333444", '555666', '111111', '222222', '333333', '444444', '555555', '666666'], i, True) b = a.split("/") oso = int(b[0]) nimi = int(b[1]) print(str(i)+ " "+str(oso*6**i/nimi)) </code></pre>
[]
[ { "body": "<h2>Use numpy!</h2>\n\n<p>Don't roll your own <code>matMul</code>. It's not worth it. <code>numpy</code> will outperform you and will be simpler to use. The same goes for <code>matPow</code>, though (I'm not sure) you may still need to write a thin wrapper around numpy.</p>\n\n<h2>Python names</h2>\n\n<p>Use snake_case for functions and variables, such as</p>\n\n<p><code>get_sub_prob</code></p>\n\n<h2>Make a <code>main</code> function</h2>\n\n<p>...to pull your last six lines out of global scope.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T19:17:00.377", "Id": "238898", "ParentId": "238828", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T13:33:00.730", "Id": "238828", "Score": "2", "Tags": [ "python", "combinatorics" ], "Title": "Count number of ways that sequences contain at least one of the given subsequences" }
238828
<p>It appears to me that this has been before in all languages except dart...</p> <p>Referenced in order btw, any improvements, any tips, any feed back would be appreciated...</p> <pre><code>// The Goal: raise (x + 1) to a power and get a list of strings output final int power = 6; //determines which power final String firstVar = "y"; // final int secondNumber = 1; void main() { //reference first List&lt;List&lt;double&gt;&gt; pyrmide = [ [1], // anything to the power of zero is one [1,1]]; // needs [1,1] to work properly //reference second for(int i = 1; i &lt; power // this builds the pyrmide ; i += 1) { List&lt;double&gt; nextLayer = [1,1]; // outside numbers for(int j = 0; j &lt; (pyrmide.length - 1); // finds inside numbers j += 1) { nextLayer .insert(j + 1, pyrmide[i][j] + pyrmide[i][j + 1] // finds number from the above layers ); } pyrmide.add(nextLayer); // adds to the pyrmide next layer to be found } List&lt;String&gt; output = []; // will output something similar to ["x^2", "2x", "1"] //reference third for(int k = 0; // k finds the power of secondvar k &lt; pyrmide.length; k += 1) { int l = power - k; // finds the power of firstvar if (l != 0 &amp;&amp; k != 0) // don't want x^0 or 1x^power { output.add("${(pyrmide[power][k]*secondNumber).toString()}$firstVar^${l.toString()}"); } else if (l == 0) { output.add("${(pyrmide[power][k] * secondNumber).toString()}"); } else if (k == 0) { output.add("$firstVar^$l"); } } print(output); } /* it turns that pyrmides predicts powers of (x+1) power of zero: 1 power of one: 1,1 (x + 1) power of two: 1, 2, 1 (x^2 + 2x + 1) */ /* write the pyrmide down, the outside numbers are always one you only have to find 1 inside number for the power of 2, 2 inside numbers for power of 3, so on */ /* every term in any power of (x + 1) will always have its sum of the powers inside of it equal the power you raised (x + 1) to get to it*/ <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T13:56:40.690", "Id": "238829", "Score": "1", "Tags": [ "dart" ], "Title": "Finding powers of (x+1)" }
238829
<p>My code works, but it looks very bad.</p> <p>I need to move <code>.xlsx</code> files from the previous days from one folder to another, but I should'nt move the files with today's date, just the files from previous days.</p> <p>In my current code, I am moving the files by specifying each one of them with a Minus X days, but I think the code is not in the best 'shape' nor the best performance/quality.</p> <p>Any one can help me improve it?</p> <pre><code>import datetime,os, glob, shutil from pathlib import Path dir_carteiras = r"C:\Users\GuilhermeMachado\Documents\Carteiras" test = os.listdir(dir_carteiras) for item in test: if item.endswith(".jpg"): os.remove( os.path.join(dir_carteiras, item)) #get todays date and a calculation for today -1 day today=datetime.date.today() minus_one_day=datetime.timedelta(days=-1) #use the calculation to get previous 5 days strings d_N1=today+minus_one_day d_N1_ = d_N1.strftime('%Y.%m.%d') d_N2=d_N1+minus_one_day d_N3=d_N2+minus_one_day d_N4=d_N3+minus_one_day d_N5=d_N4+minus_one_day #format dates for the files formats Date_Carteira_N1 = d_N1.strftime('%d_%m_%Y') Date_Carteira__0 = today.strftime('%d_%m_%Y') Date_Carteira_N2 =d_N2.strftime('%d_%m_%Y') Date_Carteira_N3 =d_N3.strftime('%d_%m_%Y') Date_Carteira_N4 =d_N4.strftime('%d_%m_%Y') Date_Carteira_N5 =d_N5.strftime('%d_%m_%Y') Alocacao_0 = today.strftime('%Y%m%d') Alocacao_N1 = d_N1.strftime('%Y%m%d') Alocacao_N2 = d_N2.strftime('%Y%m%d') Alocacao_N3 = d_N3.strftime('%Y%m%d') Alocacao_N4 = d_N4.strftime('%Y%m%d') Alocacao_N5 = d_N5.strftime('%Y%m%d') #folder destination NewFolderPath = dir_carteiras+"\Historico" Path(NewFolderPath).mkdir(parents=True, exist_ok=True) #Move the "Carteira" files from previous 5 days Carteiras_move_N1 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N1+'.xlsx', recursive=True) for f in Carteiras_move_N1: shutil.move(f,NewFolderPath) Carteiras_move_N2 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N2+'.xlsx', recursive=True) for f in Carteiras_move_N2: shutil.move(f,NewFolderPath) Carteiras_move_N3 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N3+'.xlsx', recursive=True) for f in Carteiras_move_N3: shutil.move(f,NewFolderPath) Carteiras_move_N4 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N4+'.xlsx', recursive=True) for f in Carteiras_move_N4: shutil.move(f,NewFolderPath) Carteiras_move_N5 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N5+'.xlsx', recursive=True) for f in Carteiras_move_N5: shutil.move(f,NewFolderPath) #Move the "Alocacao" files from the previous 5 days Alocacao_move_N1 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N1+'.xlsx', recursive=True) for f in Alocacao_move_N1: shutil.move(f,NewFolderPath) Alocacao_move_N2 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N2+'.xlsx', recursive=True) for f in Alocacao_move_N2: shutil.move(f,NewFolderPath) Alocacao_move_N3 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N3+'.xlsx', recursive=True) for f in Alocacao_move_N3: shutil.move(f,NewFolderPath) Alocacao_move_N4 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N4+'.xlsx', recursive=True) for f in Alocacao_move_N4: shutil.move(f,NewFolderPath) Alocacao_move_N5 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N5+'.xlsx', recursive=True) for f in Alocacao_move_N5: shutil.move(f,NewFolderPath) </code></pre>
[]
[ { "body": "<p>First, if you are using Python 3, you can use <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> to make your life regarding paths a lot easier (especially if you want your scripts to work on both Windows and Linux). If you are not using Python 3 by now, well, you should.</p>\n\n<p>While your approach works (and could be made a bit shorter maybe using a complex RegEx), you might want to look into different methods of doing this. Instead of manually using the format of your file names, you can use the time the file was last modified (or accessed) and just filter on that:</p>\n\n<pre><code>from datetime import datetime, timedelta\nfrom pathlib import Path\nimport shutil\nfrom typing import Iterable\n\ndef old_files(dir: Path, pattern: str, start: int = -5, end: int = -1) -&gt; Iterable[Path]:\n \"\"\"List all files in `dir` matching `pattern` modified between\n `start` and `end` (both inclusive) days from today.\n \"\"\"\n today = datetime.today()\n start = (today.replace(hour=0, minute=0, second=0, microsecond=0)\n + timedelta(days=start)).timestamp()\n end = (today.replace(hour=23, minute=59, second=59, microsecond=999999)\n + timedelta(days=end)).timestamp()\n return (file for file in dir.glob(pattern)\n if file.is_file() and start &lt;= file.stat().st_mtime &lt;= end)\n</code></pre>\n\n<p>Which you can use like this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n dir = Path(r\"C:\\Users\\GuilhermeMachado\\Documents\\Carteiras\")\n new_dir = dir / \"Historico/\"\n new_dir.mkdir(exist_ok=True)\n for file in old_files(dir, \"*.xlsx\", start=-5, end=-1)\n shutil.move(str(file), new_dir)\n</code></pre>\n\n<p>Note that I used the fact that when you divide a path by a string (`dir / \"Historico\") it just joins the path (with the correct path separator depending on your OS).</p>\n\n<p>I also added a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without the code running, made the number of days to select parameters of a function to which I also added typing hints and a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> and followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, by having spaces around the <code>=</code> for assignments.</p>\n\n<p>Of course this assumes that you have no <em>other</em> Excel spreadsheets modified during the last five days in that folder. In that case you might be able to adapt the pattern to only match the files you want, or you will have to use a different method for filtering the files. But that would just mean modifying the function, not your whole script. This way the changes are localized, which makes it easier to track.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:05:33.660", "Id": "468370", "Score": "0", "body": "\"The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.\" - [PEP 8](https://www.python.org/dev/peps/pep-0008/#maximum-line-length). Interesting, could this have time-zone problems?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:08:10.417", "Id": "468371", "Score": "0", "body": "@Peilonrayz: That would mean another set of parenthesis... Regarding the timezones: I'm not sure what happens if your internal system clock is automatically set, you modify a file, move to a different timezone and then run this script. But I think the data is saved in UTC time and using timestamps this should be true also for `start` and `end`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:10:44.643", "Id": "468373", "Score": "0", "body": "@Peilonrayz: Got it using only one set of parenthesis by moving stuff around :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:12:57.287", "Id": "468374", "Score": "0", "body": "@Peilonrayz There could be Timezone problems if the files were created by someone else, in a different timezone. Then it depends on whose definition of days you use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:14:19.530", "Id": "468375", "Score": "1", "body": "Yeah, either way it's going to look bad to someone Hmm, I don't know enough, about FS stats. Eh ‍♀️‎" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:22:45.633", "Id": "468376", "Score": "0", "body": "Sorry, i dont uderstand everything you said, but i tried to run the code and my old files were not moved" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:26:26.550", "Id": "468377", "Score": "0", "body": "The files were too old, i tried with yesterday's files and got AttributeError: 'WindowsPath' object has no attribute 'rstrip'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:34:07.020", "Id": "468379", "Score": "0", "body": "@guialmachado: That was a bug. `shutil.move` cannot deal with `pathlib.Path` objects, apparently, so I need to cast it to a `str` at the end. Try it now, it works on my machine now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T17:19:21.627", "Id": "468387", "Score": "1", "body": "It worked, thanks" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T15:55:56.300", "Id": "238833", "ParentId": "238830", "Score": "3" } } ]
{ "AcceptedAnswerId": "238833", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T14:46:02.683", "Id": "238830", "Score": "4", "Tags": [ "python", "datetime", "file-system" ], "Title": "Moving all .xlsx files from the last five days (but not today)" }
238830
<p>I want to check if a variable is <code>nan</code> with Python.</p> <p>I have a working method <code>value != value</code> gives <code>True</code> if <code>value</code> is an <code>nan</code>. However, it is ugly and not so readable. Plus, sonarcloud considers it as a bug for the reason "identical expressions should not be used on both sides of a binary operator".</p> <p>Do you have a better/elegant solution? Thanks.</p> <pre><code>import math import numpy as np v1 = float('nan') v2 = math.nan v3 = np.nan def check_nan(value) -&gt; bool: is_nan = value != value return is_nan v1_is_nan = check_nan(value=v1) v2_is_nan = check_nan(value=v2) v3_is_nan = check_nan(value=v3) print(v1_is_nan) # printed True print(v2_is_nan) # printed True print(v3_is_nan) # printed True </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:32:04.547", "Id": "468378", "Score": "0", "body": "The code as provided doesn't really look like real actual code from a project. Who would use the name `check_nan_ugly_method` in actual code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:35:35.367", "Id": "468380", "Score": "0", "body": "@Peilonrayz this is an example code, I have simplified my actual project code to focus on my question. Why do you need my actual project code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:39:44.830", "Id": "468381", "Score": "4", "body": "Please read the [help center](https://codereview.stackexchange.com/help/on-topic), specifically the section \"Is it actual code from a project rather than pseudo-code or hypothetical code?\" Currently the, unhelpful, answer \"use better function names\" can be a legitimate answer because you chose to change your code to be worse than I assume it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:48:57.177", "Id": "468383", "Score": "0", "body": "@Peilonrayz thanks for your info. I did not know this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T22:50:28.140", "Id": "468408", "Score": "0", "body": "@aura You should edit your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:59:32.090", "Id": "468674", "Score": "0", "body": "What do you expect this will do? `is_nan = value != value`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T01:13:04.713", "Id": "468775", "Score": "0", "body": "Thank you, I have started a vote to reopen" } ]
[ { "body": "<p>IMHO your function is correct and readable as it is.\nIf I see something like <code>x != x</code> in any language my mind jumps immediately to NaN,\nregardless of the type.\nSo if you have something like a missing string or date or whatever, this test still makes sense.</p>\n\n<p>Regarding the report from sonarsource. It is always helpful to read the rationale behind a rule. If you look <a href=\"https://rules.sonarsource.com/cpp/RSPEC-1764\" rel=\"nofollow noreferrer\">here</a>\nthere are nice examples why this rule generally makes sense. I don't think this applies in your case and you can ignore it.</p>\n\n<p>Some nitpicks:</p>\n\n<ol>\n<li>I would directly return without creating a temporary. The same is true for printing.</li>\n<li>There are two spaces after is_nan =</li>\n<li>Your functions are not in a class and are really functions. Even if they were methods it would be very redundant to add it. Why don't you just call it <code>is_nan</code>?</li>\n</ol>\n\n<pre><code>import math\nimport numpy as np\n\nv1 = float('nan')\nv2 = math.nan\nv3 = np.nan\n\ndef is_nan(value) -&gt; bool:\n return value != value\n\nprint(is_nan(v1))\nprint(is_nan(v2))\nprint(is_nan(v3))\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T14:45:39.970", "Id": "468480", "Score": "0", "body": "thanks for your answer. I like your idea about renaming the function. However, I still think `x==x` is not so readable for checking `nan`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:40:27.657", "Id": "238836", "ParentId": "238835", "Score": "2" } }, { "body": "<p>Methods for this already exist, particularly because of the weird properties of NaNs. One of them can be found in the <code>math</code> library, <a href=\"https://docs.python.org/3/library/math.html#math.isnan\" rel=\"nofollow noreferrer\"><code>math.isnan</code></a> and <code>numpy</code> already has a method implemented for this as well, <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.isnan.html\" rel=\"nofollow noreferrer\"><code>numpy.isnan</code></a>. They both deal with all three kinds of NaNs shown in your code (but the <code>numpy</code> version is vectorized):</p>\n\n<pre><code>import math\nimport numpy as np\n\nlist(map(math.isnan, [float(\"nan\"), math.nan, np.nan]))\n# [True, True, True]\n\nnp.isnan([float(\"nan\"), math.nan, np.nan]) \n# array([ True, True, True])\n</code></pre>\n\n<p>If you are using <a href=\"https://pandas.pydata.org/\" rel=\"nofollow noreferrer\"><code>pandas</code></a>, <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isna.html\" rel=\"nofollow noreferrer\"><code>pandas.isna</code></a> is also interesting because it considers <code>None</code> and <code>pandas.NaT</code> (Not a Time) as missing values as well:</p>\n\n<pre><code>import pandas as pd\n\npd.isna([float(\"nan\"), math.nan, np.nan, None, pd.NaT])\n# array([ True, True, True, True, True])\n</code></pre>\n\n<hr>\n\n<p>Your code has a potential flaw, it does not return <code>True</code> only for NaNs (although it does return <code>True</code> for all NaNs), but for all objects which are not equal to themselves. In particular, it will think any instance of this class is NaN (probably true, but not necessarily):</p>\n\n<pre><code>class A:\n def __equal__(self, other):\n return False\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T11:16:44.813", "Id": "238881", "ParentId": "238835", "Score": "6" } } ]
{ "AcceptedAnswerId": "238881", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:23:38.967", "Id": "238835", "Score": "1", "Tags": [ "python" ], "Title": "Check if a variable is nan with Python" }
238835
<p>I wrote a simple command-line script to count all words in all documents (of the supported formats) in the current directory. Currently it supports TXT, DOCX, XLSX, and PDF formats and has been satisfactorily tested with them. As a freelance translator and content writer, this script provides me with an excellent tool, to quickly evaluate the scope of large projects by simply "dropping" the script into a directory and running it from PowerShell/Terminal.</p> <p>Currently tested in Windows 10 only.</p> <p>What do you think of this script? What should I improve?</p> <pre><code>import os import openpyxl import platform import docx2txt import PyPDF2 def current_dir(): if platform.system() == "Windows": directory = os.listdir(".\\") else: directory = os.getcwd() return directory def excel_counter(filename): count = 0 wb = openpyxl.load_workbook(filename) for sheet in wb: for row in sheet: for cell in row: text = str(cell.value) if text != "None": word_list = text.split() count += len(word_list) return count def pdf_counter(filename): pdf_word_count = 0 pdfFileObj = open(filename, "rb") pdfReader = PyPDF2.PdfFileReader(pdfFileObj) number_of_pages = pdfReader.getNumPages() - 1 for page in range(0, number_of_pages + 1): page_contents = pdfReader.getPage(page - 1) raw_text = page_contents.extractText() text = raw_text.encode('utf-8') page_word_count = len(text.split()) pdf_word_count += page_word_count return pdf_word_count def main(): word_count = 0 print(f"Current Directory: {os.getcwd()}") for file in current_dir(): file_name_list = os.path.splitext(file) extension = file_name_list[1] if extension == ".xlsx": current_count = excel_counter(file) print(f"{file} {current_count}") word_count += current_count if extension == ".docx": text = docx2txt.process(file) current_count = len(text.split()) print(f"{file} {current_count}") word_count += current_count if extension == ".txt": f = open(file, "r") text = f.read() current_count = len(text.split()) print(f"{file} {current_count}") word_count += current_count if extension == ".pdf": pdf_word_count = pdf_counter(file) print(f"{file} {pdf_word_count}") word_count += pdf_word_count else: pass print(f"Total: {word_count}") main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T22:50:00.063", "Id": "468407", "Score": "0", "body": "What do you consider to be a word?" } ]
[ { "body": "<p>I recommend using pathlib and Path objects instead of os, and you should use a context manager when manipulating files (e.g. <code>with open(\"file.txt\", \"r\") as file: ...</code>). You also have a lot of repeating code when you're checking extensions, and you keep checking the rest of the if statements even if it's matched an earlier one. And the final <code>else: pass</code> does literally nothing so just remove that.</p>\n\n<p>You could also do something about your nested for loops for sheet, row and cell (you'd typically use zip or itertools.product then) but this is kind of readable and nice so I'm not sure it's worth the conversion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T20:15:59.677", "Id": "238847", "ParentId": "238838", "Score": "3" } }, { "body": "<p>Refactor the code so each file type gets it's own function for counting the words like <code>excel_counter()</code> and <code>pdf_counter()</code>. Then use a dict to map file extensions to the functions.</p>\n\n<p>Something like:</p>\n\n<pre><code>def docx_counter(file):\n text = docx2txt.process(file)\n return len(text.split())\n\ndef txt_counter(file):\n f = open(file, \"r\")\n text = f.read()\n return len(text.split())\n\ndef unknown_counter(file):\n print(f\"Don't know how to process {file}.\")\n return 0\n\n\ndef main():\n word_count = 0\n\n print(f\"Current Directory: {os.getcwd()}\")\n\n counter = {\n \".xlsx\":excel_counter,\n \".docx\":docx_counter,\n \".txt\":txt_counter,\n \".pdf\":pdf_counter\n }\n\n for file in current_dir():\n file_name_list = os.path.splitext(file)\n extension = file_name_list[1]\n\n current_count = counter.get(extension, null_counter)(file)\n print(f\"{file} {current_count}\")\n word_count += current_count\n\n print(f\"Total: {word_count}\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T11:05:46.063", "Id": "468473", "Score": "0", "body": "Redefining the `counter` dictionary for every file seems like a waste. Jut move it out of the loop. And it seems like you renamed `null_counter` to `unknown_counter`, but forgot to update the `counter.get` line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T17:02:24.763", "Id": "468492", "Score": "1", "body": "@Graipher, You're absolutely correct--revised. It could be a global constant as well, or built dynamically by searching the module for functions with names like \"*_counter\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T03:18:58.310", "Id": "238866", "ParentId": "238838", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T16:48:23.843", "Id": "238838", "Score": "3", "Tags": [ "python", "file", "console" ], "Title": "Python word counter for all files in the current directory" }
238838
<p>I've written the following single-script minesweeper console game and would appreciate your feedback!</p> <p>What I'm interested in:</p> <ul> <li>Enums: I think the usage of Enums could be better. It feels weird that I need to make the player_field a <code>List[List[Union[int, PlayerFieldState]]]</code> instead of simply a <code>List[List[PlayerFieldState]]</code></li> <li>Separation of I/O and game logic: I think there is quite a bit of code which only deals with fixing user input / outputting the field to the user. Is there a nice way to separate both?</li> <li>Anything that would make the code easier to read / more concise</li> </ul> <p>What I'm not interested in:</p> <ul> <li>Pure formatting: I use <a href="https://pypi.org/project/black/" rel="noreferrer"><code>black</code></a> and <a href="https://pypi.org/project/isort/" rel="noreferrer"><code>isort</code></a> and I'm pretty happy with that.</li> </ul> <h2>Code</h2> <p>You need Python 3.6+ with <code>numpy</code> to execute the following:</p> <pre><code># Core Library modules import enum from typing import List, Tuple, cast, Union # Third party modules import numpy as np def main(): game = Game(n=10, m=10, nb_mines=10) while game.is_running: game.take_step() class PlayerFieldState(enum.Enum): ZERO = 0 ONE = 1 TWO = 2 THREE = 3 FOUR = 4 FIVE = 5 SIX = 6 SEVEN = 7 EIGHT = 8 UNDISCOVERED = 9 EXPLODED_BOMB = 10 MARKED = 11 class PlayerAction(enum.Enum): EXPLORE = 0 MARK = 1 field_state2str = { 0: " ", 1: "1 ", 2: "2 ", 3: "3 ", 4: "4 ", 5: "5 ", 6: "6 ", 7: "7 ", 8: "8 ", PlayerFieldState.UNDISCOVERED: "? ", PlayerFieldState.EXPLODED_BOMB: "", PlayerFieldState.MARKED: "", } class Game: def __init__(self, n: int, m: int, nb_mines: int): self.mine_field = Game.create_field(n, m, nb_mines) self.player_field: List[List[Union[int, PlayerFieldState]]] = [ [PlayerFieldState.UNDISCOVERED for _ in range(m)] for _ in range(n) ] self.is_running = True self.nb_mines = nb_mines self.nb_marked = 0 @staticmethod def create_field(n: int, m: int, nb_mines: int) -&gt; List[List[bool]]: field = np.zeros(n * m, dtype=bool) for i in range(nb_mines): field[i] = True np.random.shuffle(field) field = field.reshape((n, m)) return field.tolist() def print_field(self, uncover: bool = False): top_line = [" "] + [str(y) + " " for y in range(len(self.player_field[0]))] top_line_str = " ".join(top_line) print(top_line_str) print("-" * len(top_line_str)) for x, line in enumerate(self.player_field): to_print = [str(x) + "|"] for y, field in enumerate(line): el = field_state2str[field] if uncover: if ( self.mine_field[x][y] and field != PlayerFieldState.EXPLODED_BOMB ): el = "" if field == PlayerFieldState.MARKED: if not self.mine_field[x][y]: el = "" else: el = "" to_print.append(el) print(" ".join(to_print)) print("-" * len(top_line_str)) print(top_line_str) def take_step(self): self.print_field() x, y, step_type = self.get_valid_input() if step_type == PlayerAction.MARK: self.take_step_mark_bomb(x, y) elif step_type == PlayerAction.EXPLORE: self.take_step_explore(x, y) else: raise ValueError(f"step_type={step_type} is not known") def take_step_mark_bomb(self, x: int, y: int): if self.player_field[x][y] == PlayerFieldState.MARKED: self.player_field[x][y] = PlayerFieldState.UNDISCOVERED self.nb_marked -= 1 elif self.player_field[x][y] == PlayerFieldState.UNDISCOVERED: self.player_field[x][y] = PlayerFieldState.MARKED self.nb_marked += 1 self.check_win_condition() def take_step_explore(self, x: int, y: int): if self.player_field[x][y] == PlayerFieldState.MARKED: print(f"Please unmark ({x},{y}) before you hit it.") elif self.mine_field[x][y]: self.player_field[x][y] = PlayerFieldState.EXPLODED_BOMB self.is_running = False print("Game over") self.print_field(uncover=True) else: self.uncover(x, y) def check_win_condition(self): if self.nb_marked == self.nb_mines: print( f"You have marked {self.nb_marked} fields with mines. " "This is equal to the number of hidden mines." ) stop_game = get_yes_no("Do you want to finish the game?") if stop_game: self.is_running = False if self.are_mines_marked_correctly(): print("You won!") else: print("You lose!") self.print_field(uncover=True) def uncover(self, x: int, y: int): adjacent_mines = self.get_adjacent_mines(x, y) self.player_field[x][y] = adjacent_mines if adjacent_mines == 0: for xn, yn in self.get_neighbors(x, y): if self.player_field[xn][yn] == PlayerFieldState.UNDISCOVERED: self.uncover(xn, yn) def get_neighbors(self, x: int, y: int) -&gt; List[Tuple[int, int]]: neighbors = [] for xd in [-1, 0, 1]: for yd in [-1, 0, 1]: if xd == 0 and yd == 0: continue if self.is_on_field(x + xd, y + yd): neighbors.append((x + xd, y + yd)) return neighbors def get_adjacent_mines(self, x: int, y: int) -&gt; int: adjacent_mines = 0 for xn, yn in self.get_neighbors(x, y): adjacent_mines += self.is_mine(xn, yn) return adjacent_mines def is_on_field(self, x: int, y: int) -&gt; bool: return 0 &lt;= x &lt; len(self.mine_field) and 0 &lt;= y &lt; len(self.mine_field[0]) def is_mine(self, x: int, y: int) -&gt; bool: if not self.is_on_field(x, y): return False return self.mine_field[x][y] def get_valid_input(self) -&gt; Tuple[int, int, PlayerAction]: position = None while not self.is_valid_input(position): position = input( "Where would you like to hit " "(add ',m' if you want to mark a bomb)? " ) position = cast(str, position) splitted = position.split(",") x = int(splitted[0]) y = int(splitted[1]) if len(splitted) == 3: if splitted[2] == "m": t = PlayerAction.MARK else: t = PlayerAction.EXPLORE else: t = PlayerAction.EXPLORE return x, y, t def is_valid_input(self, position): if position is None: return False if "," not in position: return False splitted = position.split(",") x = splitted[0] y = splitted[1] if len(splitted) == 3: t = splitted[2] if t not in ["m", "b"]: return False try: x = int(x) y = int(y) if not self.is_on_field(x, y): return False return True except: return False def are_mines_marked_correctly(self): for x, line in enumerate(self.mine_field): for y, is_mine in enumerate(line): if is_mine: if self.player_field[x][y] != PlayerFieldState.MARKED: return False else: if self.player_field[x][y] == PlayerFieldState.MARKED: return False return True def get_yes_no(message: str) -&gt; bool: value = input(message) while value not in ["Y", "y", "N", "n", "yes", "no", "1", "0"]: value = input(message + " [y/n] ") return value in ["Y", "y", "yes", "1"] if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<h2>Requirements</h2>\n\n<blockquote>\n <p>You need Python 3.6+</p>\n</blockquote>\n\n<p>So at the least, you should add a shebang:</p>\n\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n\n<blockquote>\n <p>with numpy</p>\n</blockquote>\n\n<p>should go in a <code>requirements.txt</code>.</p>\n\n<h2>Definition order</h2>\n\n<p>You define <code>main</code> at the top. Call me old-fashioned, but I'm used to stricter languages where the referred symbols in a function need to be defined before that function. I still consider defining things in dependence order to be more legible, and suggest that <code>main</code> go at the bottom.</p>\n\n<h2><code>Enum</code></h2>\n\n<p>Use <code>unique</code> and <code>auto</code>:</p>\n\n<pre><code>@unique\nclass PlayerFieldState(Enum):\n UNDISCOVERED = auto()\n EXPLODED_BOMB = auto()\n MARKED = auto()\n</code></pre>\n\n<p>I think it's probably inappropriate to represent the values 0-8 in that enum; they should be stored in a different variable. It looks like you're already going in that direction? given this: </p>\n\n<pre><code>self.player_field: List[List[Union[int, PlayerFieldState]]]\n</code></pre>\n\n<p>In other words: why have an int-state union if your state captures ints?</p>\n\n<h2>Numpy</h2>\n\n<pre><code> return field.tolist()\n</code></pre>\n\n<p>Why the <code>tolist</code> call? Wouldn't leaving the field as a Numpy array be a more efficient representation?</p>\n\n<h2>Iterating coordinates</h2>\n\n<p><code>get_neighbors</code> probably shouldn't return a list. Instead, make it a generator, and don't do iterative concatenation. Something like:</p>\n\n<pre><code> for xd in [-1, 0, 1]:\n xa = x + xd\n for yd in [-1, 0, 1]:\n ya = y + yd\n if self.is_on_field(xa, ya) and not (xd == 0 and yd == 0):\n yield xa, ya\n</code></pre>\n\n<p>The same goes for <code>get_adjacent_mines</code>.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code> if not self.is_on_field(x, y):\n return False\n return self.mine_field[x][y]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return self.is_on_field(x, y) and self.mine_field[x][y]\n</code></pre>\n\n<h2>Sets for validation</h2>\n\n<pre><code>while value not in [\"Y\", \"y\", \"N\", \"n\", \"yes\", \"no\", \"1\", \"0\"]:\n value = input(message + \" [y/n] \")\nreturn value in [\"Y\", \"y\", \"yes\", \"1\"]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>yes_vals = {\"Y\", \"y\", \"yes\", \"1\"}\nno_vals = {\"N\", \"n\", \"no\", \"0\"}\nwhile value not in yes_vals|no_vals:\n value = input(message + \" [y/n] \")\nreturn value in yes_vals\n</code></pre>\n\n<p>Your loop structure could also be simplified. Just do a <code>while True</code>, do one <code>input</code>, check for membership and return:</p>\n\n<pre><code>yes_vals = {\"Y\", \"y\", \"yes\", \"1\"}\nno_vals = {\"N\", \"n\", \"no\", \"0\"}\nwhile True:\n value = input(message + \" [y/n] \")\n if value in yes_vals|no_vals:\n return value in yes_vals\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T04:32:42.160", "Id": "238869", "ParentId": "238841", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T18:17:49.200", "Id": "238841", "Score": "5", "Tags": [ "python", "game", "minesweeper" ], "Title": "Python - CLI Minesweeper" }
238841
<p>There are lots of shell programs that have <code>/bin/sh</code> as interpreter, yet use some features that are specific to bash or other popular shells. I have written a little program that detects these unportable features. It is not meant to compete with ShellCheck, its purpose is only to catch a few common mistakes.</p> <p>Since the program checks for portability issues, I had to lead by example and make this program as portable as possible as well. Therefore I sticked to the headers and functions provided by C99.</p> <p>Since C is a dangerous programming language with lots of ways to shoot yourself in the foot, the first half of the code defines an API for the second half of the code, which starts at <code>typedef enum</code>. This API is easier to use than the standard C functions for dealing with strings. It takes some ideas from C++ (<code>nullptr</code>, <code>npos</code>) and Go (immutable strings defined by <code>(data, len)</code>, herein called <code>cstr</code>), and probably from several other languages as well.</p> <p>Implementing generic functions with callbacks is quite verbose in C. I really like that the code in <code>foreach_3_fields_in_line</code> is trivial to understand. This simplicity comes at the cost of having to define a <code>struct</code> for the callback parameters. If standard C had nested function scopes, I would have used an inner function, and the code would have been much shorter. Maybe there is a more elegant way of implementing <code>checkline_sh_test_eqeq</code>, for now that's all I have, and it works well.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;assert.h&gt; #include &lt;ctype.h&gt; #include &lt;stdarg.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define nullptr ((void *) 0) static const size_t npos = -1; static bool is_alnum(char c) { return isalnum((unsigned char) c) != 0; } static bool is_hspace(char c) { return c == ' ' || c == '\t'; } // cstr is a constant string view. typedef struct { const char *data; // never nullptr size_t len; } cstr; #define CSTR(str) ((cstr) { str, strlen(str) }) static const char * cstr_charptr(cstr s) { assert(memchr(s.data, 0, s.len) == nullptr); assert(s.data[s.len] == '\0'); return s.data; } #if 0 /* unused */ static bool cstr_ends_with(cstr s, cstr suffix) { if (suffix.len &gt; s.len) return false; const char *start = s.data + s.len - suffix.len; return memcmp(start, suffix.data, suffix.len) == 0; } #endif static bool cstr_starts_with(cstr s, cstr prefix) { if (prefix.len &gt; s.len) return false; return memcmp(s.data, prefix.data, prefix.len) == 0; } static cstr cstr_substr(cstr s, size_t start, size_t end) { assert(start &lt;= s.len); assert(end &lt;= s.len); assert(end - start &lt;= s.len); return (cstr) { s.data + start, end - start }; } static size_t cstr_index(cstr haystack, cstr needle) { if (needle.len &gt; haystack.len) return npos; size_t limit = haystack.len - needle.len; for (size_t i = 0; i &lt;= limit; i++) if (memcmp(haystack.data + i, needle.data, needle.len) == 0) return i; return npos; } static bool cstr_contains_char(cstr haystack, char needle) { return memchr(haystack.data, needle, haystack.len); } static bool cstr_contains(cstr haystack, cstr needle) { return cstr_index(haystack, needle) != npos; } static size_t cstr_rindex(cstr haystack, cstr needle) { if (needle.len &gt; haystack.len) return npos; size_t limit = haystack.len - needle.len; for (size_t i = limit + 1; i-- &gt; 0; ) if (memcmp(haystack.data + i, needle.data, needle.len) == 0) return i; return npos; } static bool cstr_eq(cstr s1, cstr s2) { return s1.len == s2.len &amp;&amp; memcmp(s1.data, s2.data, s1.len) == 0; } static cstr cstr_next_field(cstr line, size_t *pidx) { size_t idx = *pidx; while (idx &lt; line.len &amp;&amp; is_hspace(line.data[idx])) idx++; size_t start = idx; while (idx &lt; line.len &amp;&amp; !is_hspace(line.data[idx])) idx++; *pidx = idx; return cstr_substr(line, start, idx); } static cstr cstr_right_of_last(cstr s, cstr delimiter) { size_t i = cstr_rindex(s, delimiter); if (i == npos) return s; return cstr_substr(s, i + delimiter.len, s.len); } // str is a modifiable string buffer. typedef struct { char *data; size_t len; size_t cap; } str; #define STR_EMPTY { nullptr, 0, 0 } static cstr str_c(str *s) { assert(s-&gt;data != nullptr); return (cstr) { s-&gt;data, s-&gt;len }; } static void str_free(str *s) { free(s-&gt;data); } static void str_reserve(str *s, size_t n) { size_t req_len = s-&gt;len + n; assert(req_len &gt;= s-&gt;len); if (req_len &lt;= s-&gt;cap) return; size_t new_cap = s-&gt;cap == 0 ? 64 : 2 * s-&gt;cap; if (new_cap == 0) new_cap = -1; char *new_data = realloc(s-&gt;data, new_cap); if (new_data == nullptr) { perror(nullptr); exit(EXIT_FAILURE); } s-&gt;data = new_data; s-&gt;cap = new_cap; } static void str_append_char(str *s, char c) { str_reserve(s, 1); s-&gt;data[s-&gt;len++] = c; } static const char * str_charptr(str *s) { str_reserve(s, 1); s-&gt;data[s-&gt;len] = '\0'; assert(memchr(s-&gt;data, '\0', s-&gt;len) == nullptr); return s-&gt;data; } static bool str_read_line(str *s, FILE *f) { int c; s-&gt;len = 0; while ((c = fgetc(f)) != EOF &amp;&amp; c != '\n' &amp;&amp; c != '\r') { str_append_char(s, (char) c); } return c != EOF; } static bool str_read_text_line(str *s, FILE *f) { int c; s-&gt;len = 0; while ((c = fgetc(f)) &gt; '\0' &amp;&amp; c != '\n' &amp;&amp; c != '\r') { str_append_char(s, (char) c); } assert(c != '\0'); return c != EOF; } typedef enum { W_how_to_fix, W_dollar_random, W_test_eqeq, W_double_bracket } warning_kind; static unsigned long explained = 0; static void explain(warning_kind warning, ...) { unsigned long mask = 1UL &lt;&lt; warning; if ((explained &amp; mask) != 0) return; explained |= mask; va_list args; va_start(args, warning); printf("\n"); const char *line; while ((line = va_arg(args, const char *)) != nullptr) printf("%s%s\n", line[0] == '\0' ? "" : "\t", line); printf("\n"); va_end(args); } static void explain_how_to_fix(void) { explain( W_how_to_fix, "To fix this message, decide whether this file is necessary", "for the package to build. Then choose any of these variants:", "", "1. Add a patch for the file", " (see https://www.netbsd.org/docs/pkgsrc/pkgsrc.html#components.patches)", "2. Add a SUBST block for the file to the package Makefile", " (see mk/subst.mk)", "3. Add CHECK_PORTABILITY_SKIP+= shell/glob to the package Makefile", " (see mk/check/check-portability.mk)", nullptr); } static size_t index_opening_bracket(cstr s) { size_t index = cstr_index(s, CSTR("[[")); if (index == npos) return npos; if (index &gt; 0 &amp;&amp; !is_hspace(s.data[index - 1])) return npos; if (index + 2 &lt; s.len &amp;&amp; !is_hspace(s.data[index + 2])) return npos; return index; } static size_t index_closing_bracket(cstr s) { size_t index = cstr_index(s, CSTR("]]")); if (index == npos) return npos; if (index &gt; 0 &amp;&amp; !is_hspace(s.data[index - 1])) return npos; if (index + 2 &lt; s.len &amp;&amp; !is_hspace(s.data[index + 2]) &amp;&amp; s.data[index + 2] != ';') return npos; return index; } static size_t nerrors = 0; static bool is_shell_comment(cstr line) { size_t i = 0; cstr f1 = cstr_next_field(line, &amp;i); return cstr_starts_with(f1, CSTR("#")); } static void checkline_sh_double_brackets(cstr filename, size_t lineno, cstr line) { if (is_shell_comment(line)) return; size_t opening_index = index_opening_bracket(line); if (opening_index == npos) return; cstr suffix = cstr_substr(line, opening_index, line.len); size_t closing_index = index_closing_bracket(suffix); if (closing_index == npos) return; printf("%s:%zu:%zu: double brackets: %s\n", cstr_charptr(filename), lineno, opening_index + 1, cstr_charptr(line)); nerrors++; explain( W_double_bracket, "The keyword [[ is only available in bash, not in other shells.", "Since it is typically used inside an if statement, if that", "command is missing, it is interpreted as a \"no\".", "", "An error message of the form \"[[: command not found\"", "is logged, but that is easy to overlook in the large", "output of the build process.", nullptr); explain_how_to_fix(); } // Check for $RANDOM, which is specific to ksh and bash. static void checkline_sh_dollar_random(cstr filename, size_t lineno, cstr line) { // Note: This code does not find _all_ instances of // unportable code. If a single line contains an unsafe and // a safe usage of $RANDOM, it will pass the test. if (is_shell_comment(line)) return; if (!cstr_contains(line, CSTR("$RANDOM"))) return; // $RANDOM together with the PID is often found in GNU-style // configure scripts and is considered acceptable. if (cstr_contains(line, CSTR("<span class="math-container">$$-$RANDOM"))) return; if (cstr_contains(line, CSTR("$RANDOM-$$</span>"))) return; // Variable names that only start with RANDOM are not special. size_t idx = cstr_index(line, CSTR("$RANDOM")); if (idx != npos &amp;&amp; idx + 7 &lt; line.len &amp;&amp; is_alnum(line.data[idx + 7])) return; printf("%s:%zu:%zu: $RANDOM: %s\n", cstr_charptr(filename), lineno, idx + 1, cstr_charptr(line)); explain( W_dollar_random, "The variable $RANDOM is not required for a POSIX-conforming shell, and", "many implementations of /bin/sh do not support it. It should therefore", "not be used in shell programs that are meant to be portable across a", "large number of POSIX-like systems.", nullptr); explain_how_to_fix(); } typedef void (*foreach_3_fields_cb)(cstr f1, cstr f2, cstr f3, void *actiondata); static void foreach_3_fields_in_line(cstr line, foreach_3_fields_cb action, void *actiondata) { size_t idx = 0; cstr f1 = cstr_next_field(line, &amp;idx); cstr f2 = cstr_next_field(line, &amp;idx); cstr f3 = cstr_next_field(line, &amp;idx); while (f3.len &gt; 0) { action(f1, f2, f3, actiondata); f1 = f2; f2 = f3; f3 = cstr_next_field(line, &amp;idx); } } struct checkline_sh_test_eqeq_actiondata { cstr filename; size_t lineno; cstr line; }; static void checkline_sh_test_eqeq_action(cstr f1, cstr f2, cstr f3, void *actiondata) { if (!cstr_eq(f3, CSTR("=="))) return; if (!cstr_eq(f1, CSTR("test")) &amp;&amp; !cstr_eq(f1, CSTR("["))) return; struct checkline_sh_test_eqeq_actiondata *ad = actiondata; printf( "%s:%zu:%zu: found test ... == ...: %s\n", cstr_charptr(ad-&gt;filename), ad-&gt;lineno, (size_t) (f3.data - ad-&gt;line.data), cstr_charptr(ad-&gt;line)); explain( W_test_eqeq, "The \"test\" command, as well as the \"[\" command, are not required to know", "the \"==\" operator. Only a few implementations like bash and some", "versions of ksh support it.", "", "When you run \"test foo == foo\" on a platform that does not support the", "\"==\" operator, the result will be \"false\" instead of \"true\". This can", "lead to unexpected behavior.", nullptr); explain_how_to_fix(); } static void checkline_sh_test_eqeq(cstr filename, size_t lineno, cstr line) { if (is_shell_comment(line)) return; struct checkline_sh_test_eqeq_actiondata ad = { filename, lineno, line }; foreach_3_fields_in_line(line, checkline_sh_test_eqeq_action, &amp;ad); } static bool is_shell_shebang(cstr line) { if (!cstr_starts_with(line, CSTR("#!"))) return false; size_t i = 2; cstr full_interp = cstr_next_field(line, &amp;i); cstr arg = cstr_next_field(line, &amp;i); cstr interp = cstr_right_of_last(full_interp, CSTR("/")); if (cstr_eq(interp, CSTR("env")) &amp;&amp; arg.len &gt; 0) { interp = arg; } return cstr_eq(interp, CSTR("sh")) || cstr_eq(interp, CSTR("ksh")) || cstr_eq(interp, CSTR("@SH@")) || cstr_eq(interp, CSTR("@SHELL@")); } static bool is_irrelevant_extension(cstr ext) { return cstr_eq(ext, CSTR("bz2")) || cstr_eq(ext, CSTR("c")) || cstr_eq(ext, CSTR("cc")) || cstr_eq(ext, CSTR("cpp")) || cstr_eq(ext, CSTR("gz")) || cstr_eq(ext, CSTR("m4")) || cstr_eq(ext, CSTR("pdf")) || cstr_eq(ext, CSTR("ps")) || cstr_eq(ext, CSTR("xz")) || cstr_eq(ext, CSTR("zip")); } static bool skip_shebang(cstr basename) { return cstr_eq(basename, CSTR("Makefile.am")) || cstr_eq(basename, CSTR("Makefile.in")) || cstr_eq(basename, CSTR("Makefile")); } static void check_file(cstr filename) { cstr basename = cstr_right_of_last(filename, CSTR("/")); cstr ext = cstr_right_of_last(basename, CSTR(".")); if (is_irrelevant_extension(ext)) return; FILE *f = fopen(cstr_charptr(filename), "rb"); if (f == nullptr) { perror(cstr_charptr(filename)); nerrors++; return; } str line = STR_EMPTY; size_t lineno = 0; if (!skip_shebang(basename)) { if (!str_read_line(&amp;line, f)) goto cleanup; lineno++; if (!is_shell_shebang(str_c(&amp;line))) goto cleanup; } while (str_read_line(&amp;line, f)) { cstr cline = str_c(&amp;line); if (cstr_contains_char(str_c(&amp;line), '\0')) break; lineno++; str_charptr(&amp;line); checkline_sh_double_brackets(filename, lineno, cline); checkline_sh_dollar_random(filename, lineno, cline); checkline_sh_test_eqeq(filename, lineno, cline); } cleanup: str_free(&amp;line); (void) fclose(f); } static void check_files_from_stdin(void) { str line = STR_EMPTY; while (str_read_text_line(&amp;line, stdin)) { str_charptr(&amp;line); check_file(str_c(&amp;line)); } } static int usage(const char *progname) { fprintf(stderr, "usage: %s &lt; file-list\n" " %s file...\n", progname, progname); return EXIT_FAILURE; } int main(int argc, char **argv) { if (argc &gt; 1 &amp;&amp; argv[1][0] == '-') return usage(argv[0]); if (argc == 1) check_files_from_stdin(); for (int i = 1; i &lt; argc; i++) check_file(CSTR(argv[i])); return nerrors &gt; 0 ? EXIT_FAILURE : EXIT_SUCCESS; } </code></pre> <p>To test the code by manual inspection, <a href="https://github.com/NetBSD/pkgsrc/tree/trunk/pkgtools/check-portability/files/testdata" rel="nofollow noreferrer">there are some example files</a>. Up to now, I haven't added an automatic test, even though it would be easy to do.</p>
[]
[ { "body": "<h2>Spaces</h2>\n\n<p>My first read of this code:</p>\n\n<pre><code> \"The \\\"test\\\" command, as well as the \\\"[\\\" command, are not required to know\",\n \"the \\\"==\\\" operator. Only a few implementations like bash and some\",\n \"versions of ksh support it.\",\n</code></pre>\n\n<p>was wrong; I didn't notice that it's actually a varargs-function accepting one line per argument. That's a little odd. This has the disadvantage of hard wraps regardless of actual console size, a significant departure from what people typically expect from a CLI. </p>\n\n<p>The C-idiomatic way is to simply have one long string, potentially split onto multiple lines using implicit literal concatenation. The non-standardness of this pattern ties into my next point:</p>\n\n<h2>C</h2>\n\n<p>Prepare for me to editorialize:</p>\n\n<blockquote>\n <p>C is a dangerous programming language with lots of ways to shoot yourself in the foot</p>\n</blockquote>\n\n<p>You're right, and I don't particularly think that any of the structures you've put on top of it help to change that. In fact, you repeat some of the worst offenders, such as assignment-in-condition. In general I'd say that it isn't worth attempting to make C something that it isn't, and a much-smaller, idiomatic C program is easier to understand and maintain (particularly for others, if you open-source this) than a larger, non-idiomatic one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T03:37:52.027", "Id": "238868", "ParentId": "238842", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T18:30:15.737", "Id": "238842", "Score": "3", "Tags": [ "c", "strings", "shell" ], "Title": "Check shell programs for portability" }
238842
<p>I am at the moment trying to grasp multi-file programming instead of one big main.cpp.</p> <p>The class I wrote is about ISBN 13.</p> <p>Can you point out what could be done to improve my code?</p> <p>Also is there a good guide how to write include guards? My sources differate in this respect.</p> <p><a href="https://wandbox.org/permlink/5UY7txTEbzHVFeaW" rel="nofollow noreferrer">Runnable code here on Wandbox</a></p> <p>ISBN.hpp</p> <pre><code>#include &lt;ostream&gt; class ISBN { /* examples 978-345-314-697-6 978-3-12-732320-7 */ private: //the numbers between the minus signs unsigned int isbn_field1; unsigned int isbn_field2; unsigned int isbn_field3; unsigned int isbn_field4; unsigned int isbn_field5; public: //constructors ISBN() : ISBN{978,3,12,732320,7} // a valid ISBN as default {} ISBN(const unsigned int&amp; a, const unsigned int&amp; b, const unsigned int&amp; c, const unsigned int&amp; d, const unsigned int&amp; e); //output operator overloading friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, ISBN const&amp; i); };//ISBN </code></pre> <p>ISBN.cpp</p> <pre><code>#include "ISBN.hpp" #include &lt;iostream&gt; #include &lt;string&gt; bool is_valid_isbn(const std::string&amp; digits) { unsigned int weighted_sum=0; std::string temp; for (unsigned int i=0; i&lt;(digits.length());i++) { temp=digits[i]; if ((i%2)==0) { weighted_sum+=std::stoi(temp); } else { weighted_sum+=std::stoi(temp)*3; } } if ((weighted_sum%10)!=0) { return false; } return true; } ISBN::ISBN(const unsigned int&amp; a, const unsigned int&amp; b, const unsigned int&amp; c, const unsigned int&amp; d, const unsigned int&amp; e) { const std::string digit_string=std::to_string(a) +std::to_string(b) +std::to_string(c) +std::to_string(d) +std::to_string(e); std::string temp; //check if last field is exactly one digit temp=std::to_string(e); if(temp.length()!=1) { throw "last unit is not a single digit\n"; } //check if first field is 978 or 979 if(a!=978 &amp;&amp; a!=979) { throw "first unit is neither 978 nor 979\n"; } //check number of digits=13 if(digit_string.length()!=13) { throw "number of digits is not exactly 13\n"; } if (!is_valid_isbn(digit_string)) { throw "not a valid ISBN\n"; } isbn_field1=a; isbn_field2=b; isbn_field3=c; isbn_field4=d; isbn_field5=e; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, ISBN const&amp; i) { return os &lt;&lt; i.isbn_field1 &lt;&lt; "-" &lt;&lt; i.isbn_field2 &lt;&lt; "-" &lt;&lt; i.isbn_field3 &lt;&lt; "-" &lt;&lt; i.isbn_field4 &lt;&lt; "-" &lt;&lt; i.isbn_field5; } </code></pre> <p>main.cpp</p> <pre><code>#include "ISBN.hpp" #include &lt;iostream&gt; int main() { try { ISBN test; std::cout &lt;&lt; test; } catch(char const* e) { std::cout &lt;&lt; "Error:" &lt;&lt; e; } catch(...) { std::cout &lt;&lt; "test error"; } return 0; } </code></pre>
[]
[ { "body": "<p>The comment in the <code>ISBN</code> class should rather be outside the class declaration, and it should contain a few words for the human reader, such as the expanded abbreviation and the Wikipedia page, to make it easy to get additional information about the topic of ISBNs.</p>\n\n<p>Storing an ISBN as 5 numbers is wrong. If the length of these numbers doesn't sum up to 13, you cannot be sure where to add the zeroes. The <a href=\"https://en.wikipedia.org/wiki/International_Standard_Book_Number\" rel=\"nofollow noreferrer\">Wikipedia article</a> contains a table of example ISBN-10 numbers, and some of them have leading digits.</p>\n\n<p>The variable names <code>isbn_field1</code> are bad. The word <code>isbn</code> is not necessary since that information is given by the class <code>ISBN</code> already. Therefore <code>field1</code> is better than <code>isbn_field1</code>. But what is <code>field1</code>, what does it mean? The Wikipedia article gives nice names to these fields, and so should your code.</p>\n\n<p>The characters between the digits are not \"minus signs\" (as you say) but hyphens.</p>\n\n<p>The no-argument constructor is wrong. There should be no way to construct an ISBN object without specifying all its parts. Having a single \"best default\" is simply not possible for an ISBN. You definitely don't want to convert all your programming mistakes to a book about analytic geometry.</p>\n\n<p>In the constructor with the <code>const unsigned int&amp;</code> parameters, the <code>const&amp;</code> is not necessary. Integer values are typically passed directly instead of referencing them since they are one machine word long, and the computer can process them quickly. References make your code run slower in this case. For larger types such as <code>std::vector&lt;std::vector&lt;ISBN&gt;&gt;</code> it makes sense to use references instead of simple values.</p>\n\n<p>In the <code>is_valid_isbn</code> function, you should add spaces around the tokens in <code>i=0</code>. Most C++ programmers are used to read this as <code>i = 0</code>.</p>\n\n<p>In the same line, the parentheses around <code>digits.length()</code> are not necessary.</p>\n\n<p>Instead of calling <code>std::stoi</code>, you can also write <code>digits[i] - '0'</code>, which gives you the numeric value of a digit character. Which reminds me that some of the characters might not be digits at all. Your code should skip them and later verify that the string contained 13 digits in total.</p>\n\n<p>In the <code>ISBN::ISBN</code> constructor, instead of checking whether the last field has length 1, you can just check whether <code>e &lt; 10</code>. This is simpler and faster.</p>\n\n<p>When validating multiple values, you should validate them in reading order. Start with the first field, and validate the last field last.</p>\n\n<p>You didn't test your code by calling <code>ISBN{0, 0, 0, 0, 0}</code>.</p>\n\n<p>When you <code>throw</code> something from your code, it should be a proper exception from the C++ standard library, such as <code>std::invalid_argument</code>.</p>\n\n<p>Instead of the verbose <code>std::string temp; temp = std::to_string(e); temp.length() != 1</code>, you can simply write <code>std::to_string(e).length() != 1</code>. This way you don't have to think about a better variable name instead of <code>temp</code>. The name <code>temp</code> is always a bad variable name since it doesn't tell enough of a story. (Well, except if you use it as an abbreviation for <em>temperature</em>, but that's not the case here.)</p>\n\n<p>The exception strings should not include a newline character. That character should be added when the exception is printed in a log file. If you want to save the exception somewhere else, the newline is probably wrong.</p>\n\n<p>The <code>main</code> program is pretty useless. There is no way to enter an ISBN and validate it. You should rather define the following functions to get some automated tests:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void assert_valid_isbn(const std::string &amp;isbn)\n{\n /* TODO */\n}\n\nvoid assert_invalid_isbn(const std::string &amp;isbn, const std::string &amp;expected_error)\n{\n /* TODO */\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T09:06:38.623", "Id": "468456", "Score": "0", "body": "Can you write in pseudocode what the automated tests should do? I rewrote my class with the tips you gave me, but I don't know what those should do!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-20T21:39:36.777", "Id": "469216", "Score": "0", "body": "To see how the `assert` functions should look like, take some time, get a cup of tea and read the documentation of [Googletest](https://github.com/google/googletest/blob/master/googletest/docs/primer.md). Since you asked this question, I'm assuming that you have never written any unit test before." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T19:55:59.540", "Id": "238846", "ParentId": "238843", "Score": "1" } } ]
{ "AcceptedAnswerId": "238846", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T18:45:29.120", "Id": "238843", "Score": "2", "Tags": [ "c++", "object-oriented", "c++17" ], "Title": "Class ISBN - checks for valid ISBN 13" }
238843
<p>I have created a Node class that I am using for various projects in my data structures class(at school) and I am overloading the insertion operator <code>&lt;&lt;</code>. I am using <code>std::any</code> for my container datatype inside Node class and am using <code>std::any_cast</code> to insert this data into a stream whenever possible. <code>Std::any_cast</code> requires that I know the datatype beforehand, and so I've come up with a hacky way to get this information by detangling the value typename into a string and then <em>using a ton of else if statements</em> to compare this string, as you can see in my code below... I'm looking for a different solution or even some advice about why this approach is fundamentally wrong and how to go about making better programming decisions. Lay it on me, I need help and can take it!</p> <pre><code>friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; out, Node&amp; n){ std::string t; t = abi::__cxa_demangle(n.value.type().name(), 0, 0, 0);; if (t.find("string") != std::string::npos) { out &lt;&lt; std::any_cast&lt;std::string&gt;(n.value); } else if (t == "unsigned long long int") { out &lt;&lt; std::any_cast&lt;unsigned long long int&gt;(n.value); } else if (t == "unsigned long int") { out &lt;&lt; std::any_cast&lt;unsigned long int&gt;(n.value); } else if (t == "long long int") { out &lt;&lt; std::any_cast&lt;long long int&gt;(n.value); } else if (t == "long int") { out &lt;&lt; std::any_cast&lt;long int&gt;(n.value); } else if (t == "unsigned short int") { out &lt;&lt; std::any_cast&lt;unsigned short int&gt;(n.value); } else if (t == "short int"){ out &lt;&lt; std::any_cast&lt;short int&gt;(n.value); } else if (t == "int") { out &lt;&lt; std::any_cast&lt;int&gt;(n.value); } else if (t == "long double") { out &lt;&lt; std::any_cast&lt;long double&gt;(n.value); } else if (t == "double") { out &lt;&lt; std::any_cast&lt;double&gt;(n.value); } else if (t == "float") { out &lt;&lt; std::any_cast&lt;float&gt;(n.value); } else if (t == "bool") { out &lt;&lt; std::any_cast&lt;bool&gt;(n.value); } else if (t == "unsigned char") { out &lt;&lt; std::any_cast&lt;unsigned char&gt;(n.value); } else if (t == "signed char") { out &lt;&lt; std::any_cast&lt;signed char&gt;(n.value); } else if (t == "char") { out &lt;&lt; std::any_cast&lt;char&gt;(n.value); } else { out &lt;&lt; t; }; return out; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T22:57:15.603", "Id": "468410", "Score": "2", "body": "Seems like you missed the class on inheritance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T07:13:52.397", "Id": "468440", "Score": "3", "body": "Welcome. This here is [CodeReview@SE](https://codereview.stackexchange.com/help/on-topic), set to help improve *working code from a project* as well as *coding habits and skills*. I do not see the code presented to be part of any judicious attempt of tackling a problem. Choosing among the mechanisms of a programming language of choice seems a better fit over at [StackOverflow](https://stackoverflow.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T09:26:39.420", "Id": "468458", "Score": "0", "body": "@greybeard my mistake, apologies for misunderstanding. I can't seem to remove this post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T09:49:40.750", "Id": "468464", "Score": "0", "body": "(No longer thinking a post was the best course of action is *not* a sufficient cause to remove it: thinking it *not helpful* is. With questions, this includes all the answers…)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T11:14:25.237", "Id": "468475", "Score": "1", "body": "If `type()` returns a `type_info const &`, you can compare that to `typeid(std::string)` to find out if it's a string." } ]
[ { "body": "<p>There are way too many ways to improve the situation. Some require big changes some require small changes.</p>\n\n<p>Why not simply store the data inside <code>double</code> instead of <code>any</code>? <code>double</code> only fails to 100% accurately contain <code>long long</code> types - but even that happens for very large numbers. At most have <code>long long</code>, <code>double</code> and a boolean that indicates which variable it is. Or say use <code>std::variant&lt;double, long long&gt;</code>.</p>\n\n<p>Using <code>std::any</code> for basic types is a total overkill and will surely result in lots of overhead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T14:26:32.617", "Id": "468479", "Score": "2", "body": "You overlooked the first option: `std::string`. Aside from that, yes, restricting the options, and potentially merging some of them, is a good idea." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T20:46:59.630", "Id": "238848", "ParentId": "238844", "Score": "7" } }, { "body": "<p>First, this call to <code>__cxa_demangle</code> returns a buffer allocated with malloc and which must be freed. This isn't freed, so this code has a memory leak.</p>\n\n<p>Second, as I understand it, <code>__cxa_demangle</code> does not exist in MSVC, so this is not portable.</p>\n\n<p>Third, the <code>.find(\"string\")</code> catches more than <code>std::string</code>. It would match <code>std::wstring</code>, <code>std::stringstream</code>, <code>void (*)(std::string)</code>.</p>\n\n<p>Fourth, this code relies essentially on knowing the potential types that are in that <code>std::any</code>. That is knowledge at a distance, and if you allow more types at the place of construction, you need more types here.</p>\n\n<p>Fifth, if the type isn't one of those types, the error is silent and the output is the type contained, not the value. That could be harmless, but it could be a real problem. If you allowed type <code>Foo</code> in the <code>any</code>, and neglected to update this location, you wouldn't be able to tell if the output <code>Foo</code> was that type name or the value of a string stored in the <code>any</code>.</p>\n\n<p>The suggestion of the other answer is to constrain the types stored using the type storing them. Instead of <code>any</code> use <code>std::variant&lt;std::string, long long, unsigned long long, double&gt;</code>. I added the <code>string</code> and <code>unsigned</code> options relative to the other answer. Then just visit:</p>\n\n<pre><code>std::visit([&amp;](const auto&amp; value) { out &lt;&lt; value; }, n.value);\n</code></pre>\n\n<p>This is a very strong option.</p>\n\n<p>A second option would be to erase not almost every aspect of the type (as with <code>std::any</code>) but instead leave the interface you need, e.g. erase everything but the stream operator if that's all you need:</p>\n\n<pre><code> printable p = 2.3;\n std::cout &lt;&lt; p &lt;&lt; \"\\n\";\n p = \"foo\";\n std::cout &lt;&lt; p &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>Example: <a href=\"https://godbolt.org/z/NtJqWk\" rel=\"noreferrer\">https://godbolt.org/z/NtJqWk</a></p>\n\n<p>(edit: added a missing virtual destructor to impl_base)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T03:57:26.700", "Id": "468433", "Score": "0", "body": "Thank you for your feedback, Im getting way too ahead of myself and ended up stripping most everything away. I have been going though each one of your points and taking note. I appreciate your time and thanks for the great response!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T21:45:28.453", "Id": "238851", "ParentId": "238844", "Score": "10" } }, { "body": "<p><em>Other answers have already provided alternative solutions to <code>std::any</code>, such as <code>std::variant</code>, or inheritance; this answer will focus on correct usage of <code>std::any</code> itself.</em></p>\n\n<blockquote>\n <p>and so I've come up with a hacky way to get this information by detangling the value typename into a string and then using a ton of else if statements to compare this string</p>\n</blockquote>\n\n<p><code>std::any</code> does actually provide several ways to query the underlying type without relying on string parsing, let's review them below:</p>\n\n<pre><code>void ingest_any(std::any any)\n{\n try\n {\n std::cout &lt;&lt; std::any_cast&lt;std::string&gt;(any) &lt;&lt; \"\\n\";\n }\n catch (std::bad_any_cast const&amp;) {}\n\n if (std::string* str = std::any_cast&lt;std::string&gt;(&amp;any)) {\n std::cout &lt;&lt; *str &lt;&lt; \"\\n\";\n }\n\n if (std::type_index{ typeid(std::string) } == any.type()) {\n // Known not to throw, as previously checked.\n std::cout &lt;&lt; std::any_cast&lt;std::string&gt;(any) &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n\n<p>In general, when the actual type is not known, I would suggest either relying on the pointer form of <code>any_cast</code> for ad-hoc querying, or on <code>type_index</code> for look-ups.</p>\n\n<p>When you are about to create an if-ladder, you are in the look-up case:</p>\n\n<pre><code>using AnyAction = std::function&lt;void(std::any const&amp;)&gt;;\n\ntemplate &lt;typename T&gt;\nvoid print(std::any const&amp; a) { std::cout &lt;&lt; std::any_cast&lt;T&gt;(a) &lt;&lt; \"\\n\"; }\n\nstd::map&lt;std::type_index, AnyAction&gt; const Actions = {\n { typeid(std::string), print&lt;std::string&gt; },\n { typeid(unsigned long), print&lt;unsigned long&gt; },\n { typeid(long), print&lt;long&gt; },\n { typeid(double), print&lt;double&gt; },\n { typeid(float), print&lt;float&gt; },\n { typeid(char), print&lt;char&gt; },\n};\n\nvoid doit(std::any const&amp; a)\n{\n if (auto it = Actions.find(a.type()); it != Actions.end())\n {\n it-&gt;second(a);\n return;\n }\n\n std::cout &lt;&lt; \"Unknown type: \" &lt;&lt; a.type().name() &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p><a href=\"https://godbolt.org/z/iLqkrP\" rel=\"nofollow noreferrer\">See it in action on godbolt</a>.</p>\n\n<p>The main advantage of such maps is that they need not be <code>const</code>; you can instead use a run-time registry in which the user registers a type, as well as the appropriate (various) actions that can be undertaken on that type.</p>\n\n<p>This allows a core code which knows nothing of the concrete types, and therefore allows a library never to expose its internal types to the exterior world.</p>\n\n<p>Of course, in exchange for the flexibility, you pay a run-time penalty.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:30:42.260", "Id": "468608", "Score": "1", "body": "`using AnyAction = void (*)(std::any const &);` would work just as well but with less indirection so with slightly better performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T09:59:59.290", "Id": "468678", "Score": "0", "body": "@RomanOdaisky: In this very specific case, yes. As soon as you'd like to capture some state, it would stop working though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T13:19:24.370", "Id": "238883", "ParentId": "238844", "Score": "4" } }, { "body": "<p>You kept it concise. Anyone concerned with your code can easily comment it out and rewrite it. Add a test case and everyone will help you fix stuff if it needs it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T21:47:32.837", "Id": "238907", "ParentId": "238844", "Score": "-2" } }, { "body": "<p>You can avoid all the copypasta by writing a template function that tries a number of types in a row. The idea is that e. g. <code>visit_any_as&lt;int, double, char&gt;(any, visitor)</code> will try calling <code>visitor(std::any_cast&lt;int&gt;(any))</code> if possible, otherwise it will call <code>visit_any_as&lt;double, char&gt;(any, visitor)</code> to try the next type, and so on until the types are exhausted:</p>\n\n<pre><code>#include &lt;any&gt;\n#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;string&gt;\n#include &lt;utility&gt;\n\ntemplate &lt;class Visitor&gt;\nvoid visit_any_as(std::any const &amp;, Visitor &amp;&amp;)\n{\n throw std::logic_error(\"std::any contained no suitable type, unable to visit\");\n}\n\ntemplate &lt;class First, class... Rest, class Visitor&gt;\nvoid visit_any_as(std::any const&amp; any, Visitor&amp;&amp; visitor)\n{\n First const* value = std::any_cast&lt;First&gt;(&amp;any);\n if(value)\n {\n visitor(*value);\n }\n else\n {\n visit_any_as&lt;Rest...&gt;(any, std::forward&lt;Visitor&gt;(visitor));\n }\n}\n\nint main()\n{\n std::any any{-1LL};\n\n try\n {\n visit_any_as&lt;std::string, int, double, char&gt;(any, [](auto const&amp; x) {\n std::cout &lt;&lt; x &lt;&lt; std::endl;\n });\n }\n catch(std::exception const&amp; e)\n {\n std::cout &lt;&lt; e.what() &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p>However, do consider std::variant if you know in advance the list of possible types, as then std::visit will solve the problem much more neatly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T23:04:47.290", "Id": "238912", "ParentId": "238844", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T19:13:10.020", "Id": "238844", "Score": "7", "Tags": [ "c++", "beginner" ], "Title": "C++ how to use std::any_cast and avoid else if statements" }
238844
<p><strong>Assignment description</strong></p> <p>I'd like to receive feedback on an assignment which I'm currently working on. I have to make two traffic lights which allow traffic to run smoothly. I'm using a master Arduino which handles the main serial communication and one slave Arduino which handles the light sequence. Both lights turn red if the master Arduino is disconnected. <em>I must use the SoftwareSerial library.</em> The situation is shown below: <img src="https://i.stack.imgur.com/CWnbL.png" alt="1]"> <strong>Wiring</strong> <a href="https://i.stack.imgur.com/92fe3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/92fe3.png" alt="enter image description here"></a> <strong>Code master Arduino</strong></p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;SoftwareSerial.h&gt; SoftwareSerial serial(2, 3); // RX, TX // Timer unsigned long currentTime; unsigned long previousTime = 0; const unsigned long event = 50; String readString = ""; // String containing serial data bool sendACK = false; // Boolean regulating handshaking void setup() { Serial.begin(9600); // Native USB connection (baudrate 9600) Serial.setTimeout(10); while (!Serial) { ; // Wait for serial port to connect } serial.begin(9600); // SoftwareSerial connection (baudrate 9600) serial.setTimeout(10); // Maximum wait time } void loop() { currentTime = millis(); // Set current time /* Set string to incoming data. Once request to 'three-way handshake' has been acknowledged, set boolean sendACK to true, allowing "ACK" to be sent. */ if (serial.available() &gt; 0) { while (serial.available() &gt; 0) { readString = serial.readString(); Serial.print(readString); } if (readString == "SYN-ACK/") { sendACK = true; } } /* Send "SYN" to initiate 'three-way handshake'. Once connection established, send "ACK" */ if ((currentTime - previousTime) &gt; event) { if (sendACK == false) { serial.print("SYN/"); Serial.print("SYN/"); } else if (sendACK == true) { serial.print("ACK/"); Serial.print("ACK/"); sendACK = false; } previousTime = currentTime; } } </code></pre> <p><strong>Code slave Arduino</strong></p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;SoftwareSerial.h&gt; SoftwareSerial serial(8, 9); // RX, TX // First traffic light LED's const int redLED1 = 2; const int yellowLED1 = 3; const int greenLED1 = 4; // Second traffic light LED's const int redLED2 = 5; const int yellowLED2 = 6; const int greenLED2 = 7; long counter = 0; // Counter bool setLight = false; // Timer unsigned long currentTime; unsigned long previousTime = 0; const unsigned long event = 200; String readString = ""; // String containing serial data void setup() { // Multiple LED outputs pinMode(redLED1, OUTPUT); pinMode(yellowLED1, OUTPUT); pinMode(greenLED1, OUTPUT); pinMode(redLED2, OUTPUT); pinMode(yellowLED2, OUTPUT); pinMode(greenLED2, OUTPUT); serial.begin(9600); // SoftwareSerial connection (baudrate 9600) serial.setTimeout(10); // Maximum wait time } void loop() { currentTime = millis(); // Set current time /* Set string to incoming data. Establish 'three-way handshake' and count the amount of times handshaking performed. Set lights according to the handshakes counted. */ if (serial.available() &gt; 0) { while (serial.available() &gt; 0) { readString = serial.readString(); } if (readString == "SYN/") { serial.print("SYN-ACK/"); } else if (readString == "ACK/") { switch (counter) { case 0: digitalWrite(redLED1, HIGH); digitalWrite(redLED2, HIGH); break; case 10: digitalWrite(greenLED1, HIGH); digitalWrite(redLED1, LOW); break; case 40: digitalWrite(yellowLED1, HIGH); digitalWrite(greenLED1, LOW); break; case 50: digitalWrite(redLED1, HIGH); digitalWrite(yellowLED1, LOW); break; case 60: digitalWrite(greenLED2, HIGH); digitalWrite(redLED2, LOW); break; case 90: digitalWrite(yellowLED2, HIGH); digitalWrite(greenLED2, LOW); break; case 100: digitalWrite(redLED2, HIGH); digitalWrite(yellowLED2, LOW); break; } counter++; if (counter &gt; 100) { counter = 0; } } setLight = false; previousTime = currentTime; } // If handshake did not work, wait for 200 milliseconds and set traffic lights to red. else if ((currentTime - previousTime) &gt; event &amp;&amp; !setLight) { digitalWrite(redLED1, HIGH); digitalWrite(redLED2, HIGH); digitalWrite(yellowLED1, LOW); digitalWrite(yellowLED2, LOW); digitalWrite(greenLED1, LOW); digitalWrite(greenLED2, LOW); counter = 0; setLight = true; } } </code></pre> <p>Please give me feedback on my code and which parts I could do more efficiently. Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T07:36:05.907", "Id": "468444", "Score": "2", "body": "Welcome to CodeReview@SE. How is this `c++`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T15:31:27.507", "Id": "468484", "Score": "1", "body": "I have rolled this back to the original code. Please do not update it as a result of feedback; open a new question if you want another round of feedback." } ]
[ { "body": "<h2>Use a common protocol file</h2>\n\n<p>Any common constants, such as</p>\n\n<ul>\n<li>9600</li>\n<li><code>SYN</code>, <code>ACK</code>, etc. strings</li>\n</ul>\n\n<p>should be <code>#define</code>d in one place, in this case a <code>.h</code> file accessible to both Arduino projects.</p>\n\n<h2>Indentation</h2>\n\n<p>One-space indentation is essentially never used. Typically four is used instead.</p>\n\n<h2>Globals</h2>\n\n<p>In the master code, every single one of those globals should be moved to <code>loop()</code> and declared <code>static</code>. That way they will retain their value through multiple calls but will also have their scope reduced.</p>\n\n<h2>Efficiency</h2>\n\n<p>I realize a lot of these may fall outside of the constraints of your assignment; nevertheless:</p>\n\n<ul>\n<li>Don't use software-serial; use a hardware serial port</li>\n<li>Don't use Arduino; use smaller microcontrollers that are better-suited to your application</li>\n<li>Don't use ASCII string signalling; use single-byte constants. If fidelity is a concern, add a checksum.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T15:10:10.623", "Id": "468481", "Score": "0", "body": "Thanks for your feedback! I've made the following changes (and edited the code in the main question): 1. Added a header file. I don't know if I should make 3 header files (master Arduino constants, slave Arduino constants and common protocol) or one header like I made. 2. Changed constants and moved most to loop() function. 3. Changed indentation to four. Could you check if I did it correctly? Thanks again :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T15:29:58.083", "Id": "468483", "Score": "1", "body": "Please do not edit the code in the main question as a result of feedback - CR policy is that you open a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T15:32:12.970", "Id": "468485", "Score": "1", "body": "_I don't know if I should make 3 header files (master Arduino constants, slave Arduino constants and common protocol) or one header like I made._ 3, in my opinion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T15:53:59.200", "Id": "468486", "Score": "0", "body": "Alright I will open a new question and split the header file into 3" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T03:17:28.817", "Id": "238865", "ParentId": "238849", "Score": "3" } } ]
{ "AcceptedAnswerId": "238865", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T21:00:57.953", "Id": "238849", "Score": "2", "Tags": [ "c++", "c", "serialization", "arduino", "serial-port" ], "Title": "Feedback on Traffic Light which revolves around Serial Communication" }
238849
<p>I am learning graph theory in CS and for practice, I have implemented Djikstra's algorithm in Java. I have created a <code>GraphVertex</code> class that contains information about the vertex and <code>WeightedEdge</code> class which contains information about the edges and their weights. <code>DirectedGraphWithHeights</code> class contains the implementation of the algorithm.</p> <p>I received feedback <a href="https://codereview.stackexchange.com/questions/238800/directed-graph-with-weights-in-java">earlier</a> on Code Review and I have tried to improve on the naming convention I use in the classes.</p> <p>I wanted to understand if the methodology I am taking towards solving the algorithm and constructing the graph is up to the mark or not.</p> <p>DirectedGraphWithWeights </p> <pre><code>public class DirectedGraphWithWeights { private HashMap&lt;GraphVertex, LinkedList&lt;WeightedEdge&gt;&gt; adjacentVerticesByVertex; private Set&lt;GraphVertex&gt; vertexSet; /** * Constructor */ DirectedGraphWithWeights() { adjacentVerticesByVertex = new HashMap&lt;&gt;(); vertexSet = new HashSet&lt;&gt;(); } /** * Returns the number of vertices in the Graph * @return Returns the number of vertices */ public int getNumberOfVertices() { return this.vertexSet.size(); } /** * Adds a node to the graph. VertexA -&gt; VertexB, adding a vertex creates an * edge between VertexA and VertexB with the specified weight * @param vertexA Vertex A * @param vertexB Vertex B * @param weight Weight of the edge */ public void addEdge(int vertexA, int vertexB, int weight) { GraphVertex graphVertexA = new GraphVertex(vertexA); GraphVertex graphVertexB = new GraphVertex(vertexB); vertexSet.add(graphVertexA); vertexSet.add(graphVertexB); WeightedEdge weightedEdge = new WeightedEdge(weight, graphVertexA, graphVertexB); if(!adjacentVerticesByVertex.containsKey(graphVertexA)) adjacentVerticesByVertex.put(graphVertexA, new LinkedList&lt;WeightedEdge&gt;()); adjacentVerticesByVertex.get(graphVertexA).add(weightedEdge); } /** * Returns all the adjacent nodes * @param source Source node * @return Returns all the adjacent nodes */ public Iterable&lt;WeightedEdge&gt; getAdjacentVertices(int source) { GraphVertex tempNode = new GraphVertex(source); return adjacentVerticesByVertex.get(tempNode); } /** * Djikstra's algorithm implementation */ public void calculateShortedPath(int source) { Set&lt;GraphVertex&gt; visitedVertices = new HashSet&lt;&gt;(); GraphVertex sourceVertex = new GraphVertex(source); HashMap&lt;GraphVertex, Integer&gt; shortestPathMap = new HashMap&lt;&gt;(); // Set the value of all vertex -&gt; weight to infinity and to the source // to 0 for(GraphVertex vertex : vertexSet) { if(vertex.equals(sourceVertex)) shortestPathMap.put(sourceVertex, 0); else shortestPathMap.put(vertex, Integer.MAX_VALUE); } // TODO: Move this to a function later // Get all the nodes which can be visited from the start node for(WeightedEdge edge : adjacentVerticesByVertex.get(sourceVertex)) { shortestPathMap.put(edge.getDestination(), edge.getEdgeWeight()); } visitedVertices.add(sourceVertex); // The function will work until there are no more nodes to visit while(true) { // Next closest vertex GraphVertex currentVertex = getLowestWeightVertex(shortestPathMap, visitedVertices); if(visitedVertices.size() == vertexSet.size()) { break; } visitedVertices.add(currentVertex); // Get the adjacent vertices to the currentVertex and update the // shortestPathMap if(adjacentVerticesByVertex.containsKey(currentVertex)) { for(WeightedEdge edge : adjacentVerticesByVertex.get(currentVertex)) { if(!visitedVertices.contains(edge.getDestination())) { int edgeWeightCumulative = shortestPathMap.get(currentVertex) + edge.getEdgeWeight(); int edgeDestinationWeight = shortestPathMap.get(edge.getDestination()); if(edgeWeightCumulative &lt; edgeDestinationWeight) { shortestPathMap.put(edge.getDestination(), edgeWeightCumulative); } } } } } System.out.println(shortestPathMap); } /** * Gets * @param shortestPathMap * @param visitedVertices * @return */ private GraphVertex getLowestWeightVertex( HashMap&lt;GraphVertex, Integer&gt; shortestPathMap, Set&lt;GraphVertex&gt; visitedVertices) { int lowestWeight = Integer.MAX_VALUE; GraphVertex lowestVertex = null; for(GraphVertex vertex : vertexSet) { if(!visitedVertices.contains(vertex)) { if(shortestPathMap.get(vertex) &lt; lowestWeight) { lowestWeight = shortestPathMap.get(vertex); lowestVertex = vertex; } } } return lowestVertex; } } </code></pre> <p>WeightedEdge.java</p> <pre><code>public class WeightedEdge { private GraphVertex source; private GraphVertex destination; private int edgeWeight; WeightedEdge(int edgeWeight, GraphVertex source, GraphVertex destination) { this.edgeWeight = edgeWeight; this.source = source; this.destination = destination; } public GraphVertex getSource() { return source; } public void setSource(GraphVertex source) { this.source = source; } public GraphVertex getDestination() { return destination; } public void setDestination(GraphVertex destination) { this.destination = destination; } public int getEdgeWeight() { return edgeWeight; } public void setEdgeWeight(int edgeWeight) { this.edgeWeight = edgeWeight; } } </code></pre> <p>GraphVertex.java</p> <pre><code>public class GraphVertex implements Comparator&lt;GraphVertex&gt; { private int value; GraphVertex(int value) { this.value = value; } public int getValue() { return this.value; } @Override public int hashCode() { return new Integer(this.value).hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GraphVertex other = (GraphVertex) obj; if(value != other.getValue()) return false; return true; } /** * Compares two nodes. The comparison is based on the value in the node * @param one * @param two * @return */ public int compare(GraphVertex one, GraphVertex two) { if(one.value == two.value) return 0; return one.value &gt; two.value ? 1 : -1; } } </code></pre>
[]
[ { "body": "<p><em>I'm by no means a java programmer, just some things I noticed.</em></p>\n\n<hr>\n\n<h1><code>GraphVertex.equals</code></h1>\n\n<p>This method is messy to say the least. The number of <code>return</code> in this method mixed with <code>if</code> statements with no brackets makes it hard to read. And, it looks like you only want to check one condition, anything else other than that would result in a <code>false</code> return. Now, you only have to check for a <code>null</code> value. Have a look:</p>\n\n<pre><code>@Override\npublic boolean equals(Object obj) {\n return (obj == null) || (this == obj);\n}\n</code></pre>\n\n<h1><code>GraphVertex.compare</code></h1>\n\n<p>I see you've already used a ternary operator, nice. You can simplify this even further using another ternary operator. Have a look:</p>\n\n<pre><code>public int compare(GraphVertex one, GraphVertex two) {\n return (one.value == two.value) \n ? 0 \n : (one.value &gt; two.value) \n ? 1 \n : -1;\n}\n</code></pre>\n\n<p>I used some tabbing to make it more clear what is being compared.</p>\n\n<h1>One line if statements</h1>\n\n<p>It's a convention to use brackets even when there's only one line after the <code>if</code> statement. It increases readability and makes your code clearer.</p>\n\n<h1>Constructors</h1>\n\n<p>Unless you want to label a constructor as something other than <code>public</code>, I would keep it, for example, <code>public GraphVertex(int value) { ... }</code>.</p>\n\n<h1><code>DirectedGraphWithWeights.getAdjacentVertices</code></h1>\n\n<p>For this method you don't have to create the variable <code>tempNode</code>. Instead, you can return an anonymous object. Have a look:</p>\n\n<pre><code>public Iterable&lt;WeightedEdge&gt; getAdjacentVertices(int source) {\n return adjacentVerticesByVertex.get(new GraphVertex(source));\n}\n</code></pre>\n\n<h1>Better looping</h1>\n\n<p>Instead of having one break condition, you can put that inside the while loop. This is so the <code>while</code> loop is solely dependent on that condition, instead of dependent on the <code>break</code> condition. Something like this:</p>\n\n<pre><code>while (visitedVertices.size() == vertexSet.size()) { ... }\n</code></pre>\n\n<h1>Using <code>this</code></h1>\n\n<p>Using <code>this</code> when referencing instance variables can help you keep track of what variables were made in the constructor, and what were made solely in the methods of the class. It's on your discretion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:50:13.667", "Id": "468740", "Score": "0", "body": "Just FYI on `GraphVertex.equals` This is pretty much the standard way of implementing equals on Java. It looks like the code might have been auto generated. As such I'd call the number of `return` statements normal. Most of them are short-circuit checks for common conditions, or error checking that we want to return `false` for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T00:59:46.040", "Id": "238968", "ParentId": "238854", "Score": "0" } }, { "body": "<p><em>Hey, I think you have pretty nice code there already. Anyways, I have some suggestions:</em></p>\n\n<hr>\n\n<h2>Formatting</h2>\n\n<p><em>This looks pretty good already so please don't take the points to seriously. Mostly it's my personal preferences.</em></p>\n\n<hr>\n\n<p>I don't like breaking variable definitions like so:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private HashMap&lt;GraphVertex, LinkedList&lt;WeightedEdge&gt;&gt;\n adjacentVerticesByVertex;\n</code></pre>\n\n<p>You could mistake it with a function when scrolling over the code.</p>\n\n<hr>\n\n<p>I don't like breaking code like so:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> int edgeWeightCumulative =\n shortestPathMap.get(currentVertex) +\n edge.getEdgeWeight();\n</code></pre>\n\n<p>It's harder to read. Usually you want to split what is logically splittable but not single statements.</p>\n\n<hr>\n\n<p><em>You have more places with strange breaks but I guess you wanted to do it for the post here. Just keep in mind to put a little bit more thoughts into breaks. I won't repeat for the other places.</em></p>\n\n<hr>\n\n<p>You don't have an empty line at the beginning of <code>DirectedGraphWithWeights</code> like in the other classes. Please decide for one thing and do it consistently.</p>\n\n<hr>\n\n<p>Please add a space after keywords for control structures.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> if(visitedVertices.size() == vertexSet.size()) {\n break;\n }\n</code></pre>\n\n<p>It will make things more readable.</p>\n\n<hr>\n\n<p>You should add empty space between overall text and keywords in the documentation.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> /**\n * Returns the number of vertices in the Graph\n * @return Returns the number of vertices\n */\n</code></pre>\n\n<hr>\n\n<h2>Naming</h2>\n\n<hr>\n\n<p>It's a directed graph so all methods should respect that in naming.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public void addEdge(int vertexA, int vertexB, int weight) {\n</code></pre>\n\n<p><code>A</code> and <code>B</code> can be replaced by <code>Source</code> or <code>Src</code> and <code>Destination</code> or <code>Dest</code>.</p>\n\n<hr>\n\n<p>The <code>value</code> variable in <code>GraphVertex</code> should be named something like <code>index</code>. When it's called <code>value</code> you could assume that two vertices can have the same value for that. As well, this will make the following method much clearer as you notice that vertices are addressed by their index.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public void addEdge(int vertexA, int vertexB, int weight) {\n</code></pre>\n\n<hr>\n\n<h2>Syntax</h2>\n\n<hr>\n\n<p>Don't use <code>this</code> keyword where you don't need to.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public int getNumberOfVertices() {\n return this.vertexSet.size();\n }\n</code></pre>\n\n<hr>\n\n<p>One line if statements should be avoided in general but especially multiple ones at the same place.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass()) return false;\n GraphVertex other = (GraphVertex) obj;\n if(value != other.getValue()) return false;\n return true;\n }\n</code></pre>\n\n<p>It's harder to read for no real benefit in exchange.</p>\n\n<hr>\n\n<p>Consider making <code>adjacentVerticesByVertex</code> and <code>vertexSet</code> <code>final</code> because the reference is never changed.</p>\n\n<hr>\n\n<p>I don't see why you should use a <code>LinkedList</code> here. The benefit is performance when you are removing items often. This is not the case for your code.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private HashMap&lt;GraphVertex, LinkedList&lt;WeightedEdge&gt;&gt;\n adjacentVerticesByVertex;\n</code></pre>\n\n<hr>\n\n<p>The temporary variable is not necessary here. Just create the instance in the getter argument.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public Iterable&lt;WeightedEdge&gt; getAdjacentVertices(int source) {\n GraphVertex tempNode = new GraphVertex(source);\n return adjacentVerticesByVertex.get(tempNode);\n }\n</code></pre>\n\n<hr>\n\n<h2>Documentation</h2>\n\n<p><em>I must say that you don't have the best documentation. It's easy to get the feeling that the reader will understand the code as you do while writing, but that is not the case. Try to write more extensive documentation that includes explanations to the algorithm itself. Also add more detailed documentation to the functions and methods. Keep in mind that in production code, you want to minimize the time someone needs to understand the code. Time is money.</em></p>\n\n<hr>\n\n<p>Please avoid documentation that is not adding information to the code. In <code>WeightedEdge</code> you didn't add any comments to the trivial methods as it should be. But in <code>DirectedGraphWithWeights</code> you did:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> /**\n * Constructor\n */\n DirectedGraphWithWeights() {\n adjacentVerticesByVertex = new HashMap&lt;&gt;();\n vertexSet = new HashSet&lt;&gt;();\n }\n</code></pre>\n\n<p>Have a look at <a href=\"https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/util/ArrayList.java\" rel=\"nofollow noreferrer\">ArrayList</a> on GitHub. It's good reference for documentation.</p>\n\n<hr>\n\n<h2>Design</h2>\n\n<p><em>While writing I'm checking constantly your logic. I can't find anything realy mentionable and think you did a good job on applying the algorithm itself on the class structure you created.</em></p>\n\n<hr>\n\n<p>You could have done something different when creating the class structure. The directed graph, including the vertices and edges, and the algorithm itself are two different concepts. Your program could reflect that with an additional class <code>DijkstraAlgorithm</code> or <code>DijkstraSolver</code> that has a static method with a parameter for <code>DirectedGraphWithWeights</code> to apply the algorithm on.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class DijkstraAlgorithm {\n public static void solve(DirectedGraphWithWeights graph) {\n // Apply algorithm and print the result.\n }\n}\n</code></pre>\n\n<p>Another thing is that an edge can be regarded as a relationship between two vertices. The relationship has three attributes, i.e.:</p>\n\n<ul>\n<li>One vertex is the source.</li>\n<li>The other is the destination.</li>\n<li>The weight of the relationship.</li>\n</ul>\n\n<p>In your code you made the relationships a map with vertex as key and its relationships as value. This has to be managed like in the following code.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public void addEdge(int vertexA, int vertexB, int weight) {\n GraphVertex graphVertexA = new GraphVertex(vertexA);\n GraphVertex graphVertexB = new GraphVertex(vertexB);\n vertexSet.add(graphVertexA);\n vertexSet.add(graphVertexB);\n WeightedEdge weightedEdge = new WeightedEdge(weight, graphVertexA,\n graphVertexB);\n if(!adjacentVerticesByVertex.containsKey(graphVertexA))\n adjacentVerticesByVertex.put(graphVertexA, new\n LinkedList&lt;WeightedEdge&gt;());\n adjacentVerticesByVertex.get(graphVertexA).add(weightedEdge);\n }\n</code></pre>\n\n<p>As the relationships are seperated from the concept <em>vertex</em> by the class <code>WeightedEdge</code>, the key value is stored in every relationship entity which is redundant. When I get the value for a key vertex, I get a list of <code>WeightedEdge</code> instances that all have the same key vertex as a field. Every vertex should know its relationship to other vertices.</p>\n\n<p>A solution to that is to let every vertex manage its relations itself. As the graph is directed this will be reflected perfectly by a net of such vertices. To represent the weight we can simply make use of a map. An entry represents a key neighbour vertex and a value weight.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class GraphVertex {\n public final Map&lt;GraphVertex, Integer&gt; edges;\n public final int index; // The 'value' in your version.\n\n // All the methods needed for the algorithm.\n}\n</code></pre>\n\n<p>Another think you could think about is not having indexing at all because it's not relevant to the algorithm. The algorithm only needs to know the first vertex. The first vertex is always the one that is not the destination of any relationship, or rather edge. The final vertex is the one that is not the source for any relationship, or rather edge. This will ensure that the graph organization is fully representable by the data itself. A class to represent the graph would become redundant. You can keep a variable to give the vertices good names for printing the result.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Vertex {\n public final Map&lt;Vertex, Integer&gt; edges;\n public final String name;\n\n public Vertex(String name) {\n edges = new HashMap&lt;&gt;();\n this.name = name;\n }\n\n public Vertex addEdge(Vertex other, int weight) {\n edges.put(other, weight);\n return this;\n }\n\n public static void main(String[] args) {\n Vertex start = new Vertex(\"start\");\n Vertex otherA = new Vertex(\"otherA\");\n Vertex otherB = new Vertex(\"otherB\");\n Vertex end = new Vertex(\"end\");\n\n start.addEdge(otherA, 1).addEdge(otherB, 2);\n otherA.addEdge(otherB, 3).addEdge(end, 4);\n otherB.addEdge(end, 5);\n }\n\n // Other stuff.\n}\n</code></pre>\n\n<p>This would limit you to some degree though because you will have a hard time in changing a graph. You will have an even harder time to go through the graph in a different way than from the implicit starting to the ending vertex. A class to manage that would become necessary. Anyways, these are all implementation details and depend on your requirements.</p>\n\n<p>I've found <a href=\"https://www.baeldung.com/java-graphs\" rel=\"nofollow noreferrer\">this</a> tutorial that has a very similar approach to what you did. Maybe you can find some impressions there as well.</p>\n\n<hr>\n\n<p><em>I won't program the whole thing for you to post it here but you should have a good idea about what you could improve in your code to make it more object oriented and cleaner.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T03:14:16.920", "Id": "238974", "ParentId": "238854", "Score": "3" } }, { "body": "<p>Two small, related points</p>\n\n<pre><code>public void calculateShortedPath(int source) \n</code></pre>\n\n<p>Seems like it should be <code>calculateShortestPath</code> (not Shorted). At the moment the method returns void and is responsible for both calculating the path and printing it out. Consider changing it to return the shortest path instead, so that the caller can decide what it wants to do with the path (print it / use it for navigation). This is likely to make the code easier to reusing going forward.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T09:18:38.033", "Id": "238989", "ParentId": "238854", "Score": "0" } } ]
{ "AcceptedAnswerId": "238974", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:09:53.047", "Id": "238854", "Score": "4", "Tags": [ "java", "graph" ], "Title": "Dijkstra's Algorithm implementation in Java" }
238854
<p>I would like to use this feature</p> <pre><code>&gt;&gt;&gt; def func(): &gt;&gt;&gt; return 1, 2 &gt;&gt;&gt; x, y = func() </code></pre> <p>But I have a formatting problem, because I want to assign values in the <code>__init__()</code> of a Class.</p> <pre><code>import csv class Filewriter: def __init__(self, jsonstring, filepath): self.katAsk, self.katBid, self.promAsk, self.promBid, self.montAsk, self.montBid, self.katProm, self.katMont, self.promKat, self.promMont, self.montKat, self.montProm, self.ticker = self.get_row() self.jsonstring = jsonstring self.filepath = filepath def jsonparse(self, ticker, label): try: output = self.jsonstring[ticker][label] except (KeyError, ValueError) as e: output = None return output def test(self, teststring, ticker, cx): return self.jsonparse(ticker, cx+"."+teststring) def get_row(self, ticker): checkdic = {"ticker": ticker} # Check if asks/bids exist checkdic["cx"] = "CI1" try: katAsk = float(self.test("ask", **checkdic)) except (TypeError, ValueError) as e: katAsk = -1 try: katBid = float(self.test("bid", **checkdic)) except (TypeError, ValueError) as e: katBid = -1 checkdic["cx"]="IC1" try: promAsk = float(self.test("ask", **checkdic)) except (TypeError, ValueError) as e: promAsk = -1 try: promBid = float(self.test("bid", **checkdic)) except (TypeError, ValueError) as e: promBid = -1 checkdic["cx"]="NC1" try: montAsk = float(self.test("ask", **checkdic)) except (TypeError, ValueError) as e: montAsk = -1 try: montBid = float(self.test("bid", **checkdic)) except (TypeError, ValueError) as e: montBid = -1 # bidDest - askSource = sales # Determine sales # Kat -&gt; Prom if(promBid &gt; 0 and katAsk &gt; 0): katProm = promBid - katAsk else: katProm = -1 # Kat -&gt; Mont if(montBid &gt; 0 and katAsk &gt; 0): katMont = montBid - katAsk else: katMont = -1 # Prom -&gt; Kat if(katBid &gt; 0 and promAsk &gt; 0): promKat = katBid - promAsk else: promKat = -1 # Prom -&gt; Mont if(montBid &gt; 0 and promAsk &gt; 0): promMont = montBid - promAsk else: promMont = -1 # Mont -&gt; Kat if(katBid &gt; 0 and montAsk &gt; 0): montKat = katBid - montAsk else: montKat = -1 # Mont -&gt; Prom if(promBid &gt; 0 and montAsk &gt; 0): montProm = promBid - montAsk else: montProm = -1 return katAsk, katBid, promAsk, promBid, montAsk, montBid, katProm, katMont, promKat, promMont, montKat, montProm, ticker def tablewriter(self): with open(self.filepath, mode='w', newline='') as ag: agWriter = csv.writer(ag, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) agWriter.writerow([self.ticker, self.katAsk, self.katBid, self.promAsk, self.promBid, self.montAsk, self.montBid, "", self.katProm, self.katMont, self.promKat, self.promMont, self.montKat, self.montProm, "", ]) </code></pre> <p>Is it possible to format this statement on more than one line ?</p> <p>edit: edited with real code</p> <p>edit2: noticed a missing "self." before test() calls</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T00:27:24.020", "Id": "468420", "Score": "0", "body": "Thank you for the edit, this looks good. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T00:48:58.997", "Id": "468421", "Score": "0", "body": "I have to add, that I'm trying here to convert a bad written stand alone python script into a module for a webapp. I'm not sure if the whole process should be re-thinked. Maybe the use of a class is not the right one?" } ]
[ { "body": "<p>Use parens:</p>\n\n<pre><code>(self.katAsk, self.katBid, self.promAsk, self.promBid, self.montAsk,\n self.montBid, self.katProm, self.katMont, self.promKat, self.promMont,\n self.montKat, self.montProm, self.ticker) = self.get_row()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T01:04:46.860", "Id": "468422", "Score": "0", "body": "Those variables may be stored in a tupple?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T01:12:49.667", "Id": "468423", "Score": "0", "body": "@Halavus `self.get_row` returns a tuple. `1, 2` is short hand for `(1, 2)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T01:48:07.060", "Id": "468424", "Score": "0", "body": "The target (the left hand side) of an [assignment statement](https://docs.python.org/3.6/reference/simple_stmts.html?#assignment-statements) can be an iterable such as a list or tuple. Here, the commas make it a tuple, the parens just let it span multiple lines. You could use '[' and ']' instead." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T01:02:45.380", "Id": "238858", "ParentId": "238857", "Score": "2" } } ]
{ "AcceptedAnswerId": "238858", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T23:54:17.007", "Id": "238857", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Assign multiple values to variables with a function in a class" }
238857
<p>Some Task methods don't take cancellation tokens. This is a problem because some long-running tasks may never finish and there is no way to send them a cancellation request. This seems a bit dodgy to me but this is a workaround. <strong><em>Is there anything wrong with this? Is there a better way?</em></strong></p> <pre><code>public static Task&lt;T&gt; SynchronizeWithCancellationToken&lt;T&gt;(this Task&lt;T&gt; task, int delayMilliseconds = 10, CancellationToken cancellationToken = default) { if (task == null) throw new ArgumentNullException(nameof(task)); while (!task.IsCompleted &amp;&amp; !task.IsFaulted &amp;&amp; !task.IsCanceled) { Thread.Sleep(delayMilliseconds); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled&lt;T&gt;(cancellationToken); } } return task; } </code></pre> <p><strong>Example</strong></p> <p>The methods where this is a problem tend to be obscure APIs that haven't had much love in a long time or APIs that are wrappers for other platforms. One example is <a href="https://docs.microsoft.com/en-us/dotnet/api/android.hardware.usb.usbdeviceconnection.requestwaitasync?view=xamarin-android-sdk-9" rel="nofollow noreferrer"><code>RequestWaitAsync</code></a> on <code>UsbDeviceConnection</code>. It's a wrapper for an Android USB API . The issue can be worked around like so:</p> <pre><code>var buffers = await GetReadResultAsync(bufferLength, byteBuffer).SynchronizeWithCancellationToken(cancellationToken); </code></pre> <p>Another way to workaround the issue might be with <code>Task.Run</code></p> <pre><code>public async Task&lt;ReadResult&gt; ReadAsync(uint bufferLength, CancellationToken cancellationToken = default) { return await Task.Run(async () =&gt; { try { //... return await GetReadResultAsync(bufferLength, byteBuffer); } catch (Exception ex) { //... } }, cancellationToken); } </code></pre> <p><strong><em>Which of these two work arounds are the safest?</em></strong></p> <p><strong><em>Unit Test</em></strong></p> <p>This is a pathetic attempt at a unit test. It passes:</p> <pre><code>[TestMethod] public async Task TestSynchronizeWithCancellationToken() { var stopWatch = new Stopwatch(); stopWatch.Start(); var completed = false; var task = Task.Run&lt;bool&gt;(() =&gt; { //Iterate for one second for (var i = 0; i &lt; 100; i++) { Thread.Sleep(10); } return true; }); var cancellationTokenSource = new CancellationTokenSource(); //Start a task that will cancel in 500 milliseconds var cancelTask = Task.Run&lt;bool&gt;(() =&gt; { Thread.Sleep(500); cancellationTokenSource.Cancel(); return true; }); //Get a task that will finish when the cancellation token is cancelled var syncTask = task.SynchronizeWithCancellationToken(cancellationToken: cancellationTokenSource.Token); //Wait for the first task to finish var completedTask = (Task&lt;bool&gt;) await Task.WhenAny(new Task[] { syncTask, cancelTask }); //Ensure the task didn't wait a long time Assert.IsTrue(stopWatch.ElapsedMilliseconds &lt; 1000); //Ensure the task wasn't completed Assert.IsFalse(completed); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T13:06:47.517", "Id": "468706", "Score": "1", "body": "You might want to take a look at https://stackoverflow.com/a/25652873" } ]
[ { "body": "<p>Starting with the first function, I would make a few changes:</p>\n\n<ul>\n<li><code>Task.IsCompleted</code> covers all completion states already (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.iscompleted?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.iscompleted?view=netframework-4.8</a>)</li>\n<li>Tasks are all about not blocking the current thread. Never use <code>Thread.Sleep</code> and always use <code>Task.Delay</code>.</li>\n<li>Cancellation can be more succinctly handled with <code>Task.ThrowIfCancellationRequested</code></li>\n</ul>\n\n<pre><code>public static async Task&lt;T&gt; SynchronizeWithCancellationToken&lt;T&gt;(this Task&lt;T&gt; task, int delayMilliseconds = 10, CancellationToken cancellationToken = default)\n{\n if (task == null)\n throw new ArgumentNullException(nameof(task));\n\n while (!task.IsCompleted)\n {\n await Task.Delay(delayMilliseconds);\n cancellationToken.ThrowIfCancellationRequested();\n }\n\n return await task;\n}\n</code></pre>\n\n<p>This is about as good as it gets to \"add cancellation\" to a Task that doesn't do cancellation. The key to understanding Task cancellation in .NET is that it is cooperative. This means that simply passing a cancellation token around doesn't do anything on its own; instead the Task implementation itself has to handle cancellation. This makes a lot of sense since only the Task implementation itself knows when best to allow cancellation without causing invalid state or corruption.</p>\n\n<p>I would definitely recommend taking the time to do a read-through of the MSDN article on this: <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation?view=netframework-4.8</a></p>\n\n<p>Your second function attempts to use the <code>Task.Run</code> overload that takes a <code>CancellationToken</code> in order to cancel the operation. However, <code>Task.Run</code> only uses the token to avoid starting the Task (if it's already cancelled when it goes to run it), and it's left to the user to use the token inside the implementation passed to <code>Task.Run</code> to handle further cancellation. See here: <a href=\"https://stackoverflow.com/questions/22637642/using-cancellationtoken-for-timeout-in-task-run-does-not-work\">https://stackoverflow.com/questions/22637642/using-cancellationtoken-for-timeout-in-task-run-does-not-work</a></p>\n\n<p>The first method is definitely the one you want to use. Just remember that it isn't <em>true cancellation</em> which would require you to modify the implementation of the API function and add the cooperative cancellation bits. When you add cancellation like this, without the implementation bits, you're only cancelling the wait for the Task to finish, not the Task itself. If the Task has further operations to carry out, they will still be carried out. This can often times be a deal breaker with some APIs, and you might be forced to find an alternative implementation that handles cancellation, or even implement your own.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>It also slipped my mind that you can use <code>CancellationToken.Register</code> to asynchronously wait and get rid of the polling...</p>\n\n<pre><code> public static async Task ToTask(this CancellationToken token)\n {\n var source = new TaskCompletionSource&lt;object&gt;();\n using (token.Register(() =&gt; source.SetResult(null)))\n await source.Task;\n }\n\n public static async Task&lt;T&gt; SynchronizeWithCancellationToken&lt;T&gt;(this Task&lt;T&gt; task,\n CancellationToken cancellationToken = default, string message = default)\n {\n if (task == null)\n throw new ArgumentNullException(nameof(task));\n\n if (await Task.WhenAny(task, cancellationToken.ToTask()) == task)\n return await task;\n else\n throw new OperationCanceledException(message ?? \"The operation was canceled.\");\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T16:23:17.913", "Id": "533873", "Score": "0", "body": "I don't think you need to wait for the task twice, since you've already **\"awaited\"** for it using WhenAny, you can just get the result, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T01:40:05.180", "Id": "534045", "Score": "0", "body": "One reason to reason to use `await` instead of `.Result` in this case is that `.Result` will always wrap any exceptions thrown by the Task in an AggregateException which can be annoying to handle further up. There's probably a few other quirks I can't think of at the moment as well..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T01:43:33.760", "Id": "534046", "Score": "1", "body": "Ah yep it was something to do with deadlocks; here's the more in-depth info on it, if you're interested:\nhttps://stackoverflow.com/questions/24623120/await-on-a-completed-task-same-as-task-result" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T19:56:17.853", "Id": "239019", "ParentId": "238859", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T01:09:09.610", "Id": "238859", "Score": "4", "Tags": [ "c#", "async-await" ], "Title": "Cancelling A Task Without Cancellation Token" }
238859
<p>While working on a project to do some spatial data processing in PostgreSQL, I found it cumbersome to use the <code>psycopg2.sql</code> objects to safely compose queries. I wrote a small wrapper over the formatting functionality of <code>psycopg2.sql.SQL.format</code> which allows you to specify the type of argument that a query placeholder is expecting. It also comes with a few unit tests, though I don't have as much experience in writing them.</p> <p>I would really love some feedback on how the style, structure and even the concept can be improved.</p> <strong><code>template-query.py</code></strong> <pre><code># -*- coding: utf-8 -*- &quot;&quot;&quot; Module for the `TemplateQuery` class which makes it easier compose SQL queries for psycopg2 when specifying the sql object type of placeholders to prevent SQL injection vulnerabilities. &quot;&quot;&quot; from typing import Union, Iterator, Match, List, Dict, Tuple, Any from psycopg2.sql import Literal, Identifier, SQL, Placeholder, Composed import re from functools import reduce _dot = '.' _sql_dot = SQL(_dot) def _dot_separated_identifier( qualified_name_string: str ) -&gt; Union[Identifier, Composed]: &quot;&quot;&quot; Converts the qualified name string `qualified_name_string` containing multiple dot-separated identifiers into a `Composed` object joining each subname formatted with `Identifier` with a sql dot, or a single `Identifier` if the name string contains no dots. &quot;&quot;&quot; try: first_dot_index = qualified_name_string.index(_dot) except ValueError: # no split character so the whole string is the identifier return Identifier(qualified_name_string) schema = qualified_name_string[:first_dot_index] table = qualified_name_string[first_dot_index + 1:] return _sql_dot.join(( Identifier(schema), Identifier(table) )) class TemplateQuery: &quot;&quot;&quot;Template query with psyopg2.sql placeholder embedded in the query string. Stores `query_text` as a template and replaces placeholders in the string with arguments that can be formatted based on tags inside the placeholder key. Formatting placeholders in `query_text` are written as `{key@X}` where `key` is the name of a keyword argument supplied to TemplateQuery.format and `X` is one of the following psyqcopg2.sql types: S: (SQL) raw query snippet with no escaping !!beware of SQL injection!! I: (Identifier) identifier representing names of database objects L: (Literal) value hardcoded into the query P: (Placeholder) %s style placeholder whose value can be added later Q: qualified name which is multiple dot-separated identifiers. In psycopg2 2.8, the same effect can be achieved by passing the identifiers as a `Tuple` of strings to the I: (Identifier) formatter If `X` is not one of the options above, the placeholder key will be treated as a regular placeholder, and the key should be present in the keyword args supplied to the `format` method. If `key` is not supplied, the placeholder draws its value from a positional argument. Regular placeholders (as used in `str.format`) are also supported, but the values passed to their arguments need to be `Composable` objects which are accepted by `psycopg2.sql.SQL.format`. Args: query_text: Query string that has placeholders which can be formatted. Examples: Simple schema-qualified table name and column value: &gt;&gt;&gt; TemplateQuery('SELECT * FROM {@Q} WHERE foo={foo@L}').format( ... 'schema.table', foo='bar' ... ) Composed([SQL('SELECT * FROM '), Composed([Identifier('schema'), SQL('.'), Identifier('table')]), SQL(' WHERE foo='), Literal('bar')]) With regular arguments: &gt;&gt;&gt; TemplateQuery('SELECT * FROM my_table WHERE foo{@S}{@L}').format( ... '&lt;', Literal(3) ... ) Composed([SQL('SELECT * FROM my_table WHERE foo'), Literal(SQL('&lt;')), Literal(3)]) &quot;&quot;&quot; # Acceptable placeholder formatting tags and the functions that are used to # format the arguments served to those placeholders. _placeholder_formatters = { 'S': SQL, 'I': Identifier, 'L': Literal, 'P': Placeholder, 'Q': _dot_separated_identifier } # String that marks a placeholder key as one that needs to be formatted and # separated the key name from the format. _placeholder_marker = '@' # Regex search flags used in conjunction with `placeholder_pattern`. # braces doubled up to account for string formatting _placeholder_pattern = r&quot;&quot;&quot; \{{ (?P&lt;key&gt; # full key name including market and form (?P&lt;subkey&gt; # key name excluding the market and form [^\{{\}}]*? ) (?: {marker} # the marker character (?P&lt;format&gt;{formats}) # each possible form separated by | )? ) \}} &quot;&quot;&quot; # Regex search flags for the placeholder_pattern placeholder_search_flags = re.VERBOSE def __init__(self, query_text: str): self._matches = list(self._placeholder_matches_iterator(query_text)) self._adjusted_query = self._adjusted_query_from_matches( query_text, self._matches ) def _placeholder_matches_iterator( self, raw_query: str ) -&gt; Iterator[Match]: &quot;&quot;&quot;Returns iterator of all placeholder matches in `raw_query`&quot;&quot;&quot; possible_formats = list(self._placeholder_formatters.keys()) formatted_pattern = self._placeholder_pattern.format( formats='|'.join(possible_formats), marker=self._placeholder_marker ) compiled_pattern = re.compile( formatted_pattern, self.placeholder_search_flags ) return compiled_pattern.finditer(raw_query) @staticmethod def _adjusted_query_from_matches( raw_query: str, matches: List[Match], replace_with='{}', ) -&gt; str: &quot;&quot;&quot; Returns `raw_query` with formatted placeholders (e.g. `{@I}`) replaced with regular placeholders `{}`. &quot;&quot;&quot; # should be no multi-pass collisions since relevant matches # must have a format and target is an empty placeholder return reduce( lambda string, to_replace: string.replace(to_replace, replace_with), ( m.group() for m in matches if m['format'] is not None and m['subkey'] is '' ), raw_query ) def _process_format_args( self, *args, **kwargs ) -&gt; Tuple[List, Dict[str, Any]]: &quot;&quot;&quot; Returns `args` and `kwargs` with formatting applied to their values based on how their position or key matches with that of placeholder matches in the originally supplied `query_string` &quot;&quot;&quot; # which positional argument to draw from next posn_arg_index = 0 # total number of arguments posn_arg_count = len(args) # args to list so that items can be modified args = list(args) # kwarg keys that have a formatted placeholder formatted_kwarg_keys = set() # kwarg keys that have a regular placeholder unformatted_kwarg_keys = set() for match in self._matches: key = match['key'] subkey = match['subkey'] format_key = match['format'] if format_key is None: # regular placeholder and the argument does not need to be # formatted if subkey is '': # positional argument posn_arg_index += 1 else: # keyword argument unformatted_kwarg_keys.add(subkey) else: # special placeholder and the argument needs to be formatted # function used to format the argument based on placeholder # key format format_func = self._placeholder_formatters[format_key] if subkey is '': # positional argument if posn_arg_index &gt;= posn_arg_count: raise IndexError( f&quot;Positional argument placeholder at index &quot; f&quot;{posn_arg_index} is larger than &quot; f&quot;the number of positional arguments provided &quot; f&quot;({posn_arg_count}).&quot; ) # replace positional argument value with formatted value args[posn_arg_index] = format_func( args[posn_arg_index] ) else: # keyword argument if subkey not in kwargs: raise KeyError( f&quot;'{subkey}' from placeholder '{key}' was not &quot; f&quot;found in provided keyword arguments.&quot; ) # apply the appropriate formatting to the keyword argument # value and replace the original key with one that includes # the format and marker formatted_kwarg_keys.add(subkey) kwargs[key] = format_func(kwargs[subkey]) # remove kwargs that were only used formatted placeholders for kwarg_key in formatted_kwarg_keys - unformatted_kwarg_keys: del kwargs[kwarg_key] return args, kwargs def format(self, *args, **kwargs): &quot;&quot;&quot; Returns a `psycopg2.sql.Composed` query by formatting the values of `args` and `kwargs` based on how their position or key matches with that of placeholders in the originally supplied `query_string`. Arguments that do not have a placeholder will be passed to the `psycopg.sql.SQL.format` method used to created the `Composed` query. See the class documentation for how to structure the query string and supply arguments to the `format` method properly. Args: args: positional arguments to format the query with kwargs: keyword arguments to format the query with &quot;&quot;&quot; new_args, new_kwargs = self._process_format_args(*args, **kwargs) return SQL(self._adjusted_query).format(*new_args, **new_kwargs) if __name__ == '__main__': import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE) </code></pre> <strong><code>test-template-query.py</code></strong> <pre><code># -*- coding: utf-8 -*- &quot;&quot;&quot; Unit tests for template_query &quot;&quot;&quot; from psycopg2.sql import Composed, SQL, Identifier, Literal, Placeholder from unittest import TestCase, main from template_query import TemplateQuery def composed(*args): &quot;&quot;&quot;Simpler wrapper over Composed&quot;&quot;&quot; return Composed(args) # assert that marker is as expected assert TemplateQuery._placeholder_marker == '@' class TemplateQueryTests(TestCase): def test_simple_kwarg_formatted(self): &quot;&quot;&quot;All formats as keyword argument&quot;&quot;&quot; foo_val = 'bar' subtests = [ ['{foo@S}', SQL], ['{foo@I}', Identifier], ['{foo@L}', Literal], ['{foo@P}', Placeholder] ] for p, f in subtests: with self.subTest(placeholder=p, formatter=f): tq = TemplateQuery(p) actual = tq.format(foo=foo_val) expected = composed(f(foo_val)) self.assertEqual(actual, expected) p = '{foo@Q}' with self.subTest('schema.table identifier'): tq = TemplateQuery(p) actual = tq.format(foo=&quot;schema.table&quot;) expected = composed( Identifier('schema') + SQL('.') + Identifier('table') ) self.assertEqual(actual, expected) def test_simple_posn_arg_formatted(self): &quot;&quot;&quot;All formats as positional argument&quot;&quot;&quot; foo_val = 'bar' subtests = [ ['{@S}', SQL], ['{@I}', Identifier], ['{@L}', Literal], ['{@P}', Placeholder] ] for p, f in subtests: with self.subTest(placeholder=p, formatter=f): tq = TemplateQuery(p) actual = tq.format(foo_val) expected = composed(f(foo_val)) self.assertEqual(actual, expected) p = '{@Q}' with self.subTest('schema.table identifier'): tq = TemplateQuery(p) actual = tq.format(&quot;schema.table&quot;) expected = composed( Identifier('schema') + SQL('.') + Identifier('table') ) self.assertEqual(actual, expected) def test_empty_query(self): &quot;&quot;&quot;Empty query string&quot;&quot;&quot; actual = TemplateQuery('').format() expected = composed() self.assertEqual(actual, expected) def test_edge_case_placeholders(self): &quot;&quot;&quot;Edge case placeholders that can fit on one query&quot;&quot;&quot; tq = TemplateQuery( &quot;{} {foo} {bar@I} {bar@S} {bar@Q} {kyt@@S} {@I} {@} {@@} &quot; &quot;{tek@} {nol@@}&quot; ) actual = tq.format( Literal('a'), 'c', **{ 'foo': Literal('b'), 'bar': 'schema.table', 'kyt@': 'apple.orange', '@': Identifier('banana'), '@@': SQL('mango'), 'tek@': SQL('tangerine'), 'nol@@': Literal('avacado') } ) expected = composed( Literal('a'), SQL(' '), Literal('b'), SQL(' '), Identifier('schema.table'), SQL(' '), SQL('schema.table'), SQL(' '), composed(Identifier('schema'), SQL('.'), Identifier('table')), SQL(' '), SQL('apple.orange'), SQL(' '), Identifier('c'), SQL(' '), Identifier('banana'), SQL(' '), SQL('mango'), SQL(' '), SQL('tangerine'), SQL(' '), Literal('avacado') ) self.assertEqual(actual, expected) def test_missing_posn_args(self): &quot;&quot;&quot;Not enough positional arguments&quot;&quot;&quot; with self.assertRaises(IndexError): TemplateQuery(&quot;{}{@L}{foo@L}&quot;).format( 'kyt', foo='bar' ) def test_missing_kwargs(self): &quot;&quot;&quot;Missing keyword argument&quot;&quot;&quot; with self.assertRaises(KeyError): TemplateQuery(&quot;{}{@L}{foo@L}&quot;).format( 'sar', 'kyt' ) if __name__ == '__main__': main() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T03:29:53.257", "Id": "238867", "Score": "2", "Tags": [ "python", "sql", "template" ], "Title": "Python class for helping template SQL queries when working with psycopg2" }
238867
<p>A while back I wrote a socket programmed chat in Python. This question isn't really about the program specifically, moreso on conventions of Python and my style of coding. I've only been using Python for a couple of months and any pointers would be appreciated.</p> <p>Here's some code I'm curious about:</p> <pre class="lang-py prettyprint-override"><code># in case of inappropriate arguments, remind user how to execute if len(sys.argv) != 3: print("\nExecute the script as below:") print(" $ ./sock_client.py &lt;IP Address&gt; &lt;Port&gt;") print("For example: `./sock_server.py 127.0.0.1 8008`.") print("Additionally, ensure the socket server is live beforehand.\n") sys.exit(1) </code></pre> <p>In all of my Python projects so far, which all are ran from a terminal, I have a block of code like this at the top to ensure number of arguments, and if not, remind the user on how to execute. I don't know if this is good convention or not.</p> <pre class="lang-py prettyprint-override"><code>def send_user(m, u): """ Sends a message to a single client. Parameter: m -- the message to send u -- the client to send to """ for c in CLIENT_LIST: # only specific client/user if CLIENT_LIST[c] == u: c.send(bytes(m, "utf8")) </code></pre> <p>Here's an example docstring. Were I to have a return statement, it would look more like this, though:</p> <pre class="lang-py prettyprint-override"><code>def function(param1, param2): """ What function does in a couple words. More detail if needed. Parameter: param1 -- some parameter param2 -- another parameter Return: -- some value </code></pre> <p>What is considered ideal convention for docstrings?</p> <p>Here's the full repo: <a href="https://github.com/stratzilla/socket-chat" rel="nofollow noreferrer">link</a>.</p>
[]
[ { "body": "<p>Instead of always manually parsing <code>sys.argv</code>, you can use the standard library tool <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a>. It automatically enforces the right usage and prints a nicely formatted usage if not. For your given example it would look like this:</p>\n\n<pre><code>import argparse\n\ndef ip_address(ip):\n # TODO: implement checking if IP is valid\n return ip\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser(description=\"Tool for server client connection.\",\n epilog=\"Ensure the socket server is live before using this tool.\")\n parser.add_argument(\"ip\", type=ip_address, help=\"The IP address of the server\")\n parser.add_argument(\"port\", type=int, help=\"The port where the server listens.\")\n return parser.parse_args(args)\n</code></pre>\n\n<p>I put it into a function so you can test it without having to run the whole code, by passing a list of strings to the function. It also allows setting the type of arguments, which can be any callable (so in the above example you need to have e.g a function called <code>ip_address</code> that can check if the argument is a valid IP address). The help messages generated by this example are like this:</p>\n\n<pre><code>$ python3 /tmp/sock_client.py 127.0.0.1\nusage: sock_client.py [-h] ip port\nsock_client.py: error: the following arguments are required: port\n\n$ python3 /tmp/sock_client.py -h \nusage: sock_client.py [-h] ip port\n\nTool for server client connection.\n\npositional arguments:\n ip The IP address of the server\n port The port where the server listens.\n\noptional arguments:\n -h, --help show this help message and exit\n\nEnsure the socket server is live before using this tool.\n</code></pre>\n\n<p>You can also add optional arguments, arguments with multiple parameters, mutually exclusive arguments/argument groups. Check out the documentation for more examples.</p>\n\n<hr>\n\n<p>Instead of iterating only over the keys of a dictionary, iterate over the keys and values at the same time if you need both of them. Also, don't use too short names. No matter how nice your docstring is, it is always better if your function signature already tells you everything you need to know.</p>\n\n<pre><code>def send_user(message, user):\n \"\"\"\n Sends a message to a single client.\n\n Parameter:\n message -- the message to send\n user -- the client to send to\n \"\"\"\n for client, user_name in CLIENT_LIST.items():\n # only specific client/user\n if user_name == user:\n client.send(bytes(message, \"utf8\"))\n</code></pre>\n\n<p>Also, don't lie in your docstrings. This function sends a message to every client with the right name (i.e. value in the dictionary)! You can just <code>break</code> after you have found the user to ensure there is only one, or adapt the docstring to the reality of the code. In either case, add tests to ensure that your code does what it should.</p>\n\n<p>Calling what appears to be a dictionary <code>CLIENT_LIST</code> is one of the reasons why you should not include the type in the variable. Here it is very misleading and probably wrong! Just call them <code>CLIENTS</code> or <code>ALL_CLIENTS</code> or even <code>USER_NAMES</code>.</p>\n\n<hr>\n\n<p>There are two widely used docstring conventions (that I know of, i.e. in scientific computing). The first is the <a href=\"http://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings\" rel=\"nofollow noreferrer\">Google style</a> and the other one the <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"nofollow noreferrer\"><code>numpy</code> style</a>. Your code seems to be closer to the latter, but as long as you are consistent and include all necessary information you should be fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T10:28:20.797", "Id": "238879", "ParentId": "238870", "Score": "3" } } ]
{ "AcceptedAnswerId": "238879", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T04:58:52.677", "Id": "238870", "Score": "2", "Tags": [ "python", "python-3.x", "socket" ], "Title": "Python Socket programming chat - getting a handle on PEP conventions" }
238870
<p>Please review for performance and C# style.</p> <p>I already solved this question in 1 way. <a href="https://codereview.stackexchange.com/questions/222077/leetcode-trapping-rain-water-c">LeetCode: trapping rain water C#</a></p> <p>I tried also the dynamic programming approch</p> <p><a href="https://leetcode.com/problems/trapping-rain-water/" rel="nofollow noreferrer">https://leetcode.com/problems/trapping-rain-water/</a></p> <p><a href="https://i.stack.imgur.com/h7kbd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h7kbd.png" alt="enter image description here"></a></p> <pre><code>using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/trapping-rain-water/ /// &lt;/summary&gt; [TestClass] public class TrappingRainWater { [TestMethod] public void TestMethod1() { int[] height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; Assert.AreEqual(6, TrapDynamicProgramming(height)); } public int TrapDynamicProgramming(int[] height) { if (height == null || height.Length == 0) { return 0; } int ans = 0; int size = height.Length; var leftMax = Enumerable.Repeat(0, size).ToList(); var rightMax = Enumerable.Repeat(0, size).ToList(); //compute the max height from the left for each cell //starting from the left leftMax[0] = height[0]; for (int i = 1; i &lt; size; i++) { leftMax[i] = Math.Max(height[i], leftMax[i - 1]); } //compute the max height from the right for each cell //starting from the right.. rightMax[size - 1] = height[size - 1]; for (int i = size - 2; i &gt;= 0; i--) { rightMax[i] = Math.Max(height[i], rightMax[i + 1]); } //the amount of water is the minimal between left and right height. // and we need to remove the height of the cell, think of this // like where the ground starts for (int i = 1; i &lt; size - 1; i++) { ans += Math.Min(leftMax[i], rightMax[i]) - height[i]; } return ans; } } </code></pre>
[]
[ { "body": "<p>There is no reason to use lists instead of arrays, <code>new int[size]</code> will give you an array full of <code>0</code>s without any overhead.</p>\n\n<p>You can get away with creating only one array (<code>leftMax</code>) and then while computing the values of <code>rightMax</code>, instead of saving them into an array, complete the full calculation of how much to add to <code>ans</code>. Like this:</p>\n\n<pre><code>public int TrapDynamicProgramming(int[] height)\n{\n if (height == null || height.Length == 0)\n {\n return 0;\n }\n\n int ans = 0;\n int size = height.Length;\n int[] leftMax = new int[size];\n\n leftMax[0] = height[0];\n for (int i = 1; i &lt; size; i++)\n {\n leftMax[i] = Math.Max(height[i], leftMax[i - 1]);\n }\n\n int rightMax = height[size - 1];\n for (int i = size - 2; i &gt;= 0; i--)\n {\n rightMax = Math.Max(height[i], rightMax);\n ans += Math.Min(leftMax[i], rightMax) - height[i];\n }\n\n return ans;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T07:24:45.227", "Id": "239042", "ParentId": "238871", "Score": "2" } } ]
{ "AcceptedAnswerId": "239042", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T07:12:40.047", "Id": "238871", "Score": "2", "Tags": [ "c#", "performance", "programming-challenge", "dynamic-programming" ], "Title": "LeetCode: Trapping Rain Water DP C#" }
238871
<p>(Also, see the <a href="https://codereview.stackexchange.com/questions/238936/remotefile-in-java-follow-up"><strong>next iteration</strong></a>.)</p> <p>I have this tiny class for downloading files from internet:</p> <pre><code>package com.github.coderodde.utils.io; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Objects; /** * This class implements a downloadable remote file. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 14, 2020) ~ initial Happy Pi Day -version. * @since 1.6 (Mar 14, 2020) */ public class RemoteFile { /** * The URL of the target remote file. */ private String url; /** * Constructs a new {@code RemoteFile} object with given URL as a string. * * @param url the URL of the target remote file. */ public RemoteFile(String url) { this.url = Objects.requireNonNull(url, "The URL is null."); } /** * Downloads the remote file to local disk. * * @param path the path of the target file on the local disk. * * @throws MalformedURLException if there are problems with URL. * * @throws IOException if I/O fails. */ public void download(String path) throws MalformedURLException, IOException { InputStream inputStream = new URL(url).openStream(); Files.copy(inputStream, Paths.get(path), StandardCopyOption.REPLACE_EXISTING); } } </code></pre> <p><strong>Critique request</strong></p> <p>I would like to hear any comments. In particular, I would like to know what other functionalities I could add to it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T19:52:12.797", "Id": "468505", "Score": "1", "body": "Maybe add a callback / blocking call for when it is downloaded?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T09:07:19.910", "Id": "468540", "Score": "0", "body": "@tieskedh I suspect `downoad` blocks until done downloading." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T09:25:35.030", "Id": "468543", "Score": "0", "body": "Depends on the use-case... If there is a possibility to do it with callbacks, then you can do it (maybe singlethreaded) while doing something else (advanced topic, but you could look into completeableFutures). At other moments, you need to wait for the result. Both have use cases, but you're the programmer " } ]
[ { "body": "<p>It would probably be good to directly in the <code>RemoteFile</code> constructor perform the conversion to <code>URL</code> to allow the code to fail fast.</p>\n<p>The code should also close the InputStream retrieved from <code>openStream()</code> once the copying is done, e.g. using a <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\"><code>try-with-resources</code> statement</a>.</p>\n<p>In general (unless required by your use case) it might be even better to directly use <code>URL</code> as type for the <code>url</code> parameter of the constructor and <code>Path</code> as type for the <code>download(...)</code> argument. This way your are handing off validation / parsing responsiblity to the caller.</p>\n<p>And it might be good to make sure the <code>path</code> argument of <code>download(...)</code> is non-<code>null</code> <em>before</em> opening the InputStream.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-27T22:21:57.817", "Id": "249932", "ParentId": "238872", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T07:29:47.547", "Id": "238872", "Score": "2", "Tags": [ "java", "file", "io", "network-file-transfer" ], "Title": "RemoteFile in Java" }
238872
<p>Im trying to write a College class equals method that compare the content of the arrays of the two objects of college class. So The method will compare the Student[] array in college object to other Student[] array in another college object and same for the teacher[] array. I have written an equals method for this, but it looks too long and not pretty. Is there a better way to write it?</p> <p><strong>College Class</strong></p> <pre><code>public class College { private Student[] student; private Teacher[] teacher; public College() { student = new Student[9]; teacher = new Teacher[9]; } public Student[] getStudent() { return student; } public void setStudent(Student[] student) { this.student = student; } public Teacher[] getTeacher() { return teacher; } public void setTeacher(Teacher[] teacher) { this.teacher = teacher; } public boolean equals(Object inObj) {// this equals method boolean isEqual = false; College inCollege = (College)inObj; if(student.length == inCollege.getStudent().length) { for(int i = 0; i &lt; student.length; i++) { if(student[i].equals(inCollege.student[i])) { isEqual = true; } } } if((teacher.length == inCollege.getTeacher().length) &amp;&amp; isEqual == true) { isEqual = false; for(int i = 0; i &lt; inCollege.getTeacher().length; i++ ) { if(teacher[i].equals(inCollege.teacher[i])) { System.out.println("im in"); isEqual = true; } } } return isEqual; } } </code></pre> <p><strong>Student Class</strong></p> <pre><code>public class Student { private String name; private int age; public Student() { name = "Samrah"; age = 19; } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean equals(Object inObj) { boolean isEqual = false; if(inObj instanceof Student) { Student inStudent = (Student)inObj; if(this.name.equals(inStudent.getName())) if(this.age == inStudent.getAge()) isEqual = true; } return isEqual; } public String toString() { String str; return str = "name: "+name+" age: "+age; } } </code></pre> <p><strong>Teacher Class</strong></p> <pre><code>public class Teacher { private String name; private int age; public Teacher() { name = "Sanjay"; age = 45; } public Teacher(String name, int age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean equals(Object inObj) { boolean isEqual = false; if(inObj instanceof Teacher) { Teacher inTeacher = (Teacher)inObj; if(this.name.equals(inTeacher.getName())) if(this.age == inTeacher.getAge()) isEqual = true; } return isEqual; } public String toString() { String str; return str = "name: "+name+" age: "+age; } } </code></pre> <p>Trying to do something like this:</p> <pre><code> boolean isEqual = false; if(inObject instanceof EngineClass) { EngineClass inEngine = (EngineClass)inObject; if(cylinders == inEngine.getCylinders()) if(fuel.equals(inEngine.getFuel())) isEqual = true; } return isEqual; </code></pre> <p>but with since its an array I have to loop through the arrays so I'm really confused.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T09:27:10.190", "Id": "468459", "Score": "1", "body": "Please post code as it is in your IDE, so that it compiles. If you want to annotate the code, do it first in your IDE to make sure it still compiles. Adding annotations that stop the code compiling (for example this: `**public boolean equals(Object inObj)`) make it harder to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T09:33:58.973", "Id": "468461", "Score": "1", "body": "If one college had students ['fred', 'foo'] and a second college had students ['foo','fred'] you wouldn't consider them equal (unless you have some sorting implemented that you've not shown us). Is this by design? Do you have to use arrays, or can you use other data structures like `Set`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T09:43:41.413", "Id": "468463", "Score": "0", "body": "@forsvarir I only have to use arrays and yes it is by design." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T10:52:25.197", "Id": "468470", "Score": "2", "body": "If two colleges contain the students `['Fred', ..., 'George']` and `['Foo', ..., 'George']`, your method would return true, since the variable is always overridden, so only the last students are really compared. And then it gets overwritten again by the last teachers, so really it only compares the last teachers. Instead return false as soon as a mismatch is detected. This makes the code broken and off-topic for this site, I'm afraid." } ]
[ { "body": "<ol>\n<li>It depends on what is exactly possible in your class - can you override class, can some fields be null at any point? For example retrofit creates classes using reflection and some classes can be very unexpectedly null unless set in constructor without parameters.</li>\n<li>Many IDEs have generators, they do this really well.</li>\n<li>If you override <code>equals</code>, you really should override <code>hashCode</code> too:\n<a href=\"https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java\">https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java</a></li>\n</ol>\n\n<p>I included equals generated by Android Studio - 2 possibilities, depending on if you are okay with subclasses too (hashcodes both same).</p>\n\n<pre><code> @Override\n public boolean equalsV1(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n College college = (College) o;\n return Arrays.equals(student, college.student) &amp;&amp;\n Arrays.equals(teacher, college.teacher);\n }\n\n @Override\n public boolean equalsV2(Object o) {\n if (this == o) return true;\n if (!(o instanceof College)) return false;\n College college = (College) o;\n return Arrays.equals(student, college.student) &amp;&amp;\n Arrays.equals(teacher, college.teacher);\n }\n\n @Override\n public int hashCode() {\n int result = Arrays.hashCode(student);\n result = 31 * result + Arrays.hashCode(teacher);\n return result;\n }\n</code></pre>\n\n<ul>\n<li>You can notice, that there are static methods for arrays in <code>Array</code> class.</li>\n<li>Code is trying to exit as soon as it is sure, that equality isn't there rather than your approach, where code runs till the end and maybe it will set equals to <code>true</code> along the way, which has to run longer.</li>\n<li>You don't need to use getters, you can use fields directly since it's accessing fields of different instance, but same class.</li>\n<li>In <code>College</code> class it's fine, but in <code>Student</code> your class would crash if name is <code>null</code>. It shouldn't happen as even if your empty constructor you set it to something. But sadly in java I can still create <code>Student</code> class and pass <code>null</code> myself (would be good to do null check there). So just to be safe, equals should be able to handle that. There's method for that to make it easier - <code>Objects.equals(name, other.name)</code> rather than <code>name.equals(other.name)</code>. First one will work fine and return false when <code>name</code> is null. Second one will raise <code>NullPointerException</code>. </li>\n<li><code>equals</code> shouldn't ever throw <code>Exception</code>. If you aren't sure to guarantee that, it might be better to just surround code in try-catch and return <code>false</code> on exception.</li>\n<li>Unless it's exercise, try to rely on these generators. They are pretty good and worked well for me. </li>\n<li>Now I switched to <code>kotlin</code>, that has data classes, which automatically have <code>equals</code> and <code>hashCode</code> based on all class properties already saves work and lines of code!</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T08:24:50.547", "Id": "468452", "Score": "0", "body": "I am trying to do something of this sort: boolean isEqual = false;\n \n if(inObject instanceof EngineClass)\n {\n EngineClass inEngine = (EngineClass)inObject;\n if(cylinders == inEngine.getCylinders())\n if(fuel.equals(inEngine.getFuel()))\n isEqual = true;\n }\n return isEqual;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T08:26:42.400", "Id": "468453", "Score": "0", "body": "The versions that you have given are all good but are very high level for me as I still do not know anything about hashCodes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T08:27:29.723", "Id": "468454", "Score": "0", "body": "Ye I added comments on generated code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T08:10:50.247", "Id": "238874", "ParentId": "238873", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T07:51:21.080", "Id": "238873", "Score": "1", "Tags": [ "java", "object-oriented" ], "Title": "Trying to write an equals method for a class containing array of objects" }
238873
<p>I'm looking for any advice on the way I have implemented methods (explained below). More specifically, is it a good practice or not? And if not, any suggestions?</p> <hr> <blockquote> <p><strong>NOTE</strong> - <code>communications.js</code> is used in many places throughout the app.</p> </blockquote> <hr> <p><strong>Search_user.js</strong></p> <blockquote> <p>This code searches for cookies and returns a user object if any matches found.</p> </blockquote> <hr> <pre><code>function searchForAUser () { let userName = "userName="; let userId = "userId="; let user = {}; let decodedCookie = decodeURIComponent(document.cookie); let cookieArr = decodedCookie.split(';'); for(var i=0; i&lt; cookieArr.length; i++) { var c = cookieArr[i]; while (c.charAt(0) === " ") { c= c.substring(1); } if (c.indexOf(userName) === 0) { let userNameDecoded = c.substring(userName.length, c.length); user.userName = userNameDecoded; console.log(userNameDecoded); } if (c.indexOf(userId) === 0 ) { var userIdDecoded = c.substring(userId.length, c.length); user.userId = userIdDecoded; console.log(user.userId); } return user; </code></pre> <p><strong>main.js</strong></p> <pre><code>//used for xmlHttpRequests let comms = require("./communications.js"); //searches a user let serachUser = require("./search_user.js"); var main = { user : {}, init : async function () { this.user = await searchForAUser(); console.log(this.user); }, } //verifies the user.t against a database async function searchForAUser () { let user = serachUser(); let verify = await comms.sendUserData(user,"../../backend/Log_in.php"); if (user.t === verify) { user.loggedInStatus = true; } else { user.loggedInStatus = false; } return user; } </code></pre> <p>My question is, whether above <code>searchForAUser</code> function is unnecessary? And, is it good practice to use below one instead of above function?</p> <hr> <blockquote> <p><strong>Passing <code>comms</code> to Search_User.js</strong></p> </blockquote> <hr> <p><strong>Search_User.js</strong></p> <pre><code>function searchForAUser (comms) { let userName = "userName="; let userId = "userId="; let user = {}; let decodedCookie = decodeURIComponent(document.cookie); let cookieArr = decodedCookie.split(';'); for(var i=0; i&lt; cookieArr.length; i++) { var c = cookieArr[i]; while (c.charAt(0) === " ") { c= c.substring(1); } if (c.indexOf(userName) === 0) { let userNameDecoded = c.substring(userName.length, c.length); user.userName = userNameDecoded; console.log(userNameDecoded); } if (c.indexOf(userId) === 0 ) { var userIdDecoded = c.substring(userId.length, c.length); user.userId = userIdDecoded; console.log(user.userId); } //communication is also done in the same function let verify = comms.sendUserData(user,"../../backend/Log_in.php"); if (user.t === verify) { user.loggedInStatus = true; } return user; </code></pre> <p><strong>main.js</strong></p> <pre><code>let comms = require("./communications.js"); let serachUser = require("./search_user.js"); var main = { user : {}, init : async function () { //passing comms to the searchuser function this.user = searchUser(comms); console.log(this.user); }, } </code></pre> <p>Passing the comms method to the <code>searchUser</code> function and executing it inside the <code>searchUser</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T04:34:18.487", "Id": "468533", "Score": "1", "body": "Welcome to Code Review. This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](https://codereview.meta.stackexchange.com/a/1231)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:21:14.897", "Id": "468580", "Score": "0", "body": "@L.F. thank you for advice. I have edited and added more details. Basically I need to know is, whether passing the ````comms```` to ````searchUser```` is a good practice? I have to use more functions of this pattern throughout the app." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:57:05.593", "Id": "468672", "Score": "0", "body": "Are all those `console.log` statements part of your actual code? Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:17:05.967", "Id": "468697", "Score": "0", "body": "@Mast No, ````console.log```` are only for testing purpose." } ]
[ { "body": "<p>In the matter of simplify <code>Search_User.js</code> instead:</p>\n\n<pre><code>var c = cookieArr[i];\nwhile (c.charAt(0) === \" \") {\n c= c.substring(1);\n}\n</code></pre>\n\n<p>you can use <code>trim()</code></p>\n\n<pre><code>var c = cookieArr[i].trim();\n</code></pre>\n\n<p>and in <code>IF's</code> use <code>slice</code> or <code>substring</code> with <code>start</code> argument only </p>\n\n<pre><code>if (c.indexOf(userName) === 0) { user.userName = c.slice(userName.length) }\nif (c.indexOf(userId) === 0) { user.userId = c.substring(userId.length) }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T13:43:47.647", "Id": "238942", "ParentId": "238882", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T12:43:11.150", "Id": "238882", "Score": "-3", "Tags": [ "javascript", "node.js" ], "Title": "Searching for a user" }
238882
<p>Recently started writing more rust code and interested in how anyone may get around using <code>.clone()</code> within a map of a referenced data structure. I've included a test so you can see exactly what the desired outcome is. That is, if any of the <code>block</code>s are <code>statement-permissions</code> then filter any options that are not <code>consent</code>. </p> <pre><code>use crate::{Block, BlockData, PermissionOption, Rule, Template}; /// # Filter options by justifications /// /// Filters a set of options within a permissions block /// based on it's justifications. pub fn filter_justifications(template: &amp;mut Template, justifications: Vec&lt;String&gt;) { template.blocks = template.blocks .iter() .map(|block: &amp;Block| -&gt; Block { let Block { r#type, data } = block.clone(); Block { r#type, data: match data { BlockData::StatementPermissions { id, options } =&gt; { BlockData::StatementPermissions { id, options: options .into_iter() .filter(|option| { justifications.contains(&amp;option.justification) }) .collect(), } } _ =&gt; data, }, } }) .collect(); } #[cfg(test)] mod test { use super::*; #[test] fn filter_blocks_for_consents() { let mut template = Template { id: "01".to_string(), name: "template 01".to_string(), blocks: vec![ Block { r#type: "preference".to_string(), data: BlockData::Preferences { preference: "some data".to_string(), }, }, Block { r#type: String::from("statement-permissions"), data: BlockData::StatementPermissions { id: "statement-01".to_string(), options: vec![ PermissionOption { option_id: "option-01".to_string(), state: Some("GRANTED".to_string()), justification: "consent".to_string(), }, PermissionOption { option_id: "option-02".to_string(), state: None, justification: "contract".to_string(), }, PermissionOption { option_id: "option-03".to_string(), state: Some("DENIED".to_string()), justification: "consent".to_string(), }, ], }, }, ], }; let expected = Template { id: "01".to_string(), name: "template 01".to_string(), blocks: vec![ Block { r#type: "preference".to_string(), data: BlockData::Preferences { preference: "some data".to_string(), }, }, Block { r#type: String::from("statement-permissions"), data: BlockData::StatementPermissions { id: "statement-01".to_string(), options: vec![ PermissionOption { option_id: "option-01".to_string(), state: Some("GRANTED".to_string()), justification: "consent".to_string(), }, PermissionOption { option_id: "option-03".to_string(), state: Some("DENIED".to_string()), justification: "consent".to_string(), }, ], }, }, ], }; let rule = Rule { name: "block-types".to_string(), parameters: vec![ "consent".to_string() ], }; filter_justifications(&amp;mut template, rule.parameters); assert_eq!(template, expected); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T09:02:35.907", "Id": "468676", "Score": "1", "body": "I can't test this, so please clarify: does or doesn't the current code produce the correct output?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T14:34:03.997", "Id": "238884", "Score": "1", "Tags": [ "rust" ], "Title": "Filtering two dimensional vector in Rust" }
238884
<h1>Assignment description</h1> <p>This is the improved code for a <a href="https://codereview.stackexchange.com/questions/238849/feedback-on-traffic-light-which-revolves-around-serial-communication">question</a> I've posted earlier. I'd like to receive feedback on an assignment which I'm currently working on. I have to make two traffic lights which allow traffic to run smoothly. I'm using a master Arduino which handles the main serial communication and one slave Arduino which handles the light sequence. Both lights turn red if the master Arduino is disconnected. <em>I must use the SoftwareSerial library.</em> The situation is shown below: <img src="https://i.stack.imgur.com/CWnbL.png" alt="Traffic flow"> </p> <h1>Wiring</h1> <p><img src="https://i.stack.imgur.com/92fe3.png" alt="Wiring"></p> <h2><strong>Common protocol header file</strong></h2> <pre><code>#define SYNCHRONIZE "SYN" #define SYNACK "SYN-ACK" #define ACKNOWLEDGED "ACK" #define BAUDRATE 9600 #define TIMEOUT 10 </code></pre> <h2>Master header file</h2> <pre><code>#define MASTERPINS 2, 3 #define MASTEREVENT 50 </code></pre> <h2>Code master Arduino</h2> <pre><code>#include &lt;Arduino.h&gt; #include &lt;SoftwareSerial.h&gt; #include "Protocol.h" #include "Master.h" SoftwareSerial serial(MASTERPINS); // RX, TX void setup() { Serial.begin(BAUDRATE); // Native USB connection Serial.setTimeout(TIMEOUT); while (!Serial) { ; // Wait for serial port to connect } serial.begin(BAUDRATE); // SoftwareSerial connection serial.setTimeout(TIMEOUT); // Maximum wait time } void loop() { static String readString; // String containing serial data static bool sendACK = false; // Boolean regulating handshaking /* Set string to incoming data. Once request to 'three-way handshake' has been acknowledged, set boolean sendACK to true, allowing "ACK" to be sent. */ if (serial.available() &gt; 0) { while (serial.available() &gt; 0) { readString = serial.readString(); Serial.print(readString); } if (readString == SYNACK) { sendACK = true; } } unsigned long currentTime = millis(); // Set current time static unsigned long previousTime = 0; // Set previous time /* Send "SYN" to initiate 'three-way handshake'. Once connection established, send "ACK" */ if ((currentTime - previousTime) &gt; MASTEREVENT) { if (sendACK == false) { serial.print(SYNCHRONIZE); Serial.print(SYNCHRONIZE); } else if (sendACK == true) { serial.print(ACKNOWLEDGED); Serial.print(ACKNOWLEDGED); sendACK = false; } previousTime = currentTime; } } </code></pre> <h2>Slave header file</h2> <pre><code>#define SLAVEPINS 8, 9 #define SLAVEEVENT 200 #define REDLED1 2 #define YELLOWLED1 3 #define GREENLED1 4 #define REDLED2 5 #define YELLOWLED2 6 #define GREENLED2 7 </code></pre> <h2>Code slave Arduino</h2> <pre><code>#include &lt;Arduino.h&gt; #include &lt;SoftwareSerial.h&gt; #include "Protocol.h" #include "Slave.h" SoftwareSerial serial(SLAVEPINS); // RX, TX void setup() { // Multiple LED outputs pinMode(REDLED1, OUTPUT); pinMode(YELLOWLED1, OUTPUT); pinMode(GREENLED1, OUTPUT); pinMode(REDLED2, OUTPUT); pinMode(YELLOWLED2, OUTPUT); pinMode(GREENLED2, OUTPUT); serial.begin(BAUDRATE); // SoftwareSerial connection (baudrate 9600) serial.setTimeout(TIMEOUT); // Maximum wait time } void loop() { static String readString; // String containing serial data static long counter = 0; // Counter static bool setLight = false; // Turn lights on once unsigned long currentTime = millis(); // Set current time static unsigned long previousTime = 0; // Set previous time /* Set string to incoming data. Establish 'three-way handshake' and count the amount of times handshaking performed. Set lights according to the handshakes counted. */ if (serial.available() &gt; 0) { while (serial.available() &gt; 0) { readString = serial.readString(); } if (readString == SYNCHRONIZE) { serial.print(SYNACK); } else if (readString == ACKNOWLEDGED) { switch (counter) { case 0: digitalWrite(REDLED1, HIGH); digitalWrite(REDLED2, HIGH); break; case 10: digitalWrite(GREENLED1, HIGH); digitalWrite(REDLED1, LOW); break; case 40: digitalWrite(YELLOWLED1, HIGH); digitalWrite(GREENLED1, LOW); break; case 50: digitalWrite(REDLED1, HIGH); digitalWrite(YELLOWLED1, LOW); break; case 60: digitalWrite(GREENLED2, HIGH); digitalWrite(REDLED2, LOW); break; case 90: digitalWrite(YELLOWLED2, HIGH); digitalWrite(GREENLED2, LOW); break; case 100: digitalWrite(REDLED2, HIGH); digitalWrite(YELLOWLED2, LOW); break; } counter++; if (counter &gt; 100) { counter = 0; } } setLight = false; previousTime = currentTime; } // If handshake did not work, wait for 200 milliseconds and set traffic lights to red. else if ((currentTime - previousTime) &gt; SLAVEEVENT &amp;&amp; !setLight) { digitalWrite(REDLED1, HIGH); digitalWrite(REDLED2, HIGH); digitalWrite(YELLOWLED1, LOW); digitalWrite(YELLOWLED2, LOW); digitalWrite(GREENLED1, LOW); digitalWrite(GREENLED2, LOW); counter = 0; setLight = true; } } </code></pre> <p><strong>Please give me feedback on my code and which parts I could do better and/or more efficiently. Thanks!</strong></p>
[]
[ { "body": "<p><strong>Separate pin definitions</strong></p>\n\n<p>Clearer and easier to maintain.</p>\n\n<pre><code>//#define SLAVEPINS 8, 9\n//SoftwareSerial serial(SLAVEPINS); // RX, TX\n\n#define SLAVEPINS_RX 8\n#define SLAVEPINS_TX 9\nSoftwareSerial serial(SLAVEPINS_RX, SLAVEPINS_TX);\n</code></pre>\n\n<p><strong>Code guards</strong></p>\n\n<pre><code>#ifndef _SLAVE_H\n#define _SLAVE_H 1\n\n#define SLAVEPINS 8, 9\n#define SLAVEEVENT 200\n....\n\n#endif\n</code></pre>\n\n<p>Also see <code>#pragma once</code></p>\n\n<p><strong>Suggest prefix for name space control</strong></p>\n\n<p>Consider file name</p>\n\n<pre><code>//#define SLAVEEVENT 200\n//#define REDLED1 2\n//#define REDLED2 5\n#define SLAVE_EVENT 200\n#define SLAVE_REDLED1 2\n#define SLAVE_REDLED2 5\n</code></pre>\n\n<p><strong>Use standard header files</strong></p>\n\n<p>Code uses <code>bool</code> in <code>static bool sendACK</code> yet lacks needed include. Do no rely on other includes to provide that definition.</p>\n\n<pre><code>#include &lt;stdbool.h&gt;\n</code></pre>\n\n<p><strong>Use units</strong></p>\n\n<p>50 what? micro, milli, seconds?</p>\n\n<pre><code>// #define MASTEREVENT 50\n#define MASTEREVENT 50 /* ms */\n</code></pre>\n\n<p><strong>Hardware idea</strong></p>\n\n<p>Rather than both legs of LED hot, place one on ground and the resistor on the hot side. Safer and more common for serviceable parts (lights) to have one side ground.</p>\n\n<p>///</p>\n\n<p>Perhaps more later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:16:11.397", "Id": "468591", "Score": "0", "body": "`#pragma once` isn't portable C, although it's present in Arduino and widely implemented in other compilers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T18:21:56.637", "Id": "238894", "ParentId": "238888", "Score": "3" } } ]
{ "AcceptedAnswerId": "238894", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T16:22:06.247", "Id": "238888", "Score": "1", "Tags": [ "c", "serialization", "arduino" ], "Title": "Traffic Light which revolves around Serial Communication" }
238888
<p>This is an improvement on the code presented <a href="https://codereview.stackexchange.com/questions/238801/simple-simulation-of-animals-eating-other-animals">here</a></p> <p>I was given the exercise of refactoring some code that was breaking the Open-Closed Principle in a SOLID design, ensuring that the new code would follow all the SOLID design principles. It refers to an Animal Park, where there are a couple of different species of animals, and it defines the rules in which these animals can eat other animals. The Animal Park class processes a polymorphic array of the represented animals, in which the animal <em>i</em> tries to eat the <em>i+1</em> animal. What are your thoughts about the code below? </p> <pre><code>public abstract class Animal { public AnimalKind Kind { get; set; } public Size Size { get; set; } public bool IsDead { get; set; } protected Animal(Size size) { this.Size = size; } } public enum AnimalKind { Error = 0, Hyena = 1, Lion = 2 } public class Lion : Animal { public Lion(Size size) : base(size) { Kind = AnimalKind.Lion; } // Some more logic, which the exercise had, but I omitted because it was not necessary for this question } public class Hyena : Animal { public Hyena(Size size) : base(size) { Kind = AnimalKind.Hyena; } // Some more logic, which the exercise had, but I omitted because it was not necessary for this question } public enum Size { Error = 0, Small = 1, Medium = 2, Big = 3 } public static class EatingPreferencesFactory { public static IDictionary&lt;AnimalKind, Size&gt; GetEatingPreferences(Animal animal) { Size biggestPreySizeExclusive; IDictionary&lt;AnimalKind, Size&gt; animalPreys = new Dictionary&lt;AnimalKind, Size&gt;(); switch(animal.Kind) { case AnimalKind.Lion: animalPreys.Add(AnimalKind.Hyena, animal.Size); biggestPreySizeExclusive = animal.Size; if(biggestPreySizeExclusive &gt; Size.Small &amp;&amp; biggestPreySizeExclusive &lt; animal.Size) { animalPreys.Add(AnimalKind.Lion, biggestPreySizeExclusive); } break; case AnimalKind.Hyena: biggestPreySizeExclusive = animal.Size; if (biggestPreySizeExclusive &gt; Size.Small &amp;&amp; biggestPreySizeExclusive &lt; animal.Size) { animalPreys.Add(AnimalKind.Hyena, animal.Size); } break; default: break; } return animalPreys; } } public interface IEatingPreferencesService { public bool CanEat(Animal eater, Animal animal); } public class EatingPreferencesService : IEatingPreferencesService { public bool CanEat(Animal eater, Animal prey) { if (eater.IsDead || prey.IsDead) return false; var eatingPreferences = EatingPreferencesFactory.GetEatingPreferences(eater); if (eatingPreferences.TryGetValue(prey.Kind, out Size ediblePreySize)) { if(ediblePreySize&gt;=prey.Size) { return true; } } return false; } } public class AnimalPark { private readonly IEatingPreferencesService _eatingPreferencesService; private readonly IList&lt;Animal&gt; _animals = new List&lt;Animal&gt;(); public AnimalPark(IEatingPreferencesService eatingPreferencesService) { _eatingPreferencesService = eatingPreferencesService; } public void AddAnimal(Animal animal) { if(animal != null) { _animals.Add(animal); } } public void Process() { int length = _animals.Count; for(int i=1; i&lt;length; i++) { if( _eatingPreferencesService.CanEat(_animals[i - 1], _animals[i]) ) { _animals[i].IsDead = true; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T18:01:22.650", "Id": "468496", "Score": "0", "body": "what is the basic rule for an animal to be eaten ? in your logic , it's the size, so there is a base rule which is `firstAnimal.Size > secondAnimal.Size` this means firstAnimal would eat the second one. or that what I understood in your logic. is there any other required logic for this part ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T18:31:06.660", "Id": "468497", "Score": "0", "body": "In this case, the rule doesn't differ much from that: An Hyena can eat a Lion if it is a bigger, however a Lion can eat a same sized Lion. Carnivore \"attacks\" happen when the secondAnimal is smaller. But this is just a simplification: if some more animals need to be added, that logic can change, and even more variables can come into play" } ]
[ { "body": "<p>I think you're overdoing it. I know that you want SOLID pattern, but enforcing it like this way add more code complicity. </p>\n\n<p>What happens on your code, is defining a <code>AnimalKind</code> and define multiple animals names (such as Lion, Hyena), which would be fine for a testable project, but it will make things much complicated in real or big projects. A simple example of this complicity would be adding more different animals from different species such as (Elephant, Parrot, Penguin, Spider ..etc). Now, think of how you would apply <code>CanEat</code> on these different kinds of animals. If you take <code>Size</code> as a factor, an Elephant would eat all animals including fish, and a Parrot would be eaten by a Penguin .. and so on.This would make a false logic. So, what you need is to use <code>AnimalKind</code> to define the specie type such as mammals, birds, reptiles, fishes, ..etc. Then, add <code>AnimalName</code>, which would holds the name of that animal such as Lion, Hyena ..etc. </p>\n\n<p>Another thing you need to consider is the food system for each animal. Is the animal Herbivore, Carnivore or Omnivore ? what type of food source does it eat Plant, meat of both ? \nif you define that for each animal, it'll make things much smoother to compare and work with. As you'll have several factors that can be used to specify your logic. </p>\n\n<p>Also, your <code>EatingPreferences</code> you're treating it as an attack, and not for eating purpose which makes it a misleading naming. </p>\n\n<p>Naming convesion needs to be enforced by adding a prefix naming on each class that releated to another class. So, <code>EatingPreferences</code> would be <code>AnimalEatingPreferences</code> and <code>Size</code> would be <code>AnimalSize</code> ..etc. </p>\n\n<p>Overall, I think you only need three classes that would serve your current context purpose, while having the ability to extend, add more logic to them. </p>\n\n<p>First the <code>Enum</code>s : </p>\n\n<pre><code>public enum AnimalType { Mammals, Birds, Reptiles, Amphibians, Fishes, Insects }\npublic enum AnimalName { Hyena, Lion }\npublic enum AnimalSize { Small, Medium, Big }\npublic enum AnimalDietType { Herbivore, Carnivore, Omnivore }\npublic enum AnimalFoodSource { Plant, Meat, Both }\n</code></pre>\n\n<p>these are just stored information, which we need an object to hold them (model), and a collection to gather them in one box (so it can be retrieved). Also, we will need a middle-ware class that defines the rules (surely each animal has some living rules), but the trick here, we want it to be extendable as we expect to have multiple unique rules for each animal and others might be shared. Finally, we need a container class that would be used to connect all of these objects. </p>\n\n<p>So, we need : </p>\n\n<ol>\n<li>Model Class (Animal)</li>\n<li>Collection Class (AnimalCollection)</li>\n<li>Living Rules Class (AnimalSurvivalRole)</li>\n<li>Container class (AnimalPark)</li>\n</ol>\n\n<p>To make things much easier to maintain, we will implement interfaces for some of the classes that I think it would be useful. an interface would implement a contract to the class and also would give you the ability to access its properties without using reflection (you'll see that in the below examples).</p>\n\n<p>So, first we will implement the interfaces : </p>\n\n<pre><code>public interface IAnimal\n{\n AnimalType Type { get; }\n AnimalName Name { get; }\n AnimalSize Size { get; }\n AnimalDietType DietType { get; }\n AnimalFoodSource FoodSource { get; }\n IAnimalSurvivalRole SurvivalRoles { get; }\n}\n\npublic interface IAnimalSurvivalRole\n{\n bool IsEdible { get; }\n bool IsKillable { get; }\n}\n\npublic interface IAnimalCollection\n{\n int Count { get; }\n void Clear();\n void Add(IAnimal animal);\n bool Remove(IAnimal animal);\n IEnumerable&lt;IAnimal&gt; GetAnimals();\n}\n</code></pre>\n\n<p>the interface is a key that you want to define your requirement. Now, from these interfaces, we can implement their classes : </p>\n\n<pre><code>public class Animal : IAnimal\n{\n public AnimalType Type { get; set; }\n\n public AnimalName Name { get; set; }\n\n public AnimalSize Size { get; set; }\n\n public AnimalDietType DietType { get; set; }\n\n public AnimalFoodSource FoodSource { get; set; }\n\n public IAnimalSurvivalRole SurvivalRoles { get; set; }\n\n public bool IsDead { get; set; }\n\n}\n</code></pre>\n\n<p><code>AnimalSurvivalRole</code> would contain the rules for each animal in order to survive either feeding or attacking or any other type that would be linked to animal survival (for instance, it's not only feeding or attacking each other, some other natural events would kill an animal like drowning, or fire ..etc). So, this class would cover all these things.</p>\n\n<pre><code>// use this class to define the animal survival roles such as eating and battling to live.\npublic sealed class AnimalSurvivalRole : IAnimalSurvivalRole\n{\n private readonly IAnimal _firstAnimal; \n\n private readonly IAnimal _secondAnimal;\n\n public bool IsEdible =&gt; CanEat(_firstAnimal, _secondAnimal);\n\n public bool IsKillable =&gt; CanKill(_firstAnimal, _secondAnimal);\n\n public AnimalSurvivalRole(IAnimal first, IAnimal second)\n {\n _firstAnimal = first;\n _secondAnimal = second;\n }\n\n private bool CanEat(IAnimal first, IAnimal second)\n {\n return first.DietType != AnimalDietType.Herbivore &amp;&amp; second.DietType == AnimalDietType.Herbivore;\n }\n\n private bool CanKill(IAnimal first, IAnimal second)\n {\n // by your logic, if the animals are the same or one of them is bigger than the other, it should kill the other one\n return first.Size &gt; second.Size || first.Type == second.Type;\n }\n}\n</code></pre>\n\n<p>For the time being, I used it as a comparable class to compare between two objects, it can be extended for other survival causes. </p>\n\n<p>The <code>AnimalPark</code> class is used as collection and also as main class at the same time. This violates SOLID principle. You will need to implement a collection class that meant to only store animals objects only, all the storing validations should be inside this collection. </p>\n\n<pre><code>public class AnimalCollection : IAnimalCollection, IEnumerable&lt;IAnimal&gt;\n{\n private readonly List&lt;IAnimal&gt; _animals = new List&lt;IAnimal&gt;();\n\n public AnimalCollection() { }\n\n public AnimalCollection(IEnumerable&lt;IAnimal&gt; animals) { _animals.AddRange(animals); }\n\n public IAnimal this[int index] \n {\n get =&gt; _animals[index];\n set =&gt; _animals[index] = value;\n }\n\n public int Count =&gt; _animals.Count;\n\n public void Clear() =&gt; _animals.Clear();\n\n public void Add(IAnimal animal)\n {\n if(animal == null) { throw new ArgumentNullException(nameof(animal)); }\n\n _animals.Add(animal);\n }\n\n public bool Remove(IAnimal animal)\n {\n if (animal == null) { throw new ArgumentNullException(nameof(animal)); }\n\n return _animals.Remove(animal);\n }\n\n public IEnumerable&lt;IAnimal&gt; GetAnimals() =&gt; _animals;\n\n /// &lt;summary&gt;Returns an enumerator that iterates through the collection.&lt;/summary&gt;\n /// &lt;returns&gt;An enumerator that can be used to iterate through the collection.&lt;/returns&gt;\n public IEnumerator&lt;IAnimal&gt; GetEnumerator() =&gt; _animals.GetEnumerator();\n\n IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator();\n\n}\n</code></pre>\n\n<p><code>IEnumerator</code> is a way to give your class an ability to use <code>foreach</code> loop.</p>\n\n<p>Now, use the <code>AnimalCollection</code> inside the <code>AnimalPark</code> as a storage, and make <code>AnimalPark</code> as main logic process (container) for all of them : </p>\n\n<pre><code>public class AnimalPark\n{\n private readonly AnimalCollection _animals = new AnimalCollection();\n\n public AnimalPark() { Initiate(); }\n\n private void Initiate()\n {\n // set here the animals in this park. \n\n // Sample : this park has one lion and Hyena\n\n var lion = new Animal\n {\n Type = AnimalType.Mammals,\n Name = AnimalName.Lion,\n Size = AnimalSize.Big,\n DietType = AnimalDietType.Carnivore,\n\n FoodSource = AnimalFoodSource.Meat\n };\n\n var hyena = new Animal\n {\n Type = AnimalType.Mammals,\n Name = AnimalName.Hyena,\n Size = AnimalSize.Big,\n DietType = AnimalDietType.Carnivore,\n FoodSource = AnimalFoodSource.Meat\n };\n\n // Now set the SurvivalRoles\n lion.SurvivalRoles = new AnimalSurvivalRole(lion, hyena);\n hyena.SurvivalRoles = new AnimalSurvivalRole(hyena, lion);\n\n // add them to the animal storage\n _animals.Add(lion);\n _animals.Add(hyena); \n }\n\n public IEnumerable&lt;IAnimal&gt; GetAnimals()\n {\n return _animals.GetAnimals();\n }\n\n}\n</code></pre>\n\n<p>The <code>AnimalSurvivalRole</code> can be defined differently, but since it's not clear for me what you intent to do exactly, I left it inside the model as a view so you can use it to define rule for each animal or type of animal, or you can create another class role that would handle other animal roles. </p>\n\n<p>Try to always categorize the code requriements, and choose a good naming convetion that would describe the object role clearely, even if is it going to be long, its better than having short description that ended you with (I'm just here, go figure!). For instance, You will notice that <code>IsDead</code> I've never used it, because i'm not sure what you meant by that exactly dead how ? if is it dead why still exists in the park at the first place ? these are some of the question that I thought about when I came across it. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T01:20:33.413", "Id": "469018", "Score": "0", "body": "Well picked about breaking the Single Responsibility Principle! \n\nThe context of this question is an interview I had, in which I struggled a lot. So I decided to reproduce the exercise, and when I had some questions, I decided to post my solution for review. That said, I omitted some parts of the exercise, like some behaviour associated with both the Lion and the Hyena. I really like your solution, but I don't think I could have avoided having a class representation of each animal because there was more behaviour linked with both animals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T01:24:59.050", "Id": "469021", "Score": "0", "body": "But I definitely agree that having the animal name as an Enum is a good practice! \n\nI also like more the way you coped with the survival/eating logic than in my solution. I also agree that it felt weird to leave dead animals in the AnimalPark, but that was taken directly from the given exercise. \n\nThanks for your enriching answer!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T03:29:54.727", "Id": "238917", "ParentId": "238890", "Score": "3" } }, { "body": "<p>that's me who did the review of your previous version.</p>\n\n<p>I'd still stick to what I proposed in the other answer. So here I will just add a few additions and clarifications. Then I will mostly try to focus on where you break SOLID and maybe other OOP principles in your current version. I will also include a few references to iSR5's answer.</p>\n\n<p>I realized the <code>IEater</code> interface is never used alone, so the <code>Eat</code> method could belong to IAnimal directly.</p>\n\n<p>Also maybe the IDictionary would better be hidden within an implementation of a new interface</p>\n\n<pre><code>interface IEatingPreferences\n{\n public bool CanEat(IDinner eater, IDinner dinner);\n}\n</code></pre>\n\n<p>Now you see we have basically a comparator interface for two dinners, which maybe tells us that instead of <code>IAnimal</code> extending <code>IDinner</code>, it could just have a property of <code>IDinner</code> type and the <code>IDinner</code> interface itself would deserve a better name like <code>IAnimalAppearance</code> (assuming animals will decide their prey on its apprearance is a good desription of how its supposed to be working here).</p>\n\n<p>Notice that IEatingPreferences plays the role of a strategy of the strategy pattern (in my implementation where it is held by the animal objects).</p>\n\n<p>As I already mentioned (in previous post comments) and opposed to your and iSR5's solutions, it allows for animals to behave in individual manner (not every small lion has to behave like every other small lion). And I believe for this reason both your and iSR5's solution break encapsulation principle in this respect. You expose data classes to cover the behaviour from outside. You should encapsulate the data with the behaviour together. Now if you do that you are free to extend the animls for example that they can have mood which would actually influence their eating preferences at certain mood.</p>\n\n<p>Further the abstract factory was there just to simplify the common cases, while nothing is preventing you from extending the factory (as oposed to modifying it) to create those individually behaved animals that dont behave like others of their kind. Or you could implement a builder for the animals. Whatever will ease the creating of the animals...</p>\n\n<h2>Errors in Enums</h2>\n\n<p>I am not sure why you added <code>AnimalKind.Error</code> and <code>Size.Error</code>. Nor I see them being referenced from anywhere nor I see reason for them to part of the respective enums.</p>\n\n<p>I would actually recommend to go the other way. Instead promote the enums to classes with comparision operators etc. (again this would strenghten the encapsulation)</p>\n\n<h2>Dependency Inversion Principle (The \"D\" in SOLID)</h2>\n\n<p><code>EatingPreferencesService</code> violates this principle because it calls static method <code>EatingPreferencesFactory.GetEatingPreferences</code>. The factory should be injected to the service from outside.</p>\n\n<h2>Single Responsibility Principle (The \"S\" in SOLID)</h2>\n\n<p>The <code>AnimalPark</code> class now break this principle because it manipulates list of animals and also allows to build it in the first place. We already have interface we can use (and that's something I would also argue against in iSR5's solution, why reinventing what already exists?): <code>ICollection&lt;IAnimal&gt;</code>.</p>\n\n<h2>Interface Segregation Principle (The \"I\" in SOLID)</h2>\n\n<p>On few places you depend on <code>Animal</code> but never use <code>IsDead</code> or <code>Eat</code>. This breaks the above principle. Like why is EatingPreferencesFactory allowed to kill the animals?</p>\n\n<p>For this reason, in my solution, I have separated <code>IDinner</code>/<code>IAnimalAppearance</code> from <code>IAnimal</code>. In my solution there are places that need just the appearance and there are places which need the entire animal. As I mentioned above, doing this through composition leaves us with a more flexible base (we are now free to extend base animal to privde those individuum overrides, while allowed same crazyness for all kinds of animals)</p>\n\n<p>Ie.</p>\n\n<pre><code>class CrazyAnimal : Animal\n{\n // ...\n}\n\n// yet still we can have\nnew CrazyAnimal(AnimalKind.Lion)\nnew CrazyAnimal(AnimalKind.Hyena)\n\n// without implementing CrazyLion and CrazyHyena. And eventually CrazyElephant when elepthants become a thing.\n\n// although maybe we have even an extra level of freedom to do this:\nnew Animal(AnimalKind.Lion, new CrazyEatingPreferences(/*...*/));\n// if eating preferences are the crazy thing about that animal indiviuum.\n</code></pre>\n\n<p>In relation to this, it buffles me why you still have Lion and Hyena classes extending Animal if there is nothing abstract about the Animal except (and idk why) the constructor. Smells like SRP or Liskov Substition principle violation...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T02:43:36.523", "Id": "469023", "Score": "0", "body": "\"Your (...) solution break encapsulation principle in this respect. You expose data classes to cover the behaviour from outside. You should encapsulate the data with the behaviour together\" - Very good point, thanks! \n\nRegarding the Enum values, I wanted just to avoid having the value 0 given to an animal, and have 0 to be explicitly represented as an invalid Enum. \n\nGood point about breaking the dependency Inversion Principle (The \"D\" in SOLID). I did know the correct way was to inject the EatingPreferencesFactory, but I wasn't aware I was breaking the Dependency Inversion Principle!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T03:27:04.467", "Id": "469025", "Score": "0", "body": "Regarding your comments on both mine and iSR5 solutions breaking the Single Responsibility Principle, I also agree with you. So, what you suggest is just to pass the animals being processed as a parameter to the Process() method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T13:56:33.797", "Id": "469088", "Score": "0", "body": "Still regarding having broken encapsulation, and summing up your two answers, it seems to me that: \n\na) The Open Closed Principle is broken if the eating preferences logic is kept at the Animal level, thus meaning that there will be changes to these individual classes whenever new animals will be added,\nb) Encapsulation is broken if this logic is passed to some kind of an Animal Factory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T13:57:04.653", "Id": "469089", "Score": "0", "body": "(...) The only solution that comes to my mind is to get rid of the service in my solution, and while still keeping the eating preferences logic at an Eating Preferences Factory, I would store the returned Objects in the Animals. Which kinda aligns to your solution in the other answer. What do you think?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T20:14:28.537", "Id": "469136", "Score": "0", "body": "Regarding what you said about having Animal as an abstract class, and Hyena and Lion inheriting from it, since the two Animals share the CanEat method, shouldn't I leave it in the super class? And when some Animal needs to override it, they can. \n\nTaking all the answers in consideration, I came up with a new solution and I will post it as an answer. I don't want to create a third post. Would be great if you could find some time to review it as well!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:19:10.940", "Id": "238993", "ParentId": "238890", "Score": "3" } }, { "body": "<p>Taking the two answers in this post in consideration, as well as in the linked post, and the discussions, I came up with this solution. I believe it now finally respects all the SOLID principles! </p>\n\n<pre><code> public abstract class Animal : IEater\n {\n public AnimalKind Kind { get; set; }\n public AnimalSize Size { get; set; }\n public bool IsDead { get; set; }\n\n public IAnimalEatingPreferences EatingPreferences { get; set; }\n\n\n public Animal(AnimalSize size)\n {\n this.Size = size;\n }\n\n public virtual bool CanEat(Animal prey)\n {\n if (this.IsDead || prey.IsDead) return false;\n\n if (EatingPreferences.TryGetPreys(prey.Kind, out AnimalSize ediblePreySize))\n {\n if (ediblePreySize &gt;= prey.Size)\n {\n return true;\n }\n }\n\n return false;\n }\n }\n\n public class Hyena : Animal\n {\n public Hyena(AnimalSize size) : base(size)\n {\n Kind = AnimalKind.Hyena;\n }\n\n // Some more logic, which the exercise had, but I omitted because it was not necessary for this question\n }\n\n public class Lion : Animal\n {\n public Lion(AnimalSize size) : base(size)\n {\n Kind = AnimalKind.Lion;\n }\n\n // Some more logic, which the exercise had, but I omitted because it was not necessary for this question\n }\n\n public enum AnimalKind\n {\n None = 0,\n Hyena = 1,\n Lion = 2\n }\n\n public enum AnimalSize\n {\n None = 0,\n Small = 1,\n Medium = 2,\n Big = 3\n }\n\n public interface IEater\n {\n bool CanEat(Animal prey);\n }\n\n public interface IEatingPreferencesFactory\n {\n IAnimalEatingPreferences GetEatingPreferences(AnimalKind animal, AnimalSize size);\n }\n\npublic interface IAnimalPark\n {\n void AddAnimal(Animal animal);\n void Process();\n }\n\n public interface IAnimalEatingPreferences\n {\n void AddPrey(AnimalKind animal, AnimalSize size);\n bool TryGetPreys(AnimalKind prey, out AnimalSize returnEdiblePreySize);\n }\n\n public class EatingPreferencesFactory : IEatingPreferencesFactory\n {\n public IAnimalEatingPreferences GetEatingPreferences(AnimalKind animal, AnimalSize size)\n {\n AnimalEatingPreferences eatingPreferences = new AnimalEatingPreferences();\n AnimalSize biggestPreySizeExclusive;\n\n switch(animal)\n {\n case AnimalKind.Lion:\n eatingPreferences.AddPrey(AnimalKind.Hyena, size);\n\n biggestPreySizeExclusive = size;\n if(biggestPreySizeExclusive &gt; AnimalSize.Small &amp;&amp; biggestPreySizeExclusive &lt; size)\n {\n eatingPreferences.AddPrey(AnimalKind.Lion, biggestPreySizeExclusive);\n }\n break;\n\n case AnimalKind.Hyena:\n biggestPreySizeExclusive = size;\n if (biggestPreySizeExclusive &gt; AnimalSize.Small &amp;&amp; biggestPreySizeExclusive &lt; size)\n {\n eatingPreferences.AddPrey(AnimalKind.Hyena, size);\n }\n break;\n\n default: break;\n }\n\n return eatingPreferences;\n }\n }\n\npublic class AnimalEatingPreferences : IAnimalEatingPreferences\n {\n private readonly IDictionary&lt;AnimalKind, AnimalSize&gt; _animalPreys;\n\n public AnimalEatingPreferences()\n {\n _animalPreys = new Dictionary&lt;AnimalKind, AnimalSize&gt;();\n }\n\n public void AddPrey(AnimalKind animal, AnimalSize size)\n {\n _animalPreys.Add(animal, size);\n }\n\n public bool TryGetPreys(AnimalKind prey, out AnimalSize returnEdiblePreySize)\n {\n if( _animalPreys.TryGetValue(prey, out AnimalSize ediblePreySize) )\n {\n returnEdiblePreySize = ediblePreySize;\n return true;\n }\n\n returnEdiblePreySize = AnimalSize.None;\n return false;\n }\n }\n\npublic class AnimalPark : IAnimalPark\n {\n private readonly IList&lt;Animal&gt; _animals;\n\n public AnimalPark(IList&lt;Animal&gt; animals)\n {\n _animals = animals;\n }\n\n public void AddAnimal(Animal animal)\n {\n _animals.Add(animal);\n }\n\n public void Process()\n {\n int length = _animals.Count;\n for(int i=1; i&lt;length; i++)\n {\n if( _animals[i-1].CanEat(_animals[i]) )\n {\n _animals[i].IsDead = true;\n }\n }\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T20:19:09.540", "Id": "239158", "ParentId": "238890", "Score": "1" } } ]
{ "AcceptedAnswerId": "238993", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T16:26:20.770", "Id": "238890", "Score": "3", "Tags": [ "c#", "object-oriented" ], "Title": "Make it SOLID: simple simulation of animals eating other animals (improved)" }
238890
<p>I have written the below code which generates 4 random, whole integer values between 1 and 6 and then saves the sum of the 3 largest values. It generates a total of 6 values this way, displays the total along with all 6 values once finished.</p> <ul> <li>The order in which each value was generated must be preserved.</li> <li>The total of all 6 values must be at least 75 or above.</li> <li>At least 2 of the values must be 15 or more.</li> </ul> <pre><code>import java.util.Random; import java.util.Arrays; public class Test { static boolean goodRoll = false; public static int genAttribute() { Random dice = new Random(); int[] sumArray = {dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1}; for (int num : sumArray) { System.out.println(num); } int first = Integer.MIN_VALUE; int firstIndex = -1; int second = Integer.MIN_VALUE; int secondIndex = -1; int third = Integer.MIN_VALUE; for (int i = 0; i &lt; sumArray.length; i++) { int num = sumArray[i]; if (num &gt; first) { first = num; firstIndex = i; } } for (int i = 0; i &lt; sumArray.length; i++) { int num = sumArray[i]; if (num &gt; second &amp;&amp; num &lt;= first &amp;&amp; i != firstIndex) { second = num; secondIndex = i; } } for (int i = 0; i &lt; sumArray.length; i++) { int num = sumArray[i]; if (num &gt; third &amp;&amp; num &lt;= second &amp;&amp; i != secondIndex &amp;&amp; i != firstIndex) { third = num; } } System.out.println(first + " " + second + " " + third); return first + second + third; } public static boolean checkFinalArray(int[] checkArray) { int fifteenCount = 0; for (int z : checkArray) { if (z &gt;= 15) { fifteenCount++; } } return (fifteenCount &gt;= 2 &amp;&amp; Arrays.stream(checkArray).sum() &gt;= 75); } public static void main(String[] args) { while (!goodRoll) { int[] finalArray; finalArray = new int[6]; for (int i = 0; i &lt; 6; ++i) { finalArray[i] = genAttribute(); } if (checkFinalArray(finalArray)) { System.out.println("sum: " + Arrays.stream(finalArray).sum()); // Enhanced for to print each die for (int x : finalArray) { System.out.println(x); } goodRoll = true; } } } } </code></pre> <p>Can this be more efficiently written?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T19:15:31.553", "Id": "468504", "Score": "0", "body": "Any suggestions ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T21:14:07.673", "Id": "468511", "Score": "1", "body": "(Down-voters please comment.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T21:15:58.923", "Id": "468512", "Score": "1", "body": "Welcome to CodeReview@SE. How did you check this code does what it is supposed to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T21:16:20.477", "Id": "468513", "Score": "0", "body": "I have optimised from O(nlogn) to above .Please check and also can anyone help to convert it into TestNG so that no main method is required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T21:21:26.633", "Id": "468514", "Score": "2", "body": "Can you please motivate why *efficiency* would be a concern?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T03:40:31.877", "Id": "468531", "Score": "0", "body": "To improve the time and space complexity of this code." } ]
[ { "body": "<ul>\n<li><a href=\"https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#styleguide\" rel=\"nofollow noreferrer\">Document your code. In the code.</a> </li>\n<li><p>Be sure you got the specification right.<br>\nVery helpful here is giving <em>test</em> serious consideration early on.<br>\n• testing <code>order in which each value was generated must be preserved</code><br>\n looks a nightmare</p>\n\n<p>One way to present the approach coded:<br>\n1) generate six sums<br>\n2) if this sextuple is not admissible, start over<br>\n<em>Alternatives</em>:<br>\n2b) while sextuple is not admissible, delete oldest sum and append a new one<br>\n  This still results in six sums generated in a row.<br>\n2c) while sextuple is not admissible, delete smallest sum and append a new one<br>\n  This still preserves <code>the order in which each value was generated</code><br>\n  - but it skews the distribution.<br>\n<strong>But:</strong> What if the <strong><em>real</em></strong> requirement was<br>\n<em>Generate</em> six pseudo-random values with a distribution identical to the one from a procedure as sketched, <em>with <strong>utmost efficiency</em></strong><br>\n(You'd have to define <em>efficiency</em>.)</p></li>\n<li>Name things for what they can/will be used for. Difficult to guess for (<code>test</code>,) <code>genAttribute()</code>, <code>checkFinalArray()</code></li>\n<li>Parametrise where it does not add effort<br>\nWhat if you next wanted seven values each from five rolls of tetrahedral dice, three over a threshold of eleven and a total of at least 42?</li>\n<li>sometimes it pays to take a step back and try to look at the requirements specification from a different angle:<br>\nThe sum of the three largest values out of four may seem to require identifying those three values.<br>\nFrom a distance, it looks like the total minus the minimum.</li>\n</ul>\n\n<p>I started putting in writing what I think should do:</p>\n\n<pre><code> /** @param &lt;code&gt;nSums&lt;/code&gt; count of sums to return\n * @param &lt;code&gt;nDraws&lt;/code&gt; count of summands for each sum\n * @param &lt;code&gt;from&lt;/code&gt; lower bound for summands\n * @param &lt;code&gt;to_inclusive&lt;/code&gt; upper bound for summands\n * @param &lt;code&gt;threshold&lt;/code&gt; for \"big enough\"\n * @param &lt;code&gt;requiredCount&lt;/code&gt; count of sums required to be\n * \"big enough\"\n * @param &lt;code&gt;lowestTotal&lt;/code&gt; total to reach\n *\n * @return &lt;code&gt;nSums&lt;/code&gt; of &lt;code&gt;nDraws&lt;/code&gt; values each\n * but the smallest among those\n * - &lt;em&gt;if&lt;/em&gt;&lt;br/&gt;\n * - at least &lt;code&gt;requiredCount&lt;/code&gt; \n * sums reach &lt;code&gt;threshold&lt;/code&gt; &lt;em&gt;and&lt;/em&gt;&lt;br/&gt;\n * - the total is &lt;code&gt;lowestTotal&lt;/code&gt;, at least */\n public static int[]\n sufficientTopSums(int nSums, int nDraws, int from, int to_inclusive,\n int threshold, int requiredCount, int lowestTotal) {\n // Start with a queue filled with very negative values\n // keep a total and a count of sufficiently high sums\n\n // check int range suffices\n assert((long)(nDraws - 1) * to_inclusive &lt; Integer.MAX_VALUE / nSums);\n final int veryNegative = Integer.MIN_VALUE/nDraws;\n Queue&lt;Integer&gt; q = new ArrayDeque&lt;&gt;(Collections.nCopies(\n nSums, veryNegative));\n for (int total = veryNegative * nSums, sufficient = 0 ; ; ) {\n int replaced = q.remove();\n // account for value removed\n total -= replaced;\n if (threshold &lt;= replaced)\n sufficient--;\n // generate &amp; keep new sum\n int sum = sumIgnoringMin(nDraws, from, to_inclusive);\n q.add(sum);\n // account for new value\n if (threshold &lt;= sum)\n sufficient++;\n if (lowestTotal &lt;= (total += sum)\n &amp;&amp; requiredCount &lt;= sufficient)\n return q.stream().mapToInt(x-&gt;x).toArray();\n }\n }\n public static void main(String[] args) {\n System.out.println(Arrays.toString(\n sufficientTopSums(6, 4, 1, 6, 15, 2, 75)));\n }\n\n static final java.util.Random dice = new java.util.Random();\n private static final int[] NO_INTS = {};\n\n /** @param &lt;code&gt;nDraws&lt;/code&gt; count of values to draw\n * @param &lt;code&gt;from&lt;/code&gt; lower bound for values\n * @param &lt;code&gt;to_inclusive&lt;/code&gt; upper bound for values\n * @return sum of draws, excluding minimal value drawn */\n static int sumIgnoringMin(int nDraws, int from, int to_inclusive) {\n int to = to_inclusive - from + 1;\n int min = Integer.MAX_VALUE,\n sum = from * (nDraws);\n while (0 &lt;= --nDraws) {\n int drawn = dice.nextInt(to);\n if (drawn &lt; min)\n min = drawn;\n sum += drawn;\n }\n return sum - min - from;\n }\n</code></pre>\n\n<p>and stumbled upon not really knowing what representation to choose for the return value.<br>\nOh, well, <code>int[]</code> and <code>Collection&lt;Integer&gt;</code> can be converted easily enough.<br>\nFor lack of array rotation support, I went for a <code>Queue&lt;Integer&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T15:12:58.177", "Id": "468574", "Score": "0", "body": "`sumIgnoringMin` could alternatively use `dice.ints(from, to_inclusive+1).limit(nDraws).summaryStatistics().getSum/Min()`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T08:26:29.653", "Id": "238931", "ParentId": "238891", "Score": "2" } }, { "body": "<p>As already said by <a href=\"https://codereview.stackexchange.com/a/238931/203649\">greybeard</a> you have to try to be more specific about efficiency and what you want to improve. Your code can be simplified , for example your <code>genAttribute()</code> method:</p>\n\n<blockquote>\n<pre><code>public static int genAttribute() {\n Random dice = new Random();\n int[] sumArray = {dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1};\n for (int num : sumArray) {\n System.out.println(num);\n }\n //three cycles to obtain the three greatest elements omitted for brevity\n System.out.println(first + \" \" + second + \" \" + third);\n return first + second + third;\n}\n</code></pre>\n</blockquote>\n\n<p>You can use sort the array and loop over it in reverse, excluding the minimum element standing in the first position of the sorted array like below and avoiding the writing of three cycles for the three max elements:</p>\n\n<pre><code>public static int genAttribute() {\n Random dice = new Random();\n final int n = 4;\n int[] sumArray = dice.ints(n, 1, 7).toArray();\n\n for (int num : sumArray) {\n System.out.println(num);\n }\n\n Arrays.sort(sumArray);\n\n int sum = 0;\n StringJoiner joiner = new StringJoiner(\" \");\n for (int i = n - 1; i &gt; 0; --i) {\n sum += sumArray[i];\n joiner.add(Integer.toString(sumArray[i]));\n }\n System.out.println(joiner);\n\n return sum;\n}\n</code></pre>\n\n<p>I used the method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#ints-long-int-int-\" rel=\"nofollow noreferrer\">Random.ints</a> to generate the array and after the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html\" rel=\"nofollow noreferrer\">StringJoiner</a> class to print the elements. The code is using a parameter <code>n</code> that can be modified at your choice, so the code will remain the same even if the parameter <code>n</code> (number of dices) is modified.</p>\n\n<p>A slight modification can be applied on your method <code>checkFinalArray</code>:</p>\n\n<blockquote>\n<pre><code>public static boolean checkFinalArray(int[] checkArray) {\n int fifteenCount = 0;\n for (int z : checkArray) {\n if (z &gt;= 15) {\n fifteenCount++;\n }\n }\n return (fifteenCount &gt;= 2 &amp;&amp; Arrays.stream(checkArray).sum() &gt;= 75);\n}\n</code></pre>\n</blockquote>\n\n<p>Obtain the sum of the elements directly in the array inside the cycle without using of stream at the end of the method:</p>\n\n<pre><code>public static boolean checkFinalArray(int[] checkArray) {\n int fifteenCount = 0;\n int sum = 0;\n for (int z : checkArray) {\n if (z &gt;= 15) {\n fifteenCount++;\n }\n sum += z;\n }\n return (fifteenCount &gt;= 2 &amp;&amp; sum &gt;= 75);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:04:50.873", "Id": "238994", "ParentId": "238891", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T16:30:07.893", "Id": "238891", "Score": "1", "Tags": [ "java" ], "Title": "Adding up dice rolls with constraints" }
238891
<p><a href="https://en.wikipedia.org/wiki/Run-length_encoding" rel="nofollow noreferrer">Run-length encoding (RLE)</a> is a simple form of data compression, where runs (consecutive data elements) are replaced by just one data value and a count.</p> <p>For example:</p> <pre><code>WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW </code></pre> <p>becomes this:</p> <pre><code>12W1B12W3B24W1B14W </code></pre> <p>Here's an implementation of <code>RunLengthEncode</code> and <code>RunLengthDecode</code> functions in Go. I'd appreciate any feedback. What's OK, what's not, and what could be improved and/or changed.</p> <pre><code>package encode import ( "strconv" "strings" "unicode" ) type runLength struct { enc, dec func(string) string } func newRunLength() *runLength { return &amp;runLength{ enc: func(input string) string { var result strings.Builder for len(input) &gt; 0 { firstLetter := input[0] inputLength := len(input) input = strings.TrimLeft(input, string(firstLetter)) if counter := inputLength - len(input); counter &gt; 1 { result.WriteString(strconv.Itoa(counter)) } result.WriteString(string(firstLetter)) } return result.String() }, dec: func(input string) string { var result strings.Builder for len(input) &gt; 0 { letterIndex := strings.IndexFunc(input, func(r rune) bool {return !unicode.IsDigit(r)}) multiply := 1 if letterIndex != 0 { multiply, _ = strconv.Atoi(input[:letterIndex]) } result.WriteString(strings.Repeat(string(input[letterIndex]), multiply)) input = input[letterIndex+1:] } return result.String() }} } func (rl runLength) encode(input string) string { return rl.enc(input) } func (rl runLength) decode(input string) string { return rl.dec(input) } func RunLengthEncode(input string) string { return newRunLength().encode(input) } func RunLengthDecode(input string) string { return newRunLength().decode(input) } </code></pre> <p><strong>Test cases:</strong></p> <pre><code>package encode // run-length encode a string var encodeTests = []struct { input string expected string description string }{ {"", "", "empty string"}, {"XYZ", "XYZ", "single characters only are encoded without count"}, {"AABBBCCCC", "2A3B4C", "string with no single characters"}, {"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB", "12WB12W3B24WB", "single characters mixed with repeated characters"}, {" hsqq qww ", "2 hs2q q2w2 ", "multiple whitespace mixed in string"}, {"aabbbcccc", "2a3b4c", "lowercase characters"}, } // run-length decode a string var decodeTests = []struct { input string expected string description string }{ {"", "", "empty string"}, {"XYZ", "XYZ", "single characters only"}, {"2A3B4C", "AABBBCCCC", "string with no single characters"}, {"12WB12W3B24WB", "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB", "single characters with repeated characters"}, {"2 hs2q q2w2 ", " hsqq qww ", "multiple whitespace mixed in string"}, {"2a3b4c", "aabbbcccc", "lower case string"}, } // encode and then decode var encodeDecodeTests = []struct { input string expected string description string }{ {"zzz ZZ zZ", "zzz ZZ zZ", "encode followed by decode gives original string"}, } </code></pre> <p><strong>Tests:</strong></p> <pre><code>package encode import "testing" func TestRunLengthEncode(t *testing.T) { for _, test := range encodeTests { if actual := RunLengthEncode(test.input); actual != test.expected { t.Errorf("FAIL %s - RunLengthEncode(%s) = %q, expected %q.", test.description, test.input, actual, test.expected) } t.Logf("PASS RunLengthEncode - %s", test.description) } } func TestRunLengthDecode(t *testing.T) { for _, test := range decodeTests { if actual := RunLengthDecode(test.input); actual != test.expected { t.Errorf("FAIL %s - RunLengthDecode(%s) = %q, expected %q.", test.description, test.input, actual, test.expected) } t.Logf("PASS RunLengthDecode - %s", test.description) } } func TestRunLengthEncodeDecode(t *testing.T) { for _, test := range encodeDecodeTests { if actual := RunLengthDecode(RunLengthEncode(test.input)); actual != test.expected { t.Errorf("FAIL %s - RunLengthDecode(RunLengthEncode(%s)) = %q, expected %q.", test.description, test.input, actual, test.expected) } t.Logf("PASS %s", test.description) } } </code></pre>
[]
[ { "body": "<p>This is a real-world code review: Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.</p>\n\n<hr>\n\n<p>The Go programming language was designed for simplicity and readability. Why did you write:</p>\n\n<pre><code>type runLength struct {\n enc, dec func(string) string\n}\n\nfunc newRunLength() *runLength {\n return &amp;runLength{\n enc: func(input string) string {\n var result strings.Builder\n for len(input) &gt; 0 {\n firstLetter := input[0]\n inputLength := len(input)\n input = strings.TrimLeft(input, string(firstLetter))\n if counter := inputLength - len(input); counter &gt; 1 {\n result.WriteString(strconv.Itoa(counter))\n }\n result.WriteString(string(firstLetter))\n }\n return result.String()\n },\n dec: func(input string) string {\n var result strings.Builder\n for len(input) &gt; 0 {\n letterIndex := strings.IndexFunc(input, func(r rune) bool { return !unicode.IsDigit(r) })\n multiply := 1\n if letterIndex != 0 {\n multiply, _ = strconv.Atoi(input[:letterIndex])\n }\n result.WriteString(strings.Repeat(string(input[letterIndex]), multiply))\n input = input[letterIndex+1:]\n }\n return result.String()\n }}\n}\n\nfunc (rl runLength) encode(input string) string {\n return rl.enc(input)\n}\n\nfunc (rl runLength) decode(input string) string {\n return rl.dec(input)\n}\n\nfunc RunLengthEncode(input string) string {\n return newRunLength().encode(input)\n}\n\nfunc RunLengthDecode(input string) string {\n return newRunLength().decode(input)\n}\n</code></pre>\n\n<p>when a simpler, more readable form is:</p>\n\n<pre><code>func RunLengthEncode(input string) string {\n var result strings.Builder\n for len(input) &gt; 0 {\n firstLetter := input[0]\n inputLength := len(input)\n input = strings.TrimLeft(input, string(firstLetter))\n if counter := inputLength - len(input); counter &gt; 1 {\n result.WriteString(strconv.Itoa(counter))\n }\n result.WriteString(string(firstLetter))\n }\n return result.String()\n}\n\nfunc RunLengthDecode(input string) string {\n var result strings.Builder\n for len(input) &gt; 0 {\n letterIndex := strings.IndexFunc(input, func(r rune) bool { return !unicode.IsDigit(r) })\n multiply := 1\n if letterIndex != 0 {\n multiply, _ = strconv.Atoi(input[:letterIndex])\n }\n result.WriteString(strings.Repeat(string(input[letterIndex]), multiply))\n input = input[letterIndex+1:]\n }\n return result.String()\n}\n</code></pre>\n\n<hr>\n\n<p>Go was designed and implemented to be reasonably efficient. Your code looks inefficient.</p>\n\n<p>For example,</p>\n\n<p>baduker:</p>\n\n<pre><code>$ go test -bench=. -benchmem -run=!\ngoos: linux\ngoarch: amd64\nBenchmarkEncode-4 614804 1936 ns/op 464 B/op 27 allocs/op\nBenchmarkDecode-4 844690 1446 ns/op 256 B/op 18 allocs/op\n$ \n</code></pre>\n\n<p>versus peterSO:</p>\n\n<pre><code>$ go test -bench=. -benchmem -run=!\ngoos: linux\ngoarch: amd64\nBenchmarkEncode-4 3543656 342 ns/op 104 B/op 4 allocs/op\nBenchmarkDecode-4 2717763 460 ns/op 216 B/op 7 allocs/op\n$ \n</code></pre>\n\n<p><code>benchmark_test.go</code>:</p>\n\n<pre><code>package encode\n\nimport (\n \"testing\"\n)\n\nfunc BenchmarkEncode(b *testing.B) {\n for N := 0; N &lt; b.N; N++ {\n RunLengthEncode(\"AABCCCDEEEE\")\n RunLengthEncode(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB\")\n }\n}\n\nfunc BenchmarkDecode(b *testing.B) {\n for N := 0; N &lt; b.N; N++ {\n RunLengthDecode(\"2AB3CD4E\")\n RunLengthDecode(\"12WB12W3B24WB\")\n }\n}\n</code></pre>\n\n<p>peterSO <code>run_length_encoding.go</code>:</p>\n\n<pre><code>package encode\n\nimport (\n \"strconv\"\n)\n\nfunc RunLengthEncode(s string) string {\n e := make([]byte, 0, len(s))\n for i := 0; i &lt; len(s); i++ {\n c := s[i]\n j := i + 1\n for ; j &lt;= len(s); j++ {\n if j &lt; len(s) &amp;&amp; s[j] == c {\n continue\n }\n if j-i &gt; 1 {\n e = strconv.AppendInt(e, int64(j-i), 10)\n }\n e = append(e, c)\n break\n }\n i = j - 1\n }\n return string(e)\n}\n\nfunc RunLengthDecode(s string) string {\n d := make([]byte, 0, len(s))\n for i := 0; i &lt; len(s); i++ {\n n := 0\n for ; i &lt; len(s) &amp;&amp; (s[i] &gt;= '0' &amp;&amp; s[i] &lt;= '9'); i++ {\n n = 10*n + int(s[i]-'0')\n }\n if i &lt; len(s) {\n c := s[i]\n for ; n &gt; 1; n-- {\n d = append(d, c)\n }\n d = append(d, c)\n }\n }\n return string(d)\n}\n</code></pre>\n\n<p>baduker <code>run_length_encoding.go</code>:</p>\n\n<pre><code>package encode\n\nimport (\n \"strconv\"\n \"strings\"\n \"unicode\"\n)\n\ntype runLength struct {\n enc, dec func(string) string\n}\n\nfunc newRunLength() *runLength {\n return &amp;runLength{\n enc: func(input string) string {\n var result strings.Builder\n for len(input) &gt; 0 {\n firstLetter := input[0]\n inputLength := len(input)\n input = strings.TrimLeft(input, string(firstLetter))\n if counter := inputLength - len(input); counter &gt; 1 {\n result.WriteString(strconv.Itoa(counter))\n }\n result.WriteString(string(firstLetter))\n }\n return result.String()\n },\n dec: func(input string) string {\n var result strings.Builder\n for len(input) &gt; 0 {\n letterIndex := strings.IndexFunc(input, func(r rune) bool { return !unicode.IsDigit(r) })\n multiply := 1\n if letterIndex != 0 {\n multiply, _ = strconv.Atoi(input[:letterIndex])\n }\n result.WriteString(strings.Repeat(string(input[letterIndex]), multiply))\n input = input[letterIndex+1:]\n }\n return result.String()\n }}\n}\n\nfunc (rl runLength) encode(input string) string {\n return rl.enc(input)\n}\n\nfunc (rl runLength) decode(input string) string {\n return rl.dec(input)\n}\n\nfunc RunLengthEncode(input string) string {\n return newRunLength().encode(input)\n}\n\nfunc RunLengthDecode(input string) string {\n return newRunLength().decode(input)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:54:41.050", "Id": "468555", "Score": "0", "body": "Thanks for yet another no-nonsense review. This is good stuff!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T05:56:25.657", "Id": "238927", "ParentId": "238893", "Score": "1" } }, { "body": "<p>Your implementation quickly falls apart when we have digits inside strings. Consider the following testcases:</p>\n\n<pre><code>package encode\n\n// run-length encode a string\nvar encodeTests = []struct {\n input string\n expected string\n description string\n}{\n {\"1111111111111\", \"131\", \"numbers test\"},\n {\"131\", \"131\", \"unique numbers test\"},\n}\n\n// run-length decode a string\nvar decodeTests = []struct {\n input string\n expected string\n description string\n}{\n {\"131\", \"1111111111111\", \"numbers test\"},\n {\"131\", \"131\", \"unique numbers test\"},\n}\n\n// encode and then decode\nvar encodeDecodeTests = []struct {\n input string\n expected string\n description string\n}{\n {\"1111111111111\", \"1111111111111\", \"encode followed by decode gives original string\"},\n {\"131\", \"131\", \"encode followed by decode gives original string\"},\n}\n</code></pre>\n\n<p>These requirements are impossible to satisfy as two distinct inputs can give the same output. When actually run, a panic results:</p>\n\n<pre><code>--- FAIL: TestRunLengthDecode (0.00s)\npanic: runtime error: slice bounds out of range [recovered]\n panic: runtime error: slice bounds out of range\n\ngoroutine 19 [running]:\ntesting.tRunner.func1(0xc0000a4300)\n /usr/lib/go-1.11/src/testing/testing.go:792 +0x387\npanic(0x512100, 0x619ff0)\n /usr/lib/go-1.11/src/runtime/panic.go:513 +0x1b9\nencode.newRunLength.func2(0x536b33, 0x3, 0x5207a0, 0xc00005e4b0)\n /home/minombre/go/src/encode/encode.go:34 +0x2eb\nencode.runLength.decode(0x53fb70, 0x53fb80, 0x536b33, 0x3, 0xc000030601, 0x40bbf8)\n /home/minombre/go/src/encode/encode.go:48 +0x3a\nencode.RunLengthDecode(0x536b33, 0x3, 0x6074c8, 0x27)\n /home/minombre/go/src/encode/encode.go:56 +0x4f\nencode.TestRunLengthDecode(0xc0000a4300)\n /home/minombre/go/src/encode/encode_test.go:16 +0xee\ntesting.tRunner(0xc0000a4300, 0x53fb58)\n /usr/lib/go-1.11/src/testing/testing.go:827 +0xbf\ncreated by testing.(*T).Run\n /usr/lib/go-1.11/src/testing/testing.go:878 +0x35c\nFAIL encode 0.008s\n</code></pre>\n\n<p>You could possibly store these into some sort of a structure with a character per structure but that would be impractical.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:58:58.920", "Id": "238951", "ParentId": "238893", "Score": "3" } } ]
{ "AcceptedAnswerId": "238927", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T17:14:44.530", "Id": "238893", "Score": "5", "Tags": [ "go" ], "Title": "Run Length Encoding in Go(lang)" }
238893
<p>I'm studying design patterns from <a href="http://shop.oreilly.com/product/9780596007126.do" rel="nofollow noreferrer">Head First Design Patterns</a> and, in order to get confident, I plan to implement the each pattern in C++ after studying the corresponding chapter.</p> <p>As regards the Strategy pattern, this is the result:</p> <ul> <li><code>Duck.hpp</code>:</li> </ul> <pre><code>#ifndef DUCK_H #define DUCK_H #include &lt;memory&gt; #include "FlyBehavior.hpp" #include "QuackBehavior.hpp" class Duck { private: std::unique_ptr&lt;FlyBehavior&gt; flyBehavior; std::unique_ptr&lt;QuackBehavior&gt; quackBehavior; public: Duck(std::unique_ptr&lt;FlyBehavior&gt;, std::unique_ptr&lt;QuackBehavior&gt;); void performFly(); void performQuack(); void setFlyBehavior(std::unique_ptr&lt;FlyBehavior&gt;); void setQuackBehavior(std::unique_ptr&lt;QuackBehavior&gt;); virtual void display() = 0; }; #endif /* ifndef DUCK_H */ </code></pre> <ul> <li><code>Duck.cpp</code>:</li> </ul> <pre><code>#include &lt;algorithm&gt; #include &lt;memory&gt; #include "Duck.hpp" Duck::Duck(std::unique_ptr&lt;FlyBehavior&gt; fb, std::unique_ptr&lt;QuackBehavior&gt; qb) : flyBehavior(std::move(fb)) , quackBehavior(std::move(qb)) {} void Duck::performFly() { flyBehavior-&gt;fly(); }; void Duck::performQuack() { quackBehavior-&gt;quack(); }; void Duck::setFlyBehavior(std::unique_ptr&lt;FlyBehavior&gt; fb) { flyBehavior = std::move(fb); }; void Duck::setQuackBehavior(std::unique_ptr&lt;QuackBehavior&gt; qb) { quackBehavior = std::move(qb); }; </code></pre> <ul> <li><code>RubberDuck.hpp</code>:</li> </ul> <pre><code>#ifndef RUBBERDUCK_H #define RUBBERDUCK_H #include "Duck.hpp" class RubberDuck : public Duck { public: RubberDuck(); void display() override; }; #endif /* ifndef RUBBERDUCK_H */ </code></pre> <ul> <li><code>RubberDuck.cpp</code>:</li> </ul> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include "FlyNoWay.hpp" #include "RubberDuck.hpp" #include "Squeak.hpp" RubberDuck::RubberDuck() : Duck(std::make_unique&lt;FlyNoWay&gt;(), std::make_unique&lt;Squeak&gt;()) { }; void RubberDuck::display() { std::cout &lt;&lt; "Hello, I am a rubber duck!\n"; }; </code></pre> <ul> <li><code>SupersonicDuck.hpp</code>:</li> </ul> <pre><code>#ifndef SUPERSONICDUCK_H #define SUPERSONICDUCK_H #include "Duck.hpp" class SupersonicDuck : public Duck { public: SupersonicDuck(); void display() override; }; #endif /* ifndef SUPERSONICDUCK_H */ </code></pre> <ul> <li><code>SupersonicDuck.cpp</code>:</li> </ul> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include "FlyRocketPowered.hpp" #include "SupersonicDuck.hpp" #include "SupersonicSqueak.hpp" SupersonicDuck::SupersonicDuck() : Duck(std::make_unique&lt;FlyRocketPowered&gt;(), std::make_unique&lt;SupersonicSqueak&gt;()) { } void SupersonicDuck::display() { std::cout &lt;&lt; "Hello, I am a supersonic duck!\n"; }; </code></pre> <ul> <li><code>FlyBehavior.hpp</code>:</li> </ul> <pre><code>#ifndef FLYBEHAVIOR_H #define FLYBEHAVIOR_H class FlyBehavior { public: virtual void fly() = 0; }; #endif /* ifndef FLYBEHAVIOR_H */ </code></pre> <ul> <li><code>FlyNoWay.hpp</code>:</li> </ul> <pre><code>#ifndef NOFLY_H #define NOFLY_H #include "FlyBehavior.hpp" class FlyNoWay : public FlyBehavior { public: void fly() override; }; #endif /* ifndef NOFLY_H */ </code></pre> <ul> <li><code>FlyNoWay.cpp</code>:</li> </ul> <pre><code>#include &lt;iostream&gt; #include "FlyNoWay.hpp" void FlyNoWay::fly() { std::cout &lt;&lt; "I can't fly!\n"; }; </code></pre> <ul> <li><code>FlyRocketPowered.hpp</code>:</li> </ul> <pre><code>#ifndef FLYROCKETPOWERED_H #define FLYROCKETPOWERED_H #include "FlyBehavior.hpp" class FlyRocketPowered : public FlyBehavior { void fly() override; }; #endif /* ifndef FLYROCKETPOWERED_H */ </code></pre> <ul> <li><code>FlyRocketPowered.cpp</code>:</li> </ul> <pre><code>#include &lt;iostream&gt; #include "FlyRocketPowered.hpp" void FlyRocketPowered::fly() { std::cout &lt;&lt; "WHOOOOOOMMMMMM\n"; }; </code></pre> <ul> <li><code>QuackBehavior.hpp</code></li> </ul> <pre><code>#ifndef QUACKBEHAVIOR_H #define QUACKBEHAVIOR_H class QuackBehavior { public: virtual void quack() = 0; }; #endif /* ifndef QUACKBEHAVIOR_H */ </code></pre> <ul> <li><code>Squeak.hpp</code></li> </ul> <pre><code>#ifndef SQUEAK_H #define SQUEAK_H #include "QuackBehavior.hpp" class Squeak : public QuackBehavior { public: void quack() override; }; #endif /* ifndef SQUEAK_H */ </code></pre> <ul> <li><code>Squeak.cpp</code></li> </ul> <pre><code>#include &lt;iostream&gt; #include "Squeak.hpp" void Squeak::quack() { std::cout &lt;&lt; "Squeak!\n"; }; </code></pre> <ul> <li><code>SupersonicSqueak.hpp</code></li> </ul> <pre><code>#ifndef SUPERSONICSQUEAK_H #define SUPERSONICSQUEAK_H #include "QuackBehavior.hpp" class SupersonicSqueak : public QuackBehavior { public: void quack() override; }; #endif /* ifndef SUPERSONICSQUEAK_H */ </code></pre> <ul> <li><code>SupersonicSqueak.cpp</code></li> </ul> <pre><code>#include &lt;iostream&gt; #include "SupersonicSqueak.hpp" void SupersonicSqueak::quack() { std::cout &lt;&lt; "SQUEEEEAAAAK!\n"; }; </code></pre> <ul> <li><code>main.cpp</code></li> </ul> <pre><code>#include &lt;memory&gt; #include "RubberDuck.hpp" #include "SupersonicDuck.hpp" #include "FlyRocketPowered.hpp" #include "Squeak.hpp" int main() { RubberDuck rd; rd.display(); rd.performFly(); rd.performQuack(); SupersonicDuck sd; sd.display(); sd.performFly(); sd.performQuack(); // enhance rd with rockets: rd.setFlyBehavior(std::make_unique&lt;FlyRocketPowered&gt;()); rd.display(); rd.performFly(); rd.performQuack(); } </code></pre> <p>The code works, hence I'm posting here an not on Stack Overflow, however I have some concerns about the following choices:</p> <ul> <li>I've used <code>make_unique</code>/<code>unique_ptr</code>, but I could also use <code>make_shared</code>/<code>shared_ptr</code>;</li> <li>I've tried to always split a translation unit in header and implementation files;</li> <li>I've not defined a default constructor, but rather a two parameter constructor, as no duck should exist without the two behaviors;</li> <li>The methods <code>setFlyBehavior</code> and <code>setQuackBehavior</code> can change the objects' behavior at runtime, such that the only two things that cannot change are the type itself of the object, and those methods (such as <code>display</code>) which have not been factored out of the <code>Duck</code> class.</li> </ul>
[]
[ { "body": "<p>The code looks good. It is probably a good idea to make the include guard macros agree with the file name (<code>_H</code> vs <code>.hpp</code>).</p>\n\n<p>There is a simpler way to implement the strategy pattern &mdash; to store <code>std::function</code>s rather than smart pointers to base classes:</p>\n\n<pre><code>struct Duck {\n using behavior_t = std::function&lt;void()&gt;;\n behavior_t fly;\n behavior_t quack;\n behavior_t display; // maybe const; but that disables moving\n};\n</code></pre>\n\n<p>Now everything is much simpler:</p>\n\n<pre><code>// for example\nconst auto plain_fly = [] { std::cout &lt;&lt; \"(flies)\\n\"; };\nconst auto plain_quack = [] { std::cout &lt;&lt; \"(quacks)\\n\"; };\n\n// can even determine operation dynamically\nstruct hello_display {\n std::string name;\n void operator()() const\n {\n std::cout &lt;&lt; \"Hello, I am a \" &lt;&lt; name &lt;&lt; \"!\\n\";\n }\n};\n\nint main()\n{\n Duck plain_duck{plain_fly, plain_quack, hello_display{\"plain duck\"}};\n plain_duck.fly();\n plain_duck.quack();\n plain_duck.display();\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/zitlvLiT0nu8SSNz\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n\n<blockquote>\n <p>I've used <code>make_unique</code>/<code>unique_ptr</code>, but I could also use <code>make_shared</code>/<code>shared_ptr</code>;</p>\n</blockquote>\n\n<p>If the resource is owned by only one smart pointer rather than shared by multiple smart pointers, then <code>unique_ptr</code> is a reasonable choice.</p>\n\n<blockquote>\n <p>I've tried to always split a translation unit in header and implementation files;</p>\n</blockquote>\n\n<p>For simple operations, you can alternatively define the methods inline in the header file.</p>\n\n<blockquote>\n <p>I've not defined a default constructor, but rather a two parameter\n constructor, as no duck should exist without the two behaviors;</p>\n</blockquote>\n\n<p>Consider checking for null pointers.</p>\n\n<blockquote>\n <p>The methods <code>setFlyBehavior</code> and <code>setQuackBehavior</code> can change the\n objects' behavior at runtime, such that the only two things that\n cannot change are the type itself of the object, and those methods\n (such as display) which have not been factored out of the <code>Duck</code> class.</p>\n</blockquote>\n\n<p>This is fine if it fits the semantics of your program. Note that you can also use the strategy pattern for immutable attributes by not providing the corresponding modifier method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T09:13:15.327", "Id": "468542", "Score": "0", "body": "Concerning `unique_ptr` vs `shared_ptr`, your comment seems correct by definition. But how does this translate in common (not necessarily toy) usecases? I mean, using `shared_ptr` means that one could use a single `flyBehavior` object for all `Duck` objects, whereas using `unique_ptr` means that one should use a `flyBehavior` object for each `Duck` object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:19:54.637", "Id": "468547", "Score": "1", "body": "@EnricoMariaDeAngelis As you mentioned, shared pointers can be copied, while unique pointers can only be moved (virtual `clone` methods are required if you want to copy them). The selection depends on the semantics - do you want each duck to have exclusive possession the objects indicating its behavior? There isn't a clear-cut choice to make." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:23:31.763", "Id": "468549", "Score": "0", "body": "Ok, I understand that the two approaches (`unique_ptr` vs `shared_ptr`) are equally desirable in different scenarios (I just don't know what the two groups of scenarios are, but maybe I just need to have some exposure to them in a professional framework)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:33:37.753", "Id": "468550", "Score": "0", "body": "@EnricoMariaDeAngelis You can take a look at [Differences between unique_ptr and shared_ptr](https://stackoverflow.com/q/6876751) for some information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:36:24.123", "Id": "468551", "Score": "0", "body": "As regards your alternative approach, my understanding is: once I decide to encapsulate *all* behaviors, I don't need to subclass `Duck` anymore, as it just becomes a collection of a certain number of behaviors, each having a specific name and a specific signature (the latter happens to be the same for all behaviors, but it does not have to). I don't even need one class representing the interface of each possible concrete behavior, as that is imposed by `std::function`. In turn, I don't even need the concrete behavior classes. Am I talking nonsense?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:39:38.783", "Id": "468553", "Score": "1", "body": "@EnricoMariaDeAngelis Your understanding is correct. My point was that sometimes OOP patterns don't necessary need to be implemented with inheritance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:17:49.073", "Id": "468579", "Score": "0", "body": "Correct me if I'm wrong, but your approach is a more functional one. If this is the case, maybe it's good for a reader that I link the question [“Strategy Pattern” in Haskell](https://stackoverflow.com/questions/21677201/strategy-pattern-in-haskell)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T00:45:18.980", "Id": "468628", "Score": "0", "body": "@EnricoMariaDeAngelis I don’t really see how my approach is functional (usage of function != functional programming), but it doesn’t matter what pattern/paradigm/idiom/structure/design/whatever you all a certain way of solving the problem as long as it is suitable and convenient for the purpose. Patterns are just typical examples that help you find the optimal design; you are free to adapt them as you deem appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T06:26:06.137", "Id": "468647", "Score": "0", "body": "I was referring to injecting functions directly without having to wrap them in classes. Isn't this distinctive of FP, where functions are first class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T06:33:21.580", "Id": "468649", "Score": "1", "body": "@EnricoMariaDeAngelis Well, I always regarded FP as [a programming paradigm \\[...\\] that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm in that programming is done with expressions or declarations instead of statements.](https://en.wikipedia.org/wiki/Functional_programming) I don't think it has anything directly to do with first-class functions. I might be wrong." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T04:27:29.797", "Id": "238920", "ParentId": "238901", "Score": "2" } } ]
{ "AcceptedAnswerId": "238920", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T20:42:56.213", "Id": "238901", "Score": "5", "Tags": [ "c++", "design-patterns", "inheritance" ], "Title": "Strategy pattern in C++ - the Duck simulator" }
238901
<p>I made a very simple Instagram Bot that can download images and videos of the user, like Gallery with photos or videos. It saves the data in the folder.</p> <h1>How it works:</h1> <ul> <li><p>Creating directory for saving images and videos</p> </li> <li><p>Using Selenium for links extraction</p> </li> <li><p>Check the availability of Instagram profile if it's private or existing</p> </li> <li><p>Using threads and multiprocessing improve execution speed</p> </li> </ul> <p>My code:</p> <pre><code>import string import requests import os import time from selenium import webdriver from selenium.common.exceptions import WebDriverException import sys from multiprocessing.dummy import Pool import random import urllib.parse import argparse import re from concurrent.futures import ThreadPoolExecutor LINKS = [] PICTURES = [] VIDEO = [] def check_availability(link, cookies): &quot;&quot;&quot; This function checks the availability of profile and the status code :param link: link that searching for and includes the profile name :param cookies: cookies from class &lt;MyHttpBase&gt; :return: False if the &lt;privacy&gt; is True and &lt;followed_by_viewer&gt; is False &quot;&quot;&quot; search = requests.get(urllib.parse.urljoin(link, &quot;?__a=1&quot;), cookies) if search.ok: load_and_check = search.json() privacy = load_and_check.get(&quot;graphql&quot;).get(&quot;user&quot;).get(&quot;is_private&quot;) followed_by_viewer = load_and_check.get(&quot;graphql&quot;).get(&quot;user&quot;).get(&quot;followed_by_viewer&quot;) if privacy and not followed_by_viewer: return False else: search.raise_for_status() def URL_fetcher(url, cookies): &quot;&quot;&quot; This function extracts images and videos :param url: Taking the url of array LINKS :param cookies: cookies from class &lt;MyHttpBase&gt; :return: &quot;&quot;&quot; logging_page_id = requests.get(url.split()[0], cookies=cookies).json() try: &quot;&quot;&quot;Taking Gallery Photos or Videos&quot;&quot;&quot; for i in range(len(logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'])): video = \ logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][i]['node'][ &quot;is_video&quot;] if video is True: video_url = \ logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][i][ 'node'][ &quot;video_url&quot;] if video_url not in VIDEO: VIDEO.append(video_url) else: image = \ logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][i][ 'node'][ 'display_url'] if image not in PICTURES: PICTURES.append(image) except KeyError: &quot;&quot;&quot;Unique photo or Video&quot;&quot;&quot; image = logging_page_id['graphql']['shortcode_media']['display_url'] if image not in PICTURES: PICTURES.append(image) if logging_page_id['graphql']['shortcode_media'][&quot;is_video&quot;] is True: videos = logging_page_id['graphql']['shortcode_media'][&quot;video_url&quot;] if videos not in VIDEO: VIDEO.append(videos) class MyHttpBase: &quot;&quot;&quot; Setting up a Requests session and pass it around &quot;&quot;&quot; s = requests.Session() def setupCookies(self, COOKIES): for cookie in COOKIES: c = {cookie[&quot;name&quot;]: cookie[&quot;value&quot;]} self.s.cookies.update(c) def cookieJar(self): return self.s.cookies def close_session(self): return self.s.close() class InstagramPV: def __init__(self, username, password, folder, search_name): &quot;&quot;&quot; :param username: username :param password: password :param folder: folder name :param search_name: the name what will search &quot;&quot;&quot; self.username = username self.password = password self.folder = folder &quot;&quot;&quot;To avoid any errors, with regex find the url and taking the name &lt;search_name&gt;&quot;&quot;&quot; find_name = &quot;&quot;.join(re.findall(r&quot;(?P&lt;url&gt;https?://[^\s]+)&quot;, search_name)) if find_name.startswith(&quot;https&quot;): self.search_name = urllib.parse.urlparse(find_name).path.split(&quot;/&quot;)[1] else: self.search_name = search_name try: self.driver = webdriver.Chrome() except WebDriverException as e: print(str(e)) sys.exit(1) def __enter__(self): return self def control(self): &quot;&quot;&quot; Create the folder name and raises an error if already exists &quot;&quot;&quot; if not os.path.exists(self.folder): os.mkdir(self.folder) else: raise FileExistsError(&quot;[*] Alredy Exists This Folder&quot;) def login(self): &quot;&quot;&quot;Login To Instagram&quot;&quot;&quot; self.driver.get(&quot;https://www.instagram.com/accounts/login&quot;) time.sleep(3) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) submit = self.driver.find_element_by_tag_name('form') submit.submit() time.sleep(3) try: &quot;&quot;&quot;Check For Invalid Credentials&quot;&quot;&quot; var_error = self.driver.find_element_by_class_name(&quot;eiCW-&quot;).text if len(var_error) &gt; 0: print(var_error) sys.exit(1) except WebDriverException: pass try: self.driver.find_element_by_xpath('//button[text()=&quot;Not Now&quot;]').click() except WebDriverException: pass time.sleep(2) &quot;&quot;&quot;Taking Cookies To pass it in class &lt;MyHttpBase&gt;&quot;&quot;&quot; cookies = self.driver.get_cookies() MyHttpBase().setupCookies(cookies) COOKIES = MyHttpBase().cookieJar() self.driver.get(&quot;https://www.instagram.com/{name}/&quot;.format(name=self.search_name)) &quot;&quot;&quot;Checking the availability&quot;&quot;&quot; if not check_availability(&quot;https://www.instagram.com/{name}/&quot;.format(name=self.search_name), COOKIES): return self.scroll_down() def _get_href(self): elements = self.driver.find_elements_by_xpath(&quot;//a[@href]&quot;) for elem in elements: urls = elem.get_attribute(&quot;href&quot;) if &quot;p&quot; in urls.split(&quot;/&quot;): LINKS.append(urls) def scroll_down(self): &quot;&quot;&quot;Taking hrefs while scrolling down&quot;&quot;&quot; end_scroll = [] while True: self.driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);&quot;) time.sleep(2) self._get_href() time.sleep(2) new_height = self.driver.execute_script(&quot;return document.body.scrollHeight&quot;) end_scroll.append(new_height) if end_scroll.count(end_scroll[-1]) &gt; 4: self.extraction_url() break def extraction_url(self): &quot;&quot;&quot;Gathering Images and Videos Using ThreadPoolExecutor and pass to function &lt;URL_fetcher&gt; &quot;&quot;&quot; links = list(set(LINKS)) print(&quot;[!] Ready for video - images&quot;.title()) print(&quot;[*] extracting {links} posts , please wait...&quot;.format(links=len(links)).title()) cookies = MyHttpBase().cookieJar() new_links = [urllib.parse.urljoin(link, &quot;?__a=1&quot;) for link in links] with ThreadPoolExecutor(max_workers=8) as executor: [executor.submit(URL_fetcher, link, cookies) for link in new_links] def content_of_url(self, url): &quot;&quot;&quot; :param url: the url :return: the content &quot;&quot;&quot; re = requests.get(url) return re.content def _download_video(self, new_videos): &quot;&quot;&quot; Saving the content of video in the file &quot;&quot;&quot; with open( os.path.join(self.folder, &quot;Video{}.mp4&quot;).format( &quot;&quot;.join([random.choice(string.digits) for i in range(20)])), &quot;wb&quot;) as f: content_of_video = self.content_of_url(new_videos) f.write(content_of_video) def _images_download(self, new_pictures): &quot;&quot;&quot;Saving the content of picture in the file&quot;&quot;&quot; with open( os.path.join(self.folder, &quot;Image{}.jpg&quot;).format( &quot;&quot;.join([random.choice(string.digits) for i in range(20)])), &quot;wb&quot;) as f: content_of_picture = self.content_of_url(new_pictures) f.write(content_of_picture) def downloading_video_images(self): &quot;&quot;&quot;Using multiprocessing for Saving Images and Videos&quot;&quot;&quot; print(&quot;[*] ready for saving images and videos!&quot;.title()) new_pictures = list(set(PICTURES)) new_videos = list(set(VIDEO)) pool = Pool(8) pool.map(self._images_download, new_pictures) pool.map(self._download_video, new_videos) print(&quot;[+] done&quot;.title()) MyHttpBase().close_session() def __exit__(self, exc_type, exc_val, exc_tb): self.driver.close() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(&quot;-u&quot;, &quot;--username&quot;, help='Username or your email of your account', action=&quot;store&quot;, required=True) parser.add_argument(&quot;-p&quot;, &quot;--password&quot;, help='Password of your account', action=&quot;store&quot;, required=True) parser.add_argument(&quot;-f&quot;, &quot;--filename&quot;, help='Filename for storing data', action=&quot;store&quot;, required=True) parser.add_argument(&quot;-n&quot;, &quot;--name&quot;, help='Name to search', action=&quot;store&quot;, required=True) args = parser.parse_args() with InstagramPV(args.username, args.password, args.filename, args.name) as pv: pv.control() pv.login() pv.downloading_video_images() </code></pre> <h1>Simple Usage:</h1> <pre><code>myfile.py -u example@hotmail.com -p mypassword -f myfile -n stackoverjoke </code></pre> <p>Even though it was just a way to learn a bit the Selenium, the main thing it was the data scraping, but became a simple 'download posts' bot.</p> <p><a href="https://codereview.stackexchange.com/questions/238713/instagram-scraper-posts-videos-and-photos">Instagram scraper Posts (Videos and Photos)</a> is the previous related question.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T02:39:11.300", "Id": "468530", "Score": "2", "body": "https://codereview.stackexchange.com/q/238713/25834 is the previous related question. It's usually good to note this in subsequent ones." } ]
[ { "body": "<h2>Requests raising</h2>\n\n<p>This pattern:</p>\n\n<pre><code>if search.ok:\n ...\nelse:\n search.raise_for_status()\n</code></pre>\n\n<p>is redundant. Just call <code>raise_for_status()</code>, which will be a no-op if the response is OK.</p>\n\n<p><code>check_availability</code> still has a confused return. If you're returning <code>False</code>, is there ever a point where it could return <code>True</code>? If not, why return a value at all? This boils down to the same problem that you had in the first question: either you should catch the set of exceptions that you expect from a request and return either <code>True</code> or <code>False</code>; or you should do what <code>raise_for_status</code> does - no-op if successful, raise if unsuccessful.</p>\n\n<h2>Temporary variables</h2>\n\n<p>You should use one for <code>logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']</code>. Also, this pattern:</p>\n\n<pre><code>for i in range(len(things)):\n .. use things[i]\n</code></pre>\n\n<p>is counter to idiomatic Python iteration. Instead,</p>\n\n<pre><code>for thing in things:\n</code></pre>\n\n<h2>Uniqueness</h2>\n\n<p>If you don't care about the order of <code>PICTURES</code>, make it a set. That way, you don't need this <code>if</code>:</p>\n\n<pre><code> if videos not in VIDEO:\n VIDEO.append(videos)\n</code></pre>\n\n<p>The same applies to your images list.</p>\n\n<h2>Nomenclature</h2>\n\n<p><code>URL_fetcher</code> (more specifically <code>URLFetcher</code>) would have been appropriate as a class name, but it's no longer a class, it's a function. So call it <code>fetch_url</code>.</p>\n\n<h2>Cookie handling</h2>\n\n<p>Your handling of cookies is certainly better than last time, but I still think you should take this a step further and try assigning them to a session and passing the session around instead. Then, instead of <code>requests.get(url, cookies)</code>, you can simply write <code>session.get(url)</code>.</p>\n\n<p>Looking further down - you have this <code>MyHttpBase</code> with a session in it. First of all, you've made <code>s</code> effectively a class static, which you shouldn't - it should be in instance scope. That aside, I don't think <code>MyHttpBase</code> should exist at all. Have a read through <a href=\"https://2.python-requests.org/en/master/api/#api-cookies\" rel=\"nofollow noreferrer\">https://2.python-requests.org/en/master/api/#api-cookies</a></p>\n\n<h2>Exception handling</h2>\n\n<p>This:</p>\n\n<pre><code> try:\n self.driver = webdriver.Chrome()\n except WebDriverException as e:\n print(str(e))\n sys.exit(1)\n</code></pre>\n\n<p>should really not be done in the scope of a class init function. If you want to print exceptions, fine; do it at the top level in <code>main</code>.</p>\n\n<p>Also, this pattern:</p>\n\n<pre><code> try:\n self.driver.do_something()\n except WebDriverException:\n pass\n</code></pre>\n\n<p>is almost certainly not what you actually want to happen. If it's actually somewhat OK for the driver to explode, at the least you'd want to print a warning about it. But why is it OK for the driver to explode?</p>\n\n<h2>f-strings</h2>\n\n<pre><code>\"[*] extracting {links} posts , please wait...\".format(links=len(links))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f\"[*] extracting {len(links)} posts; please wait...\"\n</code></pre>\n\n<h2>Typo</h2>\n\n<p>Alredy = Already</p>\n\n<h2>Booleans</h2>\n\n<p>Replace <code>if video is True:</code> with <code>if video:</code>.</p>\n\n<h2>Static methods</h2>\n\n<p><code>content_of_url</code> shouldn't exist. Even if it did need to exist, it should be made a static method, or more likely a utility function outside of the class.</p>\n\n<h2>Random filenames</h2>\n\n<pre><code> os.path.join(self.folder, \"Image{}.jpg\").format(\n \"\".join([random.choice(string.digits) for i in range(20)])),\n</code></pre>\n\n<p>I'm sure given the information you're scraping from IG that you can do better than this. Even if you can't, at least use something like a timestamp, which is both reasonably guaranteed to be unique as well as meaningful to the user.</p>\n\n<h2>Context manager</h2>\n\n<p>You've done a good job in implementing a context manager to close your driver. However, this:</p>\n\n<pre><code> MyHttpBase().close_session()\n</code></pre>\n\n<p>is (a) done in the wrong function - it should be done in <code>__exit__</code>; and (b) should simply be manipulating a Requests session object directly.</p>\n\n<h2>Main method</h2>\n\n<p>Put the last 11-ish lines of your program into a <code>main</code> method. Currently they're in global scope.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:02:57.693", "Id": "468577", "Score": "0", "body": "I don't know how to thank you. Now, in the `check_availability` i prefer to raise an `error` if its unsuccessful. My first thought to pass around the cookies was to create a class. I don't understand very good the part \"try assigning them to a session and passing the session around instead\". You mean to replace? and second, would be better if i let the driver to \"explode\" without control the exceptions? and why? THANKS!!!!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:21:26.760", "Id": "468581", "Score": "1", "body": "_I don't know how to thank you_ - Return the favour; stay an active member in this community :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:22:34.383", "Id": "468582", "Score": "1", "body": "_I don't understand very good the part \"try assigning them to a session and passing the session around instead\"._ - Where you currently pass the cookies in as a parameter, instead pass the session itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:24:01.790", "Id": "468583", "Score": "1", "body": "_would be better if i let the driver to \"explode\" without control the exceptions?_ - That depends on a lot of things. What particular exceptions are coming out of this section of the code? If a driver call fails, shouldn't you know about it? And is the failure fatal (i.e. it indicates that we probably won't be able to process the rest of the page), or not? At the least, it should probably somehow be printed on the terminal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:57:12.877", "Id": "468586", "Score": "0", "body": "I am sorry for asking all the time. One last question. I am thinking to open a session in the `__init__` while i am passing the cookies, passing around the session and close it in `__exit__` . Is it inappropriate? I mean like \"code smell\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:22:41.833", "Id": "468595", "Score": "0", "body": "That seems reasonable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T22:04:12.060", "Id": "468611", "Score": "0", "body": "Before i post my new question , i don't understand why is \"bad way\" to indicate an error condition within a constructor. _should really not be done in the scope of a class init function_. Or i misunderstood it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T23:25:18.430", "Id": "468616", "Score": "0", "body": "_why is [it a] \"bad way\" to indicate an error condition within a constructor_ - because you don't want to make the decision of whether to print an error or not in inner code. Some callers may choose to catch and output the error; others may choose to catch the exception and wrap it; and yet others will want to let the exception fall through. It's a matter of separation of concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T01:15:37.987", "Id": "468632", "Score": "0", "body": "another one [question](https://codereview.stackexchange.com/questions/238969/web-scraping-using-selenium-multiprocessing-instagrambot) :)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T03:41:59.863", "Id": "238918", "ParentId": "238902", "Score": "4" } } ]
{ "AcceptedAnswerId": "238918", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T20:50:25.693", "Id": "238902", "Score": "3", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "instagram" ], "Title": "Scraping Instagram with selenium, extract URLs, download posts" }
238902
<p>I just coded an object-oriented Sudoku solver, but I don't have any possibility to check whether I have written good code, so I thought I would just post it here for review. I have looked for other solutions online but they mostly use different approaches so it's hard for me to compare.</p> <p>I'm just getting started and trying to learn how to write good and clean code, so any suggestions and criticism are welcome, including variable naming, documentation but also on the algorithm itself. Especially i would like to know if my approach is appropriate for such a problem and if there are Sudoku puzzles which could break my code. So far everything worked.</p> <p>The idea is basically to solve it like a human would: look at a field, check what values are permitted and fill it in if there is only one possibility. The only difference is that the fields are checked linearly instead of looking for fields which may be easy to fill in. To check for possible values I look at rows, columns, and "blocks" separately. If all fields have been checked the loop restarts and hopefully more fields can be filled in during the next iteration. I keep track of everything by storing it in attributes of two classes: a "field" class with position and value and the "board" which is "composited" of 81 fields which are automatically set up when instantiating a board.</p> <p>Here is my code:</p> <pre><code>import itertools class Field: """A sudoku field which consists of a value (default is 0 = empty), position information given by row, column and block a list of permitted values, which is to be filled later by a sudoku board method""" def __init__(self, row, column): self.value = 0 self.row = row self.column = column self.block = (row // 3) * 3 + column // 3 self.permitted_values = set([]) def __str__(self): """When printing print the value""" return str(self.value) class Board: """Sudoku board consisting of an ordered list of field objects dictionaries which link row/column/block number to the associated ordered list of field objects a filled attributed which tracks how many fields are already filled, later used for breaking the solve loop""" def __init__(self): """Sets up the sudoku board by instantiating 81 fields with default values 0 and creating the dictionaries""" self.fields = [] self.rows = {i: [] for i in range(9)} self.columns = {i: [] for i in range(9)} self.blocks = {i: [] for i in range(9)} self.filled = 0 for i, pos in enumerate(itertools.product(range(9), range(9))): self.fields.append(Field(*pos)) self.rows[pos[0]].append(self.fields[i]) self.columns[pos[1]].append(self.fields[i]) self.blocks[self.fields[i].block].append(self.fields[i]) def check_possible(self, field): """For a given field checks which values are possible and updates the associated attribute""" if field.value != 0: return 0 forbidden_values = set([]) units = [self.rows[field.row], self.columns[field.column], self.blocks[field.block]] for unit in units: for unit_element in unit: forbidden_values.add(unit_element.value) field.permitted_values = set([i + 1 for i in range(9)]) - forbidden_values def load_game(self, fields): """Loads a game which is given in as a list with 81 elements""" for i, j in enumerate(fields): self.fields[i].value = j if j != 0: self.filled += 1 def export_game(self): """Returns the current board setup as a list with 81 elements""" return [self.fields[i].value for i in range(81)] def print_board(self): for i in range(9): print(*self.rows[i]) def solve(self): """While not everything is filled in, loops over fields linearly an fills in the solution when one is found If solved print out the solution""" while self.filled &lt; 81: for field in self.fields: self.check_possible(field) if len(field.permitted_values) == 1: field.value = list(field.permitted_values)[0] self.filled += 1 print("Board solved!") self.print_board() def test_field(self, field_number): """Print out all information about a field by field number in .fields""" print("Printing field {} information".format(field_number)) self.fields[field_number].info() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T02:16:34.933", "Id": "468528", "Score": "1", "body": "There are many Sudoku boards that cannot be solved using this algorithm. For example, see [the dailysudoku](http://dailysudoku.com/sudoku/play.shtml?year=2020&month=03&day=13) for March 13, 2020. It eventually reaches a point where each field has more than 1 permitted value." } ]
[ { "body": "<h2>Use type hints for parameters and members</h2>\n\n<pre><code>def __init__(self, row, column):\n self.value = 0\n self.row = row\n self.column = column\n self.block = (row // 3) * 3 + column // 3\n self.permitted_values = set([])\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def __init__(self, row: int, column: int):\n self.value: int = 0\n self.row = row\n self.column = column\n self.block: int = (row // 3) * 3 + column // 3\n self.permitted_values: Set[int] = set()\n</code></pre>\n\n<h2>Data structures</h2>\n\n<p>These:</p>\n\n<pre><code> self.rows = {i: [] for i in range(9)}\n self.columns = {i: [] for i in range(9)}\n self.blocks = {i: [] for i in range(9)}\n</code></pre>\n\n<p>aren't a particularly useful representation of index-to-list. The index is contiguous, integral and zero-based, so you can simply represent them as a list rather than a dictionary; <code>i</code> can index into the list. Similarly,</p>\n\n<pre><code>[self.fields[i].value for i in range(81)]\n</code></pre>\n\n<p>would probably become</p>\n\n<pre><code>[f.value for f in self.fields]\n</code></pre>\n\n<h2>Range</h2>\n\n<pre><code>set([i + 1 for i in range(9)])\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>set(range(1, 10))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T13:31:46.007", "Id": "238941", "ParentId": "238908", "Score": "2" } } ]
{ "AcceptedAnswerId": "238941", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T21:47:53.457", "Id": "238908", "Score": "3", "Tags": [ "python", "algorithm", "object-oriented", "sudoku" ], "Title": "Python sudoku solver with classes" }
238908
<p>I have an array of objects, each with a <code>dimensions</code> field for storing various metrics related to the object, e.g. length, width, weight, etc. Each object may be different in terms of what metrics it has.</p> <p>I have a solution but not sure if it's optimal.</p> <pre><code>let dimensions = [{ a: 1, b: 2, c: 3}, { a: 2, c: 1, d: 3 }, { b: 1, e: 8, f: 1 }] // get all keys let dimensionsFields = _.map(dimensions, Object.keys); // =&gt; [[a, b, c], [a, c, d], [b, e, f]] // flatten dimensionsFields = _.flatten(dimensionsFields ); // =&gt; [a, b, c, a, c, d, b, e, f] // filter out duplicates dimensionsFields = _.uniq(dimensionsFields ); // =&gt; [a, b, c, d, e, f] // init return data let dimensionsData = {}; // loop through available metrics, add up the values dimensionsFields.forEach(field =&gt; { dimensionsData[field] = _.reduce(dimensions, function(a, b) { return a + b[field]; }, 0); }); // =&gt; { a: 3, b: 3, c: 4, d: 3, e: 8, f: 1 } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T22:34:04.480", "Id": "468519", "Score": "1", "body": "As written your code doesn't run, I imagine _ is lodash, but metrics isn't defined (I guess it should be dimensions), but then this still doesn't work for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T22:37:20.690", "Id": "468520", "Score": "0", "body": "sorry, i changed some var names and missed that one. fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T22:43:59.283", "Id": "468521", "Score": "1", "body": "It still doesn't work for me, I get that every key has value NaN, which isn't too surprising since for instance we do a + b[\"d\"] but d might not be a property of b." } ]
[ { "body": "<p>What do you mean optimal?</p>\n\n<p>Your thing transforms the object lots of times, which is liable to not be very efficient, if that's what you meant.</p>\n\n<p>Here's something that I hope is simple to read that does your task.</p>\n\n<pre><code>function sumObjects(obj1, obj2) {\n return Object.keys(obj2).reduce(\n (acc, currKey) =&gt; ({\n ...acc,\n [currKey]: acc[currKey] ? acc[currKey] + obj2[currKey] : obj2[currKey]\n }),\n obj1\n );\n}\n\nconst result = dimensions.reduce(sumObjects);\n</code></pre>\n\n<p>The observation is that you just need to see how to do your task for two objects and the rest is just a reduce.</p>\n\n<p>The most efficient thing will likely be just a for loop, like </p>\n\n<pre><code>const res = {};\nfor (const obj of dimensions) {\n for (const key in obj) {\n res[key] = res[key] ? res[key] + obj[key] : obj[key];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T23:02:59.377", "Id": "468522", "Score": "0", "body": "i was definitely overthinking this problem. thanks for the help!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T22:19:25.313", "Id": "238910", "ParentId": "238909", "Score": "2" } } ]
{ "AcceptedAnswerId": "238910", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T21:47:55.423", "Id": "238909", "Score": "1", "Tags": [ "javascript", "array" ], "Title": "Sum array of objects by unique keys" }
238909
<p>Specifically the if/else statements trying to match model and brand. The code works, but it's ugly. Any suggestions to clean it up?</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Cell_Phone_Test { class CellPhone { // Fields private string _brand; // Phone brand private string _model; // Phone model private decimal _price; // Phone price // Constructor public CellPhone() { _brand = ""; _model = ""; _price = 0m; } // Brand property public string Brand { get { return _brand; } set { _brand = value; } } // Model property public string Model { get { return _model; } set { _model = value; } } // Price property public decimal Price { get { return _price; } set { _price = value; } } } public partial class cellPhoneForm : Form { public cellPhoneForm() { InitializeComponent(); } // The GetPhoneData method accepts a CellPhone object as an argument. It assigns the data entered by the user to the object's properties. private void GetPhoneData(CellPhone phone) { // Temporary variable to hold the price. decimal price; // Get the phone's brand. Check that it is a valid brand. if ((brandTextBox.Text.Contains("Google")) || (brandTextBox.Text.Contains("iPhone")) || (brandTextBox.Text.Contains("Samsung"))) { phone.Brand = brandTextBox.Text; } else { MessageBox.Show("Please enter a valid brand. (Google, iPhone, or Samsung)"); } // Get the phone's model. Check that it is a valid model and matches brand. if ((modelTextBox.Text.Contains("Galaxy")) || (modelTextBox.Text.Contains("Note")) || (modelTextBox.Text.Contains("8")) || (modelTextBox.Text.Contains("X")) || (modelTextBox.Text.Contains("Pixel"))) { if ((modelTextBox.Text.Contains("Galaxy")) || (modelTextBox.Text.Contains("Note")) == (brandTextBox.Text.Contains("Samsung"))) // { phone.Model = modelTextBox.Text; if ((modelTextBox.Text.Contains("Pixel")) == (brandTextBox.Text.Contains("Google"))) { phone.Model = modelTextBox.Text; if ((modelTextBox.Text.Contains("8")) || (modelTextBox.Text.Contains("x")) == (brandTextBox.Text.Contains("iPhone"))) { phone.Model = modelTextBox.Text; } else { MessageBox.Show("Please enter an iPhone model. (8 or X)"); } } else { MessageBox.Show("Please enter a Google model. (Pixel)"); } } else { MessageBox.Show("Please enter a Samsung model. (Galaxy or Note)"); } } else { MessageBox.Show("Please enter a valid model. (Galaxy, Note, 8, X, Pixel)"); } // Get the phone's price. Check if it is within the range. if (decimal.TryParse(priceTextBox.Text, out price)) { if (price &gt;= 0.01m &amp; price &lt;= 2000.00m) { phone.Price = price; } else { MessageBox.Show("Please enter a price between $0.01 and $2000.00."); } } else { // Display an error message. MessageBox.Show("Invalid price"); } } private void createObjectButton_Click(object sender, EventArgs e) { try { // Creat a CellPhone object. CellPhone myPhone = new CellPhone(); // Get the phone data. GetPhoneData(myPhone); // Display the phone data. brandLabel.Text = myPhone.Brand; modelLabel.Text = myPhone.Model; priceLabel.Text = myPhone.Price.ToString("c"); } catch { // Display an error message. MessageBox.Show("Invalid data was entered."); } } private void exitButton_Click(object sender, EventArgs e) { // Close the form. this.Close(); } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>too many false arguments, for instance </p>\n\n<pre><code>if ((modelTextBox.Text.Contains(\"Pixel\")) == (brandTextBox.Text.Contains(\"Google\")))\n{\n phone.Model = modelTextBox.Text;\n\n if ((modelTextBox.Text.Contains(\"8\")) || (modelTextBox.Text.Contains(\"x\")) == (brandTextBox.Text.Contains(\"iPhone\")))\n {\n phone.Model = modelTextBox.Text;\n }\n else\n {\n MessageBox.Show(\"Please enter an iPhone model. (8 or X)\");\n }\n}\nelse\n{\n MessageBox.Show(\"Please enter a Google model. (Pixel)\");\n}\n</code></pre>\n\n<p>if is it contains Pixel and Google, then how it could be possible to contain iPhone ?</p>\n\n<p>your logic needs to be refactored and tested. The easiest way to refactor it is to invert the ifs. If you give a good look at the ifs, you'll find that <code>phone.Model</code> is assigned multiple times with <code>modelTextBox.Text</code>, which is redundant. it needs to be assigned once. So what you can do is to extract the validations and invert them to be outside and the compile would go throw them top to bottom, and if passed all, the bottom line would assign whatever value to <code>phone.Model</code> example : </p>\n\n<pre><code>// Get the phone's brand. Check that it is a valid brand.\nif(!((brandTextBox.Text.Contains(\"Google\")) || (brandTextBox.Text.Contains(\"iPhone\")) || (brandTextBox.Text.Contains(\"Samsung\"))))\n{\n MessageBox.Show(\"Please enter a valid brand. (Google, iPhone, or Samsung)\");\n}\n\nphone.Brand = brandTextBox.Text;\n\n// Get the phone's model. Check that it is a valid model and matches brand.\nif (!((modelTextBox.Text.Contains(\"Galaxy\")) || (modelTextBox.Text.Contains(\"Note\")) || (modelTextBox.Text.Contains(\"8\")) || (modelTextBox.Text.Contains(\"X\")) || (modelTextBox.Text.Contains(\"Pixel\"))))\n{\n MessageBox.Show(\"Please enter a valid model. (Galaxy, Note, 8, X, Pixel)\");\n}\n\nif (!((modelTextBox.Text.Contains(\"Galaxy\")) || (modelTextBox.Text.Contains(\"Note\")) == (brandTextBox.Text.Contains(\"Samsung\"))))\n{\n MessageBox.Show(\"Please enter a Samsung model. (Galaxy or Note)\");\n}\n\nif (!((modelTextBox.Text.Contains(\"Pixel\")) == (brandTextBox.Text.Contains(\"Google\"))))\n{\n MessageBox.Show(\"Please enter a Google model. (Pixel)\");\n}\n\nif (!((modelTextBox.Text.Contains(\"8\")) || (modelTextBox.Text.Contains(\"x\")) == (brandTextBox.Text.Contains(\"iPhone\"))))\n{\n MessageBox.Show(\"Please enter an iPhone model. (8 or X)\");\n}\n\nphone.Model = modelTextBox.Text;\n</code></pre>\n\n<p>The real refactoring you need to do is to move the validations into separate methods, and keep the validations based on the brand. So, you now have three brands <code>Google, iPhone, or Samsung</code> it would be much cleaner if you implement three methods <code>ValidateSuamsung(string model)</code> and <code>ValidateGoogle(string model)</code> and <code>ValidateGoogle(string model)</code> then you can implement each validation inside its method, and then use a simple validation on the brand and execute its method like this : </p>\n\n<pre><code>// The GetPhoneData method accepts a CellPhone object as an argument. It assigns the data entered by the user to the object's properties.\n\n private void GetPhoneData(CellPhone phone)\n {\n switch(brandTextBox.Text)\n {\n case \"Google\":\n ValidateGoogle(modelTextBox.Text);\n break;\n case \"Samsung\":\n ValidateSamsung(modelTextBox.Text);\n break;\n case \"iPhone\":\n ValidateiPhone(modelTextBox.Text);\n break;\n default: \n MessageBox.Show(\"Please enter a valid brand. (Google, iPhone, or Samsung)\");\n break; \n }\n\n phone.Brand = brandTextBox.Text;\n }\n</code></pre>\n\n<p>Also, since you have multiple <code>Contains</code>, you could do something like : </p>\n\n<pre><code>// Get the phone's model. Check that it is a valid model and matches brand.\n\nvar model = new string[] { \"Galaxy\", \"Note\", \"8\", \"X\", \"Pixel\" };\n\nif(!model.Contains(modelTextBox.Text))\n{\n MessageBox.Show(\"Please enter a valid model. (Galaxy, Note, 8, X, Pixel)\");\n}\n</code></pre>\n\n<p>if you move the validations based on the brand like I suggested, I beleive that you'll make a simpler validation and shorter as well, as you'll validate based on brand, which will make things more specific and straight forward. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T04:33:44.927", "Id": "238921", "ParentId": "238914", "Score": "1" } }, { "body": "<p>A few things to consider:</p>\n\n<p>Since you're not doing anything special with the getters and setters of your properties, I would suggest using the simple version(<code>string Brand { get; set; }</code>).</p>\n\n<p>To simplify your validation, I would suggest a class that holds a collection of CellPhone's. Leveraging the underlying collection would allow you to fill a combobox with choices. Choose the brand, then fill the next combobox with the appropriate models. Since the choices come from the collection they're automatically correct. </p>\n\n<p>If you make the underlying collection a <code>Dictionary&lt;string,Dictionary&lt;string,CellPhone&gt;&gt;</code> You can get near constant time lookups to search for a particular brand and model.</p>\n\n<p>Such a class could look like this:</p>\n\n<pre><code>private class CellPhones\n{\n public class CellPhone\n {\n public string Brand { get; set; }\n public string Model { get; set; }\n public decimal Price { get; set; }\n\n public CellPhone() { }\n public CellPhone(string brand, string model, decimal price)\n {\n Brand = brand;\n Model = model;\n Price = price;\n }\n\n }\n Dictionary&lt;string,Dictionary&lt;string,CellPhone&gt;&gt; phones { get; set; }\n public CellPhones()\n {\n phones = new Dictionary&lt;string, Dictionary&lt;string, CellPhone&gt;&gt;();\n }\n public void AddUpdatePhone(string brand, string model, decimal price)\n {\n CellPhone newPhone = new CellPhone(brand, model, price);\n if(!phones.ContainsKey(brand))\n {\n phones.Add(brand, new Dictionary&lt;string, CellPhone&gt;());\n }\n if(!phones[brand].ContainsKey(model))\n {\n phones[brand].Add(model, newPhone);\n return;\n }\n if(phones[brand][model].Price != price)\n {\n phones[brand][model].Price = price;\n }\n }\n public List&lt;string&gt; GetBrands()\n {\n return phones.Keys.ToList();\n }\n public List&lt;string&gt; GetModels(string brand)\n {\n return phones[brand].Keys.ToList();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T05:22:37.867", "Id": "238925", "ParentId": "238914", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T01:54:24.313", "Id": "238914", "Score": "3", "Tags": [ "c#", "winforms" ], "Title": "Entering specific models, brands, and prices into system" }
238914
<p>Problem my code solves:</p> <p>Lack of lightweight <strong>numeric</strong> range classes which can tell if arbitrary values lie inside them, supporting more than just simple exclusive max modes and integers, and that <em>support iteration with configurable stepsizes</em>. </p> <p>What I think My code does:</p> <ul> <li>Provides a lightwieght class encapsulating a numeric range</li> <li>Iteration Should be valid for <em>any</em> &lt;= 64bit numeric type, at the very least <ul> <li><code>std::uint8_t</code>, <code>std::uint16_t</code>, <code>std::uint32_t</code>, <code>std::uint64_t</code></li> <li><code>std::int8_t</code>, <code>std::int16_t</code>, <code>std::int32_t</code>, <code>std::int64_t</code></li> <li><code>half</code>, <code>float</code>, <code>double</code>. </li> </ul></li> <li>Should be valid with out iteration otherwise. </li> <li>Guaranteed iteration starts and ends</li> <li>Proper exclusive, inclusive, exclusive max, exclusive min check for values (shown in top quarter of code). </li> <li>Iterators that start and end at exclusive, inclusive, exclusive max and exclusive min (bottom part of code) with configurable step size. </li> <li>Reverse iteration with configurable step size. </li> </ul> <p>Concerns with my code:</p> <ul> <li>I'm not really sure how I handled the iterators was "correct" even though it works, I'm not exactly sure how I'm supposed to handle iterators that aren't reference/pointer types underneath. </li> <li>Are there any important facilities I've missed that should be in such a class (not necisarily how to implement them)</li> <li>Are there any C++ features I'm not using correctly/idiomatically or are missing?</li> <li>Architectural problems?</li> <li>Problematic API choices?</li> <li>Code clarity from both user perspective and developer perspective. </li> <li>Any other issues</li> </ul> <p>Here is the code</p> <p>(<a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEAGYA7KS3oAMnlqYAcsYBGmYiEmkADqgWE6rR6hibmVn4BanT2ji5G7p7eSirRtAwEzMQEIcamlorKmKpBGVkEsc5uHl6Kmdm5YQUK9RUOVQk1kgCUiqgGxMgcAOTiAAwAggD0U1JmDsiGWADUUpK0xh54yAD6xCLAmApTaLRUeMAAdAhr4xNzC0uYq2Y6LApK2eJm2HcPtIsDCtvjoCABPHyYHYEfaEBTfX6Tf6A4GvQgeZhEYgIv6TWjMIxHHzMIbLFoAD1WFlkSMmy3pywImCMPmETJB4Mh%2BMJywAKji6QzFswPssNoTiNs9gdnuJqXcGcsfAZXKxtiAFYqGeKtrt9qJMBBTi0%2BatJAA2IwOUjLY0EU1SS3McndZYgZZGHZW2gQb29D1e52%2B52uuU0iZayPLEWfAi%2Br0OF46b4AEQDRhD33DUapKdxEajOsleplRroJt5ZqdLrd6YcYblKZtnoz5ODNYbgpz9JjHjjLcTINT6czZmzUcb%2BZzle9EFddqp4%2B7y2ImAIA1oddoWc1kcntILkZnQfn5ftncP3dX6%2BIm5bzp3Xa1%2B8vit3WsrAQAXobT7QTRey70teG4jpSAC0W6Pq%2BDIvu%2BipFlK%2BqHFWSgEIGbYLpWjoAG5sAYmChvKT45r22QQHhhiyj8w4DrQ3TQUBYEvGmlEEYxQEgbeywAFQEAgeDwmO8GwRYeYHjmiElgaqFrgmPpYVWbGEYuImRmRcbKUmtEYQxwkkVGdEscsykccuXGbnxAlCUuz5iVOUYzI8BgBDhzynJkDgKB6iYiOgHoPgZ9KuKg%2Bi2nQnn/jszmuYaWGOiZ%2BEqXagGcWuoHxt62lmKxSWhhaCUUUl2VpveLpmXu9lBfSanLDMmDkoCsXLA1KJHMsIX8T5m5%2BQFlK1SFYUecwXk7K1hixWW/72vyFqJVRf4tKl5npdxmWDq880Efl5qFVpIJgXptlvlV9zVfVjVPH1yzOVg3lZa4Bj2uNQLta2A2haw4X0CNUUvVgGFTRWCXKYtBDLVeq2butm5DjlW0qY6e3FQdZVHbVcHnVM/3PFlt1vc6HVPS1l2vfd9bVYNX3DaNOPyUDM0g3l31LcRMGRhZyww0mCM7cjVElYdFUneJZ3s3V2Ok3dfUfUNEW/QoDMOhaoMs%2BebNMZzNN/VLUKtkVC3C6Jou1cKorovsWKqdVyqquqtWKhbmIkBALToCAIDflC9otJgPjRdoDU2m7Hte9CZJMv7rakA7TGKY63o2vHFqtq6GrVUxnq%2B/7DhYG22cB3n/pZ5HgMF6nMcZ0BdG%2Bg4xeA6n1vi6RHx9q7pe5w1gvlw%2BMicOjVeRngVBqw1PjEFzIcgIJAdMsA%2BysDsOEgvyPxEcdTEMjMADuzyOJg/lEAFADWzwKAMzzD8su/RquyzoKgDjADd9ARwYVBULHy47%2B5IhgMM9oEDMDckqcoeA2ARz9goG0rBUDAG2MsQ4BBvJALwMQMElwv7dg0lAMqyxIJ0XygAVkgVHQmqZhxjAHs3Ccp0mKYxofSJ2VtHSoEhJbEgcg5BzibpvBkJc/aFy7lw%2BGnAjYrRvJZfiglxF2RNoPG6TIOETzYRiLEXCZAQAcAQdeWDHZKOdhPa8lFjJWRkfpRhz4ZDcLMQoahfDgJQxXGuSisiRYOWXFTZYqjlEUJylogxVtUD8Q8GDXhDjOYCJzoHfqOVhzBIQB4S4UShHkj0cuJGc0UmthYvEkJxBkk7B7mkhRQFMnmi3Lk%2BGCSkl0XSd2cpzE/FphqQUsqbjjYeO7F4nxhiwBgFTAEtRJBvH5LCRDTWTj%2BkQFsVUlpYyOk1VOlgysvSsQ8R4SlDWDiZg0AntozAhxiDQOviQY%2B3l2FUGKAQVgGDlh7PubAzEJywT9FtH/ABiC1xKg8Fc1QRNwalK3lMYAzABgiCZO1beiTNzZxfnnG63kxj1Ilpc65pCfBP3uSMg5Rz4RAqYSPO0Y8J7t3dtPBQs9DkLyXivBEuiCVakifJM0G8HGRlwRhfBW5XRTADMU10PF%2BUdxiYsuRLVWBKHCey%2BkMxHmoExFivw2ixSYAPt5I%2B7hlhAO0Owfy%2BAP4eC0DcsEjJUAosVHK4ABgsgQrVYyIBPtWjeV6jYF1d8xjRm0MsTgmDGWWr5bQVApziDoO8SPDwxARlUCjUYFcMpozoHwGkC1DJOacuKdylJncayzH9UBFoirdjvHBq8Ve2B4wCsFZUrh%2BbuyVpFQivlha1DFpFKWnQ5aG2CNTtW9pFj2UvnoXQoCcrmEjJhCNZBWCXJYoNVc1cAJvYQmommVebKtSztEAjaEK7jLrpnQEbdyr6AeGMlPMOpaN2Ki3c/VcC6tCkmHNhAqA6gK3sUcM4gOwWBzxIKa4cU89nbyyOgaKgSSDQmYMAWR488B4SZOnSxF68A/nDtm0Vb7lwobQ/abJD4sPdhnPJMVxH3qEfcRY02whRSrjcscqE46J4TIZLbNUyAkOTPo0ocDX6yWh1Q97UhqTg4EHJZe4T0dU1CjPMrS01o1ZycbpxmV9IMN53boInN9dimabIS6Sulicw1z9M2BuIZpWbxwQXHN3dS7vT7vYhxV9iXknHpPMTHsZ64ppcvMt9LLPsp/qqg%2BZqT5nwvjdEeN8sjPAflilVLR36fzrRLG%2BLBaD/0AcA54xJsjgK%2BtnE5sD4HIC%2Bcg7VI10F%2BqM1GHBmVCYEPksQyT5C4nwyoWK9xCiGFcY8DxpjVY1mcOsZohltW1NFMbcI6xoiutpqcbYsVvW0rccYxBlR7DDEaOkFo%2Bg432V0f6%2Btr9ziCAmOHEtijZTRu7dsU5vhnNjFsGW8shRPStvqPaymCAR2GO8eUaMxJxBxnbMe049TwjvtA9qVNrTorUuwQKlkuH%2Bm5kw7aajjC0m3zI4qUZZpGPCnehx0j3aKOcmE9acTgj17OkSSAh9r9/TBl/YGxtjHoO6ccymZAWZVOFnXcqvIyxqzPskA2WDFj38pgPNxf1m028zkXN%2Bdc25lxsUTyoE85BNpXkGHeZlz5SCfnED%2BfaR6gKJsS1BeC09UKYWkPhV3QSyxkWMpmGi/52dMXbrl6evFKKXNnhJR58l3mA%2B%2BbpWvQLOypiOFBWkMkCB%2BisHQEbq3qnHGSOYuBUnHKGsQR5XVYVPaLNCu7dEou82llpmUFK6Xm85Xa4VWoY9j9X773QBq4NWqdXoD1ffYeD76C3LNTjq1Nr9SQodZiCO5QXXerdbfZ4nreq%2Bon4G4NSvQ2mtQBG0N0bY3xpkswJNgQ6A4/TZXrlTWbMxN5fnyMLapQlujxW/DLo%2B1ctrdboCN/bNm1MhW0f12138b9e1eIoIhcGkR0Mk4Duwx0OdJ04RD051h8jUl1d1IR90xUP1lJsDV0%2BQ8Cj1n4T0lFz1PNPZBNoQSCsV71MCn14YX1doYCb1SDP1lFQC/0w1AMqDgNQMAdDEoMYMYC4MEMOAsEcMhNIc0k2CGRpD0MsdyNudTQ6l5D6QyNacMZ7IqNqomQWQ2RMAQQzZvJeQABJDbAUcWUwkmNqMabQIQrEaUGSRvNje2BROmGwJwyDZCQ0RQp1MvckJOWTFgxORTMIzMVLd0T/PTXSMzWcUzMCdscbLBIdICCwjndweBH0boLZVQxUTmTIvjMYMzYpBIhTNGV7UWJiYowHGwOcfIlFIoywvjT/Mo%2BzZ0Co2gBI0cVQlbSMcQzESQhRAI0vfTUjaA1QrQuQjdScPQ8WAw1kYYkwmjMw1o3xGiaqWwumbIhwHw79Pw2PekdwjjLBXYw5fYpjFww4fjag3DVrYIiIqscI5OasBiBRGI5QoMAVbo2ueiXotsRuC8NIhA6cDYwxDqS43IpoxlFojbCATgDooI7owEh7WAmojIiEq2BovIs8RvHMeEto74tJPuZE/TVEoWDQ3MWqIYxDKQqgiTT/SY9Q6YsCWReY8MWqJYow1YmMPkbEzhLYmwtYl%2BJqeDE7Lgo4twlUdjFTZcGKCUg4m4/wxkmgwIik54hOBTN41OLBL43TX4rcf4%2BufWYEtmUEzE5cOoyEvY3ItWAkqMIk5RCAUo8YjCSkqo6k9I60wUieXEh0sHTeZ0wxCA3uaQJE906OLcNE6o2kyUCQ%2BU7sMY5k6ksjesNM9kmAzkrpRUHklY14Wwm0r7REEU/kl6WKZU6UoMxUU4pMnMCspU64vwu4iTcorUlOHU0Il4qIyxA0zo/OAc00hwE0wElIpuS0lZP0qEnIxo/EmstKHPYsl2SM9omMqk/osEqMZc/07QOc6aR0nnJcv0sMp4tcuiWM70rck4hM4Y%2BsqMFMkklkkjTM/tOY3Qrk6qLwxw5smUEEJjBETXEDYgMDOmfWeKOaAuL2BiBc5/NUh4zNQDQTOcKYKCwTMVTmb8sDX8g0f8qwn4OI6Mi8jcnQkXBs3WHYO0qsv8tEfC7AICwQsCkciCipNCn8GC1QsYxC%2BGL2FCti4w6kzCiiqinCw4PCr9BEQiro9cr098siqMRstyai3C2iiSn4BikCsaUmSaFi4TaCw8iOcTdUx489ZC7oVC0uL2DCpxRSyU4Qvw8SzYitds4i2S0i3MhkRUpS0SgSnQAC9SgQzSryuKUIhKfijihkoyhCgc0yn8Piyy9CwSpxYK5SsS1SpyqSs8%2BSS8uSjy2VVCkDHwF%2BJRfESVKElgFyZ4NnS%2BDnCqpQcmHqb1HJI%2BBQQq2qZvY/dwLFO0r1fyGwZxBQSEEoNyMfI%2Bfq3qO02qC4nI1K3y6qg4wC%2BasCoMXS8KgyrimKpCuK8y/i6ynPaaq4jbFUkEea/y5ygcz03SDkt7cWLC2ak6zANbBa9Spaii2cVahK9i9a%2BCoTbitMXinaz6gS1QoS%2Bw7wnyh6p6s6zKy6vU7Mm68i8U7yo6hy14U6ui5xJ62ypWWaVioGiK0Yn68OP6skMyiywRKypK/a7SpslGminQdGtS86lEmSq6%2BG%2BSoeAECaWmr9Y6tGx647Z6%2Bi06rm2dNyHGsK/G76qK36zanism3aqm0CFKiG/mqGuimG1muG3Kg8dqqYCyF1DS/yQbfiOfHGDVRJFqb1ffB1KqhNFI2qQbO0/c1mVQu61WvyjGny9uItUApaV4AIySgG4cnokihRTmHyy4Z29E7rcWPWg26MI2zgyE0256XWC254fqm2kJE/FCB26qQbXE2Eyxd2umlSz2pm5O5wlsl/Ntf2nQQOgi4O2GvorBCOsuw4S4XE66jmrUGYBO5gTG47KuidR1Owp4DOq2/ybOy2o4k02qRmwHYgaO4upiUu3m1GhmgW/7M6kew40sWuv2jtRu5ysykOnKtu5KjuzAKO6EucHuvKiWAeoehjPe2fNOtqSerOkeHOuev0Be7e9nU7RddAF28GWCrUdeqU%2Bmxe7bdS72w%2Bt/AOom0tU%2B7a8%2BsOyxdujemULuvcmO%2BnMWWs28%2Bk6qdM7cGAmYiqHMhnekfM9kV4TkLQAkZ4ctd8Kmd8YbbEb7JWKSPmztQCx0VgBAE5BcPhze8tKsYgERg7J0pxYRhQZJEc0MaHaRxR2cPmOaBR5JE8dHNRnRtsdEgYxkZkZYhh0EFdbkVh6wxUDhp8LhlnfxMRzYYsfhyRoRkRkI6aMUFxpCem9xi0NR2Ro80CaZBRvRmR6h5ZG65EK6f8/wGETAAkawu4FVDMZRiGCkD2cR%2BmlvTEQCmNUsMYS4N0zgYpzrQjLJkAHJ8u7RQCtBIpm0Mp6hd8KeNAYmOGHQM0SQQpmSbWbyIhS4bgMwIhd0NYbKLp%2B5Pwy4fpiAQZ4ZohFR5MTaW4IhHQbcSQSQCqNp/oc8V4A6NYXplCB%2BdqINe0bWcesW1fEpsZzZiZ%2BkfpI5m%2B/prSpGw0cppZg5zZ8QNZjZrZypqg9pvZ5ZrptYBpvp%2BWLyZYUZ7p%2B5qZ3B2ZxZ%2B51Z9Z24AF8lIF5FzZ8F451AU54Jb6SKS55qMp25yQOFx56Zl57G5prFrZ35tFz8y8HZjp/ZlZzZp5qujgbpiqPZCAMFI%2BPAWsJ5gm8WFl4Fg6IVzp7pmOb5wjH0wyj2TF6VlFv57ZwF3ZulnFmqtRblxl98PlgV4NIV90bV0VnMcV%2B5qVtl0FzZ2V/52yBVy1lV75hluVplxUZ1m17pzl4pkhZhPV91g1l2I1m6YV6ZwK0Ct6oMP17oc1h8jV1lkFsNl17wfVp8J1xNiV9l%2Bl1FoNp8L15NsFo48lgNsl3lkNp6Y12sbVy4SN15p4QGHoeNuCjFzV6V61otu19Ny8TNttpNr53NtVhYwopxZFKjU6YYXoVgEAYYIhYYUgUwYYMYBd1AWd5MW7MkfoQYWUSQMwTgBdggWdlduN0gY%2BcwAADkuEkAsAsDGAWfNDMDMAvYsE4AsF4BneGG4AXaXZXdIDXeGAXYUBAFKKPeXandIDgFgBgEQBQFQBZDwHYDIAoDLAQ6Q5QGEFEGhGIAMFoGPlIHOFYCUWA4gFcGPYXdcAcCyDBFnYPdIDQCMEJHoAAHlaBblyPSAsAMxRB2AOP8BVxhqjgOOGpignoRg/2DlP2/21RXB9h0E9AsBaPD3JQjAlPegaB6AmA2AOAeB%2BBBBMOxAdshA8BXBgPIBeg2E0hgPhhwI3ZUwJBbtJBB7wJmPJAgOigSgNAIAbBGhTAkSbBKh4hEhBBIgL9gh9A8gQv/AwvAvqhPAkSUhrlShWhfPBBEvPP0hWhYvOh4u6hyhUuEusv2gguah%2B4%2BgBghguBp3Z353F2OOAPyQL3zRwJzRuBbQDOuYYRcPj5XQIBcBCARk5hIy9A0Oz0hvXQN3ZAZBD3yPT3z2iFSjP3v3SBVOFu6vwP/3Z2gOQPSAwOT3IOYOIAkBdnlQCByBKAGPMV0P/Pk0SBBANPGAWBePdPt59gfA1OhAauf36vZ2hvr5CAEBlhGvmvWv2uDhOucO8PugZvwPT3Ekz8ag5xPuv2F3VvSjf3V2tvFAdu9up3ehz3zRfULBNmABOIhVrswc0QnyQC9swZHswb7jbgDmHk96r4YNz9bv95n3b2b3objIIEAbgIAA%3D" rel="nofollow noreferrer">godbolt link as well</a>)</p> <p>numeric_range.h</p> <pre><code>#pragma once #include &lt;cassert&gt; #include &lt;type_traits&gt; #include &lt;iterator&gt; namespace stx { template&lt;typename T&gt; class numeric_range { public: numeric_range(const T &amp;min, const T &amp;max) : m_min(min), m_max(max) { assert(m_min &lt;= m_max); } numeric_range(const T &amp;max) : m_min{}, m_max(max) { assert(m_min &lt;= m_max); } T min() const { return m_min; } T max() const { return m_max; } T size() const { return m_max - m_min; } numeric_range &amp;set_max(const T &amp;value) { assert(value &gt;= m_min); m_max = value; return *this; } numeric_range &amp;set_min(const T &amp;value) { assert(value &lt;= m_max); m_min = value; return *this; } //inclusive contains min and max bool contains_inclusive(const T&amp; value) const{ return (m_min &lt;= value) &amp;&amp; (value &lt;= m_max); } //exclusive excludes both min and max bool contains_exclusive(const T&amp; value) const{ return (m_min &lt; value) &amp;&amp; (value &lt; m_max); } //exclude max includes min but excludes max bool contains_exclude_max(const T&amp; value) const{ return (m_min &lt;= value) &amp;&amp; (value &lt; m_max); } //exclude min includes max but excludes min bool contains_exclude_min(const T&amp; value) const{ return (m_min &lt; value) &amp;&amp; (value &lt;= m_max); } //excludes max bool contains(const T &amp;value) const { return contains_exclude_max(value); } class iterator { public: iterator(std::size_t step_index, std::size_t step_max, const T &amp;min, const T &amp;max) : m_step_index(step_index), m_step_max(step_max), m_min(min), m_max(max) { assert(step_index &lt;= step_max+1); if constexpr (std::is_integral_v&lt;T&gt;) { //we need to make sure if we are doing int stuff //we can't have partial steps, logic gets hairy. assert((m_max - m_min) % step_max == 0); } } iterator &amp;operator++() { m_step_index += 1; return *this; } iterator operator++(int) { iterator retval = *this; ++(*this); return retval; } bool operator==(iterator other) const { return m_step_index == other.m_step_index &amp;&amp; m_step_max == other.m_step_max &amp;&amp; m_min == other.m_min &amp;&amp; m_max == other.m_max; } bool operator!=(iterator other) const { return !(*this == other); } T operator*() const{ //for integers, works perfectly. for floats, you can't get perfect but //gaurantees when step index is 0 //perfect stepping for integers if constexpr (std::is_integral_v&lt;T&gt;) { return m_min + ((m_max - m_min) / m_step_max) * m_step_index; } else { // floating point needs to be handled differently to // guarantee that starts and ends are 0 and 1. // no worry of error from range addition return ((m_step_max - m_step_index) / static_cast&lt;T&gt;(m_step_max)) * m_min + (m_step_index / static_cast&lt;T&gt;(m_step_max)) * m_max; } } // iterator traits using difference_type = T; using value_type = T; using pointer = std::size_t; using reference = T &amp;; using iterator_category = std::forward_iterator_tag; private: std::size_t m_step_index; std::size_t m_step_max; T m_min; T m_max; }; class reverse_iterator { public: reverse_iterator(std::size_t step_index, std::size_t step_max, const T &amp;min, const T &amp;max) : m_step_index(step_index), m_step_max(step_max), m_min(min), m_max(max) { assert(step_index &lt;= step_max+1); if constexpr (std::is_integral_v&lt;T&gt;) { //we need to make sure if we are doing int stuff //we can't have partial steps, logic gets hairy. assert((m_max - m_min) % step_max == 0); } } reverse_iterator &amp;operator++() { m_step_index += 1; return *this; } reverse_iterator operator++(int) { reverse_iterator retval = *this; ++(*this); return retval; } bool operator==(reverse_iterator other) const { return m_step_index == other.m_step_index &amp;&amp; m_step_max == other.m_step_max &amp;&amp; m_min == other.m_min &amp;&amp; m_max == other.m_max; } bool operator!=(reverse_iterator other) const { return !(*this == other); } T operator*() const{ //for integers, works perfectly. for floats, you can't get perfect but //gaurantees when step index is 0 //perfect stepping for integers if constexpr (std::is_integral_v&lt;T&gt;) { //negation shouldn't return m_max - ((m_max - m_min) / m_step_max) * (m_step_index); } else { // floating point needs to be handled differently to // guarantee that starts and ends are 0 and 1. // no worry of error from range addition return ((m_step_max - m_step_index) / static_cast&lt;T&gt;(m_step_max)) * m_max + (m_step_index / static_cast&lt;T&gt;(m_step_max)) * m_min; } } // iterator traits using difference_type = T; using value_type = T; using pointer = std::size_t; using reference = T &amp;; using iterator_category = std::forward_iterator_tag; private: std::size_t m_step_index; std::size_t m_step_max; T m_min; T m_max; }; template&lt;class TIterator&gt; class exclude_end_iterator_range { public: exclude_end_iterator_range(std::size_t step_max, const T &amp;min, const T &amp;max) : m_step_max(step_max), m_min(min), m_max(max) { } TIterator begin()const{ return TIterator(0, m_step_max, m_min, m_max); } TIterator end()const{ return TIterator(m_step_max, m_step_max, m_min, m_max); } private: std::size_t m_step_max; T m_min; T m_max; }; template&lt;class TIterator&gt; class exclude_begin_iterator_range { public: exclude_begin_iterator_range(std::size_t step_max, const T &amp;min, const T &amp;max) : m_step_max(step_max), m_min(min), m_max(max) { } TIterator begin()const{ return TIterator(1, m_step_max, m_min, m_max); } TIterator end()const{ return TIterator(m_step_max+1, m_step_max, m_min, m_max); } private: std::size_t m_step_max; T m_min; T m_max; }; template&lt;class TIterator&gt; class inclusive_iterator_range { public: inclusive_iterator_range(std::size_t step_max, const T &amp;min, const T &amp;max) : m_step_max(step_max), m_min(min), m_max(max) { } TIterator begin() const{ return TIterator(0, m_step_max, m_min, m_max); } TIterator end() const{ return TIterator(m_step_max+1, m_step_max, m_min, m_max); } private: std::size_t m_step_max; T m_min; T m_max; }; template&lt;class TIterator&gt; class exclusive_iterator_range { public: exclusive_iterator_range(std::size_t step_max, const T &amp;min, const T &amp;max) : m_step_max(step_max), m_min(min), m_max(max) { } TIterator begin()const{ return TIterator(1, m_step_max, m_min, m_max); } TIterator end()const{ return TIterator(m_step_max, m_step_max, m_min, m_max); } private: std::size_t m_step_max; T m_min; T m_max; }; exclude_end_iterator_range&lt;iterator&gt; forward_exclude_max(const T&amp; step_size){ std::size_t step_max = size()/step_size; return exclude_end_iterator_range&lt;iterator&gt;(step_max, m_min, m_max); } exclude_begin_iterator_range&lt;iterator&gt; forward_exclude_min(const T&amp; step_size){ std::size_t step_max = size()/step_size; return exclude_begin_iterator_range&lt;iterator&gt;(step_max, m_min, m_max); } exclusive_iterator_range&lt;iterator&gt; forward_exclusive(const T&amp; step_size){ std::size_t step_max = size()/step_size; return exclusive_iterator_range&lt;iterator&gt;(step_max, m_min, m_max); } inclusive_iterator_range&lt;iterator&gt; forward_inclusive(const T&amp; step_size){ std::size_t step_max = size()/step_size; return inclusive_iterator_range&lt;iterator&gt;(step_max, m_min, m_max); } //swap internals because reverse iterator causes min and max to swap // from being begin and end respectively to end and begin exclude_begin_iterator_range&lt;reverse_iterator&gt; reverse_exclude_max(const T&amp; step_size){ std::size_t step_max = size()/step_size; return exclude_begin_iterator_range&lt;reverse_iterator&gt;(step_max, m_min, m_max); } exclude_end_iterator_range&lt;reverse_iterator&gt; reverse_exclude_min(const T&amp; step_size){ std::size_t step_max = size()/step_size; return exclude_end_iterator_range&lt;reverse_iterator&gt;(step_max, m_min, m_max); } exclusive_iterator_range&lt;reverse_iterator&gt; reverse_exclusive(const T&amp; step_size){ std::size_t step_max = size()/step_size; return exclusive_iterator_range&lt;reverse_iterator&gt;(step_max, m_min, m_max); } inclusive_iterator_range&lt;reverse_iterator&gt; reverse_inclusive(const T&amp; step_size){ std::size_t step_max = size()/step_size; return inclusive_iterator_range&lt;reverse_iterator&gt;(step_max, m_min, m_max); } //returns a forward iterator that excludes the end of the range (max) iterator begin()const{ exclude_end_iterator_range&lt;iterator&gt; iterator_range(static_cast&lt;std::size_t&gt;(size()), m_min, m_max); return iterator_range.begin(); } //returns a forward iterator that excludes the end of the range (max) iterator end()const{ exclude_end_iterator_range&lt;iterator&gt; iterator_range(static_cast&lt;std::size_t&gt;(size()), m_min, m_max); return iterator_range.end(); } //returns a reverse iterator that excludes the end of the range (min) reverse_iterator rbegin()const{ exclude_end_iterator_range&lt;reverse_iterator&gt; iterator_range(static_cast&lt;std::size_t&gt;(size()), m_min, m_max); return iterator_range.begin(); } //returns a reverse iterator that excludes the end of the range (min) reverse_iterator rend()const{ exclude_end_iterator_range&lt;reverse_iterator&gt; iterator_range(static_cast&lt;std::size_t&gt;(size()), m_min, m_max); return iterator_range.end(); } private: T m_min; T m_max; }; template&lt;typename T&gt; bool operator==(const numeric_range&lt;T&gt; &amp;lhs, const numeric_range&lt;T&gt; &amp;rhs) { return lhs.min() == rhs.min() &amp;&amp; lhs.max() == rhs.max(); } template&lt;typename T&gt; bool operator!=(const numeric_range&lt;T&gt; &amp;lhs, const numeric_range&lt;T&gt; &amp;rhs) { return !(lhs == rhs); } } </code></pre> <p>main.cpp</p> <pre><code>#include "numeric_range.h" #include &lt;iostream&gt; int main(){ stx::numeric_range&lt;float&gt; frange(0.0, 10.0); stx::numeric_range&lt;int&gt; irange(0, 10); std::cout &lt;&lt; "frange contains 5.435: " &lt;&lt; frange.contains(5.435) &lt;&lt; "\n"; std::cout &lt;&lt; "frange does not contain exclusive 0.0: " &lt;&lt; !frange.contains_exclusive(0.0) &lt;&lt; "\n"; std::cout &lt;&lt; "irange contains 5: " &lt;&lt; frange.contains(5) &lt;&lt; "\n"; std::cout &lt;&lt; "irange does not contain exclusive 10: " &lt;&lt; !frange.contains_exclusive(10) &lt;&lt; "\n"; std::cout &lt;&lt; "frange iterate: "; for(auto i : frange){ std::cout &lt;&lt; i &lt;&lt; ","; } std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "irange iterate: "; for(auto i : irange){ std::cout &lt;&lt; i &lt;&lt; ","; } std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "frange 0.5 iterate: "; for(auto i : frange.forward_exclude_max(0.5)){ std::cout &lt;&lt; i &lt;&lt; ","; } std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "irange 2 iterate: "; for(auto i : irange.forward_exclude_max(2)){ std::cout &lt;&lt; i &lt;&lt; ","; } std::cout &lt;&lt; "\n"; return 0; } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Arguments of scalar types are better passed by value.</p></li>\n<li><p>It makes sense for iterator types to befriend the range class itself and hide their constructors private.</p></li>\n<li><p>As a rule, it is undefined to compare iterators into different containers. Consequently, you can reduce your iterators comparison to but a single relational iterator (add a debug-time diagnostic for checking range ends if you like).</p></li>\n<li><p>Next, iterators don't need to keep track of range ends. The range itself knows its max when constructing an end iterator, the iterator itself needs not to know it's past the end. Finally, you don't need to execute division on each increment, even if it's optimized out (I wonder if every 17-compliant compiler is capable of that).</p></li>\n<li><p>Iterators are trivially random-access, so you can add more relational and arithmetical operators to them.</p></li>\n<li><p>Perhaps it makes sense to add a setter that mutates both ends of a range in a single call. In addition, operators like union of adjacent ranges might prove useful.</p></li>\n<li><p>gaurantees :)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T21:51:35.793", "Id": "468610", "Score": "0", "body": "so for 3 you are saying that you shouldn't be comparing iterators from different objects anyway because no one should expect that to work? For 4, don't I need to know the size still? for integers I could use a step size with out knowing the end, but for floats I can't guarantee addition will add up to the end. For floats I can't pre-multiply the division because I won't be able to guarantee that things like ((m_max/m_step_max) * m_step_index) = m_max." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T07:08:34.687", "Id": "468659", "Score": "1", "body": "3. Yes. 4. Ok, they make sense, but only for FP, for better precision." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:40:44.490", "Id": "468712", "Score": "0", "body": "do you think it would be worth it to just create two enable-ifed classes for the iterator types then since there is already type specific logic in each type (int and float) to take advantage of this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T06:50:25.513", "Id": "468792", "Score": "1", "body": "Yes, should work." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:40:28.703", "Id": "238959", "ParentId": "238916", "Score": "2" } } ]
{ "AcceptedAnswerId": "238959", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T02:19:59.613", "Id": "238916", "Score": "2", "Tags": [ "c++", "template", "iterator", "c++17", "interval" ], "Title": "template iterable numeric range class with multiple min/max inclusion modes" }
238916
<p>I have code that creates an AlertDialog to select a date by a user. I ran into a problem that this code began to take up a lot of space. Could you offer ideas on how to shorten this code / put it into different methods. Thanks in advance</p> <pre><code> public static AlertDialog getTextDialog(Context ctx, final OnSelectNewValueListener calendarListener) { View view = LayoutInflater.from(ctx).inflate(R.layout.calendar_dialog, null); AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setView(view); CalendarView calendar = view.findViewById(R.id.calendarView); TextView yearTextView = view.findViewById(R.id.year); TextView dateTextView = view.findViewById(R.id.date); Button cancel = view.findViewById(R.id.cancel); Button ok = view.findViewById(R.id.ok); AlertDialog calendarAlertDialog = builder.create(); LocalDate currentDate = getLocalDateFromMilli(calendar.getDate()); showCurrentDate(currentDate, yearTextView, dateTextView); calendar.setOnDateChangeListener((view1, year, month, dayOfMonth) -&gt; { LocalDate selectDate = LocalDate.of(year, Month.values()[month], dayOfMonth); showCurrentDate(selectDate, yearTextView, dateTextView); calendar.setDate(new GregorianCalendar(year,month,dayOfMonth).getTimeInMillis()); }); cancel.setOnClickListener(v -&gt; { calendarAlertDialog.cancel(); }); ok.setOnClickListener(v-&gt;{ calendarListener.onCalendarSelect(getLocalDateFromMilli(calendar.getDate())); calendarAlertDialog.cancel(); }); return calendarAlertDialog; } private static void showCurrentDate(LocalDate selectDate, TextView yearTextView, TextView dateTextView) { yearTextView.setText(String.valueOf(selectDate.getYear())); dateTextView.setText(selectDate.format(dateFormatMedium)); } @Override public void onCalendarSelect(LocalDate time) { date.setText(dateFormatShort.format(time)); } </code></pre> <p>OnSelectNewValueListener</p> <pre><code>interface OnSelectNewValueListener { void onCalendarSelect(LocalDate time); } </code></pre> <p>Imports:</p> <pre><code>import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.CalendarView; import android.widget.TextView; import com.sgc.weightcontrol.R; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import butterknife.BindView; import butterknife.ButterKnife; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T05:00:19.860", "Id": "468535", "Score": "0", "body": "Can you please include all imports used in this program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T05:02:57.397", "Id": "468536", "Score": "0", "body": "Added, I really do not understand what it will give you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T08:11:18.853", "Id": "468537", "Score": "1", "body": "@Destroyer `import` statement will significantly affect the space consumed by your code, that's why Linny asked for it. You should remove any `import` statement that's not really needed to compile your code.#" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T04:42:57.877", "Id": "238922", "Score": "1", "Tags": [ "java", "beginner", "datetime", "android", "interface" ], "Title": "Code for creating a dialog for choosing a date" }
238922
<p>I have built a maths project that asks the user an addition, subtraction, multiplication, division, power and square root questions based on the difficulty level they choose!</p> <p>But I am trying to refactor the code so I don't repeat myself too many times.</p> <p>Can anyone please help me make the code less repeatable?</p> <p>Here is the code:</p> <pre><code>using System; namespace mathstester { class Program { enum UserDifficulty { Easy, Normal, Hard } public static void Main(string[] args) { string userDifficulty = ""; do { Console.WriteLine("What difficulty level would you like to do! Please type E for Easy, N for Normal and H for hard"); userDifficulty = Console.ReadLine().ToUpper(); } while (userDifficulty != "E" &amp;&amp; userDifficulty != "N" &amp;&amp; userDifficulty != "H"); int numberOfQuestions = 0; do { Console.Write("How many questions would you like to answer? Please type a number divisible by 10!"); int.TryParse(Console.ReadLine(), out numberOfQuestions); } while (numberOfQuestions % 10 != 0); int numberOfQuestionsLeft = numberOfQuestions; Random random = new Random(); int score = 0; while (numberOfQuestionsLeft &gt; 0) { var operation = random.Next(1, 7); int number1 = 0; int number2 = 0; switch (userDifficulty) { case "E": switch (operation) { case 1: number1 = random.Next(1000); number2 = random.Next(1000); break; case 2: number1 = random.Next(1000); number2 = random.Next(1000); break; case 3: number1 = random.Next(13); number2 = random.Next(13); break; } break; case "N": switch (operation) { case 1: number1 = random.Next(1000); number2 = random.Next(1000); break; case 2: number1 = random.Next(1000); number2 = random.Next(1000); break; case 3: number1 = random.Next(1000); number2 = random.Next(1000); break; case 4: number1 = random.Next(1, 10000); number2 = random.Next(1, 1000); break; } break; case "H": switch (operation) { case 3: number1 = random.Next(1000); number2 = random.Next(1000); break; case 4: number1 = random.Next(1, 10000); number2 = random.Next(1, 1000); break; case 5: number1 = random.Next(13); number2 = random.Next(5); break; case 6: number1 = random.Next(1000); break; } break; } if(operation == 1 &amp;&amp; (userDifficulty == "E" || userDifficulty == "N")) { Console.Write($"What is {number1} + {number2} ="); int correctAnswer = number1 + number2; int userAnswer = Convert.ToInt32(Console.ReadLine()); if (correctAnswer == userAnswer) { Console.WriteLine("Well Done!"); score++; } else { Console.WriteLine("Your answer is incorrect!"); } numberOfQuestionsLeft--; } else if (operation == 2 &amp;&amp; (userDifficulty == "E" || userDifficulty == "N")) { Console.Write($"What is {number1} - {number2} ="); int correctAnswer = number1 - number2; int userAnswer = Convert.ToInt32(Console.ReadLine()); if (correctAnswer == userAnswer) { Console.WriteLine("Well Done!"); score++; } else { Console.WriteLine("Your answer is incorrect!"); } numberOfQuestionsLeft--; } else if (operation == 3 &amp;&amp; (userDifficulty == "E" || userDifficulty == "N" || userDifficulty == "H")) { Console.Write($"What is {number1} * {number2} ="); int correctAnswer = number1 * number2; int userAnswer = Convert.ToInt32(Console.ReadLine()); if (correctAnswer == userAnswer) { Console.WriteLine("Well Done!"); score++; } else { Console.WriteLine("Your answer is incorrect!"); } numberOfQuestionsLeft--; } else if (operation == 4 &amp;&amp; (userDifficulty == "N" || userDifficulty == "H") &amp;&amp; (number1 &gt; number2)) { Console.Write($"To the nearest integer, What is {number1} / {number2} ="); double correctAnswer = ((double)number1) / ((double)number2); double roundedCorrectAnswer = Math.Round(correctAnswer); int userAnswer = Convert.ToInt32(Console.ReadLine()); if (roundedCorrectAnswer == userAnswer) { Console.WriteLine("Well Done!"); score++; } else { Console.WriteLine("Your answer is incorrect!"); } numberOfQuestionsLeft--; } else if (operation == 5 &amp;&amp; userDifficulty == "H") { Console.Write($"What is {number1} ^ {number2} ="); double correctAnswer = Math.Pow(number1, number2); int userAnswer = Convert.ToInt32(Console.ReadLine()); if (correctAnswer == userAnswer) { Console.WriteLine("Well Done!"); score++; } else { Console.WriteLine("Your answer is incorrect!"); } numberOfQuestionsLeft--; } else if (operation == 6 &amp;&amp; userDifficulty == "H") { Console.Write($"To the nearest integer, What is √{number1} ="); double correctAnswer = Math.Sqrt(number1); double roundedCorrectAnswer = Math.Round(correctAnswer); int userAnswer = Convert.ToInt32(Console.ReadLine()); if (roundedCorrectAnswer == userAnswer) { Console.WriteLine("Well Done!"); score++; } else { Console.WriteLine("Your answer is incorrect!"); } numberOfQuestionsLeft--; } } Console.WriteLine($"You got a score of {score} out of {numberOfQuestions}"); </code></pre> <p>Thanks</p>
[]
[ { "body": "<p>I would create more classes:</p>\n\n<p>An interface Operation with the functions:</p>\n\n<ul>\n<li>getQuestionString</li>\n<li>checkAnswer<br>\nat the moment, you don't need this.<br>\nAdd this when you want to add questions with multiple possible answers eg. 3/4 and 6/8</li>\n<li>getAnswer</li>\n<li>next</li>\n</ul>\n\n<p>checkAnswer takes a String: the one the user answered and return if it is the correct answer.</p>\n\n<p>You then can create different subclasses: SumOperation, ProductOperation, SubtractOperation</p>\n\n<p>You add a constructor asking for the <code>maximumNumber1</code> and <code>maximumNumber2</code>.<br>\nYou could call those constructor straight from your program, but it would be even better if you created subclasses (eg. SimpleSumOperation, HardProductOperation) where you define these values.<br>\nThis is necessary if you would have operations that takes more and/or other arguments.</p>\n\n<p>When you add these operations to an array based upon the user choosen level, you can select a random value of this array call <code>next</code> on the question and you have your next question.</p>\n\n<h1>factory</h1>\n\n<p>You could add even more classes...<br>\nIf you remove next from you question and if the questions don't longer ask for a maxRand but for the specific values instead, you can do the exact same quiz twice.<br>\nThis means you do need to create those operations.<br>\nYou can do this yourself, by calling the constructors with the specific values, but you could also create a factory for each operation (eg. ProductOperationFactory).</p>\n\n<p>This factory could take the difficulty and \nknow about the random values for each difficulty, but you could also create a subclass for each factory (eg. SimpleSubtractFactory).<br>\nYou can add these factories to an array, random select a factory and then create the question which you then ask.</p>\n\n<p>This are all suggestions which you all can ignore if you want.\nUsing all of my suggestions would mean that instead of a class you get a big fat program which could be way to much for what you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T08:58:04.363", "Id": "238933", "ParentId": "238923", "Score": "1" } }, { "body": "<p>You need to consider using classes more often. </p>\n\n<p>For your current work, you need two classes (at least) to handle the application process. A class would be for holding the <code>Questions</code> and another class to hold the application logic. </p>\n\n<pre><code>// define the number of levels you need which would be used for random.\n// so if the user chose Easy, this means it will pick from 1 to 3 MathOperation.\npublic enum UserDifficulty { Easy = 3, Normal = 4, Hard = 6 }\n\npublic enum MathOperation { Addition = 1, Subtraction = 2, Multiplication = 3, Division = 4, Power = 5, SquareRoot = 6 }\n\npublic class MathQuestions\n{\n public int QuestionNumber { get; set; }\n public MathOperation OperaionType { get; set; }\n public int LeftHand { get; set; }\n public int RightHand { get; set; }\n public int CorrectAnswer =&gt; Calculate();\n public int GivenAnswer { get; set; }\n\n public bool IsCorrect =&gt; CorrectAnswer == GivenAnswer;\n\n public int Calculate()\n {\n switch (OperaionType)\n {\n case MathOperation.Addition:\n return LeftHand + RightHand;\n case MathOperation.Subtraction:\n return LeftHand - RightHand;\n case MathOperation.Multiplication:\n return LeftHand * RightHand;\n case MathOperation.Division:\n return LeftHand / RightHand;\n case MathOperation.Power:\n return (int)Math.Pow(LeftHand, RightHand);\n case MathOperation.SquareRoot:\n return (int)Math.Sqrt(LeftHand);\n default:\n return 0;\n }\n }\n\n public string GetOperationString()\n {\n switch (OperaionType)\n {\n case MathOperation.Addition:\n return $\"{LeftHand} + {RightHand}\";\n case MathOperation.Subtraction:\n return $\"{LeftHand} - {RightHand}\";\n case MathOperation.Multiplication:\n return $\"{LeftHand} x {RightHand}\";\n case MathOperation.Division:\n return $\"{LeftHand} / {RightHand}\";\n case MathOperation.Power:\n return $\"{LeftHand} ^ {RightHand}\";\n case MathOperation.SquareRoot:\n return $\"√{LeftHand}\";\n default:\n return string.Empty;\n }\n }\n}\n\npublic class MathClass\n{\n // you need two randoms, one for the questions, and ther other one for the operators\n // using one for each would avoid skipping the operator numbers and vise versa. \n private readonly Random random = new Random();\n\n private readonly Random randomOperator = new Random();\n\n private readonly List&lt;MathQuestions&gt; questions = new List&lt;MathQuestions&gt;();\n\n private int NumberOfQuestions { get; }\n\n private UserDifficulty Difficulty { get; }\n\n public MathClass(UserDifficulty difficulty, int numberOfQuestions)\n {\n Difficulty = difficulty;\n NumberOfQuestions = numberOfQuestions;\n }\n\n public IEnumerable&lt;MathQuestions&gt; GetQuestions()\n {\n var level = (int)Difficulty + 1;\n\n int operation;\n\n for (int x = 1; x &lt;= NumberOfQuestions; x++)\n {\n operation = randomOperator.Next(1, level);\n\n var question = new MathQuestions\n {\n QuestionNumber = x,\n LeftHand = random.Next(1000),\n RightHand = random.Next(500),\n OperaionType = (MathOperation)operation\n\n };\n\n // Calculate the Correct Answer.\n question.Calculate();\n\n questions.Add(question);\n }\n\n return questions;\n }\n\n}\n</code></pre>\n\n<p>then you can do this : </p>\n\n<pre><code>public static class Program\n{ \n public static void Main(string[] args)\n {\n\n //for the MathClass\n UserDifficulty difficulty = UserDifficulty.Normal;\n\n int numberOfQuestions = 0;\n\n int steps = 1; // number of process steps before getting the exam\n\n while (steps &lt;= 2)\n {\n if(steps == 1)\n {\n Console.WriteLine(\"What difficulty level would you like to do! Please type E for Easy, N for Normal and H for hard\");\n\n var userDifficultyStr = Console.ReadLine().ToUpper();\n\n\n if (!new[] { \"E\", \"N\", \"H\" }.Contains(userDifficultyStr)) { continue; } // return to this step.\n\n switch (userDifficultyStr)\n {\n case \"E\":\n difficulty = UserDifficulty.Easy;\n break;\n case \"N\":\n difficulty = UserDifficulty.Normal;\n break;\n case \"H\":\n difficulty = UserDifficulty.Hard;\n break;\n }\n\n //Go to the next Step\n steps++;\n }\n\n\n if(steps == 2)\n {\n Console.Write(\"How many questions would you like to answer? Please type a number divisible by 10!\");\n\n if(!int.TryParse(Console.ReadLine(), out numberOfQuestions) || numberOfQuestions % 10 != 0) { continue; } // return to this step.\n\n // if all things okay break this loop \n break;\n }\n }\n\n // Create the questions\n var questions = new MathClass(difficulty, numberOfQuestions).GetQuestions().ToList();// using Linq\n\n // Loop over them \n foreach (var question in questions)\n {\n\n int answer;\n\n Console.Write($\"What is {question.GetOperationString()} = \");\n\n while (!int.TryParse(Console.ReadLine(), out answer))\n {\n Console.WriteLine(\"Invalid Input, only integers are allowed. Try Again!\");\n }\n\n // store the answer of this question \n question.GivenAnswer = answer;\n\n if (answer != question.CorrectAnswer)\n {\n Console.WriteLine(\"Your answer is incorrect!\");\n }\n else\n {\n Console.WriteLine(\"Well Done!\");\n }\n }\n\n\n var score = questions.Count(x =&gt; x.IsCorrect); // using Linq\n\n Console.WriteLine($\"You got a score of {score} out of {questions.Count}\");\n\n }\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>if just want to make partial changes on the current loop you can do this : </p>\n\n<pre><code>// set the operation max value based on the given difficulty.\nint operationMax = 0;\n\nswitch (userDifficulty)\n{\n case \"E\":\n operationMax = 3; \n break;\n case \"N\":\n operationMax = 4; \n break;\n case \"H\":\n operationMax = 7; \n break; \n} \n\nwhile (numberOfQuestionsLeft &gt; 0)\n{\n var operation = random.Next(1, operationMax);\n\n // make them all double \n double number1 = 0;\n double number2 = 0;\n double correctAnswer; \n double userAnswer; \n\n // store the msg\n string msg = string.Empty;\n\n switch(operation)\n {\n case 1:\n number1 = random.Next(1000);\n number2 = random.Next(1000);\n correctAnswer = number1 + number2;\n msg = $\"{number1} + {number2}\";\n break;\n case 2:\n number1 = random.Next(1000);\n number2 = random.Next(1000);\n correctAnswer = number1 - number2;\n msg = $\"{number1} - {number2}\";\n break; \n case 3:\n number1 = random.Next(13);\n number2 = random.Next(13);\n correctAnswer = number1 * number2;\n msg = $\"{number1} x {number2}\";\n break;\n case 4:\n number1 = random.Next(1, 10000);\n number2 = random.Next(1, number1 - 1); // this would give smaller number than number1 \n correctAnswer = number1 / number2;\n msg = $\"{number1} / {number2}\";\n break; \n case 5:\n number1 = random.Next(13);\n number2 = random.Next(5); \n correctAnswer = Math.Pow(number1, number2);\n msg = $\"{number1} ^ {number2}\";\n break; \n case 6:\n number1 = random.Next(1000); \n correctAnswer = Math.Sqrt(number1);\n msg = $\"√{number1}\";\n break; \n }\n\n\n if(operation == 4 || operation == 6)\n {\n Console.Write($\"To the nearest integer, What is {msg} =\"); \n }\n else \n {\n Console.Write($\"What is {msg} =\");\n }\n\n userAnswer = Convert.ToDouble(Console.ReadLine());\n\n if (Math.Round(correctAnswer) == Math.Round(userAnswer))\n {\n Console.WriteLine(\"Well Done!\");\n score++;\n }\n else\n {\n Console.WriteLine(\"Your answer is incorrect!\");\n } \n\n}\n\nConsole.WriteLine($\"You got a score of {score} out of {numberOfQuestions}\");\n</code></pre>\n\n<p>let me know if you have any questions. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T00:14:18.700", "Id": "468625", "Score": "0", "body": "Thank You, But for now, I just want to make my code less repeatable without changing it much. For example, after the switch cases I made, there is an \"if else-if\" loop. Inside that loop, there is an \"if-else\" loop. How do I take that if-else loop out of the other loop so I do not write it so many times?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T01:05:53.583", "Id": "468631", "Score": "1", "body": "@crazydanyal1414 check the update" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:44:20.197", "Id": "238949", "ParentId": "238923", "Score": "2" } } ]
{ "AcceptedAnswerId": "238949", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T05:00:54.757", "Id": "238923", "Score": "3", "Tags": [ "c#", "beginner", "console", "mathematics" ], "Title": "C# maths quiz with user choosen difficulty-level" }
238923
<pre><code>#include &lt;stdio.h&gt; #include &lt;assert.h&gt; #include &lt;stdlib.h&gt; #define STACK_SIZE 100 typedef struct _stack { char *mem; size_t size; int top; } STACK; STACK *stack_create(char *mem, size_t size); void stack_push(STACK *stack, char c); char stack_pop(STACK *stack); char stack_peek(STACK *const stack); void stack_print(STACK *stack); int main() { char stack_mem[STACK_SIZE]; STACK *my_stack = stack_create(stack_mem, STACK_SIZE); stack_push(my_stack, 'a'); stack_push(my_stack, 'b'); stack_push(my_stack, 'c'); stack_push(my_stack, 'd'); stack_print(my_stack); printf("Top of stack contains: %c\n", stack_peek(my_stack)); stack_pop(my_stack); stack_print(my_stack); stack_pop(my_stack); stack_pop(my_stack); stack_pop(my_stack); stack_push(my_stack, 'j'); stack_push(my_stack, 'k'); stack_print(my_stack); free(my_stack); return EXIT_SUCCESS; } STACK *stack_create(char *mem, size_t size) { assert(mem &amp;&amp; size); STACK *output = malloc(sizeof(STACK)); output-&gt;mem = mem; output-&gt;size = size; output-&gt;top = -1; return output; } void stack_push(STACK *stack, char c) { assert(stack); if(c &lt; 0) { fprintf(stderr, "This stack is not designed for negative char values\n"); return; } if((stack-&gt;top + 1) &lt; stack-&gt;size) { stack-&gt;mem[stack-&gt;top + 1] = c; stack-&gt;top++; } return; } char stack_pop(STACK *stack) { assert(stack); if(stack-&gt; top &lt; 0) { fprintf(stderr, "Cannot pop from empty stack.\n"); return -1; } char o; o = stack-&gt;mem[stack-&gt;top]; stack-&gt;top--; return o; } char stack_peek(STACK * const stack) { assert(stack); if(stack-&gt;top &lt; 0) { fprintf(stderr, "Nothing on stack to peek at.\n"); return -1; } return stack-&gt;mem[stack-&gt;top]; } void stack_print(STACK *stack) { assert(stack); if(!stack-&gt;top) { fprintf(stderr, "Nothing on stack to print.\n"); return; } printf("Entire stack:\n"); int i; for(i = stack-&gt;top; i &gt;= 0; --i) { printf("%c\n", stack-&gt;mem[i]); } } </code></pre> <p>Please provide feedback on whatever you see fit, however, error handling would be a helpful focus.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T18:20:35.417", "Id": "468887", "Score": "0", "body": "Out of curiosity: why code this? Why is this tagged [tag:algorithm]? Why *not* [tag:reinventing-the-wheel]?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T04:45:34.167", "Id": "469026", "Score": "0", "body": "@greybeard For fun." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T05:39:44.747", "Id": "469028", "Score": "0", "body": "No algorithm without any repetition. Wait, there's `stack_print()`." } ]
[ { "body": "<p>You could allow to initialize the stack locally.\nJust by separating the bigger part of stack_create to separate function.</p>\n\n<pre><code>void stack_init(STACK* stack, char* mem, size_t size)\n{\n stack-&gt;mem = mem;\n stack-&gt;size = size;\n stack-&gt;top = -1;\n}\n\nchar stack_mem[STACK_SIZE];\nSTACK stack;\nstack_init(&amp;stack, stack_mem, STACK_SIZE);\n</code></pre>\n\n<p>As for error handling, stack usualy does not handle it. You should instead offer the \"is empty?\" and \"is full?\" functions. Consumers of the stack are then responsible for making sure stack is not empty before they peek or pop, and that it is not full before they push. Check for emptiness is often integral part of algorithms using the stack anyway. Check for fullness not so much, it Is mostly limitation of a fixed size stack. But the consumer must check it nevertheless or they must be sure that bigger stack is never needed.</p>\n\n<p>In stack_create you should check if malloc returns null then dont assign to properties and return null as well. Consumers are again responsible for checking this situation.</p>\n\n<p>One last point, the stack_create could be complemented with stack_destroy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T03:17:21.967", "Id": "468783", "Score": "0", "body": "I agree about `stack_create`...`stack_destroy`. It should be noted if one followed the `stack_init` suggestion, I would expect the user would be responsible for destroying the stack, which could be on the stack or anywhere." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T08:24:57.230", "Id": "238930", "ParentId": "238929", "Score": "3" } }, { "body": "<h2>Datatype</h2>\n\n<p>The <code>size_t size</code> is appropriate, but <code>int top</code> is less. This effectively limits an entire <code>size_t</code> to just storing <code>INT_MAX</code>, and the only value that is negative is -1, the rest are wasted. <code>gcc</code> gave me a warning about comparing integers of different signs, but they should moreover be the same type because they are both storing indices; instead of <code>size</code> and <code>top</code>, it's more effective to store <code>capacity</code> and <code>size</code>, which is <code>top + 1</code>.</p>\n\n<h2>Code Coverage</h2>\n\n<p>You don't account for all return values from <a href=\"https://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html\" rel=\"nofollow noreferrer\"><code>malloc</code></a>; specifically, if null is returned, you program will write to it and crash.</p>\n\n<p>Error messages are printed on <code>stderr</code>, which is a good habit, especially if one is doing a unix command-driven application. However, in a general library, I would not expect output from the code at all, (except when I ask.) This probably necessitates having a way to return an error condition, such as a return,</p>\n\n<pre><code>if(c &lt; 0) return errno = EDOM, 0;\n</code></pre>\n\n<p>or just silently ignoring mis-formed input like the <code>stack_push</code> is already doing for the size,</p>\n\n<pre><code>if(stack-&gt;size &gt;= stack-&gt;capacity || c &lt; 0) return;\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>You've come up with a naming system that reduces potential namespace conflicts when defining non-static functions carefully. This is excellent for the reuseabity of your code.</p>\n\n<p><code>_stack</code> is a dangerous name, as explained in the <a href=\"http://c-faq.com/decl/namespace.html\" rel=\"nofollow noreferrer\">C faq</a>, \"all identifiers beginning with an underscore are reserved for ordinary identifiers (functions, variables, typedefs, enumeration constants) with file scope.\" Also, <code>typedef</code> and tags have different namespace, <em>and</em> your names are distinct anyway, so you aren't really gaining much. You aren't self-referencing, so you might as well make it an anonymous <code>struct</code>. However, even if you don't agree, it's worth checking out the <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html#typedefs\" rel=\"nofollow noreferrer\">Linux kernel style typedef</a>, (which says it's a mistake to <code>typedef</code> in this case.)</p>\n\n<p>I would say that capitalized <code>typedef</code> names have a <a href=\"https://en.wikipedia.org/wiki/Naming_convention_(programming)\" rel=\"nofollow noreferrer\">connotation of being constant</a>. However, has some precedent in <code>C</code>, (<em>eg</em>, <code>FILE</code>.)</p>\n\n<h2>Design</h2>\n\n<p>Writing a test case is a great software engineering design practice.</p>\n\n<p>Your usage of <code>assert</code> is effective at specifying the contract must be followed when calling a function.</p>\n\n<p>In 3 places you mix declarations and code that could easily be swapped to make it C90-compatible, should you so desire.</p>\n\n<p>Your design choice of specifying the stack size and <code>STACK_SIZE</code> is confusing. While it finds use in existing <code>char</code> arrays that one wants to put a stack on top of temporarily, or perhaps stacks on the stack (<em>sic</em>,) it's generally better to contain the implementation's external dependencies as much as possible. Instead of passing <code>mem</code>, consider,</p>\n\n<pre><code>struct Stack *stack_create(const size_t capacity) {\n struct Stack *output;\n\n assert(capacity);\n\n if(!(output = malloc(sizeof *output + capacity))) return 0;\n\n output-&gt;mem = (char *)(output + 1);\n output-&gt;capacity = capacity;\n output-&gt;size = 0;\n return output;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T02:39:19.997", "Id": "239035", "ParentId": "238929", "Score": "1" } } ]
{ "AcceptedAnswerId": "239035", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T07:14:19.703", "Id": "238929", "Score": "3", "Tags": [ "algorithm", "c", "stack" ], "Title": "Basic 'char' Stack implementation in C" }
238929
<p><strong>Problem Statement</strong>:</p> <p>Consider the following example: a coin was tossed <code>n=7</code> times and the results were </p> <pre><code>"Heads, Tails, Tails, Tails, Heads, Heads, Tails" </code></pre> <p>Therefore, the longest <code>Heads</code> streak was 2 and the longest <code>Tails</code> streak was 3.</p> <p><strong>Here is my code</strong>:</p> <pre><code>def getMaxStreaks(toss): #toss=&gt; ["Heads, Tails, Tails, Tails, Heads, Heads, Tails"] # Return an array of two integers containing the maximum streak of heads and tails respectively scH, scT = 0, 0 H, T = 0, 0 for tossResult in range(0, len(toss)): if toss[tossResult] == 'Heads': H, T = H+1, 0 if H &gt; scH: scH = H elif toss[tossResult] == 'Tails': H, T = 0, T+1 if T &gt; scT: scT = T return [scH, scT] # 2 3 </code></pre> <p>What can I do to improve my code, are there any improvements required? Please let me know if I need to update the question.</p>
[]
[ { "body": "<p>Don't iterate over the indices of a list only to then access the element at that index. Instead iterate directly over the elements of the list! Have a look at <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"noreferrer\">Loop Like A Native by Ned Halder</a>.</p>\n\n<p>In the standard library module <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"noreferrer\"><code>itertools</code></a> there is the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>groupby</code></a> function, which groups equal elements together. You can use this to make your code easier:</p>\n\n<pre><code>from itertools import groupby\n\ndef max_streaks(tosses):\n longest_streaks = {\"Heads\": 0, \"Tails\": 0}\n for toss, streak in groupby(tosses):\n longest_streaks[toss] = max(longest_streaks[toss], len(list(streak)))\n return longest_streaks[\"Heads\"], longest_streaks[\"Tails\"]\n\n\nmax_streaks(\"Heads, Tails, Tails, Tails, Heads, Heads, Tails\".split(\", \"))\n# 2, 3\n</code></pre>\n\n<p>Note that this does not assume anything about <code>tosses</code>, unlike your code. It could be a list or a string, but also something like a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"noreferrer\">generator</a>, which has no <code>len</code>.</p>\n\n<p>You could generalize this function to being able to count the longest streak of any elements by using a <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>collections.defaultdict</code></a> and returning it:</p>\n\n<pre><code>from collections import defaultdict\nfrom itertools import groupby\nfrom typing import Dict, Iterable, Hashable\n\ndef longest_streaks(elements: Iterable[Hashable]) -&gt; Dict[Hashable, int]:\n \"\"\"Count the length of the longest streak of each distinct element \n present in `elements`.\n All elements need to be hashable.\n \"\"\"\n longest_streak = defaultdict(int)\n for element, streak in groupby(elements):\n longest_streak[element] = max(longest_streak[element], len(list(streak)))\n return dict(longest_streak)\n\n\nif __name__ == \"__main__\":\n longest_streaks([1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 3])\n # {1: 3, 2: 2, 3: 3}\n</code></pre>\n\n<p>Note that I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, by using <code>lower_case</code> for variables and functions and wrapped the calling code in a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without running the example. I also added some <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> and a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstring</a>, which makes it easier to figure out what a function does, both for anybody else reading your code and for yourself in two months.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T11:00:36.990", "Id": "238938", "ParentId": "238935", "Score": "7" } }, { "body": "<p>On top of @Graipher's style recommendations, you should use better, more descriptive names to begin with. In this context, it's fairly clear what at least <em>part</em> of the intent of <code>H</code> and <code>T</code> are. <code>H</code> has to do with \"heads\"... but what about \"heads\"? I would name it something closer to <code>head_streak</code>, or something else descriptive. Especially with as short of lines as you have, succinct variables names aren't necessary or even preferable. And that suggestions applies to an even greater extent for names like <code>scH</code>. <em>Be descriptive</em>. <code>record_heads</code> or something similar would be better.</p>\n\n<hr>\n\n<p>I'm not a fan of multiple variable assignments on one line; especially when it's using tuple destructuring. </p>\n\n<pre><code>H, T = H+1, 0\n</code></pre>\n\n<p>That may be succinct and fit on one line, but I don't think it reads near as clearly as:</p>\n\n<pre><code>H += 1\nT = 0\n</code></pre>\n\n<p>And I would say the same about</p>\n\n<pre><code>scH, scT = 0, 0\n</code></pre>\n\n<p>And the like at the top.</p>\n\n<hr>\n\n<p>Arguably, it would be better to have the function return a tuple instead of a list. Really, it doesn't make any actual difference. Symbolically though, you're returning a structure that will <em>always</em> have exactly two elements. If you were to type-hint your function signature:</p>\n\n<pre><code>from typing import List\n\ndef getMaxStreaks(tosses: List[str]) -&gt; List[int]:\n . . .\n</code></pre>\n\n<p>That, what you have now, suggests that the function could return a variable amount of numbers, which isn't true. This on the other hand though:</p>\n\n<pre><code>from typing import List, Tuple\n\ndef getMaxStreaks(tosses: List[str]) -&gt; Tuple[int, int]:\n . . .\n</code></pre>\n\n<p>Lets the caller (and the IDE) know that the function will always return exactly two integers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T06:20:14.670", "Id": "468646", "Score": "0", "body": "sure, thanks for your answer. I will explore how to specify return value for a function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:07:35.410", "Id": "238955", "ParentId": "238935", "Score": "5" } } ]
{ "AcceptedAnswerId": "238938", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T09:12:31.053", "Id": "238935", "Score": "6", "Tags": [ "python", "programming-challenge" ], "Title": "Find max number of repeating heads and tails" }
238935
<p>(See the first and initial iteration at <strong><a href="https://codereview.stackexchange.com/questions/238872/remotefile-in-java">RemoteFile in Java</a></strong>.)</p> <p>I have added some new facilities for convenience. Now I have this in mind:</p> <p><strong>com.github.coderodde.utils.io.RemoteFileDownloadListener.java:</strong></p> <pre><code>package com.github.coderodde.utils.io; /** * This interface specifies an application programming interface for * {@link RemoteFile} downloading. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 15, 2020) ~ initial version. * @since 1.6 (Mar 15, 2020) */ public interface RemoteFileDownloadListener { public void onStart(); public void onReady(); } </code></pre> <p><strong>com.github.coderodde.utils.io.RemoteFile.java:</strong></p> <pre><code>package com.github.coderodde.utils.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * This class implements a downloadable remote file. * * @author Rodion "rodde" Efremov * @version 1.61 (Mar 15, 2020) * @since 1.6 (Mar 14, 2020) */ public class RemoteFile { /** * The URL of the target remote file. */ private final String url; /** * The list of remote file listeners listening on download progress. */ private final List&lt;RemoteFileDownloadListener&gt; listeners = new ArrayList&lt;&gt;(); /** * Constructs a new {@code RemoteFile} object with given URL as a string. * * @param url the URL of the target remote file. */ public RemoteFile(String url) { this.url = Objects.requireNonNull(url, "The URL is null."); } public String getURl() { return this.url; } /** * Downloads the remote file to local disk. * * @param path the path of the target file on the local disk. * * @throws MalformedURLException if there are problems with URL. * * @throws IOException if I/O fails. */ public void download(String path) throws MalformedURLException, IOException, URISyntaxException { this.download(new File(path)); } /** * Downloads the remote file to local disk.. * * @param file the target file object. * * @throws MalformedURLException if there are issues with the URL. * * @throws IOException if there are I/O issues. * * @throws URISyntaxException if URI is bad. */ public void download(File file) throws MalformedURLException, IOException, URISyntaxException { for (RemoteFileDownloadListener listener : listeners) { listener.onStart(); } InputStream inputStream = new URL(url).openStream(); Files.copy(inputStream, Path.of(file.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); for (RemoteFileDownloadListener listener : listeners) { listener.onReady(); } } /** * Adds a download listener. * * @param listener the target listener. */ public void addRemoteFileListener(RemoteFileDownloadListener listener) { this.listeners.add( Objects.requireNonNull( listener, "The listener is null.")); } /** * Removes a download listener. * * @param listener the target listener. */ public void removeRemoteFileListener(RemoteFileDownloadListener listener) { this.listeners.remove(listener); } } </code></pre> <p><strong>com.github.coderodde.utils.io.RemoteFileTest.java:</strong></p> <pre><code>package com.github.coderodde.utils.io; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import org.junit.Test; public class RemoteFileTest { @Test public void testDownloadedFileIsCreatedAfterDownload() throws IOException, MalformedURLException, URISyntaxException { RemoteFile remoteFile = new RemoteFile("https://www.baeldung.com/java-download-file"); remoteFile.addRemoteFileListener(new RemoteFileDownloadListener() { private long milliseconds; @Override public void onStart() { System.out.println("onStart"); milliseconds = System.currentTimeMillis(); } @Override public void onReady() { milliseconds = System.currentTimeMillis() - milliseconds; System.out.println( "onReady. Milliseconds elapsed: " + milliseconds); } }); remoteFile.download("C:\\baeldung.html"); } } </code></pre> <p><strong>Critique request</strong></p> <p>I would like to hear any comments regarding my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:56:54.350", "Id": "468557", "Score": "0", "body": "Your test doesn't test, it just runs..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T11:00:13.500", "Id": "468558", "Score": "0", "body": "@tieskedh I know. The intent was to make sure that `RemoteFile` does not throw anything funny (unless there are connectivity problems)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T11:55:50.023", "Id": "468561", "Score": "0", "body": "Ah, use org.junit.jupiter.api.Assertions.assertDoesNotThrow" } ]
[ { "body": "<p>in my opinion, the code is good, but I have some suggestions.</p>\n\n<h1>com.github.coderodde.RemoteFile class</h1>\n\n<h3><code>com.github.coderodde.RemoteFile#download(java.io.File)</code></h3>\n\n<ol>\n<li><p>The <code>URISyntaxException</code> in the method <code>com.github.coderodde.RemoteFile#download(java.io.File)</code> is never thrown and can be removed.</p></li>\n<li><p>In my opinion, the logic of this method should be extracted to an external object (composition). This will allow you to make unit tests without running the whole application, and it will allow you to add other types of remote files very easily.</p></li>\n</ol>\n\n<p><strong>com.github.coderodde.executors.Executor</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface Executor {\n void execute(File file) throws IOException;\n}\n</code></pre>\n\n<p><strong>com.github.coderodde.executors.HttpExecutorImpl</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class HttpExecutorImpl implements Executor {\n private String url;\n\n public HttpExecutorImpl(String url) {\n this.url = url;\n }\n\n @Override\n public void execute(File file) throws IOException {\n\n InputStream inputStream = new URL(url).openStream();\n\n Files.copy(inputStream,\n Path.of(file.getAbsolutePath()),\n StandardCopyOption.REPLACE_EXISTING);\n }\n}\n</code></pre>\n\n<h2>Refactored code</h2>\n\n<p><strong>com.github.coderodde.RemoteFile</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class RemoteFile {\n\n private final Executor executor;\n\n private final List&lt;RemoteFileDownloadListener&gt; listeners =\n new ArrayList&lt;&gt;();\n\n public RemoteFile(Executor executor) {\n this.executor = Objects.requireNonNull(executor, \"The EXECUTOR is null.\");\n }\n\n public void download(String path) throws\n IOException {\n this.download(new File(path));\n }\n\n public void download(File file) throws IOException {\n for (RemoteFileDownloadListener listener : listeners) {\n listener.onStart();\n }\n\n executor.execute(file);\n\n for (RemoteFileDownloadListener listener : listeners) {\n listener.onReady();\n }\n }\n\n public void addRemoteFileListener(RemoteFileDownloadListener listener) {\n this.listeners.add(\n Objects.requireNonNull(\n listener,\n \"The listener is null.\"));\n }\n\n public void removeRemoteFileListener(RemoteFileDownloadListener listener) {\n this.listeners.remove(listener);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:51:22.927", "Id": "238961", "ParentId": "238936", "Score": "2" } } ]
{ "AcceptedAnswerId": "238961", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:50:40.187", "Id": "238936", "Score": "2", "Tags": [ "java", "file", "io", "network-file-transfer" ], "Title": "RemoteFile in Java - follow-up" }
238936
<p>This is a calculator I made for fun and also to practice a bit. My goal was to make a calculator that can handle user input as well as a scientific calculator.<br> I made it as a Singleton to keep things tidy and provide some additional calculator functionality.<br></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;string&gt; #include &lt;cstring&gt; #include &lt;cmath&gt; static const long double pi_num = 3.1415926535897932; template &lt;typename T, typename U&gt; static T factorial(U num) { T res = 1; while (num &gt; 1) { res *= num; --num; } return res; } // singleton template &lt;typename NUM_TYPE&gt; class calculator { public: static calculator &amp;get(); calculator(const calculator &amp;) = delete; calculator &amp;operator=(const calculator &amp;) = delete; static NUM_TYPE calc(const std::string &amp;expression); static NUM_TYPE calc(const char *expression); NUM_TYPE calc_substr(const std::string &amp;, unsigned begin, unsigned end); static const std::string output(); static void printOutput(); static bool error(); static NUM_TYPE ans(); private: calculator() {} std::string error_msg; NUM_TYPE answer = 0; bool error_flag = false; bool paren_flag = false; // for preventing parentheses from overwriting answer static void applyFunction(std::string &amp;, NUM_TYPE &amp;); }; template &lt;typename NUM_TYPE&gt; calculator&lt;NUM_TYPE&gt; &amp;calculator&lt;NUM_TYPE&gt;::get() { static calculator&lt;NUM_TYPE&gt; Calculator; return Calculator; } template &lt;typename NUM_TYPE&gt; NUM_TYPE calculator&lt;NUM_TYPE&gt;::calc(const std::string &amp;expression) { return get().calc_substr(expression, 0, expression.length() - 1); } template &lt;typename NUM_TYPE&gt; NUM_TYPE calculator&lt;NUM_TYPE&gt;::calc(const char *expression) { return get().calc_substr(expression, 0, strlen(expression) - 1); } template &lt;typename NUM_TYPE&gt; NUM_TYPE calculator&lt;NUM_TYPE&gt;::calc_substr(const std::string &amp;expression, unsigned begin, unsigned end) { // the calculator splits the input into segments (units) each containing an operation and a number // these segments (units) are stored in calc_units std::vector&lt; std::pair&lt;char, NUM_TYPE&gt; &gt; calc_units; std::string function; function.reserve(6); NUM_TYPE num = 0, res = 0; char operation = '+'; bool operation_flag = true; // setting the operation flag to true since // the first number's plus sign is usually omitted bool negative_flag = false; bool function_flag = false; error_flag = false; // parsing the string and calculating functions for (int i = begin; i &lt;= end; ++i) { if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/' || expression[i] == '%' || expression[i] == '^') { if (operation_flag) { if (expression[i] == '-') // negative number negative_flag = true; else if (operation == '*' &amp;&amp; expression[i] == '*') // python notation for exponentiation operation = '^'; else { error_flag = true; error_msg = "Syntax Error"; return 0; } } else if (function_flag) { error_flag = true; error_msg = "Syntax Error"; return 0; } else { operation = expression[i]; operation_flag = true; negative_flag = false; } } else if (expression[i] == '!') calc_units[calc_units.size() - 1].second = factorial&lt;NUM_TYPE&gt;(calc_units[calc_units.size() - 1].second); else if (expression[i] &gt;= 'a' &amp;&amp; expression[i] &lt;= 'z') { function.clear(); while ((expression[i] &gt;= 'a' &amp;&amp; expression[i] &lt;= 'z') &amp;&amp; i &lt;= end) { function.push_back(expression[i]); ++i; } i--; if (function == "ans") { num = answer; if (negative_flag) num *= -1; if (operation_flag == false) // omitting the '*' in multiplication operation = '*'; calc_units.push_back(std::make_pair(operation, num)); num = 0; operation_flag = false; negative_flag = false; } else if (function == "pi") { num = pi_num; if (negative_flag) num *= -1; if (operation_flag == false) // omitting the '*' in multiplication operation = '*'; calc_units.push_back(std::make_pair(operation, num)); num = 0; operation_flag = false; negative_flag = false; } else function_flag = true; } // parsing numbers and applying functions // the user might use a decimal point without a zero before it to show a number smaller than one // example: 1337 * .42 where the zero in 0.42 is omitted else if ((expression[i] &gt;= '0' &amp;&amp; expression[i] &lt;= '9') || expression[i] == '.') { while (expression[i] &gt;= '0' &amp;&amp; expression[i] &lt;= '9' &amp;&amp; i &lt;= end) { num = 10 * num + (expression[i] - '0'); ++i; } if (expression[i] == '.') // decimal point { ++i; unsigned decimals_count = 0; NUM_TYPE decimals = 0; while (expression[i] &gt;= '0' &amp;&amp; expression[i] &lt;= '9' &amp;&amp; i &lt;= end) { decimals = 10 * decimals + (expression[i] - '0'); decimals_count++; ++i; } num += decimals / pow(10, decimals_count); decimals = 0; decimals_count = 0; } if (negative_flag) // negative number num *= -1; // applying functions if (function_flag) { applyFunction(function, num); if (error_flag) { error_msg = "Unknown Function"; return 0; } function_flag = false; } if (operation_flag == false) // omitting the '*' in multiplication operation = '*'; calc_units.push_back(std::make_pair(operation, num)); num = 0; operation_flag = false; negative_flag = false; --i; } else if (expression[i] == '(') { unsigned open = ++i; // the user might open parentheses but not close them // in the case that several parentheses are opened but only some of them // are closed, we must pair the closest open and close parentheses together // parenthesis_count is used to check if a close parenthesis belongs to // the current open paranthesis int parenthesis_count = 1; while (parenthesis_count &gt; 0 &amp;&amp; i &lt;= end) { if (expression[i] == '(') ++parenthesis_count; if (expression[i] == ')') --parenthesis_count; ++i; } i--; paren_flag = true; // preventing parentheses from overwriting answer num = get().calc_substr(expression, open, i); if (error_flag) return 0; if (negative_flag) num *= -1; // applying functions if (function_flag) { applyFunction(function, num); if (error_flag) { error_msg = "Unknown Function"; return 0; } function_flag = false; } if (operation_flag == false) // omitting the '*' in multiplication operation = '*'; calc_units.push_back(std::make_pair(operation, num)); num = 0; operation_flag = false; negative_flag = false; paren_flag = false; } } for (int i = 0; i &lt; calc_units.size(); ++i) { if (calc_units[i].first == '+') { num = calc_units[i].second; } else if (calc_units[i].first == '-') { num = calc_units[i].second * -1; } // left-to-right associativity else if (calc_units[i].first == '*' || calc_units[i].first == '/') { res -= num; while (i &lt; calc_units.size() &amp;&amp; (calc_units[i].first == '*' || calc_units[i].first == '/')) { if (calc_units[i].first == '*') num *= calc_units[i].second; else if (calc_units[i].first == '/') { if (calc_units[i].second == 0) { error_flag = true; error_msg = "Math Error"; return 0; } else num /= calc_units[i].second; } ++i; } --i; } // right-to-left associativity else if (calc_units[i].first == '^' || calc_units[i].second == '%') { res -= num; NUM_TYPE temp; int count = 0; // finding where the operations with right-to-left associativity end while (i + count + 1 &lt; calc_units.size() &amp;&amp; (calc_units[i + count + 1].first == '^' || calc_units[i + count + 1].first == '%')) ++count; temp = calc_units[i + count].second; for (int j = count; j &gt;= 0; --j) { if (calc_units[i + j].first == '^') temp = pow(calc_units[i + j - 1].second, temp); if (calc_units[i + j].first == '%') temp = (long long) calc_units[i + j - 1].second % (long long) temp; } if (calc_units[i - 1].first == '+') num = temp; else if (calc_units[i - 1].first == '-') num = temp * -1; else if (calc_units[i - 1].first == '*') { num /= calc_units[i - 1].second; num *= temp; } else if (calc_units[i - 1].first == '/') { num *= calc_units[i - 1].second; num /= temp; } i += count; } res += num; } if (paren_flag == false) // preventing parentheses from overwriting answer answer = res; return res; } template &lt;typename NUM_TYPE&gt; const std::string calculator&lt;NUM_TYPE&gt;::output() { if (get().error_flag) return get().error_msg; else { using std::to_string; // for compatibility with non-fundamental data types return to_string(get().answer); } } template &lt;typename NUM_TYPE&gt; void calculator&lt;NUM_TYPE&gt;::printOutput() { if (get().error_flag) std::cout &lt;&lt; get().error_msg; else std::cout &lt;&lt; get().answer; } template &lt;typename NUM_TYPE&gt; bool calculator&lt;NUM_TYPE&gt;::error() { return get().error_flag; } template &lt;typename NUM_TYPE&gt; NUM_TYPE calculator&lt;NUM_TYPE&gt;::ans() { return get().answer; } template &lt;typename NUM_TYPE&gt; void calculator&lt;NUM_TYPE&gt;::applyFunction(std::string &amp;function, NUM_TYPE &amp;num) { if (function == "abs") num = fabs(num); else if (function == "sqrt") num = sqrt(num); else if (function == "cbrt") num = cbrt(num); else if (function == "sin") num = sin(num); else if (function == "cos") num = cos(num); else if (function == "tan") num = tan(num); else if (function == "cot") num = 1 / tan(num); else if (function == "sec") num = 1 / cos(num); else if (function == "csc") num = 1 / sin(num); else if (function == "arctan") num = atan(num); else if (function == "arcsin") num = asin(num); else if (function == "arccos") num = acos(num); else if (function == "arccot") num = atan(1 / num); else if (function == "arcsec") num = acos(1 / num); else if (function == "arccsc") num = asin(1 / num); else if (function == "sinh") num = sinh(num); else if (function == "cosh") num = cosh(num); else if (function == "tanh") num = tanh(num); else if (function == "coth") num = 1 / tanh(num); else if (function == "sech") num = 1 / cosh(num); else if (function == "csch") num = 1 / sinh(num); else if (function == "arctanh") num = atanh(num); else if (function == "arcsinh") num = asinh(num); else if (function == "arccosh") num = acosh(num); else if (function == "arccoth") num = atanh(1 / num); else if (function == "arcsech") num = acosh(1 / num); else if (function == "arccsch") num = asinh(1 / num); else if (function == "log") num = log10(num); else if (function == "ln") num = log(num); else if (function == "exp") num = exp(num); else if (function == "gamma") num = tgamma(num); else if (function == "erf") num = erf(num); else get().error_flag = true; function.clear(); } </code></pre> <p>Possible way of using the calculator:</p> <pre><code>using Calculator = calculator&lt;long double&gt;; int main() { std::string expression; while (true) { std::getline(std::cin, expression); Calculator::calc(expression); if (Calculator::error()) std::cout &lt;&lt; Calculator::output() &lt;&lt; "\n\n"; else std::cout &lt;&lt; "= " &lt;&lt; std::setprecision(15) &lt;&lt; Calculator::ans() &lt;&lt; "\n\n"; } } </code></pre> <p>Output example:</p> <pre><code>4400 * 1337 - 42 / 7 + 9000 = 5891794 2sin(pi/4)cos(pi/4) = 1 ans * 32 = 32 2 * 2 ^ 2 ^ 3 = 512 (2 + 3) * 4 = 20 5(8+9) = 85 2 * -4 = -8 tan(2)*log(5)/exp(6) = -0.00378574198801152 sin1sqrt2 = 1.19001967905877 1 / 0 Math Error sin*cos Syntax Error 2 */ 4 Syntax Error lol(1234) Unknown Function </code></pre> <p>A few questions:</p> <ul> <li>Is my extensive use of flags causing code-spaghetti?</li> <li>Does my code need more comments?</li> <li>Was it a good idea to use the Singleton design pattern?</li> </ul> <p>Let me know what you think! Suggestions and Ideas are very welcome :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T13:12:05.103", "Id": "468569", "Score": "0", "body": "Welcome to Code Review! You can take the [tour] and visit our [FAQs](https://codereview.meta.stackexchange.com/questions/tagged/faq?tab=Votes) to further familiarize yourself with our community." } ]
[ { "body": "<p>Use the constant <code>M_PI</code> (and others) from <code>&lt;cmath&gt;</code> instead of defining your own. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons\">Singletons are bad</a>, and there is no need for one here. I would recommend you avoid this pattern.</p>\n\n<p>There is no way to cleanly exit the program.</p>\n\n<p>Break out some functions, the body of the main calculation function is too long to be easy to understand.</p>\n\n<p>Use <code>std::stringstream</code> and it's formatted input functions to read numbers etc instead of writing your own code for this.</p>\n\n<p>You should use the correct algorithm for parsing mathematical expressions: <a href=\"https://en.m.wikipedia.org/wiki/Shunting-yard_algorithm\" rel=\"noreferrer\">shunting yard algorithm</a>.</p>\n\n<p>Regarding more or less comments. Your code should be structured such that comments are not necessary. Break out functions wherever you think you need a comment and make the function name sat what what your comment would have had is one way to think of it. Of course it's not always possible but it's one way to think about it.</p>\n\n<p>Eg. Instead of having:</p>\n\n<pre><code>// Read in a number from string\n... Lots of code...\n</code></pre>\n\n<p>Do:</p>\n\n<pre><code>auto number = read_number(input_string);\n</code></pre>\n\n<p>If you apply this consistently you'll find that you get more readable and maintainable code with less comments.</p>\n\n<p>I'm missing unit tests, this is an obvious class to test with unit testing to make sure it works and produces the correct result.</p>\n\n<p>I'm going to stop here without going too deep into the technical issues with the code such as using <code>int</code> instead of <code>vector&lt;&gt;::size_type</code> etc because I believe that you have bigger things to address (e.g. use the right algorithm and test your code)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:41:06.263", "Id": "468584", "Score": "0", "body": "Thank you for your in-depth review!\nI do agree that I should've used more functions. The main function body is kind of a mess right now...\n`std::stringstream` looks very interesting. It would've saved me a lot of headaches.\nDoes shunting yard algorithm address input like `2sinxcosx` too? I did consider converting my input into RPN for parsing, but I was concerned about omitted multiplication signs and parantheses. It was a good exercise too, so I decided to write my own algorithm (coming to think of it, it's very similar to RPN)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:44:54.190", "Id": "468585", "Score": "0", "body": "I did use something like unit tests (much less rigorous) when writing my code. I should get into the habit of writing proper unit tests though..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T23:06:30.407", "Id": "468614", "Score": "1", "body": "Worth noting that `M_PI` isn't standard C++. From C++20 there is `std::numbers::pi`, though, I believe." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T14:50:21.313", "Id": "238945", "ParentId": "238937", "Score": "5" } } ]
{ "AcceptedAnswerId": "238945", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T10:53:11.513", "Id": "238937", "Score": "5", "Tags": [ "c++", "calculator" ], "Title": "String Calculator" }
238937
<p>I wanted to optimize the following code in terms of better looking code. The code is finding lowest and highest value used for StochRSI formula. An example might be using LINQ or a different data structure.</p> <pre><code>List&lt;decimal&gt; rsis = new List&lt;decimal&gt;(); decimal lowestLow = 1000000000000000m; decimal highestHigh = -1000000000000000m; decimal[] rsi = CalculateRSI(prices, 14); for (int i = 1; i &lt; price.Length; ++i) { rsis.Insert(0, rsi[i]); if (rsi[i] &gt; highestHigh) highestHigh = rsi[i]; if (rsi[i] &lt; lowestLow) lowestLow = rsi[i]; if (rsis.Count &gt; rsiLength) { decimal last = rsis[rsis.Count - 1]; rsis.RemoveAt(rsis.Count - 1); if (last &gt;= highestHigh || last &lt;= lowestLow) { lowestLow = 1000000000000000; highestHigh = -1000000000000000; for (int l = 0; l &lt; rsis.Count; l++) { if (rsis[l] &gt; highestHigh) highestHigh = rsis[l]; if (rsis[l] &lt; lowestLow) lowestLow = rsis[l]; } } } } </code></pre> <p>This is what <code>decimal[] rsi</code> is. It would be nice if you know a way not to recalculate the entire thing everytime there is a new price added to <code>decimal[] price</code>.</p> <pre><code>public decimal[] CalculateRSI(decimal[] price, int period) { var rsi = new decimal[price.Length]; decimal gain = 0m; decimal loss = 0m; rsi[0] = 0m; for (int i = 1; i &lt;= period; ++i) { var diff = price[i] - price[i - 1]; if (diff &gt;= 0) { gain += diff; } else { loss -= diff; } } decimal avrg = gain / period; decimal avrl = loss / period; decimal rs = gain / loss; rsi[period] = 100m - (100m / (1m + rs)); for (int i = period + 1; i &lt; price.Length; ++i) { var diff = price[i] - price[i - 1]; if (diff &gt;= 0) { avrg = ((avrg * (period - 1)) + diff) / period; avrl = (avrl * (period - 1)) / period; } else { avrl = ((avrl * (period - 1)) - diff) / period; avrg = (avrg * (period - 1)) / period; } rs = avrg / avrl; rsi[i] = 100m - (100m / (1m + rs)); } return rsi; } </code></pre> <h3>Edit:</h3> <p>I did it myself. The only thing left is to calculate the RSI (CalculateRSI) without having to recalculate everything. I know I have to backup the gain/loss but not sure how to do it yet. The reason is because if I have to do that again and again for each new price, which takes a lot of time and I won't be able to catch up on web socket event trigger.</p> <pre><code>// New code var stochs = new decimal[prices.Length]; var rsi = CalculateRSI(prices, 14); var highestHigh = CalculateHighest(rsi, 9); var lowestLow = CalculateLowest(rsi, 9); // Helpers public decimal[] CalculateHighest(decimal[] prices, int period) { var highest = new decimal[prices.Length]; highest[0] = prices[0]; for (int i = 1; i &lt; period; ++i) { if (prices[i] &gt; highest[i - 1]) { highest[i] = prices[i]; } else { highest[i] = highest[i - 1]; } } int highestIdx = 0; for (int i = period; i &lt; prices.Length; ++i) { decimal highestHigh = decimal.MinValue; var start = Math.Max(i - period + 1, highestIdx); for (int s = start; s &lt;= i; ++s) { if (prices[s] &gt; highestHigh) { highestHigh = prices[s]; highestIdx = s; } } highest[i] = highestHigh; } return highest; } public decimal[] CalculateLowest(decimal[] prices, int period) { var lowest = new decimal[prices.Length]; lowest[0] = prices[0]; for (int i = 1; i &lt; period; ++i) { if (prices[i] &lt; lowest[i - 1]) { lowest[i] = prices[i]; } else { lowest[i] = lowest[i - 1]; } } int lowestIdx = 0; for (int i = period; i &lt; prices.Length; ++i) { decimal lowestLow = decimal.MaxValue; var start = Math.Max(i - period + 1, lowestIdx); for (int s = start; s &lt;= i; ++s) { if (prices[s] &lt; lowestLow) { lowestLow = prices[s]; lowestIdx = s; } } lowest[i] = lowestLow; } return lowest; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T14:06:09.257", "Id": "468572", "Score": "7", "body": "_decimal[] rsi = ..._ - please don't elide code; we should see the full code for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:22:30.813", "Id": "468594", "Score": "0", "body": "@Reinderien, it's a decimal[] of RSI values. I pasted the formula for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:21:36.747", "Id": "468698", "Score": "1", "body": "You are ignoring first value from rsi array: `for (int i = 1; i < price.Length; ++i)` and then `rsis.Insert(0, rsi[i]);` This is by design?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:29:26.023", "Id": "468699", "Score": "0", "body": "@Peska, Binance did it that way. Probably not by design, because everyone calculates the RSI this way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:35:08.970", "Id": "468700", "Score": "0", "body": "@Peska, this one is a bit more clear: https://github.com/michaelcostabr/IndicatorsBot/blob/master/IndicatorsBot.Core/Indicators/RSI.cs, not sure if their output is the same (haven't tested it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:50:24.573", "Id": "468717", "Score": "2", "body": "`decimal[] rsi = ...` should still be replaced by the actual call. Don't make us guess. We'll do it wrong, you get a useless answer and we've wasted our time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T22:08:34.950", "Id": "468760", "Score": "0", "body": "@Mast, I did that part myself. You can see my edit. The only part left is to make the `CalculateRSI` method not recalculate everything (all prices) everytime I add a new price. Something like an additional method \"Recalculate(decimal price)` which can be useful when a new price is added. It has to backup the sum somehow." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T11:43:41.490", "Id": "238939", "Score": "5", "Tags": [ "c#" ], "Title": "Finding lowest and highest relative strength index for StochRSI formula" }
238939
<p>I wrote this program in C to solve a given Sudoku puzzle (represented as 2D array) using backtracking algorithm. How can I make it more efficient, maybe faster and more C-onic?</p> <p>This is my first post here, all suggestions are welcome! (be pedantic with me!)</p> <pre><code>#include &lt;stdio.h&gt; #define GRID_SIZE 9 typedef int (*grid)[GRID_SIZE]; typedef struct { int x, y; } v2; void dump(const grid board) { int i, j; for (i = 0; i &lt; GRID_SIZE; ++i) { for (j = 0; j &lt; GRID_SIZE; ++j) printf("%d ", board[i][j]); puts(""); } } int possible(const grid board, const v2 pos, const int v) { int i, j, x0, y0; for (i = 0; i &lt; GRID_SIZE; ++i) if (board[pos.y][i] == v) return 0; for (i = 0; i &lt; GRID_SIZE; ++i) if (board[i][pos.x] == v) return 0; x0 = (pos.x / 3) * 3; y0 = (pos.y / 3) * 3; for (i = 0; i &lt; 3; ++i) for (j = 0; j &lt; 3; ++j) if (board[i + y0][j + x0] == v) return 0; return 1; } void solve(grid board) { int y, x, v; for (y = 0; y &lt; GRID_SIZE; ++y) for (x = 0; x &lt; GRID_SIZE; ++x) if (board[y][x] == 0) { for (v = 1; v &lt; 10; ++v) { const v2 pos = {x, y}; if (possible(board, pos, v)) { board[y][x] = v; solve(board); board[y][x] = 0; } } return; } dump(board); } int main(void) { /* 0 represents an empty cell */ int board[GRID_SIZE][GRID_SIZE] = { {7, 0, 0, 0, 0, 1, 0, 0, 3}, {0, 0, 3, 0, 0, 2, 6, 0, 0}, {0, 2, 0, 7, 0, 8, 0, 0, 5}, {0, 6, 0, 0, 1, 0, 3, 7, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 5, 0, 7, 0, 0, 6, 0}, {3, 0, 0, 2, 0, 4, 0, 5, 0}, {0, 0, 8, 5, 0, 0, 7, 0, 0}, {5, 0, 0, 1, 0, 0, 0, 0, 9}, }; solve(board); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:04:33.727", "Id": "468578", "Score": "0", "body": "This look great, to me. How can it be more efficient? Sudoku solving is a well studied area, one observation is that you can implement 'Algorithm X' https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X which applies to Sudoku https://rafal.io/posts/solving-sudoku-with-dancing-links.html and this will be faster on average. I imagine though that there are faster more bespoke algorithms you could find and implement. Personally I think the nicest thing to do is not any faster, which is to rephrase Sudokus as extending a graph colouring, and instead write an algorithm which extends graph colourings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T07:34:28.837", "Id": "468664", "Score": "0", "body": "There seems to be a key problem with the code. 1) the `board` is declared as a 2 dimensional array of `int`s 2) the `grid` is defined as a single array of 9 pointers to `int`. Therefore, IMO: there is a serious problem with the code logic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:06:57.883", "Id": "468696", "Score": "0", "body": "@user3629249 `grid` is a pointer to an array of `GRID_SIZE` integers. notice the parentheses. a pointer to an array is a 2d array." } ]
[ { "body": "<p>I would tag your <code>struct</code> in addition to, if not instead of, using a <code>typedef</code>:</p>\n\n<pre><code>struct v2\n{\n int x, y;\n};\n// typedef struct v2 v2;\n</code></pre>\n\n<p>Then you can use <code>struct v2</code> wherever you are using <code>v2</code>. This makes it clear that <code>v2</code> is a structure.</p>\n\n<p>I think you should create a symbolic <code>SUBGRID_SIZE</code> instead of using <code>3</code> here:</p>\n\n<pre><code>x0 = (pos.x / 3) * 3;\ny0 = (pos.y / 3) * 3;\n\nfor (i = 0; i &lt; 3; ++i)\n for (j = 0; j &lt; 3; ++j)\n if (board[i + y0][j + x0] == v)\n return 0;\n</code></pre>\n\n<p>This would make it more obvious about what you're dealing with. I would put <code>GRID_SIZE</code> and <code>SUBGRID_SIZE</code> next to each other, and then use an <code>#if</code> to check if they're valid:</p>\n\n<pre><code>#define GRID_SIZE 9\n#define SUBGRID_SIZE 3\n\n#if SUBGRID_SIZE * SUBGRID_SIZE != GRID_SIZE\n# error grid size and subgrid size dont match\n#endif\n</code></pre>\n\n<p>You might use <code>printf(\"\\n\");</code> or <code>putchar('\\n');</code> instead of <code>puts(\"\");</code>. The compiler is likely to optimize the former into <code>puts(\"\");</code> anyway, and the second may be faster.</p>\n\n<p>I like that you've used <code>const</code> everywhere that you're not going to modify a variable. This eliminates chances to make mistakes.</p>\n\n<p>Your formatting is very good. It is consistent, too.</p>\n\n<p>Your code is also well-commented. The only thing that was slightly non-obvious you've commented:</p>\n\n<pre><code>/* 0 represents an empty cell */\n</code></pre>\n\n<p>Being pedantic with you, your code has zero warnings with <code>-Wall -Wextra -std=c99 -pedantic</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:04:29.767", "Id": "468587", "Score": "0", "body": "Thank you for you comment! and, I better `#define` `SUBGRID_SIZE` as sqrt(GRID_SIZE), don't I? then I don't have to change 2 constants, just one.\n(\"It is set on a board with NxN squares where N is a number with a whole-number square root (4x4, 9x9, etc.)\")" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:13:15.703", "Id": "468590", "Score": "0", "body": "@Shechner I have a better solution where `SUBGRID_SIZE` is a constant; see my edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:18:50.190", "Id": "468592", "Score": "0", "body": "I like it, but don't you think sqrting is better since it is dynamic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:20:06.827", "Id": "468593", "Score": "1", "body": "@Shechner `sqrt` gives a `double` result which will cause a conversion to `double` on every iteration. `double` conversion takes time, and a decent amount of it, too. A static constant will almost always be faster, and will leave even less room for errors if you have that `#if` there. For example, if `GRID_SIZE` is `10` and `SUBGRID_SIZE` is `sqrt(GRID_SIZE)` vs. `GRID_SIZE` is `10` and `SUBGRID_SIZE` is `3`; the error in the latter will be caught but the error in the former will not." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T16:21:18.210", "Id": "238948", "ParentId": "238947", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T15:36:55.090", "Id": "238947", "Score": "3", "Tags": [ "algorithm", "c", "sudoku", "backtracking" ], "Title": "C backtracking Sudoku solver" }
238947
<p>I was wondering if you'd be able to review my basic login system that uses sstream and fstream? I feel a lot is wrong with it in terms of efficiency. I've included validation such as if a username already exists they won't be able to use it. </p> <p>To test it works, the text file needs the following format: </p> <blockquote> <p>George,Password,</p> <p>AwesomeUser321,Password123, </p> <p>Jill,Password123,</p> <p>Sam,321Password,</p> </blockquote> <p>I'm hoping the code will be fairly logical. I have commented it for further information.</p> <pre><code>// FileHandling.cpp : This file contains the 'main' function. Program execution begins and ends there. #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; using namespace std; struct User{ string sUsername; string sPassword; }; bool Check_Text_File(vector&lt;User&gt;&amp;objUsers, string &amp;sUsername, string &amp;sPassword) { for(int iCount = 0; iCount &lt; objUsers.size(); iCount++) { if (sUsername == objUsers.at(iCount).sUsername) { cout &lt;&lt; "Sorry, someone already has this username.\n"; cout &lt;&lt; "Try again!\n"; return true; } } return false; } bool Is_Login_Details_Correct(vector&lt;User&gt;&amp;objUsers, string &amp;sUsername, string &amp;sPassword) { for(int iCount = 0; iCount &lt; objUsers.size(); iCount++) { if (sUsername == objUsers.at(iCount).sUsername &amp;&amp; sPassword == objUsers.at(iCount).sPassword) { cout &lt;&lt; "You have successfully logged in.\n"; return true; } } cout &lt;&lt; "Incorrect.\n"; return false; } void Create_Account(vector&lt;User&gt;&amp;objUsers, string &amp;sUsername, string &amp;sPassword) { cout &lt;&lt; "Enter a new username: "; getline(cin &gt;&gt; ws, sUsername); cout &lt;&lt; "Enter your new password: "; getline(cin &gt;&gt; ws, sPassword); } void Append_Credential_To_Text_File(string &amp;sUsername, string &amp;sPassword) { ofstream file; file.open("/Applications/Practice.cpp/Practice.cpp/Practice/doodle/HowQuickly/HowQuickly/new.txt", fstream::app); file &lt;&lt; sUsername &lt;&lt; "," &lt;&lt; sPassword &lt;&lt; ",\n"; file.close(); } void Last_Line_To_Vector(vector&lt;User&gt;&amp;objUsers) { const std::string filename = "/Applications/Practice.cpp/Practice.cpp/Practice/doodle/HowQuickly/HowQuickly/new.txt"; std::ifstream fs; fs.open(filename.c_str(), std::fstream::in); if(fs.is_open()) { //Got to the last character before EOF fs.seekg(-1, std::ios_base::end); if(fs.peek() == '\n') { //Start searching for \n occurrences fs.seekg(-1, std::ios_base::cur); long int i = fs.tellg(); for(i;i &gt; 0; i--) { if(fs.peek() == '\n') { //Found fs.get(); break; } //Move one character back fs.seekg(i, std::ios_base::beg); } } std::string lastline; getline(fs, lastline); std::cout &lt;&lt; lastline &lt;&lt; std::endl; string sResult = ""; stringstream ssSplit(lastline); vector&lt;string&gt;objSplit; objUsers.push_back(User()); objSplit.resize(0); while (getline(ssSplit, sResult, ',')) { objSplit.push_back(sResult); } objUsers.at(objUsers.size() - 1).sUsername = objSplit.at(0); objUsers.at(objUsers.size() - 1).sPassword = objSplit.at(1); } } void Add_Text_File_To_Vector(vector&lt;User&gt;&amp;objUsers, vector&lt;string&gt;&amp;objSplit){ string sLine = ""; string sResult = ""; ifstream file3("/Applications/Practice.cpp/Practice.cpp/Practice/doodle/HowQuickly/HowQuickly/new.txt"); if(objUsers.size() == 0) { while (getline(file3, sLine)) { stringstream ssSplit(sLine); objUsers.push_back(User()); objSplit.resize(0); while (getline(ssSplit, sResult, ',')) { objSplit.push_back(sResult); } objUsers.at(objUsers.size() - 1).sUsername = objSplit.at(0); objUsers.at(objUsers.size() - 1).sPassword = objSplit.at(1); } } } void Login_To_Account(vector&lt;User&gt;&amp;objUsers) { string sUsername; string sPassword; cout &lt;&lt; "Enter your username: "; cin &gt;&gt; sUsername; cout &lt;&lt; "Enter your password: "; cin &gt;&gt; sPassword; } int main() { string sUsername; string sPassword; vector&lt;User&gt;objUsers; vector&lt;string&gt;objSplit; //Add_Text_File_To_Vector() function reads everything from the file to the struct object objUsers before the user can subsequntly append a new detail which will be formatted in accordance to the format presented in the text file. Add_Text_File_To_Vector(objUsers, objSplit); do { Create_Account(objUsers, sUsername,sPassword); } while(Check_Text_File(objUsers, sUsername, sPassword)); //The Append_Crendential_To_Text_File() function appends the new login details the user types in the function "Create_Account()". Append_Credential_To_Text_File(sUsername, sPassword); //The Last_Line_To_Vector appends the newly added credential to the vector, instead of re-writing the entire vector. Last_Line_To_Vector(objUsers); do { Login_To_Account(objUsers); }while(Is_Login_Details_Correct(objUsers, sUsername, sPassword) == false); } </code></pre>
[]
[ { "body": "<p>I think this code is very basic. I didn't look very deeply inside it and didn't bother to run it. I think I can give you some advices without it. I only looked at readability not efficiency, which when you are using standard c++ should be fine in most cases. You should usually be woried about efficiency only when you detect there is problem with it and it matters. There were some highlights in your code but there are things you should work at.</p>\n\n<ol>\n<li><p>hungarian notation. I don't want to get into this discussion, but I think nowadays it's not popular to use it. So imho:\nsUsername should be called username.\nsPassword - password\nobjUsers - users\netc...</p></li>\n<li><p>Lines in comments shouldn't be longer than code itself. It's very annoying to reader.</p></li>\n<li><p>In Add_Text_File_To_Vector:</p></li>\n</ol>\n\n<p>file3 should be passed as argument (type of argument should be const std::istream &amp;) and why is it called file3? Where is file1, file2...</p>\n\n<p>Name of file should not be inside function. Functions should be generic, works in different environments. This is gonna work only in your filesystem with your directory structure. </p>\n\n<p>You could define file in main in first line, eg:</p>\n\n<pre><code>std::string inputFilePath = \"/Applications/Practice.cpp/Practice.cpp/Practice/doodle/HowQuickly/HowQuickly/new.txt\"\n</code></pre>\n\n<p>Or better yet, program filename could be argument to program. I mean you could change <code>int main()</code> to <code>int main(int argc, char** argv)</code> and pass it as argv. This way you could try different input files without recompiling program.</p>\n\n<p>Potential reviewer have to dive deep into your code to even run it.</p>\n\n<p>I don't understand the point of this:</p>\n\n<pre><code>if (objUsers.size() == 0) {\n // loop code\n}\n</code></pre>\n\n<p>You should just write code without this if condition.\nWithout it program is gonna work the same way and function will be simpler and more generic. If you realy wanted to kind of assert, that input is correct you could write: <code>assert(objUsers.size() == 0)</code>\nThis way program would immediately stopped on error - and this is good behavior for most programs.</p>\n\n<p>It was very hard to figure out what <code>objSplit</code> is for. But I think you wanted to do some optimization because I don't see it is used anywhere. I think you should create this vector inside function. You shouldn't bother reader of your high level code with this low level detail. If it is realy true (it's not obvious), that resize(0) is faster than creating objSplit from scratch every time and it is realy gonna make a difference than you could make it a global variable. Premature optimization are usualy harmfull and this was very harmfull for readability. And it was not said in comment. I had to figure it out by myself. Comment near the function only stated obvious thing that I figured out before I read it.</p>\n\n<p>I think this singature of function would be better:</p>\n\n<pre><code> Read_Users_List(const istream &amp; input, vector&lt;User&gt;&amp; users) {}\n</code></pre>\n\n<ol start=\"4\">\n<li>In Create_Account</li>\n</ol>\n\n<p>you passed objUsers but function don't use it. This is plain wrong and hurts readability.</p>\n\n<p>5 Check_Text_File</p>\n\n<p>name of function is a lie. It doesn't check any text file inside it. It should be called for example Is_Username_Unique.\nAnd it should not has sPassword as argument, because it is not used anywhere.</p>\n\n<p>If you use c++11 you could exchange:</p>\n\n<pre><code>for(int iCount = 0; iCount &lt; objUsers.size(); iCount++)\n</code></pre>\n\n<p>with </p>\n\n<pre><code>for (const auto &amp; user : objUsers)\n</code></pre>\n\n<p>and than use:</p>\n\n<pre><code>if (sUsername == user.sUsername)\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>if (sUsername == objUsers.at(iCount).sUsername)\n</code></pre>\n\n<p>It is important to use this whenever you can. Because it is easier to read and more errorproof.</p>\n\n<ol start=\"6\">\n<li>Append_Credential_To_Text_File</li>\n</ol>\n\n<p>You hardcoded name of the file with credentials. You write the same name of the file twice in your code. This is the worst thing you done so far. You should pass the name of file as argument or at least make it a global variable. In this program you have to change one thing in two places. \nIf i wanted to run this, I'd have to change the path in two places.</p>\n\n<ol start=\"7\">\n<li>Last_Line_To_Vector:</li>\n</ol>\n\n<p>the same filename again...\nThis has so much duplication in it... and it is sooo complex. \nCouldn't you just write </p>\n\n<pre><code>objUsers.push_back({sUsername, sPassword}); \n</code></pre>\n\n<p>instead:</p>\n\n<pre><code>Last_Line_To_Vector(objUsers);\n</code></pre>\n\n<p>Or at least you could write:</p>\n\n<pre><code>User objUser;\nobjUser.sUsername = sUsername;\nobjUser.sPassword = sPassword;\nobjUsers.push_back(objUser);\n</code></pre>\n\n<p>If I understood correctly that this is what you wanted to do...</p>\n\n<ol start=\"8\">\n<li>Login_To_Account</li>\n</ol>\n\n<p>sUsername and sPassword does nothing. Shouldn't you return it somehow from function, for example add arguments <code>string &amp; sUsername</code>, <code>string &amp; sPassword</code> \nthan Is_Login_Details_Correct would have more sense... You should pass to this function the same credentials.</p>\n\n<pre><code>while(Is_Login_Details_Correct(objUsers, sUsername, sPassword) == false);\n</code></pre>\n\n<p>should be just:</p>\n\n<pre><code>while(not Is_Login_Details_Correct(objUsers, sUsername, sPassword));\n</code></pre>\n\n<p>There are more things that could be done better, but let's start with this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T14:59:07.933", "Id": "533126", "Score": "0", "body": "I am looking back at old questions and I am so sorry I never thanked you for your answer. I found this very beneficial!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:38:13.027", "Id": "238958", "ParentId": "238952", "Score": "3" } } ]
{ "AcceptedAnswerId": "238958", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T17:32:27.247", "Id": "238952", "Score": "1", "Tags": [ "c++", "c++11" ], "Title": "Basic login system that uses credentials from text file" }
238952
<p>I wrote my first unit testing code on a service class using Mockito. The code looks like this:</p> <pre><code>// Test Class public class TestVideoService { private VideoService videoService; @Mock private VideoRepository videoRepository; @Rule public MockitoRule mRule = MockitoJUnit.rule(); @Before public void setUp(){ this.videoService = new VideoService(videoRepository); } @Test public void testGetAllVideos() throws Exception{ when(videoRepository.findAll()).thenReturn(new ArrayList&lt;Video&gt;()); assertEquals(new ArrayList&lt;Video&gt;(), videoService.getAllVideos(), "tested"); } } </code></pre> <p>I also have several questions. I feel like I'm just comparing the same mock values (ArrayList of Video) – what's the point of doing this, or am I just doing it the wrong way?</p> <p>Some other classes:</p> <pre><code>@Service public class VideoService { @Autowired private VideoRepository videoRepository; public VideoService(VideoRepository videoRepository){ this.videoRepository = videoRepository; } public List&lt;Video&gt; getAllVideos(){ return videoRepository.findAll(); } } @Repository public interface VideoRepository extends JpaRepository&lt;Video, Long&gt; { } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T11:32:04.403", "Id": "468694", "Score": "1", "body": "You are still using JUnit4: Switch to JUnit5." } ]
[ { "body": "<p>Welcome to code review and thanks for sharing your code.</p>\n\n<p>When writing UnitTests keep in mind that they are <strong>documentation</strong>. \nTest code has less restrictions for identifier names.\nThis means that method names are usually longer and you should not \"shorten\" your unit test methods.</p>\n\n<ol>\n<li><p>The <em>test name</em> should describe the expected behavior <strong>in detail</strong></p>\n\n<pre><code>@Test\npublic void getAllVideos_returnsCompleteListFromRepository() throws Exception{ \n // ...\n</code></pre></li>\n<li><p>A unit test always has three parts: <code>arrange</code>, <code>act</code> and <code>assert</code>. \nYou should always have this three parts visible in your test methods. </p>\n\n<p>In your example you do the <code>act</code> part implicitly in the <code>assert</code> line. \nThis prevents you from introducing variable that could give useful information about the result:</p>\n\n<pre><code>@Test\npublic void getAllVideos_returnsCompleteListFromRepository()\n // arrange \n List&lt;Video&gt; allVideosInRepository = new ArrayList&lt;&gt;();\n when(videoRepository.findAll()).thenReturn(new ArrayList&lt;Video&gt;());\n // act\n List&lt;&gt; allVideosFromRepository = videoService.getAllVideos();\n // assert\n assertEquals(allVideosInRepository, allVideosFromRepository, \"tested\");\n}\n</code></pre>\n\n<p>For the same reason the <code>String</code> parameter of the <code>assert*</code> method should always be a useful hint in case the test fails because it is part of the error message:</p>\n\n<pre><code> assertEquals(allVideosInRepository,\n allVideosFromRepository,\n \"is same object\");\n</code></pre></li>\n</ol>\n\n<hr>\n\n<blockquote>\n <p>I feel like i just compare the same mock values ArrayList of Video and what's the point of doing this or i just do it wrong way.</p>\n</blockquote>\n\n<p>This is not a problem of your unit tests but of your current design. </p>\n\n<p>For the time being your <code>VideoService</code> class is nothing more than a <em>facade</em> to a <code>Collection</code>, there is no business behavior (yet) to be tested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T04:43:14.740", "Id": "468641", "Score": "4", "body": "The AAA pattern is interesting, I learned them as Given, When and Then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:56:34.693", "Id": "468671", "Score": "2", "body": "@l0b0 Yes, it they are synonym, but IMHO it is easier to memorize that your tests should have AAA quality rating (like stocks)... ;o)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T22:22:50.723", "Id": "238966", "ParentId": "238954", "Score": "18" } }, { "body": "<p>The idea of the test class is ok: you want to test the service, mock the repository and you check on the outcome.</p>\n\n<p>In the test, it would be nice to use the AAA (arrange/act/assert) pattern. In my tests, i call these setup, execute and verify.</p>\n\n<p>There is no logic in the service layer, and your method returns the database objects.\nAlso you only have one test, with an empty arraylist. What if you find 1,2,..1000 items. What would you return, the whole list or the first 10,...\nAdditional questions you can have: In what order are they returned? Are you handling errors,...</p>\n\n<p>Imagine some logic on your service layer and these tests will get more to it </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T22:31:02.413", "Id": "238967", "ParentId": "238954", "Score": "8" } }, { "body": "<p>Some notes:</p>\n\n<ol>\n<li>If you're using mocks you are pretty much by definition doing <em>integration</em> rather than unit testing, because mocks enable you to test how a piece of code <em>integrates</em> with something else having a specific behaviour.</li>\n<li>The primary goal of tests is to gain confidence that the code does what you expect. A sub-goal of this is clarity - the test should be as simple as possible while demonstrating something new and non-trivial about the code under test. Because of these I would inline <code>setUp</code> until you add more test cases which definitely need the exact same preconditions.</li>\n<li>A useful pattern for test names is that they should have a name starting with the word <em>\"should\"</em> which says exactly and only <em>what the test is meant to demonstrate.</em> This is much more helpful than the \"test\" prefix, which encourages test names which only say which <em>method</em> is being tested. So if you're trying to test that <code>getAllVideos</code> simply forwards the response from the video repository's <code>findAll</code> you could name it something like <code>getAllVideosShouldReturnVideoRepositoryFindAllReturnValue</code>. At this point it's pretty obvious that the service isn't actually doing anything interesting yet — a better implementation would have no video repository at all — you might as well skip this test and think of the simplest <em>interesting</em> thing that the code could do, such as counting videos, filtering videos by some property, or something else entirely.</li>\n<li>The third argument to <code>assertEquals</code> is only useful so long as it actually conveys something about the test which the assertion output doesn't already convey. This becomes super clear with TDD, because you always run the failing test before implementing the production code, so you get to check whether the error message is useful enough to debug the problem when the test inevitably fails in the future.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:52:57.210", "Id": "468670", "Score": "2", "body": "to 1. No, it is the opposite. The definition of a *unit test* is to test the logic of your unit **in isolation**, and you need Mocks to cut of possibly changing behavior of other units your unit under test depends on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T09:00:49.257", "Id": "468675", "Score": "1", "body": "to 4: The name of the test method should describe the **business behavior** expected while the `String` argument of the `assert*` method should clarify the **technical expectation** not met." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:20:37.227", "Id": "468681", "Score": "2", "body": "Not really.... I think point 1 is mistaken" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T11:44:24.910", "Id": "468695", "Score": "3", "body": "I really disagree with the first point. A class has dependencies that are (hopefully) loosely coupled through an interface. In unit-testing, you are testing a single *unit* of code (a class). Mocking the dependencies is the only way to test one unit, while instantiating and initializing all the dependencies is an integration test." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T05:04:48.450", "Id": "238978", "ParentId": "238954", "Score": "4" } }, { "body": "<p>Testing strategy seems like it might be a bit out of scope for Code Review, but having historically also found this process a bit confusing, my suggestion would be to not explicitly test your <code>VideoService</code> class. Test its consumers.</p>\n\n<p>It's not necessary (or desirable) for there to be a one-to-one mapping of test classes to implementation classes. Your entry point to your tests should be your API - the point from which you can perform a useful operation (this can be your definition of a \"unit\") - in the case of a REST API this is probably your controller class. You might still end up with the situation where you end up with a mock repository which does the same as you have now, but you should be able to test all the other collaborators using their actual implementations rather than mocks. This way you will end up with less brittle tests, since you won't be mocking out all your collaborators and you won't have to update all those mocks if some behaviour changes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:04:46.137", "Id": "238984", "ParentId": "238954", "Score": "2" } } ]
{ "AcceptedAnswerId": "238966", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T18:23:08.083", "Id": "238954", "Score": "14", "Tags": [ "java", "unit-testing", "spring", "spring-mvc" ], "Title": "Unit testing Video Service class" }
238954
<p>I wrote the following C program to compare software version strings. Please provide any general feedback you'd like, but with special focus on error handling decisions, user input validation/sanitation, and robustness. My end-goal is for the program to properly handle user input and not have non-graceful crashes, etc... A couple of known issues/concerns I already have (but haven't decided on a solution for yet) is, where should I be handling errors? Should I be printing to <code>stderr</code> only in the driver (main) program and leave all of that out of the main "library" code? Secondly, I have an <code>enum</code> definitionn for <code>FAIL</code> but I never actually use it because when I wrote the <code>switch</code> clause, I thought it may be a better idea to just <code>default</code> to error rather than select it explicitly. I'm not sure if this is the best choice. This was compiled with GCC 7.5.0 for Linux 64-bit on my end.</p> <p>The program is only intended to work with inputs with 4 version numbers concatenated with a <code>.</code> for now. I also need to build out a better driver which accepts actual user input eventually of course.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;assert.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; enum VERSION_RESULT { FAIL = -1, LEFT = 1, RIGHT = 2, EQUAL = 3 }; typedef struct _version { unsigned int major; unsigned int minor; unsigned int build; unsigned int revision; } VERSION; VERSION *version_new(char *str); int version_parse(VERSION *pVer, char *str); bool validate_version_string(char *str); void version_print(VERSION *pVer); void version_compare_print(VERSION *pL, VERSION *pR); int main() { char ver_string[] = {'5','.','2','5','.','5','.','0','\0'}; // CANNOT use read-only memory due to strtok char ver_string2[] = {'5','.','5','.','5','.','1','\0'}; VERSION *ver = version_new(ver_string); VERSION *ver2 = version_new(ver_string2); version_compare_print(ver, ver2); free(ver); free(ver2); ver = NULL; ver2 = NULL; return EXIT_SUCCESS; } VERSION *version_new(char *str) { assert(str); VERSION *pVer = malloc(sizeof(VERSION)); assert(pVer); int result = version_parse(pVer, str); if(result == -1) { fprintf(stderr, "Failed to parse version from string.\n"); free(pVer); return NULL; } return pVer; } int version_parse(VERSION *pVer, char * str) { assert(pVer &amp;&amp; str); if(!validate_version_string(str)) { fprintf(stderr, "Invalid version #. Format xxx.xxx.xxx.xxx\n"); return -1; } char *token; char *delim = "."; token = strtok(str, delim); pVer-&gt;major = (unsigned int) atoi(token); token = strtok(NULL, delim); pVer-&gt;minor = (unsigned int) atoi(token); token = strtok(NULL, delim); pVer-&gt;build = (unsigned int) atoi(token); token = strtok(NULL, delim); pVer-&gt;revision = (unsigned int) atoi(token); } bool validate_version_string(char *str) { assert(str); unsigned int count = 0; char *copy; char tmp; for(copy = str; *copy != '\0'; ++copy) { tmp = *copy; if(tmp == '.') ++count; if((tmp &gt; '9' || tmp &lt; '0') &amp;&amp; tmp != '.') return false; } if(count == 3) return true; return false; } void version_print(VERSION *pVer) { assert(pVer); printf("%u.%u.%u.%u", pVer-&gt;major,pVer-&gt;minor,pVer-&gt;build,pVer-&gt;revision); return; } /* * Compare 2 versions. Return -1 if error, 1 if left is largest, 2 if right is largest, 3 if equal */ enum VERSION_RESULT version_compare(VERSION *pL, VERSION *pR) { assert(pL &amp;&amp; pR); //Major checks if(pL-&gt;major &gt; pR-&gt;major) return LEFT; if(pR-&gt;major &gt; pL-&gt;major) return RIGHT; //Majors are equal if(pL-&gt;minor &gt; pR-&gt;minor) return LEFT; if(pR-&gt;minor &gt; pL-&gt;minor) return RIGHT; //Minors are equal if(pL-&gt;build &gt; pR-&gt;build) return LEFT; if(pR-&gt;build &gt; pL-&gt;build) return RIGHT; //Builds are equal if(pL-&gt;revision &gt; pR-&gt;revision) return LEFT; if(pR-&gt;revision &gt; pL-&gt;revision) return RIGHT; //Revisions are equal return EQUAL; } void version_compare_print(VERSION *pL, VERSION *pR) { assert(pL &amp;&amp; pR); switch(version_compare(pL, pR)) { case LEFT: version_print(pL); printf(" &gt; "); version_print(pR); putchar('\n'); break; case RIGHT: version_print(pL); printf(" &lt; "); version_print(pR); putchar('\n'); break; case EQUAL: version_print(pL); printf(" == "); version_print(pR); putchar('\n'); break; default: fprintf(stderr, "An error occurred in the version compare function.\n"); } return; } </code></pre>
[]
[ { "body": "<p>The validation of the string seems to leave some gaps. For instance, the version numbers seem to be valid whatever size they have. They could be zero digits large, or contain so many digits that they would not fit into an integer.</p>\n\n<p>I'd try not to print to standard error if this is supposed to be used as a library. In that case you might want to use separate header files, c code and test code of course as well.</p>\n\n<p>I'd keep <code>version_compare_print</code> possibly out of the library; at the very least it should otherwise just populate a string pointer rather than print it to standard out. <code>version_print</code> makes more sense, but it should also populate a string. Then the application can print it to standard output. Probably best to call it <code>version_sprint</code>.</p>\n\n<h2>Coding remarks</h2>\n\n<p><strong>main</strong></p>\n\n<p>I'm not sure if setting:</p>\n\n<pre><code>ver = NULL;\n</code></pre>\n\n<p>does any good for a local variable, after you've already freed it.</p>\n\n<p><strong>version_new</strong></p>\n\n<p>I'm not sure if this function should be there at all, just let the caller perform the <code>malloc</code> and call <code>version_parse</code>. They'll have to <code>dealloc</code> anyway.</p>\n\n<p><strong>version_parse</strong></p>\n\n<pre><code>unsigned int count = 0;\n</code></pre>\n\n<p>Count of what? You should make that explicit in the variable name (<code>delimiter_count</code> seems logical).</p>\n\n<pre><code>char *copy;\n</code></pre>\n\n<p>This doesn't seem to operate on a copy - just on a copy of the reference; just call it <code>position</code> or something similar.</p>\n\n<pre><code>return -1;\n</code></pre>\n\n<p>You're hiding the error code. Either you should probably upgrade to a more application specific code or just return the code you're given. Currently it is possible to read the error from standard error stream, but the calling method will be left in the dark.</p>\n\n<p><strong>version_compare</strong></p>\n\n<p>Compare almost always use a negative value if the leftmost parameter is smaller than the second, zero if they are equal and a positive value if the leftmost parameter is great than the second.</p>\n\n<p>As you don't seem to use FAIL value anyway (and since you use pointers to the already parsed versions), I think it is best to keep to that.</p>\n\n<p><strong>version_compare_print</strong></p>\n\n<p>I'm not sure if this should be a special function; better keep it with <code>main</code> or at least explain <em>what</em> it does.</p>\n\n<p>There is a lot of repetition in the code. You could just set a variable to <code>\"&lt;\"</code>, <code>\"==\"</code> or <code>\"&gt;\"</code> and then perform the print after the switch.</p>\n\n<p>The final <code>return</code> statement seems rather useless; nothing is returned and the method is at the end.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:14:02.740", "Id": "468679", "Score": "3", "body": "Setting freed variables to null instead of letting them dangle makes it much easier to find use after free errors. It's not that uncommon, although usually someone writes a macro for it sooner than later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:28:39.067", "Id": "468683", "Score": "1", "body": "It seems to me that for local variables it just adds to the clutter; I can see this spill over from pointers in other locations though. Maybe I'm too used to Java where null pointers are commonly the *cause* of problems, not part of the solution to problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:30:04.697", "Id": "468684", "Score": "0", "body": "The corresponding situation in Java would be a disposed object being accessed. Which is also really bad, if generally a bit easier to diagnose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:33:18.640", "Id": "468685", "Score": "0", "body": "And a lot less common, since objects are disposed if there are no references to them left... Exactly the situation that would trigger the error is used to keep the system from disposing the object. Weak references (not a commonly used structure outside of caching) are the one exception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:37:43.743", "Id": "468686", "Score": "1", "body": "No not GCed objects (which yes I guess with resurrection that would be a problem), but .NET got me. I meant the Closeable interfaces (try with resources and so) Say using a file reader after it has been closed. Also with try-with-resources not a problem in general because you limit the scope to its lifetime, but if you can't (say it's a member) setting those to null is a good idea too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:47:13.693", "Id": "468688", "Score": "0", "body": "Generally I'd make that class an auto-closeable too, and still use try-with-resources. But yeah, in the case of resources more care is required. Setting it to `null` is a dangerous proposition; due to GC you don't know when the destructor of the resource will be called after all; it could well survive until the end of the application (and in the case of application servers, that could be about forever). So it may help *a bit*, but just closing it is the only fail safe way..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:53:34.767", "Id": "468689", "Score": "1", "body": "Well that's the problem trying to find analogies for constructs in other languages (my point wasn't to speed up GC, but to make it harder for someone to access a closed resource afterwards). The main point is that there's no downside to setting the variable to NULL, while it can help avoid a common programming error (use after free errors are a very common security exploit after all)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:50:29.133", "Id": "468704", "Score": "1", "body": "Maarten Bodewes, \"I'm not sure if setting: `ver = NULL;` does any good\". This is an OK C idiom. It has marginal cost yet marginal value, so a such if fine to have, fine to not have. Follow group's coding guidelines here. @Voo, In cases where `ver` is not used later, it may get optimized out, so provides no improved security. Agree about ease for debugging." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:50:14.390", "Id": "238960", "ParentId": "238956", "Score": "5" } }, { "body": "<p>Instead of spelling out every single element of the array,</p>\n\n<pre><code>char ver_string[] = {'5','.','2','5','.','5','.','0','\\0'};\n</code></pre>\n\n<p>just use a string literal. It's the same thing:</p>\n\n<pre><code>char ver_string[] = \"5.25.5.0\";\n</code></pre>\n\n<blockquote>\n <p>Should I be printing to stderr only in the driver (main) program and leave all of that out of the main \"library\" code?</p>\n</blockquote>\n\n<p>Yes, exactly. You can return error codes and set <code>errno</code> to be more specific.</p>\n\n<blockquote>\n <p>Secondly, I have an <code>enum</code> definitionn for <code>FAIL</code> but I never actually use it because when I wrote the switch clause, I thought it may be a better idea to just default to error rather than select it explicitly.</p>\n</blockquote>\n\n<p>That's fine. Anything other than a valid input is an invalid input.</p>\n\n<p>You don't return a value from <code>version_parse</code> even though it looks like you even inserted a newline where it was supposed to go.</p>\n\n<p>Instead of using <code>LEFT</code> and <code>RIGHT</code>, I would use <code>GREATER</code> and <code>LESS</code>. Those names convey more meaning to me.</p>\n\n<p>Usually, functions that don't take values have an unnamed <code>void</code> parameter. I suggest doing that with <code>main</code>, because it might be undefined behavior if you don't:</p>\n\n<pre><code>int main(void)\n{\n</code></pre>\n\n<p>(I also fixed up the formatting to make it more consistent.)</p>\n\n<p>In <code>validate_version_string</code>, <code>tmp</code> and <code>copy</code> are unnecessary. Just use <code>str</code> and <code>*str</code>, like so:</p>\n\n<pre><code>for(; *str != '\\0'; ++str)\n{\n if(*str == '.') ++count;\n if((*str &gt; '9' || *str &lt; '0') &amp;&amp; *str != '.') return false;\n}\n</code></pre>\n\n<p>You may think that removing <code>tmp</code> is bad for performance, but it's not; in any nonzero optimization level, these are equivalent.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:52:54.090", "Id": "238962", "ParentId": "238956", "Score": "7" } }, { "body": "<ul>\n<li><p>Don't <code>strtok</code> + <code>atoi</code>. Use <code>strtol</code>, which (a) doesn't need a mutable input, (b) has much better error handling and reporting, and (c) eliminates the need for independent validation. An example of use would be</p>\n\n<pre><code>char * end;\n\npVer-&gt;major = strtol(str, &amp;end, 0);\nif (*end != '.') {\n // major is not a number.\n return suitable_failure;\n}\nstr = end + 1;\n\npVer-&gt;minor = strtol(str, &amp;end, 0);\n// etc, and keep going with other pieces of a version.\n// After revision is computed, *end must be 0\n</code></pre></li>\n<li><p>Instead of spelling out the field names, have an array. Then you could wrap the repeated number parsing in a loop.</p></li>\n<li><p>I don't see the need for a dynamic allocation. <code>VERSION</code> is simple <code>struct</code>, and <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged &#39;c&#39;\" rel=\"tag\">c</a> would be happy to return it:</p>\n\n<pre><code>VERSION version_new(char * str)\n{\n VERSION v;\n ....\n return v;\n}\n\nint main()\n{\n ....\n VERSION ver1 = version_new(str);\n // etc\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T06:06:11.503", "Id": "468644", "Score": "0", "body": "@vnp to clarify, you mean don't use the struct fields but just use an array? Re: \"\n\nInstead of spelling out the field names, have an array. Then you could wrap the repeated number parsing in a loop.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T12:41:51.333", "Id": "468703", "Score": "4", "body": "As `major` is unsigned, `strtoul()` makes more sense then `strtol()` here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T21:29:07.083", "Id": "238964", "ParentId": "238956", "Score": "11" } }, { "body": "<p>A small version compare improvement would perform up to n +1 rather than 2n compares.</p>\n\n<p>Instead of </p>\n\n<pre><code>if(pL-&gt;major &gt; pR-&gt;major) return LEFT;\nif(pR-&gt;major &gt; pL-&gt;major) return RIGHT;\n\nif(pL-&gt;minor &gt; pR-&gt;minor) return LEFT;\nif(pR-&gt;minor &gt; pL-&gt;minor) return RIGHT;\n...\n</code></pre>\n\n<p>Compare for equality first:</p>\n\n<pre><code>if(pL-&gt;major != pR-&gt;major) {\n return pL-&gt;major &gt; pR-&gt;major ? LEFT : RIGHT;\n}\n\nif(pL-&gt;minor != pR-&gt;minor) {\n return pL-&gt;minor &gt; pR-&gt;minor ? LEFT : RIGHT;\n}\n...\n</code></pre>\n\n<p>Yet since such code is not likely to be in a critical path, coding for clarity likely overrides.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T13:29:08.693", "Id": "238996", "ParentId": "238956", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T20:19:18.113", "Id": "238956", "Score": "13", "Tags": [ "c", "strings", "validation" ], "Title": "C Program which compares software version strings" }
238956
<blockquote> <p>Given an array of numbers arr and a window of size k, print out the median of each window of size k starting from the left and moving right by one position each time.</p> <p>For example, given the following array and k = 3:</p> <p>[-1, 5, 13, 8, 2, 3, 3, 1]</p> <p>Your function should print out the following:</p> <p>5 &lt;- median of [-1, 5, 13]<br> 8 &lt;- median of [5, 13, 8]<br> 8 &lt;- median of [13, 8, 2]<br> 3 &lt;- median of [8, 2, 3]<br> 3 &lt;- median of [2, 3, 3]<br> 3 &lt;- median of [3, 3, 1]</p> <p>Recall that the median of an even-sized list is the average of the two middle numbers.</p> </blockquote> <p><strong>Is there any improvement possible in this implementation?</strong></p> <pre><code> #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;array&gt; #include &lt;algorithm&gt; template &lt;typename T&gt; struct range { auto begin()const {return a; } auto end()const {return b;} T a,b; }; range&lt;const int*&gt;make_range(const int* begin, const int* end) { return {begin, end}; } range&lt;const int *&gt; make_window(const std::vector&lt;int&gt;&amp; vec, size_t start, size_t end) { return make_range(vec.data() + start, vec.data() + end); } int median(int arr[], size_t N) { //sort the array std::sort(arr, arr + N); if(N % 2 == 0) return (arr[N/2 - 1] + arr[N/2])/2; return arr[N/2]; } int main(){ const auto window_length = 3; std::vector&lt;int&gt; input{-1, 5, 13, 8, 2, 3, 3, 1}; const auto end_length = input.size() - window_length; std::array&lt;int, window_length&gt; arr{}; for(size_t i(0); i &lt; end_length; i++) { int counter (0); const auto window = make_window(input, i, i + window_length); for(const auto&amp; value : window) { std::cout &lt;&lt; value &lt;&lt; ' '; arr[counter++] = value; } int result = median(arr.data(), arr.size()); counter = 0; std::cout &lt;&lt; "\nmedian " &lt;&lt; result &lt;&lt; '\n'; std::cout &lt;&lt; '\n'; } return EXIT_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T22:30:54.767", "Id": "468613", "Score": "1", "body": "Formatting seems a bit off." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:14:11.700", "Id": "468733", "Score": "0", "body": "Are you considering efficiency when you wrote \"improvement\". If yes, what are the maximum values of `N` and `k` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:16:51.523", "Id": "468734", "Score": "0", "body": "@Damien as u can see from statement \" Given an array of numbers arr and a window of size k \" , it can be change anytime, dynamic." } ]
[ { "body": "<p>My main issue is that the median function takes a C-style array. Generally C-style arrays are avoided in modern C++. It would be much better if it took an <code>std::array</code>, set or vector as its input. </p>\n\n<p>Similarly, your make window function seems mostly unnecessary. It should only take one or two lines to get the window from the array.</p>\n\n<p>In general there is very rarely a good reason to use use the <code>data()</code> functions on on STL containers; you should just use the container instead.</p>\n\n<p>Other minor points:</p>\n\n<p>There is some inconsistent formatting in number of spaces and <code>{}</code> positioning. Not a major issue but make things harder to read.</p>\n\n<p><code>main()</code> doesn't strictly need a return statement and will return 0 by default if no value is given.</p>\n\n<p>You've included <code>&lt;algorithm&gt;</code> but haven't used anything from it.</p>\n\n<p>Given these changes, my version looks like:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nint median( const std::vector&lt; int &gt;&amp; window )\n{\n const size_t N = window.size();\n if ( N % 2 == 0 )\n return ( window[N / 2 - 1] + window[N / 2] ) / 2;\n return window[N / 2];\n}\n\nint main()\n{\n const auto window_length = 3;\n std::vector&lt; int &gt; input{ -1, 5, 13, 8, 2, 3, 3, 1 };\n\n for ( auto it = input.begin(); it != input.end()-window_length+1; ++it )\n {\n std::vector&lt; int &gt; window( it, it + window_length );\n\n for ( const auto&amp; value : window )\n {\n std::cout &lt;&lt; value &lt;&lt; ' ';\n }\n\n std::sort( window.begin(), window.end() );\n int result = median( window );\n std::cout &lt;&lt; \"\\nmedian \" &lt;&lt; result &lt;&lt; '\\n';\n std::cout &lt;&lt; '\\n';\n }\n}\n</code></pre>\n\n<p>Another issue I haven't considered. If you take the median of 3, 4 I would expect 3.5, but your code does integer division and returns an <code>int</code> from <code>median()</code>, so will return 3. Not clear whether this is intentional or an oversight.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:12:46.117", "Id": "468732", "Score": "0", "body": "Thank you for you ideas. Yes, intentional to use int. \nYes, i tried using std::array, but was little bit confused, how use in median. But now is more clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T07:09:57.760", "Id": "468793", "Score": "1", "body": "`sort` should probably be called inside `median`, because it is a step of calculating the median (there are more efficient ways, of course). So let `median` take the vector by value and move the window into it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T16:04:58.860", "Id": "239004", "ParentId": "238963", "Score": "3" } }, { "body": "<p>This compiles cleanly and produces reasonable integer output (though not in the format required by the problem statement).</p>\n\n<p>Note that you are required to include <code>&lt;cstdlib&gt;</code> before using <code>EXIT_SUCCESS</code>; failing to do so may be a portability bug.</p>\n\n<p>All that copying and sorting gets expensive as the input and <code>k</code> both get larger. We should probably create a stateful class that we can update with the new right-most value and the left-most to be removed. I'd probably implement that with two sets - one holding values lower than the median and one holding higher values. When we shift the window by one position, then we update the two sets and move an element if necessary to balance them (remember that because a set is sorted, it's easy to find the lowest and highest values using <code>front()</code> and <code>back()</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T18:35:27.597", "Id": "468742", "Score": "0", "body": "One more idea. Thank you. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T12:00:06.297", "Id": "468964", "Score": "0", "body": "You misread the question. He needs not `(lowest + highest)/2` but median value. The problem is that `std::set` doesn't allow one to get median element quickly. For this you'd need some custom `set` class or use a custom algorithm with `std::vector` as base." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T12:59:38.257", "Id": "468970", "Score": "0", "body": "No, I didn't misread the question, but perhaps I failed to explain my thinking clearly enough. We store *two* (multi-)sets, `lower` containing those values that are less than the median, and `higher` containing those greater than the median. When we add a new value and remove an old one, we add/remove from `lower` and/or `higher` as appropriate, and if necessary move an element from `lower.back()` to `higher`, or from `higher.front()` to `lower`. Then the new median can be computed from `lower.back()` and `higher.front()` (or just one of them for an odd-size window)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:23:56.917", "Id": "239010", "ParentId": "238963", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T21:22:07.457", "Id": "238963", "Score": "4", "Tags": [ "c++", "c++14" ], "Title": "Rolling median function (Daily Coding Problem 377)" }
238963
<p>An Instagram Bot which downloads the posts from profile</p> <p>I have to mention my previous posts:</p> <ol> <li><a href="https://codereview.stackexchange.com/questions/238713/instagram-scraper-posts-videos-and-photos]">Instagram scraper Posts (Videos and Photos)</a></li> <li><a href="https://codereview.stackexchange.com/questions/238902/scraping-instagram-with-selenium-extract-urls-download-posts">Scraping Instagram with selenium, extract URLs, download posts</a></li> </ol> <p>My code:</p> <pre><code>import requests import os import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from multiprocessing.dummy import Pool import urllib.parse import argparse import re from concurrent.futures import ThreadPoolExecutor LINKS = [] PICTURES = [] VIDEO = [] chromedriver_path = None def check_availability(link, session_base): """ This function checks the availability of profile and the status code :param session_base: The requests session :param link: link that searching for and includes the profile name :return: raise Exception if &lt;privacy&gt; is True and &lt;followed_by_viewer&gt; is False """ search = session_base.get(urllib.parse.urljoin(link, "?__a=1")) search.raise_for_status() load_and_check = search.json() privacy = load_and_check.get("graphql").get("user").get("is_private") followed_by_viewer = load_and_check.get("graphql").get("user").get("followed_by_viewer") if privacy and not followed_by_viewer: raise Exception("[!] Account is private") def fetch_url(url, session_base): """ This function extracts images and videos :param session_base: The requests session :param url: Taking the url of array LINKS """ logging_page_id = session_base.get(url.split()[0]).json() try: """Taking Gallery Photos or Videos""" for log_pages in logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']: video = log_pages.get("node").get("is_video") if video: video_url = log_pages.get("node").get("video_url") VIDEO.append(video_url) else: image = log_pages.get("node").get("display_url") PICTURES.append(image) except KeyError: """Unique photo or Video""" image = logging_page_id.get('graphql').get('shortcode_media').get('display_url') PICTURES.append(image) if logging_page_id.get('graphql').get('shortcode_media').get("is_video"): videos = logging_page_id.get('graphql').get('shortcode_media').get("video_url") VIDEO.append(videos) class InstagramPV: def __init__(self, username, password, folder, search_name): """ :param username: username :param password: password :param folder: folder name :param search_name: the name what will search """ self.username = username self.password = password self.folder = folder self.HttpBase = requests.Session() """To avoid any errors, with regex find the url and taking the name &lt;search_name&gt;""" find_name = "".join(re.findall(r"(?P&lt;url&gt;https?://[^\s]+)", search_name)) if find_name.startswith("https"): self.search_name = urllib.parse.urlparse(find_name).path.split("/")[1] else: self.search_name = search_name if chromedriver_path is not None: self.driver = webdriver.Chrome(chromedriver_path) else: self.driver = webdriver.Chrome() def __enter__(self): return self def control(self): """ Create the folder name and raises an error if already exists """ if not os.path.exists(self.folder): os.mkdir(self.folder) else: raise FileExistsError("[*] Already Exists This Folder") def login(self): """Login To Instagram""" self.driver.get("https://www.instagram.com/accounts/login") time.sleep(3) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) submit = self.driver.find_element_by_tag_name('form') submit.submit() time.sleep(3) """Check For Invalid Credentials""" try: var_error = self.driver.find_element_by_class_name("eiCW-").text raise ValueError("[!] Invalid Credentials") except NoSuchElementException: pass try: """Close Notifications""" self.driver.find_element_by_xpath('//button[text()="Not Now"]').click() except NoSuchElementException: pass time.sleep(2) """Taking Cookies and update the self.HttpBase""" cookies = self.driver.get_cookies() for cookie in cookies: c = {cookie["name"]: cookie["value"]} self.HttpBase.cookies.update(c) self.driver.get("https://www.instagram.com/{name}/".format(name=self.search_name)) """Checking for availability""" check_availability("https://www.instagram.com/{name}/".format(name=self.search_name), self.HttpBase) return self.scroll_down() def _get_href(self): elements = self.driver.find_elements_by_xpath("//a[@href]") for elem in elements: urls = elem.get_attribute("href") if "p" in urls.split("/"): LINKS.append(urls) def scroll_down(self): """Taking hrefs while scrolling down""" end_scroll = [] while True: self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) self._get_href() time.sleep(2) new_height = self.driver.execute_script("return document.body.scrollHeight") end_scroll.append(new_height) if end_scroll.count(end_scroll[-1]) &gt; 4: self.extraction_url() break def extraction_url(self): """Gathering Images and Videos Using ThreadPoolExecutor and pass to function &lt;fetch_url&gt; """ links = list(set(LINKS)) print("[!] Ready for video - images".title()) print(f"[*] extracting {len(links)} posts , please wait...".title()) new_links = [urllib.parse.urljoin(link, "?__a=1") for link in links] with ThreadPoolExecutor(max_workers=8) as executor: [executor.submit(fetch_url, link, self.HttpBase) for link in new_links] def _download_video(self, new_videos): """ Saving the content of video in the file """ number, link = new_videos with open(os.path.join(self.folder, f"Video{number}.mp4"), "wb") as f: content_of_video = InstagramPV.content_of_url(link) f.write(content_of_video) def _images_download(self, new_pictures): """Saving the content of picture in the file""" number, link = new_pictures with open(os.path.join(self.folder, f"Image{number}.jpg"), "wb") as f: content_of_picture = InstagramPV.content_of_url(link) f.write(content_of_picture) def downloading_video_images(self): """Using multiprocessing for Saving Images and Videos""" print("[*] ready for saving images and videos!".title()) new_pictures = list(set(PICTURES)) new_videos = list(set(VIDEO)) picture_data = [i for i in enumerate(new_pictures)] video_data = [i for i in enumerate(new_videos)] pool = Pool(8) pool.map(self._images_download, picture_data) pool.map(self._download_video, video_data) print("[+] Done") def __exit__(self, exc_type, exc_val, exc_tb): self.HttpBase.close() self.driver.close() @staticmethod def content_of_url(url): req = requests.get(url) return req.content def main(): parser = argparse.ArgumentParser() parser.add_argument("-u", "--username", help='Username or your email of your account', action="store", required=True) parser.add_argument("-p", "--password", help='Password of your account', action="store", required=True) parser.add_argument("-f", "--filename", help='Filename for storing data', action="store", required=True) parser.add_argument("-n", "--name", help='Name to search', action="store", required=True) args = parser.parse_args() with InstagramPV(args.username, args.password, args.filename, args.name) as pv: pv.control() pv.login() pv.downloading_video_images() if __name__ == '__main__': main() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Requests makes things easy</h2>\n\n<pre><code>session_base.get(urllib.parse.urljoin(link, \"?__a=1\"))\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>session_base.get(link, params={__a: 1})\n</code></pre>\n\n<h2>Exception types</h2>\n\n<pre><code> raise Exception(\"[!] Account is private\")\n</code></pre>\n\n<p>The use of the base <code>Exception</code> should be replaced by a custom exception of yours. They're easy to make, and using them makes it so that upstream code can more meaningfully handle exceptions.</p>\n\n<h2>Some things need to exist</h2>\n\n<p>In these two cases:</p>\n\n<pre><code> video_url = log_pages.get(\"node\").get(\"video_url\")\n VIDEO.append(video_url)\n\n\n image = log_pages.get(\"node\").get(\"display_url\")\n PICTURES.append(image)\n</code></pre>\n\n<p>the dictionary value is mandatory, so you shouldn't <code>get</code> it; you should use regular bracket indexing. This will allow failures to be caught earlier, instead of leaking <code>None</code> into your data.</p>\n\n<h2>Nomenclature</h2>\n\n<pre><code>self.HttpBase = requests.Session()\n</code></pre>\n\n<p>Member variables should be lower_snake_case, i.e. <code>http_base</code>.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<pre><code>\"https://www.instagram.com/{name}/\".format(name=self.search_name)\n</code></pre>\n\n<p>should be put in a temporary variable.</p>\n\n<h2>Packed-tuple argument?</h2>\n\n<p>This:</p>\n\n<pre><code>def _images_download(self, new_pictures):\n number, link = new_pictures\n</code></pre>\n\n<p>is <strike>a little odd</strike> probably necessary due to your use of <code>map</code>, so never mind.</p>\n\n<h2>List creation</h2>\n\n<pre><code>[i for i in enumerate(new_pictures)]\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>list(enumerate(new_pictures))\n</code></pre>\n\n<p>but since you are only iterating through it once, don't even materialize it to a list; simply leave it as</p>\n\n<pre><code>picture_data = enumerate(new_pictures)\n</code></pre>\n\n<h2>Globals</h2>\n\n<p>These:</p>\n\n<pre><code>LINKS = []\nPICTURES = []\nVIDEO = []\n</code></pre>\n\n<p>are a problem. They're assigned in global scope, and then both written to and read from a class instance. The easy, and vaguely correct, thing to do is to move all of them to members of <code>InstagramPV</code>. <code>fetch_url</code> would then need to either:</p>\n\n<ol>\n<li>return new video and picture lists; or</li>\n<li>move to being a method on <code>InstagramPV</code> and populate the members there.</li>\n</ol>\n\n<p>I think I'd vote for the second, although this is bordering on making an uber-class without meaningful separation. One way to split this up is to make a class for Instagram data (links, pictures, videos) and a class for Instagram scraping (session, authentication, etc.); but I could be convinced that there are other sensible approaches.</p>\n\n<h2>Session use</h2>\n\n<p>Why isn't this:</p>\n\n<pre><code>@staticmethod\ndef content_of_url(url):\n req = requests.get(url)\n return req.content\n</code></pre>\n\n<p>using your session? It's surprising that it does the right thing without a cookie jar.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:07:20.630", "Id": "468709", "Score": "0", "body": "I owe you many thanks and i will update my post to tell you how much i appreciate you and the community. _but I could be convinced that there are other sensible approaches_ . Do you mean to change all my code and try to find a different way? Can you give me an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:16:24.087", "Id": "468710", "Score": "0", "body": "Put another way: once this round of review is over and you have a large(r) `InstagramPV` class, that means the obvious problems have largely been addressed, and more abstract problems would need to be approached, in this case object-oriented structure. I'd not worry about that yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T20:09:24.113", "Id": "468895", "Score": "1", "body": "First of all @Reinderien i thank you. Second , i promise that i will not stop until i will \"hear\" \"well done\" from you :). I know that it will be very difficult, but give me a chance to impress you with my progress. It's a challenge for me. My new [question](https://codereview.stackexchange.com/questions/239074/fixing-code-instagram-bot-selenium-web-scraping)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T20:52:30.990", "Id": "468901", "Score": "1", "body": "Great attitude :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T03:18:04.830", "Id": "470664", "Score": "1", "body": "Packed-tuple argument edited - I don't think you can easily escape the need for a single tuple." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T03:49:36.063", "Id": "238976", "ParentId": "238969", "Score": "2" } } ]
{ "AcceptedAnswerId": "238976", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T01:14:06.157", "Id": "238969", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "instagram" ], "Title": "Web scraping using selenium, multiprocessing, InstagramBot" }
238969
<p>i'm building an url router and i want to improve it to respect SOLID principles, i want suggestions of how can i make it less coupled.</p> <p>here's my current code:</p> <p><strong>Router.php</strong> <pre><code>namespace App\Helpers; use App\Interfaces\Request\IRequest; use App\Exceptions\MethodNotAllowedException; class Router { private $routes = []; private $methodsAllowed = ['GET', 'POST']; private $request; private $uri; private $matchTypes = [ 'i' =&gt; '[0-9]++', 'a' =&gt; '[0-9A-Za-z]++', '*' =&gt; '.+?', ]; public function __construct(IRequest $request) { $this-&gt;request = $request; $this-&gt;setUri($request-&gt;getUri()); } public function setUri($uri): void { $this-&gt;uri = $uri; } public function getUri(): string { return $this-&gt;uri; } public function on($method, $route, $callback): void { $this-&gt;setRoute($route, $method, $callback); } function setRoute($route, $method, $callback): self { if(!\in_array($method, $this-&gt;methodsAllowed)) { throw new MethodNotAllowedException('Method not allowed'); } $method = strtoupper($method); $this-&gt;routes[] = [ 'uri' =&gt; $this-&gt;getUri(), 'route' =&gt; $this-&gt;handleRouteUri($route), 'method' =&gt; $method, 'callback' =&gt; $callback, 'params' =&gt; [] ]; return $this; } public function handleRouteUri ($route): string { //other filters $route = $this-&gt;filterRoutePattern($route); return $route; } public function filterRoutePattern($route): string { foreach($this-&gt;matchTypes as $matchType =&gt; $pattern) { $route = str_replace("[$matchType]", "($pattern)", $route); } return $route; } public function getRoutes(): array { return $this-&gt;routes; } public function getMethod(): string { return $this-&gt;request-&gt;getMethod(); } public function match() { foreach($this-&gt;routes as $route) { if($route['method'] != $this-&gt;getMethod()) continue; $routeUri = $route['route']; $pattern = sprintf('~^%s$~', $routeUri); if( preg_match($pattern, $this-&gt;getUri(), $matches) ) { array_shift($matches); $route['params'] = $matches; return $route; } } } } </code></pre> <p><strong>Request.php</strong></p> <pre><code>&lt;?php namespace App\Helpers; use App\Interfaces\Request\IRequest; class Request implements IRequest { private static $params = []; private static $getParams = []; private static $postParams = []; private static $serverParams = []; public function __construct() { self::setParams(); } public function setParams(): void { self::$params = $_REQUEST; self::$getParams = $_GET; self::$postParams = $_GET; self::$serverParams = $_SERVER; } public function input($name): mixed { return self::$params[$name]; } public function post($name): mixed { return self::$postParams[$name]; } public function get($name): mixed { return self::$params_get[$name]; } public function merge($name, $value): void { self::$params[$name] = $value; } public function getMethod(): string { return self::$serverParams['REQUEST_METHOD']; } public function getUri(): string { return self::$serverParams['REQUEST_URI']; } } </code></pre> <p>usage:</p> <pre><code>use App\Helpers\Request; use App\Helpers\Router; $router = new Router(new Request()); $router-&gt;on('GET', '/', function() {}); $router-&gt;on('GET', 'users/[i]', 'UsersController@show'); $router-&gt;on('POST', 'user/store', function() {}); $match = $router-&gt;match(); if($match == true) { echo '&lt;pre&gt;'; print_r($match); } else { print_r($router-&gt;getUri()); } </code></pre> <p>1 - in order to achieve the Open Closed Principle, if i wanted to add more <code>$methodsAllowed</code> how could i do it without changing the structure of the class? </p> <p>2 - i think that would be better to have a Route class where it could store its own properties and methods, but how could i group multiple routes and call it? a class RouteBag or RouteCollection? </p> <p>3 - should i create a separated class to deal with the regex expressions? (filtering, etc...) </p> <p>4 - if i wanted to create a separated route file and use it anywhere i wanted, like <code>web.php</code> in laravel, how should i do it? return an array with the routes or some kind of a collection as i mentioned in step 2</p> <p>5 - if some route matches a given URL it's returned an array with the route's info, how can i handle calling the controller/method or running the closure callback?</p> <p>feel free to suggest anything you think would be useful </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T03:20:21.973", "Id": "238975", "Score": "2", "Tags": [ "php", "object-oriented", "design-patterns", "url-routing" ], "Title": "implementation of a mvc url router with low coupling and solid principles" }
238975
<p>I need to show a map of the United States using Leaflet, where if the user clicks on a state, the map zooms in to view all of the state's census tracts. I need to do this without a significant delay in loading.</p> <p>The best approach I have tried so far requests all of the census tract data when the page loads. I send these requests using a WebWorker, which receives all of the data in one message and then fires off 51 separate XHR requests. As the WebWorker receives each XHR response, it parses the response's JSON and sends this back to the main thread. As the main thread receives each parsed JSON, it creates a GeoJSON Leaflet layer for the state, appending it to a collection for future reference. </p> <p>There is a significant, unacceptable delay when the page first loads and weird lags later on. When I check the memory usage in Firefox, it looks like the page is using 900+ MB. If I take the census tracts out of the code, the page uses much less memory. </p> <p>How do I get rid of this delay/lag? I also think there is a memory leak because if I refresh the page a few times, the tab freezes and I have to close it. </p> <p>I have also tried an alternative approach where I fire off an XHR request only when the user clicks on the state. However, there is a lag in receiving the response, leaving the user hanging for a couple seconds. And once all of the states have loaded, there is still the same overall lag in map movement.</p> <p>The census tract data is 161.3 MB. The state data that I use at the beginning is 523 KB. </p> <p>Full HTML, SSCCE:</p> <pre class="lang-html prettyprint-override"><code>&lt;head&gt; &lt;style&gt; body { padding: 0; margin: 0; } #map { height: 100vh; width: 100vw; } &lt;/style&gt; &lt;!-- Leaflet --&gt; &lt;link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/&gt; &lt;script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""&gt;&lt;/script&gt; &lt;!-- my code --&gt; &lt;script src="test_script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;/body&gt; </code></pre> <p>Full JS, SSCCE:</p> <pre class="lang-js prettyprint-override"><code>window.onload = function() { /*------------------------------------------------ -------------- Initialize variables -------------- ------------------------------------------------*/ var mapboxAccessToken = 'pk.eyJ1IjoiYnJpZW5uYWtoIiwiYSI6ImNqbXRsNjN0aTAxZXAzbG13bmh0dGFjNm0ifQ.98TAXgq4Rg1LpM2Oq1rlWw'; // Get main data var xmlhttp = new XMLHttpRequest(); var url = 'http://briennakh.me/accessibility-maps/data/us_states_edited.json' xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200) { statesData = JSON.parse(this.responseText); } } xmlhttp.open('GET', url, false); xmlhttp.send(); /*------------------------------------------------ -------------- Create map ------------------------ ------------------------------------------------*/ // Create basemap var basemap = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', { id: 'mapbox/light-v9', attribution: '', tileSize: 512, zoomOffset: -1, maxZoom: 18, accessToken: mapboxAccessToken, }); // Create map var map = L.map('map', { center: new L.LatLng(37.8, -96), zoom: 4, layers: [basemap], }); var stateLayer = L.geoJson(statesData, { style: stateStyle, onEachFeature: onEachState }).addTo(map); var censusTractLayers = {}; if (typeof(Worker) !== "undefined") { w = new Worker('worker.js'); // to test worker, must serve on localhost, otherwise Security Error // Respond to message sent back from worker w.onmessage = function(e) { var state = e.data; console.log('Received message from worker for ' + state.name) censusTractLayers[state.name] = L.geoJson(state, { style: tractStyle, onEachFeature: onEachTract }); } } else { // will need to inform user they need an updated browser console.log('No support for web worker.'); } // Load each state's census tracts in the background w.postMessage(statesData.features); /*------------------------------------------------ -------------- Define styles --------------------- ------------------------------------------------*/ function tractStyle(feature) { return { fillColor: 'grey', weight: .5, // no border opacity: 1, color: 'white', dashArray: '1', fillOpacity: 0.7 } } function stateStyle(feature) { return { fillColor: 'grey', weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7 }; } /*------------------------------------------------ -------------- Define event handlers ------------- ------------------------------------------------*/ function onEachState(feature, layer) { layer.on({ mouseover: function(e) { highlightFeature(e); }, mouseout: function(e) { var feature = e.target; stateLayer.resetStyle(feature); }, click: function(e) { map.fitBounds(e.target.getBounds()); // Add census tract layer to map if it has already been loaded if (feature.properties.name in censusTractLayers) { censusTractLayers[feature.properties.name].addTo(map); } else { console.log('Not loaded yet'); } } }); } function onEachTract(feature, layer) { layer.on({ mouseover: function(e) { highlightFeature(e); }, mouseout: function(e) { var feature = e.target; for (i in censusTractLayers) { if(censusTractLayers[i].hasLayer(feature)) { censusTractLayers[i].resetStyle(feature); } } } }); } function highlightFeature(e) { var feature = e.target; feature.setStyle({ weight: 5, color: '#666', dashArray: '', fillOpacity: 0.7 }); if (!L.Browser.ie &amp;&amp; !L.Browser.opera &amp;&amp; !L.Browser.edge) { feature.bringToFront(); // to prevent feature overlaps } } } </code></pre> <p>JS for web worker:</p> <pre><code>onmessage = function(e) { console.log('Message received from main script.'); for (var i in e.data) { state = e.data[i].properties.name; var xmlhttp = new XMLHttpRequest(); var url = 'http://briennakh.me/accessibility-maps/data/census tracts/geojsons/' + state + '.json' xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200) { state_json = JSON.parse(this.responseText); postMessage(state_json); } } xmlhttp.open('GET', url); xmlhttp.send(); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T06:20:21.037", "Id": "469232", "Score": "0", "body": "You're using a synchronous XHR by specifying `false` in xmlhttp.open. Don't do it. Rework your code to use the proper modern asynchronous mode of XHR." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T04:26:59.253", "Id": "238977", "Score": "1", "Tags": [ "javascript", "memory-management", "memory-optimization" ], "Title": "Reduce memory usage/lag with multiple large JSON files coming in through XHR" }
238977
<p>I'm planning to use <a href="https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm" rel="nofollow noreferrer">Tarjan's algorithm</a> for a program in which I would be processing a file, converting the processed data to a dictionary, doing a topological sort on that dictionary (using this implementation), and then finding the longest path. </p> <p>Is there any optimization that can be made to the below code, or can be be made more pythonic?</p> <pre><code>def strongly_connected_components(graph): index_counter = [0] stack = []; result = [] lowlinks = {}; index = {} def tarjan(node): index[node] = index_counter[0] lowlinks[node] = index_counter[0] index_counter[0] += 1 stack.append(node) try: successors = graph[node] except: successors = [] for successor in successors: if successor not in lowlinks: tarjan(successor) lowlinks[node] = min(lowlinks[node],lowlinks[successor]) elif successor in stack: lowlinks[node] = min(lowlinks[node],index[successor]) if lowlinks[node] == index[node]: connected_component = [] while True: successor = stack.pop() connected_component.append(successor) if successor == node: break component = tuple(connected_component) result.append(component) for node in graph: if node not in lowlinks: tarjan(node) return result </code></pre> <p><a href="http://www.logarithmic.net/pfh-files/blog/01208083168/tarjan.py" rel="nofollow noreferrer">Source</a></p> <p>The graph is unweighted, and would look something like this:-</p> <pre><code>test_graph = { 'A' : ['B','S'], 'B' : ['A'], 'C' : ['D','E','F','S'], 'D' : ['C'], 'E' : ['C','H'], 'F' : ['C','G'], 'G' : ['F','S'], 'H' : ['E','G'], 'S' : ['A','C','G'] } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T07:27:14.297", "Id": "468663", "Score": "1", "body": "Do you know of [`networkx`](https://networkx.github.io/documentation/stable/), which has [multiple functions to deal with strongly connected components](https://networkx.github.io/documentation/stable/reference/algorithms/component.html#strong-connectivity)? It also uses Tarjan's algorithm (with some modifications), so even if you don't want to use it you could have a look at their implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T07:59:34.737", "Id": "468665", "Score": "0", "body": "It uses a modified Tarjan's implementation (\"Uses Tarjan’s algorithm[1]_ with Nuutila’s modifications[2]_\" - from the link). Also, I'm trying to avoid using any libraries." } ]
[ { "body": "<h2>Multi-statement lines</h2>\n\n<p>This:</p>\n\n<pre><code>stack = []; result = []\nlowlinks = {}; index = {}\n# ...\nif successor == node: break\n</code></pre>\n\n<p>is generally discouraged; just use two lines.</p>\n\n<h2>snake_case</h2>\n\n<p>This:</p>\n\n<p><code>lowlinks</code></p>\n\n<p>is usually spelled out, i.e. <code>low_links</code>.</p>\n\n<h2>Bare <code>except</code></h2>\n\n<pre><code> try:\n successors = graph[node]\n except:\n successors = []\n</code></pre>\n\n<p>has an except statement that's too broad. If you expect a <code>KeyError</code> from this, then <code>except KeyError</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T16:35:22.023", "Id": "239237", "ParentId": "238979", "Score": "2" } } ]
{ "AcceptedAnswerId": "239237", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T05:30:03.240", "Id": "238979", "Score": "5", "Tags": [ "python", "algorithm", "python-3.x", "sorting", "graph" ], "Title": "Tarjan's Algorithm Python Implementation" }
238979
<p>In this code in Python, I used an API called <strong><a href="https://www.coindesk.com/coindesk-api" rel="nofollow noreferrer">CoinDesk</a></strong> to get the Bitcoin price as JSON. I'm trying to follow the best practices in coding, so, I've used logging and I'm using a code formatter in my editor. Kindly, any enhancements on this code will be appreciated.</p> <pre><code># Project Idea: Bitcoin price program using CoinDesk API with Python. # Importing libraries import requests as rq from datetime import datetime import logging import objectpath # Read the library doc: http://objectpath.org/ def get_api_data(): LOG_FORMAT = '%(levelname)s : %(asctime)s - %(message)s' logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, filemode='w') # , datefmt='%d-%b-%y %H:%M:%S' logger = logging.getLogger() try: API_LINK = 'https://api.coindesk.com/v1/bpi/currentprice.json' # CoinDesk API Link API_Data = rq.get(API_LINK) logger.debug("Getting API data - Done") api_data = API_Data.json() logger.debug("Converting API data to JSON - Done") return api_data except Exception as e: print("Exception occurred: ", e) logger.debug("Exception occurred.") def main(): # Getting the data from API data = get_api_data() tree_data = objectpath.Tree(data) time = tuple(tree_data.execute('$..updated')) usd = list((tree_data.execute('$..USD'))) price = dict(usd[0]) price_usd = price["rate"] price_description = price["description"] + ' - USD' print(f"The price in {price_description}: {price_usd}") print(f"Time of the price: {time}") if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>When using the logger module, you usually want to initialize the logger once per script, at the beginning, and usually with the name of the file (or another descriptive name) as the argument. This way you can distinguish where each logging call comes from (although you have disabled that with your particular choice of formatting string).</p>\n\n<p>Since you are already catching all exceptions, you should probably raise an exception if the connection fails, instead of hoping one is raised when you try to get the JSON object out of the responses.</p>\n\n<p>When you do log exceptions, you are currently printing the exception to the standard output. If you let <code>logging</code> deal with this you could use all functionalities of the module, like outputting to different output streams (<code>stderr</code> usually, for, well, errors). You can either use <code>logger.exception</code> for this or pass the flag <code>exc_info=True</code>. The former uses the logging level <code>logging.ERROR</code>, the latter allows you to use it with any level.</p>\n\n<pre><code>import requests as rq\nfrom datetime import datetime\nimport logging\nimport objectpath # Read the library doc: http://objectpath.org/\n\nlogger = logging.getLogger(__name__)\n\ndef get_api_data(url):\n try:\n response = rq.get(url)\n response.raise_for_status()\n logger.debug(\"Getting API data - Done\")\n api_data = response.json()\n logger.debug(\"Converting API data to JSON - Done\")\n return api_data\n except Exception as e:\n logger.debug(\"Exception occurred.\", exc_info=True)\n\ndef main():\n # CoinDesk API Link\n API_LINK = 'https://api.coindesk.com/v1/bpi/currentprice.json'\n\n # Getting the data from API\n data = get_api_data(API_LINK)\n tree_data = objectpath.Tree(data)\n\n time = next(tree_data.execute('$..updated'))\n price = next(tree_data.execute('$..USD'))\n\n print(f\"The price in {price['description']} - USD: {price['rate']}\")\n print(f\"Time of the price: {time}\")\n\n\nif __name__ == '__main__':\n LOG_FORMAT = '%(levelname)s : %(asctime)s - %(message)s'\n logging.basicConfig(level=logging.DEBUG,\n format=LOG_FORMAT, filemode='w')\n main()\n</code></pre>\n\n<p>I also used <code>next</code> instead of <code>tuple</code> and <code>list</code>, which just gets the next element from the generators (no need to get all if you only need one), which also removed the superfluous <code>()</code> around the time, moved the formatting completely into the string, gave the function a parameter to change the URL from the outside and renamed <code>API_DATA</code> to <code>response</code> (since it is not a global constant).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:00:27.510", "Id": "468666", "Score": "0", "body": "I'll reconstruct my code according to these valuable notes.\nThanks a lot, appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T16:59:10.237", "Id": "468729", "Score": "1", "body": "I don't think calling `basicConfig` at the root of the script is good practice, you should at least move it into the `if __name__ == '__main__'` block." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T07:42:29.247", "Id": "238983", "ParentId": "238980", "Score": "2" } }, { "body": "<p>In general you should be more especific on the management of the exceptions, my only contribution will be to be more specific on them on the requests component. For example your code on:</p>\n\n<pre><code>def get_api_data(url):\n try:\n response = rq.get(url)\n response.raise_for_status()\n ... \n except Exception as e:\n logger.debug(\"Exception occurred.\", exc_info=True)\n</code></pre>\n\n<p>With more specific exception management</p>\n\n<pre><code>def get_api_data(url):\n try:\n response = rq.get(url)\n response.raise_for_status()\n ... \n except requests.exceptions.RequestException as _:\n logger.debug(\"Exception occurred on request.\", exc_info=True)\n except json.decoder.JSONDecodeError as _:\n logger.debug(\"Exception occurred on json decoder.\", exc_info=True)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T09:38:04.747", "Id": "468677", "Score": "0", "body": "Thanks for your contribution.\nI'll be more specific in the next codes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:52:48.023", "Id": "238987", "ParentId": "238980", "Score": "3" } } ]
{ "AcceptedAnswerId": "238983", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T05:43:29.447", "Id": "238980", "Score": "2", "Tags": [ "python", "json", "api", "cryptocurrency" ], "Title": "Print Bitcoin price by getting JSON data using CoinDesk API" }
238980
<p>The following is the simulation of <a href="https://www.youtube.com/watch?v=IiV6blF1crE&amp;t=743s" rel="nofollow noreferrer">Central Limiting Theorem</a> from Statistics:</p> <pre><code>class MyRandom: m = 4294967296;# modulus a = 1664525; # multiplier c = 1013904223; # increment seed = 1; #initial seed def NextInt(self): self.seed = (((self.a * self.seed + self.c) % self.m)); return self.seed; def NextIntMm(self, mins, maxs): temp = self.NextInt(); ddd = float(temp) / float(self.m); returns = int((maxs - mins) * ddd + mins); return returns; def NextDouble(self): temp = self.NextInt(); return float(temp) / float(self.m); def NextDoubleMm(self, mins, maxs): temp = self.NextInt(); fraction = float(temp) / float(self.m); return (maxs - mins) * fraction + mins; ################################################################# N = 999999; r = MyRandom(); population = []; population_sum = 0; for i in range(0, N): x = r.NextDouble(); population.append(x); population_sum = population_sum + x; population_mean = population_sum / len(population); print("Population mean = ", population_mean); ################################################################## rnd_num_count = 30; sample_size = 12; sample_means = []; sum_of_sample_mean = 0; for i in range(0, rnd_num_count): sums = 0; for j in range(0, sample_size): index = r.NextIntMm(0, N - 1); element = population[index]; sums = sums + element; sample_mean = sums / sample_size; sum_of_sample_mean = sum_of_sample_mean + sample_mean; sample_means.append(sample_mean); print("Mean of sample mean = ", sum_of_sample_mean/ len(sample_means)); </code></pre> <p>Here, Normal Distribution of population is used.</p> <p>Can you review this and point out any possible improvement needed?</p> <p>N.B. Defining a random number generator is part of the requirement. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T11:12:35.000", "Id": "468691", "Score": "0", "body": "You are aware of the [`random`](https://docs.python.org/3/library/random.html) module in the standard library, right? If so, consider adding the [tag:reinventing-the-wheel] tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T13:43:04.693", "Id": "468708", "Score": "0", "body": "I guess you have an indentation error in your second example, the second-to-last block should probably under the outer `for` loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:43:07.190", "Id": "468714", "Score": "0", "body": "@Graipher, No, my program is running smoothly in Spyder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:46:03.307", "Id": "468715", "Score": "0", "body": "That may be the case, but it will probably not do the right thing because `sample_means` would contain only the last sample mean and `sums` will be reset every loop iteration without being used, so `sample_mean` will only use the `sums` from the last iteration." } ]
[ { "body": "<p>Even though you are implementing your own random number generator, I would stick to the interface defined in the standard library module <code>random</code>. You could have a <code>random</code>, a <code>uniform</code>, a <code>randint</code> (or <code>randrange</code> if it is inclusive on the end) and a <code>choices</code> method.</p>\n\n<p>Your class should probably also allow setting the seed on creation.</p>\n\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends not using trailing <code>;</code> and using <code>lower_case</code> both for variables as well as functions/methods.</p>\n\n<p>Even in Python 2 (which you should no longer use), if either the numerator or the divisor is a <code>float</code>, the result is also a <code>float</code> with the division operator <code>/</code>, so you only need to cast one of them. In Python 3 <code>/</code> is always float division and <code>//</code> is always integer division, so no need for the casts to <code>float</code>.</p>\n\n<p>You should always add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>dosctring</code></a> to your code explaining how to use it.</p>\n\n<p>For <code>range</code>, the start is implicitly <code>0</code>. Also <code>_</code> is conventionally used for unused loop variables.</p>\n\n<p>Wrap the code that uses your class in a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without it running.</p>\n\n<pre><code>class Random:\n \"\"\"A pseudo-random number generator using a LCG.\"\"\"\n m = 4294967296 # modulus\n a = 1664525 # multiplier\n c = 1013904223 # increment\n\n def __init__(self, seed=1):\n \"\"\"Initialize the pseudo-random number generator with a seed (default: 1).\"\"\"\n self.state = seed\n\n def randint(self, a=None, b=None):\n \"\"\"Return either a random integer between `0` and `self.m`\n or between `a` and `b` (exclusive?).\"\"\"\n if a is None and b is None:\n self.state = (self.a * self.state + self.c) % self.m\n return self.state\n elif a is not None:\n if b is not None:\n return int(self.uniform(a, b))\n else:\n return int(self.uniform(0, a))\n else:\n raise ValueError(\"Need to also set `a` if you set `b`.\")\n\n def random(self):\n \"\"\"Return a random float between 0 and 1 (exclusive?).\"\"\"\n return float(self.randint()) / self.m\n\n def uniform(self, a, b):\n \"\"\"Return a random float between `a` and `b` (exclusive?).\"\"\"\n return (b - a) * self.random() + a\n\n def choices(self, population, k=1):\n \"\"\"Return a k sized list of population elements chosen with replacement.\"\"\"\n n = len(population)\n return [population[self.randint(n - 1)] for _ in range(k)]\n</code></pre>\n\n<p>The usage of this is similar to your code, just with renamed methods.</p>\n\n<p>You can also greatly shorten your examples using <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehensions</a> and a utility function <code>mean</code>:</p>\n\n<pre><code>random = Random()\n\ndef mean(x):\n return float(sum(x)) / len(x)\n\nif __name__ == \"__main__\":\n N = 999999 \n population = [random.random() for _ in range(N)]\n print(\"Population mean = \", mean(population))\n\n rnd_num_count = 30\n sample_size = 12\n sample_means = [mean(random.choices(population, k=sample_size))\n for _ in range(rnd_num_count)]\n print(\"Mean of sample mean = \", mean(sample_means))\n</code></pre>\n\n<p>This script has the advantage that you can easily test it with the standard library <code>random</code> module by replacing the line <code>random = Random()</code> with <code>import random</code>. This way you can see if your class produces random numbers somewhat correctly.</p>\n\n<hr>\n\n<p>If implementing so many different random functions gets tedious, you can also subclass <code>random.Random</code>:</p>\n\n<blockquote>\n <p>Class <code>Random</code> can also be subclassed if you want to use a different\n basic generator of your own devising: in that case, override the\n following methods: <code>random()</code>, <code>seed()</code>, <code>getstate()</code>, and <code>setstate()</code>.\n Optionally, implement a <code>getrandbits()</code> method so that <code>randrange()</code> can\n cover arbitrarily large ranges.</p>\n</blockquote>\n\n<p>This of course means that you are using the standard library and not your own implementations as much. In that case you probably also want to use <code>statistics.mean</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T13:49:20.287", "Id": "238997", "ParentId": "238982", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T07:40:00.180", "Id": "238982", "Score": "1", "Tags": [ "python", "statistics", "simulation" ], "Title": "Simulation of Central Limiting Theorem (CLT)" }
238982
<p>I implemented an in-memory file system that should support basic Linux commands (mkdir, cd, mkfile...) on the current working directory. It can read commands from a file and process them.</p> <p>I'm interested in a review from senior developers to see what makes a difference between a junior and senior (what should I focus on...)</p> <pre><code>#include &lt;iostream&gt; #include &lt;chrono&gt; #include &lt;ctime&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;memory&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; class Directory; enum class EntryType { FILE, DIRECTORY, ANY_TYPE }; class Entry { private: const std::string m_name; const std::time_t m_created; const EntryType m_entryType; Directory *m_parentDirectory; protected: Entry(const std::string &amp;name, EntryType entryType, Directory *parentDirectory) : m_name {name}, m_created {std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())}, m_entryType {entryType}, m_parentDirectory {parentDirectory} { } virtual ~Entry() { } public: const std::string&amp; getName() const {return m_name;} const std::time_t&amp; getTimeCreated() const {return m_created;} const EntryType&amp; getEntryType() const {return m_entryType;} Directory* getParentDirectory() {return m_parentDirectory;} }; class File : public Entry { public: File(const std::string &amp;name, Directory *parentDirectory) : Entry(name, EntryType::FILE, parentDirectory) { } }; class Directory : public Entry { private: std::vector&lt;std::shared_ptr&lt;Entry&gt;&gt; entries; public: Directory(const std::string &amp;name, Directory *parentDirectory) : Entry(name, EntryType::DIRECTORY, parentDirectory) { } ~Directory() { } private: void list(EntryType type) { for (auto &amp;entry : entries) { if (entry-&gt;getEntryType() == type) std::cout &lt;&lt; getCreatedTime(entry.get()) &lt;&lt; "\t\t" &lt;&lt; entry-&gt;getName() &lt;&lt; "\n"; } } int countEntries(EntryType type) { auto count {static_cast&lt;int&gt;(std::count_if(entries.begin(), entries.end(), [&amp;type](std::shared_ptr&lt;Entry&gt; entry){ return entry-&gt;getEntryType() == type; }))}; return count; } bool checkEntry(const std::string &amp;name) { auto findEntry {std::find_if(entries.begin(), entries.end(), [&amp;name](std::shared_ptr&lt;Entry&gt; entry){ return entry-&gt;getName() == name; })}; if (findEntry != entries.end()) return true; return false; } const std::string getCreatedTime (Entry *entry) const { std::string timeCreated {std::ctime(&amp;entry-&gt;getTimeCreated())}; timeCreated[timeCreated.length() - 1] = '\0'; return timeCreated; } public: void listEntries() { std::cout &lt;&lt; getCreatedTime(this) &lt;&lt; "\t\t" &lt;&lt; ".\n"; int numDir {1}; if (this-&gt;getParentDirectory() != nullptr) { std::cout &lt;&lt; getCreatedTime(this-&gt;getParentDirectory()) &lt;&lt; "\t\t" &lt;&lt; "..\n"; ++numDir; } list(EntryType::DIRECTORY); list(EntryType::FILE); std::cout &lt;&lt; "\n"; std::cout &lt;&lt; countEntries(EntryType::DIRECTORY) + numDir &lt;&lt; "\t\t" &lt;&lt; "Dir(s)\n"; std::cout &lt;&lt; countEntries(EntryType::FILE) &lt;&lt; "\t\t" &lt;&lt; "File(s)\n"; std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "--------------------------------------------------\n"; } void makeDirectory(const std::string &amp;name) { if (checkEntry(name)) return; entries.push_back(std::make_shared&lt;Directory&gt;(name, this)); } void makeFile(const std::string &amp;name) { if (checkEntry(name)) return; entries.push_back(std::make_shared&lt;File&gt;(name, this)); } Directory* changeDirectory(const std::string &amp;name) { if (name == ".") { return this; } else if (name == "..") { if (this-&gt;getParentDirectory() == nullptr) { return this; } else return this-&gt;getParentDirectory(); } for (auto &amp;entry : entries) { if (entry-&gt;getEntryType() == EntryType::DIRECTORY &amp;&amp; entry-&gt;getName() == name) return static_cast&lt;Directory *&gt;(entry.get()); } std::cout &lt;&lt; "Directory: " &lt;&lt; name &lt;&lt; " does not exist\n"; return this; } void deleteEntry(const std::string &amp;name, EntryType type) { auto findEntry {std::find_if(entries.begin(), entries.end(), [&amp;name](std::shared_ptr&lt;Entry&gt; entry){ return entry-&gt;getName() == name; })}; if (findEntry != entries.end()) { if (type == EntryType::ANY_TYPE || type == findEntry-&gt;get()-&gt;getEntryType()) { entries.erase(findEntry); return; } } } }; class FileSystem { private: Directory m_root; Directory *m_currentDirectory; public: FileSystem() : m_root(Directory {".", nullptr}) { m_currentDirectory = &amp;m_root; } ~FileSystem() { } private: void ls() const { m_currentDirectory-&gt;listEntries(); } void mkdir(const std::string &amp;name) const { m_currentDirectory-&gt;makeDirectory(name); } void mkfile(const std::string &amp;name) const { m_currentDirectory-&gt;makeFile(name); } void dir() const { ls(); } void cd(const std::string &amp;name) { m_currentDirectory = m_currentDirectory-&gt;changeDirectory(name); } void del(const std::string &amp;name, EntryType type = EntryType::ANY_TYPE) const { m_currentDirectory-&gt;deleteEntry(name, type); } void rmdir(const std::string &amp;name) const { del(name, EntryType::DIRECTORY); } void processCommand(const std::string &amp;command, const std::string &amp;option) { if (command == "ls") return ls(); else if (command == "dir") return dir(); else if (command == "mkdir") return mkdir(option); else if (command == "mkfile") return mkfile(option); else if (command == "cd") return cd(option); else if (command == "rmdir") return rmdir(option); else if (command == "del") return del(option); } public: void readInput(const std::string &amp;fileName) { std::ifstream infile {fileName}; std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); std::string command; std::string option; iss &gt;&gt; command; iss &gt;&gt; option; std::cout &lt;&lt; command &lt;&lt; " " &lt;&lt; option &lt;&lt; "\n"; processCommand(command, option); } } }; int main() { FileSystem filesystem; filesystem.readInput("path to the input file"); return 0; } </code></pre>
[]
[ { "body": "<p>Why do the getters for <code>Entry</code> return const references? <code>getEntryType</code>, in particular, does not benefit at all from returning a reference since it just returns an enum value (which is the same size or smaller than what would be returned for the reference).</p>\n\n<p><code>getParentDirectory</code> should be a const function.</p>\n\n<p>If the first three members of <code>Entry</code> are const members, why is <code>m_parent</code> not const (<code>Directory * const m_parentDirectory</code>)?</p>\n\n<p>In the <code>Directory</code> class, if <code>list</code> would return the number of entries found, that would avoid the need to call <code>count</code> (and iterate thru the directory twice) in the <code>listEntries</code> function. <code>list</code> can be a <code>const</code> function, and the for loop should use <code>const auto &amp;entry</code>.</p>\n\n<p><code>countEntries</code> and <code>checkEntry</code> can also be const functions.</p>\n\n<p>Why does <code>countEntries</code> return an <code>int</code>? You can't have negative entries in a directory, and if you use <code>std::size_t</code> then you won't need to do the casting with the return value, and just <code>return std::count_if</code> directly. Additionally, <code>countEntries</code> won't work if passed an <code>EntryType</code> of <code>ANY_TYPE</code>.</p>\n\n<p><code>checkEntry</code> can be simplified a bit by removing the <code>if</code> and separate returns and replacing them with <code>return findEntry != entries.end();</code>, possibly replacing the <code>findEntry</code> value with the <code>find_if</code> call. (<code>findEntry</code> is misnamed; <code>foundEntry</code> would be better.)</p>\n\n<p>Nether <code>makeDirectory</code> or <code>makeFile</code> return or report any sort of error if the entry already exists.</p>\n\n<p>The uses of <code>this-&gt;</code> in <code>listDirectory</code> and <code>changeDirectory</code> are unnecessary. That can also both be const functions.</p>\n\n<p><code>deleteEntry</code> and <code>checkEntry</code> both use the same <code>find_if</code>. This could be moved into a separate function, which can then be used by <code>changeDirectory</code> as well.</p>\n\n<p>When you make the default <code>root</code> entry in <code>FileSystem</code>, you explicitly create an entry for \".\", which none of the subdirectories have. Is this necessary? This will also allow someone to \"rmdir .\" from the root.</p>\n\n<p>Your \"del\" command can be used to delete a directory, which is probably not intended since you have an explicit command for that. You can also remove a non-empty directory.</p>\n\n<p>With a little bit of adjustment, you can create a table with commands and function pointers for <code>processCommand</code> to use, rather than using nested if/elses.</p>\n\n<p>You might want to look over <a href=\"https://stackoverflow.com/q/10231349/5231607\">this question</a> on Stack Overflow about whether to pass strings by value or reference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:46:07.043", "Id": "468739", "Score": "0", "body": "thanks for your feedback, I have one question regarding the functions pointers for process command. How would one implement function pointers in a class especially when some commands take arguments (e.g. mkdir) and others do not (e.g. ls)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T19:55:28.873", "Id": "468745", "Score": "0", "body": "@JerryThePineapple The functions that do not take parameters can be modified to take a parameter (and not use it), or be called thru a helper function that would take the parameter (and not use it)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:34:56.223", "Id": "238999", "ParentId": "238986", "Score": "5" } }, { "body": "<p>I know a directory looks like a tree structure. But you don't need to implement it as a tree. To me a file system is simply a map from name to object.</p>\n\n<pre><code>class FileSystem\n{\n std::map&lt;std::string, File&gt;. fs;\n std::string currentDir;\n};\n</code></pre>\n\n<p>The artificial construct of directories is just a convenient way to simplify things for the human brain. But you don't need to model it like that in memory.</p>\n\n<p>I would use a simple map of 'full path name' to object. Then allow the user to use absolute or relative path names to iterate over the file system object.</p>\n\n<p>This will simplify the number of objects you are maintaining. Your methods on the <code>FileSystem</code> class then internally impose the directory structure on the strings in the map. e.g.:</p>\n\n<pre><code>iterator FileSystem::listbegin(std::string const&amp; directory)\n{\n std::directory absDirectory = currentDirectory;\n if (directory[0] == '/') {\n absDirectory = directory;\n }\n else {\n absDirectory += '/' + directory;\n }\n if (absDirectory.back() != '/') {\n absDirectory += '/';\n }\n\n auto find = std::find_if(std::begin(fs), std::end(fs),\n [&amp;absDirecotry](auto const&amp; v){return v.first.substr(0, absDirecotry.size()) == absDirecotry;});\n return iterator(find);\n}\n</code></pre>\n\n<hr>\n\n<p>The other thing I would do is that once you have a reference to a file, you should be able to get a standard C++ stream to the object.</p>\n\n<pre><code>std::fsstream memoryFile(fs, \"/ThisIsAfile\");\n</code></pre>\n\n<p>I would want to treat any file object in this memory filesystem just like a file that is in the standard filesystem.</p>\n\n<hr>\n\n<p>This is more like how S3 implements its filesystem structure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-27T09:30:51.073", "Id": "469720", "Score": "0", "body": "shouldn't you have a vector or a list of files as the value in the map, since one can add multiple files to a single path?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-27T14:16:40.330", "Id": "469773", "Score": "0", "body": "@JerryThePineapple No file system I know has more than one file on a specific path. Note: Path includes the file name itself." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T23:46:29.573", "Id": "239080", "ParentId": "238986", "Score": "3" } } ]
{ "AcceptedAnswerId": "238999", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T08:50:34.393", "Id": "238986", "Score": "6", "Tags": [ "c++", "file-system" ], "Title": "In-memory filesystem" }
238986
<p>Hi I have written the following code in Python. Any improvements on my code will be appreciated as this is my first shot at pygame! </p> <p>There are some problems in terms of functionality, to state briefly ball sometimes gets stuck within a paddle, which I am continuing to resolve</p> <pre><code>import pygame, sys import random from math import degrees, radians, sin, cos pygame.init() # Create a screen win = pygame.display.set_mode((800,700)) win_info = pygame.display.Info() win_w, win_h = win_info.current_w, win_info.current_h pygame.display.set_caption("Pong") pad_colour = (255,255,255) #White colour pad_distance = 50 speed = 10 running = True fps = 30 ############################################################################# class border(pygame.sprite.Sprite): width = win_w height = 10 def __init__(self,width, height, colour): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((width,height)) self.image.fill(colour) self.rect = self.image.get_rect() def draw(self): win.blit(self.image, self.rect) ############################################################################# class paddle(pygame.sprite.Sprite): """left arg refer to top left corner coordinate of paddle """ def __init__(self,width, height, speed, colour): pygame.sprite.Sprite.__init__(self) self.width = width self.height = height self.image = pygame.Surface([width, height]) self.image.fill(colour) self.speed = speed self.vel_x = 0 self.vel_y = 0 # Size of rectangle self.rect = self.image.get_rect() def move(self, x, y): self.rect.move_ip(x,y) def moveTo(self, x, y): self.rect.topleft = (x,y) def draw(self): win.blit(self.image, (self.rect.x,self.rect.y)) ############################################################################# class ball(pygame.sprite.Sprite): """ Facing takes 1 or -1 to determine direction of movement """ def __init__(self, radius, factor, colour): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([radius*2, radius*2]) pygame.draw.circle(self.image, colour, (radius,radius), radius) self.rect = self.image.get_rect() # Replace facing when finalising implementation of ball self.facing = -1 self.factor = factor self.vel_x, self.vel_y = self.randomMovement(factor) def move(self, x,y): self.rect.move_ip(x,y) def moveTo(self, x, y): self.rect.center = (x,y) def collidePad(self): self.vel_x = self.vel_x * -1 def draw(self): win.blit(self.image, (self.rect)) def randomMovement(self,factor=None): #unit vector if factor == None: # Used for all calls after ball instance is initialised factor = self.factor angle = radians(random.randint(30,80)) rand_y = random.randrange(-1,2,2) y = sin(angle) x = cos(angle) """ How to get over the use of int and rounding errors. Using int the line before causes the vector to be 0,0 as the numbers after 0 are truncated""" self.vel_x, self.vel_y = (int(x*factor),int(y*factor)*rand_y) #print(x, y) return self.vel_x, self.vel_y ############################################################################# # Main Game Loop def main(): white = (255,255,255) border_height = 10 pad_width = int(win_w/50) pad_height = int(win_h/6) pad_left = paddle(pad_width, pad_height, speed, white) pad_right = paddle(pad_width, pad_height, speed, white) # Set X and Y of left pad pad_left.rect.topleft = (pad_distance, int((win_h-pad_height)/2)) # Set X and Y of right pad pad_right.rect.topleft = ((win_w-pad_distance-pad_width), int((win_h-pad_height)/2)) top_border = border(win_w, border_height, white) top_border.rect.topleft = (0, 0) bottom_border = border(win_w, border_height, white) bottom_border.rect.topleft = (0, win_h-border_height) gameBall = ball(10, 10, white) gameBall.rect.center = (int(win_w/2), int(win_h/2)) to_draw = [pad_left, pad_right, top_border, bottom_border, gameBall] redrawGameWin(to_draw) backGround = pygame.Surface((win_w,win_h)) backGround.fill(white) clock = pygame.time.Clock() # Game Loop while running: clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.display.quit() pygame.quit() sys.exit() keys = pygame.key.get_pressed() # Left pad moving up with top boundary collision if keys[pygame.K_s] and pad_left.rect.y &gt; 0: if pad_left.rect.y - top_border.height - pad_left.speed &lt;= 0 : pad_left.vel_y = 0 pad_left.moveTo(pad_distance, top_border.height) else: pad_left.vel_y = -pad_left.speed pad_left.move(0, pad_left.vel_y) # Left pad moving down with bottom boundary collision if keys[pygame.K_x]: if pad_left.rect.y + pad_left.height + pad_left.speed + bottom_border.height &gt;= win_h: pad_left.vel_y = 0 pad_left.moveTo(pad_distance, win_h-pad_left.height-bottom_border.height) else: pad_left.vel_y = pad_left.speed pad_left.move(0, pad_left.speed) if not keys[pygame.K_s] and not keys[pygame.K_x]: pad_left.vel_x, pad_left.vel_y = 0,0 # Right pad moving up with top boundary collision if keys[pygame.K_k]: if pad_right.rect.y - top_border.height - pad_right.speed &lt;= 0: pad_right.vel_y = 0 pad_right.moveTo(win_w-pad_distance-pad_right.width, top_border.height) else: pad_right.vel_y = -pad_right.speed pad_right.move(0, pad_right.vel_y) # Right pad moving down with bottom boundary collision if keys[pygame.K_m]: if pad_right.rect.y + pad_right.height + pad_right.speed + bottom_border.height &gt;= win_h: pad_right.vel_y = 0 pad_right.moveTo(win_w-pad_distance-pad_right.width, win_h-pad_right.height-bottom_border.height) else: pad_right.vel_y = pad_right.speed pad_right.move(0, pad_right.vel_y) if not keys[pygame.K_k] and not keys[pygame.K_m]: pad_right.vel_x, pad_right.vel_y = 0,0 # Ball bouncing off top border if gameBall.rect.colliderect(top_border.rect) or gameBall.rect.colliderect(bottom_border.rect): gameBall.vel_y = gameBall.vel_y*-1 # Ball bouncing off right pad if gameBall.rect.colliderect(pad_right.rect): gameBall.vel_x = -(gameBall.vel_x + pad_right.vel_x) gameBall.vel_y = gameBall.vel_y + pad_right.vel_y # Ball bouncing off left pad if gameBall.rect.colliderect(pad_left.rect): gameBall.vel_x = -(gameBall.vel_x + pad_left.vel_x) gameBall.vel_y = gameBall.vel_y + pad_left.vel_y # Ball moving by velocity vector gameBall.move(gameBall.vel_x, gameBall.vel_y) # Ball moves off screem if gameBall.rect.left &gt;= win_w or gameBall.rect.right &lt;=0: gameBall.randomMovement() gameBall.moveTo(int(win_w/2), int(win_h/2)) redrawGameWin(to_draw) ############################################################################# def redrawGameWin(shapes): #global dirty_rects win.fill((0,0,0)) for shape in shapes: shape.draw() pygame.display.flip() ############################################################################# if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:21:06.257", "Id": "468682", "Score": "3", "body": "Welcome to Code Review! Are you interested in adding features to your code or in reviewing the existing code? Please read the [help/on-topic] before answering that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T08:00:56.800", "Id": "468794", "Score": "0", "body": "@Mast Reviewing the existing code! And trying to address the problems I have outlined" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:02:33.350", "Id": "468836", "Score": "0", "body": "Reviewing the existing code is on topic for here but addressing that list of problems is not. You should likely edit the question to indicate that there are some functional problems but they will be addressed separately on stack overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T14:09:49.743", "Id": "468975", "Score": "1", "body": "@Reinderien Will do that now!" } ]
[ { "body": "<h2>Global code</h2>\n\n<p>This stuff:</p>\n\n<pre><code>pygame.init()\n\n# Create a screen\nwin = pygame.display.set_mode((800,700))\nwin_info = pygame.display.Info()\nwin_w, win_h = win_info.current_w, win_info.current_h\npygame.display.set_caption(\"Pong\")\n</code></pre>\n\n<p>should be moved into one or more functions. These:</p>\n\n<pre><code>pad_colour = (255,255,255) #White colour\n\npad_distance = 50\nspeed = 10\nrunning = True\nfps = 30\n</code></pre>\n\n<p>can probably stay in global scope as ALL_CAPS constants.</p>\n\n<h2>Class names</h2>\n\n<p><code>border</code> should be <code>Border</code> since it's a class name. The same goes for <code>Paddle</code>.</p>\n\n<h2>Statics</h2>\n\n<pre><code>class border(pygame.sprite.Sprite):\n width = win_w\n height = 10\n\n def __init__(self,width, height, colour):\n</code></pre>\n\n<p>I don't think that the first width/height variables do what you think they do. Currently they can be deleted. If you want them to take effect as defaults, then you'd actually write</p>\n\n<pre><code>class border(pygame.sprite.Sprite):\n def __init__(self, colour, width=win_w, height=10):\n</code></pre>\n\n<h2>Method names</h2>\n\n<p>should be snake_case, i.e.</p>\n\n<p><code>random_movement</code>, <code>collide_pad</code>, etc.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>The code to check the left/right pad is very repetitive. Think about what is shared and what differs, and factor out the differing stuff. So far as I can see, the differences include the references to the key constants <code>K_s</code>, some distance calculations, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T16:28:22.990", "Id": "239236", "ParentId": "238990", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T09:21:37.637", "Id": "238990", "Score": "1", "Tags": [ "python", "pygame" ], "Title": "Pong in Python using Pygame" }
238990
<p>In a mysql db environment there's not really a custom global variable option. One may need that for example a certain date, in order to perhaps merge two sources of data: one legacy, and one current etc.</p> <p>Using udf may slow down the queries quite a lot. Instead one could use a single row table:</p> <pre><code>CREATE TABLE `merge_date` ( `SingleRow` enum('') COLLATE utf8_unicode_ci NOT NULL, -- enforce single row `Date` date NOT NULL, -- the actual value to be used UNIQUE KEY `merge_date_SingleRow_uindex` (`SingleRow`) -- enforce single row ) </code></pre> <p>Example usage:</p> <pre><code>SELECT * FROM legacy_table lt CROSS JOIN merge_date md WHERE lt.Date &lt;= md.Date UNION ALL SELECT * FROM table t CROSS JOIN merge_date md WHERE md.Date &lt; t.Date </code></pre> <ul> <li>I'd like to know if it could be further purified or improved in some other way.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T20:40:34.353", "Id": "473530", "Score": "0", "body": "What problem does this exactly solve? Also, am I right in assuming that UDF mean \"User Defined Function\"? There are other meanings of this abbreviation, that's why I'm asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T15:25:11.760", "Id": "473654", "Score": "0", "body": "@KIKOSoftware I use this when it's required to show both legacy data and the data in the current structure. It makes it so that they both refer to the exact same date without repeating it, so it improves integrity. Yes, I meant to abbreviate User Defined Function with UDF.\n\nAlso keep in mind that I no longer use such functions, instead I use single row'd tables'." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T09:51:34.600", "Id": "238991", "Score": "0", "Tags": [ "mysql" ], "Title": "Data Integrity Through Custom Variable" }
238991
<p>I would be especially happy to hear opinions about <code>complement_union</code>. The rest of the code is just there to test the output.</p> <pre><code>program test_complement_union implicit none(type, external) call assert(all([3, 5] == complement_union([1, 2, 3], [1, 2], [5]))) call assert(all([2, 3, 4] == complement_union([1, 2, 3], [1], [4]))) call assert(all([1, 3, 5] == complement_union([1, 2, 3], [2], [5]))) contains !&gt; Merge C into A and remove values that are in B. !&gt; The result can be written with set notation as A ∪ C / B. !&gt; Preconditions (not tested!): !&gt; 1. B is a subset of A !&gt; 2. A and C are disjoint !&gt; 3. B and C are disjoint !&gt; 4. A, B, and C are sorted. pure function complement_union(A, B, C) result(D) integer, intent(in) :: A(:), B(:), C(:) integer :: D(size(A) + size(C) - size(B)) ! We will index as A(i), B(j), C(k), D(l) integer :: i, j, k, l i = 1 j = 1 k = 1 l = 1 do while(l &lt;= size(D)) ! Only indices from C have to be added to A ! We use assumption that B is a subset of A if (i &gt; size(A)) then D(l) = C(k) k = k + 1 l = l + 1 ! Neither indices from B have to be deleted in A ! nor indices from C have to be added from C to A. else if (j &gt; size(B) .and. k &gt; size(C)) then D(l) = A(i) i = i + 1 l = l + 1 ! No more indices from B have to be deleted in A else if (j &gt; size(B)) then if (A(i) &lt; C(k)) then D(l) = A(i) i = i + 1 l = l + 1 else if (A(i) &gt; C(k)) then D(l) = C(k) k = k + 1 l = l + 1 end if ! No more indices have to be added from C to A else if (k &gt; size(C)) then if (A(i) /= B(j)) then D(l) = A(i) i = i + 1 l = l + 1 else i = i + 1 j = j + 1 end if ! Normal case: ! Merge C sorted into A excluding values from B. else if (A(i) &lt; C(k)) then if (A(i) /= B(j)) then D(l) = A(i) i = i + 1 l = l + 1 else i = i + 1 j = j + 1 end if else if (A(i) &gt; C(k)) then if (A(i) /= B(j)) then D(l) = C(k) k = k + 1 l = l + 1 else D(l) = C(k) i = i + 1 j = j + 1 k = k + 1 l = l + 1 end if end if end do end function pure subroutine assert(cond) logical, intent(in) :: cond if (.not. cond) error stop end subroutine end program <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>This code has two limitations, as I see it:</p>\n<ol>\n<li>in treating in a single go the combination of three sets, it gives rise to a high cyclomatic complexity: a dozen if statements (including the while) in a single function. This circumstance limits the readability and maintainability of the code. It also makes it less extensible to more general cases.</li>\n<li>the assumption that B is a subset of A and C is disjoint from either is very particular, and likely to limit the reuse of the code elsewhere.</li>\n</ol>\n<p>As a minor point, the assertions stop the program in case a problem is detected but they do not indicate which test fails, or if other tests would have failed, which comes in handy in debug.</p>\n<p>The input vectors are assumed to be sorted in increasing order. If that were not the case, one could do that first, and increase the generality of the code further.</p>\n<p>Leaving aside for a moment the possible generalization of the code, by splitting the operation into a subtraction of B from A and a subsequent addition of C, the complexity drops drastically. Instead of a single pure function with 55 lines of code (header and declarations excluded) and 12 branching points (if and while), one can write three pure functions, with 2, 11, and 21 lines of code and only 0, 2, and 3 branching points, respectively:</p>\n<pre class=\"lang-fortran prettyprint-override\"><code>program test_complement_union\n \n implicit none(type, external)\n \n call assert( &quot;t1&quot;, all([3, 5] == complement_union([1, 2, 3], [1, 2], [5] )))\n call assert( &quot;t2&quot;, all([2, 3, 4] == complement_union([1, 2, 3], [1] , [4] )))\n call assert( &quot;t3&quot;, all([1, 3, 5] == complement_union([1, 2, 3], [2] , [5] )))\n call assert( &quot;t4&quot;, all([1, 4, 5, 6] == complement_union([1, 2, 3], [2, 3], [4, 5, 6])))\n\n contains\n\n !&gt; Merge C into A and remove values that are in B.\n !&gt; The result can be written with set notation as A ∪ C / B.\n !&gt; Preconditions (not tested!):\n !&gt; 1. B is a subset of A\n !&gt; 2. A and C are disjoint\n !&gt; 3. B and C are disjoint\n !&gt; 4. A, B, and C are sorted.\n pure function complement_union(A, B, C) result(D)\n integer, intent(in) :: A(:), B(:), C(:)\n integer :: A_B( size(A) - size(B) )\n integer :: D ( size(A) + size(C) -size(B) )\n A_B = subtract_subset(A,B)\n D = union_disjoint_sets(A_B,C)\n end function complement_union\n \n !&gt; Subtract a proper ordered subset from a given ordered set\n pure function subtract_subset( A, B ) result( C )\n integer, intent(in) :: A(:), B(:)\n integer :: C ( size(A) - size(B) ), iA, iB, iC\n iC = 0\n iA = 1\n !.. All elements of B are expected to be found in A\n do iB = 1, size(B)\n !.. Copies the elements of A between consecutive\n ! occurrences of B elements\n do while( A(iA) /= B(iB) )\n iC = iC + 1\n C(iC) = A(iA)\n iA = iA + 1\n enddo\n !.. Skips the B element\n iA = iA + 1\n enddo \n !.. Copies the elements of A past the last element of B\n if( iA &lt;= size(A) ) C(iC+1:) = A(iA:)\n end function subtract_subset\n \n !&gt; Computes the union of non-empty disjoint ordered sets\n pure function union_disjoint_sets( A, B ) result( C )\n integer, intent(in) :: A(:), B(:)\n integer :: C( size(A) + size(B) )\n integer :: iA, iB, iC, nA, nB\n nA = size(A)\n nB = size(B)\n iA = 1\n iB = 1\n iC = 0\n C = 0\n !.. Takes an element from either A or B\n ! until one of the sets is empty\n do while( iA &lt;= nA .and. iB &lt;= nB )\n iC = iC + 1\n if( A(iA) &lt;= B(iB) )then\n C(iC) = A(iA)\n iA = iA + 1\n else\n C(iC) = B(iB)\n iB = iB + 1\n endif\n end do\n !.. Copies to C the residual elements in\n ! the remaining non-empty set\n if( iA &lt;= nA )then\n C(iC+1:)=A(iA:)\n else\n C(iC+1:)=B(iB:)\n endif\n end function union_disjoint_sets\n \n subroutine assert(msg,cond)\n use, intrinsic :: iso_fortran_env, only : OUTPUT_UNIT\n character(len=*), intent(in) :: msg\n logical , intent(in) :: cond\n write(OUTPUT_UNIT,&quot;(a)&quot;,advance=&quot;no&quot;) msg//&quot; - &quot;\n if( cond )then\n write(OUTPUT_UNIT,&quot;(a)&quot;) &quot;passed&quot;\n else\n write(OUTPUT_UNIT,&quot;(a)&quot;) &quot;FAILED&quot;\n endif\n end subroutine assert\n\n end program test_complement_union\n</code></pre>\n<p>If the restrictions on the three sets, A, B, and C are removed, except for their being ordered, in general, the size of ( A U C ) / B will be different from size(A)-size(B)+size(C). Furthermore, ( A / B ) U C /= ( A U C ) / B. Let's consider the latter operation, which is a bit more challenging. If one does not want give up automatic arrays, then I think there is no alternative to having trailing &quot;empty&quot; entries in the result (e.g., zeros). Even in this case, it is best to split the work into functions that provide two disjoint sets to be merged. The subtraction here is more complicated because in general B would not be a subset of A and C may have elements in common with both B and A. Therefore, one must first figure out the A/B, C/B and C/B/A, by means of a difference function, and then merge the result, which is simple, since the sets are disjoint :\n<span class=\"math-container\">$$( A \\cup C ) / B = ( A / B ) \\cup ( ( C / B ) / A ) $$</span>\nwhere <span class=\"math-container\">$$( A / B ) \\cap ( ( C / B ) / A ) = \\varnothing$$</span>\nHere's a sketch of the idea</p>\n<pre class=\"lang-fortran prettyprint-override\"><code>program test_complement_union\n \n implicit none(type, external)\n \n call assert( &quot;t1&quot;, all([3, 5, 0, 0] == complement_union([1, 2, 3], [1, 2], [5] )))\n call assert( &quot;t2&quot;, all([2, 3, 4, 0] == complement_union([1, 2, 3], [1] , [4] )))\n call assert( &quot;t3&quot;, all([1, 3, 5, 0] == complement_union([1, 2, 3], [2] , [5] )))\n call assert( &quot;t4&quot;, all([1, 3, 5, 0, 0, 0] == complement_union([1, 2, 3], [2, 9], [1, 2, 5])))\n\n contains\n\n !.. Assumes input vectors are sorted (!)\n ! If that is not the case, the vectors should\n ! be sorted into auxiliary arrays\n !..\n function complement_union(A, B, C) result(D)\n integer, intent(in) :: A(:), B(:), C(:)\n integer :: A_B(size(A))\n integer :: C_B(size(C))\n integer :: C_AB(size(C))\n integer :: D (size(A) + size(C))\n A_B = difference(A,B)\n C_B = difference(C,B)\n C_AB = difference(C_B,A_B)\n D = union_disjoint_sets(A_B,C_AB)\n end function complement_union\n \n !.. Computes the difference between the two sets,\n ! generating a set with the same size as the first\n ! with trailing zeros for the erased fields.\n function difference( A, B ) result( C )\n integer, intent(in) :: A(:), B(:)\n integer :: C ( size(A) ), iA, iB, iC, nA, nB, nC\n nA=count(A/=0)\n nB=count(B/=0)\n if(nB==0)then\n C=A\n return\n endif\n iC=0\n iB=1\n nC=nA\n outer: do iA = 1, nA\n do while( B(iB) &lt; A(iA) )\n iB = iB + 1\n if( iB &gt; nB) exit outer\n end do\n if( B(iB) == A(iA) )then\n nC=nC-1\n cycle outer\n endif\n iC = iC + 1\n C(iC) = A(iA)\n enddo outer\n if( iB &gt; nB ) C(iC+1:nC) = A(iA:nA)\n if( nC &lt; size(A) ) C(nC+1:) = 0\n end function difference\n \n !.. Computes the union of disjoint sets\n pure function union_disjoint_sets( A, B ) result( C )\n integer, intent(in) :: A(:), B(:)\n integer :: C( size(A) + size(B) )\n integer :: iA, iB, iC, nA, nB, nC\n nA = count( A /= 0 )\n nB = count( B /= 0 )\n nC = nA + nB\n iA = 1\n iB = 1\n iC = 0\n C = 0\n do while( iA &lt;= nA .and. iB &lt;= nB )\n iC = iC + 1\n if( A(iA) &lt;= B(iB) )then\n C(iC) = A(iA)\n iA = iA + 1\n else\n C(iC) = B(iB)\n iB = iB + 1\n endif\n end do\n if( iA &lt;= nA )then\n C(iC+1:nC)=A(iA:nA)\n else\n C(iC+1:nC)=B(iB:nB)\n endif\n end function union_disjoint_sets\n \n subroutine assert(msg,cond)\n use, intrinsic :: iso_fortran_env, only : OUTPUT_UNIT\n character(len=*), intent(in) :: msg\n logical , intent(in) :: cond\n write(OUTPUT_UNIT,&quot;(a)&quot;,advance=&quot;no&quot;) msg//&quot; - &quot;\n if( cond )then\n write(OUTPUT_UNIT,&quot;(a)&quot;) &quot;passed&quot;\n else\n write(OUTPUT_UNIT,&quot;(a)&quot;) &quot;FAILED&quot;\n endif\n end subroutine assert\n\n end program test_complement_union\n</code></pre>\n<p>PS:\nFor folks not familiar with the simple syntax of modern Fortran, I suggest the following <a href=\"https://fortran-lang.org/learn/quickstart\" rel=\"nofollow noreferrer\">quick modern Fortran tutorial</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T18:50:17.190", "Id": "502260", "Score": "1", "body": "Thank you for looking back into this code.\n> In general, it will be smaller. \nI completely agree, but this code snippet emerged from an actual problem where I know that the assumed conditions (B and A disjoint, etc.) are fullfilled. So I wanted a specialiced function that can use all those conditions to be hopefully(?) as fast as possible.\nFor general code I would implement it with variable lengths of course, although I would use allocatable arrays, because now one cannot use the `0` as value in the set anymore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T18:53:34.130", "Id": "502262", "Score": "1", "body": "correction: it could even be larger than size(A) + size(C) - size(B), depending how many elements of B are in A u C. In any case, it would in general be different. e.g.: A={1,2,3}, C={1}, B={4,5,6,7}. size( (AuC)/B ) = size( {1,2,3} ) = 3 /= size(A)+size(C)-size(B) = 0." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T23:45:02.373", "Id": "502382", "Score": "0", "body": "@Toby Speight Sure, I will motivate the solution offered above, which reduces the complexity of the original and removes some of its constraints (all except the ordering of the sets and the circumstance that they must have non-zero size). I will also offer an alternative version that assumes the same constraints originally indicated by mcocdawc, giving rise to a solution that is shorter and simpler to follow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-15T07:49:36.713", "Id": "502397", "Score": "0", "body": "Greatly improved - thank you! (and +1)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T17:43:22.270", "Id": "254659", "ParentId": "238992", "Score": "2" } } ]
{ "AcceptedAnswerId": "254659", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T10:08:05.673", "Id": "238992", "Score": "2", "Tags": [ "mergesort", "fortran" ], "Title": "Return union and complement of three sets" }
238992
<p>The function below is part of a trading system. Its purpose is to assign a volume (order size) to a bid (buy) quote and and ask (sell) quote, depending on the value of the <code>position_size</code> argument. </p> <p>This trading system strictly cannot exceed a position limit of 100 in either direction, so our order volumes need to never exceed 100 when combined with the absolute value of <code>current position</code>.</p> <p>However there is one caveat. Occasionally, for uncontrollable external reasons, a bid or ask (buy or sell order) will be executed twice before its price can be re-adjusted. </p> <p>So any <code>bid_volume</code> or <code>ask_volume</code> returned by this function needs to be at most, half the value of 100 - <code>position_size</code>, in order to account for the occasional double execution. </p> <p>Thats why at any step of the if-else blocks below, doubling the <code>ask_volume</code> or <code>bid_volume</code> plus <code>current_position</code> will not exceed 100.</p> <p><strong>What is the fastest way to achieve this with Python, other than the below code?</strong></p> <pre><code>def adjust_volume(position_size): # Long. if position_size &gt; 0: if position_size &lt; 45: bid_volume = 45 - position_size ask_volume = 50 elif position_size &gt;= 45 and position_size &lt; 65: bid_volume = 65 - position_size ask_volume = 50 elif position_size &gt;= 65 and position_size &lt; 82: bid_volume = 82 - position_size ask_volume = 50 elif position_size &gt;= 82 and position_size &lt; 100: bid_volume = 91 - position_size ask_volume = 85 # Short. elif position_size &lt; 0: abs_position_size = abs(position_size) if position_size &gt; -45: bid_volume = 10 ask_volume = 45 - abs_position_size elif position_size &lt;= -45 and position_size &gt; -65: bid_volume = 50 ask_volume = 65 - abs_position_size elif position_size &lt;= -65 and position_size &gt; -82: bid_volume = 50 ask_volume = 82 - abs_position_size elif position_size &lt;= -82 and position_size &gt; -100: bid_volume = 75 ask_volume = 85 - abs_position_size elif position_size == 0: bid_volume = 30 ask_volume = 30 return position_size, bid_volume, ask_volume position_size, bid_volume, ask_volume = adjust_volume(-76) print("bid_volume:", bid_volume) print("ask_volume:", ask_volume) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T15:56:10.400", "Id": "468724", "Score": "0", "body": "This is fun. I'll whip up an example in a minute." } ]
[ { "body": "<h1>Bug</h1>\n\n<p><code>adjust_volume(0)</code> presently results in:</p>\n\n<blockquote>\n <p>UnboundLocalError: local variable 'bid_volume' referenced before assignment</p>\n</blockquote>\n\n<p>since <code>if position_size == 0:</code> is currently indented inside the <code>elif position_size &lt; 0:</code> statement, so is unreachable. (This could be a result of poor formatting when copying the code into the question post.)</p>\n\n<h1>Possible Bug</h1>\n\n<p>Some volume calculations result in negative volumes. (<code>adjust_volume(99)</code> gives <code>bid_volume == -8</code>, and <code>adjust_volume(-99)</code> gives <code>ask_volume == -14</code>, which seem like invalid results.)</p>\n\n<h1>Possible Bug</h1>\n\n<p>If <code>adjust_volume()</code> is given an argument >= 100 or &lt;= -100, it also fails with an <code>UnboundLocalError</code>. Limits should be checked and a <code>ValueError</code> be raised instead.</p>\n\n<blockquote>\n <p>This trading system strictly cannot exceed a position limit of 100 in either direction, so our order volumes need to never exceed 100 when combined with the absolute value of <code>current position</code>.</p>\n</blockquote>\n\n<p>100 does not exceed 100, so it is likely the original implementation should have allowed <code>+100</code> and <code>-100</code> as well. But these currently result in <code>UnboundLocalError</code>.</p>\n\n<h1>Chained comparisons</h1>\n\n<p>I have to say, this condition makes my brain hurt:</p>\n\n<pre><code> elif position_size &lt;= -65 and position_size &gt; -82:\n</code></pre>\n\n<p>It took me several moments to unwind what the range was, and I had to triple check that I got it right. It would be much clearer to express as:</p>\n\n<pre><code> elif -82 &lt; position_size and position_size &lt;= -65:\n</code></pre>\n\n<p>or using the chaining comparison operations:</p>\n\n<pre><code> elif -82 &lt; position_size &lt;= -65:\n</code></pre>\n\n<h1>Bisect</h1>\n\n<p>You have 9 ranges:</p>\n\n<ul>\n<li>-100 &lt; position_size &lt;= -82</li>\n<li>-82 &lt; position_size &lt;= -65</li>\n<li>-65 &lt; position_size &lt;= -45</li>\n<li>-45 &lt; position_size &lt; 0</li>\n<li>0 &lt;= position_size &lt;= 0</li>\n<li>0 &lt; position_size &lt; 45</li>\n<li>45 &lt;= position_size &lt; 65</li>\n<li>65 &lt;= position_size &lt; 82</li>\n<li>82 &lt;= position_size &lt; 100</li>\n</ul>\n\n<p>Instead of using a tree of <code>if</code>-<code>elif</code>-<code>else</code> statements to locate the correct range, you could <code>bisect</code> the list <code>-81, -64, -44, 0, 1, 45, 65, 82</code> to determine the correct range bucket.</p>\n\n<p><em>Note</em>: Negative bucket limits have been increased by 1 to account for the difference in whether the lower limit or the upper limit is included as <code>position_size</code> goes from negative values to positive values.</p>\n\n<pre><code>from bisect import bisect\n\nPOSITION = (-81, -64, -44, 0, 1, 45, 65, 82,)\nBID_ASK = (\n (75, 85), # -100 &lt; pos &lt;= -82\n (50, 82), # -82 &lt; pos &lt;= -65\n (50, 65), # -65 &lt; pos &lt;= -45\n (10, 45), # -45 &lt; pos &lt; 0\n (30, 30), # 0 &lt;= pos &lt;= 0\n (45, 50), # 0 &lt; pos &lt; 45\n (65, 50), # 45 &lt;= pos &lt; 65\n (82, 50), # 65 &lt;= pos &lt; 82\n (91, 85), # 82 &lt;= pos &lt; 100\n)\n\ndef adjust_volume(position_size):\n\n if not(-100 &lt; position_size &lt; 100):\n raise ValueError(\"position size out of range\")\n\n bucket = bisect(POSITION, position_size)\n\n bid_volume, ask_volume = BID_ASK[bucket]\n if position &gt;= 0:\n bid_volume -= position_size\n else:\n ask_volume -= abs(position_size)\n\n return position_size, bid_volume, ask_volume\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T19:30:43.393", "Id": "468744", "Score": "2", "body": "Yeah, roughly what I was going to propose. `position_size <= -100 or position_size >= 100` should be `not (-100 < position_size < 100)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:22:32.750", "Id": "468755", "Score": "0", "body": "@Reinderien “should be” may be a little strong; “could be” would be accurate. It would be slightly shorter which is a plus. Negative logic statements are often less clear, but here, “if not (valid range): raise Error” does read fairly clearly. Ok, you’ve convinced me; I’ll change it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T23:27:05.230", "Id": "468766", "Score": "1", "body": "Big fan of the chained comparisons. I find using only one operator, `<`, and ordering the values lowest to highest increases readability a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T23:28:31.610", "Id": "468767", "Score": "0", "body": "Sorry, yes, your guess was correct, the `if position_size == 0` indentation is incorrect after copying from the script. It should be outside the `elif position_size < 0: statement`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:42:39.140", "Id": "239011", "ParentId": "238998", "Score": "5" } } ]
{ "AcceptedAnswerId": "239011", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T14:33:56.063", "Id": "238998", "Score": "5", "Tags": [ "python", "performance", "algorithm", "python-3.x", "finance" ], "Title": "Calculate quote volumes (for a financial instrument) within numeric constraints" }
238998
<p>Long time reader of <strong>Code Review</strong> with my first question. I'm self-taught and suspect this code can be improved. The project is really important to me and the team and I could really use the help. </p> <p>I'm using this as part of a larger script run through the terminal which takes a <code>GeoDataFrame</code> and adds the GPS coordinates as a <code>Point</code> per the specification, and then outputs a GDF again. (I then export it as a <code>geojson</code> file.) So far it's running through ~3500 rows in about 2 hours - which is fine - but I don't think I'm using many coding best practices. I'd like to make it as robust as possible because we have some datasets to run through that are +15000 rows. Does anyone have any feedback on this script?</p> <pre><code>import pandas as pd import geopandas as gpd from shapely.geometry import Point import geopy as gpy from geopy.geocoders import GoogleV3 from geopy.extra.rate_limiter import RateLimiter from geopy.exc import GeocoderTimedOut from geopy.location import Location def addressParsing(gdf_obj, delayseconds): """ This takes a whole GeoDataFrame and adds the Geo Coords from the standard address before returning the udpated Geodataframe """ # Returned class obj if None site = Location("0", (0.0, 0.0, 0.0)) def do_geocode(address): try: return geocode_with_delay(address) except GeocoderTimedOut: return geocode_with_delay(address) print(f"starting parser: {gdf_obj.shape}, estimated time: {round(delayseconds * gdf_obj.shape[0] / 60, 2)} min") # Initiate geocoder geolocator = GoogleV3(api_key=g_api_key) # Create a geopy rate limiter class: geocode_with_delay = RateLimiter( geolocator.geocode, error_wait_seconds=delayseconds + 20, min_delay_seconds=delayseconds, swallow_exceptions=True, return_value_on_exception= site ) # Apply the geocoder with delay using the rate limiter: gdf_obj['temp'] = gdf_obj['Address'].apply(do_geocode) # Get point coordinates from the GeoPy location object on each row, drop z vector data: gdf_obj["coords"] = gdf_obj['temp'].apply(lambda loc: tuple(loc.point)[:2] if loc else tuple(site.point)[:2]) # Create shapely point objects to geometry column: gdf_obj["geometry"] = gdf_obj["coords"].apply(Point) # Drop intermediate columns gdf_obj = gdf_obj.drop(["temp", "coords"], axis=1) print("FINISHED - conversion successful - check shape") return gdf_obj </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T15:24:14.313", "Id": "468718", "Score": "2", "body": "_Long time reader of Code Review with my first question_ - Welcome, that's exciting :)" } ]
[ { "body": "<h2>Nomenclature</h2>\n\n<p>Function names should be snake_case per PEP8, i.e. <code>address_parsing</code>.</p>\n\n<h2>Type hinting</h2>\n\n<p>For function parameters and return values mainly, type hinting will help define your signatures. For example, <code>delayseconds</code> would probably become <code>delay_seconds: float</code>, and <code>gdf_obj: dict</code> if you don't know a lot about the structure of the dictionary. So:</p>\n\n<pre><code>def address_parsing(gdf_obj: dict, delay_seconds: float) -&gt; dict:\n</code></pre>\n\n<h2>Retries:</h2>\n\n<pre><code> try:\n return geocode_with_delay(address)\n except GeocoderTimedOut:\n return geocode_with_delay(address)\n</code></pre>\n\n<p>Effectively this will ignore up to one <code>GeocoderTimedOut</code> and retry, but if it occurs twice the exception will fall through. A saner way to represent this is:</p>\n\n<pre><code>TRIES = 2\n# ...\n\nfor retry in range(TRIES):\n try:\n return geocode_with_delay(address)\n except GeocoderTimedOut as e:\n print('Geocoder timed out')\nraise e\n</code></pre>\n\n<h2>Temporary variables</h2>\n\n<p>The expression</p>\n\n<pre><code>round(delayseconds * gdf_obj.shape[0] / 60, 2)\n</code></pre>\n\n<p>is complex enough that it should be assigned to a variable. That said, you're better off using Python's actual time-handling features:</p>\n\n<pre><code>from datetime import timedelta\n# ...\n\nest_time = timedelta(seconds=delayseconds * gdf_obj.shape[0])\nprint(f'Estimated time: {est_time}') # will do pretty formatting\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T16:11:39.080", "Id": "468725", "Score": "1", "body": "`gdf_object` is probably some subclass of a pandas dataframe" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T23:10:09.847", "Id": "468765", "Score": "0", "body": "Man I love SE. That is just so helpful as a self-directed learner." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T15:39:30.323", "Id": "239002", "ParentId": "239000", "Score": "5" } }, { "body": "<p>Nesting function definitions can often be useful, but it's not what you should normally do. Really, everything should be moved <em>outside</em> of the function unless there's a reason (including readability) for it to be inside.</p>\n\n<p>I would also suggest that <code>delayseconds</code> could be an external setting. Or give it a default value. Also, it seems likely that <code>delayseconds</code> is a big part of why the script takes so long!</p>\n\n<p>I'll assume you want <code>delayseconds</code> as a parameter, so I'll use functools to help keep it abstract.</p>\n\n<p><code>do_geocode</code> could be more descriptively named.</p>\n\n<p><code>site</code> needs a better name. Also it looks like you're building a whole object and only using part of it, but I may have misunderstood.</p>\n\n<p>Rather than having temporary columns, package your computation up into a single applyable step.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import partial\n\nimport pandas as pd\nimport geopandas as gpd\nfrom shapely.geometry import Point\nimport geopy as gpy\nfrom geopy.geocoders import GoogleV3\nfrom geopy.extra.rate_limiter import RateLimiter\nfrom geopy.exc import GeocoderTimedOut\nfrom geopy.location import Location\n\n\ndefault_coordinates = (0.0, 0.0)\n\n# Initiate geocoder\ngeolocator = GoogleV3(api_key=g_api_key)\n\n# Create a geopy rate limiter class:\ndef geocode_with_delay(delayseconds):\n return RateLimiter(\n geolocator.geocode,\n error_wait_seconds=delayseconds + 20,\n min_delay_seconds=delayseconds,\n swallow_exceptions=True,\n return_value_on_exception= site\n )\n\ndef point_of_location(loc):\n if loc:\n return Point(tuple(loc.point)[:2])\n else:\n return Point(default_coordinates)\n\ndef try_geocode(address, geo_coder):\n try:\n return point_of_location(geo_coder(address))\n except GeocoderTimedOut:\n return point_of_location(geo_coder(address)) # Is there a reason not to just have a default Point()?\n\ndef addressParsing(gdf_obj, delayseconds = 0):\n \"\"\"\n This takes a whole GeoDataFrame and adds the Geo Coords from the standard address\n before returning the udpated Geodataframe\n \"\"\"\n\n print(f\"starting parser: {gdf_obj.shape}, estimated time: {round(delayseconds * gdf_obj.shape[0] / 60, 2)} min\")\n\n rate_limited = geocode_with_delay(delayseconds)\n geocode_action = partial(try_geocode, geo_coder=rate_limited)\n\n # Apply the geocoder with delay using the rate limiter:\n gdf_obj['geometry'] = gdf_obj['Address'].apply(geocode_action)\n\n print(\"FINISHED - conversion successful - check shape\")\n return gdf_obj\n</code></pre>\n\n<p>I haven't tested this even to see if it runs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T16:14:28.783", "Id": "468726", "Score": "2", "body": "I haven't attempted to incorporate @Reinderien's advice, which is all good advice and I think compatible with the changes I suggested." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T16:10:25.737", "Id": "239005", "ParentId": "239000", "Score": "3" } } ]
{ "AcceptedAnswerId": "239002", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T15:05:29.840", "Id": "239000", "Score": "7", "Tags": [ "python", "pandas", "geospatial" ], "Title": "Parsing Addresses with GeoPanda's GeoDataFrame" }
239000
<p><strong>Q: Am I approaching writing idiomatic Rust code correctly?</strong></p> <p>Hi CodeReview, I'm a beginner Rustacean coming from Python going through Rust books (The Rust Book, Rust in Action). A lot of the beginner code has unwrap everywhere and I'd like to write more idiomatic Rust.</p> <p>I wrote 2 versions of a simple CLI program that reads a file and prints it to stdout, one with <code>.unwrap</code> and one without.</p> <p>Both version execute successfully and do the same thing, only differing in the error-handling.</p> <p>I tried to expand out all cases of <code>.unwrap</code> based on things in the official docs about using <code>.unwrap</code><a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap" rel="nofollow noreferrer">[1]</a><a href="https://doc.rust-lang.org/stable/rust-by-example/error.html" rel="nofollow noreferrer">[2]</a><a href="https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html" rel="nofollow noreferrer">[3]</a>. </p> <h1>Protoyping</h1> <pre class="lang-rust prettyprint-override"><code>extern crate clap; use std::{ prelude, io::{BufRead, BufReader}, fs::File, }; use clap::{App, Arg}; fn main() { let matches = App::new("File reader") .about("Read a file line by line") .help("The help text") .version("0.1") .arg(Arg::with_name("input") .value_name("INPUT") .takes_value(true) .help("Any text file to be read")) .get_matches(); // Get input argument, ensure it is valid let input = matches.value_of("input").unwrap(); // Try and open the file let f = File::open(input).unwrap(); // Load the file into BufReader let reader = BufReader::new(f); // Read the lines of the file for line_ in reader.lines() { let line = line_.unwrap(); println!("{}", line); } } </code></pre> <h1>Improving robustness</h1> <pre class="lang-rust prettyprint-override"><code>use std::{ error::Error, // prelude::*, io::{BufRead, BufReader}, fs::File, }; use clap::{App, Arg}; fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; { let matches = App::new("File reader") .about("Read a file line by line") .help("The help text") .version("0.1") .arg(Arg::with_name("input") .value_name("INPUT") .takes_value(true) .help("Any text file to be read")) .get_matches(); // Get input argument, ensure it is valid let input = matches.value_of("input"); let input = match input { Some(file) =&gt; file, None =&gt; matches.usage(), }; // Try and open the file let f = File::open(input)?; // Load the file into BufReader let reader = BufReader::new(f); // Read the lines of the file // "if let" reads "if 'let' destructures line_ into Ok(line) value, evaluate {}" for line_ in reader.lines() { if let Ok(line) = line_ { println!("{}", line); }; } Ok(()) } </code></pre> <p>Am I approaching making my code more idiomatic correctly? </p> <p><strong>Edit 2</strong>: My second take at making it more readable/idiomatic (<code>fn main</code> only)</p> <pre class="lang-rust prettyprint-override"><code>fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; { let matches = App::new("File reader") .about("Read a file line by line") .help("The help text") .version("0.1") .arg(Arg::with_name("input") .value_name("INPUT") .takes_value(true) .help("Any text file to be read")) .get_matches(); // Get input argument, ensure it is valid let input = match matches.value_of("input") { Some(input) =&gt; input, None =&gt; matches.usage(), }; // Try and open the file if let Ok(f) = File::open(input){ // If valid, load into BufReader then read the file line by line let reader = BufReader::new(f); for line_ in reader.lines() { if let Ok(line) = line_ { println!("{}", line); }; }; } else { // If file is not valid, print the CLI usage println!("{}", matches.usage()) }; Ok(()) } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T16:20:54.173", "Id": "239006", "Score": "3", "Tags": [ "beginner", "comparative-review", "file", "io", "rust" ], "Title": "Simple beginner Rust CLI file reader that prints to stdout" }
239006
<p>Please provide any suggestions on the below code for <a href="https://en.wikipedia.org/wiki/Topological_sorting#Kahn&#39;s_algorithm" rel="nofollow noreferrer">Kahn's algorithm</a>. Can it be implemented in a better manner, or be improved:</p> <pre><code>def kahn(graph): in_degree = {u : 0 for u in graph} for vertices, neighbors in graph.items(): in_degree.setdefault(vertices, 0) for neighbor in neighbors: in_degree[neighbor] = in_degree.get(neighbor, 0) + 1 no_indegree_vertices = {vertex for vertex, count in in_degree.items() if count == 0} topological_sort = [] while no_indegree_vertices: vertex = no_indegree_vertices.pop() topological_sort.append(vertex) for neighbor in graph.get(vertex, []): in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: no_indegree_vertices.add(neighbor) if len(topological_sort) != len(in_degree): print("Graph has cycles; It is not a directed acyclic graph ... ") return None else: return topological_sort </code></pre> <p>Test Data:</p> <pre><code>test_graph1 = { 'A' : set(['B','S']), 'B' : set(['A']), 'C' : set(['D','E','F','S']), 'D' : set(['C']), 'E' : set(['C','H']), 'F' : set(['C','G']), 'G' : set(['F','S']), 'H' : set(['E','G']), 'S' : set(['A','C','G']) } test_graph2 = { 'A': [], 'B': ['A'], 'C': ['B'] } test_graph3 = { 5: [2], 5: [0], 4: [0], 4: [1], 2: [3], 3: [1] } test_graph4 = { 1: [2], 2: [3], 4: [2], 5: [3] } </code></pre>
[]
[ { "body": "<ul>\n<li>Be explicit about the data structure you're using, and the assumptions. For example, a comment like this would be helpful for any future readers(including yourself): \"We represent a graph as adjacency list stored in a Python dictionary. The adjacency list can contain nodes that are not present in the keys of the dictionary, and they should be treated as nodes that contain no outward edges.\"</li>\n<li>I suspect that it's a bad idea to allow nodes that are not present in the keys. Conventionally, an adjacency list should have one entry for each node, whether they have outward edges or not. Moreover, it causes a lot of headache in implementations(To access a dictionary, we had to use <code>get()</code> method instead of the more straightforward square bracket notation). </li>\n<li>The first five lines of your function essentially counts each nodes' occurrence. If you require that all nodes should be present in the keys of the dictionary, it can be implemented in a single line:</li>\n</ul>\n\n<pre><code>in_degree = {u: sum(u in v for v in graph.values()) for u in graph}\n</code></pre>\n\n<ul>\n<li><code>topological_sort</code> sounds like a verb. Try use a noun for variable names, such as <code>sorted_nodes</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T12:49:56.237", "Id": "239099", "ParentId": "239008", "Score": "2" } } ]
{ "AcceptedAnswerId": "239099", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:20:35.857", "Id": "239008", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x", "sorting", "graph" ], "Title": "Python implementation of Kahn's Algorithm" }
239008
<p>For my robot hobby project I need to expose the system's configuration so I can quickly make changes to it. So I have made a very simple app that generates a form. In this form you can edit, save fields, cancel edits or remove a module from the configuration.</p> <p>I wrote this with no prior knowledge of JS and React. But I did not just sit down and monkey out some code. I researched and studied how to do this, and it is working. I am happy with it, and the code is the best I can produce.</p> <p>You can copy this code and play with the form to see how it works.</p> <p><code>configForm.js</code></p> <pre><code>import React from 'react' import FieldsetList from './fieldsetList' //this will be sent via and endpoint or via ws var configuration = { cameras: { USB_Camera_1: { width: 1920, height: 1080, device_path: '/dev/video1', pixel_format: 'yuy420p', input_format: 'h264', framerate: '30', segmented: true, name: 'USB_Camera_1', segment_time: '360', output_path: '/home/user/Desktop/video', mode: 2 }, USB_Camera_2: { width: 640, height: 480, device_path: '/dev/video2', pixel_format: 'yuy420p', input_format: 'h264', framerate: '30', segmented: true, name: 'USB_Camera_2', segment_time: '360', output_path: '/home/user/Desktop/video', mode: 2 } }, disk_monitor: { limit: 10000, file_extension: '.mp4' }, server: { port: ':5000', root_path: '/home/user/Desktop/video' }, pir: { vin_pin: 23, gnd_pin: 21, output_pin: 25 }, light_sensor: { vin_pin: 24, gnd_pin: 22, output_pin: 26 } } export default class ConfigForm extends React.Component { constructor(props) { super(props) this.state = configuration this.dispatch = this.dispatch.bind(this) } //config will not have more than one single nested object //parentKey passed for identifying top level object, if any, when dispatching an action dispatch = (state, parentKey, action) =&gt; { switch (action) { case 'save': if (parentKey != '') { newState = this.state newState[parentKey][Object.keys(state)[0]] = state this.setState(newState) return } //also will be written to file this.setState(state) return case 'remove': var newState = this.state if (parentKey != '') { delete newState[parentKey][Object.keys(state)[0]] this.setState(newState) return } delete newState[Object.keys(state)[0]] //also will be written to file this.setState(newState) return } } render() { let { cameras = {}, ...modules } = this.state let list = [ &lt;FieldsetList key={0} dispatch={this.dispatch} parentKey="cameras" modules={cameras} /&gt;, &lt;FieldsetList key={1} dispatch={this.dispatch} parentKey="" modules={modules} /&gt; ] return list } } </code></pre> <p><code>fieldsetList.js</code></p> <pre><code>import React from 'react' import PropTypes from 'prop-types' import Fieldset from './fieldset.js' const FieldsetList = props =&gt; { let list = [] Object.keys(props.modules).map(key =&gt; { list.push( &lt;Fieldset key={key} moduleName={key} parentKey={props.parentKey} dispatch={props.dispatch} module={props.modules[key]} /&gt; ) }) return &lt;div&gt;{list}&lt;/div&gt; } FieldsetList.propTypes = { parentKey: PropTypes.string, dispatch: PropTypes.func, modules: PropTypes.object } export default FieldsetList </code></pre> <p><code>fieldSet.js</code></p> <pre><code>import React from 'react' import PropTypes from 'prop-types' import { Input, Button, Dropdown } from 'semantic-ui-react' export default class Fieldset extends React.Component { constructor(props) { super(props) this.module = this.props.moduleName this.state = { [this.props.moduleName]: this.props.module, ctrls: { fieldsetDisabled: true, fieldsetBtn: 'edit', fieldsetBtnHandler: () =&gt; { this.edit() }, hideCancelBtn: true, dropDownDisabled: true }, dropdownOptions: [], remove: {} } //cancel event handler uses this state for resetting form this.baseState = {} //button event handlers this.inputChange = this.inputChange.bind(this) this.edit = this.edit.bind(this) this.remove = this.remove.bind(this) this.save = this.save.bind(this) this.cancel = this.cancel.bind(this) } //system will check for available modules and send via ws //dropdown options and module remove attributes async componentDidMount() { await this.setState({ dropdownOptions: [ { key: 0, text: '/dev/video11', value: '/dev/video11' }, { key: 1, text: '/dev/video12', value: '/dev/video12' }, { key: 2, text: '/dev/video13', value: '/dev/video13' } ], remove: { USB_Camera_1: true, USB_Camera_2: true, pir: true, light_sensor: true, server: false, disk_monitor: false } }) this.baseState = this.state } inputChange = e =&gt; { let field = e.currentTarget.name let value = e.currentTarget.value this.setState(prevState =&gt; ({ [this.module]: { ...prevState[this.module], [field]: value } })) } edit = () =&gt; { this.setState({ ctrls: { fieldsetBtn: 'save', fieldsetBtnHandler: () =&gt; { this.save() }, cancelBtnHandler: () =&gt; { this.cancel() }, removeBtnHandler: () =&gt; { this.remove() }, fieldsetDisabled: false, hideCancelBtn: false, dropDownDisabled: false } }) } save = () =&gt; { (async () =&gt; { await this.setState({ ctrls: { fieldsetBtn: 'edit', fieldsetBtnHandler: () =&gt; { this.edit() }, fieldsetDisabled: true, hideCancelBtn: true, dropDownDisabled: true } }) this.baseState = this.state })() let module = { [this.module]: this.state[this.module] } this.props.dispatch(module, this.props.parentKey, 'save') } cancel = () =&gt; { this.setState(this.baseState) } remove = () =&gt; { let module = { [this.module]: null } this.props.dispatch(module, this.props.parentKey, 'remove') } inputType = value =&gt; { if (isNaN(parseInt(value))) { return 'text' } else { return 'number' } } generateInputs() { var inputs = [] Object.keys(this.state[this.module]).map(inputKey =&gt; { let value = this.state[this.module][inputKey] switch (inputKey) { case 'device_path': inputs.push( &lt;div key={inputKey}&gt; &lt;span&gt;{inputKey}:&lt;/span&gt; &lt;Dropdown name={inputKey} placeholder={value} fluid selection options={this.state.dropdownOptions} disabled={this.state.ctrls.dropDownDisabled} /&gt; &lt;/div&gt; ) break default: inputs.push( &lt;div key={inputKey}&gt; &lt;span&gt;{inputKey}:&lt;/span&gt; &lt;Input type={this.inputType(value)} name={inputKey} value={value} onChange={this.inputChange} /&gt; &lt;/div&gt; ) } }) return inputs } render() { const cancelBtnStyle = this.state.ctrls.hideCancelBtn ? { display: 'none' } : {} let removeBtn = ( &lt;Button key={1} content="remove" onClick={this.state.ctrls.removeBtnHandler} type="button" /&gt; ) const showRemoveBtn = this.state.remove[this.module] ? removeBtn : null let elements = [ &lt;fieldset key={0} disabled={this.state.ctrls.fieldsetDisabled}&gt; &lt;legend&gt;{this.module}&lt;/legend&gt; {this.generateInputs()} {showRemoveBtn} &lt;/fieldset&gt;, &lt;Button key={2} content={this.state.ctrls.fieldsetBtn} onClick={this.state.ctrls.fieldsetBtnHandler} type="button" /&gt;, &lt;Button key={3} content="cancel" onClick={this.state.ctrls.cancelBtnHandler} style={cancelBtnStyle} type="button" /&gt; ] return elements } } Fieldset.propTypes = { parentKey: PropTypes.string, moduleName: PropTypes.string, dispatch: PropTypes.func, module: PropTypes.object } </code></pre>
[]
[ { "body": "<p>The last component looks quite complicated. I think some refactoring would help with readability but I have no concrete suggestions since I don't really understand what it's doing. Like this here <code>this.state.remove[this.module]</code>.\nin the comments\nI wrote some advice in the comments. Hopefully it's understandable. I mention direct state mutations a couple of times. You can find <a href=\"https://jkettmann.com/how-to-accidentally-mutate-state-and-why-not-to/\" rel=\"nofollow noreferrer\">more information here</a>. </p>\n\n<p>configForm.js</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>export default class ConfigForm extends React.Component {\n // binding dispatch is not necessary since you use an arrow function\n // thus the constructor is not required anymore\n state = configuration\n\n // too me calling this function dispatch and having an action of type string\n // is confusing. The dispatch keyword is somewhat occupied by useReducer or Redux\n dispatch = (state, parentKey, action) =&gt; {\n switch (action) {\n case 'save':\n if (parentKey != '') {\n // this is doing nothing, just assigning the state to another variable\n // not to confuse with creating a new object\n // additionally this looks like a syntax error since newState is not defined (var missing?)\n newState = this.state\n // here you're changing the state object directly which is not recommended\n // see my blog post below\n newState[parentKey][Object.keys(state)[0]] = state\n this.setState(newState)\n // rather use else statement for readability IMO\n return\n }\n // see above, rather use else IMO\n this.setState(state)\n // use break instead\n return\n case 'remove':\n var newState = this.state\n\n if (parentKey != '') {\n // again mutating state directly\n delete newState[parentKey][Object.keys(state)[0]]\n\n this.setState(newState)\n // again else statement instead\n return\n }\n\n // again mutating state directly\n delete newState[Object.keys(state)[0]]\n\n //also will be written to file\n this.setState(newState)\n return\n }\n }\n\n render() {\n let { cameras = {}, ...modules } = this.state\n let list = [\n &lt;FieldsetList\n key={0}\n dispatch={this.dispatch}\n parentKey=\"cameras\"\n modules={cameras}\n /&gt;,\n &lt;FieldsetList\n key={1}\n dispatch={this.dispatch}\n parentKey=\"\"\n modules={modules}\n /&gt;\n ]\n // you're not iterating over this array so I would suggest\n // to use a fragment &lt;&gt;...your FieldsetLists&lt;/&gt;\n return list\n }\n}\n</code></pre>\n\n<p>refactored fieldsetList.js</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>import React from 'react'\nimport PropTypes from 'prop-types'\nimport Fieldset from './fieldset.js'\n\nconst FieldsetList = props =&gt; (\n &lt;div&gt;\n {\n // map already returns an array, no need for push\n Object.keys(props.modules).map(key =&gt; (\n &lt;Fieldset\n key={key}\n moduleName={key}\n parentKey={props.parentKey}\n dispatch={props.dispatch}\n module={props.modules[key]}\n /&gt;\n ))\n }\n &lt;/div&gt;\n)\n\nFieldsetList.propTypes = {\n parentKey: PropTypes.string,\n dispatch: PropTypes.func,\n modules: PropTypes.object\n}\n\nexport default FieldsetList\n</code></pre>\n\n<p>fieldSet.js</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>import React from 'react'\nimport PropTypes from 'prop-types'\nimport { Input, Button, Dropdown } from 'semantic-ui-react'\n\nexport default class Fieldset extends React.Component {\n // constructor can be removed again\n constructor(props) {\n super(props)\n\n // not sure why you use the class variable here\n // in most cases this is a code smell IMO\n this.module = this.props.moduleName\n\n this.state = {\n [this.props.moduleName]: this.props.module,\n ctrls: {\n fieldsetDisabled: true,\n fieldsetBtn: 'edit',\n // I don't think you should have a function inside the state\n // especially one that's practically not doing anything\n fieldsetBtnHandler: () =&gt; {\n this.edit()\n },\n hideCancelBtn: true,\n dropDownDisabled: true\n },\n dropdownOptions: [],\n remove: {}\n }\n\n\n this.baseState = {}\n\n // again not needed since you use arrow functions\n this.inputChange = this.inputChange.bind(this)\n this.edit = this.edit.bind(this)\n this.remove = this.remove.bind(this)\n this.save = this.save.bind(this)\n this.cancel = this.cancel.bind(this)\n }\n\n // componentDidMount is not async\n async componentDidMount() {\n // setState doesn't return a promise so you should use await on it\n // if you need to do something as soon as the state is updated\n // use the setState callback parameter (the second I think) \n await this.setState({\n dropdownOptions: [\n {\n key: 0,\n text: '/dev/video11',\n value: '/dev/video11'\n },\n {\n key: 1,\n text: '/dev/video12',\n value: '/dev/video12'\n },\n {\n key: 2,\n text: '/dev/video13',\n value: '/dev/video13'\n }\n ],\n remove: {\n USB_Camera_1: true,\n USB_Camera_2: true,\n pir: true,\n light_sensor: true,\n server: false,\n disk_monitor: false\n }\n })\n\n // not sure why you do this but it smells\n this.baseState = this.state\n }\n\n inputChange = e =&gt; {\n let field = e.currentTarget.name\n let value = e.currentTarget.value\n\n // this looks fine form a mutation perspective\n this.setState(prevState =&gt; ({\n // why not just use this.props.moduleName\n [this.module]: {\n ...prevState[this.module],\n [field]: value\n }\n }))\n }\n\n edit = () =&gt; {\n this.setState({\n ctrls: {\n fieldsetBtn: 'save',\n // again functions in state seem odd\n fieldsetBtnHandler: () =&gt; {\n this.save()\n },\n cancelBtnHandler: () =&gt; {\n this.cancel()\n },\n removeBtnHandler: () =&gt; {\n this.remove()\n },\n fieldsetDisabled: false,\n hideCancelBtn: false,\n dropDownDisabled: false\n }\n })\n }\n\n save = () =&gt; {\n // again setState is not returning a promise\n (async () =&gt; {\n await this.setState({\n ctrls: {\n fieldsetBtn: 'edit',\n fieldsetBtnHandler: () =&gt; {\n this.edit()\n },\n fieldsetDisabled: true,\n hideCancelBtn: true,\n dropDownDisabled: true\n }\n })\n\n this.baseState = this.state\n })()\n\n let module = {\n [this.module]: this.state[this.module]\n }\n\n // I think it would increase readability if you used separate functions\n // for save, remove etc instead of abstracting them with dispatch\n this.props.dispatch(module, this.props.parentKey, 'save')\n }\n\n cancel = () =&gt; {\n this.setState(this.baseState)\n }\n\n remove = () =&gt; {\n let module = {\n [this.module]: null\n }\n\n this.props.dispatch(module, this.props.parentKey, 'remove')\n }\n\n inputType = value =&gt; {\n if (isNaN(parseInt(value))) {\n return 'text'\n } else {\n return 'number'\n }\n }\n\n generateInputs() {\n var inputs = []\n // again no need for pushing since map returns an array\n Object.keys(this.state[this.module]).map(inputKey =&gt; {\n let value = this.state[this.module][inputKey]\n\n switch (inputKey) {\n case 'device_path':\n inputs.push(\n &lt;div key={inputKey}&gt;\n &lt;span&gt;{inputKey}:&lt;/span&gt;\n &lt;Dropdown\n name={inputKey}\n placeholder={value}\n fluid\n selection\n options={this.state.dropdownOptions}\n disabled={this.state.ctrls.dropDownDisabled}\n /&gt;\n &lt;/div&gt;\n )\n break\n default:\n inputs.push(\n &lt;div key={inputKey}&gt;\n &lt;span&gt;{inputKey}:&lt;/span&gt;\n &lt;Input\n type={this.inputType(value)}\n name={inputKey}\n value={value}\n onChange={this.inputChange}\n /&gt;\n &lt;/div&gt;\n )\n }\n })\n return inputs\n }\n\n render() {\n const cancelBtnStyle = this.state.ctrls.hideCancelBtn\n ? { display: 'none' }\n : {}\n\n let removeBtn = (\n &lt;Button\n key={1}\n content=\"remove\"\n onClick={this.state.ctrls.removeBtnHandler}\n type=\"button\"\n /&gt;\n )\n\n const showRemoveBtn = this.state.remove[this.module] ? removeBtn : null\n\n // rather use a fragment, it's not common to return an array\n let elements = [\n &lt;fieldset key={0} disabled={this.state.ctrls.fieldsetDisabled}&gt;\n &lt;legend&gt;{this.module}&lt;/legend&gt;\n {this.generateInputs()}\n {showRemoveBtn}\n &lt;/fieldset&gt;,\n\n &lt;Button\n key={2}\n content={this.state.ctrls.fieldsetBtn}\n onClick={this.state.ctrls.fieldsetBtnHandler}\n type=\"button\"\n /&gt;,\n\n &lt;Button\n key={3}\n content=\"cancel\"\n onClick={this.state.ctrls.cancelBtnHandler}\n style={cancelBtnStyle}\n type=\"button\"\n /&gt;\n ]\n\n return elements\n }\n}\n\nFieldset.propTypes = {\n parentKey: PropTypes.string,\n moduleName: PropTypes.string,\n dispatch: PropTypes.func,\n module: PropTypes.object\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T14:35:28.950", "Id": "469091", "Score": "0", "body": "Hello friend. What great feedback, thanks. I have only one point where I am scratching my head, hope you can provide more feedback on it. It is concerning the `fieldsetBtnHandler` in the `ctrls` object. That's the onClick handler func for button with key 2 and its initial state is `edit`. Once clicked it's function will be replaced with `save` unless cancelled by the cancel button. Having the handler in the state is the only way I can think of assigning a new handler for the button once clicked. Is there another way to approach this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T15:16:08.090", "Id": "469093", "Score": "0", "body": "also, just for clarification, `this.state.remove[this.module]` is just really bad naming from me. It refers to modules that are allowed to be removed from config as they are not core modules and the robot can go on without them. Maybe a better name would be `can_be_removed`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T20:05:20.217", "Id": "239116", "ParentId": "239012", "Score": "1" } } ]
{ "AcceptedAnswerId": "239116", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T17:45:10.937", "Id": "239012", "Score": "2", "Tags": [ "javascript", "beginner", "react.js", "jsx" ], "Title": "React form actions > Edit, Save, Remove, Cancel" }
239012
<p>I have a list like this </p> <pre><code>list_ = [" ", " ", "X", " ", " ", "Z", " ", "Y", " "] </code></pre> <p>I am writing a function that will result in </p> <pre><code>list_ = [" ", " ", " ", " ", " ", " ", "X", "Z", "Y"] </code></pre> <p>Basically it will push all the non-empty (I'll call <code>" "</code> as empty here for simplicity) to the end of the list while retaining their orders</p> <p>My solution as follow</p> <pre><code>def push(list_): def find_current_element(list_, from_): for i in range(from_+1, len(list_)): if list_[i] != " ": return i return None list_ = list_[::-1] good_index = list_.index(" ") current_element_index = find_current_element(list_, 0) while(current_element_index is not None): for i in range(good_index, len(list_)): if list_[i] != " ": list_[good_index], list_[i] = list_[i], " " good_index += 1 current_element_index = find_current_element(list_, current_element_index) return reversed(list_) </code></pre> <p>It works, but it seems too long and using too much resource (reverse the list twice and bunch of for loops). I wouldn't care if the items were just simple character, but I plan to have some big objects as items of the list. I am wondering is there a simpler approach</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:03:08.403", "Id": "468746", "Score": "0", "body": "*\"but I plan to have some big objects as items\"* - Why does the size of the items matter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T02:07:15.053", "Id": "468779", "Score": "0", "body": "@HeapOverflow, it doesn't? I am under the impression that if the list has big objects, iterate through it too many times isn't a good idea. Sorry I am still learning" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T02:09:41.957", "Id": "468780", "Score": "3", "body": "Their data is stored in the heap. The list only contains pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T08:53:31.393", "Id": "468799", "Score": "0", "body": "Do you care about the order of the non-empty elements? I assume you want to modify the list inplace, am I correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:11:07.127", "Id": "468840", "Score": "2", "body": "@norok2 The question says *\"while retaining their orders\"*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T22:38:52.720", "Id": "469011", "Score": "0", "body": "can you share a list of the bigger items that you are going to run through this, it might help us give you a better review" } ]
[ { "body": "<p>Your code is incorrect, for example for input <code>[' ', 'X', 'Y']</code> you get into an infinite loop.</p>\n\n<p>You could just sort by emptiness, which with your apparent definition can be done like this:</p>\n\n<pre><code>&gt;&gt;&gt; list_ = [\" \", \" \", \"X\", \" \", \" \", \"Z\", \" \", \"Y\", \" \"]\n&gt;&gt;&gt; list_.sort(key=' '.__ne__)\n&gt;&gt;&gt; list_\n[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']\n</code></pre>\n\n<p>Or more generally (though slower) with a lambda or other self-made function:</p>\n\n<pre><code>list_.sort(key=lambda x: x != ' ')\nlist_.sort(key=is_non_empty)\nlist_.sort(key=is_empty, reverse=True)\n</code></pre>\n\n<p>If you actually had <a href=\"https://en.wikipedia.org/wiki/Empty_string\" rel=\"noreferrer\">empty strings</a> instead of strings containing a space character, or in general if your objects followed Python's usual thing of empty objects being false and non-empty objects being true, then you could also do this:</p>\n\n<pre><code>list_.sort(key=bool)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:13:33.843", "Id": "468747", "Score": "0", "body": "Thanks. Also if the items are objects, I'd need to override the __ne__ right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:15:26.377", "Id": "468748", "Score": "1", "body": "The items already *are* objects. But yes, if your real objects need a different emptiness check, then you need to change the key accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:49:43.753", "Id": "468758", "Score": "2", "body": "@NepNep You can pass in a `lambda` to key. Currently `' '.__ne__` is the same as `lambda i: i != ' '`. From here you can change [lambda](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions) to what you want. If it's too restrictive, as it has to be one expression, than you can make it a full fat function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:36:49.177", "Id": "468848", "Score": "5", "body": "@Barmar [\"Sorts are guaranteed to be stable\"](https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:39:23.120", "Id": "468849", "Score": "0", "body": "Thanks. I got my misinformation from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch02s04.html. I guess it's an old book, I found documentation saying it became stable in Python 2.2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:44:33.193", "Id": "468850", "Score": "0", "body": "@Barmar Yes, judging by the authors mentioned on that page it's the first edition of the book, which came out in 2002." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:08:20.453", "Id": "468874", "Score": "0", "body": "`key=lambda x: not is_empty(x)` is an easy way to define your key based on whatever you consider \"emptiness\" to be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:29:32.580", "Id": "468876", "Score": "1", "body": "@Eric Yes, although `key=is_empty, reverse=True` would be much faster (about factor 1.6 on a shuffled `[' ', 'X'] * 10**6` with `is_empty = ' '.__eq__`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T18:46:47.727", "Id": "468888", "Score": "0", "body": "Also, note that calling `__eq__` directly is almost always a bad idea, as that may return `NotImplemented`. Just use a lambda with `==`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T18:51:50.953", "Id": "468889", "Score": "0", "body": "@Eric I'm rather confident that strings have it and will keep having it :-). Otherwise `==` would only check for object identity, and that wouldn't be good. And lambda is slower." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T00:28:56.733", "Id": "468920", "Score": "0", "body": "Right, but `\" \".__eq__(None)` gives `NotImplemented`. You also need to be confident that your list contains only exact strings with no subclasses." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T01:18:40.180", "Id": "468922", "Score": "0", "body": "@Eric Ah, ok. Yes, if they also have other types, then `==` might be better. Although it seems to be just a toy example and their *\"plan to have some big objects as items\"* might come with an \"emptiness\" other than equality to some certain \"empty value\". In any case, easy to adapt." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T13:25:24.390", "Id": "468971", "Score": "1", "body": "@Eric Added a few versions now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T06:36:35.570", "Id": "470193", "Score": "0", "body": "I would use `sorted` to prevent modifying the original list. Side effects like that can really cause hard to solve bugs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T12:00:05.083", "Id": "470298", "Score": "0", "body": "@MaartenFabré Hmm, why are you calling it a side effect? It's **the** effect. The only one. The desired one. And it uses less resources." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T19:48:20.923", "Id": "239018", "ParentId": "239015", "Score": "24" } }, { "body": "<ul>\n<li><code>find_current_element</code> is a poor name, <code>find_nonempty</code> would better describe what it's doing.</li>\n<li><code>find_current_element</code> is a strange form of iteration where you constantly resume the function from where it left off. This would be better described using a generator function.</li>\n<li>Your function is good as you're swapping items in the list rather than <code>list.insert(0, value)</code>.</li>\n<li>You don't need to invert the list twice as you can just work backwards, appending to the end.</li>\n<li>Since we can do this by mutating the original list, I won't return the new list.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def find_nonempty(values, is_empty):\n for i in reversed(range(len(values))):\n if not is_empty(values[i]):\n yield i\n\ndef push(values, is_empty):\n good_index = len(values) - 1\n for i in find_nonempty(values, is_empty):\n values[i], values[good_index] = values[good_index], values[i]\n good_index -= 1\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; list_ = [\" \", \" \", \"X\", \" \", \" \", \"Z\", \" \", \"Y\", \" \"]\n&gt;&gt;&gt; push(list_, lambda i: i == \" \")\n&gt;&gt;&gt; list_\n[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']\n</code></pre>\n\n<p>Personally I would just use two list comprehensions, if I were to not use <code>list.sort</code>, as the logic would be much clearer.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def push(values, is_empty):\n return (\n [v for v in values if is_empty(v)]\n + [v for v in values if not is_empty(v)]\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:30:02.817", "Id": "468749", "Score": "0", "body": "Actually their current method is *not* O(n^2). Try it with input `[' ', 'X', 'Y']`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:35:52.957", "Id": "468750", "Score": "0", "body": "@HeapOverflow Ah, yes I forgot the `from_` argument. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:38:41.857", "Id": "468752", "Score": "0", "body": "Hmm, that rather sounds like you think I meant it's *better* than O(n^2). What I really meant is that it runs *infinitely* on that input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:41:35.983", "Id": "468753", "Score": "0", "body": "@HeapOverflow Ah so it does, either way assuming it was working I was wrong ;P This just seems like a one-off error tbh" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:47:42.800", "Id": "468754", "Score": "0", "body": "Yeah, maybe just a one-off error. I gave up trying to understand it, it's too convoluted (unlike yours, which is pretty clear). So I just generated test cases and compared it with my solution and it got stuck at that test case. (Oh and it returns a `list_reverseiterator` instead of a `list`, forgot about that when I tried to figure out why it gets stuck.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T02:12:04.410", "Id": "468781", "Score": "0", "body": "Thank, the list comprehension method is really clean" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:02:54.157", "Id": "239020", "ParentId": "239015", "Score": "10" } }, { "body": "<p>If you want to go for readability, I would prefer a plain generator approach. This one uses only <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> time but uses <span class=\"math-container\">\\$\\mathcal{O}(k)\\$</span> additional space, where <span class=\"math-container\">\\$n\\$</span> is the number of elements in the list and <span class=\"math-container\">\\$k\\$</span> is the number of non-empty values. This is in contrast to sorting (<span class=\"math-container\">\\$\\mathcal{O}(n \\log n)\\$</span> time <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> space) and using two independent list comprehensions (<span class=\"math-container\">\\$\\mathcal{O}(2n)\\$</span> time and <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> space).</p>\n\n<p>Note that for speed only the number of elements in the list matters, not how big each element is, because a Python <code>list</code> only stores pointers to the objects.</p>\n\n<pre><code>def empty_first(it):\n buffer = []\n for x in it:\n if x == \" \":\n yield x\n else:\n buffer.append(x)\n yield from buffer\n</code></pre>\n\n<p>Just wrap the calling code with a <code>list</code>:</p>\n\n<pre><code>list_ = [\" \", \" \", \"X\", \" \", \" \", \"Z\", \" \", \"Y\", \" \"]\nprint(list(empty_first(list_)))\n# [' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']\n</code></pre>\n\n<p>Performance wise, all of these approaches might be easier and more readable, but if you need raw speed, you should time the different approaches.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T07:34:44.327", "Id": "239043", "ParentId": "239015", "Score": "8" } }, { "body": "<p>The most elegant and declarative approach in my opinion is using <code>reduce</code>.</p>\n\n<pre><code>&gt;&gt;&gt; from functools import reduce\n&gt;&gt;&gt; list_ = [\" \", \" \", \"X\", \" \", \" \", \"Z\", \" \", \"Y\", \" \"]\n&gt;&gt;&gt; reduce(lambda xs, x: xs + [x] if x.strip() != \"\" else [x] + xs, list_, [])\n[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']\n</code></pre>\n\n<p>How it works: <code>reduce</code> takes 3 arguments: a function, a list, and an initial value. It then calls the function consistently for each element in the list, and each time replaces the saved initial value with return of this function, which is called with the current version of (now not initial, but <em>accumulated</em>) value as a first argument, and current element of a list as a second argument, and then returns accumulated value. </p>\n\n<p>With this we can using a single line loop through the list and conditionally append or prepend values to the new list, returning it at the end.</p>\n\n<p>More: <a href=\"https://docs.python.org/3/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/functools.html#functools.reduce</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T11:09:19.620", "Id": "468824", "Score": "0", "body": "Welcome to Code Review! 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": "2020-03-17T12:36:16.583", "Id": "468830", "Score": "1", "body": "This takes quadratic time, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T12:40:05.390", "Id": "468831", "Score": "0", "body": "@TobySpeight I guess my answer is also guilty of that, but you didn't say so because it's at least fast? Is my answer in danger of getting deleted? The OP's \"question\" doesn't actually contain any question, the only thing it says about what the OP wants from us is their *\"I am wondering is there a simpler approach\"*. And that is what Opus and I are providing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:03:14.413", "Id": "468837", "Score": "0", "body": "@HeapOverflow, no I didn't see your answer when I came here from the \"New answers to old questions\" page; I agree it could also be improved to explain what's problematic in the question code before suggesting how to address it. BTW, all Code Review questions carry the same (implicit) questions: *Is this code of good quality? What could be improved?*" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T10:18:46.480", "Id": "239049", "ParentId": "239015", "Score": "1" } }, { "body": "<p>(<strong>EDITED</strong> to include a better analysis and improve the partition-based alternative)</p>\n\n<h1>Take-home message</h1>\n\n<pre><code>def push_side_part(seq):\n seq = list(seq) # remove this for inplace\n n = len(seq)\n j = n - 1\n for i in range(n - 1, -1, -1):\n if seq[i] != ' ':\n seq[j], seq[i] = seq[i], seq[j]\n j -= 1\n return seq\n</code></pre>\n\n<p>This is an efficient (both time <code>O(1)</code> and memory <code>O(N)</code>) and simple alternative for solving the problem. It is based on a variation of <a href=\"https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme\" rel=\"nofollow noreferrer\">Lomuto partitioning used in QuickSort</a>.\nNone of the other proposed solution gets to both.\nThe solution based on sorting is, at best, <code>O(N log N)</code> in time and <code>O(1)</code> in memory.</p>\n\n<p>For the input sizes I tested, the code runs approximately as fast as the <code>list.sort()</code>-based alternative, but can be made roughly one order of magnitude faster by compiling it as is with Cython.</p>\n\n<hr>\n\n<h1>Analysis of Original Code</h1>\n\n<p>First, lets comment your code:</p>\n\n<ul>\n<li>The code fails right at the start with the <code>.index()</code> call, if the input does not contain empty strings <code>' '</code></li>\n<li>The code gets into infinite loop if, for whatever reason (e.g. for input <code>[' ', 'b', ' ', 'b', 'b']</code>), it does not enter the <code>for</code> loop, so this should be properly handled</li>\n<li>Your code for <code>find_current_element()</code> is not type-stable. Particularly, if the function <em>fails</em> it returns <code>None</code>. However, without loss in functionality, you could return a negative index, say <code>-1</code>. This is a matter of taste in Python but in light of future optimization, it may be relevant. Note that some built-in functions in Python (like e.g. <code>string.find()</code>) are type-stable in a similar fashion and some other built-in functions are not (e.g. <code>string.index()</code>) so you have both choices even within the standard library.</li>\n<li>I am not sure what is the reason for you to use <code>return reversed(...)</code> which returns an iterator, but I would rather return the reversed list via slicing</li>\n</ul>\n\n<p>A safer version of your code, while still retaining your approach is:</p>\n\n<pre><code>def find_current_element(seq, index):\n for i in range(index + 1, len(seq)):\n if seq[i] != \" \":\n return i\n return -1\n\n\ndef push_side_OP(seq):\n result = seq[::-1]\n try:\n good_index = result.index(\" \")\n except ValueError:\n return seq\n else:\n curr_index = find_current_element(result, 0)\n while curr_index &gt;= 0:\n for i in range(good_index, len(result)):\n if result[i] != \" \":\n result[good_index], result[i] = result[i], \" \"\n good_index += 1\n curr_index = find_current_element(result, curr_index)\n else:\n curr_index = -1\n return result[::-1]\n</code></pre>\n\n<hr>\n\n<p>A more polished way of writing essentially this same algorithm is:</p>\n\n<pre><code>def neg_rfind(seq, item, index=-1):\n n = len(seq)\n index %= n\n for i in range(index, -1, -1):\n if seq[i] != item:\n return i\n return -1\n\n\ndef rfind(seq, item, index=-1):\n n = len(seq)\n index %= n\n for i in range(index, -1, -1):\n if seq[i] == item:\n return i\n return -1\n # try:\n # return len(seq) - seq[::-1].index(item, index) - 1\n # except ValueError:\n # return -1\n\n\n\ndef push_side_loop(seq):\n seq = list(seq) # remove this for inplace\n j = rfind(seq, ' ')\n i = neg_rfind(seq, ' ')\n while i &gt;= 0:\n for l in range(j - 1, -1, -1):\n if seq[l] != ' ':\n seq[j], seq[l] = seq[l], ' '\n j -= 1\n i = neg_rfind(seq, ' ', i - 1)\n else:\n i = -1\n</code></pre>\n\n<p>Now, the algorithm itself is memory efficient (<code>O(1)</code>) but it is not very time efficient (<code>O(N²)</code>? -- I am not 100% sure).\nIn particular, this is updating index <code>i</code> (with a rather expensive <code>neg_rfind()</code> call_ in a loop where <code>i</code> is not required to be updated.\nAdditionally, there seems to be an unnecessary nested loop.\nSomehow, this resembles <a href=\"https://en.wikipedia.org/wiki/Bubble_sort\" rel=\"nofollow noreferrer\">bubble-sort</a> which is an inefficient sorting algorithm.</p>\n\n<p>But even if you were to implement an efficient sorting algorithm (which is sort of reinventing the wheel, as Python already has <code>sorted()</code> and <code>list.sort()</code>), the problem you are trying to solve is simpler than that.</p>\n\n<hr>\n\n<h1>Alternatives</h1>\n\n<p>For simpler comparison, the functions provided here are all preserving the input, but some could be easily made in-place, by simply skipping the line <code>seq = list(seq)</code> or similar.</p>\n\n<p>Some alternatives, while in principle very efficient, contain explicit looping, which is somewhat slow in Python.\nHowever, they can be easily made very fast with Cython (with the <code>_cy</code> suffix in benchmarks), and will be comparable to those pure Python solutions that avoid explicit looping (and recursion).</p>\n\n<h2>Using partitioning</h2>\n\n<p>You could use a variation of the partitioning functions used in sorting algorithms. Here is a variation / generalization of <a href=\"https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme\" rel=\"nofollow noreferrer\">Lomuto partitioning used in QuickSort</a>:</p>\n\n<pre><code>def partition_inplace(seq, condition, start=0, stop=-1):\n n = len(seq)\n start %= n\n stop %= n\n step = 1 if start &lt; stop else -1\n for i in range(start, stop + step, step):\n if condition(seq[i]):\n seq[start], seq[i] = seq[i], seq[start]\n start += step\n if step &gt; 0:\n return start\n else:\n return start + 1\n</code></pre>\n\n<p>This both separates the sequence inplace (according to the <code>condition</code>) and returns the index at which this separation occurs).</p>\n\n<p>Since partitioning retain the order of the elements on only one side (the side of the elements satisfying the condition) one needs to run it <em>backward</em> with the <em>non-empty</em> condition.\nAlso the separating index is not needed.</p>\n\n<p>Hardcoding all this for speed (essentially one needs to avoid the expensive call to <code>condition</code> inside the main loop), one would get:</p>\n\n<pre><code>def push_side_part(seq):\n seq = list(seq) # remove this for inplace\n n = len(seq)\n j = n - 1\n for i in range(n - 1, -1, -1):\n if seq[i] != ' ':\n seq[j], seq[i] = seq[i], seq[j]\n j -= 1\n return seq\n</code></pre>\n\n<p>This is both time and memory efficient.\nNote that this is essentially the same as <a href=\"https://codereview.stackexchange.com/a/239020/140196\">@Peilonrayz' first answer</a> except that it avoids using unnecessary generators.</p>\n\n<h2>Using sorting (from <a href=\"https://codereview.stackexchange.com/a/239018/140196\">@HeapOverflow's answer</a>)</h2>\n\n<pre><code>def push_side_sort(seq):\n result = list(seq)\n result.sort(key=' '.__ne__)\n return result\n</code></pre>\n\n<p>This will have time and memory efficiency of sorting (which is typically worse than the problem you are trying to solve).</p>\n\n<h2>Using <code>functools.reduce()</code> (from <a href=\"https://codereview.stackexchange.com/a/239049/140196\">@Opus' answer</a>)</h2>\n\n<pre><code>def push_side_reduce_slow(seq):\n def sided_join(items, item):\n if item == ' ':\n return [item] + items\n else:\n return items + [item]\n return functools.reduce(sided_join, seq, [])\n</code></pre>\n\n<p>While this is a very elegant approach for functional-style programming, it is in practice quite inefficiently creating temporary lists all the time (it is so slow it will go off charts and it is not included in the benchmarks)\nA slightly more efficient approach will use <code>list.insert()</code>, e.g.:</p>\n\n<pre><code>def push_side_reduce(seq):\n def sided_join(items, item):\n items.insert(0 if item == ' ' else len(items), item)\n return items\n return functools.reduce(sided_join, seq, [])\n</code></pre>\n\n<p>However, inserting at the beginning of a <code>list</code> is an <code>O(N)</code> (<code>N</code> being the number of elements of the list) for Python lists, because they are implemented as dynamic arrays.</p>\n\n<h2>Using <code>filter()</code> (essentially the same as <a href=\"https://codereview.stackexchange.com/a/239020/140196\">@Peilonrayz' second answer</a>)</h2>\n\n<pre><code>def push_side_filt2(seq):\n return (\n list(filter(lambda x: x == ' ', seq))\n + list(filter(lambda x: x != ' ', seq)))\n</code></pre>\n\n<p>uses <code>filter()</code> instead of a comprehension, but it is otherwise the same. This can be further improved because the first filtering can be omitted and replaced with a quicker <code>list</code> repetition, given that it will always be repeating the empty string.</p>\n\n<pre><code>def push_side_filt(seq):\n non_empty = list(filter(lambda x: x != ' ', seq))\n return [' '] * (len(seq) - len(non_empty)) + non_empty\n</code></pre>\n\n<h2>Using a buffer (essentially <a href=\"https://codereview.stackexchange.com/a/239043/140196\">@Graipher's answer</a>)</h2>\n\n<pre><code>def empty_first(items):\n buffer = []\n for item in items:\n if item == \" \":\n yield item\n else:\n buffer.append(item)\n yield from buffer\n\n\ndef push_side_buff(seq):\n return list(empty_first(seq))\n</code></pre>\n\n<p>This is the computationally most efficient approach for keeping the order of both the <em>empty</em> and the <em>non-empty</em> elements.\nHowever, it is not quite as much memory efficient because of the extra memory required by the buffer.</p>\n\n<hr>\n\n<h1>Benchmarks</h1>\n\n<h2>Generating Input</h2>\n\n<pre><code>def gen_input(n, k=0.5, tokens=string.ascii_letters + string.digits):\n picks = tokens + ' ' * int(len(tokens) * k)\n m = len(picks)\n return [picks[random.randint(0, m - 1)] for _ in range(n)]\n</code></pre>\n\n<h2>Checking for Valid Output</h2>\n\n<pre><code>def equal_output(a, b, with_order=True):\n if with_order:\n return a == b\n else:\n n = a.count(' ')\n m = b.count(' ')\n return a[:n] == b[:m]\n</code></pre>\n\n<h2>Results</h2>\n\n<p>Input sizes generated using:</p>\n\n<pre><code>input_sizes = tuple(int(2 ** (2 + (3 * i) / 4)) for i in range(4, 21))\n# N = (32, 53, 90, 152, 256, 430, 724, 1217, 2048, 3444, 5792, 9741, 16384, 27554, 46340, 77935, 131072)\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/o355f.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o355f.png\" alt=\"bm_full\"></a></p>\n\n<p>and with 40x and 10x zoom on the faster methods, respectively:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Gel7v.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Gel7v.png\" alt=\"bm_zoom_40\"></a>\n<a href=\"https://i.stack.imgur.com/FCPU2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FCPU2.png\" alt=\"bm_zoom_10\"></a></p>\n\n<p>This shows that <code>push_side_part()</code> is as fast as a <code>list.sort()</code>-based solution (which would be otherwise the fastest non-Cython-accelerated solution) and compiling this in Cython results in much faster timings than any of the proposed solutions.</p>\n\n<hr>\n\n<p>Full code available <a href=\"https://colab.research.google.com/drive/1yn_6SsYn-VprvTPsJ8qZXMtcpyD6TyCK\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:17:19.393", "Id": "468861", "Score": "0", "body": "This helped a lot. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-30T22:32:16.107", "Id": "470165", "Score": "1", "body": "Excellent answer. I appreciate all the detail you included. Great job." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:03:22.427", "Id": "239056", "ParentId": "239015", "Score": "12" } }, { "body": "<blockquote>\n <p>there is a lot of way to do this...as people answered before\n but there is easy and simplified code..but easy understandable code</p>\n</blockquote>\n\n<pre><code> def push_non_empty_items(given_list):\n\n pushed_list=[]\n for i in range(len(given_list)):\n if given_list[i] != \" \":\n pushed_list.append(given_list[i])\n\n\n no_non_empty_items = len(given_list) - len(pushed_list)\n\n\n empty_list = [\" \"] * no_non_empty_items\n return (empty_list + pushed_list)\n\n\nprint(push_non_empty_items([\" \", \" \", \"X\", \" \", \" \", \"Z\", \" \", \"Y\", \" \"]))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T09:47:42.063", "Id": "471471", "Score": "0", "body": "Please explain the changes that you have made, the logic and the gains from these changes, this helps the author understand what you have modified and gives more complete feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T16:16:41.657", "Id": "239756", "ParentId": "239015", "Score": "0" } }, { "body": "<p>Peilonrayz said:</p>\n\n<blockquote>\n <p>Personally I would just use two list comprehensions, if I were to not\n use list.sort, as the logic would be much clearer.</p>\n</blockquote>\n\n<p>I agree with this, this is the Pythonic way, short and straight to the point. And if you don't need a fancy function for evaluating what qualifies as non-empty then you could even strip down the code proposed by Peilonrayz and summarize it to a one-liner:</p>\n\n<pre><code>[i for i in list_ if i == \" \"] + [i for i in list_ if i != \" \"]\n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']\n</code></pre>\n\n<p>which could be just enough for your purpose, based on your example containing strings. Although I feel his answer should be the accepted answer as it is more elegant and provides more flexibility, since your criteria can change. A good function should be flexible and reusable.</p>\n\n<hr>\n\n<p>Additional notes:</p>\n\n<p>Since the OP seems to be concerned with possible <strong>performance</strong> issues with <strong>large lists</strong> it may be worth mentioning that a list comprehension will load the whole output list to memory. There is an alternative and that is using a <strong>generator expression</strong>. <em>A generator expression can be iterated over but yields one item at a time on demand.</em> </p>\n\n<blockquote>\n <p>Generator Expressions are somewhat similar to list comprehensions, but\n the former doesn’t construct list object. Instead of creating a list\n and keeping the whole sequence in the memory, the generator generates\n the next element in demand.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://www.geeksforgeeks.org/python-list-comprehensions-vs-generator-expressions/\" rel=\"nofollow noreferrer\">Python List Comprehensions vs Generator Expressions</a></p>\n\n<blockquote>\n <p>The performance improvement from the use of generators is the result\n of the lazy (on demand) generation of values, which translates to\n lower memory usage. Furthermore, we do not need to wait until all the\n elements have been generated before we start to use them. This is\n similar to the benefits provided by iterators, but the generator makes\n building iterators easy.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">wiki.python.org - Generators</a></p>\n\n<p>They are slightly different than lists, for instance you cannot merge them like lists using <code>+</code> as shown above. One way of doing it could be:</p>\n\n<pre><code>from itertools import chain\nlist_empty=(i for i in list_ if i == \" \" )\nlist_not_empty=(i for i in list_ if i != \" \" )\nlist_full = chain(list_empty, list_not_empty) \n\n&gt;&gt;&gt; type(list_full)\n&lt;class 'itertools.chain'&gt;\n</code></pre>\n\n<p>There may be a better way. Note that the result is an object of type <code>itertools.chain</code>.\n<br/>\nDisclaimer: I still lack familiarity with some of the aspects but I nonetheless want to share my findings for the benefit of others and of course the OP can further research the idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T18:59:48.880", "Id": "240001", "ParentId": "239015", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T19:23:08.063", "Id": "239015", "Score": "14", "Tags": [ "python" ], "Title": "Pushing all non empty items to the end of a list" }
239015
<p>My task is that of caching. If the folder exists then load the cache from disk, if it doesnt create new cache. This is trivial, what bothers me is if I want to create third mode of noop (don't do anything relating to cache).</p> <p>Currently I have this:</p> <pre class="lang-py prettyprint-override"><code>class HeavyCalculationClass: def __init__(self, cache_dir=None) self.use_cache = cache_dir is not None if self.use_cache: if os.path.exists(cache_dir): if len(os.listdir(cache_dir) != 0: self.cache_type = "write" else: self.cache_type = "read" else: os.mkdir(cache_dir) self.cache_type = "write" def __getitem__(self, idx): if self.use_cache and self.cache_type=="read": data = numpy.load(os.path.join(cache_dir, str(idx)+".npy")) else: data = very_heavy_calculation() if self.use_cache and self.cache_type == "write": numpy.save(os.path.join(cache_dir, str(idx)+".npy"), data) return data </code></pre> <p>Is there any way to write this in a more elegant form?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:58:26.153", "Id": "468759", "Score": "1", "body": "Could you provide more code, currently the way I think would be an improvement could just be a hindrance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T09:13:31.347", "Id": "468801", "Score": "0", "body": "@Peilonrayz I've tried but adding any other code would just complicate too much, and won't focus on the core issue. Could you post your thoughts as an answer? Pretty much it needs to be iterable (hence getitem) , and if the file already exists on disk, just skip heavy calculation and read from disk." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T09:52:45.933", "Id": "468808", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T10:19:03.820", "Id": "468812", "Score": "0", "body": "@TobySpeight I've edited it but I'm not sure how to name it precisely. Trying to optimize for easy recognition for someone who's done similar stuff but like this it is too specific and the same problem can be experienced with other stuff (not necesseraly caching)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T11:08:17.963", "Id": "468823", "Score": "1", "body": "Looks better now! `:-)`" } ]
[ { "body": "<p>I don't know what you mean by \"more elegant\", but I would recommend using pathlib. This class provides for caching to be enabled/disabled for all files. If the class is not initialized with a cache_dir, then caching is disabled. If a cache_dir is provided, then <code>__getitem__()</code> loads data from cached files, if they exist. Otherwise the data is calculated and cached.</p>\n\n<pre><code>class HeavyCalculationClass:\n def __init__(self, cache_dir=None):\n # sets the path to the cache directory if it was specified\n # and creates the cache directory if needed\n if cache_dir:\n self.cache = pathlib.Path(cache_dir)\n\n if not self.cache.is_dir():\n self.cache.mkdir()\n\n else:\n # empty cache path means ignore the cache\n self.cache = None\n\n def __getitem__(self, idx):\n # if caching is 'on' and this file is cached,\n # then load it\n if self.cache:\n cache_file = self.cache / f\"{idx}.npy\"\n\n if cache_file.is_file():\n data = numpy.load(cache_file))\n return data\n\n # otherwise calculate the data\n data = very_heavy_calculation()\n\n # cache the data if a cache path is set\n if self.cache:\n numpy.save(self.cache / f\"{idx}.npy\"), data)\n\n return data\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T09:11:11.440", "Id": "468800", "Score": "0", "body": "more elegant as in less lines of code less variables, simpler to read" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T23:29:29.473", "Id": "239028", "ParentId": "239016", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T19:24:06.557", "Id": "239016", "Score": "4", "Tags": [ "python", "object-oriented" ], "Title": "Python disk caching with index" }
239016
<p>I implemented a program that does the following:</p> <blockquote> <p>Consider the positive quadrant of the <em>xy</em> plane. A <strong>colored point</strong> is a triple (<em>x</em>,<em>y</em>,<em>c</em>) where <em>x</em> is its x-axis coordinate, <em>y</em> is the y-axis coordinate, and <em>c</em> is an integer representing its color.</p> <p>This program needs to read a set of <em>N</em> colored points, then take some <strong>queries</strong> and answer them.</p> <p>A query is represented by four values, (<em>x₁</em>, <em>y₁</em>, <em>x₂</em>, <em>y₂</em>) and is used to get the number of different colors inside the rectangle confined within the two points of given coordinates.</p> <p>This program will read: </p> <ol> <li>The number <em>N</em> of colored points and <em>M</em> of queries</li> <li>N lines, each containing the three numbers that identify a colored point </li> <li>M lines, each containing a query</li> </ol> <p>It will <strong>only</strong> output the answers to each query. That is the number of distinct colors within the rectangles.</p> </blockquote> <h3>NOTE</h3> <ul> <li>This code does not perform input-checks. Don't tell me it doesn't. <em>I know</em>. This exercise was not about input-checking. It also doesn't print any messages to the user. This program is to be tested automatically by my university online platform, so it has to strictly get input from stdin print the output. Also please don't comment on usage of <code>scanf()</code> and <code>printf()</code>; I know there are better options but that's not the point.</li> </ul> <p>That being said, I feel that complexity-wise, this algorithm isn't very efficient, or at least could be done better. I haven't done a thorough analysis of it, but the complexity is at least <em>O</em>(<em>NM</em>), which is potentially very very bad. I'm interested in constructive feedback on how I could improve the algorithm to make it faster and do fewer tests.</p> <p>Here's the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct colpt { int x; int y; int c; } Cp; typedef struct q { int x1; int x2; int y1; int y2; } Query; typedef struct color { int c; struct color *nextPtr; } Color; void freeList(Color **lPtr) { Color *currPtr = *lPtr; while(currPtr != NULL) { Color *tempPtr = currPtr; currPtr = currPtr-&gt;nextPtr; free(tempPtr); } } Color *newNode(int color) { Color *newPtr = malloc(sizeof(Color)); if(newPtr == NULL) exit(EXIT_FAILURE); newPtr-&gt;c = color; newPtr-&gt;nextPtr = NULL; return newPtr; } int insertAndIncrease(Color **lPtr, int thiscolor) { Color *currPtr = *lPtr; Color *prevPtr = NULL; if(currPtr == NULL) { // list is empty, add current color and return 1 *lPtr = newNode(thiscolor); return 1; } while(currPtr != NULL &amp;&amp; currPtr-&gt;c != thiscolor) { prevPtr = currPtr; currPtr = currPtr-&gt;nextPtr; } if(currPtr == NULL) { // found no color equal to the one passed, so it's a new color prevPtr-&gt;nextPtr = newNode(thiscolor); return 1; } return 0; } void processQuery(Cp *points, int npoints, Query q, int *ncolors) { Color *colors = NULL; for(size_t i = 0; i &lt; npoints; i++) { if(points[i].x &gt;= q.x1 &amp;&amp; points[i].x &lt;= q.x2 &amp;&amp; points[i].y &gt;= q.y1 &amp;&amp; points[i].y &lt;= q.y2) { // if check is passed, then the point is inside the rectangle *ncolors = *ncolors + insertAndIncrease(&amp;colors, points[i].c); } } freeList(&amp;colors); } void processQueries(Cp *points, int npoints, Query *queries, int nqueries) { for(size_t i = 0; i &lt; nqueries; i++) { int thisQColors = 0; processQuery(points, npoints, queries[i], &amp;thisQColors); printf("%d\n", thisQColors); } } int main() { int numPoints, numQueries; scanf("%d%d", &amp;numPoints, &amp;numQueries); // get number of colored points Cp *arr = malloc(sizeof(Cp) * numPoints); // allocate array of numPoints colored points if(arr == NULL) return EXIT_FAILURE; Query *queries = malloc(sizeof(Query) * numQueries); // allocate array of numQueries queries if(queries == NULL) return EXIT_FAILURE; for(size_t i = 0; i &lt; numPoints; i++) { // fill the array scanf("%d%d%d", &amp;arr[i].x, &amp;arr[i].y, &amp;arr[i].c); } for(size_t i = 0; i &lt; numQueries; i++) { // get the queries scanf("%d%d%d%d", &amp;queries[i].x1, &amp;queries[i].y1, &amp;queries[i].x2, &amp;queries[i].y2); } processQueries(arr, numPoints, queries, numQueries); free(arr); free(queries); return EXIT_SUCCESS; } </code></pre> <p>Example inputs and outputs:</p> <pre><code>INPUT 6 4 0 0 1 6 0 1 6 1 13 1 3 8 4 4 9 4 6 137000 2 2 9 7 0 0 7 7 6 2 7 8 0 2 5 5 OUTPUT 2 5 0 2 --- INPUT 10 30 3 16 6 11 1 12 16 3 32 7 7 25 3 14 4 3 0 13 6 15 19 1 4 50 1 10 19 11 5 35 7 10 16 14 2 1 16 8 3 15 11 16 14 4 15 15 2 12 3 15 11 15 16 16 3 2 10 9 1 14 9 16 3 3 3 7 4 6 8 15 14 2 15 4 10 15 11 16 4 0 13 5 2 6 5 10 7 6 12 9 1 1 2 9 5 12 11 15 15 1 15 3 6 9 14 11 15 0 16 3 14 0 16 12 15 9 15 16 7 1 13 8 7 2 8 10 7 2 11 12 11 7 13 10 3 3 9 4 11 11 14 11 5 6 6 16 12 8 15 9 OUTPUT 0 4 2 0 1 0 1 3 0 2 0 0 2 0 1 1 1 0 0 1 1 0 3 1 2 0 0 0 1 0 --- INPUT 16 3 7 97 1 21 8 2 30 21 5 14 45 4 5 83 0 7 2 2 12 91 3 3 26 8 1 62 3 20 34 6 15 65 8 18 14 0 29 49 1 29 58 6 27 28 3 27 13 6 2 69 22 99 25 50 26 57 15 50 16 96 OUTPUT 3 0 1 <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T23:01:45.233", "Id": "468763", "Score": "1", "body": "Were upper limits specified for the coordinates and the color?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T23:05:09.210", "Id": "468764", "Score": "1", "body": "@harold INT_MAX was the upper limit" } ]
[ { "body": "<blockquote>\n <p>I'm interested in constructive feedback on how I could improve the algorithm to make it faster and do less checks.</p>\n</blockquote>\n\n<p><code>processQuery()</code> is O(n) with</p>\n\n<pre><code>for(size_t i = 0; i &lt; npoints; i++) {\n</code></pre>\n\n<p>An alternative would create a binary like tree in 2 dimensions. Not a <a href=\"https://en.wikipedia.org/wiki/Binary_search_tree\" rel=\"nofollow noreferrer\">BST</a>, bit a <a href=\"https://en.wikipedia.org/wiki/Quadtree\" rel=\"nofollow noreferrer\">quadtree</a>. Then the searching within a rectangle could take advantage of <em>potentially</em> O log(n).</p>\n\n<p>As with any advanced search techniques, the real advantage occurs with large <code>n</code>, not so much with <code>n</code> of OP's test code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T01:38:56.947", "Id": "468776", "Score": "1", "body": "Thank you for the answer. I realize it won't make a difference at a small input size, but here's to things to consider: 1. Our programs will only be accepted by our online platform if it gives the output in under a second. It gets tested against 10 inputs and mine has a problem with one test case (5000 points and 5000 queries), in which it almost takes 2 seconds, indicating that there's margin of improvement 2. I am studying not so much the C code, as much as the algorithm. This is an algorithms course I'm following and I'm looking for the most efficient solution asymptotically." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T01:14:57.947", "Id": "239034", "ParentId": "239021", "Score": "4" } }, { "body": "<p>The storage of both points and queries is suboptimal - in both cases, they are plain unsorted arrays. We could use better strategies for representing one or both.</p>\n\n<p>As a simple example, consider keeping points as a list of rows in ascending order, with each row being a list of points. Now, when we evaluate a query, we can quickly skip the rows that are before the bounding rectangle, and we can finish when we reach the first row that's after the rectangle. Similarly, we can stop examining a row and quickly move to the next row when we reach the horizontal bound.</p>\n\n<p>Further improvements in indexing rows and columns can be made, potentially leading to a quadtree representation, as used in most serious geospatial applications.</p>\n\n<hr>\n\n<p>Building a linked list of colours for each query involves a lot of small memory allocations, which can be a serious performance hit. We could instead count distinct colours as we read the list of points, and then use a single array of that size to note the colours found (this can even be shared amongst all the queries). We might consider keeping this array sorted (using <code>bsearch()</code> to find elements), though the cost/benefit trade-off to that is less clear-cut than in a case where we know we have many times more lookups than insertions.</p>\n\n<hr>\n\n<p>We're gaining nothing by reading all queries into an array and then executing them sequentially. We could just execute each query immediately after we read it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T12:52:28.983", "Id": "468833", "Score": "0", "body": "As per your point of sorting points, that's the first thing I thought about. However, the second thing I thought is that I'm still not sure how, after having sorted the points (say by their *y* coordinate), I can skip to the rows that are withing the bounds of the rectangle. Won't I still have to test at least one coordinate per point? This might save me a few checks but asymptotically this part is still *O* (*n*) unless I'm missing something. Actually, having to sort first this'll now be *O* (*n*log*n*)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T12:55:11.097", "Id": "468834", "Score": "0", "body": "My intuition was to somehow use a binary search on the sorted point array, but instead of looking for one key, I'll look for keys within a given range. However, that would only allow me to find a point within the range, whereas what I need to do is find *every* point within that range." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:53:02.493", "Id": "468851", "Score": "0", "body": "I wrote this answer in fairly broad terms on purpose because so much of the workload depends on the nature of the inputs, especially the point density. I'm not recommending any particular approach but rather giving some options to explore. Certainly, a sorted list of sorted rows (or a sorted list of sorted columns) is just a starting point - I'm sure you can think how to best organise your data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:53:51.647", "Id": "468853", "Score": "0", "body": "As hinted, the quadtree will enable the very best performance on large data sets (if you keep a colour-list in each node, then you can update your results directly from that when you reach one that's entirely within the search bounds, without traversing any deeper, and certainly without visiting individual points)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T08:59:56.637", "Id": "239047", "ParentId": "239021", "Score": "3" } } ]
{ "AcceptedAnswerId": "239034", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T20:38:13.860", "Id": "239021", "Score": "4", "Tags": [ "performance", "c" ], "Title": "Count distinct colors within a bounding rectangle" }
239021
<p>First I've to indicate that <strong>this is my homework</strong>.</p> <p>An example of a given input is:</p> <pre><code>s1 = {'p1': (x1, y1), 'p2': (x2, y2)} </code></pre> <p>where all names and coordinations are user input, only the input format is predefined; also p1 is the upper leftmost point and p2 is the lower rightmost point as shown below:</p> <p><a href="https://i.stack.imgur.com/tvppc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tvppc.png" alt="enter image description here"></a></p> <p>I can go on to get area, surrounding, midpoint, height and width based on this input.</p> <p>I wrote a code that works as demanded but I don't like it. it doesn't seem I followed the Pythonic approach here; how can I improve this?</p> <pre><code>class rectangle: def __init__(self, dct): # ['name', [x, y]] names = list(dct.keys()) coords = list(dct.values()) start = [names[0], coords[0]] end = [names[1], coords[1]] self.start = start self.end = end # int start_coords = self.start[1] end_coords = self.end[1] width = end_coords[0] - start_coords[0] height = end_coords[1] - start_coords[1] self.width = width self.height = height # [x, y] midpoint = [self.width / 2, self.height / 2] self.midpoint = midpoint # int area = (self.width + self.height) * 2 surr = self.width * self.height self.area = area self.surr = surr s1 = rectangle({'p1': (1,1), 'p2': (2,2)}) print('point one: ', s1.start) print('point two: ', s1.end) print('width: ', s1.width) print('height: ', s1.height) print('midpoint: ', s1.midpoint) print('area: ', s1.area) print('surrounding: ', s1.surr) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T22:19:45.670", "Id": "468761", "Score": "0", "body": "What is those code supposed to do? Calculate the area of the rectangle? I don't see any output in your program. Please add more details about what your code is supposed to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T22:31:03.270", "Id": "468762", "Score": "0", "body": "@Linny I did, thanks. yes, it is supposed to calculate and show the values I mentioned in the title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T10:36:17.060", "Id": "468818", "Score": "6", "body": "Your `area` property is called 'perimeter' in mathematics, while your `surr` property is actually called the an 'area'." } ]
[ { "body": "<ul>\n<li>Class should begin with capital, so <code>Rectangle</code></li>\n<li>You are creating local variables just to set them to object on next line using <code>self</code>, assign calculation to <code>self.xyz</code> variable directly. For example:</li>\n</ul>\n\n<pre><code> self.area = (self.width + self.height) * 2\n self.surr = self.width * self.height\n</code></pre>\n\n<ul>\n<li>Creating list of keys, then list of values to then map it to different structure seems very obscure. Take a look at <a href=\"https://www.tutorialspoint.com/python/dictionary_items.htm\" rel=\"noreferrer\">items</a>. I think you can change your code to:</li>\n</ul>\n\n<pre><code> items = dct.items()\n start = items[0]\n end = items[1]\n</code></pre>\n\n<p>Still, I don't understand, why are you doing this. I'd just access those values directly from original dct, I find it more readable and clean, ex:</p>\n\n<pre><code>width = dct[\"p2\"][0] - dct[\"p1\"][0]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:08:01.227", "Id": "468839", "Score": "0", "body": "because point names are user input, i can't assure it's `'p1'` or `'p2'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:12:50.617", "Id": "468841", "Score": "0", "body": "You need to specify that. I assumed that part is given from the assignment." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T22:56:54.923", "Id": "239027", "ParentId": "239023", "Score": "8" } }, { "body": "<p>Following <a href=\"https://codereview.stackexchange.com/a/239027\">the advice</a> from <a href=\"https://codereview.stackexchange.com/users/214636/k-h\">K.H.</a> we get:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Rectangle:\n def __init__(self, dct):\n items = dict.items()\n self.start = items[0]\n self.end = items[1]\n\n self.width = self.end[1][0] - self.start[1][0]\n self.height = self.end[1][1] - self.start[1][1]\n self.midpoint = [self.width / 2, self.height / 2]\n self.area = (self.width + self.height) * 2\n self.surr = self.width * self.height\n</code></pre>\n\n<p>This still has a couple of problems:</p>\n\n<ul>\n<li><p>By passing <code>dct</code> as a <code>dict</code> you have made two assumptions:</p>\n\n<ol>\n<li>Dictionaries are <a href=\"https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation\" rel=\"noreferrer\">ordered by default now</a> but on 3.5 and before they are not.</li>\n<li>A user will always enter the start as the first value of the dictionary.</li>\n</ol>\n\n<p>These are bad because you've made some assumptions without being explicit. To solve this you can just pass <code>start</code> and <code>end</code> to <code>Rectangle</code>.</p></li>\n<li><p>Start is assumed to have lower values than end. This means <code>self.width</code> and <code>self.height</code> can be negative values, if this assumption no longer holds. A negative width or height don't make much sense.</p>\n\n<p>This assumption also goes on to effects <code>self.area</code> and <code>self.surr</code>.</p></li>\n<li>Start and end don't make too much sense to return a key, that isn't ever used in <code>Rectangle</code>.</li>\n<li><p><a href=\"https://duckduckgo.com/?q=area+of+a+rectangle\" rel=\"noreferrer\">Area and surr are wrong</a>.</p>\n\n<ul>\n<li>The equation for area is <span class=\"math-container\">\\$ab\\$</span> not <span class=\"math-container\">\\$2(a + b)\\$</span>.</li>\n<li>The equation for surface area, perimeter, is <span class=\"math-container\">\\$2(a + b)\\$</span> not <span class=\"math-container\">\\$ab\\$</span>.</li>\n</ul></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Rectangle:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n self.width = abs(self.end[0] - self.start[0])\n self.height = abs(self.end[1] - self.start[1])\n self.midpoint = [self.width / 2, self.height / 2]\n self.area = self.width * self.height\n self.surr = (self.width + self.height) * 2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:06:26.707", "Id": "468838", "Score": "0", "body": "`self.start = items[0]` gives me `TypeError: 'dict_items' object is not subscriptable`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:16:08.100", "Id": "468842", "Score": "1", "body": "@Nitwit I didn't make that as a suggestion, please take that up with K.H." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T00:31:37.243", "Id": "239031", "ParentId": "239023", "Score": "7" } }, { "body": "<h1>PEP-8</h1>\n\n<ul>\n<li>Class names should be <code>CapWords</code>, so instead of <code>rectangle</code> you should have <code>Rectangle</code>.</li>\n<li>Commas should be followed by 1 space. You've mostly followed this, except in <code>s1 = rectangle({'p1': (1,1), 'p2': (2,2)})</code></li>\n</ul>\n\n<h1>Bugs</h1>\n\n<ul>\n<li>The formula for \"area\" is not twice the sum of width &amp; height.</li>\n<li>I don't know what \"surrounding\" is, but the formula for perimeter is not width times height.</li>\n<li>The midpoint (centre?) of a rectangle should be within the bounds of the rectangle. Consider the rectangles with corners (10, 10) and (12, 12). The centre would be (11, 11), not (1, 1) as calculated.</li>\n</ul>\n\n<h1>Awkward initialization</h1>\n\n<p>This code:</p>\n\n<pre><code> names = list(dct.keys())\n coords = list(dct.values())\n start = [names[0], coords[0]]\n end = [names[1], coords[1]]\n self.start = start\n self.end = end\n</code></pre>\n\n<p>relies on the dictionary's ordering of keys. It can break in Python 3.6 and earlier (CPython 3.5 and earlier). It does not enforce the key names <code>p1</code> and <code>p2</code>; any two keys will work. And <code>self.start[0]</code> and <code>self.end[0]</code> are never used, so storing the key names in these entries is unnecessary.</p>\n\n<p>The code could simply and safely read:</p>\n\n<pre><code> self.start = dct['p1']\n self.end = dct['p2']\n</code></pre>\n\n<p>with suitable modifications of the usage of <code>self.start</code> and <code>self.end</code>.</p>\n\n<h1>Class with no methods</h1>\n\n<p>A class should have methods. Without any methods, you'd be better off with a <code>namedtuple</code> for constant data, or a <code>dict</code> for mutable data.</p>\n\n<p>So let's give your class some methods:</p>\n\n<pre><code> def width(self):\n return self.end[0] - self.start[0]\n\n def height(self):\n return self.end[1] - self.start[1]\n</code></pre>\n\n<p>As mentioned by <a href=\"https://codereview.stackexchange.com/a/239031/100620\">Peilonrayz</a>, you may wish to use <code>abs(...)</code> here. </p>\n\n<p>You can use these methods externally:</p>\n\n<pre><code>print('width: ', s1.width())\nprint('height: ', s1.height())\n</code></pre>\n\n<p>as well as in other members of this class:</p>\n\n<pre><code> def area(self):\n return (self.width() + self.height()) * 2 # Note: Formula is still incorrect\n</code></pre>\n\n<h1>An Over-Engineered Solution</h1>\n\n<p>Do not submit this as your home-work solution! You would likely fail or be expelled! This illustrates some advanced concepts like the <a href=\"https://docs.python.org/3/library/dataclasses.html?highlight=data#module-dataclasses\" rel=\"noreferrer\"><code>@dataclass</code></a> and the <a href=\"https://docs.python.org/3/library/typing.html?highlight=namedtuple#typing.NamedTuple\" rel=\"noreferrer\"><code>NamedTuple</code></a>, type hints and the <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\"><code>typing</code></a> module, as well as read-only <a href=\"https://docs.python.org/3/library/functions.html?highlight=property#property\" rel=\"noreferrer\"><code>@property</code></a> attributes, a <a href=\"https://docs.python.org/3/library/functions.html?highlight=classmethod#classmethod\" rel=\"noreferrer\"><code>@classmethod</code></a>, and <code>\"\"\"docstrings\"\"\"</code>. You may find these interesting to study in your free time.</p>\n\n<pre><code>from typing import NamedTuple\nfrom dataclasses import dataclass\n\nclass Point(NamedTuple):\n x: float\n y: float\n\n@dataclass\nclass Rectangle:\n \"\"\"A class for calculations on a Rectangle\"\"\"\n\n p1: Point\n p2: Point\n\n @classmethod\n def from_dict(cls, dct):\n \"\"\"\n Constructs a Rectangle from a dictionary with \"p1\" and \"p2\" keys.\n These keys must contain a tuple or list of two numeric values.\n \"\"\"\n return Rectangle(Point._make(dct['p1']), Point._make(dct['p2']))\n\n @property\n def width(self):\n \"\"\"\n Computes the width of the rectangle.\n \"\"\"\n return abs(self.p2.x - self.p1.x)\n\n @property\n def height(self):\n \"\"\"\n Computes the height of the rectangle.\n \"\"\"\n return abs(self.p2.y - self.p1.y)\n\n @property\n def area(self):\n \"\"\"\n Incorrectly computes the area of the rectangle.\n \"\"\"\n return (self.width + self.height) * 2 # Note: still the incorrect formula\n\ns1 = Rectangle.from_dict({'p1': (1,1), 'p2': (2,2)})\nprint('point one: ', s1.p1)\nprint('point two: ', s1.p2)\nprint('width: ', s1.width)\nprint('height: ', s1.height)\nprint('area: ', s1.area)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>point one: Point(x=1, y=1)\npoint two: Point(x=2, y=2)\nwidth: 1\nheight: 1\narea: 4\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:59:46.383", "Id": "468856", "Score": "4", "body": "Just to slightly extend the \"Class with no methods\" feedback; storing everything in variable is also going to cause you to synchronize this data constantly, for mutable objects. For example, if I were to change one of the parameters of the rectangle, you'd need to recalculate the area/perimeter/midpoint. By using a method, you defer the calculation to when it is actually needed. That means I can change the parameters as much as I want, and only when I want to fetch the information (e.g. midpoint) does the calculation take place with the _current_ values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:02:35.050", "Id": "468857", "Score": "3", "body": "You're not going to be failed for over-complicating your homework; my strong impression is that if OP is being asked to implement a `Rectangle` class, they'll probably get at least a C for anything that _works_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:04:05.903", "Id": "468858", "Score": "2", "body": "I would also advocate against being scared of `typing` or `namedtuple`. While OP probably doesn't need every tool they're using, use of language features for their intended purposes (particularly typing) should be encouraged." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:16:16.963", "Id": "468860", "Score": "3", "body": "@ShapeOfMatter The OP tagged their post with \"beginner\" and \"homework\". Suddenly using 7 language features which have not been taught would raise questions by any grader. If the OP cannot explain what they do or how they work, it would be obvious the code was not their own. Thus my caution not to use the over-engineered solution. It, however, is followed by an invitation to study these in their free time, which should be taken as encouragement to look into these advanced features and use them where appropriate." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T00:42:50.587", "Id": "239032", "ParentId": "239023", "Score": "15" } } ]
{ "AcceptedAnswerId": "239032", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:47:11.150", "Id": "239023", "Score": "12", "Tags": [ "python", "beginner", "object-oriented", "homework", "hash-map" ], "Title": "Implementing a rectangle class" }
239023
<p>I've written this react-native component which is giving me a bad feeling that it's not as good as my expectations.</p> <p>I want to make it look cleaner with smart and less code.</p> <pre><code>import React, { Component } from 'react'; import { SafeAreaView, View, Text, ScrollView, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native'; // Axios const axios = require('axios').default; // Toast import Toast from 'react-native-simple-toast'; // Redux import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { authenticate } from '../redux/actions/Actions'; // AsyncStorage import AsyncStorage from '@react-native-community/async-storage'; // Style import { style, textInput, button } from '../assets/Style'; class Register extends Component { constructor(props) { super(props); this.state = { first_name: '', last_name: null, username: '', email: '', password: '', password_confirmation: '', loading: false, errors: {} }; } register() { const { first_name, last_name, username, email, password, password_confirmation } = this.state; this.setState({ loading: true, errors: {} }); axios.post('register', { first_name, last_name, username, email, password, password_confirmation }).then(({data}) =&gt; { axios.defaults.headers.common['Authorization'] = `Bearer ${data.token}`; AsyncStorage.setItem('token', data.token).then(() =&gt; { this.props.authenticate(true, { user: data.user }); }); }).catch(error =&gt; { if (! error.response || (error.response &amp;&amp; error.response.status !== 422)) { Toast.show('An error occurred.'); } else { this.setState({ errors: error.response.data.errors }); } }).finally(() =&gt; { this.setState({ loading: false }); }); } getMessages(field) { const { errors } = this.state; if (! errors[field]) return &lt;&gt;&lt;/&gt;; return ( &lt;&gt;{ errors[field].map((item, index) =&gt; &lt;Text style={ style.inlineDangerMessage } key={index}&gt;{item}&lt;/Text&gt;) }&lt;/&gt; ); } render() { const { loading, errors } = this.state; const opacity = loading ? 0.5 : 1; const disabled = loading ? true : false; return ( &lt;SafeAreaView style={ style.safeArea }&gt; &lt;ScrollView contentContainerStyle={ [style.flexCenter] }&gt; &lt;View style={{ width: '60%' }}&gt; &lt;TextInput style={ [textInput.default, (errors.first_name &amp;&amp; style.isInvalidBottomBorder)] } placeholder="First name" defaultValue="" onChangeText={(text) =&gt; this.setState({ first_name: text })} /&gt; { this.getMessages('first_name') } &lt;TextInput style={ [textInput.default, (errors.last_name &amp;&amp; style.isInvalidBottomBorder), { marginTop: 10 }] } placeholder="Last name" defaultValue="" onChangeText={(text) =&gt; this.setState({ last_name: text })} /&gt; { this.getMessages('last_name') } &lt;TextInput style={ [textInput.default, (errors.username &amp;&amp; style.isInvalidBottomBorder), { marginTop: 10 }] } placeholder="Username" defaultValue="" onChangeText={(text) =&gt; this.setState({ username: text })} /&gt; { this.getMessages('username') } &lt;TextInput style={ [textInput.default, (errors.email &amp;&amp; style.isInvalidBottomBorder), { marginTop: 10 }] } placeholder="Email" defaultValue="" onChangeText={(text) =&gt; this.setState({ email: text })} /&gt; { this.getMessages('email') } &lt;TextInput style={ [textInput.default, (errors.password &amp;&amp; style.isInvalidBottomBorder), { marginTop: 10 }] } placeholder="Password" defaultValue="" secureTextEntry={true} onChangeText={(text) =&gt; this.setState({ password: text })} /&gt; { this.getMessages('password') } &lt;TextInput style={ [textInput.default, (errors.password_confirmation &amp;&amp; style.isInvalidBottomBorder), { marginTop: 10 }] } placeholder="Password confirmation" defaultValue="" secureTextEntry={true} onChangeText={(text) =&gt; this.setState({ password_confirmation: text })} /&gt; { this.getMessages('password_confirmation') } &lt;TouchableOpacity style={ [button.primary, style.flexCenter, { marginTop: 10, height: 40, opacity }] } onPress={() =&gt; this.register()} disabled={disabled}&gt; { ! loading ? &lt;Text style={ [style.vazirBold, style.textCenter, { color: '#fff' }] }&gt;Register&lt;/Text&gt; : &lt;ActivityIndicator size="small" color="#fff" /&gt; } &lt;/TouchableOpacity&gt; &lt;TouchableOpacity style={{ marginTop: 15 }} onPress={() =&gt; this.props.navigation.goBack()} disabled={loading}&gt; &lt;Text style={ [button.link, style.textCenter] }&gt;I already have an account!&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; &lt;/ScrollView&gt; &lt;/SafeAreaView&gt; ); } } const mapStateToProps = (state) =&gt; { const { redux } = state return { redux } }; const mapDispatchToProps = (dispatch) =&gt; ( bindActionCreators({ authenticate, }, dispatch) ); export default connect(mapStateToProps, mapDispatchToProps)(Register); </code></pre>
[]
[ { "body": "<ol>\n<li><p>You don't need to use <code>if</code> and <code>&lt;&gt;&lt;/&gt;</code> for conditional-rendering:</p>\n\n<pre><code> getMessages(field) {\n const { errors } = this.state;\n return (\n errors[field] &amp;&amp; errors[field].map((item, index) =&gt; (\n &lt;Text style={style.inlineDangerMessage} key={index}&gt;\n {item}\n &lt;/Text&gt;\n ))\n )\n }\n</code></pre></li>\n<li><p>You can reuse the <code>TextInput</code> since there are many of them:</p>\n\n<ul>\n<li><p>build an array of what you need</p>\n\n<pre><code>const field = [\n { id: \"1\", attr: \"first_name\", placeholder: \"First name\" },\n { id: \"2\", attr: \"last_name\", placeholder: \"Last name\" }\n // ...\n];\n</code></pre></li>\n<li><p>write common function</p>\n\n<pre><code> styleFunction = attrName =&gt; {\n const { errors } = this.state;\n return [textInput.default, errors[attrName] &amp;&amp; style.isInvalidBottomBorder];\n };\n</code></pre></li>\n<li><p>and map the repeated components</p>\n\n<pre><code>{field.map(item =&gt; (\n &lt;&gt;\n &lt;TextInput\n style={this.styleFunction(item.attr)}\n placeholder={item.placeholder}\n defaultValue=\"\"\n onChangeText={text =&gt; this.setState({ [item.attr]: text })}\n /&gt;\n {this.getMessages(item.attr)}\n &lt;/&gt;\n))}\n</code></pre></li>\n</ul></li>\n</ol>\n\n<hr>\n\n<p>I'm sure there are other places where can be improved. As far as my immediate view, that's what I have got.</p>\n\n<p>All the code here:</p>\n\n<p><a href=\"https://codesandbox.io/s/objective-cdn-rhh9y?fontsize=14&amp;hidenavigation=1&amp;theme=dark\" rel=\"nofollow noreferrer\"><img src=\"https://codesandbox.io/static/img/play-codesandbox.svg\" alt=\"Edit objective-cdn-rhh9y\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T12:19:29.437", "Id": "522347", "Score": "0", "body": "I just want to add one more thing create router classes for webservices rather than using axios everytime." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T08:11:46.310", "Id": "239045", "ParentId": "239024", "Score": "2" } } ]
{ "AcceptedAnswerId": "239045", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:55:00.033", "Id": "239024", "Score": "3", "Tags": [ "javascript", "react-native" ], "Title": "React-native component" }
239024
<blockquote> <p>Design a class called Stopwatch. The job of this class is to simulate a stopwatch. <strong>It should provide two methods: Start and Stop.</strong> We call the start method first, and the stop method next. Then we ask the stopwatch about the duration between start and stop. <strong>Duration should be a value in TimeSpan.</strong> Display the duration on the console. We should also be able to use a stopwatch multiple times. So we may start and stop it and then start and stop it again. Make sure the duration value each time is calculated properly. We should not be able to start a stopwatch twice in a row (because that may overwrite the initial start time). So the class should <strong>throw an InvalidOperationException if its started twice</strong>.</p> <p>The aim of this exercise is to make you understand that a class should be always in a valid state. We use encapsulation and information hiding to achieve that. The class should not reveal its implementation detail. It only reveals a little bit, like a blackbox. From the outside, you should not be able to misuse a class because you shouldn’t be able to see the implementation detail.</p> </blockquote> <p>That is the information given to me from the tutorial I am taking to teach myself C#. I have completed this and looking for ways to improve my code and/or learn something new here. I have tested this and to my knowledge is working as expected. Any help is appreciated.</p> <pre><code>using System; namespace ExerciseOne { public static class Stopwatch { private static DateTime TimeStart { get; set; } private static DateTime TimeStop { get; set; } private static bool isStarted = false; private static bool isStopped = false; private static void StartTimer(DateTime start) { if (isStarted) { throw new InvalidOperationException("Unable to start a stopwatch twice in a row."); } else { isStarted = true; isStopped = false; TimeStart = start; } } private static void StopTimer(DateTime stop) { if (isStopped) { throw new InvalidOperationException("Unable to stop a stopwatch twice in a row."); } else { isStarted = false; isStopped = true; TimeStop = stop; } } private static string ElapsedTimer() =&gt; (TimeStop - TimeStart).ToString(); private static void Begin() { StartTimer(DateTime.Now); System.Console.WriteLine(" - Stopwatch has begun."); } private static void End() { StopTimer(DateTime.Now); Console.WriteLine($" - Stopwatch has stopped. Elapsed Time: {ElapsedTimer()}"); } public static void RunProgram() { Console.WriteLine("Stopwatch program."); Console.WriteLine("Type \"S\" to start the program. Type \"T\" to stop the program. Type \"E\" to end the program."); while (true) { ConsoleKeyInfo cki = Console.ReadKey(false); if (cki.Key == ConsoleKey.E) { Console.WriteLine(": \"E\" key was pressed. Progam exited."); return; } else if (cki.Key == ConsoleKey.S) { Begin(); } else if (cki.Key == ConsoleKey.T) { End(); } else { Console.WriteLine("\nPlease type either \"S\" to start the program, \"T\" to stop the program, \"E\" to end the program."); } } } } } </code></pre> <pre><code>using System; namespace ExerciseOne { class Program { static void Main() =&gt; Stopwatch.RunProgram(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:23:51.943", "Id": "468865", "Score": "0", "body": "Related question that I once answered. See OP for GitHub link. https://codereview.stackexchange.com/questions/217285/stopwatch-exercise-from-training-course/217696#217696" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:25:11.323", "Id": "468866", "Score": "1", "body": "Nice that you try things on your own. If you ever want to see how Microsoft does it, check out https://referencesource.microsoft.com/#System/services/monitoring/system/diagnosticts/Stopwatch.cs,ceb0ba9cc88de82e" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:50:14.033", "Id": "468877", "Score": "0", "body": "Please be aware that `Stopwatch` is commonly used as a _high resolution_ timer. The answers I see here do not address that issue. If you don't care, you can use the `DateTime` class and properties, but be aware they will be nowhere near as accurate as `Stopwatch`. If you need a high resolution example I can write an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:57:35.317", "Id": "468879", "Score": "1", "body": "@Zer0 This is taking from a coding exercise, in which case the learners do not need a high resolution timer. The emphasis is on class design, not timers. If they needed a high resolution timer in some real application, they would obviously use `System.Diagnostics.Stopwatch`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T17:01:01.197", "Id": "468880", "Score": "0", "body": "@RickDavin Just noting the difference. And that you can code a high resolution timer without `Stopwatch`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T22:36:45.207", "Id": "468904", "Score": "0", "body": "Once I get this all refactored to satisfy the coding lesson I do intent to go back and do a proper job of this with the Stopwatch class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T19:03:41.463", "Id": "469114", "Score": "0", "body": "Please do not edit this post, especially the quote on top. It is there verbatim for a reason to understand the scope and what was given to me to work with." } ]
[ { "body": "<blockquote>\n<pre><code>public static void RunProgram()\n{\n ....\n}\n</code></pre>\n</blockquote>\n\n<p>Why do you run the application as a method on the <code>Stopwatch</code> class it self?</p>\n\n<hr>\n\n<p>You have made all the methods (<code>StartTimer()</code>, <code>StopTimer()</code>) private. This means that they only can be run from your <code>RunProgram</code> method, which occupy the main thread of the program and measures nothing. This set up makes the entire effort rather useless. I would expect a stopwatch being able to measure something in a way like:</p>\n\n<pre><code> Stopwatch stopwatch = Stopwatch.StartNew();\n\n // TODO: execute something you want to measure\n Thread.Sleep(5000);\n\n stopwatch.Stop();\n\n Console.WriteLine($\"Duration: {stopwatch.Duration}\");\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> private static bool isStarted = false;\n private static bool isStopped = false;\n</code></pre>\n</blockquote>\n\n<p>These flags can be combined into one <code>isRunning</code>, used like:</p>\n\n<pre><code> private static void StartTimer(DateTime start)\n {\n if (isRunning)\n {\n throw new InvalidOperationException(\"Unable to start a stopwatch twice in a row.\");\n }\n else\n {\n isRunning = true;\n TimeStart = start;\n }\n }\n</code></pre>\n\n<p>and</p>\n\n<pre><code> private static void StopTimer(DateTime stop)\n {\n if (!isRunning)\n {\n throw new InvalidOperationException(\"Unable to stop the stopwatch because it is not running.\");\n }\n else\n {\n isRunning = false;\n TimeStop = stop;\n }\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> private static void Begin()\n {\n StartTimer(DateTime.Now);\n System.Console.WriteLine(\" - Stopwatch has begun.\");\n }\n</code></pre>\n</blockquote>\n\n<p>You shouldn't write to the console in class methods of any object, unless it's explicitly meant to be a console application. The above message is useless in a WinForm application.</p>\n\n<hr>\n\n<blockquote>\n <p><code>private static void StartTimer(DateTime start)</code></p>\n</blockquote>\n\n<p>I don't se why you have a start time as argument to <code>StartTimer</code>. Why not just call <code>DateTime.Now</code> inside it? And likewise in <code>StopTimer</code>.</p>\n\n<hr>\n\n<p>You were told to provide the result as a <code>TimeSpan</code>, but you actually return a string:</p>\n\n<blockquote>\n <p><code>private static string ElapsedTimer() =&gt; (TimeStop - TimeStart).ToString();</code></p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><code>public static class Stopwatch</code></p>\n</blockquote>\n\n<p>The major problem with your implementation is though, that you make it static. That means that you only can run one \"instance\" at a time. In this way you aren't able to measure on two treads at the same time - or have nested measurements.</p>\n\n<p>I would remove all the static stuff and only have one static method - starting a new <code>Stopwatch</code> instance, that then can be stopped by calling <code>Stop()</code> on the returned object like I showed above. So the public interface of the object would be:</p>\n\n<pre><code> public class Stopwatch\n {\n public TimeSpan Duration { get; }\n\n public void Start() { }\n public void Stop() { }\n public static Stopwatch StartNew() { }\n }\n</code></pre>\n\n<p>I think you have misunderstood the concepts of \"<em>encapsulation and information hiding</em>\" slightly. An object must have a public interface through which clients can communicate with it, but they shouldn't be allowed to manipulate the objects internal state (for instance the <code>StartTime</code> member of your watch) - only through the public interface. The client shouldn't know about how you measure the time internally, they are only interested in the final result, when they stop the watch by calling <code>Stop()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:19:56.797", "Id": "468863", "Score": "1", "body": "Best practices for internal time keeping is to use `DateTime.UtcNow` instead of `DateTime.Now`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T22:59:13.670", "Id": "468911", "Score": "0", "body": "`I think you have misunderstod the concepts of \"encapsulation and information hiding\" slightly.` Indeed, I started this lesson thinking to myself that I don't understand the concept and just tried my best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T23:18:26.667", "Id": "468913", "Score": "0", "body": "Based on all you commented on I am working on a refactor to the best of my understanding of your suggestions and will post it when I am done. Thank you for taking the time to point out how to improve this code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T00:12:56.113", "Id": "468919", "Score": "0", "body": "This is my refactor so far.\nhttps://gist.github.com/milliorn/96d009b2a17f7ff05e884057851f0089" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T06:45:01.090", "Id": "468935", "Score": "0", "body": "@Milliorn: That looks fine to me. When we review, we often focus on the not so good things and forget to point out the good: You write actually quite clear and easy to understand code, and your naming is precise - which is not only a good start but something that always should be in focus, when writing code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T07:19:13.380", "Id": "468938", "Score": "1", "body": "@Henrik Hansen it took me about an hour to read over both post here a few times and really think about what was said. I was getting confused at first and frustrated. But after an hour of looking at my code and reading everything over a few times it started to make sense what was suggested and why. The end result is definitely better than where I started. I appreciate all your help so far on my post and thank you for it." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T06:36:40.257", "Id": "239040", "ParentId": "239033", "Score": "6" } }, { "body": "<p>I agree with @Henrik_Hansen's answer. My answer builds upon his. </p>\n\n<p>I absolutely don't see a reason for anything to be <code>static</code>.</p>\n\n<p>Your <code>Stopwatch</code> class should only be for a stop watch. Right now you have commingled a UI into the stopwatch. In the name of <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Separation of Concerns</a>, I see no reason for any <code>Console.Write</code> or <code>Console.WriteLine</code> in the <code>Stopwatch</code> class.</p>\n\n<p>Going further, I see no reason for any method in <code>Stopwatch</code> to return a <code>string</code>. For <code>Duration</code>, simply return the <code>TimeSpan</code> value and leave it to whoever called that to decide what to do with it. Maybe they want it <code>ToString()</code>, but that's up to them. Maybe they want to add the <code>Duration</code> leg to cumulative <code>TimeSpan</code>.</p>\n\n<p>Any internal time keeping calling <code>DateTime</code> should always use <code>DateTime.UtcNow</code> and not <code>DateTime.Now</code>. Granted <code>UtcNow</code> is faster than <code>Now</code> but in real-time that is laughably negligible. The main reason to do it is to avoid any Daylight Saving Time transitions where you start the stopwatch during standard time and stop it during DST. This would produce incorrect <code>Duration</code>.</p>\n\n<p>A stopwatch really has only 1 state. It is either running or it is stopped. You do not need 2 variables for start and stop state. This runs the risk of you accidentally having conflicting states, e.g. the <code>isStarted</code> and <code>isStopped</code> are both true or both false. You only need 1 such variable. I personally prefer this:</p>\n\n<pre><code>public bool IsRunning { get; private set; }\n</code></pre>\n\n<p>Adding to Henrik's skeletal class, I would update it to:</p>\n\n<pre><code>public class Stopwatch\n {\n public TimeSpan Duration { get; }\n public bool IsRunning { get; private set; }\n\n public void Start() { }\n public void Stop() { }\n public static Stopwatch StartNew() { }\n }\n</code></pre>\n\n<p>The interesting thing you can do now with <code>Duration</code> is control the behavior of what happens if someone asks for the <code>Duration</code> while the stopwatch is running. Would you want to throw an exception? I personally would want to see the current <code>Duration</code> without stopping the stopwatch. This would produce a leg time while letting the stopwatch continue running.</p>\n\n<p>Once you get this going, I would suggest you could add other nice methods. This would mirror <code>Diagnostics.Stopwatch</code>. Two such methods would be <code>Reset</code> and <code>Restart</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T17:34:47.060", "Id": "468883", "Score": "0", "body": "Good point about using **UTC** in case of Daylight Saving Time transition - very important. The OP does not state the level of **precision** sought - the strategies will be different depending on whether we want accuracy to the second, millisecond or microsecond. Plus, it should be possible to query the duration while the stopwatch is still running. Perhaps invoke a callback function at regular intervals and leave the console handling to a delegate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T00:06:53.207", "Id": "468917", "Score": "0", "body": "@Rick I have been unable to figure out how to do this suggestion `Going further, I see no reason for any method in Stopwatch to return a string`. Your wiki link was very informative and useful. I did change to `DateTime.UtcNow`. Good catch. Based on Henrik and your post I was able to refactor my code to this suggestion here `A stopwatch really has only 1 state. It is either running or it is stopped`. Thank you both for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T00:12:44.220", "Id": "468918", "Score": "0", "body": "This is my refactor so far.\nhttps://gist.github.com/milliorn/96d009b2a17f7ff05e884057851f0089" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T12:05:54.883", "Id": "468966", "Score": "0", "body": "@Milliorn Avoiding strings in Stopwatch class would mean applying this change `public TimeSpan ElapsedTimer() => (timeStop - timeStart);` although you may need to check the is running state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T21:18:19.303", "Id": "469002", "Score": "0", "body": "@RickDavin thought that was what I tried before posting. Obviously not since that works. Thank you for that." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T15:14:01.577", "Id": "239061", "ParentId": "239033", "Score": "2" } }, { "body": "<p>This is my refactor based on all the suggestions made here. Works quite nice. Thank you all for your help and teaching me a few things.</p>\n\n<p><strong><em>Stopwatch.cs</em></strong></p>\n\n<pre><code>using System;\n\nnamespace ExerciseOne\n{\n public class Stopwatch\n {\n private DateTime timeStart;\n private DateTime timeStop;\n private bool isRunning;\n\n private void StartTimer()\n {\n if (isRunning)\n {\n throw new InvalidOperationException(\"Unable to start a stopwatch twice in a row.\");\n }\n else\n {\n isRunning = true;\n timeStart = DateTime.UtcNow;\n timeStop = DateTime.UtcNow;\n }\n }\n\n private void StopTimer()\n {\n if (!isRunning)\n {\n throw new InvalidOperationException(\"Unable to stop a stopwatch twice in a row.\");\n }\n else\n {\n isRunning = false;\n timeStop = DateTime.UtcNow;\n }\n }\n\n public TimeSpan ElapsedTimer =&gt; (timeStop - timeStart);\n public void Begin() =&gt; StartTimer();\n public void End() =&gt; StopTimer();\n }\n}\n</code></pre>\n\n<p><strong><em>Program.cs</em></strong></p>\n\n<pre><code>using System;\n\nnamespace ExerciseOne\n{\n class Program\n {\n static void Main()\n {\n Console.WriteLine(\"Stopwatch program.\");\n Console.WriteLine(\"Type \\\"S\\\" to start the program. Type \\\"T\\\" to stop the program. Type \\\"E\\\" to end the program.\");\n Stopwatch sw = new Stopwatch();\n\n while (true)\n {\n ConsoleKeyInfo cki = Console.ReadKey();\n\n if (cki.Key == ConsoleKey.E)\n {\n Console.WriteLine(\": \\\"E\\\" key was pressed. Progam exited.\");\n return;\n }\n else if (cki.Key == ConsoleKey.T)\n {\n sw.End();\n Console.WriteLine($\" - Stopwatch has stopped. Elapsed Time: {sw.ElapsedTimer}\");\n }\n else if (cki.Key == ConsoleKey.S)\n {\n sw.Begin();\n System.Console.WriteLine(\" - Stopwatch has begun.\");\n }\n else\n {\n Console.WriteLine(\"\\nPlease type either \\\"S\\\" to start the program, \\\"T\\\" to stop the program, \\\"E\\\" to end the program.\");\n }\n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T21:22:52.243", "Id": "239118", "ParentId": "239033", "Score": "1" } } ]
{ "AcceptedAnswerId": "239040", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T00:50:58.597", "Id": "239033", "Score": "4", "Tags": [ "c#", "object-oriented", "console" ], "Title": "Stopwatch class without using System.Diagnostics in C#" }
239033
<p>The following is an implementation of Newton's method of finding root of a function.</p> <pre><code>using System; using System.Drawing; using ZedGraph; //Newton's Method //https://www.youtube.com/watch?v=2GrfaB88w4M&amp;t=350s //https://stackoverflow.com/questions/12915317/how-to-find-derivative-of-a-function-using-c //https://www.geeksforgeeks.org/program-for-newton-raphson-method/ namespace _1_22_Newton_Method_of_Root_Finding { public delegate double MyFunction(double x); public class RootFinder { static double EPSILON = 0.01; static double h = 1.0e-6; public static double Derivative(MyFunction func, double x0) { double x1 = x0 - h; double x2 = x0 + h; double y1 = func(x1); double y2 = func(x2); double der = (y2 - y1) / (x2 - x1);//&lt;==== i am not sure about this. return der; } private static double NextNewton(MyFunction func, double guess) { return guess - func(guess) / Derivative(func, guess); } public static double Newton(MyFunction func, double init) { double x = init; double y = NextNewton(func, x); //for(int i=0 ; i &lt; 10 ; i++) while(Math.Abs(y) &gt;= EPSILON) //while(true) { y = NextNewton(func, x); if (x == y) { break; } Console.WriteLine("Root = {0}", y); x = y; } return y; } } </code></pre> <p>Kindly, review the source code.</p> <p>Does this source code have any pitfall?</p>
[]
[ { "body": "<pre><code>double der = (y2 - y1) / (x2 - x1);//&lt;==== i am not sure about this.\n</code></pre>\n\n<p>You got it right.</p>\n\n<hr>\n\n<p>The function <code>Derivative</code> can return 0, in which case you'll end up dividing by 0 at the function <code>NextNewton</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T08:16:15.040", "Id": "239046", "ParentId": "239044", "Score": "0" } }, { "body": "<blockquote>\n <p><code>Math.Abs(y) &gt;= EPSILON</code></p>\n</blockquote>\n\n<p>I think this condition is only satisfied for roots around zero on the x-axis. Maybe you confuse yourself by naming the next <code>x</code> as <code>y</code>? A better name would be <code>x1</code>.</p>\n\n<p>The actual continue condition should be <code>Math.Abs(x - x1) &gt;= EPSILON</code> and you then can skip the test <code>if (x == y) break;</code> </p>\n\n<hr>\n\n<p>Your rather large value of <code>EPSILON</code> may result in imprecise roots now and then.</p>\n\n<hr>\n\n<p>You can clean up the main algorithm to something like:</p>\n\n<pre><code>public static double Newton(MyFunction func, double init)\n{\n double x;\n double x1 = init;\n\n do\n {\n x = x1;\n x1 = NextNewton(func, x);\n\n Console.WriteLine(\"Root = {0}\", x1);\n } while (Math.Abs(x - x1) &gt;= EPSILON);\n\n return x1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T09:22:23.030", "Id": "239048", "ParentId": "239044", "Score": "1" } } ]
{ "AcceptedAnswerId": "239048", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T07:36:52.340", "Id": "239044", "Score": "1", "Tags": [ "c#", "numerical-methods" ], "Title": "Implementation of Newton's method of finding root of a function" }
239044
<p>I'm representing coordinates in a multi-dimensional array, and I'd like to stick as closely to native arrays as possible.</p> <p><strong>nArray.hpp</strong></p> <pre><code>#include &lt;stdexcept&gt; // Array that allows for negative integers template &lt;typename T, int SIZE&gt; struct nArray { private: T array[SIZE]; public: nArray() { if ((SIZE + 1) % 2 != 0) { throw std::length_error("Array size must be odd number"); } } T&amp; operator[] (int index) { if (abs(index) &gt; (SIZE-1)/2) { throw std::out_of_range("Array index is out of bounds"); } return array[index + SIZE/2]; } }; </code></pre> <p>So something like <code>nArray&lt;nArray&lt;int, 100&gt;, 100&gt; array;</code> is a 2-dimensional array in which either bracket can accept any index whose absolute value is less than or equal to 50 without entering undefined-behavior territory (e.g. - <code>array[-40][10]</code>). As far as I can tell, it works as intended (specifically, things that crashed when I tried to give negative indices on a regular multi-dimensional array do not crash when I use negative indices on nArray), but I wouldn't be surprised if there is a lot of potentially dangerous stuff going on under-the-hood that I'm unaware of.</p> <p>Does this look ok, or is this an example of how ignorance can destroy computers?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:16:35.930", "Id": "468843", "Score": "1", "body": "This is insufficient code for a code review, we need to see how this is used in working code to be able to perform a proper code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:27:19.863", "Id": "468844", "Score": "0", "body": "@pacmaninbw The example I gave was `array[-40][10]` and that is all I am asking about; I think a \"proper code review\" would answer my question, which doesn't require anything outside of that example. Is my overloading of the `[]` operator sound, or are there native-array landmines I'm stepping on by doing this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T19:20:50.593", "Id": "468890", "Score": "0", "body": "Out of curiosity, what's the use-case for this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T19:25:15.463", "Id": "468892", "Score": "0", "body": "@John It's part of a C++ script representing a 3D coordinate system (I used a 2D example here for the sake of simplicity) where the origin of the map is (0, 0) (by the logic of the 3rd-party engine which uses the script). Also, I'm just picking up C++ again (after maybe a couple of weeks of trying it years ago), so the part about keeping it as close to native arrays as possible is more a learning exercise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T19:26:14.190", "Id": "468893", "Score": "0", "body": "Thanks, that makes sense." } ]
[ { "body": "<p>Array size can hardly be negative, so <code>std::size_t</code> would be a better type for <code>SIZE</code>.</p>\n\n<p>There's nothing wrong with negative indices as long as you stay inside the bounds. Maps and unordered maps can be indexed with values of arbitrary types (as long as those types satisfy requirements for keys), and that alone does not constitute a cause for segfault.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T12:03:57.260", "Id": "239054", "ParentId": "239052", "Score": "0" } }, { "body": "<p>Just few small points.</p>\n\n<p>You can use <code>std::array</code>.</p>\n\n<p>You can have the size represent half of the entire diameter. Thus having <code>nArray&lt;T, 50&gt;</code> allocate memory for indices -50 to 50 and avoid the odd size check.</p>\n\n<p>You might also reconsider if you really need <code>[][]</code> access and whether it wouldnt be better to implement a class that has just 1d array to represent 2d matrix and offer access through a member method <code>at(x, y)</code>. Or if you have a point like structure you could have something like <code>operator[](const point &amp; p)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T15:50:15.910", "Id": "239062", "ParentId": "239052", "Score": "5" } }, { "body": "<p>The \"odd\" check in the constructor is a bit obfuscated, and it does not need to be executed at runtime. A simpler <code>static_assert</code> to check for odd (and non-negative) would report errors sooner.</p>\n\n<pre><code>std::static_assert(SIZE &gt;= 0 &amp;&amp; (SIZE &amp; 1) == 1);\n</code></pre>\n\n<p>Having <code>operator[]</code> perform a range check is atypical. The <code>operator[]</code> is typically fast, with no error checking, while an <code>at</code> member function will perform range checks. However, your use case may require otherwise.</p>\n\n<p>It won't work with const arrays, as there is no const version of the array access operator. <code>constexpr</code> versions can also do the range checking at compile time, if you're accessing elements using constants and not variables.</p>\n\n<p><strong>Future expansion</strong></p>\n\n<p>You can add in <code>begin</code> and <code>end</code> members (et. al.) for use with iteration and range based for loops.</p>\n\n<p>Using <code>std::array</code> as the underlying storage type can make it a bit easier to implement.</p>\n\n<p>This class could be modified/expanded to allow generic upper and lower bounds, rather than balanced ones.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T17:15:06.023", "Id": "239067", "ParentId": "239052", "Score": "4" } } ]
{ "AcceptedAnswerId": "239067", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T11:44:46.610", "Id": "239052", "Score": "-1", "Tags": [ "c++", "array" ], "Title": "Array class with negative indices for half of the items" }
239052
<p>i would really appreciate if anyone could invest a bit of time to review what i did. Basically this is first time i do this, and that is reason why i need another set of eyes.</p> <p>I have Spring Boot application and i decided to use docker containers on my server to run applications across multiple environments (DEV, QA and PROD). I invested a lot of time to properly research everything and at the end i was able to achieve what i wanted from the beginning. </p> <p>Basically my code is on GitLab and instead of using jenkins i wanted to take advantage of GitLab CI and simply automatize deployment of my app. </p> <p>Lets begin, i will start from Dockerfile and it looks like this:</p> <pre><code>FROM maven:3.6.3-jdk-11-slim AS MAVEN_BUILD ARG SPRING_ACTIVE_PROFILE MAINTAINER jmj COPY pom.xml /build/ COPY src /build/src/ WORKDIR /build/ RUN mvn clean install -Dspring.profiles.active=$SPRING_ACTIVE_PROFILE &amp;&amp; mvn package -B -e -Dspring.profiles.active=$SPRING_ACTIVE_PROFILE FROM openjdk:11-slim WORKDIR /app COPY --from=MAVEN_BUILD /build/target/storm-*.jar /app/storm.jar ENTRYPOINT ["java", "-jar", "storm.jar"] </code></pre> <p><strong>Dockerfile notes:</strong> I had one major issue here, and that is passing dynamically ARG in ENTRYPOINT, to be more specific i wanted to pass active profile, i was able to fix it by passing active profile when doing docker run, which you will see below. <strong>Dockerfile question:</strong> I am using Java 11 on my project, because it is last LTS version of Java, what i have noticed compared when i used Java 8, is that docker image is really large, a lot of larger than when using Java 8. If i am correct, that is because there is no safe and tested Java 11 alpine image, which at the end produce smaller docker images. My actual question here is: Is my choice of images fine, and is it expected to have image size of ~450MB (on java 8 it was below ~200)</p> <p>Next lets jump on my .gitlab-ci.yml file.</p> <pre><code>services: - docker:19.03.7-dind stages: - build and push docker image - deploy docker build: image: docker:stable stage: build and push docker image before_script: - source .${CI_COMMIT_REF_NAME}.env script: - docker build --build-arg SPRING_ACTIVE_PROFILE=$SPRING_ACTIVE_PROFILE -t $DOCKER_REPO . - docker login -u $DOCKER_USER -p $DOCKER_PASSWORD docker.io - docker push $DOCKER_REPO deploy: image: ubuntu:latest stage: deploy before_script: - 'which ssh-agent || ( apt-get update -y &amp;&amp; apt-get install openssh-client -y )' - eval $(ssh-agent -s) - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - - mkdir -p ~/.ssh - chmod 700 ~/.ssh - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" &gt; ~/.ssh/config - source .${CI_COMMIT_REF_NAME}.env script: - ssh root@$SERVER "docker stop $APP_NAME; docker system prune -a -f; docker pull $DOCKER_REPO; docker container run -d --name $APP_NAME -p $PORT:8080 -e SPRING_PROFILES_ACTIVE=$SPRING_ACTIVE_PROFILE $DOCKER_REPO" </code></pre> <p>Its important to mention that as extension for this file i also have 3 files, with names: <strong>.develop.env,.qa.env and .master.env</strong>. They represent dynamic variables that i need on different enviorements.</p> <pre><code>export SPRING_ACTIVE_PROFILE='development' export DOCKER_REPO="$DOCKER_DEV_REPO" export APP_NAME="$DEV_APP_NAME" export PORT='8080' </code></pre> <p>That is basically it, if anyone can see something that i could improve please let me know. Thank you all in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T07:48:07.803", "Id": "469034", "Score": "1", "body": "Fair play, you've clearly done your research here, to answer your first question about the image size, I think 450MB is fine, in my current role, since we're hardening our containers & strapping tonnes of other stuff in, the size of our images gets pretty huge, pretty quickly, but I work for an international financial company so security & enterprise are both **must haves**. The only thing I can think to suggest is to have all your env files as one, perhaps having pipeline variables to take care of the difference? - But that's optional really, maybe even a matter of opinion & taste." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T06:16:38.010", "Id": "500320", "Score": "0", "body": "I have an additional question, why isn't the maven build a part of the Gitlab CI? Rather, it is a part of your container building process...; this would create an additional layer in your docker image, ultimately making it heavier. Is there a specific reason to do so? You could build the jar in the CI, and then just simply copy the jar file from the CI to the image's `/app` folder." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T12:25:51.973", "Id": "239055", "Score": "6", "Tags": [ "java", "dockerfile", "docker" ], "Title": "Implementation of Gitlab CI + Docker + Spring Boot" }
239055
<p>The data bellow shows part of my dataset, that is used to detect anomalies</p> <pre><code> describe_file data_numbers index 0 gkivdotqvj 7309.0 0 1 hpwgzodlky 2731.0 1 2 dgaecubawx 0.0 2 3 NaN 0.0 3 4 lnpeyxsrrc 0.0 4 </code></pre> <p>I used One Class SVM algorithm to detect anomalies</p> <pre><code>from pyod.models.ocsvm import OCSVM random_state = np.random.RandomState(42) outliers_fraction = 0.05 classifiers = { 'One Classify SVM (SVM)':OCSVM(kernel='rbf', degree=3, gamma='auto', coef0=0.0, tol=0.001, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=-1, contamination=outliers_fraction) } X = data['data_numbers'].values.reshape(-1,1) for i, (clf_name, clf) in enumerate(classifiers.items()): clf.fit(X) # predict raw anomaly score scores_pred = clf.decision_function(X) * -1 # prediction of a datapoint category outlier or inlier y_pred = clf.predict(X) n_inliers = len(y_pred) - np.count_nonzero(y_pred) n_outliers = np.count_nonzero(y_pred == 1) # copy of dataframe dfx = data[['index', 'data_numbers']] dfx['outlier'] = y_pred.tolist() IX1 = np.array(dfx['data_numbers'][dfx['outlier'] == 0]).reshape(-1,1) OX1 = dfx['data_numbers'][dfx['outlier'] == 1].values.reshape(-1,1) print('OUTLIERS : ',n_outliers,'INLIERS : ',n_inliers, clf_name) # threshold value to consider a datapoint inlier or outlier threshold = stats.scoreatpercentile(scores_pred,100 * outliers_fraction) tOut = stats.scoreatpercentile(dfx[dfx['outlier'] == 1]['data_numbers'], np.abs(threshold)) y = dfx['outlier'].values.reshape(-1,1) def severity_validation(): tOUT10 = tOut+(tOut*0.10) tOUT23 = tOut+(tOut*0.23) tOUT45 = tOut+(tOut*0.45) dfx['test_severity'] = "None" for i, row in dfx.iterrows(): if row['outlier']==1: if row['data_numbers'] &lt;=tOUT10: dfx['test_severity'][i] = "Low Severity" elif row['data_numbers'] &lt;=tOUT23: dfx['test_severity'][i] = "Medium Severity" elif row['data_numbers'] &lt;=tOUT45: dfx['test_severity'][i] = "High Severity" else: dfx['test_severity'][i] = "Ultra High Severity" severity_validation() from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(dfx[['index','data_numbers']], dfx.outlier, test_size=0.25, stratify=dfx.outlier, random_state=30) #Instantiate Classifier normer = preprocessing.Normalizer() svm1 = svm.SVC(probability=True, class_weight={1: 10}) cached = mkdtemp() memory = Memory(cachedir=cached, verbose=3) pipe_1 = Pipeline(steps=[('normalization', normer), ('svm', svm1)], memory=memory) cv = skl.model_selection.KFold(n_splits=5, shuffle=True, random_state=42) param_grid = [ {"svm__kernel": ["linear"], "svm__C": [0.5]}, {"svm__kernel": ["rbf"], "svm__C": [0.5], "svm__gamma": [5]} ] grd = GridSearchCV(pipe_1, param_grid, scoring='roc_auc', cv=cv) #Training y_pred = grd.fit(X_train, Y_train).predict(X_test) rmtree(cached) #Evaluation confmatrix = skl.metrics.confusion_matrix(Y_test, y_pred) print(confmatrix) Y_pred = grd.fit(X_train, Y_train).predict_proba(X_test)[:,1] def plot_roc(y_test, y_pred): fpr, tpr, thresholds = skl.metrics.roc_curve(y_test, y_pred, pos_label=1) roc_auc = skl.metrics.auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area ={0:.2f})'.format(roc_auc)) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show(); plot_roc(Y_test, Y_pred) </code></pre> <p>The code works just fine, however it just takes too long so I am hoping to maybe get some advice to optimize is so I runs faster.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T13:40:10.727", "Id": "239058", "Score": "2", "Tags": [ "python", "machine-learning" ], "Title": "One Class SVM algorithm taking too long" }
239058
<p>Since couple of days ago I started to learn python by doing AoC 2019. I would like to share with you my solution to <a href="https://adventofcode.com/2019/day/7" rel="nofollow noreferrer">day7</a> (Amplification Circuit) part 1 and part 2.</p> <p><strong>Challenge summary:</strong></p> <p>--- Day 7: Amplification Circuit ---</p> <p><strong>==================== Part 1 ====================</strong></p> <p>There are five amplifiers connected in series; each one receives an input signal and produces an output signal. They are connected such that the first amplifier's output leads to the second amplifier's input, the second amplifier's output leads to the third amplifier's input, and so on. The first amplifier's input value is 0, and the last amplifier's output leads to your ship's thrusters.</p> <pre><code> O-------O O-------O O-------O O-------O O-------O 0 -&gt;| Amp A |-&gt;| Amp B |-&gt;| Amp C |-&gt;| Amp D |-&gt;| Amp E |-&gt; (to thrusters) O-------O O-------O O-------O O-------O O-------O </code></pre> <p>The Elves have sent you some Amplifier Controller Software (your puzzle input), a program that should run on your existing <a href="https://adventofcode.com/2019/day/5" rel="nofollow noreferrer">Intcode computer</a>. Each amplifier will need to run a copy of the program.</p> <p>For example, suppose you want to try the phase setting sequence 3,1,2,4,0, which would mean setting amplifier A to phase setting 3, amplifier B to setting 1, C to 2, D to 4, and E to 0. Then, you could determine the output signal that gets sent from amplifier E to the thrusters with the following steps:</p> <p>Start the copy of the amplifier controller software that will run on amplifier A. At its first input instruction, provide it the amplifier's phase setting, 3. At its second input instruction, provide it the input signal, 0. After some calculations, it will use an output instruction to indicate the amplifier's output signal. Start the software for amplifier B. Provide it the phase setting (1) and then whatever output signal was produced from amplifier A. It will then produce a new output signal destined for amplifier C. Start the software for amplifier C, provide the phase setting (2) and the value from amplifier B, then collect its output signal. Run amplifier D's software, provide the phase setting (4) and input value, and collect its output signal. Run amplifier E's software, provide the phase setting (0) and input value, and collect its output signal. The final output signal from amplifier E would be sent to the thrusters. However, this phase setting sequence may not have been the best one; another sequence might have sent a higher signal to the thrusters.</p> <p>Here are some example programs:</p> <p><strong>Max thruster signal 43210</strong> (from phase setting sequence 4,3,2,1,0):</p> <p>3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0</p> <p><strong>Max thruster signal 54321</strong> (from phase setting sequence 0,1,2,3,4):</p> <p>3,23,3,24,1002,24,10,24,1002,23,-1,23, 101,5,23,23,1,24,23,23,4,23,99,0,0</p> <p><strong>Max thruster signal 65210</strong> (from phase setting sequence 1,0,4,3,2):</p> <p>3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33, 1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0</p> <p>Try every combination of phase settings on the amplifiers. What is the highest signal that can be sent to the thrusters?</p> <p><strong>==================== Part 2 ====================</strong></p> <pre><code> O-------O O-------O O-------O O-------O O-------O 0 -+-&gt;| Amp A |-&gt;| Amp B |-&gt;| Amp C |-&gt;| Amp D |-&gt;| Amp E |-. | O-------O O-------O O-------O O-------O O-------O | | | '--------------------------------------------------------+ | v (to thrusters) </code></pre> <p>Most of the amplifiers are connected as they were before; amplifier A's output is connected to amplifier B's input, and so on. However, the output from amplifier E is now connected into amplifier A's input. This creates the feedback loop: the signal will be sent through the amplifiers many times.</p> <p>In feedback loop mode, the amplifiers need totally different phase settings: integers from 5 to 9, again each used exactly once. These settings will cause the Amplifier Controller Software to repeatedly take input and produce output many times before halting. Provide each amplifier its phase setting at its first input instruction; all further input/output instructions are for signals.</p> <p>Don't restart the Amplifier Controller Software on any amplifier during this process. Each one should continue receiving and sending signals until it halts.</p> <p>All signals sent or received in this process will be between pairs of amplifiers except the very first signal and the very last signal. To start the process, a 0 signal is sent to amplifier A's input exactly once.</p> <p>Eventually, the software on the amplifiers will halt after they have processed the final loop. When this happens, the last output signal from amplifier E is sent to the thrusters. Your job is to find the largest output signal that can be sent to the thrusters using the new phase settings and feedback loop arrangement.</p> <p>Try every combination of the new phase settings on the amplifier feedback loop. What is the highest signal that can be sent to the thrusters?</p> <p><strong>==================== Here is my solution ====================</strong></p> <p>I found it quite clever that I actually connected this amplifiers in such cascade manner in code. What do you think?</p> <pre><code>#!/usr/bin/env python3 import sys import itertools from queue import Queue class amplifier(object): code = None def __init__(self, phase_input): self.pc = 0 self.halted = False self.other_amplifier = None self.inputs = Queue() self.add_input(phase_input) self.outputs = [] def set_other_amplifier(self, other_amplifier): self.other_amplifier = other_amplifier def has_other_amplifier(self): return self.other_amplifier is not None def add_input(self, _input): self.inputs.put(_input) def get_input(self): return self.inputs.get() def has_input(self): return not self.inputs.empty() def add_output(self, _output): if self.has_other_amplifier() and not self.other_amplifier.halted: self.other_amplifier.add_input(_output) else: self.outputs.append(_output) def run_program(self): ncp = amplifier.code.copy() i = self.pc while i &lt; len(ncp): op = ncp[i] if op == 1: ncp[ncp[i+3]] = ncp[ncp[i+1]] + ncp[ncp[i+2]] i += 4 elif op == 2: ncp[ncp[i+3]] = ncp[ncp[i+1]] * ncp[ncp[i+2]] i += 4 elif op == 3: if self.has_input(): inp = self.get_input() ncp[ncp[i+1]] = inp i += 2 else: self.pc = i if self.has_other_amplifier() and not self.other_amplifier.halted: self.other_amplifier.run_program() return elif op == 4: self.add_output(ncp[ncp[i+1]]) i += 2 elif op == 104: self.add_output(ncp[i+1]) i += 2 elif op == 5: # jump-if-true if ncp[ncp[i+1]] != 0: i = ncp[ncp[i+2]] else: i += 3 elif op == 105: if ncp[i+1] != 0: i = ncp[ncp[i+2]] else: i += 3 elif op == 1005: if ncp[ncp[i+1]] != 0: i = ncp[i+2] else: i += 3 elif op == 1105: if ncp[i+1] != 0: i = ncp[i+2] else: i += 3 elif op == 6: # jump-if-false if ncp[ncp[i+1]] == 0: i = ncp[ncp[i+2]] else: i += 3 elif op == 106: if ncp[i+1] == 0: i = ncp[ncp[i+2]] else: i += 3 elif op == 1006: if ncp[ncp[i+1]] == 0: i = ncp[i+2] else: i += 3 elif op == 1106: if ncp[i+1] == 0: i = ncp[i+2] else: i += 3 elif op == 7: # less than if ncp[ncp[i+1]] &lt; ncp[ncp[i+2]]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 107: if ncp[i+1] &lt; ncp[ncp[i+2]]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 1007: if ncp[ncp[i+1]] &lt; ncp[i+2]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 1107: if ncp[i+1] &lt; ncp[i+2]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 8: # equals if ncp[ncp[i+1]] == ncp[ncp[i+2]]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 108: if ncp[i+1] == ncp[ncp[i+2]]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 1008: if ncp[ncp[i+1]] == ncp[i+2]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 1108: if ncp[i+1] == ncp[i+2]: ncp[ncp[i+3]] = 1 else: ncp[ncp[i+3]] = 0 i += 4 elif op == 101: # addition ncp[ncp[i+3]] = ncp[i+1] + ncp[ncp[i+2]] i += 4 elif op == 1001: ncp[ncp[i+3]] = ncp[ncp[i+1]] + ncp[i+2] i += 4 elif op == 1101: ncp[ncp[i+3]] = ncp[i+1] + ncp[i+2] i += 4 elif op == 102: # multiplication ncp[ncp[i+3]] = ncp[i+1] * ncp[ncp[i+2]] i += 4 elif op == 1002: ncp[ncp[i+3]] = ncp[ncp[i+1]] * ncp[i+2] i += 4 elif op == 1102: ncp[ncp[i+3]] = ncp[i+1] * ncp[i+2] i += 4 elif op == 99: i = len(ncp) else: print(op, "opcode not supported") i += 1 self.halted = True if self.has_other_amplifier() and not self.other_amplifier.halted: self.other_amplifier.run_program() def get_signal(permutation_iter): a = amplifier(next(permutation_iter)) a.add_input(0) b = amplifier(next(permutation_iter)) c = amplifier(next(permutation_iter)) d = amplifier(next(permutation_iter)) e = amplifier(next(permutation_iter)) a.set_other_amplifier(b) b.set_other_amplifier(c) c.set_other_amplifier(d) d.set_other_amplifier(e) e.set_other_amplifier(a) a.run_program() return e.outputs def solve(permutation_base): permutations = itertools.permutations(permutation_base) max_signal = None max_signal_phase_seq = None for p in permutations: signal = get_signal(iter(p)) if not max_signal or signal &gt; max_signal: max_signal = signal max_signal_phase_seq = p print(max_signal_phase_seq, '-&gt;', max_signal) if __name__ == "__main__": with open("input") as f: amplifier.code = list(map(lambda x: int(x), f.readline().split(','))) solve([0, 1, 2, 3, 4]) # part1 solve([5, 6, 7, 8, 9]) # part2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T15:35:05.353", "Id": "468872", "Score": "0", "body": "Welcome to codereview! A post on coderevoew should be self-containing. Can you therefor add a summary of the challenge to your post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:56:48.327", "Id": "468878", "Score": "0", "body": "Also your title should reflect what you code does in a brief description." } ]
[ { "body": "<h2>Style</h2>\n\n<ul>\n<li>Use CamalCase for class names, like <code>class Amplifier</code>.</li>\n<li>No need to explicitly extends <code>object</code>.</li>\n<li>When encountering unsupported opcode, raise an exception to kill the program immediately instead of printing an error message. It helps you discover bugs earlier. This is known as <a href=\"https://en.wikipedia.org/wiki/Fail-fast\" rel=\"nofollow noreferrer\">\"fail fast\"</a>.</li>\n<li><code>get_signal()</code> should accept an <code>Iterable</code> instead of an <code>Iterator</code>. You can do a lot of magic with <code>Iterable</code>s, like this:</li>\n</ul>\n\n<pre><code>def get_signal(permutation_iter):\n # Transform list of integer into list of amplifiers and unpack them.\n a, b, c, d, e = map(amplifier, permutation_iter)\n a.add_input(0)\n\n a.set_other_amplifier(b)\n b.set_other_amplifier(c)\n c.set_other_amplifier(d)\n d.set_other_amplifier(e)\n e.set_other_amplifier(a)\n\n a.run_program()\n\n return e.outputs\n</code></pre>\n\n<p>It also makes the <code>iter()</code> call in <code>solve()</code> unnecessary.</p>\n\n<ul>\n<li>The main job of <code>solve()</code> is getting the maximum from a list of permutations, using <code>get_signal()</code> as key. Python already has <code>max()</code> function for this, but we need to extract the permutation itself as well. So we can write our own <code>argmax()</code> function to simplify this. Note that the code is a lot cleaner without <code>for</code> loop.</li>\n</ul>\n\n<pre><code>def argmax(iterable, key=None):\n arg = max((item for item in iterable), key=key)\n value = key(arg) if key else arg\n return arg, value\n\ndef solve(permutation_base):\n permutations = itertools.permutations(permutation_base)\n max_signal_phase_seq, max_signal = argmax(permutations, key=get_signal)\n print(max_signal_phase_seq, \"-&gt;\", max_signal)\n</code></pre>\n\n<h2>Structure</h2>\n\n<ul>\n<li>Pull out the intcode computer into its own function or class, which will ease code reuse(You'll need the intcode computer in multiple challenges of AoC later).</li>\n<li>Don't \"hard wire\" parameter modes into opcode. Parse parameter modes independently of actual operations. For example, opcode <code>102</code>, <code>1002</code>, and <code>1102</code> should trigger the same function(multiplication), only passing different parameters.(Spoiler: You'll need to add another parameter mode later)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T07:31:51.610", "Id": "239093", "ParentId": "239059", "Score": "1" } } ]
{ "AcceptedAnswerId": "239093", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T14:04:42.113", "Id": "239059", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "emulator" ], "Title": "Advent of Code 2019 Day 7 (simple emulator, opcode processing)" }
239059
<p>I want to represent components of LXC in django; so I defined them in models: Container, Network, Profile and Devices where each one of them have a set of attributs, but when it comes to representing configuration (each component has a set of configuration fields), I don't know if it is the right approach to follow. Below is an example code, given the fact that I use MongoDB as a database engine.</p> <pre><code>class Container(models.Model): name = models.CharField() remote = models.CharField() architecture = models.CharField() creation = models.DateField() status = models.CharField() containerType = models.CharField() pid = models.IntegerField() config = EmbeddedModelField('ContainerConfig') class ContainerConfig(models.Model): bootAutostart = models.BooleanField() bootAutoStartDelay = models.IntegerField() bootAutostartPriority = models.IntegerField() bootHostShutDownTimeOut = models.IntegerField() bootStopPrority = models.IntegerField() env = models.CharField() limitsCpu = models.CharField() limitsCpuAllowance = models.CharField() limitsCpuPriority = models.CharField() limitsDiskPriority = models.IntegerField() limitsHugePages64K = models.CharField() </code></pre> <p>Is it right to follow this approach?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:24:10.917", "Id": "239064", "Score": "2", "Tags": [ "python", "django", "mongodb" ], "Title": "Representing LXC component configuration in django" }
239064
<p>I am trying to write a human-readable tester for a functioning program.</p> <p>There are four methods in the class <code>Polynomial</code>: <code>public Polynomial(int[] coefficients)</code>, <code>public int getDegree()</code>, <code>public int getCoefficient(int k)</code>, <code>public long evaluate(int x)</code>.</p> <p>Where <code>coefficients</code> is an immutable array of elements that represent a polynomial. For example, the polynomial 6x^3 + 4x + 3 would be represented by its coefficients as <code>[3, 4, 0, 6]</code>. The method <code>getDegree()</code> determines the highest order term that has a non-zero coefficient. For example, the degree would equal 3 in the previous example. <code>getCoefficient(int k)</code> returns the coefficient of element <code>k</code>. For example, in the previous example, if <code>k = 2</code> the returned value is <code>0</code>. The method <code>evaluate(int x)</code> evaluates the polynomial with the value of <code>x</code>. In the previous example, the value returned when <code>x = 2</code> would be <code>59</code>.</p> <p>This is the tester I've written so far:</p> <pre><code>@Test public void testPolynomial() { int [] c1 = {0, 0, 0, 1}; Polynomial p1 = new Polynomial(c1); c1[2] = 1; assertEquals("Degree error", 3, p1.getDegree()); assertEquals("Polynomial must compute coefficients out of range", 0, p1.getCoefficient(-1)); assertEquals("Polynomial must compute coefficients out of range", 0, p1.getCoefficient(4)); assertEquals("Array is not immutable", 0, p1.getCoefficient(2)); assertEquals("Coefficient error near boundary", 1, p1.getCoefficient(3)); assertEquals("Coefficient error near boundary", 0, p1.getCoefficient(0)); assertEquals("Coeffificent error", 0, p1.getCoefficient(1)); assertEquals("Evaluation error", 0, p1.evaluate(0)); assertEquals("Evaluation error of negative x", -27, p1.evaluate(-3)); int[] c2 = {-1, 0, 0, 0}; Polynomial p2 = new Polynomial(c2); c2[2] = 4; assertEquals("Degree error", 0, p2.getDegree()); assertEquals("Polynomial must compute coefficients out of range", 0, p2.getCoefficient(-1)); assertEquals("Polynomial must compute coefficients out of range", 0, p2.getCoefficient(4)); assertEquals("Array is not immutable", 0, p2.getCoefficient(2)); assertEquals("Coefficient error near noundary", 0, p2.getCoefficient(3)); assertEquals("Coefficient error near noundary", -1, p2.getCoefficient(0)); assertEquals("Evaluation error", -1, p2.evaluate(0)); assertEquals("Evaluation error of negative x", -1, p2.evaluate(-3)); } </code></pre> <p>Are there any other test cases that anyone can think of that I could include into my tester or that I'm missing?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T20:37:04.357", "Id": "468900", "Score": "0", "body": "Code review is about refactoring code. Refactoring does not seem to be the purpose of your post. Without the class Polynomial, your post is therefor not a good fit for this forum. When you do add it, the question has to be reformatted to ask how you can improve your code. If reviewers are nice, they could give other testcases, but it's not the goal of this forum." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T02:06:54.203", "Id": "468923", "Score": "0", "body": "Originally I Posted on stack overflow and a comment told me was better suited here. I guess there's a lot of misinformation out there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T08:30:42.513", "Id": "468945", "Score": "0", "body": "I guess the comment thinks that we can help you further by suggesting the suggestions above... I only know about codereview and SO, so I wouldn't know where you can ask the question on your current form..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T17:21:35.147", "Id": "469104", "Score": "3", "body": "You do need to add the Polynomial class for us to do a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T21:04:07.117", "Id": "469138", "Score": "1", "body": "Yup. Add that class and it's a lot better already. Please take a look at the [help/on-topic] if you're in doubt as to what we do and don't do, or find us [in chat](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)." } ]
[ { "body": "<p>I'm not going to address what else you <em>could</em> test, since it really depends what you're expecting your <code>Polynomial</code> class to do. However, looking at your test, there's several things that could be improved.</p>\n<h1>Test One Thing</h1>\n<p>Having all of your assertions in the same test means that the test can fail for multiple different reasons, some of which are unrelated. Consider modifying your tests so that they contain the complete AAA for what they are testing. This makes it much clearer what the relationship between the data setup in the Arrange phase is, to the Assertions made.</p>\n<p>As an example, your code current does this:</p>\n<blockquote>\n<pre><code>int [] c1 = {0, 0, 0, 1};\nPolynomial p1 = new Polynomial(c1);\nc1[2] = 1;\nassertEquals(&quot;Degree error&quot;, 3, p1.getDegree());\nassertEquals(&quot;Polynomial must compute coefficients out of range&quot;, 0, p1.getCoefficient(-1)); \nassertEquals(&quot;Polynomial must compute coefficients out of range&quot;, 0, p1.getCoefficient(4));\nassertEquals(&quot;Array is not immutable&quot;, 0, p1.getCoefficient(2));\n</code></pre>\n</blockquote>\n<p>There's three unrelated assertions between the point where you modify your array (<code>c1[2] = 1</code>) and the assertion that it impacts 'Array it not immutable'. This make far less obvious what the 'c1[2] = 1' is doing there.</p>\n<p>Having multiple tests, where each one tests only a single thing also means that you don't need to put a message in each of your <code>assertEquals</code> calls. The test name itself tells you what you're testing.</p>\n<h1>Duplicate tests</h1>\n<p>Sometimes you want to test the same thing in different scenarios. Other times, it doesn't make as much sense. I'm pretty sure that if the array is immutable for <code>c1</code>, it will also be immutable for <code>c2</code>, testing it again doesn't seem like it's really adding value. If you do want to test the same thing, with different values, consider using parameterised tests. Something like this:</p>\n<pre><code>@ParameterizedTest\n@MethodSource(&quot;coefficients_outOfRangeCoefficient&quot;)\nvoid getCoefficient_outOfRange_computesZero(int[] coefficients, int outOfRangeCoefficient) {\n Polynomial polynomial = new Polynomial(coefficients);\n assertEquals(0, polynomial.getCoefficient(outOfRangeCoefficient));\n}\n\nstatic Stream&lt;Arguments&gt; coefficients_outOfRangeCoefficient() {\n return Stream.of(\n arguments(new int[] {0,0,0,1}, -1),\n arguments(new int[] {0,0,0,1}, -4),\n arguments(new int[] {-1,0,0,0}, -1),\n arguments(new int[] {-1,0,0,0}, 4)\n );\n}\n</code></pre>\n<p>Would allow the same test to be used across four different combinations of coefficients and get indexes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T12:36:42.370", "Id": "239097", "ParentId": "239065", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T16:48:19.517", "Id": "239065", "Score": "0", "Tags": [ "java", "unit-testing" ], "Title": "Possible Test Cases in Tester" }
239065
<p>Anyone could help me to optimize this block of code, I already did a bit improvement but since I'm really bad with this kind of algorithms this all I've done so far. Much appreciate if you can explain the improvement.</p> <p>This basically fill a bus (k is the number of seats on the bus) if all seats are filled save the last index of the person who gets into the bus.</p> <p>p is a list of persons waiting the bus (each person has patience limit) q is a list of time the bus will take to arrive.</p> <p>Example;</p> <pre><code>k=2 p={1,4,2,5} q={1,4} </code></pre> <p>On the first time bus will arrive in time 1 so person 1 and 2 will fill the bus and index of person will be saved in a list (r={2}).</p> <p>On the second time bus will arribe in time 4, person 1 and 3 leave person 2 and 4 fill the bus (r={2,4}).</p> <p>If the bus can't be filled then the number saved in the list is 0.</p> <pre><code>public static List&lt;Integer&gt; busFilled(int k, List&lt;Integer&gt; p, List&lt;Integer&gt; q) { List&lt;Integer&gt; busSeats = new ArrayList&lt;&gt;(); // Sort the times of bus arrival Collections.sort(q); // Loop each bus arrival for(int time : q) { // If person patience &lt; time set the patience to 0 for (int i=0; i&lt;p.size()-1; i++) { if (p.get(i) &lt; time) { p.set(i, 0); } } int aux = 0; // Loop each person patience for (int i=0; i&lt;=p.size()-1; i++) { // If person patience &gt; 0 count if ( p.get(i) &gt; 0) { aux++; } // If aux = bus seats add the last number(index) of person who filled the bus if (aux == k) { busSeats.add(i+1); break; // If i == total persons in queue set 0 } else if (i==p.size()-1){ busSeats.add(0); } } } return busSeats; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T02:23:42.270", "Id": "468928", "Score": "0", "body": "I'd suggest you [edit] your post to clarify the problem statement. Also consider editing the title to better reflect what problem is being solved (something catchy about people losing patience waiting for their bus?)" } ]
[ { "body": "<h2>Problem Statement</h2>\n\n<p>This is my understanding of the problem statement.</p>\n\n<ol>\n<li><p>We have a bus that has <code>k</code> seats.</p></li>\n<li><p>There is a list of people <code>p</code> waiting at a bus stop. The value in each position of the list is the amount of time the person is willing to wait for a bus. The list is replenished for each scheduled time the bus arrives. The wait times do not change with new people.</p></li>\n<li><p>There is a list of scheduled times <code>q</code> that the bus will arrive.</p></li>\n</ol>\n\n<p>The method <code>busFilled</code> returns a <code>List</code> of the index of the last person to get on the bus each time the bus arrives at the bus stop. There should be the same number of elements in the output <code>List</code> as there are in the list of scheduled times <code>q</code>.</p>\n\n<p>If no one can fit on the bus, the <code>List</code> should return zero in that position.</p>\n\n<h2>Analysis</h2>\n\n<p>I approached the problem the same way I approach any problem. I break the problem down into smaller and smaller steps until I can write code for each of the steps.</p>\n\n<p>Here's the code I wrote. The explanation follows the code.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class BusSimulation {\n\n public static void main(String[] args) {\n int k = 2;\n int[] people = { 1, 4, 2, 5 };\n List&lt;Integer&gt; p = createList(people);\n int[] busTime = { 1, 4 };\n List&lt;Integer&gt; q = createList(busTime);\n List&lt;Integer&gt; f = busFilled(k, p, q);\n Integer[] output = \n f.toArray(new Integer[0]);\n System.out.println(\"Result: \" + \n Arrays.asList(output));\n }\n\n public static List&lt;Integer&gt; createList(int[] array) {\n List&lt;Integer&gt; output = new ArrayList&lt;&gt;();\n for (int i = 0; i &lt; array.length; i++) {\n output.add(array[i]);\n }\n return output;\n }\n\n public static List&lt;Integer&gt; busFilled(int k, \n List&lt;Integer&gt; p, List&lt;Integer&gt; q) {\n List&lt;Integer&gt; output = new ArrayList&lt;&gt;();\n\n for (int i = 0; i &lt; q.size(); i++) {\n int busTime = q.get(i);\n int index = getPassengerIndex(k, p, busTime);\n output.add(index);\n }\n\n return output;\n }\n\n private static int getPassengerIndex(int k, \n List&lt;Integer&gt; p, int busTime) {\n int count = 0;\n int index = -1;\n\n for (int i = 0; i &lt; p.size(); i++) {\n if (busTime &lt;= p.get(i)) {\n index = i;\n count++;\n if (count &gt;= k) {\n return index + 1;\n }\n }\n }\n\n return index + 1;\n }\n\n}\n</code></pre>\n\n<p>The <code>main</code> method and the <code>createList</code> method set up the problem.</p>\n\n<p>I created a separate method, <code>getPassengerIndex</code>, to get the passenger index for one bus trip. That way, I avoided a nested for loop and worrying about how to break out of the nested for loop.</p>\n\n<p>The <code>getPassengerIndex</code> method loops through the passenger list. First, I test to see if the waiting time has been exceeded. If not, then I save the index and increment the count of the number of passengers boarding the bus. Finally, I test for the bus being filled. If so, I return the passenger number. If the bus isn't filled, I return the last passenger number whose waiting time has not been exceeded.</p>\n\n<p>I could test <code>getPassengerIndex</code> separate from the rest of the code. Once I got that method working, writing the <code>busFilled</code> method was straight forward.</p>\n\n<p>Decomposition, or divide and conquer, is the most straightforward way to solve problems.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T21:46:31.577", "Id": "240757", "ParentId": "239068", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T17:28:36.240", "Id": "239068", "Score": "0", "Tags": [ "java", "algorithm", "iteration" ], "Title": "Best way to optimize multiple search on Lists java" }
239068
<p>This is part of my homework on digital logic design, so I would like to present some technical background first.</p> <p><a href="https://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm" rel="nofollow noreferrer">Quine–McCluskey algorithm</a> is a method for minimizing Boolean functions. Given the <a href="https://en.wikipedia.org/wiki/Truthtable" rel="nofollow noreferrer">truth table</a> of a Boolean function, it tries to find the simplest sum-of-product to represent that function. </p> <p>For example, the Boolean function <span class="math-container">\$ F_{xyz}=xy' + yz \$</span> has the following truth table:</p> <pre><code> X Y Z F 0 0 0 0 0 1 0 0 1 0 2 0 1 0 0 3 0 1 1 1 4 1 0 0 1 5 1 0 1 1 6 1 1 0 0 7 1 1 1 1 </code></pre> <p>From the truth table, we can write the <a href="https://en.wikipedia.org/wiki/Disjunctive_normal_form" rel="nofollow noreferrer">DNF(disjunctive normal form)</a> of the Boolean function, which is a sum-of-product of all the rows where <span class="math-container">\$F = 1\$</span>.</p> <p><span class="math-container">\$ F_{xyz}= x'yz + xy'z' + xy'z + xyz \$</span></p> <p>Often, the DNF is represented by simply listing the index of the terms. For example, the previous function could be expressed as <span class="math-container">\$ \sum m(3,4,5,7) \$</span>. </p> <p>The Quine–McCluskey algorithm starts from DNF and ends with the simplied form, <span class="math-container">\$ F_{xyz}=xy' + yz \$</span>.</p> <p>Some more jargon:</p> <ul> <li>A <strong>minterm</strong> is a product where each variables appears once, like <span class="math-container">\$xy'z\$</span></li> <li>An <strong>implicant</strong> is a product that is not necessarily a minterm, like <span class="math-container">\$xy'\$</span>. Implicants can be obtained by combining minterms or other implicants(e.g. <span class="math-container">\$xy'z + xy'z'\$</span>)</li> <li>A <strong>prime implicant</strong> is an implicant which, when you have a bunch of implicants at hand, cannot be combined with any others to obtain simpler implicants.</li> </ul> <p>That should make it easier to understand the algorithm.</p> <hr> <p>Now the code part. I implemented a reduced version of the algorithm. There're no "don't care" inputs. The implementation assumes that the <a href="https://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm#Step_2:_prime_implicant_chart" rel="nofollow noreferrer">"prime implicant chart"</a> part of the problem can be solved via greedy algorithm, otherwise we just give up and throw an exception.</p> <p>I'm mainly concerned about two aspect of the code, but any suggestions or improvements are welcome!</p> <ul> <li>Frozensets. Python distinguishes between "normal" sets, which is mutable thus cannot be contained in a set, and frozensets. As I want to have sets within sets, I basically littered frozensets everywhere, sometimes mixing them with normal sets. Is this OK? Is there a better way to do this?</li> <li>Data abstraction. I exposed the implementation of an implicant(a tuple of a string and a set), which can make it hard to change it later on. In fact, I originally designed it that it is just a string, and later changed it, which involves a lot of search/replace. What's the proper way to solve this problem?(I know a little about OOP abstractions, but I usually find them verbose and brittle and hard to design well.)</li> </ul> <hr> <pre><code># An implicant consists of two parts in a tuple: # - A string consisting of 0, 1, and dash # - A set of numbers representing the minterms # Construct an implicant from its index in the truth table. # [var_cnt] number of variables in the truth table. # [index] its index in the truth table. def implicant_from_index(var_cnt, index): return ( bin(index)[2:].rjust(var_cnt, "0"), frozenset({index}), ) # Combines two implicants. # Returns the combined implicant, or False if they cannot be combined. # For example, combining "10-1" and "10-0" gives us "10--". def combine(implicant_a, implicant_b): str_a, nums_a = implicant_a str_b, nums_b = implicant_b def combine_str(str_a, str_b): assert len(str_a) == len(str_b) assert str_a != str_b if len(str_a) == 0 and len(str_b) == 0: return "" head_a, *rest_a = str_a head_b, *rest_b = str_b if head_a == head_b: combined = combine_str(rest_a, rest_b) if combined: return head_a + combined else: return False elif {head_a, head_b} == {"0", "1"} and rest_a == rest_b: return "-" + "".join(rest_a) else: return False combined_str = combine_str(str_a, str_b) if combined_str: return combined_str, nums_a.union(nums_b) else: return False # Find a set of prime implicants from DNF(disjunctive normal form). # [var_cnt] the number of variables. # [minterms] a list of intergers representing the boolean function in DNF. def find_prime_implicants(var_cnt, minterms): def iter(implicants): if len(implicants) == 0: return set() unused_implicants = implicants.copy() resulting_implicants = set() for term_a in implicants: for term_b in implicants: if term_a != term_b: combined = combine(term_a, term_b) if combined: unused_implicants.discard(term_a) unused_implicants.discard(term_b) resulting_implicants.add(combined) return unused_implicants.union(iter(resulting_implicants)) return iter({implicant_from_index(var_cnt, minterm) for minterm in minterms}) # Union in function form. # It also converts normal set to frozensets. # [sets] an iterable of sets to be unioned. def union(*sets): return frozenset().union(frozenset(s) if isinstance(s, set) else s for s in sets) # Select a minimum set of sets that cover their union. # This is a NP-complete problem. # Instead of implementing a proper algorithm that runs in exponential time, we just try some greedy method and give up if a solution cannot be found. # [sets] an iterable of sets to be covered. # [ignore_values] a set of values that should be excluded from the union. This argument is just for easy implementation. def minimum_cover(sets, ignore_values=frozenset()): # Remove "empty" sets. sets = frozenset( s for s in sets if len([x for x in s if x not in ignore_values]) &gt; 0 ) if len(sets) == 0: return frozenset() # Remove sets that are completely covered("shadowed") by another set. sets = frozenset(s for s in sets if not any(s &lt; t for t in sets)) # Try find a value that is only covered by one set. for v in union(*sets) - ignore_values: for s in sets: if v not in union(t - s for t in sets): # Gotcha return minimum_cover( sets - frozenset({s}), ignore_values=ignore_values.union(s) ).union({s}) # Worst case: non of the values are only covered by one set. # We give up. raise Exception() # Run the argorithm and print the result. # [vars] variable names of the boolean function. # [minterms] a list of intergers representing the boolean function in DNF(disjunctive normal form) def qm_algorithm(vars, minterms): prime_implicants = find_prime_implicants(len(vars), minterms) sets = frozenset(implicant[1] for implicant in prime_implicants) cover = minimum_cover(sets) strs = [implicant[0] for implicant in prime_implicants if implicant[1] in cover] terms = [ "".join( {"0": vars[i] + "'", "1": vars[i], "-": "",}[char] for i, char in enumerate(str) ) for str in strs ] print("sigma(", end="") print(*minterms, sep=", ", end="") print(") =&gt; ", end="") print(*terms, sep=" + ") </code></pre> <p>Test code:</p> <pre><code>qm_algorithm("XYZ", [3, 4, 5, 7]) # YZ + XY' qm_algorithm("XYZ", [1, 3, 5, 6, 7]) # XY + Z qm_algorithm("ABCD", [0, 2, 4, 8, 10, 11, 15]) # ACD + B'D' + A'C'D' qm_algorithm("WXYZ", [0, 1, 3, 5, 14, 15]) # W'X'Y' + W'Y'Z + W'X'Z + WXY </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T16:21:13.790", "Id": "468983", "Score": "0", "body": "Welcome to CodeReview@SE! What size functions do you intend to handle? Back in the day, we ran into layout&routing nightmares long before exceeding 32 bits, not to mention fan-in and fan-out limitations and processing time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T16:32:30.530", "Id": "468984", "Score": "0", "body": "(Are you aware of [Duşa, Adrian: *Enhancing Quine-McCluskey*](http://www.compasss.org/wpseries/Dusa2007b.pdf)?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T16:48:16.577", "Id": "468986", "Score": "1", "body": "(What we *did* use when we could lay hands on it was [Espresso](https://en.wikipedia.org/wiki/Espresso_heuristic_logic_minimizer#cite_note-Rudell_1986-3). Funny I should forget about \"multiple-valued variables\".)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T02:42:23.333", "Id": "469022", "Score": "0", "body": "@greybeard Could you tell me what is a \"size function\"? Do you mean how many variables we need to process? This is part of my homework to enhance my understanding of the algorithm and not meant to be practical. I'm mainly concerned about the implementation details of the code. Thanks for the additional pointers though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T05:43:49.023", "Id": "469029", "Score": "0", "body": "Not `size function`, but *size of the boolean function*. E.g. number of variables + number of terms *in the minimised function*." } ]
[ { "body": "<h2>Function signatures</h2>\n\n<p>This:</p>\n\n<pre><code>def combine(implicant_a, implicant_b):\n str_a, nums_a = implicant_a\n str_b, nums_b = implicant_b\n</code></pre>\n\n<p>should go in one of two directions:</p>\n\n<ul>\n<li>Unpack the arguments themselves, i.e. <code>def combine(str_a, nums_a, str_b, nums_b)</code>; or</li>\n<li>Make some kind of named tuple:</li>\n</ul>\n\n<pre><code>def combine(implicant_a, implicant_b):\n # Refer to implicant_a.str and implicant_a.nums\n</code></pre>\n\n<p>This <code>combine</code> function also has a problematic return type - mixed boolean-or-combined-implicant. Returning <code>False</code> on failure is a C-ism. In Python, the saner thing to do is raise an exception, and then catch it (or not) in the calling code.</p>\n\n<h2>Do not shadow built-ins</h2>\n\n<pre><code>def iter(implicants):\n</code></pre>\n\n<p>should have a different name, because <code>iter</code> is already a thing.</p>\n\n<h2>Specific exceptions</h2>\n\n<pre><code>raise Exception()\n</code></pre>\n\n<p>is going to make it effectively impossible to meaningfully catch this exception and distinguish it from others. You should use a narrower built-in at least (perhaps <code>ValueError</code>), or more likely define your own exception. This can be done in two lines and makes the job of the caller much easier.</p>\n\n<h2>Tests</h2>\n\n<p>You have tests; that's good! You should actually apply <code>assert</code>s to them so that they can be quickly run as a sanity check.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T16:15:29.243", "Id": "239235", "ParentId": "239069", "Score": "3" } } ]
{ "AcceptedAnswerId": "239235", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T17:45:12.107", "Id": "239069", "Score": "6", "Tags": [ "python", "algorithm" ], "Title": "Quine–McCluskey algorithm for minimizing Boolean functions" }
239069
<p>I have written the following routine to clean an html raw code and extract the text.</p> <p>It works, but the code is not very well written. Any ideas how to solve this faster and with fewer lines of code?</p> <p>Thanks a lot for your help!</p> <pre><code>import re def cleanhtml(raw_html): cleanr = re.compile('&lt;.*?&gt;') cleantext1 = re.sub(cleanr, ' ', raw_html) cleanr = re.compile('&amp;amp;') cleantext2 = re.sub(cleanr, '&amp;', cleantext1 ) cleanr = re.compile('\n') cleantext3 = re.sub(cleanr, ' ', cleantext2) cleanr = re.compile('&amp;nbsp;') cleantext4 = re.sub(cleanr, ' ', cleantext3) cleanr = re.compile('&amp;#8217;') cleantext5 = re.sub(cleanr, '\'', cleantext4) cleanr = re.compile('&amp;#8230;') cleantext6 = re.sub(cleanr, '...', cleantext5) cleanr = re.compile('&amp;#8216;') cleantext7 = re.sub(cleanr, '\'', cleantext6) cleanr = re.compile('&amp;#8221;') cleantext8 = re.sub(cleanr, '\'', cleantext7) cleanr = re.compile('&amp;#8220;') cleantext9 = re.sub(cleanr, '\'', cleantext8) cleanr = re.compile('&amp;#8211;') cleantext10 = re.sub(cleanr, '\'', cleantext9) cleanr = re.compile('&amp;#8212;') cleantext11 = re.sub(cleanr, '\'', cleantext10) cleanr = re.compile('&amp;#38;') cleantext12 = re.sub(cleanr, '&amp;', cleantext11) cleanr = re.compile('&amp;#2026;') cleantext13 = re.sub(cleanr, '...', cleantext12) cleanr = re.compile('&amp;#160;') cleantext14 = re.sub(cleanr, ' ', cleantext13) cleanr = re.compile('&amp;#038;') cleantext15 = re.sub(cleanr, '&amp;', cleantext14) return cleantext15.strip() </code></pre>
[]
[ { "body": "<p>Since you have basically the same statements over and over with different parameters, this can be turned into a loop. You can pair the pattern and the string you want to use to replace in a <code>dict</code>. This makes it clear what is paired with what. Take a look:</p>\n\n<pre><code>import re\n\ndef strip_html(raw_html: str) -&gt; str:\n pairs = {\n '&lt;.*?&gt;': ' ',\n '&amp;amp;': '&amp;',\n '\\n': ' ',\n '&amp;nbsp;': ' ',\n '&amp;#8217;': '\\'',\n '&amp;#8230;': '...',\n '&amp;#8216;': '\\'',\n '&amp;#8221;': '\\'',\n '&amp;#8220;': '\\'',\n '&amp;#8211;': '\\'',\n '&amp;#8212;': '\\'',\n '&amp;#38;': '&amp;',\n '&amp;#2026;': '...',\n '&amp;#160;': ' ',\n '&amp;#038;': '&amp;'\n }\n previous = raw_html\n for pattern in pairs:\n clean_text = re.sub(re.compile(pattern), pairs[pattern], previous)\n previous = clean_text\n return clean_text.strip()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T22:59:02.967", "Id": "468910", "Score": "1", "body": "I'd much rather use some kind of pairing instead to make it clear what pattern matches what. Dict or list of tupples." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T23:14:03.390", "Id": "468912", "Score": "0", "body": "Thanks a lot for your help, @Linny. Looks a lot better!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T23:26:52.747", "Id": "468916", "Score": "2", "body": "@K.H. That's an excellent point, I hadn't thought of that. I implemented that instead of zipping, it looks a lot clearer what is associated with what now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T07:41:44.603", "Id": "468943", "Score": "0", "body": "Yea, the pairing really cleaned it up." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T22:06:39.860", "Id": "239078", "ParentId": "239072", "Score": "7" } }, { "body": "<p>The problem with this approach is that it won't scale well and if you want to extract text from diverse sources it will be impossible to handle all possible cases.</p>\n\n<p>Regular expressions can be expensive, and if you have lots of text to process I would worry about performance. For many operations like changing <code>'&amp;amp;'</code> to <code>'&amp;'</code>, a regex is not even necessary, all you need is a simple <strong>search &amp; replace</strong>.</p>\n\n<p>Attempting to parse HTML or XML using regular expressions can easily turn into a coding nightmare so don't overdo it.</p>\n\n<p>I suggest that you use a dedicated library instead, like <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/\" rel=\"nofollow noreferrer\">BeautifulSoup</a> </p>\n\n<p>As a starting point:</p>\n\n<pre><code>from bs4 import BeautifulSoup\n\nhtml = \"&lt;p&gt;some HTML here&lt;/p&gt;\"\nsoup = BeautifulSoup(html, 'html.parser')\nprint(soup.get_text(\"\\n\"))\n</code></pre>\n\n<p>From the <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text\" rel=\"nofollow noreferrer\">documentation: get_text</a> (emphasis is mine):</p>\n\n<blockquote>\n <p>If you only want the text part of a document or tag, you can use the get_text() method. It returns all the text in a document or beneath a tag, as a single <strong>Unicode</strong> string</p>\n</blockquote>\n\n<p>Note the addition of <code>\"\\n\"</code>, that gets you <strong>multiline text</strong> where <code>&lt;p&gt;</code> or <code>&lt;br&gt;</code> tags are found. The function can also strip whitespace. There is a lot more to be said, so I will leave it to you to read the documentation and fine-tune the code according to your needs. This snippet is quite basic but may be sufficient for your purpose.</p>\n\n<p>As you can see a lot can be done with just a few lines of code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T13:06:44.677", "Id": "239100", "ParentId": "239072", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T18:54:22.820", "Id": "239072", "Score": "1", "Tags": [ "python", "python-3.x", "regex" ], "Title": "Cleaning HTMLs to extract text" }
239072
<p>I made a program that merges all the PDFs in a certain map. The program is made so it merges only one sided PDFs. I would like your opinion on the code and how can it be improved.</p> <pre><code>while True: print() try: map_name = input("Name of the map where PDFs are saved: ") # map where your documents are initial_path = r"C:\Users\...\Scanned Documents" # the initial path where all your documents get saved path = os.path.join(initial_path, map_name) os.chdir(path) break except (OSError, FileNotFoundError): print("There is no map with that name!") continue PDF_name_input = input("Name of your merged PDF: ") PDF_name = "{0}.pdf".format(PDF_name_input) PDF_arr = [] for file in os.listdir("."): if file.endswith("pdf"): PDF_arr.append(file) merger = PyPDF2.PdfFileMerger() for element in PDF_sez: merger.append(open(element, "rb")) with open(PDF_name, "wb") as fout: merger.write(fout) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T23:23:23.853", "Id": "525201", "Score": "1", "body": "Why do you keep saying \"map\"? This is called a \"directory\". Is there some use case context I'm missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T18:47:51.927", "Id": "525350", "Score": "0", "body": "map means folder in my native language, thats why. I didn't remember the english word." } ]
[ { "body": "<h1>List Comprehension</h1>\n\n<p><code>PDF_arr</code> can be made into a list with one line</p>\n\n<pre><code>PDF_arr = [file for file in os.listdir(\".\") if file.endswith(\"pdf\")]\n</code></pre>\n\n<h1>f-strings</h1>\n\n<p>Personally, I would use <code>f\"\"</code> when formatting variables into strings. It allows you to directly place variables without having to call the <code>.format()</code> function on them.</p>\n\n<pre><code>PDF_name = f\"{input('Name of your merged PDF: ')}.pdf\"\n</code></pre>\n\n<p>I also moved the <code>input</code> into the string, saving line count. It's also another quirk <code>f\"\"</code> has.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T23:18:40.483", "Id": "468914", "Score": "0", "body": "Downvoter, please explain why you downvoted so I may improve my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T02:22:45.547", "Id": "468927", "Score": "3", "body": "I didn't downvote, but I would really avoid anything more complex than variable references in an f-string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T10:46:08.003", "Id": "468959", "Score": "1", "body": "Isn't this just low hanging fruit. I could get more from a linter. Also pushing f-strings when they're really new is just obnoxious to people that have to support more than one version of Python." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T21:39:55.483", "Id": "239077", "ParentId": "239073", "Score": "-1" } }, { "body": "<p>This is a short script so it's probably ok to not have everything broken up into functions. In general my advice is more design choices for user input rather than anything very wrong with the python scripting style.</p>\n<ul>\n<li>As noted by Zachary Vance, what you call map should be named directory.</li>\n<li>A design choice may be to use command line arguments as input instead of repeatedly asking for user input. This will be easier to incorporate into other scripts.</li>\n<li>Another design choice is to use <code>initial_path</code> as the current working directory of the program instead of hardcoded. This gets rid of needing to change directory.</li>\n<li><code>file.endswith(&quot;pdf&quot;)</code> may match any kind of file ending in &quot;pdf&quot;, not necessarily &quot;.pdf&quot;, such as a file with no extension named &quot;pdf&quot;. Probably not an issue.</li>\n<li><code>PDF_sez</code> appears to be a typo for <code>PDF_arr</code>.</li>\n<li>Use <code>with</code> open or explicitly close file objects to prevent many file objects from remaining open. You already do this with writing the final PDF.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-10T09:38:21.320", "Id": "265907", "ParentId": "239073", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T19:48:39.777", "Id": "239073", "Score": "5", "Tags": [ "python", "pdf" ], "Title": "PDF merging program" }
239073
<p>I made some changes in my code from <a href="https://codereview.stackexchange.com/questions/238969/web-scraping-using-selenium-multiprocessing-instagrambot">the previous post</a>.</p> <p>The changes that I made:</p> <ul> <li>I put all the functions to the class</li> <li>All the global arrays I moved them to class too</li> <li>Created <code>PrivateException</code></li> <li>I made <code>property</code> for <code>search_name</code></li> </ul> <p>I could do it with a different approach but I decided to do it step by step.</p> <p>My idea was:</p> <p>To create class inheritance with parent class <code>instagramData</code> and there to create <code>classmethods</code> the functions <code>check_availability(cls, session, url)</code>, <code>login(cls, username, password, session, url)</code> and <code>fetch_url(cls, session, url)</code> which I can call to the child class <code>InstagramPv</code> and doing the rest (extraction links, download and save) but I stayed in the first plan.</p> <p>First approach</p> <pre><code> import requests import os import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from multiprocessing.dummy import Pool import urllib.parse import re from concurrent.futures import ThreadPoolExecutor chromedriver_path = None class PrivateException(Exception): pass class InstagramPV: def __init__(self, username, password, folder, search_name): """ :param username: username :param password: password :param folder: folder name :param search_name: the name what will search """ self.username = username self.password = password self.folder = folder self.http_base = requests.Session() self._search_name = search_name self.links = [] self.pictures = [] self.videos = [] self.url = "https://www.instagram.com/{name}/" if chromedriver_path is not None: self.driver = webdriver.Chrome(chromedriver_path) else: self.driver = webdriver.Chrome() @property def name(self): """To avoid any errors, with regex find the url and taking the name &lt;search_name&gt;""" find_name = "".join(re.findall(r"(?P&lt;url&gt;https?://[^\s]+)", self._search_name)) if find_name.startswith("https"): self._search_name = urllib.parse.urlparse(find_name).path.split("/")[1] return self._search_name else: return self._search_name def __enter__(self): return self def check_availability(self): search = self.http_base.get(self.url.format(name=self.name), params={"__a": 1}) search.raise_for_status() load_and_check = search.json() privacy = load_and_check.get("graphql").get("user").get("is_private") followed_by_viewer = load_and_check.get("graphql").get("user").get("followed_by_viewer") if privacy and not followed_by_viewer: raise PrivateException("[!] Account is private") def control(self): """ Create the folder name and raises an error if already exists """ if not os.path.exists(self.folder): os.mkdir(self.folder) else: raise FileExistsError("[*] Already Exists This Folder") def login(self): """Login To Instagram""" self.driver.get("https://www.instagram.com/accounts/login") time.sleep(3) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) submit = self.driver.find_element_by_tag_name('form') submit.submit() time.sleep(3) """Check For Invalid Credentials""" try: var_error = self.driver.find_element_by_class_name("eiCW-").text raise ValueError("[!] Invalid Credentials") except NoSuchElementException: pass try: """Close Notifications""" self.driver.find_element_by_xpath('//button[text()="Not Now"]').click() except NoSuchElementException: pass """Taking cookies""" cookies = self.driver.get_cookies() for cookie in cookies: c = {cookie["name"]: cookie["value"]} self.http_base.cookies.update(c) """Check for availability""" self.check_availability() self.driver.get(self.url.format(name=self.name)) return self.scroll_down() def _get_href(self): elements = self.driver.find_elements_by_xpath("//a[@href]") for elem in elements: urls = elem.get_attribute("href") if "p" in urls.split("/"): self.links.append(urls) def scroll_down(self): """Taking hrefs while scrolling down""" end_scroll = [] while True: self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) self._get_href() time.sleep(2) new_height = self.driver.execute_script("return document.body.scrollHeight") end_scroll.append(new_height) if end_scroll.count(end_scroll[-1]) &gt; 4: self.extraction_url() break def extraction_url(self): """Gathering Images and Videos Using ThreadPoolExecutor and pass to function &lt;fetch_url&gt; """ links = list(set(self.links)) print("[!] Ready for video - images".title()) print(f"[*] extracting {len(links)} posts , please wait...".title()) new_links = [urllib.parse.urljoin(link, "?__a=1") for link in links] with ThreadPoolExecutor(max_workers=8) as executor: [executor.submit(self.fetch_url, link) for link in new_links] def fetch_url(self, url): """ This function extracts images and videos :param url: Taking the url """ logging_page_id = self.http_base.get(url.split()[0]).json() try: """Taking Gallery Photos or Videos""" for log_pages in logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']: video = log_pages["node"]["is_video"] if video: video_url = log_pages["node"]["video_url"] self.videos.append(video_url) else: image = log_pages["node"]["display_url"] self.pictures.append(image) except KeyError: """Unique photo or Video""" image = logging_page_id['graphql']['shortcode_media']['display_url'] self.pictures.append(image) if logging_page_id['graphql']['shortcode_media']["is_video"]: videos = logging_page_id['graphql']['shortcode_media']["video_url"] self.videos.append(videos) def download_video(self, new_videos): """ Saving the content of video in the file """ number = new_videos[0] link = new_videos[1] with open(os.path.join(self.folder, f"Video{number}.mp4"), "wb") as f: content_of_video = InstagramPV.content_of_url(link, self.http_base) f.write(content_of_video) def images_download(self, new_pictures): """Saving the content of picture in the file""" number = new_pictures[0] link = new_pictures[1] with open(os.path.join(self.folder, f"Image{number}.jpg"), "wb") as f: content_of_picture = InstagramPV.content_of_url(link, self.http_base) f.write(content_of_picture) def downloading_video_images(self): """Using multiprocessing for Saving Images and Videos""" print("[*] ready for saving images and videos!".title()) picture_data = enumerate(list(set(self.pictures))) video_data = enumerate(list(set(self.videos))) pool = Pool(8) pool.map(self.images_download, picture_data) pool.map(self.download_video, video_data) print("[+] Done") def __exit__(self, exc_type, exc_val, exc_tb): self.http_base.close() self.driver.close() @staticmethod def content_of_url(url, req): data = req.get(url) return data.content def main(): USERNAME = "" PASSWORD = "" NAME = "" FOLDER = "" with InstagramPV(USERNAME, PASSWORD, FOLDER, NAME) as pv: pv.control() pv.login() pv.downloading_video_images() if __name__ == '__main__': main() </code></pre> <p>Second approach</p> <pre><code>chromedriver_path = None class PrivateException(Exception): pass class InstagramData: def __init__(self, search_name): """ :param search_name: The Profile that will search """ self._search_name = search_name self.links = [] self.videos = [] self.pictures = [] @property def name(self): """To avoid any errors, with regex find the url and taking the name &lt;search_name&gt;""" find_name = "".join(re.findall(r"(?P&lt;url&gt;https?://[^\s]+)", self._search_name)) if find_name.startswith("https"): self._search_name = urllib.parse.urlparse(find_name).path.split("/")[1] return self._search_name else: return self._search_name @classmethod def check_availability(cls, session, url): """ Check availability of the profile If its private and status code :param session: session &lt;self.http_base&gt; requests.session :param url: the url :return: """ search = session.get(url, params={"__a": 1}) search.raise_for_status() load_and_check = search.json() privacy = load_and_check.get("graphql").get("user").get("is_private") followed_by_viewer = load_and_check.get("graphql").get("user").get("followed_by_viewer") if privacy and not followed_by_viewer: raise PrivateException("[!] Account is private") @classmethod def login_and_scrape(cls, username, password, session, url): """ Login tO instagram, checking availability and taking links :param username: the username :param password: the password :param session: session &lt;self.http_base&gt; requests.session :param url: The URL :return: The links that we collect from scroll down """ if chromedriver_path is not None: driver = webdriver.Chrome(chromedriver_path) else: driver = webdriver.Chrome() driver.get("https://www.instagram.com/accounts/login") time.sleep(3) driver.find_element_by_name('username').send_keys(username) driver.find_element_by_name('password').send_keys(password) submit = driver.find_element_by_tag_name('form') submit.submit() time.sleep(8) """Check For Invalid Credentials""" try: var_error = driver.find_element_by_class_name("eiCW-").text raise ValueError("[!] Invalid Credentials") except NoSuchElementException: pass try: """Close Notifications""" driver.find_element_by_xpath('//button[text()="Not Now"]').click() except NoSuchElementException: pass """Getting cookies and pass it to session parameter""" cookies = driver.get_cookies() for cookie in cookies: c = {cookie["name"]: cookie["value"]} session.cookies.update(c) """Checking the availability""" InstagramData.check_availability(session, url) driver.get(url) """Scrolling down and taking the href""" new_links = [] end_scroll = [] while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) for href in cls.get_href(driver): new_links.append(href) time.sleep(2) new_height = driver.execute_script("return document.body.scrollHeight") end_scroll.append(new_height) if end_scroll.count(end_scroll[-1]) &gt; 4: driver.close() return new_links @staticmethod def get_href(driver): elements = driver.find_elements_by_xpath("//a[@href]") for elem in elements: urls = elem.get_attribute("href") if "p" in urls.split("/"): yield urls def fetch_url(self, session, url): """ Collect the images, videos and appending on self.pictures, self.videos :param session: Session of &lt;self.http_base&gt; :param url: url :return: """ logging_page_id = session.get(url.split()[0]).json() try: """Taking Gallery Photos or Videos""" for log_pages in logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']: video = log_pages["node"]["is_video"] if video: video_url = log_pages["node"]["video_url"] self.videos.append(video_url) else: image = log_pages["node"]["display_url"] self.pictures.append(image) except KeyError: """Unique photo or Video""" image = logging_page_id['graphql']['shortcode_media']['display_url'] self.pictures.append(image) if logging_page_id['graphql']['shortcode_media']["is_video"]: video = logging_page_id['graphql']['shortcode_media']["video_url"] self.videos.append(video) class InstagramPV(InstagramData): def __init__(self, username, password, search_name, folder): super(InstagramPV, self).__init__(search_name) self.username = username self.password = password self.folder = folder self.http_base = requests.Session() self.url = "https://www.instagram.com/{name}/" def __enter__(self): return self def control(self): """ Create the folder name and raises an error if already exists """ if not os.path.exists(self.folder): os.mkdir(self.folder) else: raise FileExistsError("[*] Already Exists This Folder") def extraction_url(self): """Gathering Images and Videos Using ThreadPoolExecutor """ links = list( set(InstagramData.login_and_scrape(self.username, self.password, self.http_base, self.url.format(name=self.name)))) print("[!] Ready for video - images".title()) print(f"[*] extracting {len(links)} posts , please wait...".title()) new_links = [urllib.parse.urljoin(link, "?__a=1") for link in links] with ThreadPoolExecutor(max_workers=8) as executor: [executor.submit(self.fetch_url(self.http_base, link)) for link in new_links] def download_video(self, new_videos): """ Saving the content of video in the file """ number = new_videos[0] link = new_videos[1] with open(os.path.join(self.folder, f"Video{number}.mp4"), "wb") as f: content_of_video = InstagramPV.content_of_url(link, self.http_base) f.write(content_of_video) def images_download(self, new_pictures): """Saving the content of picture in the file""" number = new_pictures[0] link = new_pictures[1] with open(os.path.join(self.folder, f"Image{number}.jpg"), "wb") as f: content_of_picture = InstagramPV.content_of_url(link, self.http_base) f.write(content_of_picture) def downloading_video_images(self): self.control() self.extraction_url() """Using multiprocessing for Saving Images and Videos""" print("[*] ready for saving images and videos!".title()) picture_data = enumerate(list(set(self.pictures))) video_data = enumerate(list(set(self.videos))) pool = Pool(8) pool.map(self.images_download, picture_data) pool.map(self.download_video, video_data) print("[+] Done") @staticmethod def content_of_url(url, req): data = req.get(url) return data.content def __exit__(self, exc_type, exc_val, exc_tb): self.http_base.close() def main(): USERNAME = "" PASSWORD = "" NAME = "" FOLDER = "" with InstagramPV(USERNAME, PASSWORD, NAME, FOLDER) as pv: pv.downloading_video_images() if __name__ == '__main__': main() </code></pre> <p>My previous posts:</p> <ol> <li><p><a href="https://codereview.stackexchange.com/questions/238713/instagram-scraper-posts-videos-and-photos]">Instagram scraper Posts (Videos and Photos)</a></p></li> <li><p><a href="https://codereview.stackexchange.com/questions/238902/scraping-instagram-with-selenium-extract-urls-download-posts">Scraping Instagram with selenium, extract URLs, download posts</a></p></li> <li><p><a href="https://codereview.stackexchange.com/questions/238969/web-scraping-using-selenium-multiprocessing-instagrambot">Web scraping using selenium, multiprocessing, InstagramBot</a></p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T18:39:04.223", "Id": "468999", "Score": "0", "body": "I realize that your earlier posts probably contain this, but a short paragraph on what the code does might be helpful. You might also want to delete one of the tags and add the comparative review tag." } ]
[ { "body": "<h2>Type hints</h2>\n\n<pre><code>def __init__(self, username, password, folder, search_name):\n</code></pre>\n\n<p>can (probably) be</p>\n\n<pre><code>def __init__(self, username: str, password: str, folder: Path, search_name: str):\n</code></pre>\n\n<p>Also, since these lists are initialized without a direct reference to the args, they should be type-declared:</p>\n\n<pre><code> self.links: List[str] = []\n self.pictures: List[str] = []\n self.videos: List[str] = []\n</code></pre>\n\n<h2>Paths</h2>\n\n<p>Note that I suggest the use of <code>Path</code>. Read about it here:</p>\n\n<p><a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/pathlib.html</a></p>\n\n<p>Then later on, you can use it like so:</p>\n\n<pre><code> self.folder.mkdir(exist_ok=True)\n</code></pre>\n\n<p>One line, no existence checks necessary. Also, this:</p>\n\n<pre><code>os.path.join(self.folder, f\"Image{number}.jpg\"\n</code></pre>\n\n<p>can be easier:</p>\n\n<pre><code>self.folder / f'Image{number}.jpg'\n</code></pre>\n\n<h2>Combined cookie update</h2>\n\n<p>I think that</p>\n\n<pre><code> \"\"\"Taking cookies\"\"\"\n cookies = self.driver.get_cookies()\n for cookie in cookies:\n c = {cookie[\"name\"]: cookie[\"value\"]}\n self.http_base.cookies.update(c)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code># Taking cookies\ncookies = {\n cookie['name']: cookie['value']\n for cookie in self.driver.get_cookies()\n}\nself.http_base.cookies.update(cookies)\n</code></pre>\n\n<h2>Quote style</h2>\n\n<p>... is inconsistent in places like this:</p>\n\n<pre><code> if logging_page_id['graphql']['shortcode_media'][\"is_video\"]:\n</code></pre>\n\n<p>So pick one or the other and stick with it.</p>\n\n<h2>Use a generator</h2>\n\n<p><code>scroll_down</code> can become a generator and gain some efficiency:</p>\n\n<ul>\n<li>Use a <code>Counter</code> class instance rather than calling <code>end_scroll.count()</code>, which is quite inefficient.</li>\n<li>Do not maintain an <code>end_scroll</code> list. Rather than appending, <code>yield new_height</code>, which makes the function a generator.</li>\n</ul>\n\n<h2>Nomenclature</h2>\n\n<p><code>extraction_url</code> sounds like a noun (i.e. it gets some data for you). That's not actually what it does. Instead, it seems like it submits some links. Call it <code>submit</code> or <code>submit_links</code> (this is a verb, and makes it clear that it's an \"action\", not a \"getter\").</p>\n\n<h2>Magic numbers</h2>\n\n<p>In this:</p>\n\n<pre><code>if end_scroll.count(end_scroll[-1]) &gt; 4:\n</code></pre>\n\n<p>What is 4? This should be saved to a named constant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T21:33:10.877", "Id": "469290", "Score": "0", "body": "I have two questions. 1) Can i use type hints for every function in the class? 2) In quote style , you mean to put in variable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T22:31:09.583", "Id": "469298", "Score": "0", "body": "_Can i use type hints for every function in the class?_ - Yes, you should :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T22:31:29.903", "Id": "469299", "Score": "1", "body": "_In quote style , you mean to put in variable?_ No, as in choose single or double quotes only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-23T15:27:00.960", "Id": "469411", "Score": "0", "body": "For the function `scroll_down` i didn't make it a generator, instead i tested the expression (condition) the number of posts and the `self.links`. Should i make it a generator anyway?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-28T01:41:46.830", "Id": "469840", "Score": "0", "body": "my new [question](https://codereview.stackexchange.com/questions/239539/instagram-scraping-using-selenium) :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T16:00:48.503", "Id": "239234", "ParentId": "239074", "Score": "1" } } ]
{ "AcceptedAnswerId": "239234", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T20:01:20.520", "Id": "239074", "Score": "1", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "instagram" ], "Title": "Instagram Bot, selenium, web scraping" }
239074
<p>I have the following class structure:</p> <p><code>MyAttribute.cs</code></p> <pre><code>public sealed class MyAttribute : Attribute { public MyAttribute(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } Name = name; } public string Name { get; } } </code></pre> <p><code>Matrix.cs</code></p> <pre><code>public class Matrix { [MyAttribute("awesome_name")] public string AwesomeName { get; set; } } </code></pre> <p>And we make an method to "extract" the value defined on <code>name</code> of <code>MyAttribute</code>:</p> <p><code>AttributeExtensions.cs</code></p> <pre><code>public static class AttributeExtensions { public static string GetMyAttributeNameOfProperty&lt;TClass&gt;(Expression&lt;Func&lt;TClass, object&gt;&gt; expression) { if (expression.Body is MemberExpression memberExpression) { var propertyInfo = (PropertyInfo)memberExpression.Member; var hasMyAttribute = propertyInfo.IsDefined(typeof(MyAttribute), false); if (hasMyAttribute) { return propertyInfo.GetCustomAttribute&lt;MyAttribute&gt;().Name; } } return default; } } </code></pre> <p>Finally, we call this way: </p> <pre><code>AttributeExtensions.GetMyAttributeNameOfProperty&lt;Matrix&gt;(exp =&gt; exp.AwesomeName) </code></pre> <p>This call, returns: <code>"awesome_name"</code></p> <p><strong>We have some doubts:</strong></p> <ol> <li><p>Exists an more "clean" way to pass the property of <code>&lt;TClass&gt;(exp.AwesomeName)</code> to this extension method?</p></li> <li><p>We really need of <code>Expression&lt;&gt;</code>? It's possible to make this only with <code>Func&lt;TClass, object&gt;</code>? </p></li> </ol> <p><strong>Like:</strong></p> <pre><code>GetMyAttributeNameOfProperty&lt;TClass&gt;(Func&lt;TClass, object&gt; expression) </code></pre> <p>Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T07:40:30.507", "Id": "468942", "Score": "0", "body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T14:46:37.107", "Id": "468976", "Score": "1", "body": "@Mast this is a concrete code. How use this, has been explained on question: \n\n\"Finally, we call this way:\n\n`AttributeExtensions.GetMyAttributeNameOfProperty<Matrix>(exp => exp.AwesomeName)\"`\n\nPlease, don't vote down! This is an solution and fully works!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T18:44:09.870", "Id": "469276", "Score": "2", "body": "While in the general case, editing a question after receiving an answer would be disallowed because it usually invalidates any reviews given, the changes applied here are okay, because they are not mentioned in the answer. Please keep in mind that editing questions after receiving answers is usually not okay. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-22T03:34:24.177", "Id": "469325", "Score": "0", "body": "@Vogel612 It's exactly the point! I know that rule! It was just a typo fixed that does not affect the scope of the review." } ]
[ { "body": "<p>I'd suggest:</p>\n\n<pre><code>public static class AttributeExtensions\n{\n public static string GetMyAttributeNameOfProperty&lt;TClass&gt;(string propertyName)\n {\n var propertyInfo = typeof(TClass).GetProperty(propertyName);\n return propertyInfo?.GetCustomAttribute&lt;MyAttribute&gt;()?.Name ?? default;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var awesome = AttributeExtensions.GetMyAttributeNameOfProperty&lt;Matrix&gt;(nameof(Matrix.AwesomeName));\nConsole.WriteLine(awesome);\n</code></pre>\n\n<p><strong>Note</strong>: The above isn't an extension method. The below code is.</p>\n\n<pre><code>public static class AttributeExtensions\n{\n public static string GetMyAttributeNameOfProperty&lt;TType&gt;(this TType me, string propertyName) where TType : Type\n {\n var propertyInfo = me.GetProperty(propertyName);\n return propertyInfo?.GetCustomAttribute&lt;MyAttribute&gt;()?.Name ?? default;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var awesome = typeof(Matrix).GetMyAttributeNameOfProperty(nameof(Matrix.AwesomeName));\nConsole.WriteLine(awesome);\n</code></pre>\n\n<p>Both output:</p>\n\n<blockquote>\n <p>awesome_name</p>\n</blockquote>\n\n<p>Benefits:</p>\n\n<ul>\n<li>Does not use an <code>Expression</code> or even the namespace\n<code>System.Linq.Expressions</code> </li>\n<li>Won't throw an exception (returns <code>null</code> if property or attribute doesn't exist)</li>\n<li>Using <code>nameof</code> makes refactoring safe in the event you rename class properties</li>\n<li>Does not use <code>Func&lt;TClass, object&gt;</code> or similar</li>\n<li>Does not require an instance of <code>Matrix</code> (or any other type since it's generic) </li>\n</ul>\n\n<p>Either way works and is really a matter of preference. There are pros and cons to using extension methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T19:08:43.093", "Id": "469000", "Score": "0", "body": "Thanks @Zer0! We make this on the past, we try to simplify our call so we don't have to use `typeof(Matrix)` and `nameof(Matrix.AwesomeName)` this make it more verbose... +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T19:33:00.790", "Id": "469001", "Score": "2", "body": "@Igor Using `Func<TClass, Object>` without `Expression` is not going to help since you'll get the _value_ of `AwesomeName` and we only care about the _type_. I could write a method with the signature `Func<TClass, Type>` and calling it with `exp => exp.AwesomeName.GetType()` if you want. But I don't find that any less verbose than the above suggestions. If you really want to avoid `typeof`, `nameof` and `GetType()` I'd stick with the method signature you already have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-19T15:40:54.237", "Id": "469096", "Score": "0", "body": "This is the way... Cheers!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T23:05:07.103", "Id": "469302", "Score": "1", "body": "@Igor Glad to hear it. Please mark as answer if you think this solved your question. I can edit in the `Func<TClass, Type>` solution if you'd like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-22T03:39:03.330", "Id": "469326", "Score": "0", "body": "Hey @Zer0, when I comment: \"This is the way\" I meant this part: \" I'd stick with the method signature you already have.\"" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T18:02:28.740", "Id": "239111", "ParentId": "239082", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T00:03:20.487", "Id": "239082", "Score": "2", "Tags": [ "c#", "reflection", "extension-methods" ], "Title": "Pass class property as parameter to extension method" }
239082