body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm trying to build a nav, but the way I currently have the data setup I'm having to map within a map with a map to get all of my data out - I have a feeling that this is a poor way of doing something and there may be a better solution?</p> <p><a href="https://codesandbox.io/s/gifted-clarke-nppvw?file=/src/App.js" rel="nofollow noreferrer">My code can also be found in a codesandbox here</a></p> <p>Both the data and jsx are up for debate and I'm more than happy to modify either or both for a better solution.</p> <p>My JSX:</p> <pre><code> &lt;div className=&quot;App&quot;&gt; &lt;nav&gt; {/* Top Level Nav Items */} {nav.map((item) =&gt; ( &lt;a href={item.url} key={item.category}&gt; {item.category} &lt;/a&gt; ))} &lt;/nav&gt; {/* Nav Sub-Categories */} &lt;div className=&quot;subCategories&quot;&gt; {nav.map((item) =&gt; ( &lt;div className=&quot;subCategory&quot;&gt; &lt;img src={item.img} /&gt; {item.subCatergories.map((subCategory) =&gt; ( &lt;&gt; &lt;h3&gt;{subCategory.title}&lt;/h3&gt; {subCategory.links.map((link) =&gt; ( &lt;a href={link.url}&gt;{link.name}&lt;/a&gt; ))} &lt;/&gt; ))} &lt;/div&gt; ))} &lt;/div&gt; &lt;/div&gt; </code></pre> <p>My data:</p> <pre><code>const nav = [ { category: &quot;LINK NAME&quot;, url: &quot;/link&quot;, img: &quot;https://via.placeholder.com/100/?text=Image&quot;, subCatergories: [ { title: &quot;Sub Category 1&quot;, links: [ { name: &quot;link 1&quot;, url: &quot;/1&quot; }, { name: &quot;link 2&quot;, url: &quot;/2&quot; }, { name: &quot;link 3&quot;, url: &quot;/3&quot; }, { name: &quot;link 4&quot;, url: &quot;/4&quot; }, { name: &quot;link 5&quot;, url: &quot;/5&quot; }, { name: &quot;link 6&quot;, url: &quot;/6&quot; }, { name: &quot;link 7&quot;, url: &quot;/7&quot; }, { name: &quot;link 8&quot;, url: &quot;/8&quot; }, { name: &quot;link 8&quot;, url: &quot;/9&quot; } ] }, { title: &quot;Sub Category 2&quot;, links: [ { name: &quot;link 1&quot;, url: &quot;/1&quot; }, { name: &quot;link 2&quot;, url: &quot;/2&quot; }, { name: &quot;link 3&quot;, url: &quot;/3&quot; }, { name: &quot;link 4&quot;, url: &quot;/4&quot; }, { name: &quot;link 5&quot;, url: &quot;/5&quot; }, { name: &quot;link 6&quot;, url: &quot;/6&quot; }, { name: &quot;link 7&quot;, url: &quot;/7&quot; }, { name: &quot;link 8&quot;, url: &quot;/8&quot; }, { name: &quot;link 8&quot;, url: &quot;/9&quot; } ] }, { title: &quot;Sub Category 3&quot;, links: [ { name: &quot;link 1&quot;, url: &quot;/1&quot; }, { name: &quot;link 2&quot;, url: &quot;/2&quot; }, { name: &quot;link 3&quot;, url: &quot;/3&quot; }, { name: &quot;link 4&quot;, url: &quot;/4&quot; }, { name: &quot;link 5&quot;, url: &quot;/5&quot; }, { name: &quot;link 6&quot;, url: &quot;/6&quot; }, { name: &quot;link 7&quot;, url: &quot;/7&quot; }, { name: &quot;link 8&quot;, url: &quot;/8&quot; }, { name: &quot;link 8&quot;, url: &quot;/9&quot; } ] } ] }, { category: &quot;LINK NAME 2&quot;, url: &quot;/link2&quot;, img: &quot;https://via.placeholder.com/100/?text=Image&quot;, subCatergories: [ { title: &quot;Sub Category 1&quot;, links: [ { name: &quot;link 1&quot;, url: &quot;/1&quot; }, { name: &quot;link 2&quot;, url: &quot;/2&quot; }, { name: &quot;link 3&quot;, url: &quot;/3&quot; }, { name: &quot;link 4&quot;, url: &quot;/4&quot; }, { name: &quot;link 5&quot;, url: &quot;/5&quot; }, { name: &quot;link 6&quot;, url: &quot;/6&quot; }, { name: &quot;link 7&quot;, url: &quot;/7&quot; }, { name: &quot;link 8&quot;, url: &quot;/8&quot; }, { name: &quot;link 8&quot;, url: &quot;/9&quot; } ] }, { title: &quot;Sub Category 2&quot;, links: [ { name: &quot;link 1&quot;, url: &quot;/1&quot; }, { name: &quot;link 2&quot;, url: &quot;/2&quot; }, { name: &quot;link 3&quot;, url: &quot;/3&quot; }, { name: &quot;link 4&quot;, url: &quot;/4&quot; }, { name: &quot;link 5&quot;, url: &quot;/5&quot; }, { name: &quot;link 6&quot;, url: &quot;/6&quot; }, { name: &quot;link 7&quot;, url: &quot;/7&quot; }, { name: &quot;link 8&quot;, url: &quot;/8&quot; }, { name: &quot;link 8&quot;, url: &quot;/9&quot; } ] }, { title: &quot;Sub Category 3&quot;, links: [ { name: &quot;link 1&quot;, url: &quot;/1&quot; }, { name: &quot;link 2&quot;, url: &quot;/2&quot; }, { name: &quot;link 3&quot;, url: &quot;/3&quot; }, { name: &quot;link 4&quot;, url: &quot;/4&quot; }, { name: &quot;link 5&quot;, url: &quot;/5&quot; }, { name: &quot;link 6&quot;, url: &quot;/6&quot; }, { name: &quot;link 7&quot;, url: &quot;/7&quot; }, { name: &quot;link 8&quot;, url: &quot;/8&quot; }, { name: &quot;link 8&quot;, url: &quot;/9&quot; } ] } ] } ]; </code></pre> <p>Any help or guidance here would be great, thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T15:42:32.317", "Id": "496792", "Score": "1", "body": "That looks like a perfectly reasonable implementation to me. Nothing stands out as being improvable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T15:48:24.680", "Id": "496795", "Score": "0", "body": "@CertainPerformance Thanks for that! I was told once it wasn't great to loop within loops and it's always stuck with me! Right or wrong! But I'll stick with this if it's alright! Thanks a lot!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T17:58:02.233", "Id": "496818", "Score": "1", "body": "Nested loops are a problem when you need an *algorithm* and the problem is solvable by iterating over the data less frequently. But here, it's not really an algorithm, just rendering data, and, eg, given `n` total `links` items, there's no avoiding iterating `n` times." } ]
[ { "body": "<p>The use of nested maps is a fine solution, I just have a few suggestions.</p>\n<p>I would rename some keys of your object to make them consistent:</p>\n<pre><code>const nav = [\n {\n name: &quot;LINK NAME&quot;,\n url: &quot;/link&quot;,\n img: &quot;https://via.placeholder.com/100/?text=Image&quot;,\n categories: [\n {\n name: &quot;Sub Category 1&quot;,\n items: [\n {name: &quot;link 1&quot;, url: &quot;/1&quot;},\n ]\n },\n {\n name: &quot;Sub Category 2&quot;,\n items: [\n {name: &quot;link 1&quot;, url: &quot;/1&quot;},\n {name: &quot;link 2&quot;, url: &quot;/2&quot;},\n ]\n },\n {\n name: &quot;Sub Category 3&quot;,\n items: [\n {name: &quot;link 1&quot;, url: &quot;/1&quot;},\n {name: &quot;link 2&quot;, url: &quot;/2&quot;},\n {name: &quot;link 8&quot;, url: &quot;/9&quot;}\n ]\n }\n ]\n },\n]\n</code></pre>\n<p>I suggest using object destruction in the parameter definition to make the code more concise by avoiding dot notation.</p>\n<p>Also, I would create a separate component for subcategories to make the code for navigation simpler to read.</p>\n<p>Here is the code for React components:</p>\n<pre><code>export default function App() {\n return (\n &lt;div className=&quot;App&quot;&gt;\n &lt;nav&gt;\n {/* Top Level Nav Items */}\n {nav.map(({ name, url }) =&gt; (\n &lt;a href={url} key={name}&gt;{name}&lt;/a&gt;\n ))}\n &lt;/nav&gt;\n\n {/* Nav Sub-Categories */}\n &lt;div className=&quot;subCategories&quot;&gt;\n {nav.map(({ categories, img }) =&gt; (\n &lt;SubCategory categories={categories} img={img} /&gt;\n ))}\n &lt;/div&gt;\n &lt;/div&gt;\n );\n}\n\nfunction SubCategory({ categories, img }) {\n return (\n &lt;div className=&quot;subCategory&quot;&gt;\n &lt;img src={img} /&gt;\n {categories.map(({ name, items}) =&gt; (\n &lt;&gt;\n &lt;h3&gt;{name}&lt;/h3&gt;\n {items.map(({ name, url }) =&gt; (\n &lt;a href={url}&gt;{name}&lt;/a&gt;\n ))}\n &lt;/&gt;\n ))}\n &lt;/div&gt;\n )\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:40:40.990", "Id": "252423", "ParentId": "252189", "Score": "1" } }, { "body": "<p>Although there is nothing wrong with nested maps you are correct to seek a better solution.</p>\n<p>Controls nest or compose much cleaner than maps. Allowing controls to have at most one map is a very good practice.<br />\n<a href=\"https://codesandbox.io/s/code-review-nav-8c7qt?file=/src/NoNest/NoNestApp.js:128-696\" rel=\"nofollow noreferrer\">CodeSandbox</a></p>\n<pre class=\"lang-javascript prettyprint-override\"><code>export default function LeafLinkList({ links }) {\n return links.map(({name, url}) =&gt; &lt;a href={url} key={url}&gt;{name}&lt;/a&gt;);\n}\n\nexport default function SubCategory({ title, links }) {\n return (\n &lt;Fragment&gt;\n &lt;h3&gt;{title}&lt;/h3&gt;\n &lt;LeafLinkList links={links} /&gt;\n &lt;/Fragment&gt;\n );\n}\n\nexport default function SubCategoryList({ item }) {\n const { subCatergories } = item || {};\n\n return subCatergories.map(({ title, links }) =&gt; (\n &lt;SubCategory key={title} title={title} links={links} /&gt;\n ));\n}\n\nexport default function App() {\n return (\n &lt;div className=&quot;App&quot;&gt;\n &lt;nav&gt;\n {/* Top Level Nav Items */}\n {nav.map((item) =&gt; (\n &lt;a href={item.url} key={item.category}&gt;\n {item.category}\n &lt;/a&gt;\n ))}\n &lt;/nav&gt;\n\n {/* Nav Sub-Categories */}\n &lt;div className=&quot;subCategories&quot;&gt;\n {nav.map((item) =&gt; (\n &lt;div className=&quot;subCategory&quot; key={item.url}&gt;\n &lt;img src={item.img} alt=&quot;box&quot; /&gt;\n &lt;SubCategoryList item={item} /&gt;\n &lt;/div&gt;\n ))}\n &lt;/div&gt;\n &lt;/div&gt;\n );\n}\n</code></pre>\n<p>One of the realities of modern development is constantly changing requirements. Nested or composed controls handles change better. Don't take my word for it. Consider the two solutions and now add the requirement that each Sub Category is collapsible.</p>\n<p>How long did it take you to find Sub Category?</p>\n<p>Where do you add state?</p>\n<p>Here is the new sub Category to handle the new requirement.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>export default function SubCategory({ title, links }) {\n const [isOpen, setOpen] = useState(false);\n const indicator = isOpen ? &quot;-&quot; : &quot;+&quot;;\n const header = `${indicator} ${title}`;\n const handleClick = () =&gt; {\n setOpen(toggleOpen);\n };\n return (\n &lt;Fragment&gt;\n &lt;h3 onClick={handleClick}&gt;{header}&lt;/h3&gt;\n {isOpen &amp;&amp; &lt;LeafLinkList links={links} /&gt;}\n &lt;/Fragment&gt;\n );\n}\n\n</code></pre>\n<p><a href=\"https://codesandbox.io/s/code-review-state-nav-6w1b1?file=/src/NoNest/SubCategory.js:184-571\" rel=\"nofollow noreferrer\">CodeSandbox - add state</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T18:13:43.067", "Id": "252610", "ParentId": "252189", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T15:20:16.593", "Id": "252189", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "react.js" ], "Title": "A better solution for nested maps" }
252189
<p>I have the following code in JS (using last ES2020), the current code check if the type is <code>'asporto'</code> or <code>'takeaway'</code> and adding to current date hours from a setup fo type <code>'takeaway'</code> or <code>'asporto'</code> and if another setup called <code>limiteOreTakeaway/Asporto</code> is <code>!== '00:00:00'</code> I have to check if the current time is greater than the <code>limiteOreTakeaway/Asporto</code>, so I'm splitting the string <code>limiteOreTakeaway/Asporto</code> to Hours and Minutes and making my checks if the current date is &gt; that <code>limiteOreTakeaway/Asporto</code> I'm adding to curDate the hours from setup + 24hours.</p> <p>My code looks like this:</p> <pre><code>const curDate = new Date(); if (this.carrello.tipo === 'asporto') { if (this.negozioSetup.limiteOreAsporto !== '00:00:00') { // controllo se l'orario limite è impostato (orariolimite != 00:00) const ore = parseInt( this.negozioSetup.limiteOreAsporto.split(':')[0], 10 ); const minuti = parseInt( this.negozioSetup.limiteOreAsporto.split(':')[1], 10 ); // controllo se l'ora di adesso ha superato l'orario limite if (curDate.getHours() &gt; ore) { curDate.setHours( curDate.getHours() + this.negozioSetup.oreMinimeAsporto + 24 ); // se l'ora corrente è uguale controllo se i minuti limite hanno superato il limite }else if (curDate.getHours() === ore &amp;&amp; curDate.getMinutes() &gt; minuti) { // se l'orario corrente è maggiore di quello limite aggiungo 24 ore alla data corrente curDate.setHours( curDate.getHours() + this.negozioSetup.oreMinimeAsporto + 24 ); } } else { // orario limite disabilitato proseguo con l'aggiunta delle ore minime tra gli ordini curDate.setHours( curDate.getHours() + this.negozioSetup.oreMinimeAsporto ); } } else if (this.carrello.tipo === 'takeaway') { if (this.negozioSetup.limiteOreTakeaway !== '00:00:00') { const ore = parseInt( this.negozioSetup.limiteOreTakeaway.split(':')[0], 10 ); const minuti = parseInt( this.negozioSetup.limiteOreTakeaway.split(':')[1], 10 ); if (curDate.getHours() &gt; ore) { curDate.setHours( curDate.getHours() + this.negozioSetup.oreMinimeTakeaway + 24 ); }else if (curDate.getHours() === ore &amp;&amp; curDate.getMinutes() &gt; minuti) { curDate.setHours( curDate.getHours() + this.negozioSetup.oreMinimeTakeaway + 24 ); } } else { curDate.setHours( curDate.getHours() + this.negozioSetup.oreMinimeTakeaway ); } } </code></pre> <p>I would like to simplify it. If it's possible, optimize it by using the last ES2020 available tools.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T15:44:12.033", "Id": "496794", "Score": "2", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T17:27:54.853", "Id": "496809", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. For now, considering the answer has already followed your edit, nothing needs to be done. But please don't do it again. It can get messy really fast." } ]
[ { "body": "<p><strong>Use functions instead of <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">repeating yourself</a></strong> The only difference between the <code>tipo === 'asporto'</code> branch and the <code>tipo === 'takeaway'</code> branch is the property name that gets passed into <code>setHours</code>: either <code>.oreMinimeAsporto</code> or <code>.oreMinimeTakeaway</code>. Create a function that takes that value as a parameter, then call it with either <code>.oreMinimeAsporto</code> or <code>.oreMinimeTakeaway</code> instead. That will about halve the size of your code.</p>\n<pre><code>const curDate = new Date();\nconst { tipo } = this.carrello;\nif (tipo === 'asporto' || tipo === 'takeaway') {\n const casedProp = tipo[0].toUpperCase() + tipo.slice(1);\n changeDate(\n currDate,\n this.negozioSetup['oreMinime' + casedProp],\n this.negozioSetup['limiteOre' + casedProp],\n );\n}\n</code></pre>\n<p><strong>Split only once and destructure</strong> to grab the <code>ore</code> and <code>minti</code> values at once. You can also use <code>Number</code> instead of <code>parseInt(str, 10)</code>, and use <code>.map</code> to apply the transformation to both elements at once:</p>\n<pre><code>const [ore, minuti] = this.negozioSetup.limiteOreAsporto.split(':').map(Number);\n</code></pre>\n<p><strong>Call functions <em>once</em> rather than multiple times</strong> when possible - you don't need to call <code>getHours</code> every time, better to call it once and store the result in a variable.</p>\n<pre><code>const currHours = curDate.getHours();\nconst currHoursWithOffset = currHours + oreMinime;\n</code></pre>\n<p><strong>Return early to avoid indentation hell</strong> - reading lots of <code>{}</code> blocks can make code more confusing to read than it needs to be. In the case of <code>00:00:00</code>, consider running the one line that's needed and then returning, rather than having a large <code>if</code>/<code>else</code>.</p>\n<p>The branches of <code>currHours &gt; ore</code> and <code>curDate.getHours() === ore &amp;&amp; curDate.getMinutes() &gt; minuti</code> also contain the same logic inside the branches, so combine them into one <code>if</code> statement:</p>\n<pre><code>const changeDate = (date, oreMinime, limiteOre) =&gt; {\n const currHours = curDate.getHours();\n const currHoursWithOffset = currHours + oreMinime;\n if (limiteOre === '00:00:00') {\n curDate.setHours(currHoursWithOffset);\n return;\n }\n const [ore, minuti] = limiteOre.split(':').map(Number);\n if (currHours &gt; ore || currHours === ore &amp;&amp; curDate.getMinutes() &gt; minuti) {\n curDate.setHours(\n currHours + oreMinime + 24\n );\n }\n};\nconst curDate = new Date();\nconst { tipo } = this.carrello;\nif (tipo === 'asporto' || tipo === 'takeaway') {\n const casedProp = tipo.slice(1).toUpperCase() + tipo.slice(1);\n changeDate(currDate, this.negozioSetup['oreMinime' + casedProp]);\n}\n</code></pre>\n<p>You could put the values into variables first if you think the combined statement is difficult to read (I'll leave that to you, I don't understand the language) - eg</p>\n<pre><code>const cond1 = currHours &gt; ore;\nconst cond2 = currHours === ore &amp;&amp; curDate.getMinutes() &gt; minuti;\nif (cond1 || cond2) {\n // ...\n}\n</code></pre>\n<p><strong>Alternative to multiple separate properties</strong> On a broader scale, having to hard-code the correlation between <code>this.carrello.tipo</code> and the <code>this.negozioSetup.oreMinime-</code> property is a bit odd. If possible, consider rearranging your data so that the two <code>oreMinime</code> and <code>limiteOre</code> values are in an <em>object</em> instead of being two separate properties. Then you just need to use bracket notation to look up the value on the object:</p>\n<pre><code>ore: {\n asporto: { minime: &lt;value&gt;, takeaway: &lt;value&gt; },\n takeaway: { minime: &lt;value&gt;, takeaway: &lt;value&gt; },\n}\n</code></pre>\n<p>Then you can:</p>\n<pre><code>changeDate(currDate, this.negozioSetup.ore[tipo]);\n</code></pre>\n<p>and change <code>changeDate</code>'s parameters as needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T16:59:01.087", "Id": "496804", "Score": "0", "body": "There was a mistake in my code, the second ELSE uses limiteOreTakeaway instead of setting the same limiteOreAsporto" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T17:26:39.220", "Id": "496808", "Score": "1", "body": "Ok, see edit - you can do the same sort of thing as before, pass a parameter to DRY" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T16:09:56.263", "Id": "252193", "ParentId": "252190", "Score": "3" } } ]
{ "AcceptedAnswerId": "252193", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T15:35:30.140", "Id": "252190", "Score": "1", "Tags": [ "javascript", "performance", "typescript" ], "Title": "How can i simplify the following If code?" }
252190
<p>I previously asked how can I simplify a validation process:</p> <p><a href="https://codereview.stackexchange.com/questions/244341/how-can-i-simplify-this-jquery-validation-process">How can I simplify this JQuery validation process?</a></p> <p>But in hindsight, what I really meant to ask was how can I turn that process into a reusable function.</p> <p>I'm going through some old code that I wrote, and I am trying to clean it up so there's not a lot of redundant code.</p> <p>I have many <code>onClick</code> events that look like this:</p> <pre><code>$('#addSubmit').on('click', function(){ var addcriteria = { addcity: $('#addcity').val(), addregion: $('#addregion').val(), addloctype: $('#addloctype').val(), // several more values } if(addcriteria.addcity == &quot;&quot; || addcriteria.addcity == null){ $('#errorModal').modal('show'); $('.message').text('You must enter a City.'); $('#errorModal').on('hidden.bs.modal', function(){ document.forms[&quot;addEquipForm&quot;].addcriteria.addcity.focus(); }); return false; } if(addcriteria.addregion == &quot;&quot;){ $('#errorModal').modal('show'); $('.message').text('You must select a Region.'); $('#errorModal').on('hidden.bs.modal', function(){ document.forms[&quot;addEquipForm&quot;].addcriteria.addregion.focus(); }); return false; } // several more checks else{ $.post('api/updateEquip.php', {addcriteria:addcriteria}, function(data){ if(data == &quot;Success&quot;){ $('#successModal').modal('show'); $('.message').text('New Equipment has been added.'); $('#successModal').on('hidden.bs.modal', function(){ location.reload(); }); } else{ $('#errorModal').modal('show'); $('.message').text('The Equipment could not be added.'); return false; } }); } }); </code></pre> <p>As stated, I have many onClick events that look similar to the above. I want to get better at creating custom functions, and I think this would be a good start.</p> <p>This was my attempt at creating a custom reusable function for the above code...</p> <p>I started by creating the function:</p> <pre><code>function criteriaCheck(checkCriteria){ if(checkCriteria == &quot;&quot;){ $('#errorModal').modal('show'); $('.message').text('Error message of some sort.'); $('#errorModal').on('hidden.bs.modal', function(){ document.forms[&quot;addEquipForm&quot;].checkCriteria.focus(); }); return false; } else{ // not sure what to return here // but I can console log a success message console.log('Success'); } } </code></pre> <p>Then, inside my <code>onClick</code> event, I can call the function and pass the value into the function:</p> <pre><code>var checkCriteria = ''; criteriaCheck(checkCriteria = addcriteria.addcity); </code></pre> <p>However, using these updates, I can only get &quot;Success&quot; in the console, even when I try to leave a blank form value.</p> <p>With all of this said, how can I build a custom reusable function using the above <code>onClick</code> event?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:41:08.693", "Id": "496893", "Score": "0", "body": "Does this question meet the criteria for this board? You’re passing a boolean into your function (`checkCriteria=addcriteria.addcity`), so your function is only receiving TRUE. Just pass the object itself." } ]
[ { "body": "<p>The basic idea that I suggest is to decompose every bit of logic into small reusable functions. In my answer, I will touch only on validation logic because that part of your code has the most code duplication.</p>\n<p>The following code is how I would like to see validation:</p>\n<pre><code>$('#addSubmit').on('click', function (e) {\n e.preventDefault();\n\n const validator = getValidator([\n [$('#addcity'), [\n combine(empty, emptyError),\n combine(notCapitalized, notCapitalizedError)]\n ],\n [$('#addregion'), [\n combine(emptyOrNull, emptyError)]\n ],\n ]);\n\n if (validator.hasErrors()) {\n const { element, error } = validator.getFirstError();\n $('.message').text(error.message);\n $('#errorModal').modal('show').on('hidden.bs.modal', element.focus.bind(element));\n } else {\n // Post request...\n }\n});\n</code></pre>\n<p>Here we use the <code>validator</code> object to check if there are any errors and to get the first occurred error to display its message on the modal dialog. For the <code>getValidator</code> function we need to provide an element that we want to validate and a list of functions that find errors. Since functions that check for errors and actual errors are independent we need the ability to combine them. For example, the line <code>combine(empty, emptyError)</code> means that we want to check if a value is empty and return <code>emptyError</code> if so.</p>\n<p>Also, I've made additional validation for the <code>city</code> field (see <code>notCapitalizedError</code>) to show how easy is to add new validation logic. To not hardcode error messages I've added <code>data-name=&quot;&quot;</code> attributes to all inputs:</p>\n<pre><code>&lt;input type=&quot;text&quot; id=&quot;addcity&quot; data-name=&quot;City&quot; placeholder=&quot;City&quot;&gt;\n&lt;input type=&quot;text&quot; id=&quot;addregion&quot; data-name=&quot;Region&quot; placeholder=&quot;Region&quot;&gt;\n</code></pre>\n<p>The implementation code is a bit hard to read and the following:</p>\n<pre><code>const empty = (str) =&gt; (str === &quot;&quot;);\nconst emptyError = ($el) =&gt; ({ name: &quot;empty&quot;, message: `You must enter a ${$el.data('name')}.` });\nconst notCapitalized = (str) =&gt; (!empty(str) &amp;&amp; str[0] === str[0].toLowerCase());\nconst notCapitalizedError = ($el) =&gt; ({ name: &quot;not-capitalized&quot;, message: `${$el.data('name')} should be capitalized.` });\nconst emptyOrNull = (val) =&gt; (empty(val) || val == null);\n\n\nconst combine = (hasError, createErr) =&gt; function($el) {\n return (hasError($el.val()) ? createErr($el) : null);\n}\n\nconst getErrors = ($element, fns) =&gt; fns.map((fn) =&gt; fn($element)).filter(res =&gt; res !== null);\nconst getValidator = (data) =&gt; {\n const map = new Map();\n data.forEach(([$el, functions]) =&gt; {\n map.set($el, functions);\n })\n\n const elements = Array.from(map.keys());\n const getFunctions = ($el) =&gt; map.get($el) || [];\n const elErrors = ($el) =&gt; getErrors($el, getFunctions($el));\n const elHasErrors = ($el) =&gt; (elErrors($el).length &gt; 0);\n const hasErrors = () =&gt; elements.some(elHasErrors);\n\n return {\n hasErrors,\n getFirstError: () =&gt; {\n if (hasErrors()) {\n const $element = elements.find(elHasErrors);\n return { element: $element, error: elErrors($element)[0]};\n }\n\n return null;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:15:30.197", "Id": "497185", "Score": "0", "body": "Thank you for your input. I will test your suggestion asap and let you know if I am successful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:20:15.767", "Id": "252361", "ParentId": "252192", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T16:09:24.590", "Id": "252192", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Reusable function for a validation process" }
252192
<p>I have updated my <a href="https://codereview.stackexchange.com/questions/252159/sha256-password-cracker-brute-force/252167#252167">previous code</a> with the suggestions. I have also implemented concurrency to speed up the results.</p> <p>I'd be interested for comments on a more efficient use on concurrency / parallel processing / hyper-threading</p> <p>Thanks</p> <pre><code>import concurrent.futures import hashlib import time def make_next_guess(guess): carry = 0 next_guess = guess for i, char in enumerate(next_guess): if ord(char) &gt;= ord(&quot;z&quot;): carry = 1 next_guess[i] = &quot;!&quot; elif ord(char) &lt; ord(&quot;z&quot;): next_guess[i] = chr(ord(char) + 1) carry = 0 if carry == 0: break if carry: next_guess.append(&quot;!&quot;) return next_guess def hash_password(pwrd): # Generates hash of original password try: pwrd = pwrd.encode(&quot;UTF-8&quot;) password = hashlib.sha256() password.update(pwrd) return password.hexdigest() except: pass def find_password(secure_password, guess, integer): list_cracked = [] # Brute force to find original password for _ in range(90 ** integer): # password maximum length 14 and there are 58 characters that can be used return_password = &quot;&quot;.join(guess) if hash_password(return_password) in secure_password: # print(f&quot;Another password has been cracked: '{return_password}'&quot;) list_cracked.append(return_password) guess = make_next_guess(guess) return f&quot;Finished cracking all passwords of length {integer}&quot;, list_cracked, integer def rainbow_table_check(secure_password): global hash list_cracked = [] for password in open(&quot;Rainbow.txt&quot;, &quot;r&quot;, encoding=&quot;utf8&quot;): try: password = password.strip() hash = hash_password(password) except: pass if hash in secure_password: # print(f&quot;Another password has been cracked: {password}&quot;) list_cracked.append(password) return &quot;Rainbow attack complete - passwords: &quot;, list_cracked, &quot;Rainbow&quot; def dic_attack(secure_password): list_cracked = [] for password in open(&quot;Dic.txt&quot;, &quot;r&quot;, encoding=&quot;utf8&quot;): password = password.strip() lst = [password.lower(), password.upper(), password.title()] for password in lst: hash = hash_password(password) if hash in secure_password: # print(f&quot;Another password has been cracked: {password}&quot;) list_cracked.append(password) return &quot;Dictionary attack complete - passwords: &quot;, list_cracked, &quot;Dictionary&quot; if __name__ == &quot;__main__&quot;: all_passwords = [] start = time.time() secure_password = set() print(&quot;Attempting to crack passwords....&quot;) password_list = [&quot;ABd&quot;, &quot;Abc&quot;, &quot;lpo&quot;, &quot;J*&amp;&quot;, &quot;Njl&quot;, &quot;!!!!&quot;, &quot;Aqz&quot;, &quot;Apple&quot;, &quot;Cake&quot;, &quot;Biden&quot;, &quot;password1&quot;] for password in password_list: secure_password.add(hash_password(password)) with concurrent.futures.ProcessPoolExecutor() as executor: results = [executor.submit(dic_attack, secure_password), executor.submit(rainbow_table_check, secure_password), executor.submit(find_password, secure_password, ['!'], 1), executor.submit(find_password, secure_password, ['!', '!'], 2), executor.submit(find_password, secure_password, ['!', '!', '!'], 3), executor.submit(find_password, secure_password, ['!', '!', '!', '!'], 4), executor.submit(find_password, secure_password, ['!', '!', '!', '!', '!'], 5)] for f in concurrent.futures.as_completed(results): message, cracked, method = f.result() time_run = f&quot;{round((time.time() - start) // 60)} min {round((time.time() - start) % 60)} sec&quot; print(f&quot;{message} : {cracked} - {time_run}&quot;) all_passwords += cracked print(f&quot;Complete list of cracked passwords: {set(tuple(all_passwords))}&quot;) print(f&quot;This operation took: {round((time.time() - start) // 60)} min {round((time.time() - start) % 60)} sec&quot;) </code></pre>
[]
[ { "body": "<p>Two observations:</p>\n<p>The methods in <code>hashlib</code> expect to receive bytes. In <code>make_next_guess()</code>, use a <code>bytearray</code> instead of a string. That avoids the calls to <code>''.join()</code>, <code>ord()</code>, <code>''.encode('UTF-8')</code>, etc. Better yet, make the function a generator that yields the guesses.</p>\n<p>Using the <code>else</code> clause on the <code>for i, byte in enumerate(guess):</code> loop simplifies the logic a bit. When the loop is finishes, the <code>else</code> clause is executed. However, a <code>break</code> skips the <code>else</code> clause. Here, if the loop doesn't find any bytes to increase, the else clause add another byte to the length of the guess.</p>\n<p>Something like:</p>\n<pre><code>def generate_guesses(start):\n ORD_Z = ord('z')\n ORD_BANG = ord(&quot;!&quot;)\n \n guess = start[:]\n \n while True:\n yield guess\n for i, byte in enumerate(guess):\n if byte &lt; ORD_Z:\n guess[i] += 1\n break\n \n else:\n guess[i] = ORD_BANG\n \n else:\n guess.append(ORD_BANG)\n</code></pre>\n<p>Called like:</p>\n<pre><code>for guess in generate_guesses(bytearray(b'xzzzz')):\n ... do something with the guess ...\n</code></pre>\n<p>Possibly, add a <code>stop</code> or <code>count</code> argument that tells when the generator should stop or how many guesses it should generate. Just change the <code>while True:</code> line to check the stop condition.</p>\n<p>Second observation is that the last job submitted to the Pool, is 90 times more work than the job before it. Indeed, it is more work than the previous 4 jobs combined (maybe all the other jobs). As a result, you end up with the other jobs finishing sooner and one job running on one processor core for a long time. Try splitting the jobs up into more equal sized chunks to keep all the processor cores busy. For example, the jobs could work on equal sized chunks of the password search space:</p>\n<pre><code>'!' to 'zzz' \n'!!!!' to 'zzz!'\n'!!!&quot;' to 'zzz&quot;'\n'!!!#' to 'zzz#' these are all chunks of 729k (90*90*90) guesses\n ...\n'!!!z' to 'zzzz'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T13:39:27.493", "Id": "496886", "Score": "0", "body": "That is a good idea. Thank you" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T00:35:18.243", "Id": "252221", "ParentId": "252194", "Score": "1" } } ]
{ "AcceptedAnswerId": "252221", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T16:46:53.230", "Id": "252194", "Score": "4", "Tags": [ "python-3.x", "concurrency", "hash" ], "Title": "SHA256 password cracker - v2 with concurrency" }
252194
<p>I created the following service for the purpose of sending in a file for parsing. I'm using the generics so that when I call <code>parse()</code> I can pass a custom type conforming to <code>Codable</code>. I'm not a huge fan of the repetition of <code>do {} catch {}</code> but I don't see any other way to avoid this.</p> <pre><code>import Foundation enum JSONError: Error { case read, parse } struct JSONService { let fileName: String func parse&lt;T: Decodable&gt;(type: T.Type) -&gt; T? { do { let fileContents = try self.getJsonContents() return try self.parseJson(data: fileContents, type: T.self) } catch { fatalError(&quot;\(error.localizedDescription)&quot;) } } private func getJsonContents() throws -&gt; Data { if let file = Bundle.main.path(forResource: self.fileName, ofType: &quot;json&quot;) { if let data = try String(contentsOfFile: file).data(using: .utf8) { return data } } throw JSONError.read } private func parseJson&lt;T: Decodable&gt;(data: Data, type: T.Type) throws -&gt; T { do { return try JSONDecoder().decode(type.self, from: data) } catch { throw JSONError.parse } } } </code></pre>
[]
[ { "body": "<p>Your method reads an object from a JSON file which is embedded in the application bundle, and aborts with a runtime error if that fails for any reason. That is fine: Bad embedded data are a <em>programming error</em> and should be detected early.</p>\n<p>The return type of the <code>parse()</code> method should not be an optional because it never returns <code>nil</code>.</p>\n<p>The custom error type is used to pass errors from the helper methods to the main method. That has two disadvantages:</p>\n<ul>\n<li><p>It hides (possible more informative) errors thrown from other methods, e.g. the JSON decoder method.</p>\n</li>\n<li><p>The messages printed with <code>fatalError()</code> show only the error type and an integer, for example</p>\n<pre><code>Fatal error: The operation couldn’t be completed. (MyApp.JSONError error 0.)\n</code></pre>\n</li>\n</ul>\n<p>The second issue can be improved (see for example <a href=\"https://stackoverflow.com/q/39176196/1187415\">How to provide a localized description with an Error type in Swift?</a> on Stack OverFlow) but I would go another route and pass on existing errors instead, where possible:</p>\n<p>In <code>parseJson()</code> you can pass the error which the JSON decoder already throws, instead of shadowing it by a custom error:</p>\n<pre><code>private func parseJson&lt;T: Decodable&gt;(data: Data, type: T.Type) throws -&gt; T {\n try JSONDecoder().decode(type.self, from: data)\n}\n</code></pre>\n<p>And in <code>getJsonContents()</code> you can use the (throwing) <code>Data(contentsOf: url)</code> method to read the data, that is also simpler than reading into a string and then converting the string to data.</p>\n<p>It remains to handle an error in <code>Bundle.main.url(forResource:withExtension:)</code>, that method does not throw an error but returns an optional.</p>\n<p>Without the do-catching in the helper methods everything fits neatly into the main method:</p>\n<pre><code>func parse&lt;T: Decodable&gt;(type: T.Type) -&gt; T {\n guard let url = Bundle.main.url(forResource: self.fileName, withExtension: &quot;json&quot;) else {\n fatalError(&quot;file not found&quot;)\n }\n do {\n let data = try Data(contentsOf: url)\n return try JSONDecoder().decode(type.self, from: data)\n } catch {\n fatalError(&quot;\\(error.localizedDescription)&quot;)\n }\n}\n</code></pre>\n<p>You many also want to print the full <code>error</code> and not its <code>localizedDescription</code> because that can provide more information (and the string is not presented to the user of your program but only for diagnostic purposes).</p>\n<p>Finally, I wonder if <code>fileName</code> should really be an instance variable. If it is only used in the <code>parse()</code> method and nowhere else then you can make it a parameter of a <em>static</em> method:</p>\n<pre><code>struct JSONService {\n static func parse&lt;T: Decodable&gt;(type: T.Type, from fileName: String) -&gt; T {\n guard let url = Bundle.main.url(forResource: fileName, withExtension: &quot;json&quot;) else {\n fatalError(&quot;file not found&quot;)\n }\n do {\n let data = try Data(contentsOf: url)\n return try JSONDecoder().decode(type.self, from: data)\n } catch {\n fatalError(&quot;\\(error)&quot;)\n }\n }\n}\n</code></pre>\n<p>which would be called as</p>\n<pre><code>let value = JSONService.parse(type: MyType.self, from: &quot;filename&quot;)\n</code></pre>\n<p>Embedding it into a <code>struct JSONService</code> is still useful as it provides a “name space“ for its static methods. If there are only static methods then you can embed them in an <code>enum JSONService</code> instead, because no instance of that type needs to be created (thanks to @Shadowrun for reminding me about that).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T10:28:57.513", "Id": "496860", "Score": "0", "body": "If a struct has only static methods, you could argue that it shouldn't be possible to instantiate such a struct with let foo = JSONService(). One way to prevent that is to make it an enum with no cases and only static methods. Another idea would be to avoid having a type at all, which means you also don't need to worry about naming it FooService/FooHelper/FooSomething. By making an extension on Decodable:\n\nextension Decodable {\n init(from fileName: String) {\n...\n self = try JSONDecoder().decode(Self.self, from: data)\n..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T10:32:31.887", "Id": "496861", "Score": "0", "body": "@Shadowrun: You are completely right, an enum is sufficient and perhaps preferable if you only want a namespace (this was also discussed on Stack Overflow: https://stackoverflow.com/q/38585344/1187415)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T10:38:08.200", "Id": "496862", "Score": "0", "body": "@Shadowrun: Defining your own type or extending an existing type both have advantages. The advantage of your own type/namespace is that you cannot have conflicts with definitions in other modules or with future extensions of the exiting type." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T19:15:50.740", "Id": "252207", "ParentId": "252197", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T17:21:29.853", "Id": "252197", "Score": "4", "Tags": [ "swift", "ios" ], "Title": "JSON parsing service" }
252197
<p>The code I'm working on looks like this - All the way up to 50... (Not ideal)</p> <p>There can be anywhere from 1 to 100 anchor/div combinations, but more often than not in single digits so there's almost always a lot of redundant CSS rules.</p> <p>I was wondering if there was a better way to write the CSS / SCSS for this rather than code for each possible outcome manually? Or would the only way to do this be by using JS?</p> <pre><code>.content { display: none; } .anchor-1:hover ~ .content-1, .anchor-2:hover ~ .content-2, .anchor-3:hover ~ .content-3, .anchor-4:hover ~ .content-4, .anchor-5:hover ~ .content-5 { display: block; } </code></pre> <p>I also have the code fiddled here: <a href="https://jsfiddle.net/rn437pw8/8/" rel="nofollow noreferrer">https://jsfiddle.net/rn437pw8/8/</a></p>
[]
[ { "body": "<p>There is! You can use <code>:nth-child()</code> with plenty of ways to select children elements of particular wrapper, for example odd or even elements, a range of elements, 3 elements after 4 other elements and repeat.</p>\n<p>Check this generator to create a rule and help you visualize what elements will be selected:\n<a href=\"https://css-tricks.com/examples/nth-child-tester/\" rel=\"nofollow noreferrer\">https://css-tricks.com/examples/nth-child-tester/</a></p>\n<p>Docs:\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T08:55:02.613", "Id": "256672", "ParentId": "252202", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T17:49:26.893", "Id": "252202", "Score": "1", "Tags": [ "css", "sass" ], "Title": "Is there a more dynamic way to target siblings in CSS / SCSS?" }
252202
<p>This question is a follow up to my previous question, link to the post can be found <a href="https://codereview.stackexchange.com/questions/252125/console-based-quiz-application/252148#252148">here</a>. I really appreciate the reviewers especially @Edward's review. They highlighted great points which were considered whilst refactoring the codebase.</p> <h1>OVERVIEW</h1> <p>This project is a console-based quiz application. It can be constructed from a <code>xml</code> file and a <code>std::vector</code> of quiz objects. <code>Quiz Application</code> was designed as one of the ways in which users of the class <code>Quiz</code> might program a quiz application. This insinuates that <code>Quiz Application</code> might be programmed in another way depending on the taste of the user.</p> <h1>AIM</h1> <ol> <li>I aim to practice object-oriented programming.</li> <li>I aim to improve my ability to produce robust and usable classes.</li> <li>I aim to solidify my knowledge on STL containers and generic algorithms.</li> </ol> <h1>MAJOR CONCERN</h1> <p>I don't know if this fits for code review site or maybe should be posted on a different stack exchange site. I planned on persisting objects of type <code>QuizApplication</code>. <code>SOLID</code> design principle requires that classes do one thing and do it very well. <code>QuizApplication</code> so far, generates quiz and grades quiz, does it make any sense for it to also persist an object of its type or should the job be moved to a different class, keeping in mind that the storage facility might change in the near future?</p> <h2>Quiz.h</h2> <pre class="lang-cpp prettyprint-override"><code>#ifndef QUIZ_H_ #define QUIZ_H_ #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;map&gt; struct Quiz { friend std::ostream&amp; operator&lt;&lt;( std::ostream &amp;os, const Quiz &amp;quiz ); Quiz(); Quiz( const std::string &amp;question, const std::vector&lt;std::string&gt;&amp; options, \ const std::string&amp; answer, const std::vector&lt;std::string&gt;&amp; tag ); bool operator==( const Quiz&amp; quiz ); bool operator==( const Quiz&amp; quiz ) const; std::string question_; std::string answer_; std::vector&lt;std::string&gt; tag_; std::map&lt;char, std::string, std::less&lt;char&gt;&gt; options_; }; #endif </code></pre> <h2>Quiz.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Quiz.h&quot; #include &lt;iostream&gt; Quiz::Quiz( const std::string &amp;question, const std::vector&lt;std::string&gt;&amp; options, \ const std::string&amp; answer, const std::vector&lt;std::string&gt;&amp; tag ) : question_{ question }, answer_{ answer }, tag_{ tag } { int alphabelt = 65; for( const auto item : options ) options_.insert( { char( alphabelt++ ) , item } ); } std::ostream&amp; operator&lt;&lt;( std::ostream &amp;os, const Quiz &amp;quiz ) { for( const auto &amp;item : quiz.tag_ ) os &lt;&lt; &quot;[&quot; &lt;&lt; item &lt;&lt; &quot;]&quot;; os &lt;&lt; '\n' &lt;&lt; quiz.question_ &lt;&lt; '\n'; for( const auto item : quiz.options_ ) os &lt;&lt; item.first &lt;&lt; &quot;. &quot; &lt;&lt; item.second &lt;&lt; '\n'; return os; } bool Quiz::operator==( const Quiz&amp; quiz ) { if( question_ != quiz.question_ ) return false; if( answer_ != quiz.answer_ ) return false; if( options_ != quiz.options_ ) return false; if( tag_ != quiz.tag_ ) return false; return true; } bool Quiz::operator==( const Quiz&amp; quiz ) const { if( question_ != quiz.question_ ) return false; if( answer_ != quiz.answer_ ) return false; if( options_ != quiz.options_ ) return false; if( tag_ != quiz.tag_ ) return false; return true; } </code></pre> <h2>QuizApplication.h</h2> <pre class="lang-cpp prettyprint-override"><code>#ifndef QUIZAPPLICATION_H_ #define QUIZAPPLICATION_H_ #include &quot;Quiz.h&quot; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;unordered_set&gt; #include &lt;map&gt; struct QuizHash { size_t operator()( const Quiz &amp;quiz ) const { return std::hash&lt;std::string&gt;()( quiz.question_ ); } }; class QuizApplication { friend std::ostream&amp; operator&lt;&lt;( std::ostream &amp;os, const QuizApplication&amp; app ); public: QuizApplication( const std::vector&lt;Quiz&gt;&amp; quiz ) : quiz_container_{ quiz } {} explicit QuizApplication( const std::string &amp;filename ) { read_xml( filename); }; QuizApplication&amp; add_quiz( const Quiz&amp; quiz ); QuizApplication&amp; remove_quiz( const Quiz&amp; quiz ); void start_quiz() const; std::vector&lt;Quiz&gt;::iterator get( Quiz&amp; quiz ); std::vector&lt;Quiz&gt;::const_iterator get( const Quiz&amp; quiz ) const; static int number_of_quiz_to_ask; private: std::vector&lt;Quiz&gt; quiz_container_; void read_xml( const std::string&amp; filename ); std::unordered_set&lt;Quiz, QuizHash&gt; generate_quiz_set() const; unsigned grade_quiz( std::multimap&lt;char, Quiz&gt; &amp;quiz_choice ) const; }; #endif </code></pre> <h2>QuizApplication.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include &quot;QuizApplication.h&quot; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;random&gt; #include &lt;map&gt; #include &lt;boost/property_tree/ptree.hpp&gt; #include &lt;boost/property_tree/xml_parser.hpp&gt; int QuizApplication::number_of_quiz_to_ask = 0; void QuizApplication::read_xml( const std::string&amp; filename ) { namespace pt = boost::property_tree; pt::ptree tree; pt::xml_parser::read_xml( filename, tree ); Quiz quiz_obj { &quot;&quot;, {}, &quot;&quot;, {} }; for( auto &amp;quiz_item : tree.get_child( &quot;quizlist&quot; ) ) { int alphabelt = 65; if( quiz_item.first == &quot;quiz&quot; ) { quiz_obj.question_ = quiz_item.second.get&lt;std::string&gt;(&quot;question&quot;); quiz_obj.answer_ = quiz_item.second.get&lt;std::string&gt;(&quot;answer&quot;); auto option_list = quiz_item.second.get_child(&quot;optionlist&quot;); for( auto &amp;item : option_list ) { quiz_obj.options_.insert( { char( alphabelt++ ), item.second.data() } ); } auto tag_list = quiz_item.second.get_child(&quot;taglist&quot;); for( auto &amp;item : tag_list ) { quiz_obj.tag_.push_back( item.second.data() ); } } quiz_container_.push_back( quiz_obj ); quiz_obj.options_ = {}; quiz_obj.tag_ = {}; } } QuizApplication&amp; QuizApplication::add_quiz( const Quiz&amp; quiz ) { quiz_container_.push_back( quiz ); return *this; } QuizApplication&amp; QuizApplication::remove_quiz( const Quiz&amp; quiz ) { auto iter = get( quiz ); if( iter != quiz_container_.cend() ) quiz_container_.erase( iter ); return *this; } std::vector&lt;Quiz&gt;::iterator QuizApplication::get( Quiz&amp; quiz ) { auto iter = std::find_if( quiz_container_.begin(), quiz_container_.end(), \ [quiz]( Quiz&amp; this_quiz ) { return ( this_quiz == quiz ); } ); return iter; }; std::vector&lt;Quiz&gt;::const_iterator QuizApplication::get( const Quiz&amp; quiz ) const { auto iter = std::find_if( quiz_container_.cbegin(), quiz_container_.cend(), \ [quiz]( const Quiz&amp; this_quiz ) { return ( this_quiz == quiz ); } ); return iter; } std::ostream&amp; operator&lt;&lt;( std::ostream &amp;os, const QuizApplication&amp; app ) { for( const auto&amp; item : app.quiz_container_ ) os &lt;&lt; item &lt;&lt; '\n'; return os; } void QuizApplication::start_quiz() const { std::unordered_set&lt;Quiz, QuizHash&gt; quiz_set = generate_quiz_set(); std::multimap&lt;char, Quiz&gt; quiz_choice; for( const auto &amp;item : quiz_set ) { std::cout &lt;&lt; '\n' &lt;&lt; item &lt;&lt; &quot;? &quot;; char choice; std::cin &gt;&gt; choice; quiz_choice.insert( { toupper( choice), item } ); } unsigned score = grade_quiz( quiz_choice ); char choice; std::cout &lt;&lt; &quot;Do you want your grade? (y/n)&quot;; std::cin &gt;&gt; choice; if( choice == 'y' ) std::cout &lt;&lt; &quot;Your score is &quot; &lt;&lt; score &lt;&lt; std::endl; else std::cout &lt;&lt; &quot;See you some other time&quot; &lt;&lt; std::endl; } std::unordered_set&lt;Quiz, QuizHash&gt; QuizApplication::generate_quiz_set() const { std::unordered_set&lt;Quiz, QuizHash&gt; quiz_set; std::default_random_engine engine( static_cast&lt;unsigned&gt;( time( nullptr) ) ); std::uniform_int_distribution&lt;unsigned&gt; random_int( 0, quiz_container_.size() - 1 ); for( int i = 0; i != number_of_quiz_to_ask; ) { unsigned index = random_int( engine ); auto insert_return = quiz_set.insert( quiz_container_[ index ] ); if( insert_return.second ) ++i; else continue; } return quiz_set; } unsigned QuizApplication::grade_quiz( std::multimap&lt;char, Quiz&gt; &amp;quiz_choice ) const { unsigned score = 0; for( const auto&amp; item : quiz_choice ) { if( item.second.options_.at( item.first ) == item.second.answer_ ) ++score; } return score; } </code></pre> <h2>quiz.xml</h2> <pre><code>&lt;quizlist&gt; &lt;quiz&gt; &lt;question&gt;Pointer-based code is complex and error-prone—the slightest omissions or oversights can lead to serious memory-access violations and memory-leak errors that the compiler will warn you about.&lt;/question&gt; &lt;optionlist&gt; &lt;option&gt;True&lt;/option&gt; &lt;option&gt;False&lt;/option&gt; &lt;/optionlist&gt; &lt;answer&gt;False&lt;/answer&gt; &lt;taglist&gt; &lt;tag&gt;C++&lt;/tag&gt; &lt;tag&gt;Programming&lt;/tag&gt; &lt;/taglist&gt; &lt;/quiz&gt; &lt;quiz&gt; &lt;question&gt;deques offer rapid insertions and deletions at front or back and direct access to any element.&lt;/question&gt; &lt;optionlist&gt; &lt;option&gt;False&lt;/option&gt; &lt;option&gt;True&lt;/option&gt; &lt;/optionlist&gt; &lt;answer&gt;True&lt;/answer&gt; &lt;taglist&gt; &lt;tag&gt;C++&lt;/tag&gt; &lt;tag&gt;Programming&lt;/tag&gt; &lt;/taglist&gt; &lt;/quiz&gt; &lt;/quizlist&gt; </code></pre> <h2>main.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &quot;Quiz.h&quot; #include &quot;QuizApplication.h&quot; int main() { QuizApplication::number_of_quiz_to_ask = 2; Quiz quiz_obj { &quot;What is my name?&quot;, { &quot;Samuel&quot;, &quot;Kingsley&quot;, &quot;Paul&quot;, &quot;John&quot; }, &quot;Samuel&quot;, { &quot;Name&quot; } }; QuizApplication app { &quot;quiz.xml&quot; }; app.add_quiz( quiz_obj ); app.start_quiz(); } </code></pre>
[]
[ { "body": "<h2><code>Quiz</code> class:</h2>\n<p><code>class Quiz</code> - I would probably call this class <code>Question</code> instead. In English a &quot;quiz&quot; would be the entire set of questions.</p>\n<hr />\n<pre><code>Quiz();\n</code></pre>\n<p>It looks like the default constructor is declared, but not defined. We should do <code>Quiz() { }</code> or <code>Quiz() = default;</code></p>\n<hr />\n<pre><code>Quiz( const std::string &amp;question, const std::vector&lt;std::string&gt;&amp; options, \\\n const std::string&amp; answer, const std::vector&lt;std::string&gt;&amp; tag );\n</code></pre>\n<p>It's fine to split function definitions across multiple lines. There's no need for the <code>\\</code>.</p>\n<hr />\n<pre><code>bool operator==( const Quiz&amp; quiz );\nbool operator==( const Quiz&amp; quiz ) const;\n</code></pre>\n<p>We don't need both of these. A <code>const</code> member function can be called on both a <code>const</code> and non-<code>const</code> <code>Quiz</code> object, so we only need the <code>const</code> version.</p>\n<p>Alternatively, we could make this a free function that takes two <code>Quiz</code> objects:</p>\n<pre><code>bool operator==(const Quiz&amp; a, const Quiz&amp; b);\n</code></pre>\n<hr />\n<p>We store the answer string twice in <code>Quiz</code> - once in the <code>answer_</code> variable, and once in the <code>options_</code> map. We only need to store the <code>char</code> key of the correct answer in the <code>answer_</code> variable.</p>\n<hr />\n<pre><code> int alphabelt = 65;\n for( const auto item : options )\n options_.insert( { char( alphabelt++ ) , item } );\n</code></pre>\n<p>Typo: in English it's <code>alphabet</code>.</p>\n<p>We could avoid the cast from <code>int</code> to <code>char</code> and make it a little clearer by doing: <code>char alphabet = 'A';</code>. <code>char</code> is an integer type too, so we can increment it.</p>\n<p>We probably want to use <code>const auto&amp; item</code> in the range-based for loop, instead of <code>const auto item</code> to avoid an unnecessary copy.</p>\n<hr />\n<p>Since we're using alphabet letters to refer to questions, we should check somewhere that we don't have more questions in a quiz than characters in the alphabet.</p>\n<hr />\n<h2><code>QuizHash</code> class:</h2>\n<p>Using a hash of the entire question string as a storage key is probably not a good idea. (It's going to be slow to compute the hash value, and we have to know the entire question string to find a question).</p>\n<p>I don't think the <code>set</code> is actually necessary here, we could just use a <code>vector</code>.</p>\n<hr />\n<h2><code>QuizApplication</code> class:</h2>\n<pre><code> std::vector&lt;Quiz&gt;::iterator get( Quiz&amp; quiz );\n std::vector&lt;Quiz&gt;::const_iterator get( const Quiz&amp; quiz ) const;\n</code></pre>\n<p>These functions are only needed inside the <code>QuizApplication</code> (and outside code has no way to access the <code>quiz_container_</code>) so they could be private.</p>\n<hr />\n<pre><code> static int number_of_quiz_to_ask;\n</code></pre>\n<p><code>number_of_questions_to_ask</code> would be a more accurate name.</p>\n<hr />\n<pre><code>Quiz quiz_obj \n{ &quot;&quot;,\n {},\n &quot;&quot;,\n {}\n};\n</code></pre>\n<p>We could use the default constructor (assuming it's defined - see above): <code>Quiz quiz_obj;</code></p>\n<hr />\n<pre><code> int alphabelt = 65;\n</code></pre>\n<p>Same as in <code>Quiz</code> class (<code>alphabet</code>, use a <code>char</code> - see above).</p>\n<hr />\n<pre><code> quiz_obj.options_ = {};\n quiz_obj.tag_ = {};\n</code></pre>\n<p>We could avoid having to reset the variable every loop iteration by declaring <code>quiz_obj</code> inside the loop.</p>\n<hr />\n<pre><code>auto iter = std::find_if( quiz_container_.begin(), quiz_container_.end(), \\\n [quiz]( Quiz&amp; this_quiz ) { return ( this_quiz == quiz ); } );\nreturn iter;\n</code></pre>\n<p>We have an <code>operator==</code> for <code>Quiz</code>, so we should able to use <code>std::find(quiz_container_.begin(), quiz_container_.end(), quiz);</code> instead.</p>\n<p>Again, there's no need for the <code>\\</code>.</p>\n<hr />\n<h2>Generating the quiz set</h2>\n<pre><code>std::unordered_set&lt;Quiz, QuizHash&gt; QuizApplication::generate_quiz_set() const\n</code></pre>\n<p>We don't want to duplicate all the <code>Quiz</code> data when generating the question set. We can generate a set of random indices into <code>quiz_container_</code> instead, something like:</p>\n<pre><code>std::vector&lt;std::size_t&gt; QuizApplication::generate_quiz_set() const\n{\n std::vector&lt;std::size_t&gt; out(quiz_container.size(), 0);\n std::iota(out.begin(), out.end(), 0); // out = { 0, 1, 2, 3 ... quiz_container.size() - 1 }\n \n std::default_random_engine engine(static_cast&lt;unsigned&gt;(time(nullptr)));\n std::shuffle(out.begin(), out.end(), engine); // shuffle the indices\n \n out.resize(std::min(number_of_quiz_to_ask, out.size())); // chop off the ones we don't need\n \n return out;\n}\n</code></pre>\n<hr />\n<h2>Running the quiz:</h2>\n<pre><code>void QuizApplication::start_quiz() const\n{\n std::unordered_set&lt;Quiz, QuizHash&gt; quiz_set = generate_quiz_set();\n std::multimap&lt;char, Quiz&gt; quiz_choice;\n\n for( const auto &amp;item : quiz_set )\n {\n std::cout &lt;&lt; '\\n' &lt;&lt; item &lt;&lt; &quot;? &quot;;\n char choice;\n std::cin &gt;&gt; choice;\n quiz_choice.insert( { toupper( choice), item } );\n }\n\n ...\n</code></pre>\n<p>We should check that the <code>choice</code> character is a valid option for the question, and ask the user again if it isn't. Currently, we'll throw an exception when grading the quiz later.</p>\n<p>Again, I don't think we need the <code>set</code> or the <code>multimap</code>. If we use a <code>vector</code> to store the generated quiz set, we could simply use another <code>vector</code> to store the choices:</p>\n<pre><code>void QuizApplication::start_quiz() const\n{\n std::vector&lt;std::size_t&gt; quiz_set = generate_quiz_set();\n std::vector&lt;char&gt; quiz_choices;\n \n for( const auto &amp;item : quiz_set )\n {\n std::cout &lt;&lt; '\\n' &lt;&lt; item &lt;&lt; &quot;? &quot;;\n char choice;\n std::cin &gt;&gt; choice;\n // todo: check choice is a valid option!!!\n quiz_choices.push_back(choice);\n }\n \n ...\n</code></pre>\n<p>Now <code>quiz_choices[i]</code> contains the response to <code>quiz_set[i]</code>, where the value stored in <code>quiz_set[i]</code> is the index to the <code>Quiz</code> in <code>quiz_container_</code>. So now marking the quiz looks something like:</p>\n<pre><code>unsigned score = 0;\nfor (auto i = std::size_t{ 0 }; i != quiz_choices.size(); ++i)\n{\n auto const&amp; choice = quiz_choices[i];\n auto const&amp; index = quiz_set[i];\n \n if (choice == quiz_container_[index].answer_) // assuming we change answer_ to be a `char` instead of the full string\n ++score;\n}\n</code></pre>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T11:57:47.677", "Id": "496866", "Score": "0", "body": "Good points. I actually preferred a `set` to a `vector `cause I want to generate only unique questions. Secondly, if I consider renaming `Quiz` to `Question`, then it would make no sense to add data member `answer` to it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T12:05:02.910", "Id": "496868", "Score": "0", "body": "Moreso, a user might mistakenly add a quiz object twice into the container, if I had used indices for generating the question set, their is a chance of having non-unique questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T13:49:49.140", "Id": "496887", "Score": "1", "body": "@theProgrammer The renaming of Quiz to Question and QuizApplication to Quiz seems to be in line with some of the answers from the previous version of the question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T11:14:49.107", "Id": "252243", "ParentId": "252203", "Score": "1" } } ]
{ "AcceptedAnswerId": "252243", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T18:13:01.170", "Id": "252203", "Score": "2", "Tags": [ "c++", "object-oriented", "design-patterns" ], "Title": "Revised console-based quiz application" }
252203
<p>I'm new to C and programming in general (some minimal prior exposure to JS and python). This is also my first time working with shell commands, scripts, and cron. This program works on my macOS and Lubuntu running on a VM (so long as you run as root).</p> <p>Using this program, you can set times throughout the day when your wifi turns off automatically. When your wifi is off, you <em>can still</em> manually turn on wifi for urgent situations for a short time (default is 30 seconds) before the program automatically turns off the wifi again.</p> <p>The code is separated into 2 C programs and 1 shell script.</p> <p><strong>checkon.sh</strong> (runs in bg and turns off wifi after a short time if it detects it was turned on)</p> <pre><code>#!/bin/bash # Check OS if [[ &quot;$OSTYPE&quot; == &quot;linux-gnu&quot;* ]]; then # If wifi on for ubuntu, keyword is UP wifion=UP elif [[ &quot;$OSTYPE&quot; == &quot;darwin&quot;* ]]; then # Name of Wi-Fi device is en0 device=en0 # If wifi on for osx, keyword is active wifion=active fi # Check status of wi-fi device (is it active or inactive?) status() { if [[ &quot;$OSTYPE&quot; == &quot;linux-gnu&quot;* ]]; then ip l show enp0s3 | awk '/state/{print $9}' elif [[ &quot;$OSTYPE&quot; == &quot;darwin&quot;* ]]; then /sbin/ifconfig $device | awk '/status:/{print $2}' fi } # If wifi is on, turn off after X seconds isactive() { sleep 30 if [[ &quot;$OSTYPE&quot; == &quot;linux-gnu&quot;* ]]; then nmcli networking off elif [[ &quot;$OSTYPE&quot; == &quot;darwin&quot;* ]]; then /usr/sbin/networksetup -setairportpower $device off fi } # Every 5 seconds, check if wifi is active or inactive while :; do if [[ &quot;$(status)&quot; == &quot;$wifion&quot; ]] then isactive fi sleep 5 done </code></pre> <p><strong>setcheck.c</strong> (cron will launch this program)</p> <pre><code>#include &lt;stdio.h&gt; // For strerror() #include &lt;stdlib.h&gt; // For exit() and system() #include &lt;string.h&gt; // For strcmp() #include &lt;unistd.h&gt; // For fork(), getcwd() #include &lt;errno.h&gt; // For errno #include &lt;time.h&gt; // For time() // Determine os #if __APPLE__ #define PLATFORM_NAME &quot;apple&quot; #elif __linux__ #define PLATFORM_NAME &quot;linux&quot; #endif #define MAXLINE 1000 // 1) If I don't assign macro to a variable, compiler will warn that code // strcmp(PLATFORM_NAME, &quot;apple&quot;) will result in unreachable code. // Need to determine condition at run-time vs compile-time. // 2) Need `static` to avoid -Wmissing-variable-declaration warning static char os[MAXLINE]; int startcheck(void); int endcheck(void); int pmessages(char *message); int turnonwifi(void); int turnoffwifi(void); // Cron calls main(), telling it to either turn on wifi (normal state) // or turn off wifi (run script) int main(int argc, char *argv[]) { strcpy(os, PLATFORM_NAME); if (argc == 1) { printf(&quot;Include argument 'wifion' or 'wifioff'\n&quot;); return 1; } // Turn off or on the background script if (!strcmp(argv[1], &quot;wifion&quot;)) { pmessages(&quot;Turning on wifi&quot;); turnonwifi(); // Run program shuts down checkon script if (endcheck()) return 1; } else if (!strcmp(argv[1], &quot;wifioff&quot;)) { pmessages(&quot;Turning off wifi&quot;); turnoffwifi(); if(startcheck()) return 1; } else { pmessages(&quot;Error: Argument must be 'wifion' or 'wifioff': %s\n&quot;); } return 0; } // Launch checkon script int startcheck(void) { char cwd[MAXLINE]; getcwd(cwd, MAXLINE); char *checkon_path2 = &quot;/checkon.sh&quot;; char *checkon_path = strcat(cwd, checkon_path2); char *checkon_arg0 = &quot;checkon.sh&quot;; // Check if checkon.sh already exists, if so, print error and exit // Need to use '-f' and include '.sh' in search for osx int isrunning = 1; if (!strcmp(os, &quot;apple&quot;)) { isrunning = system(&quot;/usr/bin/pgrep -f checkon.sh &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;); } else if (!strcmp(os, &quot;linux&quot;)) { // NTD: Why does system() return 0 when '-f' is used in // ubuntu when process doesn't exist? isrunning = system(&quot;/usr/bin/pgrep checkon &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;); } else { printf(&quot;Warning: cannot determine if checkon.sh is running\n&quot;); } if(isrunning == 0) { pmessages(&quot;Error: checkon.sh already exists&quot;); exit(1); } // Fork creates a child process that is identical except it returns // 0 for the child and the pid of the child for the parent process int pid = fork(); // We fork so that child runs in background when parent exits if (pid == 0) { setsid(); execl(checkon_path, checkon_arg0, (char *) NULL); if (errno) { printf(&quot;errno %d: %s\n&quot;, errno, strerror(errno)); return 1; } } else { exit(0); } return 0; } // Find checkon script and kill it int endcheck(void) { // pgrep -f finds name of script and kill will end it. // Redirect output otherwise if checkon.sh doesn't exist, // command will print error to terminal if (!strcmp(os, &quot;apple&quot;)) { system(&quot;/bin/kill $(/usr/bin/pgrep -f checkon.sh) &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;); } else if (!strcmp(os, &quot;linux&quot;)) { system(&quot;/usr/bin/pkill checkon &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;); } return 0; } // Print messages int pmessages(char *pmessage) { time_t current_time = time(NULL); char *c_time_string = ctime(&amp;current_time); if (pmessage != NULL) { printf(&quot;%s: %s&quot;, pmessage, c_time_string); return 0; } else { printf(&quot;pmessages error: no message: %s\n&quot;, c_time_string); return 1; } } // Turn on wifi int turnonwifi() { // Include full path b/c cron sets a different environment // than shell, meaning PATH variable is different if (!strcmp(os, &quot;apple&quot;)) { system(&quot;/usr/sbin/networksetup -setairportpower en0 on&quot;); } else if (!strcmp(os, &quot;linux&quot;)) { system(&quot;nmcli networking on&quot;); } return 0; } // Turn off wifi int turnoffwifi() { // Include full path b/c cron sets a different environment // than shell, meaning PATH variable is different if (!strcmp(os, &quot;apple&quot;)) { system(&quot;/usr/sbin/networksetup -setairportpower en0 off&quot;); } else if (!strcmp(os, &quot;linux&quot;)) { system(&quot;nmcli networking off&quot;); } return 0; } </code></pre> <p><strong>swifi.c</strong> (user interacts with this program to set cron jobs)</p> <pre><code>#include &lt;stdio.h&gt; // For printf() #include &lt;stdlib.h&gt; // For system() #include &lt;string.h&gt; // For strcmp() #include &lt;inttypes.h&gt; // For strtol() #include &lt;unistd.h&gt; // For getopt() and getcwd() #include &lt;errno.h&gt; // For errno #include &lt;time.h&gt; // For time(), ctime(), etc. // Determine os #if __APPLE__ #define PLATFORM_NAME &quot;apple&quot; #elif __linux__ #define PLATFORM_NAME &quot;linux&quot; #endif #define MAXLINE 1000 struct hourmin { int minute; int hour; }; // Need static keyword to avoid -Wmissing-variable-declaration warning static char cwd[MAXLINE]; static char os[MAXLINE]; static int addflag, rmvflag; // Default: Be on the whole day static struct hourmin starttime = { 1, 0 }; static struct hourmin endtime = { 0, 0 }; void getarg(int argc, char **argv); int addcron(struct hourmin *starttime, struct hourmin *endtime); int rmvcron(struct hourmin *starttime, struct hourmin *endtime); int clearcron(void); int turnoffwifi(void); int turnonwifi(void); int gethourmin(char *strtime, struct hourmin *); int istimebetween(void); // Takes 3 arguments: 1) add or rmv, 2) start time (-s) and 3) end time (-e) int main(int argc, char *argv[]) { getcwd(cwd, MAXLINE); strcpy(os, PLATFORM_NAME); if (argc == 1) { printf(&quot;Error: Provide at least one argument 'add' or 'rmv'\n&quot;); return 1; } getarg(argc, argv); if (addflag) { addcron(&amp;starttime, &amp;endtime); if(istimebetween()) turnoffwifi(); printf(&quot;Wifi set to turn off at %d:%02d\n&quot;, starttime.hour, starttime.minute); printf(&quot;Wifi set to turn on at %d:%02d\n&quot;, endtime.hour, endtime.minute); } else if (rmvflag) { rmvcron(&amp;starttime, &amp;endtime); if(istimebetween()) turnonwifi(); printf(&quot;Timer removed. Start: %d:%02d End: %d:%02d\n&quot;, starttime.hour, starttime.minute, endtime.hour, endtime.minute); } return 0; } // Parse arguments using getopt(). Need a separate function // to handle GNU / Linux case and OSX / BSD case. void getarg(int argc, char **argv) { int ch; // getopt man page uses &quot;ch&quot; addflag = rmvflag = 0; if (!strcmp(os, &quot;apple&quot;)) { while (optind &lt; argc) { if ((ch = getopt(argc, argv, &quot;s:e:&quot;)) != -1) { switch (ch) { case 's': gethourmin(optarg, &amp;starttime); break; case 'e': gethourmin(optarg, &amp;endtime); break; default: break; } } else if (!strcmp(argv[optind], &quot;add&quot;)) { addflag = 1; optind++; } else if (!strcmp(argv[optind], &quot;rmv&quot;)) { rmvflag = 1; optind++; } else if (!strcmp(argv[optind], &quot;clear&quot;)) { clearcron(); optind++; } else { printf(&quot;Error: Unrecognized argument.\n&quot;); exit(1); } } } else if (!strcmp(os, &quot;linux&quot;)) { while ((ch = getopt(argc, argv, &quot;s:e:&quot;)) != -1) { switch (ch) { case 's': gethourmin(optarg, &amp;starttime); break; case 'e': gethourmin(optarg, &amp;endtime); break; default: break; } } int index; for (index = optind; index &lt; argc; index++) { if (!strcmp(argv[optind], &quot;add&quot;)) { addflag = 1; } else if (!strcmp(argv[optind], &quot;rmv&quot;)) { rmvflag = 1; } else if (!strcmp(argv[optind], &quot;clear&quot;)) { clearcron(); } else { printf(&quot;Error: Unrecognized argument.\n&quot;); exit(1); } } } } // Adds cronjob to crontab int addcron(struct hourmin *start_time, struct hourmin *end_time) { char cron_wifioff[MAXLINE]; char cron_wifion[MAXLINE]; // NTD: Is there a cleaner way of preparing these commands? sprintf(cron_wifioff, &quot;(crontab -l 2&gt;&gt;/dev/null; echo '%d %d * * * %s/setcheck.out wifioff &gt;&gt;/dev/null 2&gt;&gt;/dev/null') | sort - | uniq - | crontab -&quot;, start_time-&gt;minute, start_time-&gt;hour, cwd); sprintf(cron_wifion, &quot;(crontab -l 2&gt;&gt;/dev/null; echo '%d %d * * * %s/setcheck.out wifion &gt;&gt;/dev/null 2&gt;&gt;/dev/null') | sort - | uniq - | crontab -&quot;, end_time-&gt;minute, end_time-&gt;hour, cwd); system(cron_wifioff); system(cron_wifion); return 0; } // Removes cronjobs from crontab int rmvcron(struct hourmin *start_time, struct hourmin *end_time) { // rcron stands for remove cron char rcron_wifioff[MAXLINE]; char rcron_wifion[MAXLINE]; // NTD: Is there a cleaner way of preparing these commands? sprintf(rcron_wifioff, &quot;(crontab -l | sort - | uniq - | grep -v '%d %d \\* \\* \\* %s/setcheck.out wifioff &gt;&gt;/dev/null 2&gt;&gt;/dev/null') | crontab -&quot;, start_time-&gt;minute, start_time-&gt;hour, cwd); sprintf(rcron_wifion, &quot;(crontab -l | sort - | uniq - | grep -v '%d %d \\* \\* \\* %s/setcheck.out wifion &gt;&gt;/dev/null 2&gt;&gt;/dev/null') | crontab -&quot;, end_time-&gt;minute, end_time-&gt;hour, cwd); system(rcron_wifioff); system(rcron_wifion); return 0; } // Clears crontab and restarts wifi int clearcron(void) { system(&quot;crontab -r&quot;); turnonwifi(); return 0; } int turnoffwifi(void) { char wificmd[MAXLINE]; sprintf(wificmd, &quot;%s/setcheck.out wifioff &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;, cwd); system(wificmd); return 0; } int turnonwifi(void) { char wificmd[MAXLINE]; sprintf(wificmd, &quot;%s/setcheck.out wifion &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;, cwd); system(wificmd); return 0; } // Get current time and compare if it is in between // NTD: Not sure what to do if starttime = endtime. cronjob race condition? int istimebetween(void) { // Get current time into int format (tm struc that contains int members) time_t current_time = time(NULL); struct tm *current_tm = localtime(&amp;current_time); // Rename for ease int chour = current_tm-&gt;tm_hour; int cmin = current_tm-&gt;tm_min; int shour = starttime.hour; int smin = starttime.minute; int ehour = endtime.hour; int emin = endtime.minute; // If endtime &gt; starttime, check if current time is in between // If endtime &lt; starttime, check if current time is NOT in between int checkbetween = 0; if ((ehour &gt; shour) || (ehour == shour &amp;&amp; emin &gt; smin)) checkbetween = 1; // Compare current time to starttime and endtime int isbetween = 0; switch (checkbetween) { case 0: // In case 0, endtime is &quot;earlier&quot; than starttime, so // we check endtime &lt; currenttime &lt; starttime. 4 possibilities: // 1) endhour &lt; currenthour &lt; starthour // 2) endhour = currenthour &lt; starthour; endmin &lt; currentmin // 3) endhour &lt; currenthour = starthour; currentmin &lt; startmin // 4) endhour = currenthour = starthour; endmin &lt; cmin &lt; startmin if ((chour &gt; ehour &amp;&amp; chour &lt; shour) || (chour == ehour &amp;&amp; cmin &gt; emin &amp;&amp; chour &lt; shour) || (chour == shour &amp;&amp; cmin &lt; smin &amp;&amp; chour &gt; ehour) || (chour == ehour &amp;&amp; chour == shour &amp;&amp; cmin &gt; emin &amp;&amp; cmin &lt; smin)) isbetween = 1; break; case 1: // In case 1, end time is &quot;later&quot; than starttime, so // we check starttime &lt; currenttime &lt; endtime. Inverse of above. if ((chour &gt; shour &amp;&amp; chour &lt; ehour) || (chour == shour &amp;&amp; cmin &gt; smin &amp;&amp; chour &lt; ehour) || (chour == ehour &amp;&amp; cmin &lt; emin &amp;&amp; chour &gt; shour) || (chour == shour &amp;&amp; chour == ehour &amp;&amp; cmin &gt; smin &amp;&amp; cmin &lt; emin)) isbetween = 1; break; } return (checkbetween == isbetween); } // Converts string with 'HHMM' format into struct hourmin int gethourmin(char *strtime, struct hourmin *hmtime) { // Arrays are size 3 because HH and MM can be at most 2 digits + '\0' char hour[3] = { '0', '\0', '\0' }; char minute[3] = { '0', '\0', '\0' }; // Takes 'HHMM' string and separates into minutes and hours strings switch (strlen(strtime)) { case 1: case 2: strcpy(hour, strtime); break; case 3: hour[0] = *strtime++; hour[1] = '\0'; strcpy(minute, strtime); break; case 4: hour[0] = *strtime++; hour[1] = *strtime++; hour[2] = '\0'; strcpy(minute, strtime); break; default: printf(&quot;Error: Bad time arguments. Must be of the form H, HH, HMM, or HHMM.\n&quot;); exit(1); } hmtime-&gt;hour = (int) strtol(hour, NULL, 10); hmtime-&gt;minute = (int) strtol(minute, NULL, 10); // Checks that mins and hours are legal values. First errno occurs if // either strtol() above fail (if str can't be converted to number). if (errno) { printf(&quot;Error: Bad time argument. Must provide a number.\n&quot;); printf(&quot;errno: %s\n&quot;, strerror(errno)); exit(1); } if (hmtime-&gt;hour &gt; 23 || hmtime-&gt;hour &lt; 0) { printf(&quot;Error: Bad time argument. Hour must be between 0-23.\n&quot;); exit(1); } if (hmtime-&gt;minute &gt; 59 || hmtime-&gt;minute &lt;0) { printf(&quot;Error: Bad time argument. Minute must be between 0-59.\n&quot;); exit(1); } return 0; } </code></pre> <p>Remarks / Questions:</p> <ul> <li>I came across readings suggesting that <code>system()</code> is bad practice for reasons of security, portability, and performance (<a href="https://stackoverflow.com/questions/28137628/alternative-to-system">source</a>). However, it wasn't obvious to me whether reimplementing commands like <code>pgrep</code> and <code>crontab</code> using lower-level library and system calls were worthwhile in this case (or whether that is even the right approach).</li> <li>As hinted above, I came across issues when I ran this program without being the root user. In Lubuntu, the user's cron environment doesn't execute the <code>nmcli</code> command for reasons I don't quite understand. I found others with similar issues (<a href="https://askubuntu.com/questions/107401/nmcli-works-in-script-when-i-run-itdirectly-but-not-when-run-in-cron">source</a>, <a href="https://askubuntu.com/questions/586677/how-to-disable-network-with-crontab-on-ubuntu-14-04">source</a>, <a href="https://stackoverflow.com/questions/38855933/not-authorized-to-control-networking-from-cron">source</a>), but none of the suggestions helped me fix the problem.</li> <li>I considered adding functionality that would let me filter wifi access at the application-level (vs system-wide). I came across two possible way of doing it: network extentions (<a href="https://developer.apple.com/documentation/networkextension" rel="noreferrer">source</a>) and user groups (<a href="https://askubuntu.com/questions/19346/how-to-block-internet-access-for-wine-applications">source</a>), but would be curious if another, simpler way is possible.</li> <li>How would I better 'package' this program for more convenient use? Right now I have to compile <code>setcheck.c</code>, rename as <code>setcheck.out</code>, then compile <code>swifi.c</code>, but that seems like a lot of manual work. I'm aware of <code>Makefile</code> / <code>make</code> but I'm not familiar with them and not sure if they would be overkill in a small project like this.</li> </ul>
[]
[ { "body": "<p>I will offer some suggestions.</p>\n<p>Please note I have no experience with Mac OS, but I believe most of it will still apply.</p>\n<ol>\n<li><p>Using <code>system</code> is not particularly bad in your case since you use static arguments in those calls excluding the possibility of command injection.<br />\nHowever, since your first C program is almost completely made up of <code>system</code> calls, you should consider converting it to BASH script as well, since those work a lot better for &quot;command glue&quot; than C binaries.</p>\n</li>\n<li><p>In your C binaries you should not check the OS type at runtime with <code>strcmp</code>.<br />\nThis both wastes processing time, and makes your binary larger because it contains extra code that will never be used (unless you turn optimization high enough to remove it automatically).<br />\nConsider using <a href=\"https://www.cs.auckland.ac.nz/references/unix/digital/AQTLTBTE/DOCU_078.HTM\" rel=\"noreferrer\">conditional compilation</a> instead.</p>\n</li>\n<li><p>If you are going to work with C on Linux and Mac, you should learn GNU Make, at least its basics.<br />\nEven a single file C program can benefit from a Makefile, as it will save you typing a long compiler command line.<br />\nAlso, you can have one Makefile for both of your tools since they are part of the same package.<br />\nIt is a very useful automation system any developer should have in their arsenal.</p>\n</li>\n<li><p>If you really intend to distribute your program for Linux, you will probably want to learn the basics of packaging <a href=\"https://linuxconfig.org/easy-way-to-create-a-debian-package-and-local-package-repository\" rel=\"noreferrer\">deb</a> or <a href=\"https://developers.redhat.com/blog/2019/03/18/rpm-packaging-guide-creating-rpm/\" rel=\"noreferrer\">rpm</a>.</p>\n</li>\n<li><p>Consider using better <a href=\"https://en.wikipedia.org/wiki/Inter-process_communication\" rel=\"noreferrer\">IPC</a>.<br />\nSearching for background process with <code>pgrep</code> every time is both inefficient and cumbersome.<br />\nConsider instead having the process create a &quot;lock&quot; or &quot;flag&quot; file with a fixed name in a fixed path while it is running and delete it on exit.<br />\nYou can then easily and quickly test for this file both from BASH and C.<br />\nAlso, instead of forcefully killing the processes use <a href=\"https://en.wikipedia.org/wiki/Signal_(IPC)\" rel=\"noreferrer\">signals</a>.<br />\nFinally, if you are going to communicate between C programs, such as a daemon and a client (for sending commands to the daemon), consider using <a href=\"https://en.wikipedia.org/wiki/Unix_domain_socket\" rel=\"noreferrer\">sockets</a>.\nThere is even a <a href=\"https://unix.stackexchange.com/questions/26715/how-can-i-communicate-with-a-unix-domain-socket-via-the-shell-on-debian-squeeze\">way use them from BASH</a>, though it is less convenient and more limited.</p>\n</li>\n</ol>\n<p>I don't have suggestions for fixing your WiFi control issues, and I think that question is more suitable for stackoverflow than this site, but you should consider one thing:<br />\nPerhaps refactoring your application in to a <a href=\"https://medium.com/@benmorel/creating-a-linux-service-with-systemd-611b5c8b91d6\" rel=\"noreferrer\">system service</a> will solve that problem, and make it more streamlined and efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T01:33:36.763", "Id": "496841", "Score": "0", "body": "Thank you for the response. First, when you say a \"lock\" or \"flag\" file instead of `pgrep`, are you referring to just a normal file? I ask because a quick search of lock files brings up the linux command `lockfile()` which creates a semophore file. Second, if I were to choose a fixed path, is there a recommended location (e.g. in the same directory as the source code vs in a tmp folder) or is the decision arbitrary? Third, when you say to use signals vs forcefully killing the process, do you mean using the `kill` syscall in the form `int kill(pid_t pid, int sig)` or some other method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T12:53:50.070", "Id": "496875", "Score": "1", "body": "@NNNComplex 1. I mean a regular file. Here is how `apt` does it to prevent two or more copies of it self running at the same time: https://itsfoss.com/could-not-get-lock-error/ You can also write your process PID inside this file (it is just a number), so that you can easily communicate with it via `kill`. I am not familiar with a specific convention on where to place these files so consider the advantages and disadvantages of any location and decide yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T12:55:11.070", "Id": "496876", "Score": "1", "body": "@NNNComplex 2. `kill` syscall is the way to send signals to process, but you also need code to \"trap\" signals on the other side. The `kill` and similar commands are just wrappers around `kill` syscall, and can take a parameter of what signal to send. By default `kill`, `pkill`, and `killall` commands send `kill` signal, but they can send any signal." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T22:24:03.027", "Id": "252216", "ParentId": "252204", "Score": "10" } }, { "body": "<p>We can use plain POSIX <code>/bin/sh</code>. The only Bashism I see is</p>\n<pre><code>if [[ &quot;$OSTYPE&quot; == &quot;linux-gnu&quot;* ]]; then\nelif [[ &quot;$OSTYPE&quot; == &quot;darwin&quot;* ]]; then\nfi\n</code></pre>\n<p>This is in any case more naturally expressed as</p>\n<pre><code>case &quot;$(uname -s)&quot; in\n Linux)\n ;;\n Darwin) # fill in actual value here\n ;;\nesac\n</code></pre>\n<p>It would be good for the first of these to error-exit the script if there's no match.</p>\n<p>Given that the implementations of the functions are generally completely different for each platform, I'd restructure to define them independently for each platform:</p>\n<pre><code>case &quot;$(uname -s)&quot; in\n Linux)\n status() { ... }\n\n isactive() { ... }\n\n ;;\n Darwin)\n status() { ... }\n\n isactive() { ... }\n\n ;;\nesac\n</code></pre>\n<p>If we do this, we shouldn't need the <code>$wifion</code> variable - just arrange for <code>status</code> to exit with the appropriate return value:</p>\n<pre><code> status() {\n ip link show enp0s3 | sed 1q | grep -qF 'state UP'\n }\n</code></pre>\n<hr />\n<p>In the C code, I see no point creating <code>PLATFORM_NAME</code> macro and the <code>os</code> string, that we then only ever use to compare against fixed values. Why not simply use the existing boolean macros? E.g. instead of</p>\n<blockquote>\n<pre><code>if (!strcmp(os, &quot;apple&quot;)) {\n system(&quot;/bin/kill $(/usr/bin/pgrep -f checkon.sh) &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;);\n} else if (!strcmp(os, &quot;linux&quot;)) {\n system(&quot;/usr/bin/pkill checkon &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;);\n}\n</code></pre>\n</blockquote>\n<p>We could just</p>\n<pre><code>#if __APPLE__\n system(&quot;/bin/kill $(/usr/bin/pgrep -f checkon.sh) &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;);\n#elif __linux__\n system(&quot;/usr/bin/pkill checkon &gt;&gt;/dev/null 2&gt;&gt;/dev/null&quot;);\n#else\n#error This platform not yet supported\n#endif\n</code></pre>\n<p>Some minor nits:</p>\n<ul>\n<li>C reserves identifiers beginning with <code>is</code> and <code>str</code> for future library functions. So it's a bad idea to use such names in your code.</li>\n<li>The <code>getarg()</code> function is very duplicated - only a couple of lines need to vary between the platforms.</li>\n<li>Error messages should go to the error stream - <code>fprintf(stderr, ...)</code>. I'm pleased to see a non-zero exit in the error case, and recommend using the standard <code>EXIT_FAILURE</code> macro there.</li>\n<li>As mentioned in the other answer, C probably isn't the most appropriate choice for something that mainly invokes other programs. I'd suggest writing it all in shell.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T21:05:48.987", "Id": "496940", "Score": "0", "body": "Very helpful. Would you also recommend using the `EXIT_SUCCESS` macro as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:12:55.350", "Id": "497012", "Score": "1", "body": "Yes, absolutely." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:00:13.590", "Id": "252248", "ParentId": "252204", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T18:31:19.560", "Id": "252204", "Score": "10", "Tags": [ "beginner", "c", "bash", "linux", "macos" ], "Title": "Wi-fi scheduler written in C" }
252204
<p>I have a method that received a list of CoordinateBE : <strong>setExits(..)</strong></p> <p>I want to update the existing coordinates list with a new coordinate only if there is no coordinate in the current list that has the same latitude and longitude.</p> <p><strong>Example</strong>:</p> <p>List: [Coordinate: lat:23, long:24, Coordinate: lat:34, long:24]</p> <p>I am trying to add a new Coordinate: Coordinate: lat:23, long: 24 ---&gt; this one I cannot add it because already exists in the list.</p> <p>My implementation is working, but I was wondering if I can improve it, for example through lambda expressions, etc. Do you have any ideas?</p> <p>// setter</p> <pre><code> public void setExits(final List&lt;CoordinateBE&gt; exits) { if (getExits().isEmpty()) { this.exits = exits; } else { if (!existenceOfCoordinates(getExits(), exits)) { final List&lt;CoordinateBE&gt; result = new ArrayList&lt;&gt;(); result.addAll(getExits()); result.addAll(exits); this.exits = result; } } } </code></pre> <p>//getter</p> <pre><code> public List&lt;CoordinateBE&gt; getExits() { return exits; } </code></pre> <p>// existenceOfCoordinates</p> <pre><code> private boolean existenceOfCoordinates(final List&lt;CoordinateBE&gt; existingCoordinates, final List&lt;CoordinateBE&gt; currentCoordinates) { for (final CoordinateBE existingCoordinate : existingCoordinates) { for (final CoordinateBE currCoordinateBE : currentCoordinates) { if (compareCoordinates(existingCoordinate, currCoordinateBE)) { return false; } } } return true; } </code></pre> <p>// compareCoordinates</p> <pre><code> private boolean compareCoordinates(final CoordinateBE existingCoordinate, final CoordinateBE newCoordinate) { return existingCoordinate.getLatitude().equals(newCoordinate.getLatitude()) &amp;&amp; existingCoordinate.getLongitude().equals(newCoordinate.getLongitude()); } </code></pre>
[]
[ { "body": "<p>Why do you recreate <code>this.exits</code> every time you add new items? This:</p>\n<pre class=\"lang-java prettyprint-override\"><code> final List&lt;CoordinateBE&gt; result = new ArrayList&lt;&gt;();\n result.addAll(getExits());\n result.addAll(exits);\n this.exits = result;\n</code></pre>\n<p>could be simplified to</p>\n<pre class=\"lang-java prettyprint-override\"><code> this.exits.addAll(exits);\n</code></pre>\n<hr />\n<p>If coordinates are always meaningfully equal based on latitude + longitude, you may want to override <code>equals()</code> and <code>hashCode()</code> so that so you can better leverage built-in methods. With an overrided <code>equals()</code>, you would not need <code>compareCoordinates</code>, and <code>existenceOfCoordinates</code> could be replaced with collection methods.</p>\n<p>For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private boolean existenceOfCoordinates2(List&lt;CoordinateBE&gt; a, List&lt;CoordinateBE&gt; b) {\n return b.stream().anyMatch(a::contains);\n}\n</code></pre>\n<hr />\n<p>With the above simplifications, (I'll skip the <code>equals()</code> override in case you actually don't want that), it's distilled down to:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public void setExits(final List&lt;CoordinateBE&gt; exits) {\n if (!getExits().isEmpty()) {\n // Check that no new exits are already in the list\n for (CoordinateBE exit : getExits()) {\n if (exits.stream().anyMatch(x -&gt; compareCoordinates(x, c))) {\n return;\n }\n }\n }\n\n this.exits.addAll(exits);\n}\n\n\n// If CoordinateBE overrides equals(), you could also do:\n\npublic void setExits(final List&lt;CoordinateBE&gt; exits) {\n // In this case, I'm not checking whether this.exits is empty, because\n // we're streaming the new exits as opposed to the current, and that stream\n // will just be empty if the new exits are empty.\n if (exits.stream().anyMatch(this.exits::contains)) {\n return;\n }\n this.exits.addAll(exits);\n}\n</code></pre>\n<hr />\n<p>Finally, I am assuming that order is important here, which is why you're using a List as opposed to a Set. Even so, if you're okay with overriding <code>equals()</code> and if duplicates are not allowed, using a <code>LinkedHashSet</code> for <code>this.exits</code> would likely be faster beyond lists of a few dozen elements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T08:13:33.447", "Id": "496855", "Score": "0", "body": "I tried this method \n\npublic void setExits(final List<CoordinateBE> exits) {\n if (exits.stream().anyMatch(this.exits::contains)) {\n return;\n }\n this.exits.addAll(exits);\n}" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T08:15:17.607", "Id": "496856", "Score": "0", "body": "But it is not working properly. I created a unit test, and I received: \n\njava.lang.AssertionError: [The entrances are the expected ones] \nExpecting:\n <\"23.0,24.0, 21.0,22.0, 23.0,24.0, 23.0,24.0\">\nto be equal to:\n <\"23.0,24.0, 21.0,22.0\">\nignoring case considerations" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T21:46:47.707", "Id": "252214", "ParentId": "252205", "Score": "2" } }, { "body": "<p><strong>Getters and setters for collections can be dangerous if not implemented correctly</strong></p>\n<p>First of all, getters exist for external code to access the internal fields in your class. The code in your class should not rely on them to access it's own internal data structures. Always refer to the field directly with <code>this.exits</code> instead of using <code>getExits()</code>.</p>\n<p>Because you use the <code>getExits()</code> method from within the class you allow others to break your implementation by overloading the <code>getExits()</code> method and returning a manipulated list. In general, if your algorithm relies on specific functionality of it's own <code>public</code> methods, those methods should be made <code>final</code>.</p>\n<p>Because the <code>getExits()</code> method returns the object reference directly, it exposes it's internal data structure for other classes to modify and accidentally break. Some other class may now call your <code>getExits()</code> method and pass the list to some other completely unrelated code that deletes or add entries to it. Now your object no longer contains the coordinates you intended. That kind of bugs can be a bit hard to trace. Getters that expose internal data structures should be written to use unmodifiable lists instead:</p>\n<pre><code>public List&lt;CoordinateBE&gt; getExits() {\n return Collections.unmodifiableList(exits);\n}\n</code></pre>\n<p>This is still not a 100% fool proof method, because the underlyig <code>exits</code> list is still shared by your class and the caller. While the caller can not modify the list, the list can still be modified by your class without the knowledge of the caller, which may cause surprising bugs in the caller. To prevent that you need to create a copy of the list, but that comes with a performance penalty if your lists are large or the getter is called repeatedly.</p>\n<p>Same applies to your setter as you're directly storing the incoming list reference to the internal field. Now you're again sharing the same list entity in two different parts of code. The setter should always copy the entries to an internal list.</p>\n<pre><code>this.exits = new ArrayList&lt;&gt;(exits);\n</code></pre>\n<p><strong>Setters have a specific and well defined functionality</strong></p>\n<p>The intended purpose of setter methods is to discard whatever existing value the object had in the specific field and replace it with the provided value. Your setter method breaks this contract as it adds values to the <code>exits</code>-list instead. Thus the setter should be named something else, such as <code>addExits(...)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T06:04:17.367", "Id": "252229", "ParentId": "252205", "Score": "2" } } ]
{ "AcceptedAnswerId": "252229", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T18:32:09.537", "Id": "252205", "Score": "4", "Tags": [ "java" ], "Title": "Setter method for an object using a special logic" }
252205
<p>I'm a new self taught &quot;programmer&quot; that has been given the task at my job to parse through generated .txt test records and insert the data into a database. Usually when given a task like this I just hack together something that works, but I want to get better at creating smarter code.</p> <p>Basically, the program generates a list of log files from a folder. It then loops through that list of files and reads, parses, and inserts new data into the database, ignoring previously inserted data along the way. I'm using Entity Framework to handle the database bits. My database is split into 4 tables, <code>BoardType</code>, <code>UUT</code>, <code>TestRecord</code>, and <code>TestStep</code>, with <code>BoardType</code> being the top-most &quot;level&quot; and the other tables referencing the previous one going down the list.</p> <p>The <code>ReadFile</code> method starts off the process, it reads through the file line by line until it detects that a record is complete, then it takes those lines and processes them as a chunk using <code>ParseRecord</code>, parsing data into the database object attributes. This then calls the <code>InsertIntoDatabase</code> method, which checks to see if the objects already exist in the database, and inserts them if not. The <code>TestStep</code> objects are handled differently, being collected in a list of up to 250,000 objects and bulk inserting them all at once. This process then repeats until it's read through all of the logs files.</p> <pre><code>using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity.Infrastructure; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using EntityFramework.BulkInsert.Extensions; using SimpleLogger; namespace FP2DB_EF { public class Program { List&lt;string&gt; TestRecordLines = new List&lt;string&gt;(); List&lt;TestStep&gt; TestSteps = new List&lt;TestStep&gt;(); List&lt;TestStep&gt; lastTestSteps = new List&lt;TestStep&gt;(); BoardType board = new BoardType(); UUT uut = new UUT(); TestRecord testRecord = new TestRecord(); TestRecord lastTestRecord = new TestRecord(); UUT lastUUT = new UUT(); BoardType lastBoard = new BoardType(); string[] fileArray = Directory.GetFiles(@&quot;...&quot;, &quot;*....&quot;); // Grabs acceptable products from config file for easy editing string[] productDesignators = ConfigurationManager.AppSettings[&quot;des&quot;].Split(','); Stopwatch sw = new Stopwatch(); FPContext db = new FPContext(); List&lt;TestStep&gt; bulkTestSteps = new List&lt;TestStep&gt;(); int insertCounter = 0; static void Main(string[] args) { SimpleLog.SetLogFile(logDir: &quot;.\\Log&quot;, prefix: &quot;ErrorLog_&quot;, writeText: false, check: false); Program program = new Program(); Console.WriteLine(&quot;Press any key to begin storing data.&quot;); Console.ReadKey(); Stopwatch totalTime = new Stopwatch(); totalTime.Restart(); Console.WriteLine(&quot;Running...&quot;); // Main production loop foreach (string file in program.fileArray) { foreach (string designator in program.productDesignators) { if (Path.GetFileNameWithoutExtension(file).Contains(designator)) { program.ReadFile(file); } } } totalTime.Stop(); Console.WriteLine(totalTime.Elapsed); Console.WriteLine(&quot;\nFINISHED - Data stored in ... database.&quot;); Console.WriteLine(&quot;\nPress any key to exit..&quot;); Console.ReadKey(); } public void InsertIntoDatabase() { sw.Restart(); if (board.Board_Model != lastBoard.Board_Model || board.Board_Rev != lastBoard.Board_Rev) { if (!db.BoardTypes.Any(o =&gt; o.Board_Model == board.Board_Model &amp;&amp; o.Board_Rev == board.Board_Rev)) { db.BoardTypes.Add(board); try { db.SaveChanges(); } catch (Exception e) { Console.WriteLine(&quot;Ran into error when trying to save BoardType to database. Data logged, continuing.&quot;); SimpleLog.Error($@&quot;SaveChanges threw exception {e.Message}. BoardType is {board.Board_Model} and {board.Board_Rev}&quot;); } } else { board = db.BoardTypes.SingleOrDefault(o =&gt; o.Board_Model == board.Board_Model &amp;&amp; o.Board_Rev == board.Board_Rev); uut.FK_BOARD_ID = board.Board_ID; } } else { board = lastBoard; } if (uut.UUT_SN != lastUUT.UUT_SN) { if (!db.UUTs.Any(o =&gt; o.UUT_SN == uut.UUT_SN &amp;&amp; o.FK_BOARD_ID == board.Board_ID)) { uut.FK_BOARD_ID = board.Board_ID; board.UUTs.Add(uut); db.UUTs.Add(uut); try { db.SaveChanges(); } catch (Exception e) { Console.WriteLine(&quot;Ran into error when trying to save UUT to database. Data logged, continuing.&quot;); SimpleLog.Error($@&quot;SaveChanges threw exception {e.Message}. UUT is {uut.UUT_SN}&quot;); } } else { uut = db.UUTs.SingleOrDefault(o =&gt; o.UUT_SN == uut.UUT_SN &amp;&amp; o.FK_BOARD_ID == board.Board_ID); testRecord.FK_UUT_ID = uut.UUT_ID; } } else { uut = lastUUT; } if (!db.TestRecords.Any(o =&gt; o.TR_OverallResult == testRecord.TR_OverallResult &amp;&amp; o.TR_TestDate == testRecord.TR_TestDate &amp;&amp; o.FK_UUT_ID == uut.UUT_ID)) { testRecord.FK_UUT_ID = uut.UUT_ID; uut.TestRecords.Add(testRecord); db.TestRecords.Add(testRecord); try { db.SaveChanges(); } catch (Exception e) { Console.WriteLine(&quot;Ran into error when trying to save TestRecord to database. Data logged, continuing.&quot;); SimpleLog.Error($@&quot;SaveChanges threw exception {e.Message}. TestRecord is Date: {testRecord.TR_TestDate} and Result: {testRecord.TR_OverallResult} and Side: {testRecord.TR_Side}&quot;); } foreach (TestStep ts in TestSteps) { ts.FK_TR_ID = testRecord.TR_ID; bulkTestSteps.Add(ts); } } else { // Separated comparison for debug bool stepComparison = lastTestSteps == TestSteps; // This solves the issue where sometimes 2 test records have the same overall result and test date. This should not happen more than once. if (lastTestRecord.TR_OverallResult == testRecord.TR_OverallResult &amp;&amp; lastTestRecord.TR_TestDate == testRecord.TR_TestDate &amp;&amp; !stepComparison &amp;&amp; db.TestRecords.Count(o =&gt; o.TR_OverallResult == testRecord.TR_OverallResult &amp;&amp; o.TR_TestDate == testRecord.TR_TestDate) == 1) { testRecord.FK_UUT_ID = uut.UUT_ID; uut.TestRecords.Add(testRecord); db.TestRecords.Add(testRecord); try { db.SaveChanges(); } catch (Exception e) { Console.WriteLine(&quot;Ran into error when trying to save TestRecord to database. Data logged, continuing.&quot;); SimpleLog.Error($@&quot;SaveChanges threw exception {e.Message}. TestRecord is Date: {testRecord.TR_TestDate} and Result: {testRecord.TR_OverallResult} and Side: {testRecord.TR_Side}&quot;); } foreach (TestStep ts in TestSteps) { ts.FK_TR_ID = testRecord.TR_ID; bulkTestSteps.Add(ts); } } } lastBoard = board; lastUUT = uut; lastTestSteps = TestSteps.ToList(); lastTestRecord = testRecord; sw.Stop(); Console.WriteLine(sw.Elapsed + &quot; - &quot; + board.Board_Model); resetObjects(); // Refreshes context tracking of objects every 25 inserts, stops insert time from being bogged down by unnecessary tracking ++insertCounter; if (insertCounter == 25) { db = new FPContext(); insertCounter = 0; } } public void ReadFile(string path) { var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { int lineNumber = 1; string line; int counter = 0; List&lt;string&gt; errors = new List&lt;string&gt;(); while ((line = streamReader.ReadLine()) != null) { // Read line by line. After seeing a certain number of @ symbols, process the chunk of text that was read. if ((line == &quot;@&quot; &amp;&amp; counter == 2)) { if (!ParseRecord(TestRecordLines, ref errors, lineNumber)) { string errorMessage = GetErrors(errors, String.Format(&quot;in log file {0} in entry before line {1}&quot;, path, lineNumber)); Console.WriteLine(&quot;Error: Entry {0} missing metadata. Check error logs. Skipping database entry of missing record.&quot;, path); errors.Clear(); } counter = 1; TestRecordLines.Clear(); if (bulkTestSteps.Count &gt;= 250000) { db.BulkInsert(bulkTestSteps); bulkTestSteps.Clear(); } } else if (line == &quot;@&quot;) { TestRecordLines.Add(line); counter++; } else { TestRecordLines.Add(line); } ++lineNumber; } // Process last record when we hit the end of the file if (TestRecordLines.Count &gt; 0) { if (!ParseRecord(TestRecordLines, ref errors, lineNumber)) { string errorMessage = GetErrors(errors, String.Format(&quot;in log file {0} in entry before line {1}&quot;, path, lineNumber)); Console.WriteLine(&quot;Error: Entry {0} missing metadata. Check error logs. Skipping database entry of missing record.&quot;, path); errors.Clear(); } } } if (bulkTestSteps.Count &gt; 0) { db.BulkInsert(bulkTestSteps); bulkTestSteps.Clear(); } } public bool ParseRecord(List&lt;String&gt; record, ref List&lt;string&gt; errors, int line) { bool recordParsed = true; Dictionary&lt;string, string&gt; data = new Dictionary&lt;string, string&gt;(); data.Add(&quot;Overall Result&quot;, &quot;&quot;); data.Add(&quot;Board Model&quot;, &quot;&quot;); data.Add(&quot;Board Revision&quot;, &quot;&quot;); data.Add(&quot;Date&quot;, &quot;&quot;); data.Add(&quot;Serial Number&quot;, &quot;&quot;); data.Add(&quot;Test Side&quot;, &quot;&quot;); for (int i = 0; i &lt; record.Count; i++) { // Contains the overall test result surrounded by * if (record[i].StartsWith(&quot;*&quot;) &amp;&amp; i &lt;= 7) { data[&quot;Overall Result&quot;] = record[i].Trim('*').Trim(); testRecord.TR_OverallResult = data[&quot;Overall Result&quot;]; } else if (record[i].Split(':')[0].Trim().Contains(&quot;Model&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; i &lt;= 7) { data[&quot;Board Model&quot;] = record[i].Split(':')[1].Trim(); board.Board_Model = data[&quot;Board Model&quot;]; } else if (record[i].Split(':')[0].Trim().Contains(&quot;Revision&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; i &lt;= 7) { data[&quot;Board Revision&quot;] = record[i].Split(':')[1].Trim(); board.Board_Rev = data[&quot;Board Revision&quot;]; } else if (record[i].Split(':')[0].Trim().Contains(&quot;Side&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; i &lt;= 7) { data[&quot;Test Side&quot;] = record[i].Split(':')[1].Trim(); testRecord.TR_Side = data[&quot;Test Side&quot;]; } else if (record[i].Split(':')[0].Trim().Contains(&quot;Date&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; i &lt;= 7) { DateTime date; data[&quot;Date&quot;] = record[i].Split(new char[] { ':' }, 2)[1].Trim(); if (DateTime.TryParse(data[&quot;Date&quot;], out date)) { testRecord.TR_TestDate = date; } } else if (record[i].Split(':')[0].Trim().Contains(&quot;Serial&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; i &lt;= 7) { data[&quot;Serial Number&quot;] = record[i].Split(':')[1].Trim().TrimEnd('^'); if (data[&quot;Serial Number&quot;] == null) { uut.UUT_SN = &quot; &quot;; } else { uut.UUT_SN = data[&quot;Serial Number&quot;]; } } else if (i &gt;= 8 &amp;&amp; Utilities.IsNumeric(record[i].Split(',')[0])) { try { string[] TestStepData = record[i].Split(','); // Log files must be in this order to put data in proper columns, edit test programs that don't use this format TestStep ts = new TestStep { TS_Order = int.Parse(TestStepData[0]), TS_Parts = TestStepData[1], TS_Value = TestStepData[2], TS_Comment = TestStepData[3], TS_Func = TestStepData[4], TS_HPin = TestStepData[5], TS_LPin = TestStepData[6], TS_GP1 = TestStepData[7], TS_GP2 = TestStepData[8], TS_Netname1 = TestStepData[9], TS_Netname2 = TestStepData[10], TS_Netname3 = TestStepData[11], TS_Netname4 = TestStepData[12], TS_StepResult = TestStepData[13], TS_Element = TestStepData[14], TS_Reference = TestStepData[15], TS_Test1 = TestStepData[16], TS_Test2 = TestStepData[17], TS_BMComment = TestStepData[18] }; TestSteps.Add(ts); } catch (IndexOutOfRangeException e) { SimpleLog.Error(String.Format(&quot;{0} in log for board {1} on record before line {2}. Relative record line: {3}&quot;, e.Message, data[&quot;Board Model&quot;], line, i)); File.AppendAllText(@&quot;.\\linelogs.txt&quot;, String.Format(&quot;{0} - {1}{2}&quot;, data[&quot;Board Model&quot;], ((line - record.Count) + i).ToString(), Environment.NewLine)); } } } foreach (KeyValuePair&lt;string, string&gt; entry in data) { if (String.IsNullOrEmpty(entry.Value) &amp;&amp; entry.Key != &quot;Test Side&quot;) { errors.Add(entry.Key); if (entry.Key != &quot;Test Side&quot; &amp;&amp; entry.Key != &quot;Serial Number&quot;) { recordParsed = false; } } } if (recordParsed) InsertIntoDatabase(); } void resetObjects() { TestRecordLines.Clear(); TestSteps.Clear(); board = new BoardType(); uut = new UUT(); testRecord = new TestRecord(); } private string GetErrors(List&lt;String&gt; ErrorList, string logMessage) { string errorString = &quot;&quot;; foreach (string error in ErrorList) { errorString += String.Format(&quot;{0} missing{1}&quot;, error, Environment.NewLine); } SimpleLog.Error(errorString + logMessage); return errorString; } } public static class StringExtensions { public static bool Contains(this string source, string toCheck, StringComparison comp) { return source?.IndexOf(toCheck, comp) &gt;= 0; } } } </code></pre> <p>Here is what I would like to know:</p> <ol> <li>Is there a way my code should process records that is more efficient than how I am handling it? I need the functionality of checking existing database records and only inserting new ones, which unfortunately means lots of calls to the database. Right now the <code>TestStep</code> table has about 29 million records in it, and it takes almost 20 minutes just to check existing records, which will only get longer as more records are added. Once I know the program is stable I can start archiving these .txt files to bring the time down, but for now I would like to make it as efficient as possible.</li> <li>I want to get better at breaking up my code into smaller chunks, rather than having long methods or classes that do many things. This is a concept I have really been struggling with, knowing how to split methods and classes up like this. As a specific example on this program, would it make sense to put parsing functionality and file reading functionality into their own classes? How would you split up this program using a more object oriented mindset? I want to make sure the base design is good before I go further, and I want to increase readability for anyone in the future that may have to work with this code.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T02:21:33.183", "Id": "496843", "Score": "0", "body": "Might be easier if your sample application was in a GitHub repository." } ]
[ { "body": "<p>I didn't look too closly at your code I must admit. But some pointers.</p>\n<p><strong>1) Seperate parsing and domain logic + CRUD.</strong></p>\n<p>Parse the file to a POCO, send this POCO to the domain for processing</p>\n<p><strong>2) Have a nice way of the domain to setup the parsing</strong></p>\n<p>Personally when I have done this I have used fluent mapping similar to what EF does. Example from a flatfile parser I have made</p>\n<pre><code>public class AgreementRequestConfig : IFlatFileTypeConfiguration&lt;AgreementRequestFile&gt;\n {\n public void Configure(IFlatFileTypeBuilder&lt;AgreementRequestFile&gt; builder)\n {\n var header = builder\n .Map(&quot;01&quot;, ar =&gt; ar.Agreements)\n .Property(a =&gt; a.CreatedUTC)\n .Format(&quot;yyyyMMdd&quot;)\n .Property(a =&gt; a.LayoutName)\n .Length(8)\n .Pad(44)\n .Property(a =&gt; a.BgcCustomerNumber)\n .Length(6)\n .Property(a =&gt; a.ReceiverBgcNumber)\n .Length(10)\n .Pad(2);\n\n header\n .HasMany(&quot;03&quot;, a =&gt; a.CancelRequests)\n .Property(r =&gt; r.ReceiverBgcNumber)\n .Length(10)\n .Property(r =&gt; r.PayerNumber)\n .Length(16)\n .Pad(52);\n\n header\n .HasMany(&quot;04&quot;, a =&gt; a.Requests)\n .Property(r =&gt; r.ReceiverBgcNumber)\n .Length(10)\n .Property(r =&gt; r.PayerNumber)\n .Length(16)\n .Property(r =&gt; r.PayerAccountNumber)\n .Length(16)\n .Property(r =&gt; r.PayerPartyNumber)\n .Length(12)\n .Pad(20)\n .Pad(2)\n .Pad(2);\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:01:12.823", "Id": "497034", "Score": "0", "body": "I don't know most of these terms (POCO, CRUD), but have been googling them and am getting a better understanding. The only one I am having issues finding information on is the \"domain\". Could you give a short explanation on what the domain is or point me to a resource? Is this the part of my code that interacts with the database? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:27:58.747", "Id": "497058", "Score": "1", "body": "The domain is your core logic basicly. If you remove all frameworks, boiler code etc what's left is your domain, the essential stuff." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T10:44:50.770", "Id": "252240", "ParentId": "252213", "Score": "1" } } ]
{ "AcceptedAnswerId": "252240", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T21:19:26.793", "Id": "252213", "Score": "2", "Tags": [ "c#", "performance", "beginner", "entity-framework" ], "Title": "Parsing large text files into database" }
252213
<p>I'm relatively new to programming and I was trying to work a project.</p> <p>I would like recommendations of how to annotate or comment my project and any improvement I could make to it, any suggestion is welcome,</p> <pre><code>import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; public class Util { /*/ DOC Generation -&gt; XML with ArrayList String elements */ public Document docBuilder(ArrayList&lt;String[]&gt; elements) throws ParserConfigurationException { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder(); Document xmlDoc = xmlBuilder.newDocument(); Element rootElement = xmlDoc.createElement(&quot;root&quot;); xmlDoc.appendChild(rootElement); Element mainElement = xmlDoc.createElement(&quot;elements&quot;); rootElement.appendChild(mainElement); boolean headerDefined = false; //First while will be to define header String[] header = new String[elements.size()]; //Header initialization /*/ DOC Generation -&gt; XML Generation of every ELEMENT */ for (String[] node : elements) { //FOR every ArrayString if (headerDefined) { Element nodesElements = xmlDoc.createElement(&quot;element&quot;); mainElement.appendChild(nodesElements); for (int j = 0; j &lt; node.length; j++) { node[j] = node[j].replaceAll(&quot;\&quot;&quot;, &quot;&quot;).trim(); Element nodesValues = xmlDoc.createElement(header[j]); nodesElements.appendChild(nodesValues); Text nodeTxt = xmlDoc.createTextNode(node[j]); nodesValues.appendChild(nodeTxt); } } /*/ DOC Generation -&gt; Array Generation of every COL Name for NODES */ else { header = node; for (int k = 0; k &lt; node.length; k++) { header[k] = header[k].replaceAll(&quot;[^a-zA-Z0-9]&quot;, &quot;&quot;); //We want to make sure NODE isn't NUMERIC. If it is, we make a patch try { Integer.parseInt(header[k]); header[k] = &quot;node&quot; + header[k]; } catch (NumberFormatException e) { } } headerDefined = true; } } return (xmlDoc); } /*/ XML Generation -&gt; Transform DOC Data to XML Format */ public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException { TransformerFactory xmlTransformerFactory = TransformerFactory.newInstance(); Transformer xmlTransformer = xmlTransformerFactory.newTransformer(); xmlTransformer.setOutputProperty(OutputKeys.INDENT, &quot;yes&quot;); xmlTransformer.setOutputProperty(OutputKeys.METHOD, &quot;xml&quot;); xmlTransformer.setOutputProperty(OutputKeys.ENCODING, &quot;UTF-8&quot;); xmlTransformer.setOutputProperty(&quot;{http://xml.apache.org/xslt}indent-amount&quot;, &quot;4&quot;); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream((new File(xmlFile))); } catch (FileNotFoundException e) { e.printStackTrace(); } xmlTransformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream)); } } </code></pre> <p><a href="https://github.com/codepressed/JAVACSVtoXMLConverter" rel="nofollow noreferrer">https://github.com/codepressed/JAVACSVtoXMLConverter</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T02:46:12.723", "Id": "496845", "Score": "3", "body": "This doesn't seem to be a CSV to XML converter. It's just the part of the converter that writes the XML. If you're not going to include more of the program (which might be better), you should retitle. E.g. to Write tabular data to XML. Note that your program doesn't seem that long. You could probably fit the whole thing in the post. A usage example would also be helpful. Either the code that calls these methods with sufficient context that it will run or if you add the rest of the program, show an example command line." } ]
[ { "body": "<p><strong>Line by line analysis</strong></p>\n<pre><code>public class Util {\n</code></pre>\n<p>Util is not a good class name. It does not describe what the responsibility or function of the class is. If it did, it would describe the <em>top desktop drawer of code</em>, where all random code snippets are dumped because the authors could not be bothered to think of a proper place. Suffice to say, those kinds of classes don't exist in well maintained code bases. Use something like <code>TabularToXmlConverter</code> instead.</p>\n<pre><code>/*/\nDOC Generation -&gt; XML with ArrayList String elements\n */\n</code></pre>\n<p>You should have an extremely good reason for creating your own specialized format for documenting your classes and methods. Java platform comes with <a href=\"https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html\" rel=\"nofollow noreferrer\">JavaDoc</a> which is a standardized way of formatting documentation. Programmers know how to read it and expect to see it. When encountered with your style they literally get angry because they have to learn a new (and most likely inferior) format.</p>\n<pre><code>DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();\nDocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();\n</code></pre>\n<p>Because your method created the <code>DocumentBuilderFactory</code>, it became responsible for managing it's own dependencies. If you wanted to use the converter to create a bit different kind of XML document, you couldn't do it without changing the class and breaking all code that already uses it. You might want to pass a <code>DocumentBuilder</code> reference to the class and thus employ <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a>.</p>\n<pre><code>Document xmlDoc = xmlBuilder.newDocument();\n</code></pre>\n<p>What is the reason why you build the document in memory? Most often when I have worked with XML, the biggest problem has been memory consumption caused by handling large XML documents that have been loaded into memory. Since you also provided a <code>transformDocToFile</code> it might make more sense to just write the document directly to an OutputStream using the <a href=\"https://docs.oracle.com/javase/7/docs/api/javax/xml/stream/XMLStreamWriter.html\" rel=\"nofollow noreferrer\">Streaming API for XML</a> (StAX).</p>\n<pre><code>boolean headerDefined = false; //First while will be to define header\n</code></pre>\n<p>Do not use end-of-line comments. They are difficult to read, hard to maintain and force you to compress your thoughts into fewer words that make sense. I, for example, have no idea what this comment means. And you should strive to use variable names that describe the purpose of the variable. From the variable name alone I already guessed it's a flag that tells if the header row has been generated. So there isn't any need for a comment here at all. The other end-of-line comments also just tell what the preceding code does adding no additional value. Comments should desribe why something is being done, not repeat what the code already tells. If the code isn't clear, first priority should be making it clearer instead of duplicating it in free verse.</p>\n<pre><code>public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException {\n</code></pre>\n<p>One of your methods is static and the other is not, requiring the caller to create an unnecessary instance of the Util-class.</p>\n<pre><code> } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n</code></pre>\n<p>You catch one of the possible exceptions and continue happily even though in this particular case you cannot even write to the file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T08:13:53.080", "Id": "252293", "ParentId": "252215", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T22:03:48.300", "Id": "252215", "Score": "2", "Tags": [ "java", "beginner", "csv", "xml", "dom" ], "Title": "Java CSV to XML converter" }
252215
<p>I am solving a problem for Hackerrank where I have to count the number of palindromes in a given string.</p> <p>I have the following code which counts the number of palindromes accurately but times out for large strings. How do I make the code more time-efficient?</p> <pre><code>def countPalindromes(s): num_palindrome = 0 for i in range(len(s)): for j in range(i + 1, len(s) + 1): substring = s[i: j] if len(substring) == 1: num_palindrome += 1 else: for idx in range(len(substring)): if substring[idx] != substring[-idx-1]: num_palindrome -= 1 break num_palindrome += 1 return num_palindrome </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T03:30:31.967", "Id": "496846", "Score": "2", "body": "@BCdotWEB Yes those are very useful :) [Here](https://meta.stackexchange.com/questions/92060/add-data-se-style-magic-links-to-comments) is the list" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T13:32:53.243", "Id": "496885", "Score": "1", "body": "Why can't you give us the link to the problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:33:03.780", "Id": "496891", "Score": "1", "body": "@superbrain I found the same problem on [LeetCode](https://leetcode.com/problems/palindromic-substrings)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T15:08:59.760", "Id": "496898", "Score": "0", "body": "@Marc That might have different input size limits, time/memory limits, and test cases, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T15:25:45.910", "Id": "496900", "Score": "0", "body": "@Marc Oh and different allowed characters, too. For example if it's only letters, then RootTwo's solution could replace `j>=0 and k<len(s)` with sentinels, like with `s = '[' + s + ']' at the start. That would make it faster, but whether that's possible depends on the allowed input characters." } ]
[ { "body": "<p>For each position in the string your code checks all substrings that start at that position. For example, for s = 'a2b3bb3443bab' and <code>i</code> = 3, the code checks '3', '3b', '3bb', '3bb3', ..., '3bb3443bab'. That is O(n^2) strings to palindrome check.</p>\n<p>Instead, for each position in the string, check for palindomes that are centered on that position. For example, for s = 'a2b3bb3443bab' and <code>i</code> = 3, check the substrings '3', 'b3b', and '2b3bb'. Stop there, because no other string centered on i = 3 can be a palindrome. It also needs to check for palindromes with an even length such as at i = 4, where we check 'bb', '3bb3' and stop at 'b3bb34'. I think it's O(n*p) where p is the average length of a palindrome (which is less than n). It seems to take about 2/3 as long as you code.</p>\n<pre><code>def pcount(s):\n count = 0\n \n for i in range(len(s)):\n # count the odd-length palindromes\n # centered at s[i]\n j=i\n k=i\n while j&gt;=0 and k&lt;len(s) and s[j] == s[k]:\n count += 1\n j -= 1\n k += 1\n\n # count the even-length palindromes\n # centered at s[i:i+1]\n j = i\n k = i + 1\n while j&gt;=0 and k&lt;len(s) and s[j] == s[k]:\n count += 1\n j -= 1\n k += 1\n\n return count\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T13:30:12.183", "Id": "496883", "Score": "1", "body": "How did you measure to get \"2/3\"? I'd expect a better improvement from switching from O(n^3) to O(n^2)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T15:58:20.260", "Id": "496907", "Score": "0", "body": "I just used the %timeit magic in a Jupyter notebook. But I only ran it on fairly short strings (upto 15-20 chars)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T08:36:46.800", "Id": "252234", "ParentId": "252218", "Score": "3" } }, { "body": "<p>Welcome to Code Review. @RootTwo already provided a more efficient approach. I'll add a couple of suggestions about your code:</p>\n<ul>\n<li><strong>Naming</strong>: <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">prefer underscores for function names</a>. <code>count_palindromes</code> instead of <code>countPalindromes</code>.</li>\n<li><strong>Checking if a string is palindrome</strong>: this part:\n<pre><code>if len(substring) == 1:\n num_palindrome += 1\nelse:\n for idx in range(len(substring)):\n if substring[idx] != substring[-idx-1]:\n num_palindrome -= 1\n break\n num_palindrome += 1\n</code></pre>\nCan be shorten to:\n<pre><code>if substring == substring[::-1]:\n num_palindrome += 1\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T08:51:42.863", "Id": "252236", "ParentId": "252218", "Score": "1" } }, { "body": "<p>Your</p>\n<pre><code> if len(substring) == 1:\n num_palindrome += 1\n else:\n</code></pre>\n<p>is unnecessary, as the code in the <code>else</code> part can handle single-character substrings as well. Ok, you make that special case faster, but you're making <em>all other cases slower</em>. And there are more of the latter. So this optimization attempt might very well make the solution as a whole <em>slower</em>.</p>\n<p>If you <em>do</em> want to avoid the innermost checking for single-character substrings, an easy and faster way is to start <code>j</code> at <code>i + 2</code> instead of <code>i + 1</code> (and initialize with <code>num_palindrome = len(s)</code> to make up for it, i.e., &quot;count&quot; the single-character substrings in advance).</p>\n<p>A short solution based on <a href=\"https://codereview.stackexchange.com/a/252234/228314\">RootTwo's</a>:</p>\n<pre><code>from os.path import commonprefix\n\ndef count_palindromes(s):\n return sum(len(commonprefix((s[i::-1], s[k:])))\n for i in range(len(s))\n for k in (i, i+1))\n</code></pre>\n<p>Demo:</p>\n<pre><code>&gt;&gt;&gt; count_palindromes('foo')\n4\n&gt;&gt;&gt; count_palindromes('mississippi')\n20\n</code></pre>\n<p>The latter are:</p>\n<ul>\n<li>11 palindromes of length 1</li>\n<li>3 palindromes of length 2</li>\n<li>1 palindrome of length 3</li>\n<li>3 palindromes of length 4</li>\n<li>1 palindrome of length 5</li>\n<li>1 palindrome of length 7</li>\n</ul>\n<p>(Pretty nice test case for correctness, I think.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:58:21.147", "Id": "252250", "ParentId": "252218", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T23:27:37.310", "Id": "252218", "Score": "4", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Hackerrank: Count the number of palindromes in a given string" }
252218
<p>This is a pretty simple working example using React-Redux to select a user from <code>app.com/user/:userId</code> and then fetch/display that user's info from a remote API</p> <p>Most of the examples/code I can find online use class-based components but since I already have part of a project written using a functional approach I'm looking for feedback on how I'm integrating redux into functional components. I'm also not a Javascript expert by any means either so general critique of my JS is welcome as well!</p> <p>Store.js:</p> <pre><code>import { createStore } from &quot;redux&quot;; const initialUser = { user: [] }; const userReducer = (state = initialUser, action) =&gt; { switch (action.type) { case &quot;ADD_USER&quot;: return Object.assign({}, state, { user: action.user }); default: return state; } }; export default function Store() { return createStore(userReducer); } </code></pre> <p>Actions.js:</p> <pre><code>const validResp = (resp) =&gt; { return resp.data.code === 200; }; const extractUser = (resp) =&gt; { return resp.data.data; }; export const addUser = (resp) =&gt; { let user = &quot;&quot;; if (validResp(resp)) { user = extractUser(resp); } return { type: &quot;ADD_USER&quot;, user: user }; }; </code></pre> <p>index.js:</p> <pre><code>import React from &quot;react&quot;; import ReactDOM from &quot;react-dom&quot;; import { Provider } from &quot;react-redux&quot;; import { BrowserRouter as Router, Route } from &quot;react-router-dom&quot;; import AppContainer from &quot;./AppContainer&quot;; import Store from &quot;./Store&quot;; const rootElement = document.getElementById(&quot;root&quot;); ReactDOM.render( &lt;Provider store={Store()}&gt; &lt;Router&gt; &lt;Route path=&quot;/user/:userId&quot; component={AppContainer} /&gt; &lt;/Router&gt; &lt;/Provider&gt;, rootElement ); </code></pre> <p>AppContainer.js:</p> <pre><code>import React from &quot;react&quot;; import { useEffect } from &quot;react&quot;; import { useDispatch, useSelector } from &quot;react-redux&quot;; import { useParams } from &quot;react-router-dom&quot;; import axios from &quot;axios&quot;; import { addUser } from &quot;./Actions&quot;; const baseUrl = &quot;https://gorest.co.in/public-api/users/&quot;; export default function AppContainer() { const url = baseUrl + useParams().userId; const user = useSelector((state) =&gt; state.user); const dispatch = useDispatch(); useEffect(() =&gt; { axios.get(url).then((resp) =&gt; dispatch(addUser(resp))); }); return &lt;App user={user} /&gt;; } function App(props) { return ( &lt;div className=&quot;App&quot;&gt; Name: {props.user.name} &lt;br /&gt; id: {props.user.id} &lt;/div&gt; ); } </code></pre>
[]
[ { "body": "<p><strong>Concisely merging objects</strong> can be done with spread syntax instead of <code>Object.assign</code>. The <code>ADD_USER</code> case can use:</p>\n<pre><code>return { ...state, user: action.user };\n</code></pre>\n<p>Using spread syntax instead of <code>Object.assign</code> doesn't have a big impact here, but it makes things so much easier when the state structure grows to be large and complicated.</p>\n<p><strong>Functional programming does not reassign variables</strong> - everything should be declared with <code>const</code>. If you want to be more functional, change <code>addUser</code> to use the conditional operator to either assign the empty string or the <code>extractUser</code> result to the <code>user</code> variable:</p>\n<pre><code>export const addUser = (resp) =&gt; {\n const user = validResp(resp) ? extractUser(resp) : &quot;&quot;;\n return {\n type: &quot;ADD_USER&quot;,\n user\n };\n};\n</code></pre>\n<p>(Note that if the key is named the same as the variable the value is in, you can use shorthand property names like above. You could also return the whole object at once without declaring a <code>user</code> variable first.)</p>\n<p><strong><code>useEffect</code> bug</strong> Since you didn't provide a dependency array to <code>useEffect</code>, its callback will run <em>on every render</em>. I'm pretty sure this isn't desirable - you want it to run only on the initial render, right? Pass an empty dependency array to <code>useEffect</code> so that the callback inside only runs on mount:</p>\n<pre><code>useEffect(() =&gt; {\n axios.get(url).then((resp) =&gt; dispatch(addUser(resp)));\n}, []);\n</code></pre>\n<p><strong>Error handling</strong> If the <code>axios.get</code> Promise rejects, no indication is given. Always <code>.catch</code> Promises somewhere. You might want something like</p>\n<pre><code>useEffect(() =&gt; {\n axios.get(url)\n .then((resp) =&gt; dispatch(addUser(resp)))\n .catch((error) =&gt; dispatch(addError(error.message)));\n}, []);\n</code></pre>\n<p>or something of the sort, to show that an error occurred.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T03:09:05.730", "Id": "252224", "ParentId": "252219", "Score": "1" } } ]
{ "AcceptedAnswerId": "252224", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T23:42:06.927", "Id": "252219", "Score": "3", "Tags": [ "javascript", "functional-programming", "react.js", "redux" ], "Title": "React-Redux with functional Components" }
252219
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/252154/231235">Quuxplusone's answer</a> and G. Sliepen's comments. Based on the mentioned <code>std::vector&lt;std::vector&lt;std::string&gt;&gt;</code> case, it indicates a problem about the process of unwrapping nested iterable structure. In order to make <code>recursive_count_if</code> function be more generic, I am trying to implement another version of <code>recursive_count_if</code> template function with checking container's value_type matches specified type. The process of unwrapping nested iterable structure would keep running until the base type in container is as same as the given type <code>T1</code>.</p> <pre><code>// recursive_count_if implementation template&lt;class T1, class T2, class T3&gt; requires (is_iterable&lt;T2&gt; &amp;&amp; std::same_as&lt;std::iter_value_t&lt;T2&gt;, T1&gt;) auto recursive_count_if(const T2&amp; input, const T3 predicate) { return std::count_if(input.begin(), input.end(), predicate); } // transform_reduce version template&lt;class T1, class T2, class T3&gt; requires (is_iterable&lt;T2&gt; &amp;&amp; !std::same_as&lt;std::iter_value_t&lt;T2&gt;, T1&gt;) auto recursive_count_if(const T2&amp; input, const T3 predicate) { return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp; element) { return recursive_count_if&lt;T1&gt;(element, predicate); }); } </code></pre> <p>The test cases for this version <code>recursive_count_if</code> template function:</p> <pre><code>// std::vector&lt;std::vector&lt;int&gt;&gt; case std::vector&lt;int&gt; test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector&lt;decltype(test_vector)&gt; test_vector2; test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); // use a lambda expression to count elements divisible by 3. int num_items1 = recursive_count_if&lt;int&gt;(test_vector2, [](int i) {return i % 3 == 0; }); std::cout &lt;&lt; &quot;#number divisible by three: &quot; &lt;&lt; num_items1 &lt;&lt; '\n'; // std::deque&lt;std::deque&lt;int&gt;&gt; case std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(2); test_deque.push_back(3); std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); // use a lambda expression to count elements divisible by 3. int num_items2 = recursive_count_if&lt;int&gt;(test_deque2, [](int i) {return i % 3 == 0; }); std::cout &lt;&lt; &quot;#number divisible by three: &quot; &lt;&lt; num_items2 &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;std::string&gt;&gt; case std::vector&lt;std::vector&lt;std::string&gt;&gt; v = { {&quot;hello&quot;}, {&quot;world&quot;} }; auto size5 = [](std::string s) { return s.size() == 5; }; auto n = recursive_count_if&lt;std::string&gt;(v, size5); std::cout &lt;&lt; &quot;n:&quot; &lt;&lt; n &lt;&lt; std::endl; </code></pre> <p>The output of <code>std::vector&lt;std::vector&lt;std::string&gt;&gt;</code> case is:</p> <pre><code>n:2 </code></pre> <p>Besides the <code>std::vector&lt;std::vector&lt;std::string&gt;&gt;</code> case, you can also play this <code>recursive_count_if</code> template function like this: [<code>test_vector2</code> is from the above usage]</p> <pre><code>// std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; case std::vector&lt;decltype(test_vector2)&gt; test_vector3; test_vector3.push_back(test_vector2); test_vector3.push_back(test_vector2); test_vector3.push_back(test_vector2); std::cout &lt;&lt; recursive_count_if&lt;decltype(test_vector2)&gt;(test_vector3, [test_vector2](auto&amp; element) { return std::equal(element.begin(), element.end(), test_vector2.begin()); }) &lt;&lt; std::endl; </code></pre> <p><a href="https://godbolt.org/z/651Ejv" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The previous version <code>recursive_count_if</code> template function is hard to deal with <code>std::vector&lt;std::vector&lt;std::string&gt;&gt;</code> case. The experimental improved code has been proposed here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>In order to perform container's value_type matching structure, the <a href="https://en.cppreference.com/w/cpp/concepts/same_as" rel="nofollow noreferrer"><code>std::same_as</code> syntax</a> and <a href="https://en.cppreference.com/w/cpp/iterator/iter_t" rel="nofollow noreferrer"><code>std::iter_value_t</code> syntax</a> are used here. The getting container's value_type part is handled by <code>std::iter_value_t</code> and the type matching part is handled by <code>std::same_as</code>. I am not sure if this is a good implementation.</p> <p>On the other hand, although the separated template parameter <code>T1</code> plays the role of termination condition well, I am trying to deduce the type <code>T1</code> form the given <strong>SFINAE-friendly</strong> lambda function (<code>const T3 predicate</code> here, assume that the given lambda function is SFINAE-friendly without something including <code>auto</code> syntax) so that making the following usage possible (just like the same usage in <a href="https://codereview.stackexchange.com/a/252154/231235">Quuxplusone's answer</a> ).</p> <pre><code>// std::vector&lt;std::vector&lt;std::string&gt;&gt; case std::vector&lt;std::vector&lt;std::string&gt;&gt; v = { {&quot;hello&quot;}, {&quot;world&quot;} }; auto size5 = [](std::string s) { return s.size() == 5; }; auto n = recursive_count_if(v, size5); // the `&lt;std::string&gt;` is no needed to pass in again. std::cout &lt;&lt; &quot;n:&quot; &lt;&lt; n &lt;&lt; std::endl; </code></pre> <p>I've checked some discussions about getting the type of a lambda argument, including <a href="https://stackoverflow.com/q/6512019/6667035">Can we get the type of a lambda argument?</a>, <a href="https://stackoverflow.com/q/6667449/6667035">Is it possible to retrieve the argument types from a (Functor member's) function signature for use in a template?</a>, <a href="https://stackoverflow.com/q/44595687/6667035">Getting the type of lambda arguments</a> and <a href="https://stackoverflow.com/q/52225371/6667035">C++ template deduction from lambda</a>. I think that I have no idea about how to deduce the type <code>T1</code> automatically. Is it possible done with <code>std::function</code> like the experimental code as below?</p> <pre><code>template&lt;class T1, class T2, class T3&gt; requires (is_iterable&lt;T1&gt; &amp;&amp; std::same_as&lt;std::iter_value_t&lt;T1&gt;, T3&gt;) auto recursive_count_if(const T1&amp; input, const std::function&lt;T2(T3)&gt; predicate) { //... } </code></pre> <p>However, I think that maybe <code>T3</code> is <strong>not</strong> the input type of the passed lambda function in the above structure based on some experiments. If I misunderstand something, please tell me. Moreover, please give me some hints or examples if there is any other better way.</p> <p>If there is any further possible improvement, please let me know.</p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T03:46:14.103", "Id": "252225", "Score": "2", "Tags": [ "c++", "recursion", "c++20" ], "Title": "A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++" }
252225
<p>This code is a revised version of implementation which asked for a advice. Original question is here: <a href="https://codereview.stackexchange.com/questions/252039/encode-message-by-alphabets/252041">Encode message by alphabets</a></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define MIN_ALPH 1 #define MAX_ALPH 26 unsigned int my_decode(unsigned int input) { unsigned int count = 0; unsigned int ddigit; int i; //check double digit decoding //TODO: make macro for (num &gt;= MIN_ALPH &amp;&amp; num &lt;= MAX_ALPH) if (input % 100 &gt;= MIN_ALPH &amp;&amp; input % 100 &lt;= MAX_ALPH) count++; if (input / 10 &gt;= MIN_ALPH &amp;&amp; input / 10 &lt;= MAX_ALPH) { if (input % 10 &gt; 0) count++; } //check single digit decoding for (i=1; i &lt;= 100; i*=10) { if (input % (i *10) / i == 0) break; } if (i == 1000) count++; return count; } int main(void) { /*Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed.*/ printf(&quot;result: %u\n&quot;, my_decode(512)); printf(&quot;result: %u\n&quot;, my_decode(542)); printf(&quot;result: %u\n&quot;, my_decode(112)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T12:37:07.527", "Id": "497024", "Score": "1", "body": "Can you explain why you have discarded most of the suggestions given in the original review? At least mention them, so you don't just get a lot of answers raising the same issues. (That's the main reason I'm not answering this one)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T10:56:36.857", "Id": "497599", "Score": "0", "body": "@TobySpeight My fault. Will consider it in future questions." } ]
[ { "body": "<p><strong>Test clarity</strong></p>\n<p>A sample such as with <code>my_decode(512)</code> deserves a break down of how, as letters, it might be encoded.</p>\n<p>Add as a comment, or integrate in test, the expected outputs.</p>\n<p>Posting input as well as output is useful.</p>\n<pre><code>printf(&quot;%u --&gt; result: %u\\n&quot;, 512, my_decode(512));\n</code></pre>\n<p><strong>Format</strong></p>\n<p>Other code and below hints OP is not using an auto formatter as <code>break</code> is not indented. 1) Recommend to use an auto-formatter 2) Prefer <code>{ }</code></p>\n<pre><code> if (input % (i *10) / i == 0)\n break;\n // vs.\n if (input % (i *10) / i == 0) {\n break;\n }\n</code></pre>\n<p><strong>Macro vs. code</strong></p>\n<p>Consider a helper function</p>\n<pre><code>bool alph_in_range(unsigned num) {\n return num &gt;= MIN_ALPH &amp;&amp; num &lt;= MAX_ALPH;\n}\n</code></pre>\n<p><strong>Function</strong></p>\n<p><code>my_decode(102)</code> is 2 and <code>my_decode(1002)</code> is 1. I'd expect 2 for the first is allowed, 10,2 and 1,02 then 10,02 and 1,002 allowed for the 2nd.</p>\n<hr />\n<p>Not much else to say.</p>\n<p><strong>Minor: _MAX</strong></p>\n<p><code>...._MAX</code> more common in C such as <code>INT_MAX</code></p>\n<pre><code>// #define MIN_ALPH 1\n// #define MAX_ALPH 26\n\n#define ALPH_MIN 1\n#define ALPH_MAX 26\n</code></pre>\n<p><strong>Minor: <code>unsigned</code> vs. <code>unsigned int</code></strong></p>\n<p>Either works. <code>unsigned</code> is shorter.</p>\n<p>As with such style issues, code to your group's coding standard.</p>\n<p><strong>Minor: Mixed types</strong></p>\n<p>Some coding standards dislike <code>unsigned % int</code>.</p>\n<p>Could use <code>input % 100u</code> vs. <code>input % 100</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T18:18:32.683", "Id": "252264", "ParentId": "252230", "Score": "2" } }, { "body": "<p>There should be an empty line between the <code>#include</code> lines and the macro definitions. Sure, these lines all start with <code>#</code>, which makes them look similar, but their purpose is completely different. Therefore each of these groups should get its own paragraph.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\n#define MIN_ALPH 1\n#define MAX_ALPH 26\n</code></pre>\n<p>Since your program only uses features from <code>stdio.h</code>, you don't need to include <code>stdlib.h</code>. That's why I omitted it from the above code.</p>\n<p>Now to the interesting part of your code, the function <code>my_decode</code>. This function should rather be called <code>possible_encodings</code> since that matches better what the function actually does. This suggestion already appeared in a review of the original question, therefore in a follow-up request for review, you should at least write some text about the original reviews, what you liked about them and what you didn't like, and why you wrote your code in the way you did. You did nothing of all this.</p>\n<p>The function <code>my_decode</code> should take its argument as a string of characters. This way it will be easy to test it with large digit sequences, not only 9 or 10 digits. Since this is C and not Python, the data type <code>int</code> is quite limited in which numbers it can represent. Typically it's from -2147483648 to 2147483647.</p>\n<p>The function <code>my_decode</code> is completely undocumented. Each function should have at least a one-liner comment that describes its purpose. Instead, you have a really good comment in <code>main</code>, but that comment doesn't belong there. It belongs right above the function <code>my_decode</code>.</p>\n<p>In <code>my_decode</code>, there is no need for a macro. Don't use macros, use <code>static</code> functions instead. Macros are for textual replacement, functions are for computation. Here's an example function:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdbool.h&gt;\n\nstatic bool is_in_range(int n)\n{\n return MIN_ALPH &lt;= n &amp;&amp; n &lt;= MAX_ALPH;\n}\n</code></pre>\n<p>The C programming language doesn't have a <code>between</code> operator. This operator can be approximated using the above form, which has the benefit of using only a single kind of comparison operator, thus reducing any confusion.</p>\n<p>Usually comparisons are written as <code>subject &lt;=&gt; object</code>, and the subject in this case would be <code>n</code>. Only in the case of the <em>between</em> operator should this guideline be violated.</p>\n<p>Still in <code>my_decode</code>, the <code>% 100</code> looks suspicious, as if your code would only work for 3-digit numbers. To prove this assumption wrong, your test data should include a few test cases for longer digit sequences as well.</p>\n<p>Stylistically, your code looks completely inconsistent. Sometimes you write <code>count = 0</code>, at other times you write <code>i=1</code> without any spaces around the <code>=</code>. Don't do this formatting yourself, as it is boring. Let your editor or IDE do this work for you. Search for &quot;auto format code&quot;, and you will find instructions for doing this.</p>\n<p>The special case <code>i == 1000</code> is wrong. Why did you even write this additional <code>if</code> statement? Since the whole function <code>my_decode</code> is a tricky little piece of code, you should explain to the reader of the code why you added each statement. Imagine that you needed to explain this code to someone who can program but who knows only the problem description and the code. Everything else that you want to explain should go into the comments.</p>\n<p>As others already said, don't use printf-only tests. Make the tests check their results themselves. For example, during this review I solved the same problem in Go, another programming language, and I came up with this simple list of tests:</p>\n<pre class=\"lang-golang prettyprint-override\"><code> tests := []struct {\n input string\n want uint64\n }{\n {&quot;&quot;, 1},\n {&quot;1&quot;, 1},\n {&quot;11&quot;, 2},\n {&quot;111&quot;, 3},\n {&quot;1111&quot;, 5},\n {&quot;11111&quot;, 8},\n {&quot;10&quot;, 1},\n {&quot;201&quot;, 1},\n {&quot;11111011111&quot;, 40}, // == 5 * 8\n {&quot;1000&quot;, 0},\n }\n</code></pre>\n<p>This list is easy to extend, and that's how you should write your tests. Of course, in C this looks a bit different, but the basic rule is to have one test per line, plus any additional comments needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-25T07:05:04.827", "Id": "497850", "Score": "0", "body": "thanks for the valuable advices. thank you for review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T23:32:58.720", "Id": "252275", "ParentId": "252230", "Score": "2" } }, { "body": "<p>I come back to the algorithm itself. I feel there is a lot of combinatorics in this. I took a step back and did the grouping into &quot;permutation groups&quot;.</p>\n<p>The &quot;ABC&quot; as input illustrates these groups or regions:</p>\n<pre><code>$ ./a.out\n1234567891011121314151617181920212223242526 [Code]\n(ABC)DEFGHIJ(AAABAC)(AD)(AE)(AF)(AG)(AH)(AI)T(BABBBC)(BD)(BE)(BF) [Decoded: single, grouped] \n</code></pre>\n<p>&quot;123&quot; can be &quot;ABC&quot;, but also &quot;LC&quot; and &quot;AW&quot;. Just like &quot;111&quot; can be &quot;AAA&quot;, &quot;AK&quot; or &quot;KA&quot; in OP.v1.</p>\n<p>A longer group is &quot;212223&quot;, which here is singlified to &quot;BABBBC&quot;. It ia also &quot;UVW&quot;, plus &quot;BLBW&quot;, and many more.</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid parse_msg(char *msg) {\n\n char c, cprev, cnext;\n int i;\n /* Start in a state like after a high digit 3..9 */\n cprev = '9';\n for (i = 0; msg[i] != '\\0'; i++) {\n \n c = msg[i];\n cnext = msg[i+1];\n\n /* &quot;10&quot; and &quot;20&quot; are special cases, get rid of them */ \n if (cnext == '0') {\n if (cprev &lt;= '2')\n printf(&quot;)&quot;); \n if (c == '1')\n printf(&quot;J&quot;); \n if (c == '2')\n printf(&quot;T&quot;); \n if (c &gt;= '3') {\n printf(&quot;******* Error: zero 30-90\\n&quot;);\n return; \n }\n cprev = '9'; // reset \n i++; // extra skip in msg\n continue;\n }\n /* 1: No matter what cnext is (1-9), open a &quot;(&quot; group */\n /* But don't open if next is the null byte */ \n /* Problem: makes &quot;(&quot; even if &quot;10&quot; follows */\n if (c == '1') {\n if (cprev &gt;= '3') \n if (cnext == '\\0') \n cprev = '9'; \n else {\n printf(&quot;(&quot;); \n cprev = c; \n }\n printf(&quot;A&quot;);\n continue;\n }\n\n /* 2: Open before or close after */\n if (c == '2') {\n /* new group only if 321-326 */\n if (cprev &gt;= '3' &amp;&amp; cnext &lt;= '6')\n if (cnext == '\\0') {\n cprev = '9'; \n printf(&quot;B&quot;); \n continue;\n }\n else\n printf(&quot;(&quot;); \n\n /* &quot;2&quot; is &quot;B&quot; in any case */ \n printf(&quot;B&quot;);\n\n /* &quot;127&quot;, &quot;229&quot;: was open, must close */ \n if (cprev &lt;= '2' &amp;&amp; cnext &gt;= '7') {\n printf(&quot;)&quot;); \n cprev = '9'; \n continue;\n }\n cprev = c;\n continue;\n }\n \n /* c == 3 or higher are left */\n\n /* if open, then close group &quot;)&quot; after printing */\n if (cprev == '1' || \n c &lt;= '6' &amp;&amp; cprev == '2') {\n\n printf(&quot;%c&quot;, c + 0x10);\n printf(&quot;)&quot;);\n cprev = c; \n continue; \n }\n\n printf(&quot;%c&quot;, c + 0x10);\n cprev = c;\n }\n\n /* Finish: maybe group is opened */ \n if (cprev &lt;= '2')\n printf(&quot;)&quot;);\n printf(&quot; [Decoded: single, grouped] \\n&quot;); \n return;\n}\n\nint main(void) {\n \n char *msg = &quot;1234567891011121314151617181920212223242526&quot;;\n printf(&quot;%s [Code]\\n&quot;, msg);\n parse_msg(msg);\n\n msg = &quot;2102102&quot;;\n printf(&quot;\\n%s [Code]\\n&quot;, msg);\n parse_msg(msg);\n\n msg = &quot;1181&quot;;\n printf(&quot;\\n%s [Code]\\n&quot;, msg);\n parse_msg(msg);\n\n return 0;\n}\n</code></pre>\n<p>This gives three test decodings:</p>\n<pre><code>1234567891011121314151617181920212223242526 [Code]\n(ABC)DEFGHIJ(AAABAC)(AD)(AE)(AF)(AG)(AH)(AI)T(BABBBC)(BD)(BE)(BF) [Decoded: single, grouped] \n\n2102102 [Code]\n(B)J(B)JB [Decoded: single, grouped] \n\n1181 [Code]\n(AAH)A [Decoded: single, grouped]\n</code></pre>\n<p>Maybe the code works now, except for the wrong parens in front of &quot;J&quot; and &quot;T&quot;. The &quot;10&quot; and &quot;20 really should be filtered out first, otherwise you need a 2-character look-ahead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:21:48.970", "Id": "252307", "ParentId": "252230", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T06:17:03.707", "Id": "252230", "Score": "2", "Tags": [ "algorithm", "c", "interview-questions" ], "Title": "Encode message by alphabets - Follow Up" }
252230
<p>I have written some code to solve the following interview question. Please advise how it can be improved. Thanks in advance.</p> <p>A unival tree (which stands for &quot;universal value&quot;) is a tree where all nodes under it have the same value. Given the root to a binary tree, count the number of unival subtrees. For example, the following tree has 5 unival subtrees:</p> <pre class="lang-none prettyprint-override"><code> 0 / \ 1 0 / \ 1 0 / \ 1 1 </code></pre> <p>Implementation:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; typedef struct stTree { struct stTree * left; struct stTree * right; int value; } stTree; stTree* createNode(int value) { stTree *node = malloc(sizeof *node); node-&gt;left = NULL; node-&gt;right = NULL; node-&gt;value = value; return node; } bool isTreeUniv(stTree *node) { bool flag = true; if (!node) return false; if (node-&gt;right &amp;&amp; node-&gt;right-&gt;value != node-&gt;value) { flag = false; } if (node-&gt;left &amp;&amp; node-&gt;left-&gt;value != node-&gt;value) { flag = false; } return flag; } stTree* insertRight(stTree *currNode, int value) { stTree *node = malloc(sizeof *node); currNode-&gt;right = node; node-&gt;left = NULL; node-&gt;right = NULL; node-&gt;value = value; return node; } stTree* insertLeft(stTree *currNode, int value) { stTree *node = malloc(sizeof *node); currNode-&gt;left = node; node-&gt;left = NULL; node-&gt;right = NULL; node-&gt;value = value; return node; } unsigned int uTreeCount = 0; void countUnivSubT(stTree *Node) { if (isTreeUniv(Node)) uTreeCount++; if (Node-&gt;left) countUnivSubT(Node-&gt;left); if (Node-&gt;right) countUnivSubT(Node-&gt;right); } int main(void) { //build a tree stTree *rootNode = createNode(0); insertLeft(rootNode, 1); insertRight(rootNode, 0); insertLeft(rootNode-&gt;right, 1); insertRight(rootNode-&gt;right, 0); insertLeft(rootNode-&gt;right-&gt;left, 1); insertRight(rootNode-&gt;right-&gt;left, 1); countUnivSubT(rootNode); printf(&quot;total universal subree: %u\n&quot;, uTreeCount); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T00:25:25.863", "Id": "496951", "Score": "2", "body": "All the nodes under it (or just the direct children have the same number)? Your `isTreeUniv()` only checks direct children not all nodes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T10:20:03.363", "Id": "497596", "Score": "0", "body": "I assumed that it checks direct children only, thanks for the catch. I will branch the code with this consideration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-25T05:41:24.103", "Id": "497840", "Score": "0", "body": "hey folks, follow up question is posted here with the suggested considerations: https://codereview.stackexchange.com/questions/252634/counting-unival-subtrees-follow-up. Thank you all for the review." } ]
[ { "body": "<p>The one red flag is <code>uTreeCount</code>. This should not be a global, and in fact it is easy to rephrase your <code>countUnivSubT</code> to be fully re-entrant: have it return an integer, and do addition within the body, something like</p>\n<pre><code>unsigned countUnivSubT(stTree *Node)\n{\n unsigned int uTreeCount = isTreeUniv(Node);\n\n if (Node-&gt;left)\n uTreeCount += countUnivSubT(Node-&gt;left);\n\n if (Node-&gt;right)\n uTreeCout += countUnivSubT(Node-&gt;right);\n\n return uTreeCount;\n}\n</code></pre>\n<p>That said, you have an inner null check, so this can actually reduce to</p>\n<pre><code>unsigned countUnivSubT(stTree *Node)\n{\n if (!Node) return 0;\n \n return isTreeUniv(Node)\n + countUnivSubT(Node-&gt;left)\n + countUnivSubT(Node-&gt;right);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T15:41:51.730", "Id": "252253", "ParentId": "252232", "Score": "3" } }, { "body": "<p><strong><code>const</code></strong></p>\n<p>Consider <code>const</code> with functions that do not alter the tree:</p>\n<pre><code>// bool isTreeUniv(stTree *node)\nbool isTreeUniv(const stTree *node)\n\n//void countUnivSubT(stTree *Node)\nvoid countUnivSubT(const stTree *Node)\n</code></pre>\n<p>This improves clarity of what code does and allows for select optimizations.</p>\n<p><strong>Loop opportunity vs recursion</strong></p>\n<p>Rather than a global and two recursive calls, perhaps loop on one side and recurse on the other:</p>\n<pre><code>unsigned countUnivSubT(const stTree *Node) {\n unsigned count = 0;\n while (Node) {\n count += isTreeUniv(Node);\n if (Node-&gt;left) {\n count += countUnivSubT(Node-&gt;left);\n } \n Node = Node-&gt;right;\n }\n return count;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T03:41:01.120", "Id": "252281", "ParentId": "252232", "Score": "2" } }, { "body": "<p>The algorithm is inefficient.</p>\n<p>For each node, we examine all nodes in its subtree to determine whether they are all equal. We should look to visit each node just once, and extract as much as we need in that single visit. So, as we go, report back up whether the current node is a unival tree, as well as the count of unival trees at or below it. We don't need to visit the children again, just use the retrieved information. Like this:</p>\n<pre><code>static size_t countUnivSubT_impl(const stTree *node, bool *isUnival, int *value)\n{\n if (!node) {\n return 0;\n }\n *value = node-&gt;value;\n\n /* initial values chosen to work if one/both children are null */\n int lval = node-&gt;value, rval = node-&gt;value;\n bool lunival = true, runival = true;\n\n size_t count_left = countUnivSubT_impl(node-&gt;left, &amp;lunival, &amp;lval);\n size_t count_right = countUnivSubT_impl(node-&gt;right, &amp;runival, &amp;rval);\n return count_left + count_right\n + (*isUnival = /* N.B. assignment */\n lunival &amp;&amp; lval == node-&gt;value &amp;&amp;\n runival &amp;&amp; rval == node-&gt;value);\n}\n\nsize_t countUnivSubT(const stTree *node)\n{\n bool isUnival;\n int value;\n return countUnivSubT_impl(node, &amp;isUnival, &amp;value);\n}\n</code></pre>\n<p>And use it in <code>main()</code>:</p>\n<pre><code>printf(&quot;There are %zu universal subtrees\\n&quot;,\n countUnivSubT(rootNode));\n</code></pre>\n<p>(I corrected the spelling there, too).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:23:49.273", "Id": "497028", "Score": "2", "body": "You know there is no rule forcing the operand of `+` to be fully evaluated from left to right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:48:39.347", "Id": "497065", "Score": "1", "body": "Oh, good catch - I did originally have separate statements, and mistakenly combined them overlooking the side-effects. I've fixed that now!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T12:31:39.883", "Id": "252305", "ParentId": "252232", "Score": "2" } }, { "body": "<h3>Code-formatting</h3>\n<ol>\n<li>Putting the tag-type two lines down instead of on the same line as the closing brace is curious.</li>\n</ol>\n<h3>Managing trees</h3>\n<ol start=\"2\">\n<li><p>I wonder why you don't use <code>createNode()</code> in <code>insertRight()</code> and <code>insertLeft()</code>.</p>\n</li>\n<li><p>If you change to building the trees from the leaves down to the root instead the other way around, you only need a single <code>createNode()</code> accepting a value and two (possibly <code>NULL</code>) descendants.</p>\n</li>\n<li><p>Assuming that resource-aquisition always succeeds is quite brave.</p>\n</li>\n<li><p>Consider adding a way to free a tree, for best effect using constant space, even though using it just before tearing down the whole process is unconscionably wasteful.</p>\n</li>\n</ol>\n<pre><code>stTree* createNode(int value, stTree* left, stTree* right) {\n stTree* r = malloc(sizeof *r);\n if (!r) abort();\n r-&gt;value = value;\n r-&gt;left = left;\n r-&gt;right = right;\n return r;\n}\n\nstatic stTree* findBottomLeft(stTree* node) {\n while (node-&gt;left)\n node = node-&gt;left;\n return node;\n}\nvoid freeTree(stTree* node) {\n if (!node) return;\n stTree* bottomLeft = findBottomLeft(node);\n while (node) {\n if (node-&gt;right) {\n bottomLeft-&gt;left = node-&gt;right;\n bottomLeft = findBottomLeft(bottomLeft);\n }\n stTree* old = node;\n node = node-&gt;left;\n free(old);\n }\n}\n</code></pre>\n<h3>The main part</h3>\n<ol start=\"6\">\n<li><p>If you don't need to modify something, don't require the right. Use <code>const</code>.</p>\n</li>\n<li><p><code>isTreeUniv()</code> is just <strong>broken</strong>. It only checks the direct descendents, while it should recurse into them.</p>\n</li>\n<li><p>Consequently, <code>countUnivSubT()</code> is also wrong. Still, fixing <code>isTreeUniv()</code> would result in a <span class=\"math-container\">\\$O(n^2)\\$</span> algorithm, when it should be <span class=\"math-container\">\\$O(n)\\$</span>. The idea is to get all the info you need at once.</p>\n</li>\n<li><p>Avoid globals. Using <code>uTreeCount</code> makes the code non-reentrant, and breaks locality of reasoning.</p>\n</li>\n</ol>\n<pre><code>static bool countUnivSubTimpl(const stTree* node, const stTree* parent, size_t* count) {\n if (!node) return true;\n bool r = countUnivSubTimpl(node-&gt;left, node, count)\n &amp; countUnivSubTimpl(node-&gt;right, node, count);\n *count += r;\n return r &amp; node-&gt;value == parent-&gt;value;\n}\nsize_t countUnivSubT(const stTree* node) {\n size_t r = 0;\n countUnivSubTimpl(node, node, &amp;r);\n return r;\n}\n\nint main() {\n stTree* root =\n createNode(0,\n createNode(1, NULL, NULL),\n createNode(0,\n createNode(1,\n createNode(1, NULL, NULL),\n createNode(1, NULL, NULL),\n ),\n createNode(0, NULL, NULL)));\n\n size_t uTreeCount = countUnivSubT(root);\n printf(&quot;total universal subree: %u\\n&quot;, uTreeCount);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:54:06.510", "Id": "497067", "Score": "1", "body": "I didn't spot `isTreeUniv()` failing to recurse (yet criticised its inefficiency believing it did). Even a reviewer often sees just what they expect to see, not what's actually written!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T07:15:53.777", "Id": "497704", "Score": "0", "body": "should I post my updated version of code in new thread or just leave it since I found an answer. Not being familiar with codereview" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T11:33:14.573", "Id": "497729", "Score": "1", "body": "Post a new review-request referencing this one if you want a review. Alternatively if you don't particularly want it reviewed, post an answer detailing what you changed, what advice you discarded, and your rationale. Try to give credit where due. You could also just decide that it's enough though." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T14:04:18.097", "Id": "252315", "ParentId": "252232", "Score": "3" } } ]
{ "AcceptedAnswerId": "252315", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T06:21:05.607", "Id": "252232", "Score": "5", "Tags": [ "c", "interview-questions" ], "Title": "Counting unival subtrees" }
252232
<p>I have two lists of dictionaries where both have the same &quot;id&quot; key but otherwise different data.</p> <pre><code>list1 = [{&quot;id&quot;:1, &quot;spam&quot;: 3, &quot;eggs&quot;: 5}, {&quot;id&quot;: 2, &quot;spam&quot;: 5, &quot;eggs&quot;: 7}] list2 = [{&quot;id&quot;:1, &quot;knights&quot;: 5, &quot;coconuts&quot;: 2}, {&quot;id&quot;: 2, &quot;knights&quot;: 3, &quot;cocounts&quot;: 8}] </code></pre> <p>I know I can do a nested loop something like this (I know I can use <em>dict.update</em> as well, but just writing it out as an exampel):</p> <pre><code>for id in list1: for i in list2: if id['id'] == i['id]: id['knights'] = i['knights'] id['coconuts'] = i['coconuts'] </code></pre> <p>but can anyone tell me the more pythonic or quicker way to do this? matching two lists with millions of rows in each does not practically work this way.</p> <p><strong>Expected result is:</strong></p> <pre><code>[{&quot;id&quot;: 1, &quot;spam&quot;: 3, &quot;eggs&quot;: 5, &quot;knights&quot;: 5, &quot;coconuts&quot;: 2}, {&quot;id&quot;: 2, &quot;spam&quot;: 5, &quot;eggs&quot;: 7, &quot;knights&quot;: 3, &quot;coconuts&quot;: 8}] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T09:43:22.483", "Id": "496857", "Score": "0", "body": "Where's `id['knights']` and `id['coconuts']` in **list1** ??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T15:34:11.437", "Id": "496904", "Score": "2", "body": "You've already received an excellent answer, but for future reference: you should include all of your code to have sufficient context for meaningful reviews. The code you've shown is both a snippet and pretty clearly hypothetical." } ]
[ { "body": "<p>To improve <em>time complexity</em> you must sometimes <strong>trade-off</strong> <em>space complexity</em>. It's known as <a href=\"https://en.wikipedia.org/wiki/Space%E2%80%93time_tradeoff\" rel=\"nofollow noreferrer\"><strong><code>space-time tradeoff</code></strong></a></p>\n<p>You can transform <code>list1</code> into a dictionary where <em>key</em> is <code>id</code> and <em>value</em> is the dictionary itself.</p>\n<pre><code>list1 = {d['id']: d for d in list1}\n# print(list1)\n# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},\n# 2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}}\n</code></pre>\n<p>Now, iterate through <code>list2</code> and update <code>list1</code> based on <code>id</code></p>\n<pre><code>for d in list2:\n list1[d['id']].update(d)\n\n#print(list1)\n# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},\n# 2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}}\n</code></pre>\n<p>Take <a href=\"https://docs.python.org/3.7/library/stdtypes.html#dict.values\" rel=\"nofollow noreferrer\"><code>dict.values()</code></a> to get desired output</p>\n<pre><code>print(list(list1.values()))\n# [{'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},\n# {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}]\n</code></pre>\n<h3>Dealing with <em><code>Edge cases</code></em></h3>\n<p>The above approach fails when <code>list2</code> has an <code>id</code> which doesn't exist in <code>list1</code>. If that's the case then use this and you want to add that new <code>id</code> to output too. Using <a href=\"https://docs.python.org/3.7/library/stdtypes.html#dict.setdefault\" rel=\"nofollow noreferrer\"><code>dict.setdefault</code></a></p>\n<pre><code># for example list2 is as below\n# [{'id': 1, 'knights': 5, 'coconuts': 2},\n# {'id': 2, 'knights': 3, 'coconuts': 8},\n# {'id': 3, 'knight': 4, 'coconuts': 5}] -&gt; new `id` that's not in `list1`\n\n# Here we leverage on `dict.setdefault`\n\nfor d in list2:\n list1.setdefault(d['id'], dict()).update(d)\n\nprint(list1)\n# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},\n# 2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8},\n# 3: {'id': 3, 'knight': 4, 'coconuts': 5}}\n\n# To get list of dicts use `list(list1.values())\n</code></pre>\n<p>In case you dont want to update with new <code>id</code>, we can resolve this using <code>if</code> block here.</p>\n<pre><code>for d in list2:\n if d['id'] in list1:\n list1[d['id']].update(d)\n# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},\n# 2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}}\n# No `id` 3 present in output\n</code></pre>\n<h3>Using libraries that support <a href=\"https://en.wikipedia.org/wiki/Array_programming\" rel=\"nofollow noreferrer\"><em><code>vectorization</code></em></a>?</h3>\n<p>If you are working on millions of rows you can leverage on <a href=\"https://pypi.org/project/pandas/\" rel=\"nofollow noreferrer\"><strong><code>pandas</code></strong></a> which has many vectorized operations. In your case we can use <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html\" rel=\"nofollow noreferrer\"><code>DataFrame.merge</code></a></p>\n<pre><code>import pandas as pd\n\ndf1 = pd.DataFrame(list1)\ndf2 = pd.DataFrame(list2)\n\n# Now, you have to merge them on `id`\n\nout = df1.merge(df2) \n\n# id spam eggs knights coconuts\n# 0 1 3 5 5 2\n# 1 2 5 7 3 8\n</code></pre>\n<p>To get output as a list of dict you <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html\" rel=\"nofollow noreferrer\"><code>df.to_dict</code></a> with <code>orient</code> param set to <code>records</code></p>\n<pre><code>out.to_dict(orient='records')\n\n# [{'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},\n# {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}]\n</code></pre>\n<p>If you want include new <code>id</code>s then set <code>how</code> param of <code>df.merge</code> to <code>'outer'</code> by default it's <code>'inner'</code></p>\n<pre><code>df1.merge(df2, how='outer')\n\n# id spam eggs knights coconuts\n# 0 1 3.0 5.0 5 2\n# 1 2 5.0 7.0 3 8\n# 2 3 NaN NaN 4 5\n</code></pre>\n<hr />\n<h3>Code Review</h3>\n<ul>\n<li><h3>Naming variables</h3>\n<pre><code>list1 = [...]\nlist2 = [...]\n</code></pre>\n<p>A new reader might not understand what's <code>list1</code> and <code>list2</code>. Name them so they make sense to everyone.</p>\n<pre><code>current_users_details = [...]\nnew_details = [...]\n</code></pre>\n<p>This is just an example, name them accordingly. What I do is ask myself <em>what is it storing in the data-structure?</em>... <em>family member details</em>? then variable name is <code>family_members_details</code>, <em>user details</em> then <code>user_details</code>, <em>pi value</em>? then <code>PI_VALUE</code>... etc.</p>\n</li>\n<li><h3>Violation of <code>E231</code></h3>\n<pre><code>list1 = [{&quot;id&quot;:1, &quot;spam&quot;: 3, &quot;eggs&quot;: 5}, {&quot;id&quot;: 2, &quot;spam&quot;: 5, &quot;eggs&quot;: 7}]\nlist2 = [{&quot;id&quot;:1, &quot;knights&quot;: 5, &quot;coconuts&quot;: 2}, {&quot;id&quot;: 2, &quot;knights&quot;: 3, &quot;cocounts&quot;: 8}]\n</code></pre>\n<p>The above lines use inconsistent use of spaces after <strong><code>:</code></strong>, <code>PEP-8</code> suggest add a space after <strong><code>:</code></strong>.</p>\n</li>\n<li><h3>Violation of <code>E501</code></h3>\n<pre><code>list2 = [{&quot;id&quot;:1, &quot;knights&quot;: 5, &quot;coconuts&quot;: 2}, {&quot;id&quot;: 2, &quot;knights&quot;: 3, &quot;cocounts&quot;: 8}]\n</code></pre>\n<p>Lines longer than 79 characters, <code>PEP-8</code> standard suggests to keep characters in a line &lt;= <strong>79</strong></p>\n</li>\n<li><p>You have missing <code>'</code> here <code>if id['id'] == i['id]:</code></p>\n</li>\n<li><h3>Reusability</h3>\n<p>Make a function which takes both the lists and updates them.</p>\n<pre><code>def update_details(current_details, to_update_with):\n &quot;&quot;&quot;\n updates user details\n &quot;&quot;&quot;\n\n details = {d['id']: d for d in current_details}\n for user in to_update_with:\n details[user['id']].update(user)\n return details\n</code></pre>\n<p>Write a much better docstring <code>:P</code></p>\n</li>\n</ul>\n<hr />\n<p>I suggest using <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\"><strong><code>black</code></strong></a> python code formatter.</p>\n<pre><code>ch3ster@ch3ster:~$ black --line-length 79 your_file.py\n</code></pre>\n<h3>Formatted code</h3>\n<p>Formatted your code using <code>black</code>.</p>\n<pre><code>list1 = [{&quot;id&quot;: 1, &quot;spam&quot;: 3, &quot;eggs&quot;: 5}, {&quot;id&quot;: 2, &quot;spam&quot;: 5, &quot;eggs&quot;: 7}]\nlist2 = [\n {&quot;id&quot;: 1, &quot;knights&quot;: 5, &quot;coconuts&quot;: 2},\n {&quot;id&quot;: 2, &quot;knights&quot;: 3, &quot;cocounts&quot;: 8},\n]\n\nfor d in list2:\n list1[d[&quot;id&quot;]].update(d)\n\nprint(list(list1.values())) # Equivalent to print([*list1.values()])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T10:12:44.373", "Id": "252238", "ParentId": "252235", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T08:43:04.000", "Id": "252235", "Score": "6", "Tags": [ "python", "python-3.x" ], "Title": "\"join\" two list of dictionaries on Id" }
252235
<h3>What I try to achieve</h3> <p>I need to create a administration-panel for a website. Therefore, I need a possibility to protect the content of the panel via a password. The functionality doesn't have to be very advanced. I neither need a password-reset functionality nor the possibility to add more than one user. I also don't need a &quot;keep me logged in&quot;-functionality.</p> <p>It is also a pretty small site, so I don't think the security standards need to be as high as with big companies.</p> <p>I can't use cookies for this project. It is for a completely &quot;cookie-free&quot; website.</p> <p>I've already asked a question about this on <a href="https://stackoverflow.com/questions/64863634/echo-protected-content-after-login">stackoverflow</a>, where user <a href="https://stackoverflow.com/users/1942861/ro-achterberg">Ro Achterberg</a> suggested in a <a href="https://stackoverflow.com/questions/64863634/echo-protected-content-after-login#comment114680203_64863634">comment</a> that I could add layers for improving the security.</p> <p>I therefore decided that I add <a href="https://en.wikipedia.org/wiki/Multi-factor_authentication" rel="nofollow noreferrer">2 factor authentication</a> via email.</p> <h3>The code</h3> <p><code>index.php</code></p> <pre class="lang-php prettyprint-override"><code>&lt;?php //Documentation: https://www.php.net/manual/de/function.password-hash.php $username = '$2y$10$bWW0KD6P7WUaTU99PpcjtON1xKSBhCCxxiiyoaMuY0aVehZSfgVI6'; //result of password_hash(&quot;admin&quot;, PASSWORD_BCRYPT); $password = '$2y$10$NxtrHFdZGZMG7y2G6l2o6eZpksOQfQvrQrCBTj7knEmL8VynQlcz2'; //result of password_hash(&quot;1234&quot;, PASSWORD_BCRYPT); //Loading login form $content = &quot;&lt;h1&gt;Login&lt;/h1&gt; &lt;form method='POST' class='input'&gt; &lt;label&gt; &lt;input type='text' name='username' placeholder='Username' required/&gt; &lt;/label&gt; &lt;label&gt; &lt;input type='password' name='password' placeholder='Password' required/&gt; &lt;/label&gt; &lt;input type='submit' name='login' value='Login'/&gt; &lt;/form&gt;&quot;; //Check if form was submitted if(isset($_POST['login'])) { //Documentation: https://www.php.net/manual/de/function.password-verify.php $verifyUsername = password_verify($_POST['username'], $username); $verifyPassword = password_verify($_POST['password'], $password); //Check if user entered correct username and password if($verifyUsername &amp;&amp; $verifyPassword) { //Generate and send OTP include &quot;randomCode.php&quot;; $code = randomCode(); mail(&quot;contact@example.com&quot;, &quot;One time code&quot;, &quot;Your one time code: &quot; . $code); $time = openssl_encrypt(time(),&quot;AES-128-ECB&quot;, &quot;****************&quot;); $code = password_hash($code, PASSWORD_BCRYPT) . $time; //Load 2fa screen $content = &quot;&lt;h1&gt;2-factor-authentication&lt;/h1&gt; &lt;form method='POST' class='input'&gt; &lt;label&gt; &lt;input type='text' name='2fa' placeholder='one time code' class='validInput' required/&gt; &lt;/label&gt; &lt;input id='code' name='code' type='text' value='$code' readonly/&gt; &lt;input type='submit' name='2faLogin' value='Login'/&gt; &lt;/form&gt;&quot;; } //Reload login form else { $content = &quot;&lt;h1&gt;Login&lt;/h1&gt; &lt;p&gt;Wrong username or password!&lt;/p&gt; &lt;form method='POST' class='input'&gt; &lt;label&gt; &lt;input type='text' name='username' placeholder='Username' class='validInput' required/&gt; &lt;/label&gt; &lt;label&gt; &lt;input type='password' name='password' placeholder='Password' class='validInput' required/&gt; &lt;/label&gt; &lt;input type='submit' name='login' value='Login'/&gt; &lt;/form&gt;&quot;; } } //Check if one time code was submitted if(isset($_POST['2faLogin'])) { $time = openssl_decrypt(substr($_POST['code'], 60), &quot;AES-128-ECB&quot;, &quot;****************&quot;); //Did user take too long to enter code (5 minutes)? if(!$time || time() - intval($time) &gt; 300) { include &quot;randomCode.php&quot;; $code = randomCode(); mail(&quot;contact@example.com&quot;, &quot;One time code&quot;, &quot;Your one time code: &quot; . $code); $time = openssl_encrypt(time(),&quot;AES-128-ECB&quot;, &quot;****************&quot;); $code = password_hash($code, PASSWORD_BCRYPT) . $time; $content = &quot;&lt;h1&gt;2-factor-authentication&lt;/h1&gt; &lt;p&gt;Code invalid! We've sent you a new mail.&lt;/p&gt; &lt;form method='POST' class='input'&gt; &lt;label&gt; &lt;input type='text' name='2fa' placeholder='one time code' class='validInput' required/&gt; &lt;/label&gt; &lt;input id='code' name='code' type='text' value='$code' readonly/&gt; &lt;input type='submit' name='2faLogin' value='Login'/&gt; &lt;/form&gt;&quot;; } //Did user was too fast (10 seconds)? else if(time() - intval($time) &lt; 10) { $code = $_POST['code']; $content = &quot;&lt;h1&gt;2-factor-authentication&lt;/h1&gt; &lt;p&gt;That was a bit too fast.&lt;/p&gt; &lt;form method='POST' class='input'&gt; &lt;label&gt; &lt;input type='text' name='2fa' placeholder='one time code' class='validInput' required/&gt; &lt;/label&gt; &lt;input id='code' name='code' type='text' value='$code' readonly/&gt; &lt;input type='submit' name='2faLogin' value='Login'/&gt; &lt;/form&gt;&quot;; } //Time is ok else { $verify = password_verify($_POST['2fa'], substr($_POST['code'], 0, 60)); //Verify OTP failed if(!$verify) { $code = $_POST['code']; $content = &quot;&lt;h1&gt;2-factor-authentication&lt;/h1&gt; &lt;p&gt;Entered wrong code!&lt;/p&gt; &lt;form method='POST' class='input'&gt; &lt;label&gt; &lt;input type='text' name='2fa' placeholder='one time code' class='validInput' required/&gt; &lt;/label&gt; &lt;input id='code' name='code' type='text' value='$code' readonly/&gt; &lt;input type='submit' name='2faLogin' value='Login'/&gt; &lt;/form&gt;&quot;; } //Verified OTP successfully else { $content = &quot;&lt;h1&gt;Welcome!&lt;/h1&gt;&lt;p&gt;Content here...&lt;/p&gt;&quot;; } } } ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang='en'&gt; &lt;head&gt; &lt;title&gt;John Doe&lt;/title&gt; &lt;meta http-equiv='Content-Type' content='text/html;charset=utf-8'/&gt; &lt;/head&gt; &lt;body id='body'&gt; &lt;?php echo $content; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><code>randomCode.php</code></p> <pre class="lang-php prettyprint-override"><code>&lt;?php function randomCode() { $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $random = &quot;&quot;; for($i = 0; $i &lt; 6; $i++) { $random .= $characters[rand(0, strlen($characters) - 1)]; } return $random; } </code></pre> <h3>Question</h3> <p>All suggestions are welcome. I am especially interested in the security of this code and how to further improve it.</p>
[]
[ { "body": "<p>I'm aware that the OP appears to no longer be a part of the site. However, I thought that this was an interesting topic that may have relevance to future visitors as well</p>\n<hr />\n<h2>General</h2>\n<p><strong>HTML &amp; PHP</strong></p>\n<p>The first thing I suggest is that you move all of your <code>HTML</code> code blocks to the top of your document. That way they're out of the way and don't interfere with your ability to <em>read</em> the code easily. Additionally it means you don't have repeated code for, for example, the login form. Example:</p>\n<pre><code>$htmlForms = [\n &quot;login&quot; =&gt; &quot;&lt;form&gt;....&lt;/form&gt;&quot;,\n &quot;2fa&quot; =&gt; &quot;&lt;form&gt;....&lt;/form&gt;&quot;,\n};\n\n// Use as...\n\necho $htmlForms[&quot;login&quot;];\n\n// Or...\n\n$content = $htmlForms[&quot;login&quot;];\n</code></pre>\n<p>To output PHP (<code>echo</code>) into HTML you can use shorthand to make it cleaner:</p>\n<pre><code>&lt;?php echo $content; ?&gt;\n\n// Becomes...\n\n&lt;?=$content?&gt;\n</code></pre>\n<p><strong>Storing Credentials</strong></p>\n<p>Currently you have stored <code>username</code>, <code>password</code>, and <code>key</code> in the same file as your code. The problem with that is that in the event of a server misconfiguration all of your details are exposed to the viewer.</p>\n<p>Better to store those credentials in another <code>configuration</code> file <em>outside</em> of the web root. Preferably store them in a database - that way as and when you come to need more people to have logon ability it's as simple as adding them to the database.</p>\n<p><strong>Notices</strong></p>\n<p>Your <code>password_verify</code> lines will generate notices in the event someone tries to access the page <em>without</em> the form data. You can get around this by checking the value first or using the <code>NULL</code> coalescing operator (<code>??</code>). Example:</p>\n<pre><code>$verifyUsername = password_verify($_POST['username'] ?? null, $username);\n</code></pre>\n<h2>Cookies</h2>\n<p>I'm not sure what the logic is RE not using cookies. If it's GDPR related then you should note that just because you aren't using <code>cookies</code> which has been a <em>buzzword</em> for GDPR and websites that doesn't mean you're in the clear...</p>\n<p>The guidelines are there for any personal data that is collected/stored/processed and swapping a cookie (which is just data being passed back and forth between client and server) for a variable in the page that is doing the same thing doesn't change your responsibilities as far as gaining consent etc.</p>\n<p>Perhaps there's a technical reason not to use them in this case; but if it's just to comply with <em>consent to process</em> guidelines then you're making complications for no reason. Better to just ask consent and use a cookie; you can simply only have cookies on that part of your site - it doesn't have to affect the <em>normal</em>.</p>\n<h2>2 factor authentication: general</h2>\n<p>I can't really see a reason for 2 factor authentication. Yes, usually, it makes it more secure but if this system is only for you (presumably the case because the username/password is hardcoded) then just pick good credentials.</p>\n<p><strong>N.B.</strong> the implementation of 2 factor authentication shown here is inherently insecure (see below).</p>\n<h2>Time limits</h2>\n<p>A ten second time limit seems redundant in most cases. There's nothing stopping me waiting those ten seconds and/or producing another hundred requests in those 10 seconds... If you want to use time/rate as a factor then you need to store the time of the last login attempt server side (again, potentially in a config file or database).</p>\n<p>It also impacts the user experience. In a modern society we all have our phones on us and whenever I need to receive a <code>text</code> for two factor authentication my phone is read and waiting to type the code in long before <code>10 seconds</code> had passed. Which means your user has to artificially delay their entering of the second code.</p>\n<p>Five minutes on the other hand, sometimes might not be long enough for the email to come through; meaning you could be stuck in a loop of requesting a <code>One Time Code</code> and not being able to use it.</p>\n<h2>Code Generation</h2>\n<p>It is <em>normal</em> for a <code>One Time Code</code> to be about 6 digits long. However, in your scenario that will not do. Usually the code would be stored server side but in your case you are sending the code back and forth between the client and the server which means that any <em>potential attacker</em> can crack the encryption in a very short amount of time:</p>\n<p>The total possible combinations are <code>36^6 = 2176782336</code>; guesses per second varies depending on hardware but with modern GPU leveraging software it's a lot and it's the reason minimum password lengths are required by almost every website going.</p>\n<p><a href=\"https://web.archive.org/web/20180412051235/http://www.lockdown.co.uk/?pg=combi&amp;s=articles#Classes\" rel=\"nofollow noreferrer\">This website</a> is linked from another StackExchange answer which has various tables suggesting that a <code>5 x 36</code> code can be cracked by a <em>fast PC</em> in less than <code>1 minute</code>.</p>\n<p>Additional things to bear in mind:</p>\n<ul>\n<li>That website defines a fast PC as <em>dual processors</em>; which is a bit out of date compared to modern hardware!</li>\n<li>With GPU leveraging (which almost anyone can set up) that number would likely drop even lower\n<ul>\n<li>We must assume that they would be using a powerful computer (gpu matrix) because, by this stage, they already cracked your username/password</li>\n</ul>\n</li>\n<li>These times represent total time to cycle all possibilities. So unless the attacker starts at <code>000000</code> and your code is <code>ZZZZZZ</code> it'll be far quicker</li>\n<li>You also need to bear in mind that there's a 1 in 36 chance that the first number will be a <code>0</code>; which effectively drops you back down to a 5 character code (in terms of time to crack; assuming a linear brute force)\n<ul>\n<li><code>60466176</code> possible guesses...</li>\n<li><code>5038848</code> if you're code starts <code>02</code></li>\n</ul>\n</li>\n</ul>\n<p>With your code generation you also use <code>rand</code> which comes with a <strong>caution</strong> from the PHP manual stating that is not crypto secure. This means that it shouldn't really be used in your scenario: <code>random_int($min, $max)</code> is the way to go instead. Better yet just create some <em>suitably safe</em> length string with <code>random_bytes</code> and convert to a suitable <code>base*</code> (such as your character set <code>base36</code>).</p>\n<p>The user doesn't have to do anything with this code so what's the harm in it being <code>[insert absurdly large number here]</code> characters?</p>\n<h2>Code Handling</h2>\n<p>After creating the code not only do you output that code back to the client, but you also show it to the user in an input! One look at it from anyone familiar with PHP and they will know exactly what it is (it starts <code>$2y$10</code>; they'll even know where to split the string to start cracking) without even having to check the HTML source code...</p>\n<p>Again, this should be stored server side.</p>\n<p>But even more importantly handing the code back to the user means an attacker doesn't even need to crack it. Take the following:</p>\n<pre><code>$code = bin2hex(random_bytes(10)); // 32385751bad0c265d2db\n$hash = password_hash($code, PASSWORD_DEFAULT); // $2y$10$qhEGDWr8hNwaWuRQCznX..bM6zpYZliTmbuO8RuIUo4udqtZvP8p6\n$time = openssl_encrypt(time(),&quot;AES-128-ECB&quot;, &quot;reallyStrongKey&quot;); // G2MyOIN0ni7TY2esVkfPUg==\n\n$code = $hash . $time; // $2y$10$qhEGDWr8hNwaWuRQCznX..bM6zpYZliTmbuO8RuIUo4udqtZvP8p6G2MyOIN0ni7TY2esVkfPUg==\n</code></pre>\n<p>Because an attacker recognised <code>$2y$10</code> they know that the <em>password hash</em> section of that code is the first 60 characters. So they can generate their own and replace the value:</p>\n<pre><code>echo password_hash(&quot;123&quot;, PASSWORD_DEFAULT); // $2y$10$G0Q6M65Wxg2DiwvRnsSJUOsoHIDOHYa5JqP8BrYHjKlk2XkoleMJK\n\n// Copy/Paste with\n\nG2MyOIN0ni7TY2esVkfPUg==\n</code></pre>\n<p>Now they can log on.</p>\n<p>Further more because of the structure of your code an attacker can create their own HTML form with fields:</p>\n<pre><code>username\npassword\n2fa\ncode\nlogin\n2faLogin\n</code></pre>\n<p>and log on straight away. Or rather they could if they knew the <code>key</code> to your encryption - which potentially they may do (as mentioned earlier) through a misconfiguration etc.</p>\n<p>To that end you should be clear that <code>login</code> and <code>2faLogin</code> are <em>either... or...</em> and not <em>both</em>. Easily done with <code>if... elseif...</code>.</p>\n<h2>Structure of attack</h2>\n<p>Firstly, the attacker needs to get hold of the username/password. This will happen in one of two ways:</p>\n<ol>\n<li>A brute force attack\n<ul>\n<li>Password likely with a dictionary (or hybrid) attack</li>\n<li>Username probably with guess work</li>\n</ul>\n</li>\n<li>A server misconfiguration leads to the hashes being displayed (and the AES key)\n<ul>\n<li>Now the attacker can brute force using their set up --- way faster than over HTTP</li>\n</ul>\n</li>\n</ol>\n<p>How long would it really take when...</p>\n<ul>\n<li>Usernames tend to:\n<ul>\n<li>Clearly identify people</li>\n<li>Be re-used between services</li>\n<li>Be an email address (or the first part of it at last!)</li>\n</ul>\n</li>\n<li>Passwords tend to be:\n<ul>\n<li>Of low quality</li>\n<li>Easily guessable (names/dates/etc.; hundreds of personalised guesses can be generated with software)</li>\n<li>In a password list like <code>RockYou</code></li>\n</ul>\n</li>\n</ul>\n<p>Now that the attacker has your username and password they only have to get through your <code>one time code</code>. Which will happen in a few ways:</p>\n<ol>\n<li>As explained earlier, they can use their own</li>\n<li>High chance that your email password and logon password are the same/similar\n<ul>\n<li>They'll check your emails</li>\n</ul>\n</li>\n<li>Brute force the hashed code in a few minutes and enter it in</li>\n</ol>\n<p>The only thing holding up an attacker with your two factor authentication is that they don't know what the second part of the <code>code</code> is (unless a server error meant the key was shown and they can decode it) and they can't generate it themselves. But, an attacker will experiment and submitting that same code with their custom <code>one time code</code> would be their first attempt.</p>\n<h2>Penetration testing scales</h2>\n<p>Now, I've obviously seen your source code so can work out a plan to <em>beat</em> it with that knowledge; an attacker (hopefully) is on the other end of the spectrum and wouldn't have that knowledge.</p>\n<p>However, the reality is that in a real attack once the attacker is past the username and password the rest of it is really child's play and adds no benefit to your security.</p>\n<hr />\n<h2>Code</h2>\n<p>Implementing the above suggestions you would end up with two files:</p>\n<p><strong>config.json</strong></p>\n<pre><code>{\n &quot;username&quot;:&quot;$2y$10$bWW0KD6P7WUaTU99PpcjtON1xKSBhCCxxiiyoaMuY0aVehZSfgVI6&quot;,\n &quot;password&quot;:&quot;$2y$10$NxtrHFdZGZMG7y2G6l2o6eZpksOQfQvrQrCBTj7knEmL8VynQlcz2&quot;,\n &quot;lastLogon&quot;:&quot;2021-02-07 12:00:00&quot;\n}\n</code></pre>\n<p><strong>index.php</strong></p>\n<p>Note, this doesn't implement continued authentication. Only up to the point the OPs original code did.</p>\n<pre><code>&lt;?php\n\n$credentials = json_decode(file_get_contents(&quot;../../path/to/config.json&quot;));\n\n$html = [\n &quot;logon&quot; =&gt; &quot;\n &lt;h1&gt;Login&lt;/h1&gt;\n &lt;form method='POST' class='input'&gt;\n &lt;label&gt;\n &lt;input type='text' name='username' placeholder='Username' required/&gt;\n &lt;/label&gt;\n\n &lt;label&gt;\n &lt;input type='password' name='password' placeholder='Password' required/&gt;\n &lt;/label&gt;\n\n &lt;input type='submit' name='login' value='Login'/&gt;\n &lt;/form&gt;&quot;,\n &quot;wrongCredentials&quot; =&gt; &quot;...&quot;,\n &quot;nothignSubmitted&quot; =&gt; &quot;...&quot;,\n &quot;tooSoon&quot; =&gt; &quot;...&quot;,\n];\n\n$username = $_POST[&quot;username&quot;] ?? null;\n$password = $_POST[&quot;password&quot;] ?? null;\n$lastLogon = $credentials[&quot;lastLogon&quot;];\n$timeLimit = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;-30 seconds&quot;));\n\nif($password &amp;&amp; $username)\n \n $credentials[&quot;lastLogon&quot;] = date(&quot;Y-m-d H:i:s&quot;);\n file_put_contents(&quot;../../path/to/config.json&quot;, json_encode($credentials));\n\n if (\n password_verify($username, $credentials[&quot;username&quot;]) &amp;&amp;\n password_verify($password, $credentials[&quot;password&quot;])\n ) {\n if ($lastLogon &gt; $timeLimit) {\n $content = $html[&quot;tooSoon&quot;];\n } else {\n // Logged on, everyone is happy...\n\n }\n } else {\n $content = $html[&quot;wrongCredentials&quot;];\n }\n} else {\n $content = $html[&quot;logon&quot;]\n}\n\n\n?&gt;\n\n&lt;!DOCTYPE html&gt;\n&lt;html lang='en'&gt;\n &lt;head&gt;\n &lt;title&gt;John Doe&lt;/title&gt;\n &lt;meta http-equiv='Content-Type' content='text/html;charset=utf-8'/&gt;\n &lt;/head&gt;\n &lt;body id='body'&gt;\n &lt;?=$content?&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<hr />\n<h2>Further points</h2>\n<p>This isn't in the code, so isn't part of the main review, however....</p>\n<p>The code above shows no way of a follow up request being verified. Using <code>SESSION</code> and/or cookies you can just set a <em>server side</em> variable...</p>\n<pre><code>$_SESSION[&quot;loggedon&quot;] = true;\n</code></pre>\n<p>...and check that on subsequent requests. With this code there's no real way to do that; you would have to send some form of token but - as nothing is stored server side - that could just as easily be faked/cracked by an attacker. Rendering the whole log on process (even if it was 100% secure) completely moot.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T22:41:33.750", "Id": "255738", "ParentId": "252237", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T09:54:49.460", "Id": "252237", "Score": "6", "Tags": [ "beginner", "php", "security", "form", "authentication" ], "Title": "Basic login system with 2 factor authentication" }
252237
<p>Finally after a few months of searching and learning AJAX with pagination PHP and History.pushState() I created AJAX PHP pagination.</p> <p><a href="http://mantykora.cleoni.com:8080/2020_pagination_1/public/page=2" rel="nofollow noreferrer">Test page</a></p> <p><strong>1. Ajax(index.php)</strong></p> <pre><code>$(window).on('load', function () { // makes sure that whole site is loaded $('#status').fadeOut(); $('#preloader').delay(350).fadeOut('slow'); }); $(document).ready(function(){ var url_string = window.location.href; var url_parts = url_string.split('/'); var piece = url_parts[url_parts.length -1]; //get last part of url (it should be page=n) var page; if(piece.substring(0, 5) === 'page=') { page = parseInt(piece.substr(5)); } else { //if it's the first time you landed in the page you haven't page=n page = 1; } load_data(page); // load_data(1); function load_data(page) { $('#load_data').html('&lt;div id=&quot;status&quot; style=&quot;&quot; &gt;&lt;/div&gt;'); $.ajax({ url:&quot;pagination2.php&quot;, method:&quot;POST&quot;, data:{page:page}, success:function(data){ $('#load_data').html(data); } }); } $(document).on('click', '.pagination_link', function(event) { event.preventDefault(); var page = $(this).attr(&quot;id&quot;); load_data(page); //Now push PAGE to URL window.history.pushState({page}, `Selected: ${page}`, `${'page=' + page}`) //window.history.pushState({page}, `Selected: ${page}`, `./selected=${page}`) return event.preventDefault(); }); window.addEventListener('popstate', e =&gt; { var page = $(this).attr(&quot;id&quot;); load_data(e.state.page); console.log('popstate error!'); }); }); </code></pre> <p><strong>2. pagination2.php</strong></p> <pre><code> &lt;?php $rowperpage = 10; $page = 1; if($_POST['page'] &gt; 1) { $p = (($_POST['page'] - 1) * $rowperpage); $page = $_POST['page']; } else { $p = 0; } ?&gt; &lt;?php $visible = $visible ?? true; $products_count = count_all_products(['visible' =&gt; $visible]); $sql = &quot;SELECT * FROM products &quot;; $sql .= &quot;WHERE visible = true &quot;; $sql .= &quot;ORDER BY position ASC &quot;; $sql .= &quot;LIMIT &quot;.$p.&quot;, &quot;.$rowperpage.&quot;&quot;; $product_set = find_by_sql($sql); $product_count = mysqli_num_rows($product_set); if($product_count == 0) { echo &quot;&lt;h1&gt;No products&lt;/h1&gt;&quot;; } while($run_product_set = mysqli_fetch_assoc($product_set)) { ?&gt; &lt;div style=&quot;float: left; margin-left: 20px; margin-top: 10px; class=&quot;small&quot;&gt; &lt;a href=&quot;&lt;?php echo url_for('/show.php?id=' . htmlspecialchars(urlencode($run_product_set['id']))); ?&gt;&quot;&gt; &lt;img src=&quot;staff/images/&lt;?php echo htmlspecialchars($run_product_set['filename']); ?&gt; &quot; width=&quot;150&quot;&gt; &lt;/a&gt; &lt;p&gt;&lt;?php echo htmlspecialchars($run_product_set['prod_name']); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } mysqli_free_result($product_set); ?&gt; &lt;section id=&quot;pagination&quot;&gt; &lt;?php if($_POST['page'] &gt; 1) { $page_nb = $_POST['page']; } else { $page_nb = 1; } $check = $p + $rowperpage; $prev_page = $page_nb - 1; $limit = $products_count / $rowperpage; $limit = ceil($limit); $current_page = $page_nb; if($page_nb &gt; 1) { echo &quot;&lt;span class='pagination_link' style='cursor:pointer;' id='&quot;.$prev_page.&quot;'&gt;Back&lt;/span&gt;&quot;; } if ( $products_count &gt; $check ) { for ( $i = max( 1, $page_nb - 5 ); $i &lt;= min( $page_nb + 5, $limit ); $i++ ) { if ( $current_page == $i ) { echo &quot;&lt;span class=\&quot;selected\&quot;&gt;{$i}&lt;/span&gt;&quot;; } else { echo &quot;&lt;span class='pagination_link' style='cursor:pointer;' id='&quot;.$i.&quot;'&gt;&quot;.$i.&quot;&lt;/span&gt;&quot;; } } } if ($products_count &gt; $check) { $next_page = $page_nb + 1; echo &quot;&lt;span class='pagination_link' style='cursor:pointer;' id='&quot;.$next_page.&quot;'&gt;Next&lt;/span&gt;&quot;; } ?&gt; </code></pre> <p><strong>3. htaccess</strong></p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.*)$ index.php?/$1 [L] &lt;/IfModule&gt; </code></pre> <p><strong>4. Functions</strong></p> <pre><code>function url_for($script_path) { // add the leading '/' if not present if($script_path[0] != '/') { $script_path = &quot;/&quot; . $script_path; } return WWW_ROOT . $script_path; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T23:03:27.273", "Id": "496949", "Score": "2", "body": "Why should we continue to review your code if you aren't going to take the past advice that we give you? Why am I still seeing incomprehensible function names like `h()` and `u()`?!? Please read the previous reviews, upvote the helpful ones, accept answers, adjust your future codes, do not ask reviewers to repeat good advice. In recent history: #1: https://codereview.stackexchange.com/a/240604/141885 #2: https://codereview.stackexchange.com/a/242782/141885" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T00:06:50.300", "Id": "496950", "Score": "0", "body": "@mickmackusa I did not know that '`closed`' is public visible, I thought it was just for me. I was convinced the old one could be thrown away. I corrected `h` + `u` and added function `url_for`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T06:01:55.600", "Id": "510298", "Score": "0", "body": "Ouch! I have never seen a need for nesting these: `htmlspecialchars(urlencode..)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T06:04:50.993", "Id": "510299", "Score": "0", "body": "Pagination via OFFSET has problems -- missing/duplicated data, and performance. Instead, \"remember where you left off\". http://mysql.rjweb.org/doc.php/pagination" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T07:52:08.987", "Id": "510318", "Score": "0", "body": "@Rick James I can't check - I have only 34,898 items :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T07:58:28.067", "Id": "510320", "Score": "0", "body": "@Rick James -> `htmlspecialchars(urlencode..)` for `id` output, I always do that, for security." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T08:03:09.640", "Id": "510321", "Score": "0", "body": "@Rick James it solves all problems limit and offset `$sql .= \"LIMIT {.....} \"; $sql .= \"OFFSET {.......}\"; `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T08:09:56.387", "Id": "510322", "Score": "0", "body": "@Rick James (XSS protection) `htmlspecialchars` -> sanitize for HTML output, `urlencode` -> sanitize for use in a URL" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T16:38:45.143", "Id": "510359", "Score": "0", "body": "@Mantykora7 - There is nothing left for htmlspecialchars to do after urlencode has turned many things into %hh ." } ]
[ { "body": "<h1>Overall Assessment</h1>\n<p>It appears to work, although when a user on the demo site (presuming the code is the same) goes to page 10, only the link with text <code>BACK</code> is present. Should other page numbers exist? I understand why no other numbered links appear after having looked at the PHP logic but my experience with other paging systems makes me question this UI experience.</p>\n<p>The practice of sending HTML in an AJAX response and using that to directly set the content of a DOM element is an antiquated practice, and <a href=\"https://labs.f-secure.com/blog/getting-real-with-xss/\" rel=\"nofollow noreferrer\">could be an XSS avenue</a>. While the practice of <a href=\"https://softwareengineering.stackexchange.com/questions/140036/is-it-a-good-idea-to-do-ui-100-in-javascript-and-provide-data-through-an-api\">sending data from the API and having the front end code construct the HTML dynamically may have been a new construct eight years ago</a> it is much more common in today’s web.</p>\n<p>The <strong>indentation</strong> is inconsistent - especially in the JavaScript code - which makes it difficult to read.</p>\n<p>I see that you have a <a href=\"https://codereview.stackexchange.com/q/215492/120114\">previous post</a> with identical code, thus this post is a follow-up to that one. That post has an accepted answer, though not all suggestions were taken into account. This is fine but you might want to consider those suggestions.</p>\n<p>By the way <a href=\"http://youmightnotneedjquery.com/\" rel=\"nofollow noreferrer\">you might not need jQuery</a>...</p>\n<h1>Feedback/Suggestions</h1>\n<h2>Javascript</h2>\n<h3>DOM ready callback</h3>\n<p>If you are using jQuery 3.0 or newer then the format for <a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\"><code>.ready()</code></a> can be simplified to &quot;the recommended syntax&quot;<sup><a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">3</a></sup>:</p>\n<pre><code>$(function() { ... })\n</code></pre>\n<p>Instead of:</p>\n<blockquote>\n<pre><code>$(document).ready(function(){ \n</code></pre>\n</blockquote>\n<h3>Parsing page parameter</h3>\n<p>Instead of using <code>window.location.href</code> the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Location/search\" rel=\"nofollow noreferrer\"><code>search</code></a> property could be used. On that MDN page it states:</p>\n<blockquote>\n<p>Modern browsers provide <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get#examples\" rel=\"nofollow noreferrer\">URLSearchParams</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams#examples\" rel=\"nofollow noreferrer\">URL.searchParams</a> to make it easy to parse out the parameters from the querystring.</p>\n</blockquote>\n<p>Your code could utilize <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\">the <code>URLSearchParams</code> interface</a> - something along the lines of:</p>\n<pre><code>const params = new URLSearchParams(document.location.search.substring(1));\nconst name = params.get(&quot;page&quot;) || 1;\n</code></pre>\n<h3>jQuery AJAX functions</h3>\n<p>There is a convenience method <a href=\"https://api.jquery.com/jQuery.post/\" rel=\"nofollow noreferrer\"><code>.post()</code></a> that could be used to simplify the code to run the AJAX request - for example, I haven't tested this but it could be as simple as this:</p>\n<pre><code>const container = $(#load_data);\ncontainer.html('&lt;div id=&quot;status&quot; style=&quot;&quot; &gt;&lt;/div&gt;');\n$.post(&quot;pagination2.php&quot;, { page }, container.html);\n</code></pre>\n<h3>unused variable <code>page</code> in event listener function</h3>\n<blockquote>\n<pre><code>window.addEventListener('popstate', e =&gt; {\n var page = $(this).attr(&quot;id&quot;);\n load_data(e.state.page);\n console.log('popstate error!');\n});\n</code></pre>\n</blockquote>\n<p>The variable <code>page</code> isn't used within the callback function. It can be eliminated.</p>\n<h2>PHP</h2>\n<h3>Constants</h3>\n<p>Things that shouldn't be changed (e.g. number of rows per page) can be declared as a constant - e.g. with <a href=\"https://php.net/define\" rel=\"nofollow noreferrer\"><code>define()</code></a> or <a href=\"https://php.net/const\" rel=\"nofollow noreferrer\"><code>const</code></a>.</p>\n<pre><code>const ROWS_PER_PAGE = 10; \n</code></pre>\n<hr />\n<p>One thing that was already mentioned in <a href=\"https://codereview.stackexchange.com/a/215721/120114\">the answer by @mickmackusa</a> to your previous question is that:</p>\n<blockquote>\n<p>The LIMIT clause string can be written without concatenation: <br/>\n<code>$sql .= &quot;LIMIT $p, $rowperpage&quot;;</code></p>\n</blockquote>\n<p>I see that code is still unchanged. Perhaps it be helpful to know the reason: Variables in <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double\" rel=\"nofollow noreferrer\">double-quoted</a> (and <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc\" rel=\"nofollow noreferrer\">heredoc</a> syntaxes) are expanded when they occur in double quoted strings.</p>\n<h3>Closing and re-opening PHP tags</h3>\n<p>I see this code at the top of pagination2.php:</p>\n<blockquote>\n<pre><code>&lt;?php require_once('../private/initialize.php'); ?&gt;\n</code></pre>\n</blockquote>\n<blockquote>\n<pre><code>&lt;?php\n</code></pre>\n</blockquote>\n<blockquote>\n<pre><code>$page = ''; \n</code></pre>\n</blockquote>\n<p>There is little need to close and re-open the PHP tags.</p>\n<pre><code>&lt;?php \nrequire_once('../private/initialize.php'); \n$page = ''; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T16:43:20.707", "Id": "510360", "Score": "0", "body": "Long ago, I chose to always write PHP, with `echo` to get HTML. And never go the other way (HTML with embedded PHP). The code in the Question is hard to read since it does both!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T16:35:08.750", "Id": "258845", "ParentId": "252239", "Score": "2" } } ]
{ "AcceptedAnswerId": "258845", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T10:22:05.470", "Id": "252239", "Score": "3", "Tags": [ "php", "mysql", "ajax" ], "Title": "Make Pagination using Ajax with Jquery, PHP, History.pushState()" }
252239
<p>I am writing a piece of code for some students and I came up with the following implementation of Floyd's algorithm for finding cycles in linked lists.</p> <p>I was wondering if there are ways I can improve what I have so far such that the result is</p> <ul> <li>more C++ idiomatic</li> <li>does not contain dumb mistakes associated with the generic code</li> </ul> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename T&gt; struct Node { T val; Node* next; Node() = default; Node(T x) : val(x) , next(nullptr) { } }; template &lt;typename T&gt; Node&lt;T&gt;* detect_cycle_constant_time(Node&lt;T&gt;* head) { Node&lt;T&gt; *n1, *n2; n1 = n2 = head; while (n1 &amp;&amp; n2) { n1 = n1-&gt;next; n2 = n2-&gt;next; if (n2) n2 = n2-&gt;next; else break; if (n1 == n2) break; } // second phase of Floyds's algorithm if (n1 == n2) { n2 = head; while (n1 != n2) { n1 = n1-&gt;next; n2 = n2-&gt;next; } return n1; } return nullptr; } </code></pre>
[]
[ { "body": "<h1>General</h1>\n<p>I found no &quot;dumb mistakes associated with generic code&quot;. Good job.</p>\n<p>Still, there are some points which can be improved.<br />\n(Aren't there always?)</p>\n<hr />\n<p>The first point is encapsulation.</p>\n<p>Letting nodes float around free, instead of keeping them in their dedicated container, or (rarely) evacuating them to a handle for re-insertion, is not recommended.</p>\n<p>Admittedly, a properly written container won't suddenly sprout a cycle, so there you are.</p>\n<p>Also, it would detract from the point of your code, so let's leave it alone <em>this time</em>.</p>\n<h1><code>Node</code></h1>\n<p><code>Node</code>'s default ctor won't initialize its members. The fix is easy:<br />\nJust add in-class initializers.</p>\n<p>Doing so even allows you to simplify your second constructor, removing the second mem-initializer.</p>\n<p>That is, if <code>Node</code> should even have anything but its data members. I personally prefer to have my <code>Node</code>'s not getting in the way when implementing my containers.</p>\n<h1>Floyd's algorithm</h1>\n<p>The name <code>detect_cycle_constant_time()</code> is a bald-faced lie. The algorithm needs linear time in the number of nodes.</p>\n<p>Doing an early return would simplify your code. As you don't allocate any resources, there goes the only argument against. Doing data-flow analysis is much more involved.</p>\n<p>There are more loops than the humble <code>while</code>-loop. Sometimes, they are even useful.</p>\n<p>Using <code>auto</code> would slightly simplify your local variable definitions.</p>\n<p>Whether to use <code>class</code> or <code>typename</code> for template arguments is a matter of taste. All else being equal, I prefer brevity.</p>\n<h1>Modified Code</h1>\n<pre><code>template &lt;class T&gt;\nstruct Node {\n T val = T();\n Node* next = nullptr;\n Node() = default;\n Node(T x) : val(x) {}\n};\n\ntemplate &lt;class T&gt;\nNode&lt;T&gt;* detect_cycle_floyd(Node&lt;T&gt;* head)\n{\n auto n1 = n2 = head;\n\n do {\n if (!n2)\n return n2;\n n1 = n1-&gt;next;\n n2 = n2-&gt;next;\n if (!n2)\n return n2;\n n2 = n2-&gt;next;\n } while (n1 != n2);\n\n // second phase of Floyds's algorithm\n for (n2 = head; n1 != n2; n2 = n2-&gt;next)\n n1 = n1-&gt;next;\n return n1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T13:14:25.187", "Id": "496879", "Score": "1", "body": "`Still, there are some points which can be improved -> Aren't there always?` Love it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:24:10.587", "Id": "496889", "Score": "0", "body": "The name is pure (copy and paste like mistake) dumbness." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:27:22.900", "Id": "496890", "Score": "0", "body": "Would it be good to also add support for non copy able and/or non default constructable types? For instance `unique_ptr`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:39:26.833", "Id": "496892", "Score": "0", "body": "@DavideSpataro C&P gets to the best of us. As well as half-assed hasty and half-asleep rewrites. To support non-copyable, non default-constructible, expensive and other interesting types, *my* node-class is pretty much always a completely dumb sack of data. For various reasons, it is always composed of a links-struct (or single pointer) as the first member, and the payload as the second." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T13:05:26.300", "Id": "252246", "ParentId": "252242", "Score": "7" } }, { "body": "<p>In addition to everything mentioned in <a href=\"/a/252246/75307\">Deduplicator's answer</a>: there's no good reason to force the caller to pass a pointer to a <em>modifiable</em> node, as we should only be reading. I'd expect a signature more like</p>\n<pre><code>template &lt;typename T&gt;\nNode&lt;T&gt; const* detect_cycle(Node&lt;T&gt; const* head);\n</code></pre>\n<p>I would have liked to have seen some unit tests for this code, to prove that the behaviour is as advertised!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T13:25:16.587", "Id": "252247", "ParentId": "252242", "Score": "4" } } ]
{ "AcceptedAnswerId": "252246", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T11:06:19.150", "Id": "252242", "Score": "8", "Tags": [ "c++", "algorithm", "linked-list", "c++20" ], "Title": "Floyd's cycle-finding algorithm" }
252242
<p>quick question. I'm using Spring Boot and I created e.g. this class</p> <pre><code>public interface ProductService { Page&lt;Product&gt; getPage(Pageable pageable); } @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductRepository productRepository; @Override public Page&lt;Product&gt; getPage(String name, Pageable pageable) { return productRepository.findAll(pageable); } } </code></pre> <p>And this interface has only one implementation. And what is better to use interface with one implementation and inject interface or just create a class without interface and inject class?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T21:06:32.810", "Id": "496941", "Score": "0", "body": "Hello, this question is off-topic, since we review code, not concepts, diagrams, or outlines. [What types of questions should I avoid asking?](https://codereview.stackexchange.com/help/dont-ask)" } ]
[ { "body": "<p>The answer to this question may vary depending on the opinions regarding the various so-called &quot;good practices&quot;.</p>\n<p>If we take into account the <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">dependency inversion principle</a> (In SOLID principles), then we should always aim for our classes to depend on abstractions and not on implementations.</p>\n<p>However we could also take into account the &quot;KISS&quot; principle (Keep it stupidly simple) and in this way I could tell you that if your application is not very large or complex, then do not use an interface.</p>\n<p><strong>Answering your question</strong>: &quot;what is better to use interface with one implementation and inject interface or just create a class without interface and inject class?&quot;</p>\n<p>I recommend using an interface even if it has only one implementation, so in the future if the implementation changes, the class that depends on said interface will not be affected by said change, unless the interface signature changes as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T19:48:02.703", "Id": "496938", "Score": "3", "body": "I so much disagree with that, but this question does not belong on Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:49:55.913", "Id": "497030", "Score": "0", "body": "I would like to know your opinion, and why you disagree. I think it's important to know other points of view" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:42:13.383", "Id": "497060", "Score": "0", "body": "Because, in my opinion, you're not gaining enough from doing that. You might have decoupled implementation from the interface, but if you need to change the signature you need to change it everywhere again. Additionally, the likelihood that there will be a different implementation, so that an interface is actually needed, is most of the time non-existent. An upside might be testing, but neither am I a fan of \"pure unit-tests\", in which you mock everything and only verify that methods have been called. At that point you're not testing functionality, you're verifying diffs of the source." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T18:48:29.367", "Id": "252266", "ParentId": "252249", "Score": "1" } } ]
{ "AcceptedAnswerId": "252266", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T14:08:49.867", "Id": "252249", "Score": "0", "Tags": [ "java", "spring" ], "Title": "Spring Boot should we always use interfaces even with one implementation" }
252249
<h2>Background</h2> <p>In the field of optimal control, it is part of everyday business to solve ordinary differential equations numerically. A differential equation system or dynamic system describes e.g. the physical behavior of an object over time. Every single equation can often be associated with a special state (position, velocity, acceleration, ...). Additionally, there are the &quot;controls&quot; which are the influenceable variables in the system.</p> <p>In the development process, it is not always immediately clear how many and which states have to be used and also not exactly what controls and what states are. Therefore, this is often experimented with and the associated code is often changed.</p> <p>Therefore I want to create a software library for me and my colleagues, which makes it easy to adjust the level of detail of the equations in a system. Faulty equations would often not lead to errors at runtime but only to strange results. Therefore one goal of the library is that the compiler should already perform as many checks as possible.</p> <p>The library will later be used to map states and controls to the matrix and vector indices in a NLP-Solver. So it is important that they have consecutive indices in the background. However, this is one of the main things I really want to hide from the user.</p> <p>It is also my <code>constexpr</code> learning project.</p> <h3>Example for Situation &quot;as is&quot;</h3> <p>The following code shows a part of a class which needs to be provided for an Optimal Control Solver. It shows the function to define the ODE System and also a function to provide the Derivative-Structure. The seond one means the user defines at which Entries the <a href="https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant" rel="nofollow noreferrer">Jacobian Matrix</a> of the ODE System has non zero entries.</p> <p>My library is not ready yet to provide this structure. However, I still show it here because it shows how important it is to get the indices right.</p> <p>It is only a small section from a large example, and unfortunately it is not compilable. It is only meant to shed some light on the background and does not belong to the code I would like to have a review for.</p> <p>It shows a system which describes a moving car in a 2D plane.</p> <p>The problem we are repeatedly facing is that we change the ODE system by adding or removing states. For example if we try what happens if we do not consider the acceleration to be a control directly but more to act as a set-point control which introduces one states more an changes control and state indices. In the current case one would need to update all the indices, and if one index is wrong you will see weird behaviour in the optimization process which is really hard to pin down.</p> <p>Also important: The function <code>evalSystemDynamic</code> runs a very hot loop in the system with high demands on the time.</p> <pre class="lang-cpp prettyprint-override"><code> const std::size_t idx_xPos = 0; const std::size_t idx_yPos = 1; const std::size_t idx_orientation = 2; const std::size_t idx_velocity = 3; const std::size_t idx_steeringAngle = 4; const std::size_t idx_ctrl_acceleration = 0; const std::size_t idx_ctrl_steeringAngleAcceleration = 1; const std::size_t idx_const_finalTime = 0; const double radstand = 2.768; void SingleTrackModelSimple::evalSystemDynamic(Span&lt;double&gt; newX, Span&lt;const double&gt; xAtT, Span&lt;const double&gt; uAtT, Span&lt;const double&gt; constants, Span&lt;const double&gt; /*perturbations*/, const o2c::DiscretizedTimePoint &amp;/*timepointToEvaluate*/) const { const auto orientation = xAtT[idx_orientation]; const auto velocity = xAtT[idx_velocity]; const auto steeringAngle = xAtT[idx_steeringAngle]; const auto acceleration = uAtT[idx_ctrl_acceleration]; const auto steeringAngleAcceleration = uAtT[idx_ctrl_steeringAngleAcceleration]; newX[idx_xPos] = std::cos(orientation) * velocity; newX[idx_yPos] = std::sin(orientation) * velocity; newX[idx_orientation] = velocity * std::tan(steeringAngle) / radstand; newX[idx_velocity] = acceleration; newX[idx_steeringAngle] = steeringAngleAcceleration; const auto finalTime = constants[idx_const_finalTime]; std::transform(newX.begin(), newX.end(), newX.begin(), [finalTime](const auto stateValue){ return stateValue * finalTime;}); } void SingleTrackModelSimple::getSystemDynamicDerivativeStructure(o2c::TransWorhpDiffStructure &amp;diffStruct, const o2c::StaticIndexHandler &amp;idx) const { diffStruct.setEntry(idx_xPos, idx.varIndex(idx_velocity)); diffStruct.setEntry(idx_xPos, idx.varIndex(idx_orientation)); diffStruct.setEntry(idx_xPos, idx.constantsIndex(idx_const_finalTime)); diffStruct.setEntry(idx_yPos, idx.varIndex(idx_velocity)); diffStruct.setEntry(idx_yPos, idx.varIndex(idx_orientation)); diffStruct.setEntry(idx_yPos, idx.constantsIndex(idx_const_finalTime)); diffStruct.setEntry(idx_orientation, idx.varIndex(idx_velocity)); diffStruct.setEntry(idx_orientation, idx.varIndex(idx_steeringAngle)); diffStruct.setEntry(idx_orientation, idx.constantsIndex(idx_const_finalTime)); diffStruct.setEntry(idx_velocity, idx.ctrlIndex(idx_ctrl_acceleration)); diffStruct.setEntry(idx_velocity, idx.constantsIndex(idx_const_finalTime)); diffStruct.setEntry(idx_steeringAngle, idx.ctrlIndex(idx_ctrl_steeringAngleAcceleration)); diffStruct.setEntry(idx_steeringAngle, idx.constantsIndex(idx_const_finalTime)); } </code></pre> <h2>Code To Review</h2> <h3>Prerequesites</h3> <p>My target platform is Linux and C++20, you can find compiling code under <a href="https://godbolt.org/z/3GY6q7" rel="nofollow noreferrer">https://godbolt.org/z/3GY6q7</a></p> <p>I use the gsl for gsl/span, which could also be replaced by std::span.</p> <h3>The Library</h3> <p><strong>DynamicSystem.hpp</strong></p> <p>At the center of the software is the DynamicSystem class. It receives a list of states and a list of controls from the user. In addition, the type of ID can be identified via the states and controls.</p> <p>During the design, I have tuples for the lists in my head, because the states and controls are single classes. For the IdType I have an enum in my head, because this guarantees the uniqueness. But this is ultimately up to the user.</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;StateAccessor.hpp&quot; #include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;utility&gt; #include &lt;tuple&gt; #include &lt;gsl/span&gt; namespace cmplode { namespace detail { template&lt;typename&gt; struct array_size; template&lt;typename T, size_t N&gt; struct array_size&lt;std::array&lt;T, N&gt;&gt; { static size_t const size = N; }; template&lt;class States, class StateMapper, std::size_t I = 0, typename... Tp&gt; inline typename std::enable_if&lt;I == sizeof...(Tp), void&gt;::type ode([[maybe_unused]] const std::tuple&lt;Tp...&gt;&amp; t, [[maybe_unused]] States&amp; out, [[maybe_unused]] const StateMapper&amp; in) {} template&lt;class States, class StateMapper, std::size_t I = 0, typename... Tp&gt; inline typename std::enable_if &lt; I&lt;sizeof...(Tp), void&gt;::type ode(const std::tuple&lt;Tp...&gt;&amp; t, States&amp; out, const StateMapper&amp; in) { static_assert(I &lt; std::tuple_size_v&lt;States&gt;); out[I] = std::get&lt;I&gt;(t).ode(in); ode&lt;States, StateMapper, I + 1, Tp...&gt;(t, out, in); } }// namespace detail template&lt;class IdType, class StateList, class ControlList&gt; class DynamicSystem { public: constexpr DynamicSystem(StateList states_, ControlList /*controlTypes_*/) : states(std::move(states_)) { } constexpr auto getNumberOfStates() const { return std::tuple_size_v&lt;StateList&gt;; } constexpr auto getNumberOfControls() const { return std::tuple_size_v&lt;ControlList&gt;; } template&lt;class States, class Controls&gt; constexpr void ode(States&amp; lhs, const States&amp; stateValues, const Controls&amp; controlValues) const { const StateAccessor&lt;IdType, StateList, ControlList&gt; stateMapper(stateValues, controlValues); detail::ode(states, lhs, stateMapper); } private: StateList states; }; }// namespace cmplode </code></pre> <p><strong>StateAccessor.hpp</strong></p> <p>The StateAccessor also receives the states and controls as a list. It is intended to map from an IdType id to an internal index and hide the difference between state and control from the outside.</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;OdeIndexMap.hpp&quot; #include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;tuple&gt; #include &lt;gsl/span&gt; namespace cmplode { template&lt;int... Indices&gt; struct indices { using next = indices&lt;Indices..., static_cast&lt;int&gt;(sizeof...(Indices))&gt;; }; template&lt;int Size&gt; struct build_indices { using type = typename build_indices&lt;Size - 1&gt;::type::next; }; template&lt;&gt; struct build_indices&lt;0&gt; { using type = indices&lt;&gt;; }; template&lt;typename T&gt; using Bare = typename std::remove_cv&lt;typename std::remove_reference&lt;T&gt;::type&gt;::type; template&lt;typename Tuple&gt; constexpr typename build_indices&lt;std::tuple_size&lt;Bare&lt;Tuple&gt;&gt;::value&gt;::type make_indices() { return {}; } template&lt;typename Tuple, int... Indices&gt; constexpr std::array&lt; typename std::tuple_element&lt;0, Bare&lt;Tuple&gt;&gt;::type, std::tuple_size&lt;Bare&lt;Tuple&gt;&gt;::value&gt; to_array(Tuple&amp;&amp; tuple, indices&lt;Indices...&gt;) { using std::get; return { { get&lt;Indices&gt;(std::forward&lt;Tuple&gt;(tuple))... } }; } template&lt;typename Tuple&gt; constexpr auto to_array(Tuple&amp;&amp; tuple) -&gt; decltype(to_array(std::declval&lt;Tuple&gt;(), make_indices&lt;Tuple&gt;())) { return to_array(std::forward&lt;Tuple&gt;(tuple), make_indices&lt;Tuple&gt;()); } template&lt;typename... Ts, typename Function, size_t... Is&gt; constexpr auto transform_impl(std::tuple&lt;Ts...&gt; const&amp; inputs, Function function, std::index_sequence&lt;Is...&gt;) { return std::tuple&lt;std::result_of_t&lt;Function(Ts)&gt;...&gt;{ function(std::get&lt;Is&gt;(inputs))... }; } template&lt;typename... Ts, typename Function&gt; constexpr auto transform(std::tuple&lt;Ts...&gt; const&amp; inputs, Function function) { return transform_impl(inputs, function, std::make_index_sequence&lt;sizeof...(Ts)&gt;{}); } template&lt;class StateList&gt; constexpr auto create_id_array(const StateList&amp; usedStates) { return to_array(transform(usedStates, [](const auto state) { return state.id; })); } template&lt;class IdType, class StateList, class ControlList&gt; class StateAccessor { public: template&lt;class States, class Controls&gt; constexpr StateAccessor(const States&amp; states, const Controls&amp; controls) : state_values{ gsl::span(states.data(), static_cast&lt;gsl::span&lt;const double&gt;::size_type&gt;(states.size())) }, control_values{ gsl::span(controls.data(), static_cast&lt;gsl::span&lt;const double&gt;::size_type&gt;(controls.size())) } { } template&lt;IdType id&gt; constexpr double value_of() const { constexpr OdeIndexMap&lt;IdType, std::tuple_size_v&lt;StateList&gt;&gt; id_to_idx_states(create_id_array(StateList())); constexpr OdeIndexMap&lt;IdType, std::tuple_size_v&lt;ControlList&gt;&gt; id_to_idx_controls(create_id_array(ControlList())); if constexpr (id_to_idx_states.has_id(id)) { return state_values[id_to_idx_states.idx_of(id)]; } if constexpr (id_to_idx_controls.has_id(id)) { return control_values[id_to_idx_controls.idx_of(id)]; } assert(false &amp;&amp; &quot;Unkown Id&quot;); return 0.0; } private: gsl::span&lt;const double&gt; state_values{}; gsl::span&lt;const double&gt; control_values{}; }; }// namespace cmplode </code></pre> <p><strong>OdeIndexMap.hpp</strong></p> <p>The OdeIndexMap is a <code>constexpr</code> map from IdType to a std::size_t index. The indices are sequential from 0 to the number of states.</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;algorithm&gt; namespace cmplode { template&lt;class IdList, class IdType&gt; constexpr auto compute_ode_index(const IdList&amp; ids, IdType id) { const auto posIt = std::find(std::begin(ids), std::end(ids), id); return std::distance(std::begin(ids), posIt); } template&lt;class Idtype, std::size_t numberIds&gt; struct OdeIndexMap { constexpr OdeIndexMap(std::array&lt;Idtype, numberIds&gt; usedIds_) : usedIds{ std::move(usedIds_) } { } std::array&lt;Idtype, numberIds&gt; usedIds; constexpr auto idx_of(Idtype wantedId) const { return compute_ode_index(usedIds, wantedId); } constexpr bool has_id(Idtype id) const { return std::find(std::begin(usedIds), std::end(usedIds), id) != std::end(usedIds); } }; }// namespace cmplode </code></pre> <h3>User Code</h3> <p>I created a small example for a system which describes a 1D movement with the states Position and Velocity and the control Acceleration.</p> <p><strong>States.hpp</strong></p> <p>States.hpp represents a library done by the user. The idea is that users create the possible states for their domain once and later put together systems from the possible states.</p> <pre><code>#pragma once #include &lt;cstdint&gt; #include &lt;tuple&gt; namespace cmplode { enum class state_ids { position_x = 0, velocity = 1, acceleration = 2 }; class position_x { public: constexpr static state_ids id = state_ids::position_x; template&lt;class States&gt; constexpr static double ode(const States&amp; in) { return in.template value_of&lt;state_ids::velocity&gt;(); } }; class velocity { public: constexpr static state_ids id = state_ids::velocity; template&lt;class States&gt; constexpr static double acc_from(const States&amp; in) { return in.template value_of&lt;state_ids::acceleration&gt;(); } template&lt;class States&gt; constexpr static double ode(const States&amp; in) { return acc_from(in); } }; class acceleration { public: constexpr static state_ids id = state_ids::acceleration; template&lt;class States&gt; constexpr static double ode(const States&amp; /*in*/) { return 3.0; } }; }// namespace cmplode </code></pre> <p><strong>main.cpp</strong></p> <p>I created a main.cpp to get compiling code in the compiler explorer. However, it is not the actual usecase since that one is more complex and hard to add completely to compiler explorer (which I want to do, to get some insight).</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;States.hpp&quot; #include &quot;DynamicSystem.hpp&quot; #include &lt;array&gt; #include &lt;tuple&gt; #include &lt;iostream&gt; using id = cmplode::state_ids; int main() { constexpr std::tuple&lt;cmplode::position_x, cmplode::velocity&gt; diffGl; constexpr std::tuple&lt;cmplode::acceleration&gt; controlsTypes; constexpr cmplode::DynamicSystem&lt;id, decltype(diffGl), decltype(controlsTypes)&gt; dynamic(diffGl, controlsTypes); static_assert(dynamic.getNumberOfStates() == 2); static_assert(dynamic.getNumberOfControls() == 1); std::array states{ 0.0, 1.0 }; constexpr std::array controls{ 2.0 }; std::array statesOut{ 0.0, 1.0 }; for (int iteration = 0; iteration &lt; 1000; ++iteration) { dynamic.ode(statesOut, states, controls); std::transform(statesOut.begin(), statesOut.end(), states.begin(), states.begin(), [](const auto&amp; stateDiff, const auto state) { return state + 1e-03 * stateDiff; }); } std::copy(std::begin(states), std::end(states), std::ostream_iterator&lt;double&gt;(std::cout, &quot; &quot;)); } </code></pre> <h2>Questions</h2> <p>I would be very interested in receiving feedback on the use of constexpr features. Especially if I am making something too complicated somewhere or if some functions can be replaced by existing STL functionality. Most of the basic constexpr and template functionality I got with googling and you will probably find it on Stack Overflow.</p> <p>I would also be interested if there is a way around using the &quot;template&quot; keyword in <code>States.hpp</code> in the ode features. I already tried to make the value_of function a free function or use the id as a function parameter and not as a template. The latter prevented the constexpr if in the StateAccessor and the free function didn't work in my attempt.</p> <p>You can also see a wrapper function in velocity in <code>States.hpp</code> for the acceleration. This helps but still requires the template keyword by the user at some place.</p> <p>Overall I am not satisfied with the IdType system. The need to explicitly specify it in the templates, and thus the use of <code>decltype</code>, but also the only indirect connection of the enum to the state classes bothers me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T18:32:52.423", "Id": "496931", "Score": "1", "body": "Why did you add both C++17 and C++20 tags? What version of the C++ language do you target?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:22:36.913", "Id": "496983", "Score": "1", "body": "I added both because some features used are from c++17 and some c++20. But you are right, should probably only be c++20 then." } ]
[ { "body": "<h1>Your code is too complicated</h1>\n<p>I know ODEs, I know what control systems are, but sadly I have to say that knowing this doesn't make your code any easier to understand. I would not want to use this code, because the distance between how you would write a differential equation on paper and the code you have to write here is just too great. Let's start with <code>main()</code>:</p>\n<pre><code>int main()\n{\n constexpr std::tuple&lt;cmplode::position_x, cmplode::velocity&gt; diffGl;\n constexpr std::tuple&lt;cmplode::acceleration&gt; controlsTypes;\n\n constexpr cmplode::DynamicSystem&lt;id, decltype(diffGl), decltype(controlsTypes)&gt; dynamic(diffGl, controlsTypes);\n</code></pre>\n<p>Ok, I see you have a tuple of position and velocity, and a tuple of acceleration. So since the last one is named <code>controlsTypes</code>, I assume this is what you control in your system, and the rest just evolves according to the control variables. You then create a &quot;dynamic system&quot; (I think you mean <a href=\"https://en.wikipedia.org/wiki/Dynamical_system\" rel=\"nofollow noreferrer\">dynamical system</a>) of these variables. But where is the relation between all of them?</p>\n<p>I have to look in States.hpp to figure out that <code>cmplode::position_x</code> is a type that has a function <code>ode()</code> that reads the value of <code>state_ids::velocity</code> from <code>in</code>. Ok but position is not velocity, position is velocity multiplied by time. Where is the time evolution done? There is nothing in any of the .hpp files that do any calculations whatsoever. In fact, the only thing your <code>constexpr</code> <code>template</code> machinery does is shifting variables! The real calculation is done inside the loop in <code>main()</code>:</p>\n<pre><code> for (int iteration = 0; iteration &lt; 1000; ++iteration) {\n dynamic.ode(statesOut, states, controls);\n\n std::transform(statesOut.begin(), statesOut.end(), states.begin(), states.begin(), [](const auto&amp; stateDiff, const auto state) {\n return state + 1e-03 * stateDiff;\n });\n }\n</code></pre>\n<p>Compare that to the following where the exact same calculation is performed:</p>\n<pre><code> std::array variables{0.0, 1.0, 2.0}; // position, velocity, acceleration\n\n for (int iteration = 0; iteration &lt; 1000; ++iteration) {\n std::transform(variables.begin(), variables.end() - 1, variables.begin() + 1, variables.begin(), [](auto variable, auto derivative) {\n return variable + 1e-03 * derivative;\n });\n }\n</code></pre>\n<p>That's it! Now, there is some flexibility in your code, if you add more templated classes to States.hpp, but I don't really see how this extremely complicated way to add things there is safer and less error prone than just writing out this code in the most naive way:</p>\n<pre><code>double position = 0.0;\ndouble velocity = 1.0;\nconst double acceleration = 2.0;\nconst double dt = 1e-3;\n\nfor (double t = 0; t &lt; 1; t += dt) {\n position += velocity * dt;\n velocity += acceleration * dt;\n}\n\nstd::cout &lt;&lt; &quot;Position at t = &quot; &lt;&lt; t &lt;&lt; &quot;: &quot; &lt;&lt; position &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n<h1>The code does not prevent errors</h1>\n<blockquote>\n<p>Faulty equations would often not lead to errors at runtime but only to strange results. Therefore one goal of the library is that the compiler should already perform as many checks as possible.</p>\n</blockquote>\n<p>I don't think your code prevents any errors. I can still accidentily make <code>position_x::ode()</code> return <code>in.template value_of&lt;state_ids::acceleration&gt;()</code>. A mistake like this is easy if someone copy&amp;pastes one class to make another one, and forgets to update some part of the new class. This code will compile fine of course.</p>\n<p>But there is another issue: I can create <code>state_ids</code> with duplicate entries, like so:</p>\n<pre><code>enum class state_ids {\n position_x = 0,\n velocity = 1,\n acceleration = 1\n};\n</code></pre>\n<p>This will compile without errors or warnings, nor will there be any runtime errors, but it will cause strange results.</p>\n<h1>Use of <code>constexpr</code></h1>\n<blockquote>\n<p>I would be very interested in receiving feedback on the use of constexpr features. Especially if I am making something too complicated somewhere or if some functions can be replaced by existing STL functionality.</p>\n</blockquote>\n<p>Making functions and variables <code>constexpr</code> is usually a good thing. But don't go out of your way to make code much more complicated than necessary just to make it <code>constexpr</code>, unless you have a very good reason to do so. A <code>constexpr</code> function is not guaranteed to be run at compile-time; the compiler can decide to evaluate them at run-time. Conversely, a compiler could take a non-<code>constexpr</code> function, deduce that it can calculate everything it does at compile-time, and just have it return a pre-compiled answer.</p>\n<h1>Avoiding the template keyword</h1>\n<blockquote>\n<p>I would also be interested if there is a way around using the &quot;template&quot; keyword in States.hpp in the ode features.</p>\n</blockquote>\n<p>The reason you need this is because <code>position_x::ode()</code> is a template, not a real function. So at the time the compiler tries to parse it, it does not know the type of <code>in</code>, it can be anything after all, so it also doesn't know what type <code>in.value_of</code> is. In particular, in order to correctly parse the token <code>&lt;</code>, it has to know if <code>value_of</code> is a template or not. If it is not, it would assume <code>&lt;</code> is the lesser-than operator. At instatiation time it will use the already parsed tokens, it will not reread the actual lines of code, and this will cause an error, unless you manually add the <code>template</code> keyword.</p>\n<p>I do not see a way around this here, a free-standing function would also need to be a template and thus will have exactly the same problem. The only other solution is to make <code>id</code> a regular parameter of <code>StateAccessor::value_of()</code>, but of course that would prevent you from using <code>constexpr</code> <code>if</code>-statements.</p>\n<h1>Alternatives to the <code>IdType</code> system</h1>\n<blockquote>\n<p>Overall I am not satisfied with the IdType system. The need to explicitly specify it in the templates, and thus the use of decltype, but also the only indirect connection of the enum to the state classes bothers me.</p>\n</blockquote>\n<p>Indeed, it would be better to avoid this, and intead make it possible to just refer to variables directly by name? Again, I would go back to basics, and try to avoid involving templates unless it is really necessary. You could create a <code>struct</code> with the variables of the system, and then just refer to the variable names when updating the state:</p>\n<pre><code>struct {\n double position{0.0};\n double velocity{1.0};\n double acceleration{2.0};\n\n void update(double dt) {\n position += velocity * dt;\n velocity += acceleration * dt;\n }\n} system;\n</code></pre>\n<p>Or make it more abstract and just define the ODE as an array, with each element always being the derivative of the previous element:</p>\n<pre><code>struct {\n std::array&lt;double, 3&gt; variables;\n\n void update(double dt) {\n for (size_t i = 0; i &lt; variables.size() - 1; ++i)\n variables[i] += variables[i + 1] * dt;\n }\n} system;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:27:50.557", "Id": "496984", "Score": "0", "body": "Thanks for your answer. Unfortunately I think you have misunderstood the meaning of the library. It is not meant to be a solver for ODEs, but a way to write ODEs in a way that you can use them in our solver. For this we need the exact indices of single equations in many places and if you change something you have to adjust all indices in the whole code. Therefore index shifting is what really counts. So the user can identify the states by \"name\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T08:02:44.143", "Id": "496988", "Score": "0", "body": "Ok, maybe I did misunderstand it then, although I still think the code is very complex just for that. But can you give a concrete example of how you did it before, and what could go wrong that your code solves?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T07:52:50.350", "Id": "497144", "Score": "0", "body": "On the point of complexity you might be right. I added an example for how we do it right now and tried to explain the problem. I hope it becomes more clear." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T21:22:02.337", "Id": "252273", "ParentId": "252251", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T15:14:44.893", "Id": "252251", "Score": "5", "Tags": [ "c++", "template-meta-programming", "c++20", "constant-expression" ], "Title": "Compiletime (constexpr) Differential Equation System Description for use in Optimal Control" }
252251
<p>I need to find the odd occurring numbers as a list. For example the below list should give 1 and 2 as output.</p> <p>Is there a way that I can do it in a better way?</p> <pre><code>ArrayList&lt;Integer&gt; numbers = new ArrayList&lt;&gt;(Arrays.asList(1,2,2,4,2,4)); List&lt;Integer&gt; OddOcuranceNumbers = numbers.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet().stream() .filter(map -&gt; map.getValue() % 2 == 1).map(s -&gt; s.getKey()) .collect(Collectors.toList()); System.out.println(OddOcuranceNumbers); } </code></pre>
[]
[ { "body": "<p>That depends on how you define <em>better</em>. Better might be more CPU or memory efficient, or it could be fewer bytes in the compiled code, or better parallelization.</p>\n<p>But I am going to take a chance on assuming that this code runs on a reasonably normal platform and has no special requirements, and therefore being better generally means better <em>readability</em>.</p>\n<h2>Readability Improvements</h2>\n<p>In which case, your code is fine. But we can make it easier to read by splitting it into named steps and wrapping it in a good function.</p>\n<pre><code>public List&lt;Integer&gt; getNumbersOccuringOddTimes(final List&lt;Integer&gt; numbers) {\n final Map&lt;Integer, Integer&gt; numberCounts = numbers.stream().collect(groupingBy(Function.identity(), counting()));\n final Predicate&lt;Entry&gt; isOdd = e -&gt; e.getValue() % 2 == 1;\n return numberCounts.entrySet().stream().filter(isOdd).map(Entry::getKey).collect(toList());\n}\n</code></pre>\n<p>I've made five minor adjustments to your code to help with readability. I have;</p>\n<ol>\n<li>Added a descriptive method name that wraps the steps.</li>\n<li>Split the two streams into separate statements.</li>\n<li>Used static imports (not shown) for the Collectors functions.</li>\n<li>Moved the modulus check into a predicate variable (<code>isOdd</code>) so it can be named.</li>\n<li>Swapped out the lambda in <code>.map</code> to a method reference because it is shorter and more descriptive.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:01:45.703", "Id": "496967", "Score": "2", "body": "Surely you're not suggesting that two 100 character one liner stream operations are more readable than... well anything? :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T19:36:27.167", "Id": "252269", "ParentId": "252254", "Score": "2" } }, { "body": "<p>As Rudi Kershaw said, there isn't much to fix technically. Whatever your way of implementation is, you need to count the occurences, select the odd ones and collect the values. Streams are not inherently readable so what you can do is to concentrate on the presentation a bit more. The variable names you use are either straight out confusing or just not very descriptive.</p>\n<p>For example, you're processing <code>Map.Entry</code> objects, not <code>Map</code> objects, when filtering out the odd ones. Thus use <code>entry</code> in the lambda instead of <code>map</code>:</p>\n<pre><code>.filter(entry -&gt; entry.getValue() % 2 == 1)\n</code></pre>\n<p>Likewise when picking the keys from the entries, use a variable name that describes the object being processed:</p>\n<pre><code>.map(entry -&gt; entry.getKey())\n</code></pre>\n<p>With those changes and some formatting, your code becomes this. For someone who is familiar with common stream concepts, this should be pretty clear.</p>\n<pre><code>List&lt;Integer&gt; oddOcuranceNumbers = numbers.stream()\n .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))\n .entrySet().stream()\n .filter(entry -&gt; entry.getValue() % 2 == 1)\n .map(entry -&gt; entry.getKey())\n .collect(Collectors.toList());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:17:22.253", "Id": "252284", "ParentId": "252254", "Score": "1" } } ]
{ "AcceptedAnswerId": "252269", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T15:43:02.377", "Id": "252254", "Score": "3", "Tags": [ "java", "stream" ], "Title": "Multiple filters and maps java stream" }
252254
<p><strong>UPDATE:</strong> After getting &quot;a kind of&quot; affirmation from various platforms( my discussions on twitter, reddit, other stack overflow posts,etc) I have written <a href="https://anshsachdevawork.medium.com/using-view-binding-with-convenience-87979c680707" rel="nofollow noreferrer">an article on this style of view binding.</a> Kindly check that out too, as that's the only place i am currently updating my latest version of the code (It's not behind the paywall and is completely free) . I will be happy to discuss the improvements on either of the platforms or bring those changes here too if needed.</p> <hr /> <p>Another non-android wording of this question could be : &quot;Implementation that Prevents a child class from using a value that child class itself provided to the parent class&quot;.</p> <hr /> <p><strong>Requirement</strong> : I have been using inheritance extensively in a personal project where base abstract activity and fragment classes would handle most of the work and expose only empty functions that are optionally extendible by the children fragment/activities. One of those work would be to inflate the layout. The child class would provide the layout as an overridden variable and the task of inflating the layout would be for the base classes. Eg:</p> <pre class="lang-kotlin prettyprint-override"><code>abstract class BaseActivityCurrent :AppCompatActivity(){ abstract val contentView: Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(contentView) setup() } abstract fun setup() } abstract class BaseFragmentCurrent : Fragment(){ abstract val contentView: Int override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(contentView,container,false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setup() } open fun setup(){} } </code></pre> <p>The child classes would just require to provide the layout res and optionally provide <code>setup()</code></p> <hr /> <p>Now i wish to move to view binding with the similar architecture. As There are no ways to access the correct binding class using just the layoutres, i need child classes to provide the instance of binding class. But at the same time, i would want to manage the binding class instance in the base activity/fragment, because they are supposed to manage lifecycles. So I cam up with this solution that uses effectively final variables. here is the code for base classes and their associated child classes:</p> <p>Base Binding activity and fragment:</p> <pre class="lang-kotlin prettyprint-override"><code> abstract class BaseActivityFinal&lt;VB_CHILD : ViewBinding&gt; : AppCompatActivity() { private var binding: VB_CHILD? = null //lifecycle override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(getInflatedLayout(layoutInflater)) setup() } override fun onDestroy() { super.onDestroy() this.binding = null } //internal functions private fun getInflatedLayout(inflater: LayoutInflater): View { val tempList = mutableListOf&lt;VB_CHILD&gt;() attachBinding(tempList, inflater) this.binding = tempList[0] return binding?.root?: error(&quot;Please add your inflated binding class instance at 0th position in list&quot;) } //abstract functions abstract fun attachBinding(list: MutableList&lt;VB_CHILD&gt;, layoutInflater: LayoutInflater) abstract fun setup() //helpers fun withBinding(block: (VB_CHILD.() -&gt; Unit)?): VB_CHILD { val bindingAfterRunning:VB_CHILD? = binding?.apply { block?.invoke(this) } return bindingAfterRunning ?: error(&quot;Accessing binding outside of lifecycle: ${this::class.java.simpleName}&quot;) } } //-------------------------------------------------------------------------- abstract class BaseFragmentFinal&lt;VB_CHILD : ViewBinding&gt; : Fragment() { private var binding: VB_CHILD? = null //lifecycle override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = getInflatedView(inflater, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setup() } override fun onDestroy() { super.onDestroy() this.binding = null } //internal functions private fun getInflatedView( inflater: LayoutInflater, container: ViewGroup?, attachToRoot: Boolean ): View { val tempList = mutableListOf&lt;VB_CHILD&gt;() attachBinding(tempList, inflater, container, attachToRoot) this.binding = tempList[0] return binding?.root ?: error(&quot;Please add your inflated binding class instance at 0th position in list&quot;) } //abstract functions abstract fun attachBinding( list: MutableList&lt;VB_CHILD&gt;, layoutInflater: LayoutInflater, container: ViewGroup?, attachToRoot: Boolean ) abstract fun setup() //helpers fun withBinding(block: (VB_CHILD.() -&gt; Unit)?): VB_CHILD { val bindingAfterRunning:VB_CHILD? = binding?.apply { block?.invoke(this) } return bindingAfterRunning ?: error(&quot;Accessing binding outside of lifecycle: ${this::class.java.simpleName}&quot;) } } </code></pre> <p>Child activity and fragment:</p> <pre class="lang-kotlin prettyprint-override"><code> class MainActivityFinal:BaseActivityFinal&lt;MainActivityBinding&gt;() { var i = 0 override fun setup() { supportFragmentManager.beginTransaction() .replace(R.id.container, MainFragmentFinal()) .commitNow() viewBindingApproach() } private fun viewBindingApproach() { withBinding { btText.setOnClickListener { tvText.text = &quot;The current click count is ${++i}&quot; } btText.performClick() } } override fun attachBinding(list: MutableList&lt;MainActivityBinding&gt;, layoutInflater: LayoutInflater) { list.add(MainActivityBinding.inflate(layoutInflater)) } } //------------------------------------------------------------------- class MainFragmentFinal : BaseFragmentFinal&lt;MainFragmentBinding&gt;() { override fun setup() { bindingApproach() } private fun bindingApproach() { withBinding { rbGroup.setOnCheckedChangeListener{ _, id -&gt; when(id){ radioBt1.id -&gt; tvFragOutPut.text = &quot;You Opt in for additional content&quot; radioBt2.id -&gt; tvFragOutPut.text = &quot;You DO NOT Opt in for additional content&quot; } } radioBt1.isChecked = true radioBt2.isChecked = false cbox.setOnCheckedChangeListener { _, bool -&gt; radioBt1.isEnabled = !bool radioBt2.isEnabled = !bool } } } override fun attachBinding( list: MutableList&lt;MainFragmentBinding&gt;, layoutInflater: LayoutInflater, container: ViewGroup?, attachToRoot: Boolean ) { list.add(MainFragmentBinding.inflate(layoutInflater,container,attachToRoot)) } } </code></pre> <p>Kindly review and let me know and if this could be improved. As you see ,I am using effectively final variables to prevent the children activities from using the view binding directly, that's why i initially worded the question differently. Can this made more elegant? Is there a better way to achieve what this code does?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T16:57:42.020", "Id": "252257", "Score": "3", "Tags": [ "android", "generics", "inheritance", "kotlin" ], "Title": "View Binding with Base Classes" }
252257
<p>I have the following implementation that takes in symmetric matrix W and returns matrix C</p> <pre><code>import torch import numpy as np import time W = torch.tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0, 0], [0, 1, 0, 3, 0, 0, 0, 0, 0], [0, 0, 3, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1, 0]]) A = W.clone() [n_node, _] = A.shape nI = n_node * torch.eye(n_node) # -- method 1 C = torch.empty(n_node, n_node) for i in range(n_node): for j in range(i, n_node): B = A.clone() B[i, j] = B[j, i] = 0 C[i, j] = C[j, i] = torch.inverse(nI - B)[i, j] </code></pre> <p>As you can see, I have a matrix <code>nI - B</code> and change one element at each loop and compute its inverse. Im trying to use <a href="https://cs.stackexchange.com/questions/9875/computing-inverse-matrix-when-an-element-changes">Sherman-Morrison formula</a> to enhance the performance of the code. Here is my implementation:</p> <pre><code># -- method 2 c = torch.empty(n_node, n_node) inv_nI_A = torch.inverse(nI - A) b = torch.div(A, 1 + torch.einsum('ij,ij-&gt;ij', A, inv_nI_A)) inv_nI_A_ = inv_nI_A.unsqueeze(1) for i in range(n_node): for j in range(i, n_node): c[i, j] = c[j, i] = (inv_nI_A - b[i, j] * torch.matmul(inv_nI_A_[:, :, i], inv_nI_A_[j, :, :]))[i, j] </code></pre> <p>I was wondering if I can do further enhancements on my implementation. Thanks!</p> <p>PS: W is not necessarily a sparse matrix.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:37:50.547", "Id": "497233", "Score": "0", "body": "Based on the Sherman-Morrison formula, it seems that further mathematical simplifications can be done to throw away for-loops completely (and replace them with implicit vectorized PyTorch operations). BTW, your 'method 1' code does not incorporate all the improvements in the code of my previous review. E.g., copying the entire matrix using A.clone() in each loop might be more readable but it is really inefficient when only two elements need to be changed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:06:53.213", "Id": "497338", "Score": "0", "body": "@GZ0 1. It isn't immediately clear to me how to get rid of the final loop. 2. Thanks for bringing the 'A.clone()' part to my attention. 3. I forgot to mark your answer as accepted, thanks for the review again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T21:37:17.417", "Id": "497459", "Score": "0", "body": "Inside each loop only one element needs to be calculated. Based on the Sherman-Morrison formula, it is possble to do just that rather than computing the entire matrix inverse for accessing the element." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:13:51.130", "Id": "252258", "Score": "2", "Tags": [ "python", "pytorch" ], "Title": "Computing inverse of modified matrix using Sherman-Morrison formula" }
252258
<p>I had an idea recently of simplifying some of the code I already have in my Android app that uses Kotlin. I somewhat new to Kotlin, so any opinion would be very appreciated.</p> <p>Before giving you what idea I had, I will give a base example of what code I have right now:</p> <p>Lets say that in my app I have a functionality for user to log in and save his credentials for automatic future logging in. Here it is in code.</p> <pre><code>object MyRepository { // Plenty of irrelevant code here... fun getUserInfo(): User? { // Here we fetch the local data storage and check if any credentials are saved return userInfoDao.getUserInformation() } fun setUserInfo(user: User) { // Here we save user credentials to local data storage for future uses userInfoDao.saveUserInformation(user) } } </code></pre> <p>This lead me to think that something like this could be done in a simpler manner, and here is the example:</p> <pre><code>object MyRepository { var userInfo: User? get() = userInfoDao.getUserInformation() set(value) = userInfoDao.saveUserInformation(value) } } </code></pre> <p>This of course is much simpler version of what was written above. However, what I am curious is how good of a practice this is in terms of Kotlin standards and general code readability?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:47:42.720", "Id": "496925", "Score": "0", "body": "\"This of course is much simpler version of what was written above.\" - How much have you omitted really? Please note that in order to give the best review possible, we need to get as much context as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:49:24.860", "Id": "496926", "Score": "0", "body": "@SimonForsberg what I am talking about is that in my opinion, using one variable instead of 2 functions is a much simpler approach to coding. What I omitted has no contextual benefits to the code I provided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:52:30.817", "Id": "496929", "Score": "0", "body": "I will personally let it be for now, but I would like to take the opportunity to point out - in case you are not aware - that there is a close reason on this site which is: *Missing Review Context: 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.*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T18:56:01.207", "Id": "496934", "Score": "0", "body": "I would personally give this a green signal. I can't say much about it as am myself very new to the development world, but our team has a 2yo product with a significant database and we use code similar to this for accessing sharedPreferences but not really in local databases" } ]
[ { "body": "<p>Generally speaking, I would not expect a database call to be made simply by referring to a property, such as with <code>val user = MyRepository.userInfo</code>. If a database call is being made, it's better to have a function for it.</p>\n<p>I'd even argue that it would even be better to name the function <code>fetchUserInformation</code> than <code>getUserInformation</code> to be clear that this is not just a simple getter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-07T14:39:48.723", "Id": "501756", "Score": "2", "body": "To elaborate on this, I would use getters/setters on properties exclusively for computed properties, i.e. derived from some other properties in the class." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:50:01.907", "Id": "252262", "ParentId": "252259", "Score": "5" } } ]
{ "AcceptedAnswerId": "252262", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:29:33.850", "Id": "252259", "Score": "1", "Tags": [ "kotlin" ], "Title": "Kotlin fake properties and their usage" }
252259
<p>I work with the <code>GoogleMaps</code> API, using <code>React.js</code>.</p> <p>Inside the <code>GoogleMap</code> component:</p> <ul> <li><p>I have a component called <code>UserLocationTimer</code>, which activates <code>setInterval</code> within <code>useEffect</code> and samples the user's location every 2 seconds, centering the map accordingly. In addition, returns the <code>UserLocation</code> component that displays the marker of the user's location on the map.</p> </li> <li><p>In case the user drags the map, I catch the event <code>isDragged</code>, and return only the <code>UserLocation</code> component that displays the marker of the user's location on the map.</p> </li> </ul> <p>It works fine, however, how would you optimize this code? Is there a more efficient way to catch the dragging event and stopping the timer interval from the parent, instead using conditional rendering?</p> <pre><code> &lt;GoogleMap . . . onDrag={(map) =&gt; { setIsDragged(true); }} onDragEnd={(map) =&gt; { setIsDragged(true); }} &gt; . . . {!isDragged &amp;&amp; ( &lt;UserLocationTimer userLocation={userLocation} setUserLocation={setUserLocation} panTo={panTo} &gt;&lt;/UserLocationTimer&gt; )} {isDragged &amp;&amp; ( &lt;UserLocation userLocation={userLocation}&gt;&lt;/UserLocation&gt; )} &lt;/GoogleMap&gt; </code></pre> <ul> <li></li> </ul> <pre><code>export const UserLocationTimer = (props) =&gt; { const [timer, setTimer] = useState(null); useEffect(() =&gt; { const interval = setInterval(() =&gt; { setTimer(new Date()); locateMe(); }, 2000); return () =&gt; clearInterval(interval); }, []); function locateMe() { // locating using geolocation... } return ( &lt;&gt; {timer &amp;&amp; &lt;UserLocation userLocation={props.userLocation}&gt;&lt;/UserLocation&gt;} &lt;/&gt; ); }; </code></pre> <ul> <li></li> </ul> <pre><code>export const UserLocation = (props) =&gt; { if (props.userLocation) return ( &lt;&gt; &lt;Marker position={{ lat: props.userLocation.lat, lng: props.userLocation.lng, }} icon={{ url: userLocationIcon, scaledSize: new window.google.maps.Size(30, 30), origin: new window.google.maps.Point(0, 0), anchor: new window.google.maps.Point(15, 15), }} /&gt; &lt;/&gt; ); else return null; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:49:57.887", "Id": "496928", "Score": "1", "body": "Welcome to Code Review, please [edit] the title of this question so that it only states the task that is accomplished by the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:58:55.937", "Id": "496930", "Score": "1", "body": "You've misunderstood what I meant, your title should only state the task accomplished by your code. Any questions you have belong to the body." } ]
[ { "body": "<p><strong>Typo?</strong> I think you meant to set <code>isDragged</code> to <code>false</code> when dragging finishes:</p>\n<pre><code>onDragEnd={() =&gt; {\n setIsDragged(false);\n}}\n</code></pre>\n<p>Note that you don't need to declare parameter you don't use (and probably shouldn't, to make the code easier to read).</p>\n<p><strong>Concise props</strong> When you have variables that you want to pass as props of the same name, you can make things a bit concise by using shorthand property names and spreading the object into props. For example:</p>\n<pre><code>&lt;UserLocationTimer\n userLocation={userLocation}\n setUserLocation={setUserLocation}\n panTo={panTo}\n&gt;&lt;/UserLocationTimer&gt;\n</code></pre>\n<p>can be</p>\n<pre><code>&lt;UserLocationTimer {...{userLocation, setUserLocation, panTo}} /&gt;\n</code></pre>\n<p>(it has no children, so it can be made self-closing)</p>\n<p>Listing fewer identifiers while writing code means less chance of typos, and helps enforce consistent names for things.</p>\n<p><strong>Marker position props</strong> Rather than listing out the <code>lat</code> and <code>lng</code> properties of <code>userLocation</code>, you can pass the plain object itself to <code>position</code>:</p>\n<pre><code>&lt;Marker position={props.userLocation}\n</code></pre>\n<p><strong>Return early instead of long if/else blocks</strong> - if one sees <code>if</code> followed by a long block of code, followed by an <code>else</code>, keeping track of what condition the <code>else</code> is corresponding to can be harder to recognize at a glance than it needs to be. Consider returning the short branch first instead. See below.</p>\n<p><strong>JSX fragments are only needed when enclosing 2 or more tags</strong> - if a fragment only has one child tag, it can be removed completely, like this:</p>\n<pre><code>export const UserLocation = ({ userLocation }) =&gt; (\n if (!userLocation) {\n return null;\n }\n return (\n &lt;Marker\n // ...\n</code></pre>\n<p>The same thing applies to the JSX returned by <code>UserLocationTimer</code>, but there's a better approach:</p>\n<p><strong>Consolidate <code>UserLocation</code></strong> Since <code>UserLocation</code> is being rendered regardless, I think conditionally putting it inside <code>UserLocationTimer</code> isn't the right way to go. I'd remove the timer component completely, and implement its logic in the parent component instead, while unconditionally rendering <code>UserLocation</code>.</p>\n<pre><code>const intervalRef = useRef();\nuseEffect(() =&gt; {\n if (isDragged) {\n const intervalId = setInterval(locateMe, 2000);\n // Cleanup will run on dismount and when isDragged goes to false\n return () =&gt; clearInterval(intervalId);\n }\n}, [isDragged]);\n\n// ...\n\n&lt;GoogleMap\n onDrag={() =&gt; {\n setIsDragged(true);\n }}\n onDragEnd={() =&gt; {\n setIsDragged(false);\n }}\n&gt;\n . . .\n &lt;UserLocation {...{userLocation}} /&gt;\n&lt;/GoogleMap&gt;\n</code></pre>\n<p><strong>Naming</strong> The name <code>UserLocation</code> is very similar to <code>userLocation</code>, but one is a <em>component</em>, while the other holds <em>data</em>. Maybe rename them so that they're more distinct - perhaps <code>UserLocationMarker</code> and <code>userLocationCoords</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T13:16:04.137", "Id": "497738", "Score": "0", "body": "Thank you very much for the detailed answer, very very enlightening" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T19:07:01.197", "Id": "252268", "ParentId": "252261", "Score": "2" } } ]
{ "AcceptedAnswerId": "252268", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T17:46:22.980", "Id": "252261", "Score": "2", "Tags": [ "react.js", "google-maps" ], "Title": "Turning on/off setInterval locating - using React.js" }
252261
<p>My adjacency matrix looks like this, where non-zero weights denote edges.</p> <p>[0, 2, 0, 0, 3]</p> <p>[2, 0, 2, 4, 0]</p> <p>[0, 2, 0, 3, 0]</p> <p>[0, 4, 3, 0, 1]</p> <p>[3, 0, 0, 1, 0]</p> <p>Here's my attempt, would appreciate a code review.</p> <pre><code> private static class Edge implements Comparable&lt;Edge&gt; { private int source; private int destination; private int weight; public Edge(int source, int destination, int weight) { this.source = source; this.destination = destination; this.weight = weight; } public String toString() { return source + &quot;---&quot; + weight + &quot;---&quot; + destination; } @Override public int compareTo(Edge other) { return Integer.compare(this.weight, other.weight); } @Override public boolean equals(Object other) { if (other instanceof WeightedGraphMatrix.Edge) { return equals((WeightedGraphMatrix.Edge)other); } return false; } private boolean equals(Edge other) { return other.destination == this.destination; } @Override // Uses only the destination to calculate hash for the purposes of maintaining the visited hashset. public int hashCode() { int hash = 17; int hashMultiplikator = 79; return hash * hashMultiplikator * destination; } } public static void printDijkstras(int [][] graph, int source) { // Prints shortest distances to all nodes from the source. System.out.println(Arrays.toString(Dijkstras(graph, source))); } public static int[] Dijkstras(int [][] graph, int source) { // Ideally should check matrix's validity to be square and symmetric but haven't done here since its pretty straightforward. int [] nodesVisited = new int [graph.length]; Queue&lt;Edge&gt; edgeQueue = new PriorityQueue&lt;&gt;(); int [] shortestDistance = new int[graph.length]; Arrays.fill(shortestDistance, Integer.MAX_VALUE); // Start with the source vertex. int currentNode = source; shortestDistance[0] = 0; nodesVisited[0] = 1; do { for (int col = 0; col&lt;graph[currentNode].length; col++) { // Take all edges from this node. Skip self &amp; 0-weight edges if (col == currentNode || graph[currentNode][col] == 0) { continue; } edgeQueue.add(new Edge(currentNode, col, graph[currentNode][col])); // Update distance for this destination if better than existing. if (shortestDistance[col] &gt; shortestDistance[currentNode] + graph[currentNode][col]) { shortestDistance[col] = shortestDistance[currentNode] + graph[currentNode][col]; } } //find cheapest edge to a not already visited destination. Edge edge = edgeQueue.remove(); while (nodesVisited[edge.destination] == 1) { if (edgeQueue.isEmpty()) { return shortestDistance; } edge = edgeQueue.remove(); } // Now that you've reached this edge as a destination, record it. currentNode = edge.destination; nodesVisited[edge.destination] = 1; } while (!edgeQueue.isEmpty()); return edgesVisited; } </code></pre> <p>Would also appreciate some help figuring out the runtime for my implementation and if it can be improved. For a Graph with V vertices and E edges, my outer loop runs V times, and the inner loop which iterates over each vertex's edges runs V times as well, leading to a runtime of V^2. The PQ remove call takes O(logE) time, so I think it ends up being O(V^2 + logE) which doesn't sound very efficient.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T18:14:22.350", "Id": "252263", "Score": "1", "Tags": [ "java", "graph", "dijkstra" ], "Title": "Dijkstra's shortest-path algorithm implemented via Priority Queues and an adjacency matrix represented graph" }
252263
<p>I have this Java solution to <a href="https://leetcode.com/problems/3sum/" rel="nofollow noreferrer">LeetCode's 3Sum</a> problem.</p> <p>I would be really grateful if I could get feedback on correctness, scalability, efficiency, coding best practices, and OOP design.</p> <p>I'm relatively new to Java.</p> <pre><code>class Solution { public List&lt;List&lt;Integer&gt;&gt; threeSum(int[] nums) { List l1 = new ArrayList&lt;ArrayList&gt;(); for (int idx = 0; idx &lt; nums.length; idx++) { if (idx &gt; 0 &amp;&amp; nums[idx] == nums[idx - 1]) continue; HashMap&lt;Integer, Integer&gt; hash = new HashMap&lt;&gt;(); for (int idxInner = idx + 1; idxInner &lt; nums.length; idxInner++) { if ( hash.get(nums[idxInner]) != null &amp;&amp; nums[idxInner]+hash.get(nums[idxInner]) == -1*nums[idx] ) { List l2 = new ArrayList&lt;Integer&gt;(); addInList(l2, nums[idx]); addInList(l2, hash.get(nums[idxInner])); addInList(l2, nums[idxInner]); l1.add(l2); } else { hash.put(-1*(nums[idx] + nums[idxInner]), nums[idxInner]); } } } removeDuplicates(l1); return l1; } public void addInList(List&lt;Integer&gt; list, int num) { if (list == null) return; int lSize = list.size(); if (lSize == 0) { list.add(num); return; } int idx = 0; while (idx &lt; lSize &amp;&amp; list.get(idx) &lt; num) { idx++; } if (idx &lt; lSize) list.add(idx, num); else list.add(num); return; } public void removeDuplicates(List&lt;ArrayList&lt;Integer&gt;&gt; lists) { if(lists == null) return; for(int outer = 0; outer &lt; lists.size(); outer++) { for(int inner = outer + 1; inner &lt; lists.size(); inner++) { if (areDuplicates(lists.get(outer), lists.get(inner))) { lists.remove(inner); inner--; } } } } public boolean areDuplicates(ArrayList&lt;Integer&gt; first, ArrayList&lt;Integer&gt; second) { if (first == null &amp;&amp; first == second) return true; if (first == null || second == null) return false; int fSize = first.size(); int sSize = second.size(); if (fSize != sSize) return false; for(int idx = 0; idx &lt; fSize; idx++) { if (first.get(idx) != second.get(idx)) return false; } return true; } } </code></pre> <p>I get a timeout error on LeetCode if I try to run this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T21:22:51.063", "Id": "496942", "Score": "3", "body": "Hello, I suggest that you fix your code, since it's not compiling at the moment and format it at the same time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T21:36:00.337", "Id": "496943", "Score": "0", "body": "@Doi9t Thank you for pointing that out. I've fixed the error now." } ]
[ { "body": "<p>This is a nice start, but there's some stylistic stuff that could be improved.</p>\n<p>Generally it's a good idea to name variables for what their purpose is. Names like l1 are difficult to understand. This varies depending on the language, but in Java people tend to be explicit with their variable naming, preferring descriptive names over concise ones.</p>\n<p>When declaring a data structure, convention in Java is to declare the type as the interface.</p>\n<pre><code>public boolean areDuplicates(ArrayList&lt;Integer&gt; first, ArrayList&lt;Integer&gt; second)\n</code></pre>\n<p>is more commonly written as</p>\n<pre><code>public boolean areDuplicates(List&lt;Integer&gt; first, List&lt;Integer&gt; second)\n</code></pre>\n<p>This is because List defines a set of behaviours that you want to have, and ArrayList defines how they are implemented. If someone has made a data structure with the exact same behaviour as an ArrayList, then you want your methods to support that data structure as well.</p>\n<p>The format of the code in quite unusual for Java. I'd run your code through an autoformatter, which deals with all that stuff for you. Personally I use Eclipse's default one, but there's loads of choice out there.</p>\n<p>This isn't a complete review, and it's mainly my opinion, so feel free to include or discard this advice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T11:55:30.093", "Id": "252480", "ParentId": "252267", "Score": "3" } }, { "body": "<p>The common Java style guide lines are that opening block parentheses are on the same line. Also you should always use block parentheses, even for single lines.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public List&lt;List&lt;Integer&gt;&gt; threeSum(int[] nums)\n</code></pre>\n<p><code>Integer</code> and <code>int</code> are only interchangeable because the compiler supports that with <a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow noreferrer\">AutoBoxing</a>. having this might or might not be desirable or a problem.</p>\n<p>In this case, the signature is obviously given, but it should be <code>int[][]</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> List l1 = new ArrayList&lt;ArrayList&gt;();\n</code></pre>\n<p>Always use descriptive variable names, overall your names are quite bad, they almost never tell one what the variable is or is used for.</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int idx = 0; idx &lt; nums.length; idx++)\n</code></pre>\n<p>And don't shorten names just because you can, it makes the code only harder to read and maintain.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int idxInner = idx + 1; idxInner &lt; nums.length; idxInner++)\n</code></pre>\n<p>If you have an inner loop, there's a good chance that extracting that logic into a function of its own will increase how easy the code is to understand.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public void removeDuplicates(List&lt;ArrayList&lt;Integer&gt;&gt; lists)\n</code></pre>\n<p>Always use the least super interface that gives you the required functionality, in this case <code>List</code>. It means that your code is easier to reuse.</p>\n<hr />\n<p>I'm not convinced that your solution is correct and it does seem oddly complicated. Overall, you seem to perform a lot of list iterations and management to filter out the duplicates, when I'd rather expect to iterate over the given list once and then process the result.</p>\n<p>So, let's restart at the beginning. We've been given an array of <code>int</code>s and want to find the triplets which have a sum of zero. For that I'd expect three nested loops of some kind to iterate over the array and finding the triplets.</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int firstValueIndex = 0; firstValueIndex &lt; numbers.length - 2; firstValueIndex++) {\n int firstValue = numbers[firstValueIndex];\n \n for (int secondValueIndex = firstValueIndex + 1; secondValueIndex &lt; numbers.length - 1; secondValueIndex++) {\n int secondValue = numbers[secondValueIndex];\n \n for (int thirdValueIndex = secondValueIndex + 1; thirdValueIndex &lt; numbers.length; thirdValueIndex++) {\n int thirdValue = numbers[thirdValueIndex];\n \n int sum = firstValue + secondValue + thirdValue;\n \n if (sum == 0) {\n // Hit.\n }\n }\n }\n}\n</code></pre>\n<p>With in place, we can gather the results. I'd suggest to keep using primitives for everything to do as little conversions as possible. You have to remember, that arrays are <code>Object</code>s, to a certain extend, so we can use them without conversion inside a <code>List</code>. <code>int</code> would need to be converted to <code>Integer</code>s first. Which is not necessarily a costly operation, but something to keep in mind.</p>\n<pre><code>List&lt;int[]&gt; triplets = new ArrayList&lt;&gt;();\n\n// Inside the if from above...\ntriplets.add(new int[] { firstValue, secondValue, thirdValue });\n</code></pre>\n<p>Now we have a list of all triplets. Next, I'd sort the values and remove duplicates:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int[] triplet : triplets) {\n Arrays.sort(triplet);\n}\n\nfor (int tripletIndex = 0; tripletIndex &lt; triplets.size() - 1; tripletIndex++) {\n int[] currentTriplet = triplets.get(tripletIndex);\n \n for (int searchIndex = tripletIndex + 1; searchIndex &lt; triplets.size(); searchIndex++) {\n if (Arrays.equals(currentTriplet, triplets.get(searchIndex))) {\n triplets.remove(searchIndex);\n searchIndex--;\n }\n }\n}\n</code></pre>\n<p>Not the prettiest code, but gets the job done. So all that remains is to convert it into the expected result format:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();\n\nfor (int[] triplet : triplets) {\n result.add(Arrays.asList(\n Integer.valueOf(triplet[0]),\n Integer.valueOf(triplet[1]),\n Integer.valueOf(triplet[2])));\n}\n</code></pre>\n<p>With the following sample generation, which should match the given constraints, this code runs in 12ms for me:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Random random = new Random(0);\n\nint[] numbers = new int[random.nextInt(3000)];\n\nfor (int index = 0; index &lt; numbers.length; index++) {\n numbers[index] = random.nextInt(200000) - 100000;\n}\n</code></pre>\n<p>Upping this to 6k elements will yield an execution time of 50 seconds. So we might need to cut some slack here, somehow. The first thing we can try is to inline our sort and search, so that our list never grows beyond the final result list.</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Inside the if inside the three loops.\n\nint[] triplet = new int[] { firstValue, secondValue, thirdValue };\nArrays.sort(triplet);\n\nif (!contains(triplets, triplet)) {\n triplets.add(triplet);\n}\n</code></pre>\n<p>Because the default <code>List</code> implementations don't handle arrays well, we'll have to write our own <code>contains</code> method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static final boolean contains(List&lt;int[]&gt; list, int[] value) {\n for (int[] item : list) {\n if (Arrays.equals(item, value)) {\n return true;\n }\n }\n \n return false;\n}\n</code></pre>\n<p>That cuts <em>some</em> execution time, but not nearly enough. As I've said, the default implementations of <code>List</code> and <code>Set</code> don't handle arrays too well, so if we want to use a <code>Set</code> to further cut looping, we'll have to work around that limitation:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// At the start of the function:\n\nSet&lt;Integer&gt; tripletHashes = new HashSet&lt;&gt;();\n\n// Inside the if inside the three loops.\n\nint[] triplet = new int[] { firstValue, secondValue, thirdValue };\nArrays.sort(triplet);\n\nInteger tripletHash = Arrays.hashCode(triplet);\n\n// If the hash is not in tripletHashes, we can be sure that it has not been\n// added, however, if it was found, there we need to check the exact value\n// because of possible hash collisions.\nif (!tripletHashes.contains(tripletHash) || !contains(triplets, triplet)) {\n tripletHashes.add(tripletHash);\n triplets.add(triplet);\n}\n</code></pre>\n<p>That further cuts execution time for me. Not by as much as I had hoped, but still.</p>\n<hr />\n<p>What you have to keep in mind here, is that you're looking at you're looking with 27 billion iterations at 3000 entries. If we double that to 6000 entries, we already have 216 billion iterations.</p>\n<p>There might be a good mathematical way to solve this, but this solution is purely mechanical based on the given description.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T13:22:39.917", "Id": "252483", "ParentId": "252267", "Score": "2" } } ]
{ "AcceptedAnswerId": "252483", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T18:54:32.570", "Id": "252267", "Score": "2", "Tags": [ "java", "performance", "complexity" ], "Title": "LeetCode 3Sum Java Solution" }
252267
<p>As you might know, EF Core does not support executing multiple queries in parallel on the same context using something like <code>Task.WhenAll</code>.</p> <p>So you have to write this code instead:</p> <pre><code>using var context1 = _factory.CreateDbContext(); using var context2 = _factory.CreateDbContext(); using var context3 = _factory.CreateDbContext(); var result1Task = context1.Set&lt;T1&gt;().ToListAsync(); var result2Task = context2.Set&lt;T2&gt;().ToListAsync(); var result3Task = context3.Set&lt;T3&gt;().ToListAsync(); await Task.WhenAll(result1Task, result2Task, result3Task); var result1 = result1Task.Result; var result2 = result2Task.Result; var result3 = result3Task.Result; </code></pre> <p>To get rid of all these using statements, I started writing a library which exposes a <code>Set&lt;TEntity()</code> extension method on <code>IDbContextFactory&lt;TContext&gt;</code>. You can use it like this.</p> <pre><code>var result1Task = _factory.Set&lt;T1&gt;().ToListAsync(); var result2Task = _factory.Set&lt;T2&gt;().ToListAsync(); var result3Task = _factory.Set&lt;T3&gt;().ToListAsync(); await Task.WhenAll(result1Task, result2Task, result3Task); var result1 = result1Task.Result; var result2 = result2Task.Result; var result3 = result3Task.Result; </code></pre> <p>To achieve this, it heavily relies on reflection and EF Core internals. And because of this, I would really like a code review from someone experienced with EF Core, Expressions and IQueryable.</p> <p>What it basically does is, it creates an <code>IQueryable&lt;TEntity&gt;</code> which is then exchanged for a real <code>DbSet&lt;TEntity&gt;</code> once it is executed and immediately disposes the context after that. When using the async version, it is a bit more complex. It passes down the <code>DbContext</code> to the <code>AsyncEnumerator</code> and disposes the context together with the <code>AsyncEnumerator</code>.</p> <p>You can find the whole project on Github too <a href="https://github.com/wertzui/EntityFrameworkCore.Parallel" rel="nofollow noreferrer">https://github.com/wertzui/EntityFrameworkCore.Parallel</a></p> <p>Tank you in advance.</p> <p>DbContextFactoryExtensions.cs</p> <pre><code>/// &lt;summary&gt; /// Contains the &lt;see cref=&quot;Set{TContext, TEntity}(IDbContextFactory{TContext})&quot;/&gt; extension method wich is the starting point for any query. /// &lt;/summary&gt; public static class DbContextFactoryExtensions { /// &lt;summary&gt; /// The starting point for your query. Make sure &lt;typeparamref name=&quot;TEntity&quot;/&gt; is available as a &lt;see cref=&quot;DbSet{TEntity}&quot;/&gt; on your &lt;typeparamref name=&quot;TContext&quot;/&gt;. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TContext&quot;&gt;The type of the &lt;see cref=&quot;DbContext&quot;/&gt;.&lt;/typeparam&gt; /// &lt;typeparam name=&quot;TEntity&quot;&gt;The type fo the entities.&lt;/typeparam&gt; /// &lt;param name=&quot;contextFactory&quot;&gt;The factory which can create the &lt;see cref=&quot;DbContext&quot;/&gt;.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static IQueryable&lt;TEntity&gt; Set&lt;TEntity&gt;(this IDbContextFactory&lt;DbContext&gt; contextFactory) //where TContext : DbContext where TEntity : class { var query = new EntityQueryable&lt;TEntity&gt;( new QueryProvider(new DbContextFactoryQueryContext&lt;TEntity&gt;(contextFactory)), new EntityType&lt;TEntity&gt;()); return query; } } </code></pre> <p>EntityType.cs</p> <pre><code>/// &lt;summary&gt; /// This is a minimal implementation of &lt;see cref=&quot;IEntityType&quot;/&gt; to support the creation of queries without the need of a DbContext. /// Most of its methods will just throw exceptions. /// When the query is actually executed, the expression which is started with this class is replaced to contain an instance of the implementation from the real Entity Framework library. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TEntity&quot;&gt;The type of the entities in the DbSet.&lt;/typeparam&gt; public class EntityType&lt;TEntity&gt; : IEntityType { public object this[string name] =&gt; throw new NotImplementedException(); public IEntityType BaseType =&gt; throw new NotImplementedException(); public string DefiningNavigationName =&gt; throw new NotImplementedException(); public IEntityType DefiningEntityType =&gt; throw new NotImplementedException(); public IModel Model =&gt; throw new NotImplementedException(); public string Name =&gt; throw new NotImplementedException(); public Type ClrType =&gt; typeof(TEntity); public bool HasSharedClrType =&gt; throw new NotImplementedException(); public bool IsPropertyBag =&gt; throw new NotImplementedException(); public IAnnotation FindAnnotation(string name) =&gt; throw new NotImplementedException(); public IForeignKey FindForeignKey(IReadOnlyList&lt;IProperty&gt; properties, IKey principalKey, IEntityType principalEntityType) =&gt; throw new NotImplementedException(); public IIndex FindIndex(IReadOnlyList&lt;IProperty&gt; properties) =&gt; throw new NotImplementedException(); public IIndex FindIndex(string name) =&gt; throw new NotImplementedException(); public IKey FindKey(IReadOnlyList&lt;IProperty&gt; properties) =&gt; throw new NotImplementedException(); public IKey FindPrimaryKey() =&gt; throw new NotImplementedException(); public IProperty FindProperty(string name) =&gt; throw new NotImplementedException(); public IServiceProperty FindServiceProperty(string name) =&gt; throw new NotImplementedException(); public ISkipNavigation FindSkipNavigation(string name) =&gt; throw new NotImplementedException(); public IEnumerable&lt;IAnnotation&gt; GetAnnotations() =&gt; throw new NotImplementedException(); public IEnumerable&lt;IForeignKey&gt; GetForeignKeys() =&gt; throw new NotImplementedException(); public IEnumerable&lt;IIndex&gt; GetIndexes() =&gt; throw new NotImplementedException(); public IEnumerable&lt;IKey&gt; GetKeys() =&gt; throw new NotImplementedException(); public IEnumerable&lt;IProperty&gt; GetProperties() =&gt; throw new NotImplementedException(); public IEnumerable&lt;IServiceProperty&gt; GetServiceProperties() =&gt; throw new NotImplementedException(); public IEnumerable&lt;ISkipNavigation&gt; GetSkipNavigations() =&gt; throw new NotImplementedException(); } </code></pre> <p>QueryProvider.cs</p> <pre><code>/// &lt;summary&gt; /// A basic query provider which will pass the execution logic down the the given &lt;see cref=&quot;IQueryContext&quot;/&gt;. /// &lt;/summary&gt; public class QueryProvider : IAsyncQueryProvider { private readonly IQueryContext _queryContext; private static readonly MethodInfo _genericCreateQueryMethod = typeof(QueryProvider) .GetRuntimeMethods() .Single(m =&gt; m.Name == nameof(CreateQuery) &amp;&amp; m.IsGenericMethod); private readonly MethodInfo _genericExecuteMethod; public QueryProvider(IQueryContext queryContext) { _queryContext = queryContext; _genericExecuteMethod = _queryContext.GetType() .GetRuntimeMethods() .Single(m =&gt; m.Name == nameof(IQueryContext.Execute) &amp;&amp; m.IsGenericMethod); } public virtual IQueryable CreateQuery(Expression expression) =&gt; (IQueryable)_genericCreateQueryMethod .MakeGenericMethod(expression.Type.GetSequenceType()) .Invoke(this, new object[] { expression }); public virtual IQueryable&lt;T&gt; CreateQuery&lt;T&gt;(Expression expression) =&gt; new EntityQueryable&lt;T&gt;(this, expression); public virtual object Execute(Expression expression) =&gt; _genericExecuteMethod .MakeGenericMethod(expression.Type) .Invoke(_queryContext, new object[] { expression }); TResult IQueryProvider.Execute&lt;TResult&gt;(Expression expression) =&gt; _queryContext.Execute&lt;TResult&gt;(expression); public TResult ExecuteAsync&lt;TResult&gt;(Expression expression, CancellationToken cancellationToken = default) =&gt; _queryContext.ExecuteAsync&lt;TResult&gt;(expression, cancellationToken); } </code></pre> <p>IQueryContext.cs</p> <pre><code>/// &lt;summary&gt; /// Interface for a query context. A query context is the thing that will actually execute any query. /// &lt;/summary&gt; public interface IQueryContext { TResult Execute&lt;TResult&gt;(Expression query); TResult ExecuteAsync&lt;TResult&gt;(Expression query, CancellationToken cancellationToken); } </code></pre> <p>DbContextFactoryQueryContext.cs</p> <pre><code>/// &lt;summary&gt; /// This class contains the logic which will actually create the &lt;see cref=&quot;DbContext&quot;/&gt; and execute the query on it. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TContext&quot;&gt;&lt;/typeparam&gt; /// &lt;typeparam name=&quot;TEntity&quot;&gt;&lt;/typeparam&gt; public class DbContextFactoryQueryContext&lt;TEntity&gt; : DbContextFactoryQueryContext, IQueryContext //where TContext : DbContext where TEntity : class { private readonly IDbContextFactory&lt;DbContext&gt; factory; public DbContextFactoryQueryContext(IDbContextFactory&lt;DbContext&gt; factory) { this.factory = factory ?? throw new ArgumentNullException(nameof(factory)); } public TResult Execute&lt;TResult&gt;(Expression query) { using (var context = factory.CreateDbContext()) { context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var set = context.Set&lt;TEntity&gt;(); var queryaple = set.AsQueryable(); var provider = queryaple.Provider; var replaced = ReplaceProvider(query, set, provider); var result = provider.Execute&lt;TResult&gt;(replaced); var buffered = Buffer(result); return buffered; } } private static Expression ReplaceProvider(Expression query, DbSet&lt;TEntity&gt; set, IQueryProvider provider) { var setQuery = provider is IAsyncQueryProvider asyncProvider ? new QueryRootExpression(asyncProvider, set.EntityType) : new QueryRootExpression(set.EntityType); Expression replaced; if (query is MethodCallExpression call) replaced = call.Update(call.Object, new Expression[] { setQuery }.Concat(call.Arguments.Skip(1))); else if (query is QueryRootExpression root) replaced = setQuery; else throw new ArgumentException($&quot;An Expression of type {query.Type} is not supported.&quot;, nameof(query)); return replaced; } private static TResult Buffer&lt;TResult&gt;(TResult result, CancellationToken cancellationToken = default) { if (result is IEnumerable enumerable) { var type = enumerable.GetType(); if (type.GenericTypeArguments.Length == 1) { var genericArgument = type.GenericTypeArguments[0]; var genericToList = _toListMethodInfo.MakeGenericMethod(genericArgument); var list = genericToList.Invoke(null, new object[] { enumerable }); var casted = (TResult)list; return casted; } } return result; } public TResult ExecuteAsync&lt;TResult&gt;(Expression query, CancellationToken cancellationToken) { // We cannot use a using block here, because the result will be enumerated after this method has already returned. // Instead we pass the DbContext down to the enumerator which will then dispose the context once itself gets disposed. // This will happen when the result is enumerated. var context = factory.CreateDbContext(); try { context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var set = context.Set&lt;TEntity&gt;(); var queryaple = set.AsQueryable(); var provider = queryaple.Provider; if (provider is IAsyncQueryProvider asyncProvider) { var replaced = ReplaceProvider(query, set, provider); var result = asyncProvider.ExecuteAsync&lt;TResult&gt;(replaced); var buffered = BufferAsync(result, context, cancellationToken); return buffered; } throw new InvalidOperationException(&quot;Cannot execute an async query on a non async query provider.&quot;); } catch { context.Dispose(); throw; } } private static TResult BufferAsync&lt;TResult&gt;(TResult result, IAsyncDisposable dbSet, CancellationToken cancellationToken) { if (result is IEnumerable enumerable) { var buffered = EntitiyFrameworkCore.Parallel.AsyncEnumerableExtensions.Buffer((dynamic)result, dbSet); return (TResult)buffered; } return result; } } public abstract class DbContextFactoryQueryContext { protected static readonly MethodInfo _toListMethodInfo = typeof(Enumerable) .GetMethod(nameof(Enumerable.ToList)); protected static readonly MethodInfo _toListAsyncMethodInfo = typeof(AsyncEnumerable) .GetMethod(nameof(AsyncEnumerable.ToListAsync)); protected static readonly MethodInfo _toAsyncEnumerableMethodInfo = typeof(AsyncEnumerable) .GetMethods() .Single(m =&gt; { if (m.Name != nameof(AsyncEnumerable.ToAsyncEnumerable)) return false; var parameter = m.GetParameters().FirstOrDefault(); if (parameter == null) return false; var parameterType = parameter.ParameterType; if (!typeof(Task).IsAssignableFrom(parameterType)) return false; return true; }); } </code></pre> <p>DbContextFactoryQueryContext.cs</p> <pre><code>/// &lt;summary&gt; /// This class contains the logic which will actually create the &lt;see cref=&quot;DbContext&quot;/&gt; and execute the query on it. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TContext&quot;&gt;&lt;/typeparam&gt; /// &lt;typeparam name=&quot;TEntity&quot;&gt;&lt;/typeparam&gt; public class DbContextFactoryQueryContext&lt;TEntity&gt; : DbContextFactoryQueryContext, IQueryContext //where TContext : DbContext where TEntity : class { private readonly IDbContextFactory&lt;DbContext&gt; factory; public DbContextFactoryQueryContext(IDbContextFactory&lt;DbContext&gt; factory) { this.factory = factory ?? throw new ArgumentNullException(nameof(factory)); } public TResult Execute&lt;TResult&gt;(Expression query) { using (var context = factory.CreateDbContext()) { context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var set = context.Set&lt;TEntity&gt;(); var queryaple = set.AsQueryable(); var provider = queryaple.Provider; var replaced = ReplaceProvider(query, set, provider); var result = provider.Execute&lt;TResult&gt;(replaced); var buffered = Buffer(result); return buffered; } } private static Expression ReplaceProvider(Expression query, DbSet&lt;TEntity&gt; set, IQueryProvider provider) { var setQuery = provider is IAsyncQueryProvider asyncProvider ? new QueryRootExpression(asyncProvider, set.EntityType) : new QueryRootExpression(set.EntityType); Expression replaced; if (query is MethodCallExpression call) replaced = call.Update(call.Object, new Expression[] { setQuery }.Concat(call.Arguments.Skip(1))); else if (query is QueryRootExpression root) replaced = setQuery; else throw new ArgumentException($&quot;An Expression of type {query.Type} is not supported.&quot;, nameof(query)); return replaced; } private static TResult Buffer&lt;TResult&gt;(TResult result, CancellationToken cancellationToken = default) { if (result is IEnumerable enumerable) { var type = enumerable.GetType(); if (type.GenericTypeArguments.Length == 1) { var genericArgument = type.GenericTypeArguments[0]; var genericToList = _toListMethodInfo.MakeGenericMethod(genericArgument); var list = genericToList.Invoke(null, new object[] { enumerable }); var casted = (TResult)list; return casted; } } return result; } public TResult ExecuteAsync&lt;TResult&gt;(Expression query, CancellationToken cancellationToken) { // We cannot use a using block here, because the result will be enumerated after this method has already returned. // Instead we pass the DbContext down to the enumerator which will then dispose the context once itself gets disposed. // This will happen when the result is enumerated. var context = factory.CreateDbContext(); try { context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var set = context.Set&lt;TEntity&gt;(); var queryaple = set.AsQueryable(); var provider = queryaple.Provider; if (provider is IAsyncQueryProvider asyncProvider) { var replaced = ReplaceProvider(query, set, provider); var result = asyncProvider.ExecuteAsync&lt;TResult&gt;(replaced); var buffered = BufferAsync(result, context, cancellationToken); return buffered; } throw new InvalidOperationException(&quot;Cannot execute an async query on a non async query provider.&quot;); } catch { context.Dispose(); throw; } } private static TResult BufferAsync&lt;TResult&gt;(TResult result, IAsyncDisposable dbSet, CancellationToken cancellationToken) { if (result is IEnumerable enumerable) { var buffered = EntitiyFrameworkCore.Parallel.AsyncEnumerableExtensions.Buffer((dynamic)result, dbSet); return (TResult)buffered; } return result; } } public abstract class DbContextFactoryQueryContext { protected static readonly MethodInfo _toListMethodInfo = typeof(Enumerable) .GetMethod(nameof(Enumerable.ToList)); protected static readonly MethodInfo _toListAsyncMethodInfo = typeof(AsyncEnumerable) .GetMethod(nameof(AsyncEnumerable.ToListAsync)); protected static readonly MethodInfo _toAsyncEnumerableMethodInfo = typeof(AsyncEnumerable) .GetMethods() .Single(m =&gt; { if (m.Name != nameof(AsyncEnumerable.ToAsyncEnumerable)) return false; var parameter = m.GetParameters().FirstOrDefault(); if (parameter == null) return false; var parameterType = parameter.ParameterType; if (!typeof(Task).IsAssignableFrom(parameterType)) return false; return true; }); } </code></pre> <p>SharedTypeExtensions.cs</p> <pre><code>/// &lt;summary&gt; /// Contains extension methods to find the generic type parameter of a collection type. /// &lt;/summary&gt; internal static class SharedTypeExtensions { public static Type GetSequenceType(this Type type) { var sequenceType = TryGetSequenceType(type); if (sequenceType == null) { throw new ArgumentException(&quot;The given type is not a collection type&quot;, nameof(type)); } return sequenceType; } public static Type TryGetSequenceType(this Type type) =&gt; type.TryGetElementType(typeof(IEnumerable&lt;&gt;)) ?? type.TryGetElementType(typeof(IAsyncEnumerable&lt;&gt;)); public static Type TryGetElementType(this Type type, Type interfaceOrBaseType) { if (type.IsGenericTypeDefinition) { return null; } var types = GetGenericTypeImplementations(type, interfaceOrBaseType); Type singleImplementation = null; foreach (var implementation in types) { if (singleImplementation == null) { singleImplementation = implementation; } else { singleImplementation = null; break; } } return singleImplementation?.GenericTypeArguments.FirstOrDefault(); } public static IEnumerable&lt;Type&gt; GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType) { var typeInfo = type.GetTypeInfo(); if (!typeInfo.IsGenericTypeDefinition) { var baseTypes = interfaceOrBaseType.GetTypeInfo().IsInterface ? typeInfo.ImplementedInterfaces : type.GetBaseTypes(); foreach (var baseType in baseTypes) { if (baseType.IsGenericType &amp;&amp; baseType.GetGenericTypeDefinition() == interfaceOrBaseType) { yield return baseType; } } if (type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == interfaceOrBaseType) { yield return type; } } } public static IEnumerable&lt;Type&gt; GetBaseTypes(this Type type) { type = type.BaseType; while (type != null) { yield return type; type = type.BaseType; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T12:47:06.043", "Id": "497026", "Score": "2", "body": "To those encountering this question in the close queue, the issue has been corrected." } ]
[ { "body": "<p>All public API surfaces should validate input parameters.</p>\n<hr />\n<p>Restricting the queries to a single entity type seems limiting. You can't join entities with no navigation properties.</p>\n<hr />\n<p>It fails when using navigation properties (C# 9/EF Core 5.0):</p>\n<pre><code>using Microsoft.EntityFrameworkCore;\nusing Microsoft.Extensions.DependencyInjection;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\n\nvar services = new ServiceCollection();\nservices.AddPooledDbContextFactory&lt;TestDbContext&gt;(options =&gt; options.UseInMemoryDatabase(&quot;hest&quot;));\n\nvar provider = services.BuildServiceProvider();\nvar factory = provider.GetRequiredService&lt;IDbContextFactory&lt;TestDbContext&gt;&gt;();\n\nusing (var db = provider.GetRequiredService&lt;IDbContextFactory&lt;TestDbContext&gt;&gt;().CreateDbContext())\n{\n await db.Ones.AddRangeAsync(\n Enumerable.Range(1, 10)\n .Select(i =&gt; new Entity1 { Value = (i * 2).ToString(), Entity2 = new Entity2 { Value = (i * 7).ToString(), } }));\n await db.SaveChangesAsync();\n}\n\n// Fails when rewriting the query\nvar fails = await factory.Set&lt;Entity1&gt;()\n .Select(t =&gt; t.Entity2)\n .Select(t =&gt; t.Entity1)\n .ToListAsync();\n\n// Can't join two DbSets with different contexts.\nvar test = await factory.Set&lt;Entity1&gt;()\n .Join(factory.Set&lt;Entity2&gt;(), e1 =&gt; e1.ID, e2 =&gt; e2.ID, (e1, e2) =&gt; e2.Value)\n .ToListAsync();\n\npublic class Entity1\n{\n public long ID { get; set; }\n public string Value { get; set; }\n\n public Entity2 Entity2 { get; set; }\n}\n\npublic class Entity2\n{\n public long ID { get; set; }\n public string Value { get; set; }\n\n public Entity1 Entity1 { get; set; }\n}\n\npublic class TestDbContext : DbContext\n{\n public TestDbContext([NotNull] DbContextOptions&lt;TestDbContext&gt; options) : base(options) { }\n\n public DbSet&lt;Entity1&gt; Ones { get; protected set; }\n public DbSet&lt;Entity2&gt; Twos { get; protected set; }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n base.OnModelCreating(modelBuilder);\n\n modelBuilder.Entity&lt;Entity2&gt;()\n .HasOne(e =&gt; e.Entity1)\n .WithOne(e =&gt; e.Entity2)\n .HasPrincipalKey&lt;Entity1&gt;(e =&gt; e.ID)\n .HasForeignKey&lt;Entity2&gt;(e =&gt; e.ID);\n }\n}\n</code></pre>\n<hr />\n<p>If a slightly uglier API is acceptable the whole thing can be implemented with a single extension method:</p>\n<pre><code>public static class EFConcurrentQueryExtension\n{\n public static async Task&lt;TResult&gt; ConcurrentAsync&lt;TDbContext, TResult&gt;(\n this IDbContextFactory&lt;TDbContext&gt; dbContextFactory,\n Func&lt;TDbContext, Task&lt;TResult&gt;&gt; asyncQuery)\n where TDbContext : DbContext\n {\n if (dbContextFactory is null)\n {\n throw new ArgumentNullException(nameof(dbContextFactory));\n }\n\n if (asyncQuery is null)\n {\n throw new ArgumentNullException(nameof(asyncQuery));\n }\n\n using var context = dbContextFactory.CreateDbContext();\n context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;\n var result = await asyncQuery(context);\n return result;\n }\n}\n</code></pre>\n<p>And the example would look like:</p>\n<pre><code>var result1Task = _factory.ConcurrentAsync(ctx =&gt; ctx.Set&lt;T1&gt;().ToListAsync());\nvar result2Task = _factory.ConcurrentAsync(ctx =&gt; ctx.T2.ToListAsync());\nvar result3Task = _factory.ConcurrentAsync(ctx =&gt; ctx.Set&lt;T3&gt;().ToListAsync());\n\nawait Task.WhenAll(result1Task, result2Task, result3Task);\n\nvar result1 = await result1Task;\nvar result2 = await result2Task;\nvar result3 = await result3Task;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:21:56.753", "Id": "497201", "Score": "0", "body": "Thanks for the review! I'll try to fix the problem with the navigation properties. I know that `Join()` is not working and that is acceptable. Also the \"uglier API\" is not acceptable as I want to keep the syntax equal to what everybody knows from a normal EF query." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-25T16:32:51.853", "Id": "497920", "Score": "0", "body": "For anyone interested: The first (and fixed) version is now available on NuGet https://www.nuget.org/packages/EntityFrameworkCore.Parallel/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:23:36.253", "Id": "252362", "ParentId": "252270", "Score": "2" } } ]
{ "AcceptedAnswerId": "252362", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T20:01:38.407", "Id": "252270", "Score": "3", "Tags": [ "c#", "linq", "expression-trees", "entity-framework-core", "linq-expressions" ], "Title": "A simple method to execute Entity Framework Core queries in parallel" }
252270
<p><a href="https://i.stack.imgur.com/5nemh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5nemh.png" alt="enter image description here" /></a> Can this code be shortened, optimized or remove any unnecessary parts. Just curious if this is the right way to achieve the given result in this CodePen example: <a href="https://codepen.io/MistaKisthur/pen/YzWMpMN" rel="nofollow noreferrer">CodePen Connect Four</a></p> <p>Here is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> // Debug &amp; fix this Script.. document.addEventListener('DOMContentLoaded',()=&gt;{ const displayCurrentPlayer = document.querySelector('#current-player') const squares = document.querySelectorAll('.grid div') const resetBtn = document.querySelector('#Reset') const result = document.querySelector('#result') let currentPlayer = 1 for(var i = 0, len = squares.length; i &lt; len; i++) (function(index){ // add an onclick to each square in the grid squares[i].onclick = function(){ // if the square below your current square is taken, you can go ontop of it. if(squares[index + 7].classList.contains('taken')){ if(!squares[index].classList.contains('taken')){ if(currentPlayer === 1){ squares[index].classList.add('taken') squares[index].classList.add('player-one') // Change the player currentPlayer = 2 displayCurrentPlayer.innerHTML = currentPlayer // displayCurrentPlayer.style.background = 'blue'; }else if(currentPlayer === 2){ squares[index].classList.add('taken') squares[index].classList.add('player-two') // Change the player currentPlayer = 1 displayCurrentPlayer.innerHTML = currentPlayer // displayCurrentPlayer.style.backgroundImage = `linear-gradient(-33deg,blue,green)!important`; } } } else alert('Cant Go Here') } resetBtn.addEventListener('mousedown',(e) =&gt; { if(squares[index + 7].classList.contains('taken')){ squares[index].classList.remove('taken') squares[index].classList.remove('player-one') squares[index].classList.remove('player-two') displayCurrentPlayer.innerHTML = 1 } }); })(i) //check the board for a win or lose function checkBoard() { //make const that shows all winning arrays const winningArrays = [ [0, 1, 2, 3], [41, 40, 39, 38], [7, 8, 9, 10], [34, 33, 32, 31], [14, 15, 16, 17], [27, 26, 25, 24], [21, 22, 23, 24], [20, 19, 18, 17], [28, 29, 30, 31], [13, 12, 11, 10], [35, 36, 37, 38], [6, 5, 4, 3], [0, 7, 14, 21], [41, 34, 27, 20], [1, 8, 15, 22], [40, 33, 26, 19], [2, 9, 16, 23], [39, 32, 25, 18], [3, 10, 17, 24], [38, 31, 24, 17], [4, 11, 18, 25], [37, 30, 23, 16], [5, 12, 19, 26], [36, 29, 22, 15], [6, 13, 20, 27], [35, 28, 21, 14], [0, 8, 16, 24], [41, 33, 25, 17], [7, 15, 23, 31], [34, 26, 18, 10], [14, 22, 30, 38], [27, 19, 11, 3], [35, 29, 23, 17], [6, 12, 18, 24], [28, 22, 16, 10], [13, 19, 25, 31], [21, 15, 9, 3], [20, 26, 32, 38], [36, 30, 24, 18], [5, 11, 17, 23], [37, 31, 25, 19], [4, 10, 16, 22], [2, 10, 18, 26], [39, 31, 23, 15], [1, 9, 17, 25], [40, 32, 24, 16], [9, 7, 25, 33], [8, 16, 24, 32], [11, 7, 23, 29], [12, 18, 24, 30], [1, 2, 3, 4], [5, 4, 3, 2], [8, 9, 10, 11], [12, 11, 10, 9], [15, 16, 17, 18], [19, 18, 17, 16], [22, 23, 24, 25], [26, 25, 24, 23], [29, 30, 31, 32], [33, 32, 31, 30], [36, 37, 38, 39], [40, 39, 38, 37], [7, 14, 21, 28], [8, 15, 22, 29], [9, 16, 23, 30], [10, 17, 24, 31], [11, 18, 25, 32], [12, 19, 26, 33], [13, 20, 27, 34] ]; //now take the 4 values in earch winningArray &amp; plug them into the squares values for(let y = 0; y &lt; winningArrays.length; y++) { const square1 = squares[winningArrays[y][0]]; const square2 = squares[winningArrays[y][1]]; const square3 = squares[winningArrays[y][2]]; const square4 = squares[winningArrays[y][3]]; //now check those arrays to see if they all have the class of player-one if(square1.classList.contains('player-one') &amp;&amp; square2.classList.contains('player-one') &amp;&amp; square3.classList.contains('player-one') &amp;&amp; square4.classList.contains('player-one')) { //if they do, player-one is passed as the winner result.innerHTML = 'Player one wins!' //remove ability to change result } //now check to see if they all have the classname player two else if (square1.classList.contains('player-two') &amp;&amp; square2.classList.contains('player-two') &amp;&amp; square3.classList.contains('player-two') &amp;&amp; square4.classList.contains('player-two')) { //if they do, player-two is passed as the winner as well as the chip positions result.innerHTML = 'Player two wins!' } } } //add an event listener to each square that will trigger the checkBoard function on click squares.forEach(square =&gt; square.addEventListener('click', checkBoard)) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>*{ box-sizing:border-box; text-align:center; } @font-face{ font-family:BlackChancery; src:url(../blkChancery.ttf) format('truetype'); } body{ background:teal; font-family:BlackChancery; font-size:1.17rem; /* Nice golden yellow color 252, 186, 3 */ } .grid{ margin:auto; margin-top:calc(2vh + 120px); border:solid 1px black; overflow:hidden; transform:scale(2.4); /* translate(-50%,-50%) */ display:flex;align-content:center; justify-content: center; flex-wrap:wrap;background-image:linear-gradient(-33deg,#384e65,#2e2e2e); height:124px; width:144px; } .grid div{ height:20px; width:20px; border-radius:50%; background:white; border:solid 1.8px black; filter:hue-rotate(0deg) blur(0.44px); transition:all 980ms ease-in-out; } .base{ /* Base set of Circles which are not used by players. */ display:none; } .player-one{ background-image:linear-gradient(-33deg,red,rgb(186,4,119),rgb(186,4,119))!important; border-radius:10px; filter:hue-rotate(0deg) blur(0.34px); transform:rotate(0deg); transition:all 980ms ease-in-out; } .player-two{ background-image:linear-gradient(-33deg,blue,rgb(4,186,156),rgb(4,186,156))!important; border-radius:10px; filter:hue-rotate(0deg) blur(0.34px); transform:rotate(0deg); transition:all 980ms ease-in-out; } .player-one:hover{ filter:hue-rotate(-49deg) blur(0.34px); transform:rotate(54deg); transition:all 980ms ease-in-out; } .player-two:hover{ filter:hue-rotate(47deg) blur(0.34px); transform:rotate(54deg); transition:all 980ms ease-in-out; } #current-player{ position:relative; background-image:linear-gradient(-33deg,red,rgb(186,4,119),rgb(186,4,119))!important; filter:blur(0.588px); text-shadow:1px 1px 1.7px white; border:solid 2.98px black; width:148px !important; height:48px !important; font-size:1.94rem; border-radius:50%; padding:8px 28px; margin-top:8px; top:8px; } #Reset{ margin-top:calc(1.8vh + 78px); padding:4px 8px 4px 8px; border-radius:7px; background:rgb(67, 240, 211); font-size:1.24rem; } /* position:absolute; top:50vh; left:50vw; */</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;h1&gt;Custom Connect Four&lt;br&gt;2 player Game&lt;/h1&gt; &lt;h3&gt;The Current Player&lt;br&gt;is: Player &lt;br&gt;&lt;span id="current-player" width="50"&gt;1&lt;/span&gt;&lt;/h3&gt; &lt;h3 id="result"&gt;&lt;/h3&gt; &lt;div class="grid"&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div class="taken base"&gt;&lt;/div&gt; &lt;div class="taken base"&gt;&lt;/div&gt; &lt;div class="taken base"&gt;&lt;/div&gt; &lt;div class="taken base"&gt;&lt;/div&gt; &lt;div class="taken base"&gt;&lt;/div&gt; &lt;div class="taken base"&gt;&lt;/div&gt; &lt;div class="taken base"&gt;&lt;/div&gt; &lt;/div&gt;&lt;br&gt; &lt;button id="Reset"&gt;Reset&lt;/button&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js" integrity="sha256-hBMojZuWKocCflyaG8T19KBq9OlTlK39CTxb8AUWKhY=" crossorigin="anonymous"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Are there any errors that I've not spotted? How could it be improved? Styling could be a lot better I guess, but any other suggestions apart from that?</p> <p>In the codepen example i have switched out all the let &amp; const statements &amp; created a helper function for document.querySelector &amp; selectorAll..</p>
[]
[ { "body": "<p><strong>Use the <code>defer</code> attribute</strong> on the script tag instead of having a <code>DOMContentLoaded</code> listener - it'll cut down on a level of indentation throughout your <em>entire</em> script.</p>\n<p><strong>Use <code>let</code> instead of an IIFE</strong> to solve the closure-inside-loops issue - <code>let</code> is block-scoped to each iteration inside the loop out-of-the box, so there's no need for an IIFE - it significantly reduces the noisyness of the code. If you need to support IE11, then like always, the tried-and-true professional solution is to write code in the latest version of the language, keeping the source code as readable and elegant as possible, and then use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to transpile down to ES5 automatically for production. (Don't transpile to ES5 manually!)</p>\n<p>Another option would be to consider using <strong>event delegation</strong> instead of adding a listener to each cell: watch for clicks on the whole <code>.grid</code>, and when a cell is clicked, get the target child's index from the collection of children inside the click listener.</p>\n<p><strong>Save the clicked square in a variable</strong> instead of repeating <code>squares[index]</code> lots of times - write <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> code.</p>\n<p><strong><code>base</code> elements are weird</strong> - you have 7 <code>&lt;div class=&quot;taken base&quot;&gt;&lt;/div&gt;</code> elements at the end presumably in order for the <code>squares[index + 7].classList.contains('taken')</code> test to work. These <code>taken base</code> elements are always hidden - they exist solely for this logic. Consider removing them entirely, and instead checking to see if <code>squares[index + 7]</code> exists first:</p>\n<pre><code>const belowSquare = squares[index + 7];\nif(!belowSquare || belowSquare.classList.contains('taken')){\n</code></pre>\n<p><strong>Enter short branches first</strong> so you can return early without requiring many <code>}</code>s at the end of a long block - it makes the logic easier to follow when a reader of the code doesn't have to keep track of a condition that was used 20 lines ago.</p>\n<pre><code>if (belowSquare &amp;&amp; !belowSquare.classList.contains('taken')) {\n alert('Cant Go Here')\n return;\n}\n// rest of the code\n</code></pre>\n<p><strong>Avoid <code>alert</code></strong> and its siblings <code>confirm</code> and <code>prompt</code> - they're not user-friendly, since they block the browser; when one of those dialogs is active, other JavaScript and page painting will not occur, and the page will seem completely unresponsive until the dialog is dismissed. Better to make a proper modal in the DOM and insert text into it instead.</p>\n<p><strong>Grammar</strong> Proper spelling and grammer really helps improve the presentation of an app. Use <code>&quot;Can't go here&quot;</code>.</p>\n<p><strong>DRY circle toggling</strong> Rather than two separate branches for each possible player, make the <code>player-#</code> class use a number for the player rather than words, so that setting the active player just requires concatenation with the <code>currentPlayer</code>:</p>\n<pre><code>square.classList.add('taken');\nsquare.classList.add('player-' + currentPlayer);\ncurrentPlayer = currentPlayer === 1 ? 2 : 1;\n</code></pre>\n<p><strong>Only use <code>innerHTML</code> when deliberately inserting HTML markup</strong> - otherwise, <code>textContent</code> is faster, safer, and more appropriate.</p>\n<p><strong>Don't add the same listener to an element lots of times in a loop</strong> with <code>resetBtn</code>, since the logic to carry out is the same - instead, add a <em>single</em> listener to the button, and inside the listener, iterate over all elements necessary. Also, there's no need to declare parameters you don't use: <code>(e) =&gt;</code> can be <code>() =&gt;</code>. Lastly, to reset all the class names of an element, you can assign the empty string to its <code>className</code>.</p>\n<pre><code>resetBtn.addEventListener('click', () =&gt; {\n for (const square of squares) {\n square.className = '';\n }\n displayCurrentPlayer.textContent = 1;\n});\n</code></pre>\n<p><strong>Use precise, descriptive function names</strong> to make the code more self-documenting, and to avoid the need for comments. This:</p>\n<pre><code>//check the board for a win or lose\nfunction checkBoard() {\n</code></pre>\n<p>can be</p>\n<pre><code>checkBoardForWinner() {\n</code></pre>\n<p>Also, rather than adding a click listener to each square that calls this, call this <em>inside the listener</em> already on each square.</p>\n<p><strong><code>winningArrays</code> is WET and buggy</strong> There are many 4-in-a-row combinations it doesn't pick up on. For example:</p>\n<p><a href=\"https://i.stack.imgur.com/quKZW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/quKZW.png\" alt=\"enter image description here\" /></a></p>\n<p>A better approach would be to encode the 4-in-a-row logic dynamically based in the indicies. Iterate over all cells, and check whether the northeast, east, southeast, or south have 3 of the same squares in a row. See <code>checkBoardForWinner</code> below:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const displayCurrentPlayer = document.querySelector('#current-player');\nconst squares = document.querySelectorAll('.grid div');\nconst resetBtn = document.querySelector('#Reset');\nconst result = document.querySelector('#result');\n\nlet currentPlayer = 1;\n\nfor (let i = 0, len = squares.length; i &lt; len; i++) {\n const square = squares[i];\n square.onclick = () =&gt; {\n // if the square below your current square is taken, you can go on top of it.\n const belowSquare = squares[i + 7];\n if (belowSquare &amp;&amp; !belowSquare.classList.contains('taken')) {\n alert(\"Can't go here\");\n return;\n }\n square.classList.add('taken');\n square.classList.add('player-' + currentPlayer);\n currentPlayer = currentPlayer === 1 ? 2 : 1;\n displayCurrentPlayer.textContent = currentPlayer;\n checkBoardForWinner();\n };\n}\nresetBtn.addEventListener('click', () =&gt; {\n for (const square of squares) {\n square.className = '';\n }\n displayCurrentPlayer.textContent = 1;\n});\nconst getPlayerOnSquare = square =&gt; {\n if (!square) return null;\n const { classList } = square;\n return classList.contains('player-1')\n ? 1\n : classList.contains('player-2')\n ? 2\n : null;\n};\nfunction checkBoardForWinner() {\n for (let baseSquareIndex = 0; baseSquareIndex &lt; squares.length; baseSquareIndex++) {\n const directionIndexDifferences = [\n -6, // Northeast\n 1, // East\n 8, // Southeast\n 7 // South\n ];\n // Look 4 squares in each direction from baseSquareIndex\n // If each of those squares has the same player, they win\n const playersOnSquares = directionIndexDifferences.map(\n difference =&gt; Array.from(\n { length: 4 },\n (_, i) =&gt; getPlayerOnSquare(squares[baseSquareIndex + (i * difference)])\n )\n );\n const foundSequence = playersOnSquares.find(\n players =&gt; players[0] &amp;&amp; players.every(player =&gt; player === players[0])\n );\n if (foundSequence) {\n result.textContent = `Player ${foundSequence[0]} wins!`;\n }\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n box-sizing: border-box;\n text-align: center;\n}\n\n@font-face {\n font-family: BlackChancery;\n src: url(../blkChancery.ttf) format('truetype');\n}\n\nbody {\n background: teal;\n font-family: BlackChancery;\n font-size: 1.17rem;\n /* Nice golden yellow color 252, 186, 3 */\n}\n\n.grid {\n margin: auto;\n margin-top: calc(2vh + 120px);\n border: solid 1px black;\n overflow: hidden;\n transform: scale(2.4);\n /* translate(-50%,-50%) */\n display: flex;\n align-content: center;\n justify-content: center;\n flex-wrap: wrap;\n background-image: linear-gradient(-33deg, #384e65, #2e2e2e);\n height: 124px;\n width: 144px;\n}\n\n.grid div {\n height: 20px;\n width: 20px;\n border-radius: 50%;\n background: white;\n border: solid 1.8px black;\n filter: hue-rotate(0deg) blur(0.44px);\n transition: all 980ms ease-in-out;\n}\n\n.player-1 {\n background-image: linear-gradient(-33deg, red, rgb(186, 4, 119), rgb(186, 4, 119))!important;\n border-radius: 10px;\n filter: hue-rotate(0deg) blur(0.34px);\n transform: rotate(0deg);\n transition: all 980ms ease-in-out;\n}\n\n.player-2 {\n background-image: linear-gradient(-33deg, blue, rgb(4, 186, 156), rgb(4, 186, 156))!important;\n border-radius: 10px;\n filter: hue-rotate(0deg) blur(0.34px);\n transform: rotate(0deg);\n transition: all 980ms ease-in-out;\n}\n\n.player-one:hover {\n filter: hue-rotate(-49deg) blur(0.34px);\n transform: rotate(54deg);\n transition: all 980ms ease-in-out;\n}\n\n.player-two:hover {\n filter: hue-rotate(47deg) blur(0.34px);\n transform: rotate(54deg);\n transition: all 980ms ease-in-out;\n}\n\n#current-player {\n position: relative;\n background-image: linear-gradient(-33deg, red, rgb(186, 4, 119), rgb(186, 4, 119))!important;\n filter: blur(0.588px);\n text-shadow: 1px 1px 1.7px white;\n border: solid 2.98px black;\n width: 148px !important;\n height: 48px !important;\n font-size: 1.94rem;\n border-radius: 50%;\n padding: 8px 28px;\n margin-top: 8px;\n top: 8px;\n}\n\n#Reset {\n margin-top: calc(1.8vh + 78px);\n padding: 4px 8px 4px 8px;\n border-radius: 7px;\n background: rgb(67, 240, 211);\n font-size: 1.24rem;\n}\n\n\n/* position:absolute;\n top:50vh; left:50vw; */</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h1&gt;Custom Connect Four&lt;br&gt;2 player Game&lt;/h1&gt;\n&lt;h3&gt;The Current Player&lt;br&gt;is: Player &lt;br&gt;&lt;span id=\"current-player\" width=\"50\"&gt;1&lt;/span&gt;&lt;/h3&gt;\n&lt;h3 id=\"result\"&gt;&lt;/h3&gt;\n\n&lt;div class=\"grid\"&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n\n &lt;div&gt;&lt;/div&gt;\n &lt;div&gt;&lt;/div&gt;\n&lt;/div&gt;&lt;br&gt;\n\n&lt;button id=\"Reset\"&gt;Reset&lt;/button&gt;\n\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js\" integrity=\"sha256-hBMojZuWKocCflyaG8T19KBq9OlTlK39CTxb8AUWKhY=\" crossorigin=\"anonymous\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:49:06.943", "Id": "252326", "ParentId": "252271", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T21:03:55.517", "Id": "252271", "Score": "4", "Tags": [ "javascript", "css", "html5", "connect-four" ], "Title": "Custom Connect Four game on CodePen using JavaScript" }
252271
<p>I've recently started learning rust and doing cryptopals as exercise. I coded a program that decrypts single xor cypher. The algorithm I came up with is very simple and probably not efficient, but I would like more emphasis on rust philosophy and syntax</p> <pre><code>extern crate hex; use std::collections::HashMap; fn main() { let ciphertext = &quot;1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736&quot;; let ciphertext_bytes = hex::decode(ciphertext).unwrap(); let xor_key = find_xor_key(&amp;ciphertext_bytes); println!(&quot;{}&quot;, ciphertext_bytes.iter().map(|x|(x^xor_key) as char ).collect::&lt;String&gt;()); } fn find_xor_key(ciphertext: &amp;Vec&lt;u8&gt;) -&gt; u8{ let mut max_score = 0; let mut best_key = 0; for xor_key in 1..255{ let xored_vec = ciphertext.iter().map(|x|x^xor_key).collect(); let score = get_score(xored_vec); if score &gt; max_score{ max_score = score; best_key = xor_key; } } println!(&quot;{}&quot;, max_score); best_key } fn get_score(text: Vec&lt;u8&gt;) -&gt; u8 { let ideal_frequencies: HashMap&lt;char, f32&gt; = [ ('E', 11.1607), ('M', 3.0129), ('A', 8.4966), ('H', 3.0034), ('R', 7.5809), ('G', 2.4705), ('I', 7.5448), ('B', 2.0720), ('O', 7.1635), ('F', 1.8121), ('T', 6.9509), ('Y', 1.7779), ('N', 6.6544), ('W', 1.2899), ('S', 5.7351), ('K', 1.1016), ('L', 5.4893), ('V', 1.0074), ('C', 4.5388), ('X', 0.2902), ('U', 3.6308), ('Z', 0.2722), ('D', 3.3844), ('J', 0.1965), ('P', 3.1671), ('Q', 0.1962), ].iter().cloned().collect(); for byte in text.clone(){ let char_rep: char = byte as char; if !char_rep.is_ascii(){ return 0; } } let mut score = 1; let chars: Vec&lt;char&gt; = text.iter().cloned().map(|x|x as char).collect(); let frequencies: HashMap&lt;char, f32&gt; = calculate_frequencies(&amp;chars.into_iter().collect::&lt;String&gt;()); for (letter, frequency) in &amp;frequencies{ if ideal_frequencies.contains_key(&amp;letter) &amp;&amp; //already checked here that it exists in the hashmap f32::abs(frequency - ideal_frequencies.get(&amp;letter).unwrap()) &lt;= 10.0{ score += 1; } } score } fn calculate_frequencies(text: &amp;str) -&gt;HashMap&lt;char, f32&gt;{ let mut frequencies: HashMap&lt;char, f32&gt; = HashMap::new(); let mut letter_counts:HashMap&lt;char, i32&gt; = HashMap::new(); let text_upper = text.to_ascii_uppercase(); for c in text_upper.chars(){ let count = letter_counts.entry(c).or_insert(0); *count += 1; } for (c, count) in letter_counts{ frequencies.entry(c).or_insert(count as f32 / text_upper.len() as f32 * 100.0); } frequencies } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<pre class=\"lang-rust prettyprint-override\"><code>extern crate hex;\n</code></pre>\n<p><code>extern crate</code> is generally not necessary for programs since the 2018 (currently latest) edition of Rust. You should be able to delete this line, provided that <code>edition = &quot;2018&quot;</code> is in your <code>Cargo.toml</code> file.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>let ciphertext_bytes = hex::decode(ciphertext).unwrap();\n</code></pre>\n<p>If you change <code>.unwrap</code> to <code>.expect(&quot;failed to decode ciphertext&quot;)</code> then there'll be a little more information in the error message. Of course, for a well-made command line program, you'd want to print your own better-formatted error message, instead of a Rust &quot;panic&quot; error.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn find_xor_key(ciphertext: &amp;Vec&lt;u8&gt;) -&gt; u8{\n</code></pre>\n<p>Accepting <code>&amp;Vec&lt;u8&gt;</code> is usually overly restrictive because it requires the caller to have constructed a <code>Vec</code>, whereas if you change the type to <code>&amp;[u8]</code> they can pass any <em>slice</em> of bytes. This will work without needing to change <code>main</code>, because <code>Vec</code> <em>derefs</em> to a byte slice.</p>\n<p>The same applies to <code>get_score</code>'s parameter, but you'll need to tweak a couple things to make that work, like giving <code>xored_vec</code> the explicit type <code>Vec&lt;u8&gt;</code> and changing <code>byte as char</code> to <code>*byte as char</code>.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code> let ideal_frequencies: HashMap&lt;char, f32&gt; = [\n...\n ].iter().cloned().collect();\n</code></pre>\n<p>This is basically a constant, so it'd be nice if we can compute this hash map only once rather than every time we check a score. We can do that with the <a href=\"https://docs.rs/once_cell/1.5.2/once_cell/sync/struct.Lazy.html\" rel=\"nofollow noreferrer\"><code>once_cell</code></a> crate, which will hopefully soon become <a href=\"https://doc.rust-lang.org/nightly/std/lazy/struct.Lazy.html\" rel=\"nofollow noreferrer\">part of the standard library</a>. Like this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>static IDEAL_FREQUENCIES: Lazy&lt;HashMap&lt;char, f32&gt;&gt; = Lazy::new(|| [\n ('E', 11.1607),\n ...\n].iter().cloned().collect());\n</code></pre>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>for byte in text.clone(){\n</code></pre>\n<p>Use <code>text.iter()</code> instead of <code>text.clone()</code>; it avoids allocating a copy. In general, where both are available, <code>.into_iter()</code> consumes the structure and iterates over its elements by value (moves them), and <code>.iter()</code> does not consume the structure but iterates over references to its elements instead.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>let char_rep: char = byte as char;\nif !char_rep.is_ascii(){\n</code></pre>\n<p>You can just use <code>if !byte.is_ascii() {</code> here.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>let chars: Vec&lt;char&gt; = text.iter().cloned().map(|x|x as char).collect();\nlet frequencies: HashMap&lt;char, f32&gt; = calculate_frequencies(&amp;chars.into_iter().collect::&lt;String&gt;()); \n</code></pre>\n<p><code>.cloned().map(|x|x as char)</code> can be written as <code>.map(|x| *x as char)</code>.</p>\n<p>You're collecting into <code>chars</code> and then immediately iterate to convert it to a <code>String</code>; that isn't necessary because you can just write</p>\n<pre class=\"lang-rust prettyprint-override\"><code>calculate_frequencies(&amp;text.iter().map(|x| *x as char).collect::&lt;String&gt;())\n</code></pre>\n<p>But, there's a bigger point: <code>text</code> was already an <code>&amp;[u8]</code>, and if we want a <code>&amp;str</code> out of that, that's just <a href=\"https://doc.rust-lang.org/std/str/fn.from_utf8.html\" rel=\"nofollow noreferrer\"><code>std::str::from_utf8</code></a>.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>calculate_frequencies(std::str::from_utf8(text).unwrap())\n</code></pre>\n<p>(<code>.unwrap()</code> will never fail here because we already checked that every byte is ASCII, so it cannot be invalid UTF-8.)</p>\n<hr />\n<p>Your loop over the frequencies has several unnecessary <code>&amp;</code>s, and also looks up in the hash map twice instead of once; here's both fixed:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>for (letter, frequency) in frequencies.iter() {\n if let Some(ideal_frequency) = IDEAL_FREQUENCIES.get(letter) {\n if (frequency - ideal_frequency).abs() &lt;= 10.0 {\n score += 1;\n }\n } \n}\n</code></pre>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn calculate_frequencies(text: &amp;str) -&gt;HashMap&lt;char, f32&gt;{\n</code></pre>\n<p>If we want to optimize for performance, which a real code-breaking tool would want to do, then this function should be accepting <code>&amp;[u8]</code>, since the only thing it does with the <code>str</code> is split back to characters, and we know all the characters are ASCII at this point. But for more general idiomatic programming, taking <code>&amp;str</code> is fine.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>let mut frequencies: HashMap&lt;char, f32&gt; = HashMap::new();\nlet mut letter_counts:HashMap&lt;char, i32&gt; = HashMap::new();\n</code></pre>\n<p>You can leave out the type declarations here and they will be inferred.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>let text_upper = text.to_ascii_uppercase();\nfor c in text_upper.chars(){\n</code></pre>\n<p>This allocates a <code>String</code> of uppercase unnecessarily; we might as well do it per-character instead:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>for c in text.chars() {\n let c = c.to_ascii_uppercase();\n</code></pre>\n<p>(Note, however, that this strategy does not work for Unicode-aware uppercasing, where one <code>char</code> may occasionally become several.)</p>\n<hr />\n<p>This is not a matter of Rust idiom at all, but I notice that <code>frequencies</code> is identical to <code>letter_counts</code> except for the values getting scaled. So, we can reuse a single <code>HashMap</code> instead of duplicating it:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn calculate_frequencies(text: &amp;str) -&gt;HashMap&lt;char, f32&gt;{\n let count_to_frequency_scale = 100.0 / text.len() as f32;\n \n let mut counts = HashMap::new();\n for c in text.chars() {\n *counts.entry(c.to_ascii_uppercase()).or_insert(0.0) += 1.0;\n }\n \n // Rescale counts to frequencies\n for count in counts.values_mut() {\n *count *= count_to_frequency_scale;\n }\n counts\n}\n</code></pre>\n<p>Note: Using <code>f32</code> instead of <code>i32</code> for counting does not introduce any floating-point error, for reasonable string lengths: <code>f32</code> exactly represents all integers up to 2<sup>24</sup> - 1 = 16,777,216. (However, there <em>would</em> be accumulated error if we tried to apply <code>count_to_frequency_scale</code> while counting instead of after.)</p>\n<p>If it didn't happen to be possible to reuse the same map, I'd be suggesting using iterators to do the transformation instead:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>letter_counts\n .into_iter()\n .map(|(key, count)| (key, count as f32 * count_to_frequency_scale))\n .collect()\n</code></pre>\n<hr />\n<p>Here's your code with all of my suggestions, and also formatted with <code>rustfmt</code>. I haven't tested it because I was working in the <a href=\"https://play.rust-lang.org/\" rel=\"nofollow noreferrer\"><em>Rust Playground</em></a> which doesn't include the <code>hex</code> crate in its available libraries.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>extern crate hex;\nuse once_cell::sync::Lazy;\nuse std::collections::HashMap;\n\n#[allow(dead_code)]\nfn main() {\n let ciphertext = &quot;1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736&quot;;\n let ciphertext_bytes = hex::decode(ciphertext).unwrap();\n let xor_key = find_xor_key(&amp;ciphertext_bytes);\n println!(\n &quot;{}&quot;,\n ciphertext_bytes\n .iter()\n .map(|x| (x ^ xor_key) as char)\n .collect::&lt;String&gt;()\n );\n}\n\nfn find_xor_key(ciphertext: &amp;[u8]) -&gt; u8 {\n let mut max_score = 0;\n let mut best_key = 0;\n for xor_key in 1..255 {\n let xored_vec: Vec&lt;u8&gt; = ciphertext.iter().map(|x| x ^ xor_key).collect();\n let score = get_score(&amp;xored_vec);\n if score &gt; max_score {\n max_score = score;\n best_key = xor_key;\n }\n }\n println!(&quot;{}&quot;, max_score);\n\n best_key\n}\n\nfn get_score(text: &amp;[u8]) -&gt; u8 {\n for byte in text.iter() {\n if !byte.is_ascii() {\n return 0;\n }\n }\n let mut score = 1;\n let frequencies = calculate_frequencies(std::str::from_utf8(text).unwrap());\n\n for (letter, frequency) in frequencies.iter() {\n if let Some(ideal_frequency) = IDEAL_FREQUENCIES.get(letter) {\n if (frequency - ideal_frequency).abs() &lt;= 10.0 {\n score += 1;\n }\n }\n }\n score\n}\n\nfn calculate_frequencies(text: &amp;str) -&gt; HashMap&lt;char, f32&gt; {\n let count_to_frequency_scale = 100.0 / text.len() as f32;\n\n let mut counts = HashMap::new();\n for c in text.chars() {\n *counts.entry(c.to_ascii_uppercase()).or_insert(0.0) += 1.0;\n }\n\n // Rescale counts to frequencies\n for count in counts.values_mut() {\n *count *= count_to_frequency_scale;\n }\n counts\n}\n\nstatic IDEAL_FREQUENCIES: Lazy&lt;HashMap&lt;char, f32&gt;&gt; = Lazy::new(|| {\n [\n ('E', 11.1607),\n ('M', 3.0129),\n ('A', 8.4966),\n ('H', 3.0034),\n ('R', 7.5809),\n ('G', 2.4705),\n ('I', 7.5448),\n ('B', 2.0720),\n ('O', 7.1635),\n ('F', 1.8121),\n ('T', 6.9509),\n ('Y', 1.7779),\n ('N', 6.6544),\n ('W', 1.2899),\n ('S', 5.7351),\n ('K', 1.1016),\n ('L', 5.4893),\n ('V', 1.0074),\n ('C', 4.5388),\n ('X', 0.2902),\n ('U', 3.6308),\n ('Z', 0.2722),\n ('D', 3.3844),\n ('J', 0.1965),\n ('P', 3.1671),\n ('Q', 0.1962),\n ]\n .iter()\n .cloned()\n .collect()\n});\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T03:17:02.487", "Id": "252278", "ParentId": "252272", "Score": "3" } } ]
{ "AcceptedAnswerId": "252278", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T21:13:23.670", "Id": "252272", "Score": "2", "Tags": [ "rust" ], "Title": "single byte xor decryption code" }
252272
<p><strong>Data Structure coming back from the server</strong></p> <pre><code>[ { id: 1, type: &quot;Pickup&quot;, items: [ { id: 1, description: &quot;Item 1&quot; } ] }, { id: 2, type: &quot;Drop&quot;, items: [ { id: 0, description: &quot;Item 0&quot; } ] }, { id: 3, type: &quot;Drop&quot;, items: [ { id: 1, description: &quot;Item 1&quot; }, { id: 2, description: &quot;Item 2&quot; } ] }, { id: 0, type: &quot;Pickup&quot;, items: [ { id: 0, description: &quot;Item 0&quot; }, { id: 2, description: &quot;Item 2&quot; } ] } ]; </code></pre> <ul> <li>Each element represents an event.</li> <li>Each event is only a pickup or drop.</li> <li>Each event can have one or more items.</li> </ul> <p><strong>Initial State</strong></p> <p>On initial load, loop over the response coming from the server and add an extra property called isSelected to each event, each item, and set it as false as default. <strong>-- Done.</strong></p> <p>This isSelected property is for UI purpose only and tells user(s) which event(s) and/or item(s) has/have been selected.</p> <pre><code>// shove the response coming from the server here and add extra property called isSelected and set it to default value (false) const initialState = { events: [] } </code></pre> <p>moveEvent method:</p> <pre><code>const moveEvent = ({ events }, selectedEventId) =&gt; { // de-dupe selected items const selectedItemIds = {}; // grab and find the selected event by id let foundSelectedEvent = events.find(event =&gt; event.id === selectedEventId); // update the found event and all its items' isSelected property to true foundSelectedEvent = { ...foundSelectedEvent, isSelected: true, items: foundSelectedEvent.items.map(item =&gt; { item = { ...item, isSelected: true }; // Keep track of the selected items to update the other events. selectedItemIds[item.id] = item.id; return item; }) }; events = events.map(event =&gt; { // update events array to have the found selected event if(event.id === foundSelectedEvent.id) { return foundSelectedEvent; } // Loop over the rest of the non selected events event.items = event.items.map(item =&gt; { // if the same item exists in the selected event's items, then set item's isSelected to true. const foundItem = selectedItemIds[item.id]; // foundItem is the id of an item, so 0 is valid if(foundItem &gt;= 0) { return { ...item, isSelected: true }; } return item; }); const itemCount = event.items.length; const selectedItemCount = event.items.filter(item =&gt; item.isSelected).length; // If all items in the event are set to isSelected true, then mark the event to isSelected true as well. if(itemCount === selectedItemCount) { event = { ...event, isSelected: true }; } return event; }); return { events } } </code></pre> <p>Personally, I don't like the way I've implemented the moveEvent method, and it seems like an imperative approach even though I'm using find, filter, and map. All this moveEvent method is doing is flipping the isSelected flag.</p> <ol> <li>Is there a better solution?</li> <li>Is there a way to reduce the amount of looping? Maybe events should be an object and even its items. At least, the lookup would be fast for finding an event, and I don't have to use Array.find initially. However, I still have to either loop over each other non selected events' properties or convert them back and forth using Object.entries and/or Object.values.</li> <li>Is there more a functional approach? Can recursion resolve this?</li> </ol> <p>Usage and Result</p> <pre><code>// found the event with id 0 const newState = moveEvent(initialState, 0); // Expected results [ { id: 1, type: 'Pickup', isSelected: false, items: [ { id: 1, isSelected: false, description: 'Item 1' } ] } { id: 2, type: 'Drop', // becasue all items' isSelected properties are set to true (even though it is just one), then set this event's isSelected to true isSelected: true, // set this to true because event id 0 has the same item (id 1) items: [ { id: 0, isSelected: true, description: 'Item 0' } ] } { id: 3, type: 'Drop', // since all items' isSelected properties are not set to true, then this should remain false. isSelected: false, items: [ { id: 1, isSelected: false, description: 'Item 1' }, // set this to true because event id 0 has the same item (id 2) { id: 2, isSelected: true, description: 'Item 2' } ] } { id: 0, type: 'Pickup', // set isSelected to true because the selected event id is 0 isSelected: true, items: [ // since this belongs to the selected event id of 0, then set all items' isSelected to true { id: 0, isSelected: true, description: 'Item 0' }, { id: 2, isSelected: true, description: 'Item 2' } ] } ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T01:15:11.557", "Id": "496952", "Score": "0", "body": "Please describe what `moveEvent` does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T02:07:21.403", "Id": "496955", "Score": "0", "body": "I thought my post was clear and detailed. Anyways, moveEvent is just a method that flips isSelected from false to true based on the given event id (2nd parameter). When given an event id (AKA selected event), it will find the event, set its' isSelected to true, loop over each item belonging to that event, and set each item's isSelected to true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T02:07:24.967", "Id": "496956", "Score": "0", "body": "Then, loop over the rest of the other events (AKA non selected events) and items, if the item in non selected event is the same item in the selected event (by id), then mark the item's isSelected to true. If all items' isSelected are set to true in a non selected event, then set the non selected event's isSelected to true too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T09:49:56.380", "Id": "497002", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:11:33.377", "Id": "497007", "Score": "0", "body": "Would it be helpful to simplify the original post and basically say I want this array transform into this array?" } ]
[ { "body": "<p>You can just get all selected items and compute everything in one go using functional approach with <code>map</code>:</p>\n<pre><code>const moveEvent = ({ events }, selectedEventId) =&gt; {\n const selectedEvent = events.find(({id}) =&gt; id === selectedEventId);\n const selectedItems = new Set(selectedEvent.items.map(({id}) =&gt; id));\n const allItemsSelected = (items) =&gt; items.every(({ id }) =&gt; selectedItems.has(id));\n\n return {\n events: events.map((event) =&gt; ({\n ...event,\n isSelected: (selectedEventId === event.id || allItemsSelected(event.items)),\n items: event.items.map((item) =&gt; ({\n ...item,\n isSelected: selectedItems.has(item.id)\n }))\n }))\n };\n};\n</code></pre>\n<p>If you want to be truly functional you can transform temp variables at the beginning of the <code>moveEvent</code> to pure functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:12:29.723", "Id": "497108", "Score": "0", "body": "Thank you so much! I like this approach over stackoverflow. This is easier and less to maintain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:15:34.460", "Id": "497109", "Score": "0", "body": "Dumb question...isn't this already functional? it's a pure function that takes in two arguments, no global variables, and returns new data each time without modifying anything. I'm not sure what you mean about transform temp variables at the beginning. Isn't it already defining variables at the beginning?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T03:54:22.943", "Id": "497136", "Score": "0", "body": "@FNMT8L9IN82 I think, but I'm not 100% sure, that the idea is that functional programming avoids mutating *scope* - that is, variables are never defined except in arguments, resulting in functions that take arguments and immediately return new values every time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T06:42:26.967", "Id": "497143", "Score": "0", "body": "@FNMT8L9IN82 yes, for the external observer it is pure function. But internally `moveEvent` has a sequence of statements and that is forbidden in purely functional languages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T12:32:01.743", "Id": "497158", "Score": "0", "body": "So you mean that I should take out selectedEvent, selectedItems, allItemsSelected into their own functions, and have moveEvent call those functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T12:48:47.263", "Id": "497160", "Score": "0", "body": "In this particular scenario, I don't think you should do it, but if you want to reuse them somewhere out of `moveEvent` then yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:58:59.430", "Id": "497313", "Score": "0", "body": "Thank you much for your time and response!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T18:30:55.520", "Id": "252335", "ParentId": "252276", "Score": "2" } } ]
{ "AcceptedAnswerId": "252335", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T00:57:52.193", "Id": "252276", "Score": "1", "Tags": [ "javascript", "object-oriented", "array", "functional-programming" ], "Title": "JavaScript, looping, and functional approach" }
252276
<p>I'm coding a random strings generator. It's working, but I'm not sure if this is efficient.</p> <pre><code>/** * @param n total number of strings to generate * @param length length of generated strings * @param charsetStr charset to be used when generate */ public static List&lt;String&gt; generateRandomStrings(int n, int length, @NonNull String charsetStr) { if (n &lt; 1 || length &lt; 1 || charsetStr.length() &lt; 1) { throw new IllegalArgumentException(String.format(&quot;Illegal argument(s): %d, %d, %s&quot;, n, length, charsetStr)); } //remove duplicate chars Set&lt;Character&gt; charset = new HashSet&lt;&gt;(charsetStr.length()); StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; charsetStr.length(); i++) { char c = charsetStr.charAt(i); if (charset.add(c)) { sb.append(c); } } charsetStr = sb.toString(); BigDecimal caseNum = BigDecimal.valueOf(charsetStr.length()).pow(length); BigDecimal nBd = BigDecimal.valueOf(n); if (caseNum.compareTo(nBd) &lt; 0) { throw new IllegalArgumentException( String.format(&quot;Number of possible strings cannot exceed the requested size: (length of '%s') ^ %d &lt; %d&quot;, charsetStr, length, n)); } if (nBd.divide(caseNum, 1, RoundingMode.HALF_UP).compareTo(BigDecimal.valueOf(5, 1)) &lt; 0) { //when fill factor is below 50% //generate until target size is reached Set&lt;String&gt; results = new HashSet&lt;&gt;(n); while (results.size() &lt; n) { results.add(RandomStringUtils.random(length, charsetStr)); } return new ArrayList&lt;&gt;(results); } // when fill factor is above 50% // pre-generate all possible strings List&lt;String&gt; results = new ArrayList&lt;&gt;(caseNum.intValue()); generateAllPossibleStrings(results, &quot;&quot;, charsetStr, length); // then shuffle the collection and pick target sized sublist Collections.shuffle(results); return results.subList(0, n); } public static void generateAllPossibleStrings(@NonNull List&lt;String&gt; results, @NonNull String prefix, @NonNull String charset, int length) { if (prefix.length() &gt;= length) { results.add(prefix); return; } for (int i = 0; i &lt; charset.length(); i++) { generateAllPossibleStrings(results, prefix + charset.charAt(i), charset, length); } } </code></pre> <p>Any advice would be grateful, but my main focus here is performance.</p> <p>I'm using <code>org.apache.commons.lang3.RandomStringUtils</code> to generate strings if <code>n</code> is less than 50% of the number of all possible strings(let's call it &quot;fill factor&quot;). If not, to avoid unnecessary collisions, I generate all possible strings using <code>generateAllPossibleStrings</code>, then shuffle the result and get a sublist from it.</p> <p>The reasons I used 2 methods for generating strings are:</p> <ul> <li>If the fill factor is low(like 1~2%), using <code>generateAllPossibleStrings</code> seemed overkill. So I used <code>org.apache.commons.lang3.RandomStringUtils</code>, hoping collisions not matter much.</li> <li>If the fill factor is high(like more than 90%), using <code>org.apache.commons.lang3.RandomStringUtils</code> seems inefficient since a lot of collisions will occur as time goes by. So I used <code>generateAllPossibleStrings</code> in this case, dropping without any collision looks more efficient than generating.</li> </ul> <p>There is no big reason why I choose 50% as a diverging point; I just used my hunch. This too may need to be fixed.</p> <p>While I mostly wrote about the collision, I'm looking for any advice on performance enhancements. How can I make this more time-efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T03:36:00.603", "Id": "496960", "Score": "1", "body": "What are the expected string length and the charset size?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T04:08:15.410", "Id": "496962", "Score": "0", "body": "@vnp A wild guess of string length is about 10~15, and max charset is alphanumeric(62). Maybe I need to limit the max string length, not sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:01:22.770", "Id": "497210", "Score": "0", "body": "Without doing a full review. You should not shorten names because you can, full names will *always* make the code more readable, even if they are longer. They also have the upside that lines without context becoming much more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:13:53.580", "Id": "497262", "Score": "0", "body": "@Bobby I'm assuming you're talking about `sb`, `n`, and `nBd`. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T03:32:42.680", "Id": "513692", "Score": "1", "body": "You seem to be asking for ideas on how to pick the \"diverging point\". That's really a math problem, and the exact answer will be a formula that depends on `n`, `length` and `charsetStr.length()`. But if you can put realistic bounds on these parameters, you may be able to avoid doing the math." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T03:36:05.347", "Id": "513693", "Score": "0", "body": "The other thing to note is that the problem becomes impractical if `n * length` is too large. You run out of memory." } ]
[ { "body": "<ul>\n<li>Your code broadly follows the Java conventions.</li>\n<li>Your objective is unclear, why do you need random strings? If they are for hashkeys there are plenty of strong methods for generating these. If you need simple tokens then is there any reason you cannot use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html#randomUUID()\" rel=\"nofollow noreferrer\">random UUIDs</a>?</li>\n<li>Your code is named using the programming domain not the problem domain.</li>\n<li>Use Unit tests, they can be used gauge performance for optimisations, but avoid premature optimisation.</li>\n<li>Static methods are an anti-pattern with OOP and should be avoided except in specific circumstances that do not apply here.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T02:00:52.177", "Id": "519439", "Score": "1", "body": "Thank you. About the objective, it's the requirements from our client for generating their coupon codes per coupon type. A coupon type and a coupon code together must be unique(composite key). But the coupon type is out of the scope of this question. Maybe I can use UUIDs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T02:10:22.187", "Id": "519440", "Score": "1", "body": "Oh, and the client should be able to choose charsets(numbers, lower cases, upper cases) for each code generation. Maybe that requirement could be changed, but it's too late for that. Already shipped." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T14:17:09.797", "Id": "263107", "ParentId": "252277", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T01:46:33.330", "Id": "252277", "Score": "9", "Tags": [ "java", "performance", "strings", "generator", "collision" ], "Title": "Generate unique random strings considering collisions" }
252277
<p>I wrote this a few months ago as my first &quot;serious&quot; C program (I've used JS for a few years). It's a simple resource collecting and trading game (based off one I made in HTML/JS), that takes input in the form of some simple commands.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;inttypes.h&gt; #include &lt;math.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; struct trade_like { int8_t buy_item; int8_t sell_item; uint64_t buy_amount; uint64_t sell_amount; int16_t timer; }; struct upgrade { int8_t thread; int8_t id; }; void shorten_number(char *dest, uint64_t number) { if (number &gt;= 1000000000000) { sprintf(dest, &quot;%.2fT&quot;, fmin((double) number / 1000000000000.0, 999.99)); } else if (number &gt;= 1000000000) { sprintf(dest, &quot;%.2fB&quot;, fmin((double) number / 1000000000.0, 999.99)); } else if (number &gt;= 1000000) { sprintf(dest, &quot;%.2fM&quot;, fmin((double) number / 1000000.0, 999.99)); } else if (number &gt;= 1000) { sprintf(dest, &quot;%.2fK&quot;, fmin((double) number / 1000.0, 999.99)); } else { sprintf(dest, &quot;%d&quot;, number); } return; } void print_resources(uint64_t resources[], struct trade_like trades[], struct trade_like deals[], struct upgrade upgrades[]) { char amounts[9][10]; char trade_list[5][48]; char deal_list[3][48]; char upgrade_list[9][36]; char names[9][8] = {&quot;Wood&quot;, &quot;Stone&quot;, &quot;Coal&quot;, &quot;Iron&quot;, &quot;Copper&quot;, &quot;Silver&quot;, &quot;Gold&quot;, &quot;Diamond&quot;, &quot;Emerald&quot;}; char upper_names[9][8] = {&quot;WOOD&quot;, &quot;STONE&quot;, &quot;COAL&quot;, &quot;IRON&quot;, &quot;COPPER&quot;, &quot;SILVER&quot;, &quot;GOLD&quot;, &quot;DIAMOND&quot;, &quot;EMERALD&quot;}; char unlock_costs[8][2][16] = { {&quot;Wood (200)&quot;, &quot;Coal (40)&quot;}, {&quot;Stone (400)&quot;, &quot;Coal (80)&quot;}, {&quot;Stone (200)&quot;, &quot;Iron (100)&quot;}, {&quot;Iron (300)&quot;, &quot;Copper (50)&quot;}, {&quot;Stone (1.00K)&quot;, &quot;Iron (400)&quot;}, {&quot;Copper (500)&quot;, &quot;Coal (300)&quot;}, {&quot;Iron (1.00K)&quot;, &quot;Silver (400)&quot;}, {&quot;Diamond (200)&quot;, &quot;Silver (100)&quot;} }; char multiplier_levels[7][8] = {&quot;+10%&quot;, &quot;+25%&quot;, &quot;+75%&quot;, &quot;DOUBLE&quot;, &quot;LOTS OF&quot;, &quot;TONS OF&quot;}; int16_t base_cost[7] = {200, 500, 1500, 4000, 10000, 20000}; memset(trade_list, '\0', sizeof(trade_list[0][0]) * 240); memset(deal_list, '\0', sizeof(deal_list[0][0]) * 144); memset(upgrade_list, '\0', sizeof(upgrade_list[0][0]) * 324); printf(&quot;\033[F\033[A\033[A\033[A\033[A\033[A\033[A\033[A\033[A\033[A\033[A\033[A&quot;); for (int8_t i = 0; i &lt; 9; i++) { shorten_number(amounts[i], resources[i]); } for (int8_t i = 0; i &lt; 5; i++) { if (trades[i].timer &gt;= 0) { char sell_string[10]; char buy_string[10]; shorten_number(sell_string, trades[i].sell_amount); shorten_number(buy_string, trades[i].buy_amount); sprintf(trade_list[i], &quot;[%d] %s (%s) -&gt; %s (%s)&quot;, i + 1, names[trades[i].sell_item], sell_string, names[trades[i].buy_item], buy_string); } } for (int8_t i = 0; i &lt; 3; i++) { if (deals[i].timer &gt;= 0) { char sell_string[10]; char buy_string[10]; shorten_number(sell_string, deals[i].sell_amount); shorten_number(buy_string, deals[i].buy_amount); sprintf(deal_list[i], &quot;[%d] %s (%s) -&gt; %s (%s)&quot;, i + 1, names[deals[i].sell_item], sell_string, names[deals[i].buy_item], buy_string); } } if (upgrades[0].thread != -1) { sprintf(upgrade_list[0], &quot;MINE %s&quot;, upper_names[upgrades[0].id + 1]); sprintf(upgrade_list[1], &quot; %s&quot;, unlock_costs[upgrades[0].id][0]); sprintf(upgrade_list[2], &quot; %s&quot;, unlock_costs[upgrades[0].id][1]); } if (upgrades[1].thread != -1) { sprintf(upgrade_list[4], &quot;%s %s&quot;, multiplier_levels[(int8_t) ((double) upgrades[1].id / 9.0)], upper_names[upgrades[1].id % 9]); char cost_string[10]; shorten_number(cost_string, (double) base_cost[(int8_t) upgrades[1].id / 9] * (1.0 - 0.1 * (upgrades[1].id % 9))); sprintf(upgrade_list[5], &quot; %s (%s)&quot;, names[upgrades[1].id % 9], cost_string); } if (upgrades[2].thread == 2) { sprintf(upgrade_list[7], &quot;AUTO-%s&quot;, upper_names[upgrades[2].id]); if (upgrades[2].id == 4) { strcpy(upgrade_list[8], &quot; Gold (200)&quot;); } sprintf(upgrade_list[8], &quot; %s (200)&quot;, names[upgrades[2].id + 2]); } else if (upgrades[2].thread == 3) { sprintf(upgrade_list[7], &quot;%s/%s DEALS&quot;, upper_names[upgrades[2].id * 2], upper_names[upgrades[2].id * 2 + 1]); char cost_string[10]; shorten_number(cost_string, 1750 - 375 * upgrades[2].id); sprintf(upgrade_list[8], &quot; %s (%s)&quot;, names[upgrades[2].id * 2 + 1], cost_string); } printf( &quot; Wood: %-9s%-44s%-36s\n Stone: %-9s%-44s%-36s\n Coal: %-9s%-44s%-36s\n Iron: %-9s%-44s%-36s\n Copper: %-9s%-44s%-36s\n Silver: %-9s%-44s%-36s\n Gold: %-9s%-44s%-36s\n Diamond: %-9s%-44s%-36s\n Emerald: %-9s%-44s%-36s\n\n\n\n &gt;&gt; \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b&quot;, amounts[0], trade_list[0], upgrade_list[0], amounts[1], trade_list[1], upgrade_list[1], amounts[2], trade_list[2], upgrade_list[2], amounts[3], trade_list[3], upgrade_list[3], amounts[4], trade_list[4], upgrade_list[4], amounts[5], &quot; &quot;, upgrade_list[5], amounts[6], deal_list[0], upgrade_list[6], amounts[7], deal_list[1], upgrade_list[7], amounts[8], deal_list[2], upgrade_list[8] ); return; } int main(int argc, char** argv) { int8_t unlocked = 0; uint64_t resources[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; double multipliers[9] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}; int8_t auto_level = 0; int16_t item_costs[9] = {1, 2, 5, 10, 25, 40, 80, 200, 875}; char names[9][8] = {&quot;Wood&quot;, &quot;Stone&quot;, &quot;Coal&quot;, &quot;Iron&quot;, &quot;Copper&quot;, &quot;Silver&quot;, &quot;Gold&quot;, &quot;Diamond&quot;, &quot;Emerald&quot;}; struct trade_like trades[5]; struct trade_like deals[3]; int8_t trade_tick = 0; int8_t deal_tick = 0; int8_t unlocked_deals = 0; for (int8_t i = 0; i &lt; 5; i++) { trades[i].timer = -1; if (i &lt; 3) { deals[i].timer = -1; } } struct upgrade upgrades[3]; upgrades[0].thread = 0; upgrades[0].id = 0; upgrades[0].thread = -1; upgrades[1].thread = -1; upgrades[2].thread = -1; int64_t turn_count = 0; char words_redo[4][24]; srand(time(NULL)); strcpy(words_redo[0], &quot;collect&quot;); strcpy(words_redo[1], &quot;wood&quot;); memset(words_redo[2], '\0', sizeof(words_redo[2][0]) * 48); printf(&quot;MERCHANT 2.0.0 [TERMINAL EDITION]\n\n\n\n\n\n\n\n\n\n\n\n Enter 'collect wood' to begin playing!\n\n\n\033[A&quot;); char input[24]; while (strncmp(input, &quot;quit\n&quot;, 5) != 0 &amp;&amp; strncmp(input, &quot;exit\n&quot;, 5) != 0 &amp;&amp; strncmp(input, &quot;q\n&quot;, 2) != 0 &amp;&amp; strncmp(input, &quot;x\n&quot;, 2) != 0) { print_resources(resources, trades, deals, upgrades); fgets(input, 24, stdin); printf(&quot;\033[F\033[A\033[A \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b&quot;); char words[4][24]; int8_t word_count = 0; int8_t within_word = 0; memset(words[0], '\0', sizeof(words[0][0]) * 96); for (int8_t i = 0; i &lt; 24; i++) { if (input[i] == '\n' || input[i] == '\0') { break; } else if (input[i] &gt;= 'a' &amp;&amp; input[i] &lt;= 'z' || input[i] &gt;= 'A' &amp;&amp; input[i] &lt;= 'Z' || input[i] &gt;= '0' &amp;&amp; input[i] &lt;= '9' || input[i] == '-' || input[i] == '_') { words[word_count][within_word++] = input[i]; } else { if (within_word != 0) { word_count++; within_word = 0; if (word_count == 4) { break; } } } } if (strncmp(words[0], &quot;redo\0&quot;, 5) == 0 || strncmp(words[0], &quot;r\0&quot;, 2) == 0 || words[0][0] == '\0') { strcpy(words[0], words_redo[0]); strcpy(words[1], words_redo[1]); strcpy(words[2], words_redo[2]); strcpy(words[3], words_redo[3]); } if (strncmp(words[0], &quot;collect\0&quot;, 8) == 0 || strncmp(words[0], &quot;col\0&quot;, 4) == 0 || strncmp(words[0], &quot;c\0&quot;, 2) == 0) { int16_t collect_amount; if (words[1][0] == '\0' || words[2][0] != '\0') { printf(&quot;ERR: Expected one argument (resource name)\n\n&quot;); continue; } if (strncmp(words[1], &quot;wood\0&quot;, 5) == 0 || strncmp(words[1], &quot;w\0&quot;, 2) == 0) { if (unlocked &lt; 0) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[0]) + (rand() &lt; RAND_MAX * (multipliers[0] - floorf(multipliers[0])))); resources[0] += collect_amount; printf(&quot;Collected %d wood&quot;, collect_amount); } else if (strncmp(words[1], &quot;stone\0&quot;, 6) == 0 || strncmp(words[1], &quot;s\0&quot;, 2) == 0) { if (unlocked &lt; 1) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[1]) + (rand() &lt; RAND_MAX * (multipliers[1] - floorf(multipliers[1])))); resources[1] += collect_amount; printf(&quot;Collected %d stone&quot;, collect_amount); } else if (strncmp(words[1], &quot;coal\0&quot;, 5) == 0 || strncmp(words[1], &quot;c\0&quot;, 2) == 0) { if (unlocked &lt; 2) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[2]) + (rand() &lt; RAND_MAX * (multipliers[2] - floorf(multipliers[2])))); resources[2] += collect_amount; printf(&quot;Collected %d coal&quot;, collect_amount); } else if (strncmp(words[1], &quot;iron\0&quot;, 5) == 0 || strncmp(words[1], &quot;i\0&quot;, 2) == 0) { if (unlocked &lt; 3) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[3]) + (rand() &lt; RAND_MAX * (multipliers[3] - floorf(multipliers[3])))); resources[3] += collect_amount; printf(&quot;Collected %d iron&quot;, collect_amount); } else if (strncmp(words[1], &quot;copper\0&quot;, 7) == 0 || strncmp(words[1], &quot;cp\0&quot;, 3) == 0 || strncmp(words[1], &quot;cr\0&quot;, 3) == 0) { if (unlocked &lt; 4) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[4]) + (rand() &lt; RAND_MAX * (multipliers[4] - floorf(multipliers[4])))); resources[4] += collect_amount; printf(&quot;Collected %d copper&quot;, collect_amount); } else if (strncmp(words[1], &quot;silver\0&quot;, 7) == 0 || strncmp(words[1], &quot;si\0&quot;, 3) == 0 || strncmp(words[1], &quot;sv\0&quot;, 3) == 0) { if (unlocked &lt; 5) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[5]) + (rand() &lt; RAND_MAX * (multipliers[5] - floorf(multipliers[5])))); resources[5] += collect_amount; printf(&quot;Collected %d silver&quot;, collect_amount); } else if (strncmp(words[1], &quot;gold\0&quot;, 5) == 0 || strncmp(words[1], &quot;g\0&quot;, 2) == 0) { if (unlocked &lt; 6) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[6]) + (rand() &lt; RAND_MAX * (multipliers[6] - floorf(multipliers[6])))); resources[6] += collect_amount; printf(&quot;Collected %d gold&quot;, collect_amount); } else if (strncmp(words[1], &quot;diamond\0&quot;, 8) == 0 || strncmp(words[1], &quot;d\0&quot;, 2) == 0) { if (unlocked &lt; 7) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[7]) + (rand() &lt; RAND_MAX * (multipliers[7] - floorf(multipliers[7])))); resources[7] += collect_amount; printf(&quot;Collected %d diamond&quot;, collect_amount); } else if (strncmp(words[1], &quot;emerald\0&quot;, 8) == 0 || strncmp(words[1], &quot;e\0&quot;, 2) == 0 || strncmp(words[1], &quot;m\0&quot;, 2) == 0) { if (unlocked &lt; 8) { printf(&quot;ERR: You haven't unlocked this resource\n\n&quot;); continue; } collect_amount = (int16_t) (floorf(multipliers[8]) + (rand() &lt; RAND_MAX * (multipliers[8] - floorf(multipliers[8])))); resources[8] += collect_amount; printf(&quot;Collected %d emerald&quot;, collect_amount); } else { printf(&quot;ERR: Unknown resource\n\n&quot;); continue; } } else if (strncmp(words[0], &quot;trade\0&quot;, 6) == 0 || strncmp(words[0], &quot;tr\0&quot;, 3) == 0 || strncmp(words[0], &quot;t\0&quot;, 2) == 0) { if (words[1][0] == '\0' || words[2][0] != '\0') { printf(&quot;ERR: Expected one argument (trade id)\n\n&quot;); continue; } if (words[1][1] != '\0' || words[1][0] &lt; '1' || words[1][0] &gt; '5') { printf(&quot;ERR: Invalid trade id\n\n&quot;); continue; } int8_t trade = words[1][0] - 49; if (trades[trade].timer == -1) { printf(&quot;ERR: There is no trade with that id\n\n&quot;); continue; } else if (resources[trades[trade].sell_item] &lt; trades[trade].sell_amount) { printf(&quot;ERR: You can't afford that trade\n\n&quot;); continue; } else { resources[trades[trade].buy_item] += trades[trade].buy_amount; resources[trades[trade].sell_item] -= trades[trade].sell_amount; trades[trade].timer = fmax(trades[trade].timer - (int16_t) ((trades[trade].buy_amount / resources[trades[trade].buy_item]) * 4), -1); printf(&quot;Trade #1: %s (%d) -&gt; %s (%d)&quot;, names[trades[trade].sell_item], trades[trade].sell_amount, names[trades[trade].buy_item], trades[trade].buy_amount); } } else if (strncmp(words[0], &quot;deal\0&quot;, 5) == 0 || strncmp(words[0], &quot;d\0&quot;, 2) == 0) { if (words[1][0] == '\0' || words[2][0] != '\0') { printf(&quot;ERR: Expected one argument (deal id)\n\n&quot;); continue; } if (words[1][1] != '\0' || words[1][0] &lt; '1' || words[1][0] &gt; '3') { printf(&quot;ERR: Invalid deal id\n\n&quot;); continue; } int8_t deal = words[1][0] - 49; if (deals[deal].timer == -1) { printf(&quot;ERR: There is no deal with that id\n\n&quot;); continue; } else if (resources[deals[deal].sell_item] &lt; deals[deal].sell_amount) { printf(&quot;ERR: You can't afford that deal\n\n&quot;); continue; } else { resources[deals[deal].buy_item] += deals[deal].buy_amount; resources[deals[deal].sell_item] -= deals[deal].sell_amount; deals[deal].timer = -1; printf(&quot;Deal #1: %s (%d) -&gt; %s (%d)&quot;, names[deals[deal].sell_item], deals[deal].sell_amount, names[deals[deal].buy_item], deals[deal].buy_amount); } } else if (strncmp(words[0], &quot;unlock\0&quot;, 7) == 0 || strncmp(words[0], &quot;unl\0&quot;, 4) == 0 || strncmp(words[0], &quot;u\0&quot;, 2) == 0) { if (words[1][0] == '\0' || words[2][0] != '\0') { printf(&quot;ERR: Expected one argument (resource id)\n\n&quot;); continue; } if (strncmp(words[1], &quot;wood\0&quot;, 5) == 0 || strncmp(words[1], &quot;w\0&quot;, 2) == 0) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } else if (strncmp(words[1], &quot;stone\0&quot;, 6) == 0 || strncmp(words[1], &quot;s\0&quot;, 2) == 0) { if (unlocked &gt;= 1) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (resources[0] &lt; 200 || resources[2] &lt; 40) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[0] -= 200; resources[2] -= 40; unlocked++; printf(&quot;Unlocked stone&quot;); } else if (strncmp(words[1], &quot;coal\0&quot;, 5) == 0 || strncmp(words[1], &quot;c\0&quot;, 2) == 0) { if (unlocked &gt;= 2) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (unlocked &lt; 1) { printf(&quot;ERR: You cannot unlock this resource yet\n\n&quot;); continue; } if (resources[1] &lt; 400 || resources[2] &lt; 80) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[1] -= 400; resources[2] -= 80; unlocked++; printf(&quot;Unlocked coal&quot;); } else if (strncmp(words[1], &quot;iron\0&quot;, 5) == 0 || strncmp(words[1], &quot;i\0&quot;, 2) == 0) { if (unlocked &gt;= 3) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (unlocked &lt; 2) { printf(&quot;ERR: You cannot unlock this resource yet\n\n&quot;); continue; } if (resources[1] &lt; 200 || resources[3] &lt; 100) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[1] -= 200; resources[3] -= 100; unlocked++; printf(&quot;Unlocked iron&quot;); } else if (strncmp(words[1], &quot;copper\0&quot;, 7) == 0 || strncmp(words[1], &quot;cp\0&quot;, 3) == 0 || strncmp(words[1], &quot;cr\0&quot;, 3) == 0) { if (unlocked &gt;= 4) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (unlocked &lt; 3) { printf(&quot;ERR: You cannot unlock this resource yet\n\n&quot;); continue; } if (resources[3] &lt; 300 || resources[4] &lt; 50) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[3] -= 300; resources[4] -= 50; unlocked++; printf(&quot;Unlocked copper&quot;); } else if (strncmp(words[1], &quot;silver\0&quot;, 7) == 0 || strncmp(words[1], &quot;si\0&quot;, 3) == 0 || strncmp(words[1], &quot;sv\0&quot;, 3) == 0) { if (unlocked &gt;= 5) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (unlocked &lt; 4) { printf(&quot;ERR: You cannot unlock this resource yet\n\n&quot;); continue; } if (resources[1] &lt; 1000 || resources[3] &lt; 400) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[1] -= 1000; resources[3] -= 400; unlocked++; printf(&quot;Unlocked silver&quot;); } else if (strncmp(words[1], &quot;gold\0&quot;, 5) == 0 || strncmp(words[1], &quot;g\0&quot;, 2) == 0) { if (unlocked &gt;= 6) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (unlocked &lt; 5) { printf(&quot;ERR: You cannot unlock this resource yet\n\n&quot;); continue; } if (resources[4] &lt; 500 || resources[2] &lt; 300) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[4] -= 500; resources[2] -= 300; unlocked++; printf(&quot;Unlocked gold&quot;); } else if (strncmp(words[1], &quot;diamond\0&quot;, 8) == 0 || strncmp(words[1], &quot;d\0&quot;, 2) == 0) { if (unlocked &gt;= 7) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (unlocked &lt; 6) { printf(&quot;ERR: You cannot unlock this resource yet\n\n&quot;); continue; } if (resources[3] &lt; 1000 || resources[5] &lt; 400) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[3] -= 1000; resources[5] -= 400; unlocked++; printf(&quot;Unlocked diamond&quot;); } else if (strncmp(words[1], &quot;emerald\0&quot;, 8) == 0 || strncmp(words[1], &quot;e\0&quot;, 2) == 0 || strncmp(words[1], &quot;m\0&quot;, 2) == 0) { if (unlocked == 8) { printf(&quot;ERR: You have already unlocked this resource\n\n&quot;); continue; } if (unlocked &lt; 7) { printf(&quot;ERR: You cannot unlock this resource yet\n\n&quot;); continue; } if (resources[7] &lt; 200 || resources[5] &lt; 100) { printf(&quot;ERR: You cannot afford to unlock this resource\n\n&quot;); continue; } resources[7] -= 200; resources[5] -= 100; unlocked++; printf(&quot;Unlocked emerald&quot;); } else { printf(&quot;ERR: Unknown resource\n\n&quot;); continue; } upgrades[0].thread = -1; } else if (strncmp(words[0], &quot;multiplier\0&quot;, 11) == 0 || strncmp(words[0], &quot;multiply\0&quot;, 9) == 0 || strncmp(words[0], &quot;multi\0&quot;, 6) == 0 || strncmp(words[0], &quot;mul\0&quot;, 4) == 0 || strncmp(words[0], &quot;m\0&quot;, 2) == 0) { if (words[1][0] == '\0' || words[2][0] != '\0') { printf(&quot;ERR: Expected one argument (resource name)\n\n&quot;); continue; } int8_t resource; if (strncmp(words[1], &quot;wood\0&quot;, 5) == 0 || strncmp(words[1], &quot;w\0&quot;, 2) == 0) { resource = 0; } else if (strncmp(words[1], &quot;stone\0&quot;, 6) == 0 || strncmp(words[1], &quot;s\0&quot;, 2) == 0) { resource = 1; } else if (strncmp(words[1], &quot;coal\0&quot;, 5) == 0 || strncmp(words[1], &quot;c\0&quot;, 2) == 0) { resource = 2; } else if (strncmp(words[1], &quot;iron\0&quot;, 5) == 0 || strncmp(words[1], &quot;i\0&quot;, 2) == 0) { resource = 3; } else if (strncmp(words[1], &quot;copper\0&quot;, 7) == 0 || strncmp(words[1], &quot;cp\0&quot;, 3) == 0 || strncmp(words[1], &quot;cr\0&quot;, 3) == 0) { resource = 4; } else if (strncmp(words[1], &quot;silver\0&quot;, 7) == 0 || strncmp(words[1], &quot;si\0&quot;, 3) == 0 || strncmp(words[1], &quot;sv\0&quot;, 3) == 0) { resource = 5; } else if (strncmp(words[1], &quot;gold\0&quot;, 5) == 0 || strncmp(words[1], &quot;g\0&quot;, 2) == 0) { resource = 6; } else if (strncmp(words[1], &quot;diamond\0&quot;, 8) == 0 || strncmp(words[1], &quot;d\0&quot;, 2) == 0) { resource = 7; } else if (strncmp(words[1], &quot;emerald\0&quot;, 8) == 0 || strncmp(words[1], &quot;e\0&quot;, 2) == 0 || strncmp(words[1], &quot;m\0&quot;, 2) == 0) { resource = 8; } else { printf(&quot;ERR: Unknown resource\n\n&quot;); continue; } if (multipliers[resource] == 1.0) { if (resources[resource] &lt; 200 - 20 * resource) { printf(&quot;ERR: You cannot afford this upgrade\n\n&quot;); continue; } resources[resource] -= 200 - 20 * resource; multipliers[resource] = 1.1; } else if (multipliers[resource] == 1.1) { if (resources[resource] &lt; 500 - 50 * resource) { printf(&quot;ERR: You cannot afford this upgrade\n\n&quot;); continue; } resources[resource] -= 500 - 50 * resource; multipliers[resource] = 1.25; } else if (multipliers[resource] == 1.25) { if (resources[resource] &lt; 1500 - 150 * resource) { printf(&quot;ERR: You cannot afford this upgrade\n\n&quot;); continue; } resources[resource] -= 1500 - 150 * resource; multipliers[resource] = 1.75; } else if (multipliers[resource] == 1.75) { if (resources[resource] &lt; 4000 - 40 * resource) { printf(&quot;ERR: You cannot afford this upgrade\n\n&quot;); continue; } resources[resource] -= 4000 - 400 * resource; multipliers[resource] = 2.0; } else if (multipliers[resource] == 2.0) { if (resources[resource] &lt; 10000 - 1000 * resource) { printf(&quot;ERR: You cannot afford this upgrade\n\n&quot;); continue; } resources[resource] -= 10000 - 1000 * resource; multipliers[resource] = 5.0; } else if (multipliers[resource] == 5.0) { if (resources[resource] &lt; 20000 - 2000 * resource) { printf(&quot;ERR: You cannot afford this upgrade\n\n&quot;); continue; } resources[resource] -= 20000 - 2000 * resource; multipliers[resource] = 10.0; } else { printf(&quot;ERR: This resource is already at max multiplier\n\n&quot;); continue; } upgrades[1].thread = -1; } else if (strncmp(words[0], &quot;autocollect\0&quot;, 12) == 0 || strncmp(words[0], &quot;autocol\0&quot;, 8) == 0 || strncmp(words[0], &quot;auto\0&quot;, 5) == 0 || strncmp(words[0], &quot;a\0&quot;, 2) == 0) { if (words[1][0] == '\0' || words[2][0] != '\0') { printf(&quot;ERR: Expected one argument (resource)\n\n&quot;); continue; } int8_t level; if (strncmp(words[1], &quot;wood\0&quot;, 5) == 0 || strncmp(words[1], &quot;w\0&quot;, 2) == 0) { level = 1; } else if (strncmp(words[1], &quot;stone\0&quot;, 6) == 0 || strncmp(words[1], &quot;s\0&quot;, 2) == 0) { level = 2; } else if (strncmp(words[1], &quot;coal\0&quot;, 5) == 0 || strncmp(words[1], &quot;c\0&quot;, 2) == 0) { level = 3; } else if (strncmp(words[1], &quot;iron\0&quot;, 5) == 0 || strncmp(words[1], &quot;i\0&quot;, 2) == 0) { level = 4; } else if (strncmp(words[1], &quot;metal\0&quot;, 6) == 0 || strncmp(words[1], &quot;m\0&quot;, 2) == 0) { level = 5; } else { printf(&quot;ERR: Unknown or non-automatable resource\n\n&quot;); continue; } if (auto_level &gt; level) { printf(&quot;ERR: You have already automated this resource\n\n&quot;); continue; } if (auto_level &lt; level - 1) { printf(&quot;ERR: You cannot automate this resource yet\n\n&quot;); continue; } if (resources[level + 1] &lt; 200) { printf(&quot;ERR: You cannot afford to automate this resource\n\n&quot;); continue; } auto_level = level; resources[level + 1] -= 200; upgrades[2].thread = -1; } else if (strncmp(words[0], &quot;unlock-deal\0&quot;, 12) == 0 || strncmp(words[0], &quot;unlock_deal\0&quot;, 12) == 0 || strncmp(words[0], &quot;unl-d\0&quot;, 6) == 0 || strncmp(words[0], &quot;unl_d\0&quot;, 6) == 0 || strncmp(words[0], &quot;ud\0&quot;, 3) == 0 || strncmp(words[0], &quot;l\0&quot;, 2) == 0) { if (words[1][0] == '\0' || words[2][0] != '\0') { printf(&quot;ERR: Expected one argument (resource)\n\n&quot;); continue; } int8_t deal; if (strncmp(words[1], &quot;wood\0&quot;, 5) == 0 || strncmp(words[1], &quot;w\0&quot;, 2) == 0) { deal = 2; } else if (strncmp(words[1], &quot;stone\0&quot;, 6) == 0 || strncmp(words[1], &quot;s\0&quot;, 2) == 0) { deal = 2; } else if (strncmp(words[1], &quot;coal\0&quot;, 5) == 0 || strncmp(words[1], &quot;c\0&quot;, 2) == 0) { deal = 4; } else if (strncmp(words[1], &quot;iron\0&quot;, 5) == 0 || strncmp(words[1], &quot;i\0&quot;, 2) == 0) { deal = 4; } else if (strncmp(words[1], &quot;copper\0&quot;, 7) == 0 || strncmp(words[1], &quot;cp\0&quot;, 3) == 0 || strncmp(words[1], &quot;cr\0&quot;, 3) == 0) { deal = 6; } else if (strncmp(words[1], &quot;silver\0&quot;, 7) == 0 || strncmp(words[1], &quot;si\0&quot;, 3) == 0 || strncmp(words[1], &quot;sv\0&quot;, 3) == 0) { deal = 6; } else if (strncmp(words[1], &quot;gold\0&quot;, 5) == 0 || strncmp(words[1], &quot;g\0&quot;, 2) == 0) { deal = 8; } else if (strncmp(words[1], &quot;diamond\0&quot;, 8) == 0 || strncmp(words[1], &quot;d\0&quot;, 2) == 0) { deal = 8; } else { printf(&quot;ERR: Unknown resource\n\n&quot;); continue; } if (deal &lt; unlocked_deals) { printf(&quot;You have already unlocked these deals\n\n&quot;); continue; } if (unlocked_deals &lt; deal - 2) { printf(&quot;You cannot unlock these deals yet\n\n&quot;); continue; } if (resources[deal - 1] &lt; 2125 - (deal / 2) * 375) { printf(&quot;You cannot afford to unlock these deals\n\n&quot;); continue; } resources[deal - 1] -= 2125 - (deal / 2) * 375; unlocked_deals = deal; upgrades[2].thread = -1; } else { printf(&quot;ERR: Unknown command\n\n&quot;); continue; } strcpy(words_redo[0], words[0]); strcpy(words_redo[1], words[1]); strcpy(words_redo[2], words[2]); strcpy(words_redo[3], words[3]); printf(&quot;\n\n&quot;); if (auto_level == 1) { if (rand() &lt; (double) RAND_MAX * 0.1) { resources[0]++; } } else if (auto_level == 2) { if (rand() &lt; (double) RAND_MAX * 0.2) { resources[0]++; } if (rand() &lt; (double) RAND_MAX * 0.1) { resources[1]++; } } else if (auto_level == 3) { if (rand() &lt; (double) RAND_MAX * 0.35) { resources[0]++; } if (rand() &lt; (double) RAND_MAX * 0.2) { resources[1]++; } if (rand() &lt; (double) RAND_MAX * 0.1) { resources[2]++; } } else if (auto_level == 4) { if (rand() &lt; (double) RAND_MAX * 0.5) { resources[0]++; } if (rand() &lt; (double) RAND_MAX * 0.35) { resources[1]++; } if (rand() &lt; (double) RAND_MAX * 0.2) { resources[2]++; } if (rand() &lt; (double) RAND_MAX * 0.1) { resources[3]++; } } else if (auto_level == 5) { if (rand() &lt; (double) RAND_MAX * 0.75) { resources[0]++; } if (rand() &lt; (double) RAND_MAX * 0.5) { resources[1]++; } if (rand() &lt; (double) RAND_MAX * 0.35) { resources[2]++; } if (rand() &lt; (double) RAND_MAX * 0.2) { resources[3]++; } if (rand() &lt; (double) RAND_MAX * 0.1) { resources[4]++; } if (rand() &lt; (double) RAND_MAX * 0.05) { resources[5]++; } if (rand() &lt; (double) RAND_MAX * 0.01) { resources[6]++; } } if (trade_tick-- &lt; 0) { for (int8_t i = 0; i &lt; 5; i++) { if (trades[i].timer &gt;= 0) trades[i].timer--; } if (rand() &lt; RAND_MAX * 0.15) { int8_t trade = -1; for (int8_t i = 0; i &lt; 5; i++) { if (trades[i].timer == -1) { trade = i; break; } } if (trade != -1) { trades[trade].sell_item = (int8_t) ((rand() / (double) RAND_MAX) * (unlocked + 1)); trades[trade].sell_amount = (uint64_t) (resources[trades[trade].sell_item] * ((rand() / (double) RAND_MAX) + 0.25) + (uint64_t) (rand() / (double) RAND_MAX) * 40 * multipliers[trades[trade].sell_item]); do { trades[trade].buy_item = (int8_t) ((rand() / (double) RAND_MAX) * (fmin(unlocked, 8) + 1)); double random = rand() / (double) RAND_MAX; if (random &lt; 0.02 &amp;&amp; unlocked &lt;= 5) { trades[trade].buy_item += 3; } else if (random &lt; 0.2 &amp;&amp; unlocked &lt;= 6) { trades[trade].buy_item += 2; } else if (random &lt; 0.6 &amp;&amp; unlocked &lt;= 7) { trades[trade].buy_item += 1; } } while (trades[trade].buy_item == trades[trade].sell_item); trades[trade].buy_amount = (uint64_t) (((trades[trade].sell_amount * item_costs[trades[trade].sell_item]) * ((rand() / (double) RAND_MAX) * 0.6 + 0.75)) / item_costs[trades[trade].buy_item]); trades[trade].timer = (int16_t) ((rand() / (double) RAND_MAX) * 8 + 16); } } trade_tick = (int8_t) ((rand() / (double) RAND_MAX) * 5) + 4; } if (unlocked_deals != 0 &amp;&amp; deal_tick-- &lt; 0) { for (int8_t i = 0; i &lt; 3; i++) { if (deals[i].timer &gt;= 0) deals[i].timer--; } if (rand() &lt; RAND_MAX * 0.35) { int8_t deal = -1; for (int8_t i = 0; i &lt; 3; i++) { if (deals[i].timer == -1) { deal = i; break; } } if (deal != -1) { deals[deal].sell_item = (int8_t) ((rand() / (double) RAND_MAX) * unlocked_deals); deals[deal].sell_amount = (uint64_t) (resources[deals[deal].sell_item] * ((rand() / (double) RAND_MAX) * 0.5 + 0.1) + (rand() / (double) RAND_MAX) * 20 * multipliers[deals[deal].sell_item]); do { deals[deal].buy_item = (int8_t) ((rand() / (double) RAND_MAX) * unlocked_deals); } while (deals[deal].buy_item == deals[deal].sell_item); deals[deal].buy_amount = (uint64_t) (((deals[deal].sell_amount * item_costs[deals[deal].sell_item]) * ((rand() / (double) RAND_MAX) + 0.6)) / item_costs[deals[deal].buy_item]); deals[deal].timer = (int16_t) ((rand() / (double) RAND_MAX) * 3 + 8); } } deal_tick = (int8_t) ((rand() / (double) RAND_MAX) * 2) + 2; } if (upgrades[0].thread == -1) { if (unlocked == 0) { upgrades[0].thread = 0; upgrades[0].id = 0; } else if (unlocked == 1 &amp;&amp; resources[2]) { upgrades[0].thread = 0; upgrades[0].id = 1; } else if (unlocked == 2 &amp;&amp; resources[3]) { upgrades[0].thread = 0; upgrades[0].id = 2; } else if (unlocked == 3 &amp;&amp; resources[4]) { upgrades[0].thread = 0; upgrades[0].id = 3; } else if (unlocked == 4 &amp;&amp; resources[5]) { upgrades[0].thread = 0; upgrades[0].id = 4; } else if (unlocked == 5 &amp;&amp; resources[6]) { upgrades[0].thread = 0; upgrades[0].id = 5; } else if (unlocked == 6 &amp;&amp; resources[7]) { upgrades[0].thread = 0; upgrades[0].id = 6; } else if (unlocked == 7 &amp;&amp; resources[8]) { upgrades[0].thread = 0; upgrades[0].id = 7; } } if (upgrades[1].thread == -1) { for (int8_t i = 0; i &lt; 9; i++) { if (multipliers[i] == 5.0 &amp;&amp; resources[i] &gt; 2000) { upgrades[1].thread = 1; upgrades[1].id = i + 45; break; } } for (int8_t i = 0; i &lt; 9; i++) { if (multipliers[i] == 2.0 &amp;&amp; resources[i] &gt; 1000) { upgrades[1].thread = 1; upgrades[1].id = i + 36; break; } } for (int8_t i = 0; i &lt; 9; i++) { if (multipliers[i] == 1.75 &amp;&amp; resources[i] &gt; 400) { upgrades[1].thread = 1; upgrades[1].id = i + 27; break; } } for (int8_t i = 0; i &lt; 9; i++) { if (multipliers[i] == 1.25 &amp;&amp; resources[i] &gt; 150) { upgrades[1].thread = 1; upgrades[1].id = i + 18; break; } } for (int8_t i = 0; i &lt; 9; i++) { if (multipliers[i] == 1.1 &amp;&amp; resources[i] &gt; 50) { upgrades[1].thread = 1; upgrades[1].id = i + 9; break; } } for (int8_t i = 0; i &lt; 9; i++) { if (multipliers[i] == 1.0 &amp;&amp; resources[i] &gt; 20) { upgrades[1].thread = 1; upgrades[1].id = i; break; } } } if (upgrades[2].thread == -1) { if (auto_level == 0 &amp;&amp; unlocked &gt;= 1 &amp;&amp; resources[2]) { upgrades[2].thread = 2; upgrades[2].id = 0; } else if (auto_level == 1 &amp;&amp; unlocked &gt;= 2 &amp;&amp; resources[3]) { upgrades[2].thread = 2; upgrades[2].id = 1; } else if (auto_level == 2 &amp;&amp; unlocked &gt;= 3 &amp;&amp; resources[4]) { upgrades[2].thread = 2; upgrades[2].id = 2; } else if (auto_level == 3 &amp;&amp; unlocked &gt;= 4 &amp;&amp; resources[5]) { upgrades[2].thread = 2; upgrades[2].id = 3; } else if (auto_level == 4 &amp;&amp; unlocked &gt;= 6) { upgrades[2].thread = 2; upgrades[2].id = 4; } else if (unlocked_deals == 0 &amp;&amp; unlocked &gt;= 1) { upgrades[2].thread = 3; upgrades[2].id = 0; } else if (unlocked_deals == 2 &amp;&amp; unlocked &gt;= 3) { upgrades[2].thread = 3; upgrades[2].id = 1; } else if (unlocked_deals == 4 &amp;&amp; unlocked &gt;= 5) { upgrades[2].thread = 3; upgrades[2].id = 2; } else if (unlocked_deals == 6 &amp;&amp; unlocked &gt;= 7) { upgrades[2].thread = 3; upgrades[2].id = 3; } } turn_count++; } printf(&quot;\033[F\033[A Finished game after %d turn(s)\n\n&quot;, turn_count); return 0; } </code></pre> <p>(Compiled on my machine (Bash, Linux VM) with <code>gcc -g -lm -o merchant merchant.c</code>)</p> <p>Some things I was wondering about:</p> <ul> <li>Is there a way to get rid of all those <code>else if</code>s? Maybe a <code>switch</code> statement or <code>for</code> loop?</li> <li>Is there a better way to overwrite all of the program's previous output than just moving the cursor to overwrite it?</li> <li>Is my code readable?</li> </ul> <p>First post on code review, if there's something I forgot to include let me know!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T03:31:17.453", "Id": "496958", "Score": "0", "body": "(In case of any confusion `thread` in `upgrade` doesn't refer to threads in the computer sense, it's just the word I used for \"upgrade path/type\")" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T05:40:32.337", "Id": "496966", "Score": "1", "body": "Perfect first question, don't worry about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:16:39.577", "Id": "497301", "Score": "0", "body": "OT: running the posted code through a compiler results in LOTs of warnings. When compiling, always enable the warnings, then fix those warnings. ( for `gcc`, at a minimum use: `-Wall -Wextra -Wconversion -pedantic -std=gnu11` ) Note: other compilers use different options to produce the same results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:20:04.010", "Id": "497302", "Score": "0", "body": "OT: the posted code fails to prompt the user as to what the user should input at the `>>` prompt" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:53:13.750", "Id": "497337", "Score": "1", "body": "PS look up for the ncurses.h / curses.h header-file, it's a library for terminal \"GUI\" applications, very handy." } ]
[ { "body": "<p>You may use a <code>switch</code>, but be informed that using <code>break;</code> to break the loop would not work (Instead you would have to use a <code>goto</code> to break the loop.); same applies to a nested for-loop (With additional regards to <code>continue</code>, which would also have to be used in a <code>goto</code> way.), so <em>summa summarum</em>, using <code>if</code>, <code>else if</code>, <code>else</code> is the best way in your case.</p>\n<p>Moving the cursor is the way how to do in a terminal application, totally fine.</p>\n<p>Your code is readable, but I would suggest to outsource some code to functions, especially all this redundant checking.</p>\n<p>PS I would probably separate the input code from the output code. Meaning, I would write a function only for user inputs, one function for processing those inputs and another function for outputs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:10:32.820", "Id": "252300", "ParentId": "252279", "Score": "2" } }, { "body": "<blockquote>\n<p>Is there a way to get rid of all those else ifs? Maybe a switch statement or for loop?</p>\n</blockquote>\n<p>Certainly.</p>\n<p>With <code>if (strncmp(words[0], &quot;redo\\0&quot;, ....</code> consider a table of pairs of string and function.</p>\n<pre><code>// Something like \nfor (i=0; i&lt;table_size; i++) {\n if (my_compare(words[0], table[i].s)) {\n table[i].f(state_data, words, ....); // do whatever per helper function\n break;\n }\n}\nif (i == table_size) my_handle_no_match();\n</code></pre>\n<p>With <code>shorten_number()</code>:</p>\n<p>To get a correct answer is tricky mixing 64-bit integer math with <code>double</code>.</p>\n<p>Example: (Note original code provides errant results with large values and near 999.995+*10^3x)</p>\n<pre><code>// Reduce to &quot;1.00x&quot; to &quot;999.99x&quot;\nvoid shorten_number(char *dest, uint64_t number) {\n if (number &lt; 1000) {\n sprintf(dest, &quot;%d&quot;, (int) number);\n return;\n }\n static const char suffix[] = &quot; KMBTqQ&quot;; // or maybe metric &quot; kMGTPEZY&quot;\n int suffix_index = 0;\n double scale = 1.0;\n\n while (number/scale &gt;= 999.995) {\n scale *= 1000.0;\n suffix_index++;\n }\n sprintf(dest, &quot;%.2f%c&quot;, number / scale, suffix[suffix_index]);\n}\n</code></pre>\n<hr />\n<blockquote>\n<p>Is there a better way to overwrite all of the program's previous output than just moving the cursor to overwrite it?</p>\n</blockquote>\n<p>C has no standard way to overwrite previous output. Any solution is specific to the terminal type.</p>\n<p>Rather than <code>printf(&quot;\\033[F\\033[A\\033[A ...</code>, consider making a helper function <code>erase_line()</code> that does the same, but with this abstraction allows to more easily identify and maintain implementation specific code.</p>\n<p>Same applies for any place an ANSI escape sequence is used - abstract it.</p>\n<hr />\n<blockquote>\n<p>Is my code readable?</p>\n</blockquote>\n<p>Mostly yes.</p>\n<p>I find the 4 space indent excessive over 2, yet such style issues are best decided by your group's style guide.</p>\n<p><code>main()</code> is <em>long</em>. Perhaps break it up.</p>\n<p>Too many naked <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>.</p>\n<hr />\n<p><strong>Zero data cleanly</strong></p>\n<p>Rather than potentially miscalculated code</p>\n<pre><code>// memset(trade_list, '\\0', sizeof(trade_list[0][0]) * 240);\nmemset(trade_list, 0, sizeof trade_list);\n</code></pre>\n<p>or initialize with zero</p>\n<pre><code>// char trade_list[5][48];\nchar trade_list[5][48] = { 0 };\n</code></pre>\n<p><strong>Wrong format</strong></p>\n<pre><code>uint64_t number\n// at this point number &lt; 1000, but still type uint64_t\n// sprintf(dest, &quot;%d&quot;, number);\nsprintf(dest, &quot;%d&quot;, (int) number);\n// or \nsprintf(dest, &quot;%&quot; PRIu64, number);\n</code></pre>\n<p>This hints at a serious weakness in OP's efforts: not fully enabling all warnings as a good well enabled compiler will warn about this. This is the <strong>most important feedback</strong>: enable all warnings and let your compiler give your rapid feedback.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:36:58.203", "Id": "252308", "ParentId": "252279", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T03:27:31.213", "Id": "252279", "Score": "4", "Tags": [ "c", "game" ], "Title": "A simple terminal-based trading game in C" }
252279
<p>First and foremost I want to say that I'm fully aware GOTO should normally be avoided in production code and it tends to be unreadable for others. For this specific case however, the code will not be read by anyone but me and the question is being asked mostly so I can understand what other options do I even have available since I lack experience with C++.</p> <p>What the following code snippet does is it picks the best object from a queue based on a set amount of parameters. The parameters have different importance and the importance is reflected in the if statement nesting - the most important parameters and conditions are on the outside. The subsequent parameters are only used as tiebrakers in case the more important parameters match.</p> <p>I also have not been able to find anything regarding this type of use for goto:</p> <pre><code>void class_method() { std::queue&lt;int&gt; my_queue; // generation of many objects happens here // Now I want to find the best element and I store the values for decider parameters // storing the object itself would be very inefficient as I care only about some key values int best_element_id = 0; int best_parameter_a = 0; int best_parameter_b = 0; // ... int best_parameter_z = 0; while (!my_queue.empty()) { if (my_queue.front().a_getter() &gt; best_parameter_a) { // Found new best element since parameter A is most important int best_element_id = my_queue.front().id_getter(); int best_parameter_a = my_queue.front().a_getter(); int best_parameter_b = my_queue.front().b_getter(); // ... int best_parameter_z = my_queue.front().z_getter(); } else if (my_queue.front().a_getter() == best_parameter_a) { if (my_queue.front().b_getter() &gt; best_parameter_b) { // Found new best element since parameter B is second most important int best_element_id = my_queue.front().id_getter(); int best_parameter_a = my_queue.front().a_getter(); int best_parameter_b = my_queue.front().b_getter(); // ... int best_parameter_z = my_queue.front().z_getter(); } else if (my_queue.front().a_getter() == best_parameter_a) { // ... // Many more checks // ... // Till last parameter is checked if (my_queue.front().z_getter() &gt; best_parameter_z) { int best_element_id = my_queue.front().id_getter(); int best_parameter_a = my_queue.front().a_getter(); int best_parameter_b = my_queue.front().b_getter(); // ... int best_parameter_z = my_queue.front().z_getter(); } } } my_queue.pop(); } }; </code></pre> <p>The conditions are obviously oversimplified and there are actually less than 26 parameters, I'm using a-z just to generalize the problem.</p> <p>Now I was obviously very displeased with this code and attempted to come up with some way to have the lines that update the parameters in one place. This is what I came up with:</p> <pre><code>void class_method() { std::queue&lt;int&gt; my_queue; // generation of many objects happens here // Now I want to find the best element and I store the values for deciding parameters // storing the object itself would be very inefficient as I care only about some key values int best_element_id = 0; int best_parameter_a = 0; int best_parameter_b = 0; // ... int best_parameter_z = 0; while (!my_queue.empty()) { if (my_queue.front().a_getter() &gt; best_parameter_a) { // Found new best element since parameter A is most important goto new_best; } else if (my_queue.front().a_getter() == best_parameter_a) { if (my_queue.front().b_getter() &gt; best_parameter_b) { // Found new best element since parameter B is second most important goto new_best; } else if (my_queue.front().a_getter() == best_parameter_a) { // ... // Many more checks // ... // Till last parameter is checked if (my_queue.front().z_getter() &gt; best_parameter_z) { goto new_best; } } } if (false) { new_best: int best_element_id = my_queue.front().id_getter(); int best_parameter_a = my_queue.front().a_getter(); int best_parameter_b = my_queue.front().b_getter(); // ... int best_parameter_z = my_queue.front().z_getter(); } my_queue.pop(); } }; </code></pre> <p>What other options do I have?</p> <p>Would such usecase be considered okay? If it is, maybe there is a more elegant way to write that without the <code>if (false)</code> condition? I'm also aware that I couldve used the GOTO to jump back to the first condition evaluating to True but I'm not a big fan of jumping backwards in code so I assumed putting the condition <code>if (false)</code> at the end makes this <em>somewhat</em> more readable...</p> <p>Last but not least, my IDE throws warnings because of the <code>if (false)</code> line, but I'm assuming the compiler will not optimize it away, right?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:08:19.257", "Id": "496968", "Score": "1", "body": "you missed something important, what does your code do? Currently, it looks very hypothetical" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:15:37.607", "Id": "496969", "Score": "0", "body": "Yes, the \"best object picking\" part from the whole method is just a small part, but seemingly the ugliest one. A complete conditional mess and a lot of code copying. Therefore I'm wondering if this part specifically could be rewritten in a more efficient or simply a more elegant way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:18:30.353", "Id": "496970", "Score": "0", "body": "I get it, but you should explain properly as to what your code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:26:52.587", "Id": "496971", "Score": "1", "body": "The thing is, Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. all the `...` in your question indicate that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:30:52.923", "Id": "496972", "Score": "0", "body": "I have edited the question to explain what this specific snipped of code does. The `...` in my code are there to avoid making my code example having 300 Lines of code or other lines of code that are in no way relevant to my question which is specifically about GOTO usage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:36:41.100", "Id": "496974", "Score": "0", "body": "Ok so I went through all of the uses of `//...` and I found only two different implications by that comment - either it's to show that there are more parameters that could be represented by letters from a to z or more nested if loops that follow the same logic as the previous ones? I don't feel like I left anything important out or anything of relevance to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:41:37.317", "Id": "496975", "Score": "2", "body": "The question is still very unclear, no idea what to code does, where the function belongs, whether it is a part of a class. Nothing at all :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:48:03.930", "Id": "496977", "Score": "0", "body": "What the snippet does has been already added to the question to increase clarity. What class it belongs to and what happens after the best object has been picked is in no way or form relevant to my question whether it's an acceptables use of GOTO? I'm sorry but I don't see how knowing what class it's from would change your answer whether jumping to an `if (false)` block is an okay practice or not? I could obviously add all of that information to the post but I left it out intentionally to begin with because I don't see how it could influence an answer to any of my questions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:57:55.550", "Id": "496979", "Score": "0", "body": "Yes, that's where the problem is :), I suggest you don't take my word on it and read [ask]. Only providing a \" snippet \" is not enough context for a proper review of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:02:02.367", "Id": "496982", "Score": "2", "body": "Also read [this](https://codereview.meta.stackexchange.com/questions/3649/my-question-was-closed-as-being-off-topic-what-are-my-options/3652#3652)\" If your question contains stub code, then there are significant pieces of the core functionality missing, and we need you to fill in the details. Excerpts of large projects are fine, but if you have omitted too much, then reviewers are left imagining how your program works. \"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:43:41.797", "Id": "496985", "Score": "3", "body": "As hypothetical code, this does look off topic. Are you aware of `std::priority_queue`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:59:09.907", "Id": "496987", "Score": "0", "body": "No, I was not aware of it, now that I'm reading about it, it looks like a very good alternative to the messy code that I have" } ]
[ { "body": "<p>In my personal opinion, using GOTO is totally acceptable. But regarding your example, your code looks not very optimized in the first place.</p>\n<p>Nevertheless, some tips for you when using GOTO.</p>\n<p>You should use labels in the most possible upper scope (if possible, function scope). Labels should be written in capital letters. You should never jump over any declaration of any kind. Write a label at the same column like the function scope brackets, to enhance readability. Don't use arbitrary constructs like <code>if(false)</code>, if you are using GOTO anyway, you might as well use it also in its full glory.</p>\n<p>For example:</p>\n<pre><code>while (!my_queue.empty()) {\n int best_element_id;\n int best_parameter_a;\n int best_parameter_b;\n // ...\n int best_parameter_z;\n \n if (my_queue.front().a_getter() &gt; best_parameter_a) {\n // Found new best element since parameter A is most important\n goto NEW_BEST;\n }\n else if (my_queue.front().a_getter() == best_parameter_a) {\n if (my_queue.front().b_getter() &gt; best_parameter_b) {\n // Found new best element since parameter B is second most important\n goto NEW_BEST;\n }\n else if (my_queue.front().a_getter() == best_parameter_a) {\n // ...\n // Many more checks\n // ...\n\n // Till last parameter is checked\n if (my_queue.front().z_getter() &gt; best_parameter_z) {\n goto NEW_BEST;\n }\n }\n }\n goto NO_NEW_BEST;\n \nNEW_BEST:\n best_element_id = my_queue.front().id_getter();\n best_parameter_a = my_queue.front().a_getter();\n best_parameter_b = my_queue.front().b_getter();\n // ...\n best_parameter_z = my_queue.front().z_getter();\n \nNO_NEW_BEST:\n my_queue.pop();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:00:14.030", "Id": "497011", "Score": "0", "body": "Ah, I knew there had to be a cleaner way instead of using `if (false)\"... Aside from the code not being optimized in the first place, your code does look a lot more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:19:56.297", "Id": "497013", "Score": "0", "body": "By the way, to ensure my statement, _\"You should use labels in the most possible upper scope (if possible, function scope).\"_, I would write the while-loop as a GOTO-loop. Because using a GOTO-statement within a while-loop hurts a structured text while-loop ^^. What you are actually looking for is an interleaving loop (An interleaving loop consists out of 2 or more loops, looping into each other.), a tool which structured texts doesn't provides, the only way is a GOTO. GOTO is even the most precise way to accomplish this task, any other method is just a work around." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T09:39:49.327", "Id": "252298", "ParentId": "252283", "Score": "1" } }, { "body": "<blockquote>\n<p>GOTO should normally be avoided in production code and it tends to be unreadable for others</p>\n</blockquote>\n<p>Readability isn’t just “for others”, it’s <em>for you</em>, as well.</p>\n<p>That said, if a <code>goto</code> makes code more easily readable, go for it. It’s just that these situations are exceedingly rare in C++. And your code isn’t one of them. In fact, your <code>goto</code> solution, where the label is nested in an <code>if (false)</code>, is primarily <em>cryptic</em>.</p>\n<p>As it stands, the control flow in your code is obfuscated. This isn’t just due to the <code>goto</code>, but the <code>goto</code> certainly doesn’t help (and in fact obfuscating control flow is precisely the quality that makes <code>goto</code> so controversial).</p>\n<p>Your code also contains errors, which are hard to spot. For instance, you test <code>my_queue.front().a_getter() == best_parameter_a</code> <em>twice</em>. The second time is almost certainly intended to test <code>b_getter() == best_parameter_b</code>. Such errors get more likely with complex, deeply nested code flow.</p>\n<p>It’s hard to give concrete recommendations without concrete code. Fundamentally, the purpose of your <code>goto</code> seems to be to skip a loop iteration when some conditions are not met. You’d usually use <code>continue</code> for this. Except, ah, you have that extra unconditional <code>queue.pop()</code> at the very end.</p>\n<p>One straightforward solution is to replace <code>if (false)</code> with <code>if (update)</code>, and replace the <code>goto</code>s with <code>update = true;</code>. That makes the intent immediately more explicit, and thus the code more readable.</p>\n<p>But I would be tempted to rewrite the logic completely, and in such a way that we can use <code>continue</code> inside a <code>for</code> loop here. The rewrite isn’t straightforward, since it requires not only inverting all your conditions inside the loop, but also restructuring the <em>flow</em> of the conditional statements.</p>\n<pre><code>for (; not my_queue.empty(); my_queue.pop()) {\n if (my_queue.front().a_getter() &lt; best_parameter_a) {\n continue;\n }\n if (my_queue.front().a_getter() == best_parameter_a) {\n if (my_queue.front().b_getter() &lt; best_parameter_b) {\n continue;\n }\n if (my_queue.front().a_getter() == best_parameter_a) {\n // ...\n // Many more checks\n // ...\n\n // Till last parameter is checked\n if (my_queue.front().z_getter() &lt;= best_parameter_z) {\n continue;\n }\n }\n }\n \n int best_element_id = my_queue.front().id_getter();\n int best_parameter_a = my_queue.front().a_getter();\n int best_parameter_b = my_queue.front().b_getter();\n // ...\n int best_parameter_z = my_queue.front().z_getter();\n}\n</code></pre>\n<p>But this is still deeply nested and, as mentioned, that makes it unreadable and error-prone. The fact that you’re testing a large number of hard-coded parameters is a rancid code smell. When squinting, the whole code looks like it’s trying to establish a lexicographical between two vectors of parameters. So your code should really <em>express that</em>, using appropriate data structures and operator overloading:</p>\n<pre><code>while (not my_queue.empty()) {\n if (best_parameter &lt; my_queue.front()) {\n best_parameter = my_queue.front();\n }\n my_queue.pop();\n}\n</code></pre>\n<p>There.</p>\n<p>This code isn’t (just) superior because it doesn’t require <code>goto</code>. It’s superior because it’s 90% shorter, has no deep nesting, and <em>directly expresses the intent</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:54:11.397", "Id": "497010", "Score": "0", "body": "Ah, very insightful, the fact that I wrote `my_queue.front().a_getter() == best_parameter_a` twice was indeed an error. The for loop solution is very neat, I did not consider using for loops like that. The solution with appropriate data structures and operator overloading definetly beats everything else on readability though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:41:17.110", "Id": "252302", "ParentId": "252283", "Score": "4" } } ]
{ "AcceptedAnswerId": "252302", "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T05:40:13.793", "Id": "252283", "Score": "-1", "Tags": [ "c++" ], "Title": "A case for GOTO" }
252283
<p>I'm making a command line interface (CLI) role playing tool that tracks the state of the world, storing characters, monsters, etc as text files so their data can be edited directly if needed (free Vim UI yay). This means that every game loop, I need to reload the files.</p> <p>Note: Direct editing implies no pickling. Also, I may eventually add functions to these files so I can use duck typing.</p> <p>Since filenames are pulled into Python as strings, I felt a straightforward approach would be to use <code>exec</code>. I'm concerned though because learning materials rarely discuss using this function responsibly. Instead they warn against its use for security reasons. Below is the directory, two test character files with simple data, and the main program.</p> <pre><code># Directory dnd\ main.py entities\ char01.py char02.py </code></pre> <pre><code># File: char01.py name = 'Gandalf Potter' </code></pre> <pre><code># File: char02.py name = 'Obi-wan Picard' </code></pre> <p>My solution:</p> <ol> <li>For this MWE, first check whether the files are loaded. For the first loop, they won't be loaded yet. By the second loop, the files should load and the loop will exit to avoid infinity.</li> <li>Read filenames from directory.</li> <li>Check if filename is in <code>globals()</code>.</li> <li>Depending on the check, either import or reload the module with <code>exec</code>.</li> </ol> <pre><code># File: main.py import importlib import os def main(): while True: if test_load(): return # Run until files load files = get_files('entities') load_files(files, 'entities') def get_files(dir): return (file for file in os.listdir(dir) if not file.startswith('__')) # Ignore __pycache__ def load_files(files, dir): for f in files: module = f.strip('.py') if module in globals(): exec(f'importlib.reload({module})') else: exec(f'from {dir} import {module}') modules = {k: v for k, v in locals().items() if isinstance(v, type(os))} globals().update(modules) def test_load(): try: char01.name char02.name print('loaded') return True except NameError: print('not loaded') return False main() </code></pre> <p>Questions:</p> <ol> <li><p>Is there a better approach?</p> </li> <li><p>Using <code>exec</code> is frowned upon for security reasons, however I want to start using it more often because code can be treated as strings, which allows the code to be treated as data that can be manipulated, substituted, or changed. However, I also want to be mindful of vulnerabilities.</p> </li> <li><p>Is there a better way of pulling out only the modules than using <code>if isinstance(v, type(os))</code>?</p> </li> <li><p>What is everyone's opinion of using the <code>globals()</code> function like this to do imports programmatically from within functions?</p> </li> <li><p>I used <code>DICT.update()</code> to add imports to <code>globals()</code>, however I wanted to be fancy and use Python39's new dictionary union operator <code>|=</code>. Unfortunately, lines like</p> </li> </ol> <pre><code>globals() |= {k: v for k, v in locals().items() if isinstance(v, type(os))} </code></pre> <p>don't work because a function call like <code>globals()</code> can't be assigned to. It would work if I did the following:</p> <pre><code>globals_ = globals() globals |= {k: v for k, v in locals().items() if isinstance(v, type(os))} </code></pre> <p>but at that point, it'd be simpler to just stick with <code>DICT.update()</code>.</p> <ol start="6"> <li>I welcome any other suggestions and criticisms.</li> </ol>
[]
[ { "body": "<h2>Looping</h2>\n<pre><code>while True:\n if test_load(): return # Run until files load\n</code></pre>\n<p>should simply be</p>\n<pre><code>while not test_load():\n # ...\n</code></pre>\n<h2>Getting files</h2>\n<p>It's good that you're using a generator, but you should consider basing it off of <code>pathlib</code> instead of <code>os</code>. Also, it seems like you should care less whether your file starts with underscores, and more that it's a file instead of a directory. For instance:</p>\n<pre><code>return (\n file\n for file in Path(dir).iterdir()\n if file.is_file()\n)\n</code></pre>\n<h2>Dynamic loading</h2>\n<p>You're not just loading any files - you're loading arbitrary Python modules. Since your examples only show variables being initialized, I'm going to go out on a limb and say: please, please don't load Python code when you should simply be loading data, from any of the common formats - a pickle, or JSON, or CSV, or what-have-you. It's easier, faster, more secure and generally less of a headache.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T06:33:56.037", "Id": "497142", "Score": "0", "body": "I converted everything to use pathlib. What a nice library. Could you explain why using data-only formats is easier? I will likely include functions in these files in the future (it hadn't occured to me to mention this unfortunately; I'll add that info to my post). This brings up a possible big misunderstanding I have about Python: modules seem to work as lot low boilerplate classes/singletons. I often treat my python files as objects to store data and functions: `mymodule.function(x)` or `mymodule.data`. I mean, that's what they are, right---objects that store data, functions, and procedures." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:51:57.217", "Id": "497193", "Score": "1", "body": "_why using data-only formats is easier?_ Fewer things can go wrong; surface area is reduced. Data as input permits fewer wrong things to happen than code as input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:53:05.943", "Id": "497194", "Score": "1", "body": "What kind of functions would be in these files; what would they do? If at all possible, think about what these functions would be doing, and attempt to reduce them to application functions that are already in your own code, with _parameters_ that are in a data-only file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:47:52.753", "Id": "497219", "Score": "0", "body": "I certainly could separate the data out from any functions. I'll look into JSON versus CSV for the project." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T21:04:29.040", "Id": "252340", "ParentId": "252285", "Score": "4" } } ]
{ "AcceptedAnswerId": "252340", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:23:33.020", "Id": "252285", "Score": "5", "Tags": [ "python-3.x" ], "Title": "Programmatically using `exec` to load files" }
252285
<p>I have been practising Python Practice questions and came across this question:</p> <blockquote> <p>Write a Python program to add 'ing' at the end of a given string (length should be at least 3).</p> <p>If the given string already ends with 'ing' then add 'ly' instead.</p> <p>If the string length of the given string is less than 3, leave it unchanged. Sample String : 'abc'</p> <p>Expected Result : 'abcing'</p> <p>Sample String : 'string'</p> <p>Expected Result : 'stringly'</p> </blockquote> <p>Here's my code:</p> <pre><code>string = input() if len(string) &lt; 3: print(string) elif string[-3:] == 'ing': print(string + 'ly') else: print(string + 'ing') </code></pre> <p>However, something about this code seems wrong: though it works, fine I feel it smells bad. I can't pinpoint why.</p>
[]
[ { "body": "<p>I think the code looks fine, except you could use the library function to check it ends-with &quot;ing&quot;:</p>\n<pre><code>string = input()\nif len(string) &lt; 3:\n print(string)\nelif string.endswith('ing'):\n print(string + 'ly')\nelse:\n print(string + 'ing')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:59:59.173", "Id": "252288", "ParentId": "252287", "Score": "5" } }, { "body": "<p>There's not many other ways to do it.</p>\n<p>You could replace the <code>if-elif-else</code> statement with an <code>if-elif-else</code> expression. Is that more readable or less?</p>\n<p>You could use the <code>if</code> statements to pick the appropriate suffix and have just on <code>print</code> at the end.</p>\n<p>In the <code>print</code> statement, you could use an f-string instead of string concatenation</p>\n<pre><code>string = input()\nsuffix = '' if len(string) &lt; 3 else 'ly' if string.endswith('ing') else 'ing'\nprint(f&quot;{string}{suffix}&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T20:50:23.733", "Id": "497095", "Score": "2", "body": "I find this `if-elif-else` expression too long to grok easily. @Heap Overflow's answer, using an `if len>=3` statement controlling a `string += if-else expression`, looks like a good balance to me. And has separation of logic from I/O." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:07:23.597", "Id": "497107", "Score": "1", "body": "@PeterCordes, I agree. As I implied in my answer the `if` expression might not be as readable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T08:08:10.400", "Id": "252292", "ParentId": "252287", "Score": "3" } }, { "body": "<p>The only thing somewhat bothering me is the short indentation :-P (standard is four spaces)</p>\n<p>And <code>endswith</code> is better in general as it avoids the cost of the slice copy, doesn't require stating the length, and also works for empty test-suffixes:</p>\n<pre><code>&gt;&gt;&gt; for s in 'o', 'a', '':\n print('foo'.endswith(s),\n 'foo'[-len(s):] == s)\n\nTrue True\nFalse False\nTrue False &lt;= Note the difference!\n</code></pre>\n<p>Here's how I might do it:</p>\n<pre><code>string = input()\nif len(string) &gt;= 3:\n string += 'ly' if string.endswith('ing') else 'ing'\nprint(string)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:42:28.800", "Id": "497061", "Score": "0", "body": "My small quibble with this would be that you're overwriting the original `string`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:43:26.043", "Id": "497062", "Score": "2", "body": "@Ben Yes, as instructed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:45:40.897", "Id": "497063", "Score": "0", "body": "Very true; the whole printing thing is throwing me off. I'll leave my original comment there as your response is valuable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:25:58.587", "Id": "497077", "Score": "0", "body": "I also just noticed that we need to make changes in the string itself thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:36:03.533", "Id": "497079", "Score": "0", "body": "@FoundABetterName Well, we can't really change the string itself, as it's immutable. I'd say closest thing we can do is change the variable (which is what I do). And of course if you really just input and print, it doesn't really matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T19:03:54.163", "Id": "497090", "Score": "0", "body": "got it thanks @HeapOverflow" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:05:25.647", "Id": "252306", "ParentId": "252287", "Score": "10" } }, { "body": "<h2>1. Python strings have an <a href=\"https://docs.python.org/3/library/stdtypes.html#str.endswith\" rel=\"noreferrer\"><code>.endswith()</code></a> method. Use it.</h2>\n<p>While <code>string[-3:] == 'ing'</code> isn't particular hard to read, <code>string.endswith('ing')</code> is even clearer.</p>\n<p>Potentially, depending on how it's implemented, <code>.endswith()</code> could even be slightly more efficient, since it doesn't have to copy the last three characters of the string. However, <a href=\"//softwareengineering.stackexchange.com/q/80084\">always keep Knuth's maxim in mind</a>. The entire operation of testing whether a string ends with &quot;ing&quot; is so trivial that any performance difference between different ways of doing it will surely be negligible compared to e.g. the time consumed by reading and printing the string. Thus, given two ways to do it, you should choose the most readable and idiomatic way even if it wasn't the most efficient.</p>\n<h2>2. Separate I/O from computation.</h2>\n<p>It's common for beginning programmers to litter their code with <code>input()</code> and <code>print()</code> calls in the middle of program logic, simply because those are the only ways of receiving and returning data they're familiar with. But in practice, that's almost always a mistake.(*)</p>\n<p>Your main task is to modify a string. Reading the string from standard input and printing the result to standard output are merely auxiliary tasks to that (and may or may not even be strictly necessary, unless the exercise explicitly specifies that particular method of input and output). You shouldn't unnecessarily intermix those auxiliary tasks into your solution for the main task.</p>\n<p>The simplest way to do that would be to just pull the <code>print()</code> calls out of the program logic, e.g. like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>string = input()\n\nif string.endswith('ing'):\n string += 'ly'\nelif len(string) &gt;= 3:\n string += 'ing'\n\nprint(string)\n</code></pre>\n<p>This is OK if you expect to only ever use this code for processing data read from one file (or pipe) and written to another. You're still doing the input, processing and output in one linear program, but at least the processing logic is now grouped together in a single block of code that you can extract from the script if you want to reuse it, and the I/O code is clearly separated from it, making it easy to change to another I/O method later if you need to.</p>\n<p>Alternatively, you could go a step further and wrap the program logic in a function that takes the input string as a parameter and returns the output. And, while you're at it, you can use the <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"noreferrer\"><code>if __name__ == '__main__'</code> idiom</a> to <a href=\"//stackoverflow.com/q/419163\">make your I/O code only run when your script is invoked directly</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def inglify(string):\n if len(string) &lt; 3:\n return string\n elif string.endswith('ing'):\n return string + 'ly'\n else:\n return string + 'ing'\n\nif __name__ == '__main__':\n string = input()\n print(inglify(string))\n</code></pre>\n<p>The advantage is that now your script file is also usable as a <a href=\"https://docs.python.org/3/tutorial/modules.html\" rel=\"noreferrer\">module</a> that you can <a href=\"https://docs.python.org/3/reference/simple_stmts.html#import\" rel=\"noreferrer\"><code>import</code></a> into another script to gain access to any functions defined in it <em>without</em> executing the I/O part of the code.</p>\n<hr />\n<p>*) So, when <em>is</em> it appropriate to include <code>print()</code> calls directly in your code, then? Off the top of my head, I can think of three or four cases (with some partial overlap between them):</p>\n<ol>\n<li><p>When I/O <em>is</em> the main purpose of your code, with everything not directly relevant to this purpose already split off into reusable functions. For example, <code>print(inglify(input()))</code> really does nothing but read data, call a function and print the result. Obviously, using <code>print()</code> there is not only appropriate but necessary.</p>\n</li>\n<li><p>When your code is interactive, i.e. when it prints something to the console, expects the user to reply, then prints something in response, etc. The <a href=\"https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop\" rel=\"noreferrer\">REPL</a> that you can start by running <code>python</code> with no script file argument is one example of such a program. In this case the input and output are intrinsically part of your program logic and cannot be easily separated from it. That said, you should still try to keep such interactive loops as simple as possible, and split off any parts of your code that <em>don't</em> directly involve interactive I/O into reusable functions or modules.</p>\n</li>\n<li><p>When you're doing <a href=\"https://softwareengineering.stackexchange.com/questions/225243/is-printing-to-console-stdout-a-good-debugging-strategy\">debug printing</a>, i.e. when what you're printing isn't the actual intended output of your program, but merely some metadata to help in tracing its execution. This can sometimes be a very useful ways to find out what your code is actually doing, and it's the one case where putting <code>print()</code> or other I/O calls even deep inside your program logic can be acceptable. Of course, if you're leaving such debug logging in your finished code, you should probably only enable it if requested by the user. (For example, many command-line tools will accept a <code>--verbose</code> or <code>--debug</code> switch to turn on such extra output.) Often it's best to use an actual logging framework designed for this purpose.</p>\n</li>\n</ol>\n<p>I would also personally include an exception for &quot;simple data processing&quot; scripts that involve nothing more than reading in some data, processing it and printing it out, much like the first rewritten version of your code that I suggested above.</p>\n<p>Such scripts are characterized by the fact that they only perform a single task, that this task involves reading, processing and writing data, and that their control flow is simple and mostly linear. That is, such a script might consist of a loop that reads the input, another loop or two to process it, and then a loop to print out the results. Sometimes it might even have a loop that e.g. reads a line of input, processes it, and prints out the result before reading the next line, etc. But what it definitely <em>shouldn't</em> have is print (or, worse yet, input) calls buried deep within conditional code, or in functions whose main purpose isn't obviously to perform I/O.</p>\n<p>While such scripts <em>can</em> be refactored to separate the I/O code from the rest of the data processing, often that can actually make the code harder to read, since it breaks up the simple step-by-step program flow into a more complex sequence of function calls. Basically, if your code is naturally structured like a cooking recipe, with nothing but simple sequential steps, it's sometimes better to just keep it like that and not complicate it by needless refactoring.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T18:58:52.900", "Id": "497089", "Score": "2", "body": "This is incredibly well written and explanatory thank you:)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:21:03.373", "Id": "497187", "Score": "1", "body": "I would argue that while modularization and reusability is generally important, forcing those principles onto a 7 LOC script is over-engineering. The advice about .endswith() is definitely valid though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:27:29.790", "Id": "497188", "Score": "5", "body": "@kangalioo: The point of exercises like this is to develop coding skills that can be applied to actual real-world tasks. Arguably, following good coding style for such exercises is *more* important than it usually would be. Normally, \"this is throw-away prototype code, I'm never going to reuse it\" can be a valid argument for cutting corners. When training your programming skills, however, you should always write the code as if you were going to reuse and extend it later, even if you know you really won't." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T18:00:56.427", "Id": "252331", "ParentId": "252287", "Score": "30" } } ]
{ "AcceptedAnswerId": "252331", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T06:54:43.173", "Id": "252287", "Score": "20", "Tags": [ "python", "python-3.x", "strings" ], "Title": "Add 'ing' or 'ly' suffix to a string" }
252287
<p>I apologize beforehand if the question has been repeated so many times. This is a practice task from Automate the Boring Stuff with Python. In brief, the task entails writing a code that carries out an experiment of checking if there is a streak of 6 'heads' or 'tails' in 100 coin tosses, then replicates it 10,000 times and gives a percentage of the success rate.</p> <p>When I wrote the code, I tried to be different by making the code applicable to any streaks in a number of predetermined experiments (in my case, the sample was 1 million coin tosses). I also tried to find the longest streak possible in that said experiment.</p> <p>I also want to apologize beforehand that the comments were awfully verbose.</p> <pre><code>import random, copy, time def torai(seq,pop): # seq is for #=streak, pop is for total sample/population/experiment # Creating a random chance of heads and tails tosses = [] for i in range(pop): tosses.append(random.randint(1,2)) # 1 and 2 for head and tail, and vice versa # Defining initial values for the main loop streak = 0 # Iterated streak curlongstr = 0 # Current longest streak longeststr = 0 # Longest streak evaluated peak = [] # Record local streaks from 'tosses' list # The main loop for i in range(len(tosses)): # Looping based on list indexes if i == 0: # Conditional for preventing tosses[0] == tosses[-1] continue elif tosses[i] == tosses[i-1]: # Conditional for checking if an i element has the same value as the previous element value, i-1 streak += 1 # Adding tally mark if the line above is fulfilled if i == len(tosses)-1: # A nested conditional for adding the last tally mark from 'tosses' into the overall list of steaks 'peak', see lines 27-33 peak.append(streak) elif tosses[i] != tosses[i-1]: # Conditional for checking if an i element value is different than the previous element value, i-1 curlongstr = copy.copy(streak) # Creating a variable by returning a copy of streak before it resets to 0, see line 31 if curlongstr &gt; longeststr: # A nested conditional for comparing the current longest streak and the longest streak that has happened when looping the 'tosses' list longeststr = curlongstr streak = 0 # This is where streaks ended and then resets to 0, so before that, the value of the streak is copied first, see line 28 if curlongstr &gt; streak: # After streak is reset to 0, the value of current long streak is compared to 0, so that we create a list of streaks from 'tosses' list peak.append(curlongstr) truepeak = [] for i in peak: # Example: a 2-streak is equal to either [1,1,1] or [2,2,2], a 4-streak is either [1,1,1,1,1] or [2,2,2,2,2] truepeak.append(i+1) apr = [] # Loop for finding how many #-streaks happened for i in truepeak: if i == seq: apr.append(i) print('%s-streak count: ' %seq, len(apr)) # Total of #-streaks happened in 'tosses' list print('%s-streak prob (percent): ' %seq, (len(apr)/pop)*100) # Calculating probability if how many #-streak happened in given n times tosses print('longest streak: ',longeststr + 1) # Similar reason as line 36 print('process time: ',time.process_time(), 'second\n') return (len(apr)/pop)*100 x = torai(2,1000000) y = torai(6,1000000) z = torai(10,1000000) print(x, y, z) </code></pre> <p>I tried to increase the sample to 10 million coin tosses. However, the program will run 9-10 slower each time the function was called.</p> <p>My request are can anyone check whether if the result (probability of n-streak) is right or not and are there any ways to make the code and process time shorter?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:58:10.943", "Id": "497018", "Score": "0", "body": "What on earth is \"torai\" supposed to mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T12:17:09.270", "Id": "497022", "Score": "0", "body": "It's just an arbitrary name :), from トライ (try). I'll change the function name to be more understandable and edit other things based on Aryan's input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T09:04:43.453", "Id": "497145", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<h1>Bugs</h1>\n<pre class=\"lang-py prettyprint-override\"><code>torai(1, 10000)\n</code></pre>\n<p>This should print something around <code>50 %</code>, since it's the individual count. But instead, it prints</p>\n<pre><code>1-streak count: 0\n1-streak prob (percent): 0.0\nlongest streak: 19\nprocess time: 0.046875 second\n</code></pre>\n<hr />\n<h1>Avoid too many comments</h1>\n<p>There are too many comments in your code, which makes the code look unnecessarily convoluted. What I recommend is the usage of <a href=\"https://www.programiz.com/python-programming/docstrings\" rel=\"noreferrer\">docstrings</a>. IMO It isn't very important here, but its better than a million comments</p>\n<pre class=\"lang-py prettyprint-override\"><code>def torai(seq,pop): \n tosses = []\n for i in range(pop):\n tosses.append(random.randint(1,2))\n streak = 0\n curlongstr = 0\n longeststr = 0\n peak = []\n for i in range(len(tosses)): \n if i == 0: \n continue\n elif tosses[i] == tosses[i-1]: \n streak += 1 \n if i == len(tosses)-1: \n peak.append(streak)\n\n elif tosses[i] != tosses[i-1]: \n curlongstr = copy.copy(streak) \n if curlongstr &gt; longeststr: \n longeststr = curlongstr\n streak = 0 \n if curlongstr &gt; streak: \n peak.append(curlongstr)\n\n truepeak = []\n for i in peak: \n truepeak.append(i+1)\n\n apr = []\n \n\n for i in truepeak:\n if i == seq:\n apr.append(i)\n\n print('%s-streak count: ' %seq, len(apr)) \n print('%s-streak prob (percent): ' %seq, (len(apr)/pop)*100) \n print('longest streak: ',longeststr + 1) \n print('process time: ',time.process_time(), 'second\\n')\n\n return (len(apr)/pop)*100\n</code></pre>\n<hr />\n<h1>Simplify #1</h1>\n<pre class=\"lang-py prettyprint-override\"><code> for i in range(len(tosses)): \n if i == 0: \n continue\n</code></pre>\n<p>It's clear to me that you want to skip the first element. In that case, you can specify the starting point for <code>range()</code></p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in range(1, len(tosses)): \n</code></pre>\n<hr />\n<h1>Simplify #2</h1>\n<pre class=\"lang-py prettyprint-override\"><code> for i in range(pop):\n tosses.append(random.randint(1,2))\n</code></pre>\n<p>Since this is going to be an immutable sequence, use a <a href=\"http://%20%20%20%20for%20i%20in%20range(pop):%20%20%20%20%20%20%20%20%20tosses.append(random.randint(1,2))\" rel=\"noreferrer\">tuple</a>, with a generator</p>\n<pre class=\"lang-py prettyprint-override\"><code>tosses = tuple(random.randint(1, 2) for _ in range(pop)\n</code></pre>\n<hr />\n<h1>Simplify #3</h1>\n<pre class=\"lang-py prettyprint-override\"><code> if curlongstr &gt; longeststr:\n longeststr = curlongstr\n</code></pre>\n<p>Your condition is simple. The new value is always the larger of the two<br>\nJust use the <code>max()</code> function</p>\n<pre class=\"lang-py prettyprint-override\"><code> longeststr = max(longeststr, curlongstr)\n</code></pre>\n<hr />\n<h1>Simplify #4</h1>\n<pre class=\"lang-py prettyprint-override\"><code>truepeak = []\n for i in peak:\n truepeak.append(i+1)\n</code></pre>\n<p>You're creating an entirely new list, and fill it up with the exact same elements as <code>peak</code> except with a constant <code>1</code> added to them. Very inefficient. Either add the values with the <code>+1</code> from the beginning or use the <code>+1</code> where necessary.</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in peak:\n if i + 1 == seq:\n apr.append(i + 1)\n</code></pre>\n<p>But again, all you do with <code>apr</code> is get its length, so there's absolutely no point in maintaining so many lists when all you have to do is keep a counter. That also removes the need to maintain <code>peak</code></p>\n<hr />\n<h1>Calculate tosses as you go</h1>\n<p>After removing all of the previous loops, there will still be 2 left. One for calculating the tosses and the other goes through them to calculate them. What I propose is, go through it only once, and keep track of two things. The current flip and the previous flip</p>\n<pre class=\"lang-py prettyprint-override\"><code>def torai(seq, iterations ):\n total_streaks = 0\n\n previous_flip = random.randint(1, 2)\n for _ in range(1, iterations):\n current_flip = random.randint(1, 2)\n\n if current_flip == previous_flip:\n total_streaks += 1\n\n # other calculations\n\n current_flip = previous_flip\n\n print(f&quot;Total streaks: {total_streaks}&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:24:33.503", "Id": "497074", "Score": "1", "body": "I disagree with *all* of your removal of comments—instead, I would take the comment and make that the variable name. For example, `curlongstr = 0 # Current longest streak` could be replaced with `current_longest_streak`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:47:35.973", "Id": "497082", "Score": "1", "body": "@lights0123 A few comments here and there are fine and sometimes needed but in this case, it serves very less purpose, more in making the code less readable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:04:40.120", "Id": "252299", "ParentId": "252290", "Score": "6" } } ]
{ "AcceptedAnswerId": "252299", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:57:54.470", "Id": "252290", "Score": "5", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Coin Flip Streak from Automate the Boring Stuff with Python" }
252290
<p>This is a simple program that solves a given Sudoku puzzle recursively. The input is provided as a file that contains the cells, 0 if empty, delimited by a <code>,</code> character.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;optional&gt; #include &lt;string&gt; #include &lt;string_view&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;exception&gt; #include &lt;fstream&gt; #include &lt;cctype&gt; #include &lt;algorithm&gt; using std::cout; using std::cin; using std::endl; using std::vector; using std::string; using std::string_view; using std::pair; using std::optional; using puzzle_t = vector&lt;vector&lt;int&gt;&gt;; using coord = pair&lt;size_t, size_t&gt;; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; other, const puzzle_t&amp; puzzle) { for (size_t i = 0; i &lt; 9; i++) { char comma[3] = {'\0', ' ', '\0'}; for (size_t j = 0; j &lt; 9; j++) { other &lt;&lt; comma &lt;&lt; puzzle[i][j]; comma[0] = ','; } other &lt;&lt; endl; } return other; } vector&lt;string&gt; split(const string&amp; str, const string&amp; delim) { vector&lt;string&gt; tokens; string_view str_view = str; size_t pos = 0; do { pos = str_view.find(delim); tokens.emplace_back(str_view.substr(0, pos)); str_view = str_view.substr(pos + 1, str_view.size()); } while (pos != string_view::npos); return tokens; } bool safe_isspace(char c) { return std::isspace(static_cast&lt;unsigned char&gt;(c)); } string strip(const string&amp; str) { size_t i; string result = str; for (i = 0; i &lt; result.size() &amp;&amp; safe_isspace(result[i]); i++); result = result.substr(i, result.length()); for (i = result.length() - 1; i &gt;= 0 &amp;&amp; safe_isspace(result[i]); i--); result = result.substr(0, i + 1); return result; } template &lt;class T&gt; vector&lt;T&gt; filter_empty(vector&lt;T&gt;&amp;&amp; vec) { vector&lt;T&gt; result; for (auto&amp; t : vec) { if (!t.empty()) { result.push_back(t); } } return result; } optional&lt;puzzle_t&gt; read_puzzle(std::istream&amp; in) { try { puzzle_t puzzle; while (puzzle.size() &lt; 9) { string line; std::getline(in, line); if (line.empty()) { continue; } vector&lt;string&gt; all_cells = split(line, &quot;,&quot;); vector&lt;int&gt; row; for (auto&amp; str : all_cells) { str = strip(str); } all_cells = filter_empty(std::move(all_cells)); if (all_cells.size() != 9) { return { }; } for (auto&amp; str : all_cells) { int value = std::stoi(str); if (value &lt; 0 || value &gt; 9) { return { }; } row.push_back(value); } puzzle.push_back(row); } return { puzzle }; } catch (const std::exception&amp; exn) { return { }; } } bool validate_puzzle(const puzzle_t&amp; puzzle ) { auto validate_group = [](vector&lt;int&gt; group) -&gt; bool { for (int i = 1; i &lt;= 9; i++) { if (std::count(group.begin(), group.end(), i) &gt; 1) { return false; } } return true; }; auto get_col = [&amp;puzzle](size_t col_n) -&gt; vector&lt;int&gt; { vector&lt;int&gt; col(9); for (const auto&amp; row : puzzle) { col.push_back(row[col_n]); } return col; }; auto get_group = [&amp;puzzle](size_t i, size_t j) -&gt; vector&lt;int&gt; { vector&lt;int&gt; group; for (int row = i * 3; row &lt; i * 3 + 3; row++) { for (int col = j * 3; col &lt; j * 3 + 3; col++) { group.push_back(puzzle[row][col]); } } return group; }; return validate_group(puzzle[0]) &amp;&amp; validate_group(puzzle[1]) &amp;&amp; validate_group(puzzle[2]) &amp;&amp; validate_group(puzzle[3]) &amp;&amp; validate_group(puzzle[4]) &amp;&amp; validate_group(puzzle[5]) &amp;&amp; validate_group(puzzle[6]) &amp;&amp; validate_group(puzzle[7]) &amp;&amp; validate_group(puzzle[8]) &amp;&amp; validate_group(get_col(0)) &amp;&amp; validate_group(get_col(1)) &amp;&amp; validate_group(get_col(2)) &amp;&amp; validate_group(get_col(3)) &amp;&amp; validate_group(get_col(4)) &amp;&amp; validate_group(get_col(5)) &amp;&amp; validate_group(get_col(6)) &amp;&amp; validate_group(get_col(7)) &amp;&amp; validate_group(get_col(8)) &amp;&amp; validate_group(get_group(0, 0)) &amp;&amp; validate_group(get_group(0, 1)) &amp;&amp; validate_group(get_group(0, 2)) &amp;&amp; validate_group(get_group(1, 0)) &amp;&amp; validate_group(get_group(1, 1)) &amp;&amp; validate_group(get_group(1, 2)) &amp;&amp; validate_group(get_group(2, 0)) &amp;&amp; validate_group(get_group(2, 1)) &amp;&amp; validate_group(get_group(2, 2)); } optional&lt;coord&gt; get_next_empty_coord(const puzzle_t&amp; puzzle) { for (size_t i = 0; i &lt; 9; i++) { for (size_t j = 0; j &lt; 9; j++) { if (puzzle[i][j] == 0) { return { std::make_pair(i, j) }; } } } return { }; } void solve_recursive(puzzle_t&amp; puzzle, vector&lt;puzzle_t&gt;&amp; results) { auto next_coord_opt = get_next_empty_coord(puzzle); if (!next_coord_opt) { results.push_back(puzzle); return; } auto next_coord = next_coord_opt.value(); for (int i = 1; i &lt;= 9; i++) { puzzle[next_coord.first][next_coord.second] = i; if (validate_puzzle(puzzle)) { solve_recursive(puzzle, results); } puzzle[next_coord.first][next_coord.second] = 0; } } vector&lt;puzzle_t&gt; solve(puzzle_t&amp;&amp; puzzle) { vector&lt;puzzle_t&gt; result; solve_recursive(puzzle, result); return result; } bool solver(const string&amp; in_path, const string&amp; out_path) { std::ifstream fin(in_path); std::ofstream fout(out_path); if (!fin || !fout) { cout &lt;&lt; &quot;IO failure&quot; &lt;&lt; endl; return false; } optional&lt;puzzle_t&gt; puzzle = read_puzzle(fin); if (!puzzle || puzzle.value().size() != 9 || puzzle.value()[0].size() != 9) { cout &lt;&lt; &quot;Invalid puzzle&quot; &lt;&lt; endl; return false; } auto solutions = solve(std::move(puzzle.value())); fout &lt;&lt; &quot;Number of solutions found: &quot; &lt;&lt; solutions.size() &lt;&lt; endl; fout &lt;&lt; endl; for (const auto&amp; solution : solutions) { fout &lt;&lt; solution &lt;&lt; endl; fout &lt;&lt; endl; } fin.close(); fout.close(); return true; } int main(int argc, char* argv[]) { std::ios::sync_with_stdio(false); if (argc == 3) { string in_path = argv[1]; string out_path = argv[2]; if (solver(in_path, out_path)) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } } else { cout &lt;&lt; &quot;Invalid number of arguments to program.&quot; &lt;&lt; endl; return EXIT_FAILURE; } } </code></pre> <p>The program is compiled with clang using the following options.</p> <pre><code>$ clang++ -std=c++17 -Wall -Werror -O3 -o sudoku_solver sudoku_solver.cpp # Normal $ clang++ -std=c++17 -Wall -Werror -O0 -g -fsanitize=address -fsanitize=undefined -fno-optimize-sibling-calls -o sudoku_solver sudoku_solver.cpp # for debug with ASAN </code></pre> <p>The program can be run as follows.</p> <pre><code>$ sudoku_solver &lt;input_file&gt; &lt;output_file&gt; </code></pre> <p>Here is an example of the program running. Here is an example input. Note, that whitespace is added for human readability, but the program is expected to ignore empty lines.</p> <pre><code>0, 0, 5, 0, 8, 0, 3, 0, 2 4, 2, 0, 0, 0, 0, 5, 0, 0 6, 0, 0, 0, 0, 4, 0, 0, 0 0, 0, 0, 3, 0, 0, 9, 0, 0 3, 0, 0, 0, 2, 6, 0, 0, 0 0, 0, 0, 0, 0, 0, 0, 7, 0 0, 0, 0, 0, 7, 0, 6, 8, 0 0, 9, 8, 0, 0, 0, 0, 0, 4 0, 0, 0, 5, 0, 0, 0, 0, 0 </code></pre> <p>Here is the output generated by the program.</p> <pre><code>Number of solutions found: 1 9, 1, 5, 6, 8, 7, 3, 4, 2 4, 2, 7, 9, 1, 3, 5, 6, 8 6, 8, 3, 2, 5, 4, 1, 9, 7 8, 7, 1, 3, 4, 5, 9, 2, 6 3, 4, 9, 7, 2, 6, 8, 5, 1 2, 5, 6, 8, 9, 1, 4, 7, 3 1, 3, 2, 4, 7, 9, 6, 8, 5 5, 9, 8, 1, 6, 2, 7, 3, 4 7, 6, 4, 5, 3, 8, 2, 1, 9 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T12:34:13.137", "Id": "497023", "Score": "2", "body": "Micro-review: **`std::`** `size_t`. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:45:55.900", "Id": "497029", "Score": "1", "body": "Is there a particular aspect that you want the review to focus on?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:42:46.973", "Id": "497047", "Score": "0", "body": "@harold Primarily style and use of modern c++" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T21:11:49.007", "Id": "497097", "Score": "0", "body": "@adityagnet Maybe use a named constant instead of `9` in a lot of places?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:35:34.543", "Id": "497361", "Score": "0", "body": "So proud of you. That's a lot of work. I did some stuff related years and years ago, feel free to steal any ideas you want: https://github.com/phorgan1/sudoku-system.git" } ]
[ { "body": "<blockquote>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;optional&gt;\n#include &lt;string&gt;\n#include &lt;string_view&gt;\n#include &lt;vector&gt;\n#include &lt;utility&gt;\n#include &lt;exception&gt;\n#include &lt;fstream&gt;\n#include &lt;cctype&gt;\n#include &lt;algorithm&gt;\n</code></pre>\n</blockquote>\n<p>I find it helps if I keep my includes in alphabetical order - that makes it easy to quickly check whether I have already included one I'm about to add.</p>\n<hr />\n<blockquote>\n<pre><code>using std::cout;\nusing std::cin;\nusing std::endl;\nusing std::vector;\nusing std::string;\nusing std::string_view;\nusing std::pair;\nusing std::optional;\n</code></pre>\n</blockquote>\n<p>I don't like these at file scope (but infinitely better than <code>using</code> the whole of <code>namespace std</code>). But that's perhaps just a personal preference.</p>\n<p>Despite not <code>using</code> <code>std::size_t</code>, it's written unqualified in many places - a likely portability issue.</p>\n<hr />\n<blockquote>\n<pre><code>//Flat vectors/arrays are faster, but for this small a data set it doesn't really matter.\n</code></pre>\n</blockquote>\n<p>It's not really the size of data that matters, but more the number of accesses. An array of arrays would probably be a better choice, given that the size is fixed:</p>\n<pre><code>using puzzle_t = std::array&lt;9, std::array&lt;9, int&gt;&gt;;\n</code></pre>\n<p>Be careful using identifiers ending in <code>_t</code> - in the global namespace, POSIX reserves those names. Not a problem here, but something to be aware of.</p>\n<hr />\n<blockquote>\n<pre><code> char comma[3] = {'\\0', ' ', '\\0'};\n\n for(size_t j = 0; j &lt; 9; j++) {\n other &lt;&lt; comma &lt;&lt; puzzle[i][j];\n comma[0] = ',';\n }\n</code></pre>\n</blockquote>\n<p>It took me a while to work out what's happening here. I think it's clearer and more idiomatic to just switch a pointer between two constant string literals:</p>\n<pre><code> char const *sep = &quot;&quot;;\n for (auto cell: puzzle[i]) {\n other &lt;&lt; sep &lt;&lt; cell;\n sep = &quot;, &quot;;\n }\n</code></pre>\n<p>I think that's easier to follow than manipulating individual characters in an array. You might want to consider using a <code>std::ostream_iterator()</code> to do the delimiter handling for you (though that doesn't do exactly what we want here).</p>\n<hr />\n<blockquote>\n<pre><code> other &lt;&lt; endl;\n</code></pre>\n</blockquote>\n<p>We don't need to flush output for every line. Just write <code>\\n</code> there instead.</p>\n<hr />\n<blockquote>\n<pre><code>bool safe_isspace(char c) {\n return std::isspace(static_cast&lt;unsigned char&gt;(c));\n}\n</code></pre>\n</blockquote>\n<p>Yes, that's a good way to reduce clutter, and to reduce the likelihood of forgetting the cast somewhere.</p>\n<hr />\n<blockquote>\n<pre><code>for (i = 0; i &lt; result.size() &amp;&amp; safe_isspace(result[i]); i++);\nresult = result.substr(i, result.length());\nfor (i = result.length() - 1; i &gt;= 0 &amp;&amp; safe_isspace(result[i]); i--);\nresult = result.substr(0, i + 1);\n</code></pre>\n</blockquote>\n<p>Instead of assigning twice to <code>result</code>, it's better to find the start and end positions and use <code>substr()</code> just once. If we use iterators rather than indexes, standard algorithms come to our aid:</p>\n<pre><code>using RevIt = std::reverse_iterator&lt;std::string::iterator&gt;;\nauto a = std::find_if_not(str.begin(), str.end(), safe_isspace);\nauto z = std::find_if_not(str.rbegin(), RevIt(a), safe_isspace).base();\nreturn std::string{a,z};\n</code></pre>\n<p>Look, no arithmetic!</p>\n<hr />\n<p>Another loop that can be replaced here:</p>\n<pre><code>for (auto&amp; t : vec) {\n if (!t.empty()) {\n result.push_back(t);\n }\n}\n</code></pre>\n<p>That looks like a candidate for <code>std::copy_if()</code>.</p>\n<hr />\n<pre><code> for (int i = 1; i &lt;= 9; i++) {\n if (std::count(group.begin(), group.end(), i) &gt; 1) {\n return false;\n }\n }\n</code></pre>\n<p>Looks inefficient. Instead of searching for each possible value, why not gather what's there into a <code>std::multiset</code> (or even count into a simple array) and examine the counts in that? That has the advantage (if you put it into the Puzzle class itself) of being reusable for checking whether a solution is complete.</p>\n<hr />\n<blockquote>\n<pre><code>return validate_group(puzzle[0]) &amp;&amp;\n validate_group(puzzle[1]) &amp;&amp;\n validate_group(puzzle[2]) &amp;&amp;\n validate_group(puzzle[3]) &amp;&amp;\n validate_group(puzzle[4]) &amp;&amp;\n validate_group(puzzle[5]) &amp;&amp;\n validate_group(puzzle[6]) &amp;&amp;\n validate_group(puzzle[7]) &amp;&amp;\n validate_group(puzzle[8]) &amp;&amp;\n validate_group(get_col(0)) &amp;&amp;\n validate_group(get_col(1)) &amp;&amp;\n validate_group(get_col(2)) &amp;&amp;\n validate_group(get_col(3)) &amp;&amp;\n validate_group(get_col(4)) &amp;&amp;\n validate_group(get_col(5)) &amp;&amp;\n validate_group(get_col(6)) &amp;&amp;\n validate_group(get_col(7)) &amp;&amp;\n validate_group(get_col(8)) &amp;&amp;\n validate_group(get_group(0, 0)) &amp;&amp;\n validate_group(get_group(0, 1)) &amp;&amp;\n validate_group(get_group(0, 2)) &amp;&amp;\n validate_group(get_group(1, 0)) &amp;&amp;\n validate_group(get_group(1, 1)) &amp;&amp;\n validate_group(get_group(1, 2)) &amp;&amp;\n validate_group(get_group(2, 0)) &amp;&amp;\n validate_group(get_group(2, 1)) &amp;&amp;\n validate_group(get_group(2, 2));\n</code></pre>\n</blockquote>\n<p>Although quite clear, it might be better transformed into a few loops (possible internal to calls to <code>std::all_of()</code>). That trades one clarity for another - we would then not need to check whether we'd missed one out.</p>\n<hr />\n<pre><code> cout &lt;&lt; &quot;Invalid number of arguments to program.&quot; &lt;&lt; endl;\n return EXIT_FAILURE;\n</code></pre>\n<p>Error messages should go to the standard error stream <code>std::cerr</code>, not <code>std::cout</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T21:31:36.603", "Id": "497099", "Score": "0", "body": "Hmm, alphabetical includes... never thought about that! I always do it by increasing order of dependencies/complexity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:48:45.147", "Id": "497226", "Score": "2", "body": "+1 for alphy sorted includes/imports. It makes it really easy to spot a missing import. This is especially helpful in code reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:52:49.947", "Id": "497227", "Score": "2", "body": "also, +1 for calling out `endl` as meaning \"newline AND flush\" and not simply a constant for '\\n'. I have solved many a performance issue by replacing endl with '\\n'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T15:52:56.203", "Id": "533209", "Score": "0", "body": "_Note that identifiers ending in _t are reserved for use by the Standard Library, so I recommend changing that name._ Say what? Any identifier that's not actually reserved for the implementation (`_Ugly`, `two__scores`) won't be a macro or \"magic\" and can be defined in your own scope that's not going to conflict with what's in `namespace std`. You might be thinking of Posix, which would only apply to the global namespace in C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T16:04:22.513", "Id": "533210", "Score": "0", "body": "Yes, @JDługosz, I was thinking of POSIX." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T16:10:42.540", "Id": "533211", "Score": "1", "body": "@TobySpeight that's a good reason to put a `namespace` around the whole thing, even for simple one-file programs like this." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:35:36.143", "Id": "252329", "ParentId": "252294", "Score": "12" } }, { "body": "<p>Everything <a href=\"https://codereview.stackexchange.com/a/252329/6499\">that Toby said</a>, plus:</p>\n<p>In <code>operator&lt;&lt;</code>, the output stream should not be called <code>other</code>. The variable name <code>other</code> should only be used in comparison functions between <code>this</code> and <code>other</code>. It should rather be called <code>out</code> or <code>os</code>.</p>\n<p>When I run the program, I get an error message that doesn't help me:</p>\n<pre><code>$ ./cmake-build-debug/sudoku.exe sudoku.txt\nInvalid number of arguments to program.\n</code></pre>\n<p>The common pattern is to print this instead:</p>\n<pre><code>usage: sudoku.exe &lt;input file&gt; &lt;output file&gt;\n</code></pre>\n<p>&quot;Don't tell me what I did wrong, tell me how to do it correctly.&quot;</p>\n<p>What is the purpose of the commas in the input and output? I don't see any. In my own sudoku solver, I rather used this format:</p>\n<pre><code>---3-8---\n--2---31-\n35-2-1-68\n6---1-2-7\n--3-9-4--\n1-4-8---9\n84-6-5-23\n-31---5--\n---1-9---\n</code></pre>\n<p>Of course, you can choose any other character for unknown cells. Or allow spaces. But spaces + commas is a little too much to me.</p>\n<p>Just like Toby, I had a hard time reading the code around <code>char comma[3]</code>. Seeing that a variable called comma didn't actually contain a comma could only mean one thing: That you are a liar, or at least your code is. You should rather write trustworthy code instead, where the variable names match their content and purpose. This one should have been called <code>separator</code> or <code>sep</code> instead, just like Toby said. I usually use <code>sep</code> since that name is long enough in a function with less than 10 lines of code.</p>\n<p>In the function <code>get_group</code>, you compare signed with unsigned numbers. You should use consistent data types, which in this case means <code>std::size_t</code> instead of <code>int</code>. In the compiler warnings, you forgot <code>-Wextra</code> for GCC and <code>-Weverything</code> for Clang.</p>\n<p>In <code>validate_group</code> you construct a vector with 9 elements each time. This looks like unnecessary memory allocation to me. I'd rather use <code>std::array&lt;int, 9&gt;</code> instead, or maybe even write it without any memory allocation at all. The way you did it in <code>validate_puzzle</code> looks easy to understand though, therefore chances are high that after trying to do it in another way, I'd just throw that attempt away and return to your code instead.</p>\n<p>I'm a bit confused when I see a loop like <code>for (int i = 1; i &lt;= 9; i++)</code> since I expect loops with the variable <code>i</code> to start at 0 and use <code>&lt;</code> instead of <code>&lt;=</code>. If you had renamed the variable to <code>candidate</code> or <code>cand</code> for short, I wouldn't be as surprised.</p>\n<p>I'd rename <code>validate_puzzle</code> to <code>is_solvable</code>. On second thought, the correct name would rather be <code>is_not_obviously_unsolvable</code>, but that quickly gets ugly. So the appropriate name might be <code>may_be_solvable</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> cout &lt;&lt; &quot;Invalid puzzle&quot; &lt;&lt; endl;\n</code></pre>\n<p>This is really unfriendly to the user. Again, don't tell me that I did something wrong (without even telling me what this something is), tell me how and where to fix it. Line number and column number are the least that your program must provide.</p>\n<p>In <code>main</code>, the <code>argc != 3</code> is an error condition. Therefore it should be written with a simple <code>if</code>, not an <code>if-else</code>, like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main(int argc, char* argv[]) {\n std::ios::sync_with_stdio(false);\n\n if (argc != 3) {\n cout &lt;&lt; &quot;Invalid number of arguments to program.&quot; &lt;&lt; endl;\n return EXIT_FAILURE;\n }\n\n string in_path = argv[1];\n string out_path = argv[2];\n\n if (!solver(in_path, out_path))\n return EXIT_FAILURE;\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p>This way, the main control flow all happens at the same indentation level of the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T11:05:58.337", "Id": "497291", "Score": "1", "body": "\"The variable name other should only be used in comparison functions between this and other\" this is a specific programming style rather than a general rule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T11:18:19.767", "Id": "497292", "Score": "0", "body": "It's a general rule. The word _other_ only makes sense if there is also a _this_. It's not a programming rule but a language rule. Language rules apply to code reviews as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T12:26:46.717", "Id": "497295", "Score": "1", "body": "\"Other\" makes sense in any context in which there is a clear comparator, it does not need to be `this` as you stated. Of course, I agree like any variable name it should be chosen to make sense in context but your specification is overly narrow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:19:20.433", "Id": "497366", "Score": "0", "body": "@JackAidley Could you drop me a note when you come across a piece of code that uses the variable name `other` in a meaningful way, without also having a variable called `self` or `this` or `it` at the same time? I'd expect it to be difficult to find such code, that's why I'd like to know." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:51:47.723", "Id": "252391", "ParentId": "252294", "Score": "3" } }, { "body": "<p>You should separate loading, solving, and saving the solution into different usable functions. Consider that you could have unit tests that have a board embedded directly into the source code, and you would want to call a <em>different</em> function to ingest that (rather than giving it a file name). Your tests might perturb an existing board to generate different cases, and just call <code>solve</code> without re-loading the whole thing from scratch. You can compare the output against the known correct value, and not save it to a file at all.</p>\n<p>It's not just to consider unit testing, but such separation makes it easy to maintain. What if you add a GUI or other file formats? That should be possible and <em>easy</em> without having to touch the <code>solve</code> function.</p>\n<hr />\n<p>Consider using <code>string_view</code>. In particular, this makes it easy to trim spaces without recopying the input to an output string. If you do all the processing of the individual values on a line while the whole line is still in memory, you can use <code>string_view</code> end to end from <code>split</code> through to the final value.</p>\n<p>BTW, I use a <code>split</code> that returns an <code>array&lt;string_view,N&gt;</code> so it does not have to allocate memory as with a <code>vector</code> (or any of the <code>string</code> elements) at all! Since you know how many items are on one line (it's an error if that's not right) you could use that method as well.</p>\n<hr />\n<p>Donald Knuth wrote a Sudoku solver called <em>Dancing Links</em> that is very efficient. If I wanted to do this, I would implement his algorithm using modern C++, along with the desired input and output routines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T16:52:54.563", "Id": "533213", "Score": "1", "body": "+1 for the hint to separate I/O from algorithm and mentioning unit tests" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T16:06:40.367", "Id": "270096", "ParentId": "252294", "Score": "2" } } ]
{ "AcceptedAnswerId": "252329", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T08:19:47.780", "Id": "252294", "Score": "11", "Tags": [ "c++", "recursion", "c++17", "sudoku" ], "Title": "Sudoku solver program written in modern c++" }
252294
<p>I am using OWIN to self host a WebAPI service. There is Unity to serve as an IoC container. Within several OWIN middlewares (e.g. authorization layer) as well as in WebAPI I need to access a Unity container to resolve my dependencies. There should be a single child container per each request so that there is for example a single DB context which is used several times during the request and it is disposed at the end of the request along with the Unity container. For WebAPI I would like to use the same container as for previous middlewares. However, the default <code>UnityHierarchicalDependencyResolver</code> creates its own child container from the given parent per each request. So I had to write my own infrastructure to force WebAPI to use existing child containers. Please review the following code snippets. I would be happy for any kind of feedback since this is quite critical a part of my application.</p> <p>Here is my app configuration method:</p> <pre class="lang-cs prettyprint-override"><code>public static void Configure(IAppBuilder app, IUnityContainer container) { //register middleware that creates child container for each request app.UseUnityContainer(container); //register other middlewares ... //create httpconfig var config = new HttpConfiguration { DependencyResolver = container.Resolve&lt;OwinUnityDependencyResolver&gt;() }; //... config.MessageHandlers.Insert(0, container.Resolve&lt;OwinDependencyScopeHandler&gt;()); app.UseWebApi(config); } </code></pre> <p>The <code>UseUnityContainer</code> extension method that is responsible for creating and disposing child containers:</p> <pre class="lang-cs prettyprint-override"><code>public static void UseUnityContainer(this IAppBuilder app, IUnityContainer container) { app.Use&lt;UnityMiddleware&gt;(container); } private class UnityMiddleware : OwinMiddleware { private readonly IUnityContainer _parent; public UnityMiddleware(OwinMiddleware next, IUnityContainer parent) : base(next) { _parent = parent; } public override async Task Invoke(IOwinContext context) { using (var child = _parent.CreateChildContainer()) { context.SetUnityContainer(child); await Next.Invoke(context); } } } </code></pre> <p>To access and store the container within the OWIN context there are following extension methods:</p> <pre class="lang-cs prettyprint-override"><code>public static class UnityOwinContextExtensions { private const string UnityContainerKey = &quot;OwinUnityContainer&quot;; public static IUnityContainer GetUnityContainer(this IOwinContext context) { return context.Get&lt;IUnityContainer&gt;(UnityContainerKey); } public static void SetUnityContainer(this IOwinContext context, IUnityContainer container) { context.Set(UnityContainerKey, container); } } </code></pre> <p><code>OwinUnityDependencyResolver</code> class used in <code>HttpConfiguration</code>:</p> <pre class="lang-cs prettyprint-override"><code>public class OwinUnityDependencyResolver : IDependencyResolver { private static readonly IDependencyScope NullScope = new NullDependencyScope(); private readonly IUnityContainer _parent; public OwinUnityDependencyResolver(IUnityContainer parent) { _parent = parent; } public void Dispose() { //parent container is disposed in SureStowWebApiService } public object GetService(Type serviceType) { try { return _parent.Resolve(serviceType); } catch (ResolutionFailedException) { return null; } } public IEnumerable&lt;object&gt; GetServices(Type serviceType) { try { return _parent.ResolveAll(serviceType); } catch (ResolutionFailedException) { return null; } } public IDependencyScope BeginScope() { //BeginScope should not be called as there should be already scope registered by OwinDependencyScopeHandler return NullScope; } private class NullDependencyScope : IDependencyScope { public void Dispose() { } public object GetService(Type serviceType) =&gt; null; public IEnumerable&lt;object&gt; GetServices(Type serviceType) =&gt; null; } } </code></pre> <p><code>OwinDependencyScopeHandler</code> class that is used to retrieve the existing child container from an OWIN context and create a new dependency scope out of it. This handler is registered in <code>HttpConfiguration</code>.</p> <pre class="lang-cs prettyprint-override"><code>public class OwinDependencyScopeHandler : DelegatingHandler { protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var context = request.GetOwinContext(); var scope = new OwinUnityDependencyScope(context); //this prevents HttpRequestMessageExtensions.GetDependencyScope to initialize scope from dependency resolver request.Properties[HttpPropertyKeys.DependencyScope] = scope; return base.SendAsync(request, cancellationToken); } private class OwinUnityDependencyScope : IDependencyScope { private readonly IUnityContainer _container; public OwinUnityDependencyScope(IOwinContext owinContext) { _container = owinContext.GetUnityContainer(); //this is child container created by UnityMiddleware } public void Dispose() { //_container should be disposed by UnityMiddleware } public object GetService(Type serviceType) =&gt; _container.Resolve(serviceType); public IEnumerable&lt;object&gt; GetServices(Type serviceType) =&gt; _container.ResolveAll(serviceType); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:03:53.030", "Id": "497005", "Score": "1", "body": "Welcome to CodeReview@SE. (Guessing your first language isn't Indo-Germanic: can you try and insert articles where appropriate? And please consistently capitalise names, e.g. *Unity*.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:54:33.217", "Id": "497031", "Score": "0", "body": "@greybeard thanks for your feedback. Could you please give an example where it is appropriate to insert an article?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T22:39:21.780", "Id": "497101", "Score": "0", "body": "If only using the right article was trivial! Without \"domain\" knowledge, it is difficult to tell whether in indefinite article is in order or a definite one. Please have your hypertext browser follow the *edited <period> ago* link beneath the post and have it show the difference *before* vs. *after* side by side. There are places where I left both forms because neither seemed unlikely : please remove (at least) one. Caveat: no \"native\" speaker would mistake me for one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T06:47:54.863", "Id": "497280", "Score": "0", "body": "@greybeard thanks for your grammar input, really appreciated. Do you have any comments on the code? It would be really helpful to have someone as precise as you for code inspection too." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T09:27:52.733", "Id": "252297", "Score": "2", "Tags": [ "c#", "dependency-injection", "asp.net-web-api", "unity-container", "owin" ], "Title": "How to use single child Unity container for OWIN middleware and WebAPI" }
252297
<p>To compare the speed of <code>Julia</code> to <code>Python+numba</code>, I implemented <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="noreferrer">Game of Life</a> in both languages.</p> <p>For anyone who is not familiar with Game of Life: Start with a matrix of boolean entries, encoding whether a cell is <em>alive</em> or <em>dead</em>. Then, at every iteration, update the state of a cell based upon its value and the eight neighboring values.</p> <ol> <li>If the cell is alive, and <strong>exactly</strong> two or three neighboring cells are alive, the cell stays alive.</li> <li>If the cell is alive and <strong>fewer than two</strong> or <strong>more than three</strong> neighboring cells are alive, the cell dies.</li> <li>If a cell is dead, and <strong>exactly</strong> three neighbors are alive, it becomes alive.</li> <li>If none of the above applies, the cell keeps it state.</li> </ol> <p>I chose a special initial condition called <em>Acorn</em>, just to make sure the population stays alive sufficiently long.</p> <p>Here is the reference <code>Python+numba</code> code with the respective timing and output.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from time import time from numba import njit def acorn(n): # Initial condition state = np.zeros((n,n)) mid = n//2 state[mid,mid-2:mid+5] = 1 state[mid,mid] = 0 state[mid,mid+1] = 0 state[mid+1,mid+1] = 1 state[mid+2,mid-1] = 1 return state&gt;0 @njit def update(s): dimx,dimy = s.shape nexts = np.copy(s) for i in range(1,dimx-1): for j in range(1,dimy-1): count = -1 if s[i,j] else 0 for offi in [-1,0,+1]: for offj in [-1,0,+1]: if s[i+offi,j+offj]: count += 1 if s[i,j]: if count &lt; 2 or count &gt; 3: nexts[i,j] = False else: if count ==3: nexts[i,j] = True return nexts def run(state,n): for i in range(n): state = update(state) return state n = 100 nruns = 1000 state = acorn(n) t = time() s = run(state,nruns) dt = time() -t plt.pcolormesh(s) plt.grid(&quot;on&quot;) print(&quot;Elapsed time {:.5f} seconds&quot;.format(dt)) print(&quot;One run in {:.5f} seconds&quot;.format(dt/n)) print(&quot;{} runs per seconds&quot;.format(int(n/dt))) plt.savefig(&quot;out.png&quot;) </code></pre> <p>Output (after a precompilation run):</p> <pre><code>Elapsed time 0.07883 seconds One run in 0.00079 seconds 1268 runs per seconds </code></pre> <p><a href="https://i.stack.imgur.com/qxwwk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qxwwk.png" alt="enter image description here" /></a></p> <p>This seems reasonably fast on my Intel i5 notebook with 12gb of RAM and Python 3.8 and recent numpy + numba versions.</p> <p>Next is the Julia code. I basically translated the Python code to Julia using my limited Julia knowledge.</p> <pre><code>using PyPlot function acorn(n) mid = Int(n/2)+1 state = zeros(n,n) state[mid,mid-2:mid+4] .= 1 state[mid,mid] = 0 state[mid,mid+1] = 0 state[mid+1,mid+1] = 1 state[mid+2,mid-1] = 1 return state .&gt; 0 end function update!(nextstate::BitArray{2},state::BitArray{2}) dimx,dimy = size(state) for i = 2:dimx-1 for j = 2:dimy -1 count = ifelse(state[i,j],-1,0) for offi in [-1,0,1] for offj in [-1,0,1] if state[i+offi,j+offj] count += 1 end end end if state[i,j] if count &lt;2 || count &gt; 3 nextstate[i,j] = false end else if count == 3 nextstate[i,j] = true end end end end end function run(state,nsteps) nextstate = deepcopy(state) for i=1:nsteps update!(nextstate,state) state = deepcopy(nextstate) end return state end nsteps = 1000 n = 100 state = acorn(n) @time s = run(state,nsteps) plt.pcolormesh(s) plt.grid(&quot;on&quot;) </code></pre> <p>Output:</p> <pre><code> 1.746477 seconds (38.55 M allocations: 4.015 GiB, 7.56% gc time) </code></pre> <p><a href="https://i.stack.imgur.com/YIuuc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YIuuc.png" alt="enter image description here" /></a></p> <p>I see that there is a lot of memory allocation going on. But I am not sure about the best way to avoid this. Ultimately (unless I come up with a completely different algorithm), I do need two matrices (<code>state</code> array and its copy).</p> <p><strong>What do I have to change in my Julia code to reach similar or better performance than my Python code?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:29:05.290", "Id": "497014", "Score": "0", "body": "Did you profile the code to see where are the CPU cycles consumed? Not sure but deepcopy looks like is copy memory in deep and is a candidate for optimize" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:40:02.220", "Id": "497015", "Score": "0", "body": "The `deepcopy`does not seem to be the problem. If I remove it from the inner loop (i.e., I basically repeat the first iteration `nsteps` times), the timing doesn't change much:\n `1.649412 seconds (38.42 M allocations: 4.007 GiB, 8.31% gc time)`. I will have to look into profiling tools, I'm not familiar with them yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:45:41.453", "Id": "497016", "Score": "0", "body": "Okay it seems that `for offi in [-1,0,1]` is the bottleneck. I can obviously replace it with `for i=-1:1` which speeds up things significantly. \n`0.202571 seconds (7.01 k allocations: 1.772 MiB)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T13:59:54.753", "Id": "500210", "Score": "1", "body": "`n // 2` should become `n ÷ 2`, I believe. `Int(n/2)` fails for odd numbers." } ]
[ { "body": "<p>Here is my &quot;optimized&quot; version of your code, I'm going down to about <s>32</s> 7 ms</p>\n<p>I use <code>@btime</code> from <code>BenchmarkTools</code> to average multiple trys and avoid counting the compilation time</p>\n<p>I made <s>4</s> 5 changes :</p>\n<ul>\n<li>switch from BitArray to Array{Int} (I don't know why it's faster though)</li>\n<li>update <code>state</code> with <code>.=</code> instead of a copy</li>\n<li>unroll the short loops</li>\n<li>update <code>nextstate</code> with a branchless <code>ifelse</code></li>\n<li>(EDIT) <code>@inbounds</code> bypasses checking if indices are in the bounds of the array (only use it if you're sure the index isn't greater than the size of the array)</li>\n</ul>\n<p>I also changed <code>count</code> to <code>counter</code> since <code>count</code> is a built-in function.</p>\n<pre><code>using PyPlot, BenchmarkTools\n\nfunction acorn(n)\n mid = Int(n/2)+1\n state = zeros(Int, n, n) # &lt;- specify Int (will be Float64 if not specified)\n state[mid,mid-2:mid+4] .= 1\n state[mid,mid] = 0\n state[mid,mid+1] = 0\n state[mid+1,mid+1] = 1\n state[mid+2,mid-1] = 1\n\n # I found that Array{Int} is faster than BitArray. Array{Bool} is slowest\n return state \nend\n\nfunction update!(nextstate,state)\n dimx,dimy = size(state)\n for j in 2:dimy-1\n for i in 2:dimx-1\n # unroll loops\n @inbounds counter = state[i-1,j-1] + state[i-1,j] + state[i-1,j+1] +\n state[i ,j-1] + state[i ,j+1] +\n state[i+1,j-1] + state[i+1,j] + state[i+1,j+1]\n \n # branchless if statement\n @inbounds nextstate[i,j] = ifelse(state[i,j] == 1, 1 &lt; counter &lt; 4, counter == 3)\n\n end \n end\nend\n\nfunction run(state,nsteps)\n nextstate = copy(state)\n state = copy(state)\n\n for i in 1:nsteps\n update!(nextstate,state)\n\n # each value from nextstate is copied to state, instead of copying the whole array\n state .= nextstate\n end\n return state\nend\n\nnsteps = 1000\nn = 100\nstate = acorn(n)\ns = @btime run(state,nsteps)\nplt.pcolormesh(s)\nplt.grid(&quot;on&quot;)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T08:32:03.600", "Id": "497283", "Score": "1", "body": "Thank you! This was the kind of performance I expected but couldn't achieve. `Int` vs `BitArray` is strange though.\nThanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T05:12:26.290", "Id": "497379", "Score": "0", "body": "The downside of `BitArray`s is that they don't play well with vectorization since computers can only address bytes at a time. This means that re-ordering `getindex` and `setindex` can have really weird results." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:35:20.183", "Id": "252363", "ParentId": "252301", "Score": "5" } } ]
{ "AcceptedAnswerId": "252363", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:14:25.293", "Id": "252301", "Score": "6", "Tags": [ "python", "performance", "julia" ], "Title": "Speed of Python vs Julia for Game of Life. Why is Julia slow?" }
252301
<p>I have this piece of code:</p> <pre><code>final ResultDO response = transformJsonToResponseDO(rawDataResponse, ResultDO.class); return Optional.ofNullable(response) .map(results -&gt; createPOIs(Collections.singletonList(response), providerResponse)) .orElse(Collections.emptyList()); </code></pre> <p>The important part is that: <strong>response</strong> is an object of type <strong>ResultDO</strong>. Within an Optional I want to call that method createPois(). Methot createPois wants a list of ResultDO, but there I will always have it only element because of that I wrapped in a Collections.singletonList().</p> <p>As I wrote it, is it the right way, with that .map() ?</p> <p>I don't want to use if(response != null) ...</p> <p>Maybe it is worth to mention that createPois() return a list of some other types. A list of Points.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T16:26:22.140", "Id": "497431", "Score": "0", "body": "Why not use an if statement here?" } ]
[ { "body": "<p>This looks mostly correct. IMO, should not use <code>response</code> in the map function, but <code>results</code>. I.e.</p>\n<pre><code>final ResultDO response = transformJsonToResponseDO(rawDataResponse, ResultDO.class);\n\nreturn Optional.ofNullable(response)\n .map(results -&gt; createPOIs(Collections.singletonList(results), providerResponse))\n .orElse(Collections.emptyList());\n</code></pre>\n<p>Even though they are the same in this case, typically this is how you are supposed to use Optional when you're not wrapping in #ofNullable.</p>\n<p>Furthermore, this lets you put it all on one line:</p>\n<pre><code>return Optional.ofNullable(transformJsonToResponseDO(rawDataResponse, ResultDO.class))\n .map(results -&gt; createPOIs(Collections.singletonList(results), providerResponse))\n .orElse(Collections.emptyList());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T14:24:42.133", "Id": "253618", "ParentId": "252303", "Score": "1" } } ]
{ "AcceptedAnswerId": "253618", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T11:25:18.137", "Id": "252303", "Score": "1", "Tags": [ "java" ], "Title": "How can I apply an Optional in which I want to call a method?" }
252303
<p>I created this hangman game today as my first stand alone project. It is a quite basic and simplified approach. How could I improve the game to make it more interesting?</p> <pre><code> import random words = [&quot;abductions&quot;, &quot;abridgment&quot;, &quot;admixtures&quot; ,&quot;backfields&quot;, &quot;blueprints&quot;, &quot;chivalrous&quot;, &quot;complexity&quot;, &quot;cyberpunks&quot;, &quot;desolating&quot;, &quot;duplicator&quot;,&quot;earthlings&quot;, &quot;fluoridate&quot;,&quot;flustering&quot;,&quot;fornicates&quot;,&quot;godfathers&quot;,&quot;humanizers&quot;,&quot;ideographs&quot;,&quot;journalism&quot;, &quot;languished&quot;,&quot;logarithms&quot;,&quot;mendacious&quot;,&quot;neighborly&quot;,&quot;outlandish&quot;,&quot;palindrome&quot;,&quot;philanders&quot; ,&quot;proclaimed&quot;,&quot;randomizes&quot;,&quot;shrinkable&quot;,&quot;sublimated&quot;, &quot;truckloads&quot;,&quot;upholstery&quot;,&quot;vanquished&quot;,&quot;vulcanizes&quot;,&quot;wanderlust&quot;,&quot;womanizers&quot; ] i = random.randint(0, len(words) - 1) word = words[i] guesses = &quot;_&quot;*len(word) print(guesses) lives = 0 while lives &lt; 5: character_check = input(&quot;&quot;) if character_check in word and character_check != word: a = word.index(character_check) guesses = guesses[:a] + word[a] + guesses[a+1:] print(guesses) if guesses == word or character_check == word: print(&quot;Winner!&quot;) break elif character_check not in word: print(lives) lives += 1 if lives == 5: print(&quot;You lose! It was {}&quot;.format(word)) </code></pre>
[]
[ { "body": "<p>A couple of coding suggestions...</p>\n<ol>\n<li><p>You can use <code>random.choice(words)</code> to pick a random item out of the <code>words</code> list.</p>\n</li>\n<li><p>I'd be tempted to <code>sys.exit()</code> instead of <code>break</code> on winning. That way you don't need to test the value of <code>lives</code> - if you reach the end of the while loop you have lost.</p>\n</li>\n</ol>\n<p>In terms of making the program 'more interesting', I'd add a welcome message, maybe explain the rules. Maybe also display a list of letters already guessed and do nothing if the same letter is guessed twice? (Right now choosing the same letter 5times loses the game). you could also have short, medium and long (or easy, medium, hard) word lists and ask the person to choose which they want to use.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:38:17.983", "Id": "497154", "Score": "0", "body": "Thanks! I'll try to implement those things as soon as possible" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T14:11:18.063", "Id": "252317", "ParentId": "252309", "Score": "0" } }, { "body": "<p>This is a great start. Let me point out a few things you should consider.</p>\n<h2>Make it interactive</h2>\n<p>When I ran the code, it produces some numbers whenever I lose a guess, it took a while to figure out that it was my guess count incrementing. A nice prompt message would be helpful. Also the guess count should reduce for each guess made.</p>\n<h2>Avoid hardcorded values</h2>\n<p>What is <code>5</code> in the following statement\n<code>while lives &lt; 5:</code>. it can be written as follow</p>\n<pre><code>MAX_LIVES = 5\nwhile lives &lt;= MAX_LIVES:\n</code></pre>\n<h2>Misleading names</h2>\n<p><code>character_check</code> is just too misleading, promises one thing(to check a character) and does another thing(recieves input from the user). This can rewritten as <code>user_input</code></p>\n<h2>Features worth adding</h2>\n<ol>\n<li>You could make the game a class,implement a board class to nicely draw the man being hung.</li>\n<li>You could also implement a hint package interface, user might want to buy and use hints when they are stuck.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:13:54.013", "Id": "497229", "Score": "1", "body": "Thanks! I have since changed a couple things already. I did notice afterwards that the lives should have been decreasing not increasing, I had like a D'oh moment. I like the idea for hints, I'll try to incorporate that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:51:34.763", "Id": "252370", "ParentId": "252309", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:48:37.663", "Id": "252309", "Score": "4", "Tags": [ "python", "game", "hangman" ], "Title": "Improvements to simple Hangman Game in Python" }
252309
<p><a href="https://leetcode.com/problems/longest-valid-parentheses/" rel="nofollow noreferrer">Link here</a></p> <p>I'll include a solution in Python and C++ and you can review one. I'm mostly interested in reviewing the C++ code which is a thing I recently started learning; those who don't know C++ can review Python code. Both solutions share similar logic, so the review will apply to either.</p> <hr /> <h2>Problem statement</h2> <blockquote> <p>Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.</p> </blockquote> <p><strong>Example 1:</strong></p> <pre><code>Input: s = &quot;(()&quot; Output: 2 Explanation: The longest valid parentheses substring is &quot;()&quot;. </code></pre> <p><strong>Example 2:</strong></p> <pre><code>Input: s = &quot;)()())&quot; Output: 4 Explanation: The longest valid parentheses substring is &quot;()()&quot;. </code></pre> <p><strong>Example 3:</strong></p> <pre><code>Input: s = &quot;&quot; Output: 0 </code></pre> <p><strong>Example 4:</strong></p> <pre><code>Input: s = &quot;(()()()&quot; Output: 6 </code></pre> <p><strong>Example 5:</strong></p> <pre><code>Input: s = &quot;((())((((())))&quot; Output: 8 </code></pre> <p>Both solutions are Oⁿ and pass all test cases including the time limit however, they are taking time more than I expected, specially the c++ version though both share the same logic. I need to improve time as a priority.</p> <p><code>longest_parentheses.py</code></p> <pre><code>def check_longest(s): opened = [] closed = [] cum_distance = 0 max_distance = 0 for i, ss in enumerate(s): if ss == ')': if opened: closed.append((opened.pop(), i)) if ss == '(': opened.append(i) closed = set(sum(closed, ())) for j in range(len(s)): if j in closed: cum_distance += 1 else: cum_distance = 0 max_distance = max(max_distance, cum_distance) return max_distance if __name__ == '__main__': print(check_longest(')((()()()()')) </code></pre> <p><strong>Stats:</strong></p> <pre><code>Runtime: 272 ms, faster than 5.14% of Python3 online submissions for Longest Valid Parentheses. Memory Usage: 15.5 MB, less than 6.57% of Python3 online submissions for Longest Valid Parentheses. </code></pre> <p><code>longest_parentheses.h</code></p> <pre><code>#ifndef LEETCODE_LONGEST_PARENTHESES_H #define LEETCODE_LONGEST_PARENTHESES_H #include &lt;string_view&gt; int calculate_distance(size_t p_size, const std::vector&lt;size_t&gt; &amp;closed); int get_longest(const std::string_view &amp;s); #endif //LEETCODE_LONGEST_PARENTHESES_H </code></pre> <p><code>longest_parentheses.cpp</code></p> <pre><code>#include &quot;longest_parentheses.h&quot; #include &lt;vector&gt; #include &lt;iostream&gt; int calculate_distance(size_t p_size, const std::vector&lt;size_t&gt; &amp;closed) { int cum_distance = 0; int max_distance = 0; for (size_t i = 0; i &lt; p_size; ++i) { if (std::find(closed.begin(), closed.end(), i) != closed.end()) { cum_distance++; } else { cum_distance = 0; } max_distance = std::max(max_distance, cum_distance); } return max_distance; } int get_longest(const std::string_view &amp;s) { std::vector&lt;size_t&gt; opened, closed; for (size_t i = 0; i &lt; s.size(); ++i) { auto ss = s[i]; if (ss == ')') { if (!opened.empty()) { closed.push_back({opened.back()}); closed.push_back(i); opened.pop_back(); } } if (ss == '(') { opened.push_back(i); } } return calculate_distance(s.size(), closed); } int main() { std::cout &lt;&lt; get_longest(&quot;)()())&quot;); } </code></pre> <p><strong>Stats:</strong></p> <pre><code>Runtime: 1276 ms, faster than 5.09% of C++ online submissions for Longest Valid Parentheses. Memory Usage: 9.3 MB, less than 5.04% of C++ online submissions for Longest Valid Parentheses. </code></pre>
[]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n<h1>C++ version</h1>\n<h2>Use all of the required <code>#include</code>s</h2>\n<p>The type <code>std::vector&lt;size_t&gt;</code> is used in the definition of <code>calculate_distance()</code> in the header file, but <code>#include &lt;vector&gt;</code> is missing from the list of includes there. Also, <code>std::max()</code> is used, but <code>#include &lt;algorithm&gt;</code> is missing from the <code>.cpp</code> file.</p>\n<h2>Minimize the interface</h2>\n<p>The <code>.h</code> file is a declaration of the <em>interface</em> to your software. The <code>.cpp</code> is the <em>implementation</em> of that interface. It is good design practice to minimize the interface to just that which is needed by outside programs. For that reason, I would remove the <code>calculate_distance()</code> function from the header.</p>\n<h2>Make local functions <code>static</code></h2>\n<p>With the smaller interface as advocated above, the <code>calculate_distance</code> function becomes an implementation detail used only within the <code>.cpp</code> file. For that reason, it should be made <code>static</code> so the compiler knows that it's safe to inline the function.</p>\n<h2>Use a <code>switch</code> rather than a series of <code>if</code> statements</h2>\n<p>The code currently contains this:</p>\n<pre><code>for (size_t i = 0; i &lt; s.size(); ++i) {\n auto ss = s[i];\n if (ss == ')') {\n if (!opened.empty()) {\n closed.push_back({opened.back()});\n closed.push_back(i);\n opened.pop_back();\n }\n }\n if (ss == '(') {\n opened.push_back(i);\n }\n}\n</code></pre>\n<p>It would be a little faster and a little easier to read if it were instead written like this:</p>\n<pre><code>for (size_t i = 0; i &lt; s.size(); ++i) {\n switch(s[i]) {\n case ')':\n if (!opened.empty()) {\n closed.push_back({opened.back()});\n closed.push_back(i);\n opened.pop_back();\n }\n break;\n case '(':\n opened.push_back(i);\n break;\n }\n}\n</code></pre>\n<h2>Be careful with signed vs. unsigned</h2>\n<p>What would it mean if <code>calculate_distance</code> return a negative number? It probably has no sensible interpretation, so for that reason, I'd recommend having it return an <code>unsigned</code> quantity versus a signed <code>int</code>.</p>\n<h2>Write test functions</h2>\n<p>You have provided some test input in the description of the problem, but it would be good to write a full test script to exercise the function. For this kind of thing, I tend to like to use a test object. Here's the one I wrote for this code:</p>\n<pre><code>class ParenTest {\npublic:\n ParenTest(std::string_view input, unsigned longest)\n : input{input}\n , longest{longest}\n {}\n unsigned operator()() const {\n return static_cast&lt;unsigned&gt;(get_longest(input));\n }\n bool test() const {\n return longest == operator()();\n }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const ParenTest&amp; test) {\n auto calculated = test();\n return out &lt;&lt; (calculated == test.longest ? &quot;ok &quot; : &quot;BAD &quot;) \n &lt;&lt; &quot;\\&quot;&quot; &lt;&lt; test.input &lt;&lt; &quot;\\&quot;, &quot; &lt;&lt; test.longest &lt;&lt; &quot;, got &quot; &lt;&lt; calculated &lt;&lt; &quot;\\n&quot;;\n }\nprivate:\n std::string_view input;\n unsigned longest;\n};\n</code></pre>\n<p>Now here are some test vectors and a <code>main</code> routine:</p>\n<pre><code>int main(int argc, char* argv[]) {\n static const std::vector&lt;ParenTest&gt; tests{\n { &quot;(()&quot;, 2 },\n { &quot;)()())&quot;, 4 },\n { &quot;&quot;, 0 },\n { &quot;(()()()&quot;, 6 },\n { &quot;((())((((())))&quot;, 8 },\n { &quot;(())(())(()))&quot;, 12 },\n { &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))&quot;, 12 },\n { &quot;(())(())(()))(())(())(())(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;, 38 },\n { &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;, 38 },\n { &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;\n &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;, 38 },\n };\n for (const auto &amp;test : tests) {\n std::cout &lt;&lt; test;\n }\n}\n</code></pre>\n<p>To both assure correctness and also do some timing, I've used my <a href=\"https://codereview.stackexchange.com/questions/58055/stopwatch-template\">stopwatch template</a>. The final version of <code>main</code> looks like this:</p>\n<pre><code>#include &quot;longest_parentheses.h&quot;\n#include &quot;stopwatch.h&quot;\n#include &lt;string_view&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\n// the ParenTest class goes here\n\nint main(int argc, char* argv[]) {\n static const std::vector&lt;ParenTest&gt; tests{\n { &quot;(()&quot;, 2 },\n { &quot;)()())&quot;, 4 },\n { &quot;&quot;, 0 },\n { &quot;(()()()&quot;, 6 },\n { &quot;((())((((())))&quot;, 8 },\n { &quot;(())(())(()))&quot;, 12 },\n { &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))&quot;, 12 },\n { &quot;(())(())(()))(())(())(())(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;, 38 },\n { &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;, 38 },\n { &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;\n &quot;(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))&quot;, 38 },\n };\n for (const auto &amp;test : tests) {\n std::cout &lt;&lt; test;\n }\n if (argc != 2) {\n std::cout &lt;&lt; &quot;Usage: &quot; &lt;&lt; argv[0] &lt;&lt; &quot; num_trials\\n&quot;;\n return 1;\n }\n \n auto iterations = std::stoul(argv[1]);\n\n Stopwatch&lt;&gt; timer{};\n bool valid{true}\n\n for (auto i{iterations}; i; --i) {\n valid &amp;= tests.back().test();\n }\n\n auto elapsed{timer.stop()};\n if (!valid) {\n std::cout &lt;&lt; &quot;The program failed!\\n&quot;;\n return 2;\n }\n\n std::cout &lt;&lt; iterations &lt;&lt; &quot; trials took &quot; &lt;&lt; elapsed &lt;&lt; &quot; microseconds\\n&quot;\n &quot; for an average of &quot; &lt;&lt; elapsed/iterations &lt;&lt; &quot; microseconds/trial\\n&quot;;\n}\n</code></pre>\n<h2>Use a better algorithm</h2>\n<p>The existing code is not so bad, but it's not as efficient as it could be. On my machine with the code shown above and with one million trials, it takes 5.66 microseconds per invocation of <code>get_longest()</code> on the longest test input, which is also the last of the set. We can do better. Here is an alternative routine that uses a <code>std::vector</code> to keep track of each of the starting <code>(</code> as they occur, but also does the calculation of span length as it encounters each closing <code>)</code>. Here's how I did it:</p>\n<pre><code>unsigned get_longest(const std::string_view&amp; in) {\n struct Span {\n std::size_t begin;\n std::size_t end;\n Span(std::size_t begin, std::size_t end)\n : begin{begin}\n , end{end}\n {}\n std::size_t len() const {\n return end - begin + 1;\n }\n bool is_strictly_enclosing(const Span&amp; other) const {\n return other.begin - begin == 1 &amp;&amp;\n end - other.end == 1;\n }\n bool is_contiguous_with(const Span&amp; other) const {\n return begin - other.end == 1;\n }\n };\n std::vector&lt;std::size_t&gt; parenmatch;\n std::vector&lt;Span&gt; spans;\n std::size_t longest{0};\n for (std::size_t i{0}; i &lt; in.size(); ++i) {\n switch(in[i]) {\n case '(':\n parenmatch.push_back(i);\n break;\n case ')':\n if (!parenmatch.empty()) {\n Span curr_span{parenmatch.back(), i};\n parenmatch.pop_back();\n if (!spans.empty() &amp;&amp; curr_span.is_strictly_enclosing(spans.back())) {\n // destroy the last one\n spans.pop_back();\n }\n if (!spans.empty() &amp;&amp; curr_span.is_contiguous_with(spans.back())) {\n // merge the contiguous spans\n spans.back().end = curr_span.end;\n } else {\n spans.push_back(curr_span);\n }\n longest = std::max(longest, spans.back().len());\n } \n break;\n default:\n parenmatch.clear();\n spans.clear();\n }\n }\n return longest;\n}\n</code></pre>\n<p>There is probably still room for improvement, but here's how this works. First, it keeps track of each <code>Span</code> of matching and nested parentheses. So <code>()</code> would be correspond to such a span, as would <code>(())</code>. The code uses <code>is_strictly_enclosing</code> to test for these. As an example, in <code>(())</code>, the inner pair is found first and would have a span of <code>{1,2}</code>. The outer pair is found last and has a span of <code>{0,3}</code>. If we examine the logic, it's now clear what this code is looking for:</p>\n<pre><code>bool is_strictly_enclosing(const Span&amp; other) const {\n return other.begin - begin == 1 &amp;&amp;\n end - other.end == 1;\n}\n</code></pre>\n<p>Secondly, there is the case of matching but non-nested parentheses such as <code>()()</code> or <code>(())()</code>. Here again, we use a member function of <code>Span</code>:</p>\n<pre><code>bool is_contiguous_with(const Span&amp; other) const {\n return begin - other.end == 1;\n}\n</code></pre>\n<p>Using this code, we get the following timing report:</p>\n<blockquote>\n<p>1000000 trials took 562299 microseconds for an average of 0.562299 microseconds/trial</p>\n</blockquote>\n<p>So this version of the code is about 10x faster. Note too, that it correctly handles malformed input such as <code>((*))</code> by reporting <code>0</code> for such a string.</p>\n<h1>Python version</h1>\n<h2>Use <code>elif</code> for mutually exclusive conditions</h2>\n<p>The check for the opening <code>(</code> uses <code>if</code> but it would make more sense to use <code>elif</code> here because the two cases (either <code>(</code> or <code>)</code>) are the only ones considered. Making just this one change drops each iteration (using the same very long string as in the C++ code) from 74.167 microseconds to 72.444 microseconds.</p>\n<h2>Don't update values that are unchanged</h2>\n<p>The code currently has this sequence:</p>\n<pre><code>for j in range(len(s)):\n if j in closed:\n cum_distance += 1\n else:\n cum_distance = 0\n max_distance = max(max_distance, cum_distance)\n</code></pre>\n<p>A quick look at the code will verify that <code>max_distance</code> can only get a new value if the <code>if</code> statement is true, so let's move the line there. This drops the time down to 71.680 microseconds.</p>\n<h2>Use a faster algorithm</h2>\n<p>Once again, what works in the C++ version also works in Python. Here's a Python version of the algorithm above:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_longest(s):\n parenmatch = []\n spans = []\n longest = 0\n for i, ss in enumerate(s):\n if ss == '(':\n parenmatch.append(i)\n elif ss == ')':\n if parenmatch:\n curr_span = (parenmatch.pop(), i)\n if spans and spans[-1][0] - curr_span[0] == 1 and curr_span[1] - spans[-1][1] == 1:\n spans.pop()\n if spans and curr_span[0] - spans[-1][1] == 1:\n spans[-1] = (spans[-1][0], curr_span[1])\n else:\n spans.append(curr_span)\n longest = max(longest, spans[-1][1] - spans[-1][0] + 1)\n return longest \n</code></pre>\n<p>This time, the difference is not as dramatic, and the time for this function is 64.562 microseconds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T04:19:11.613", "Id": "252353", "ParentId": "252311", "Score": "3" } } ]
{ "AcceptedAnswerId": "252353", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T13:55:26.007", "Id": "252311", "Score": "0", "Tags": [ "python", "c++", "programming-challenge" ], "Title": "Leetcode longest valid parentheses" }
252311
<h1><a href="https://github.com/Zoran-Jankov/Weekly-Employee-Report-Generator" rel="nofollow noreferrer">Weekly Employee Report Generator PowerShell Script</a></h1> <h2>Description</h2> <p>This script is used for generating a Markdown template file for weekly employee reports. In <strong><code>Settings.cfg</code></strong> file you can define the name and title of the employee, report title and report folder name, starting hour and working time, and the names of the days of the week, to cover all the languages. When you run the script it will first try to find existing file for current week and open it in the the default Markdown editor, and if it does not exist it will create one for current week, and then it will open newly created file.</p> <h3>Settings Example</h3> <pre><code>EmployeeName = John Doe EmployeeTitle = System Administrator ReortFolderName = Weekly Reports ReportTitle = Weekly report StartingTime = 09:00 WorkingTime = 8 MondayName = Monday TuesdayName = Tuesday WednesdayName = Wednesday ThursdayName = Thursday FridayName = Friday SaturdayName = Saturday SundayName = Sunday </code></pre> <h2>PowerShell Script</h2> <pre><code>$Date = Get-Date $DayDecrement = 0 $Settings = Get-Content -Path &quot;$PSScriptRoot\Settings.cfg&quot; | ConvertFrom-StringData switch ($Date.DayOfWeek) { 'Monday' { $DayDecrement = 0 } 'Tuesday' { $DayDecrement = -1 } 'Wednesday' { $DayDecrement = -2 } 'Thursday' { $DayDecrement = -3 } 'Friday' { $DayDecrement = -4 } 'Saturday' { $DayDecrement = -5 } 'Sunday' { $DayDecrement = -6 } } $MondayDate = $Date.AddDays($DayDecrement).ToString(&quot;dd.MM.yyyy.&quot;) $SundayDate = $Date.AddDays($DayDecrement + 6).ToString(&quot;dd.MM.yyyy.&quot;) $Settings = Get-Content -Path &quot;$PSScriptRoot\Settings.cfg&quot; | ConvertFrom-StringData $ReportTitle = $Settings.ReportTitle + &quot; $MondayDate - $SundayDate&quot; $Documents = [environment]::getfolderpath(&quot;mydocuments&quot;) $ReportFolderName = $Settings.ReortFolderName $ReportFullName = &quot;$Documents<span class="math-container">\$ReportFolderName\$</span>ReportTitle&quot; + &quot;md&quot; if (-not (Test-Path -Path $ReportFullName)) { $DaysOfWeek = @( $Settings.MondayName $Settings.TuesdayName $Settings.WednesdayName $Settings.ThursdayName $Settings.FridayName $Settings.SaturdayName $Settings.SundayName ) $Employee = &quot;&gt; &quot; + $Settings.EmployeeName + &quot; - &quot; + $Settings.EmployeeTitle $ReportBody = &quot;# $ReportTitle`n`n$Employee`n`n------`n`n&quot; foreach ($Day in $DaysOfWeek) { $ReportBody += &quot;## $Day &quot; + $Date.AddDays($DayDecrement).ToString(&quot;dd.MM.yyyy.&quot;) $DayDecrement ++ $ReportBody += &quot;`n`n------`n`n&quot; for ($Hour = 0; $Hour -lt $Settings.WorkingTime; $Hour ++) { $Start = ([datetime]::ParseExact($Settings.StartingTime, &quot;HH:mm&quot;, $null)).AddHours($Hour).ToString(&quot;HH:mm&quot;) $End = ([datetime]::ParseExact($Settings.StartingTime, &quot;HH:mm&quot;, $null)).AddHours($Hour + 1).ToString(&quot;HH:mm&quot;) $ReportBody += &quot;### $Start - $End`n`n- `n`n&quot; } $ReportBody += &quot;------`n`n&quot; } New-Item -Path $ReportFullName -Force Add-Content -Path $ReportFullName -Value $ReportBody } Start-Process $ReportFullName </code></pre> <h2><a href="https://github.com/Zoran-Jankov/Weekly-Employee-Report-Generator/blob/main/Generated%20Report%20Example.md" rel="nofollow noreferrer">Generated Report Example</a></h2> <h2>Question</h2> <p>I am planning on creating a GUI for editing <strong><code>Settings.cfg</code></strong> file, and to have the option to select work days so not the whole week is created, just the days you work on. I would like your opinions on my little project and how to improve it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:07:09.627", "Id": "497053", "Score": "2", "body": "[1] dotnet has a dayname enum >>> `[System.DayOfWeek]::GetNames([System.DayOfWeek])` <<< plus, it is culture aware. [2] you may want to consider using `Export/Import-CliXml` for your config files since that stores things in a way that neatly restores objects." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T14:02:27.947", "Id": "252313", "Score": "1", "Tags": [ "powershell", "generator" ], "Title": "Weekly Employee Report Generator PowerShell Script" }
252313
<p>I recently was reading an article labeled &quot;Modern C++ Singleton Template&quot;. The proposed solution used C++11 feature of Magic Statics (N2660). I wanted to adapt it for an own project in &quot;freestanding&quot; (fno-hosted) environment.</p> <p>My code looks as follows:</p> <h3>Singleton.hpp</h3> <pre><code>namespace std { template &lt;typename T&gt; class Singleton { public: // = initialization and termination methods Singleton( const Singleton&amp; ) = delete; // copy constructor Singleton( Singleton&amp;&amp; ) = delete; // move constructor Singleton&amp; operator=( const Singleton&amp; ) = delete; // assignment operator Singleton&amp; operator=( Singleton&amp;&amp;) = delete; // copy move operator // = accessor methods. static T&amp; getInstance(); protected: Singleton() {}; // default constructor ~Singleton() {}; // default destructor struct Token {}; private: }; // end template class T template &lt;typename T&gt; T&amp; Singleton&lt;T&gt;::getInstance() { static T __singleInstance( Token{} ); return( __singleInstance ); } // end public method 'getInstance()' } // end namespace std </code></pre> <h3>Test.hpp</h3> <pre><code>#include &quot;libs/libc++/singleton.hpp&quot; // declaration of template class 'Singleton' class Test final : public TestSingelton&lt;Test&gt; { public: Test(TestToken); ~Test(); void use(); }; </code></pre> <h3>Test.cpp</h3> <pre><code>Test::Test(TestToken) { logTraceEvent_m( loging to file ); } Test::~Test() { logTraceEvent_m( loging to file ); } void Test::use() { logTraceEvent_m( loging to file ); } </code></pre> <h3>Problem</h3> <p>In hosted environment (Linux, GCC 7.5.0) it works as presented in the article refereed to above. The static variable is initialized only once; the constructor of the derived class is called only once.</p> <pre><code>Entering main() Entering a() constructed in use Entering b() in use Leaving main() destructed </code></pre> <p>However, in my &quot;-ffreestandig&quot; environment it is not working. &quot;freestanding&quot; = kernel without any standard headers; without any libraries!</p> <p>Static variable (&quot;__singleInstance&quot;) is initialized on every call to &quot;Test::getInstance()&quot;.</p> <pre><code>______ TRACE: constructor = Test::Test(TestSingelton&lt;Test&gt;::TestToken), ... ______ TRACE: use = void Test::use(), file = test/Test.cpp, line = 37. ______ TRACE: constructor = Test::Test(TestSingelton&lt;Test&gt;::TestToken), ... ______ TRACE: use = void Test::use(), file = test/Test.cpp, line = 37. </code></pre> <p>What I'm doing wrong? Is there any advice in which direction I have to investigate?</p> <ul> <li>compiler options?</li> <li>-W -Wall -pedantic -ffreestanding -std=gnu++17 -fno-PIC -fno-exceptions -fno-rtti -fno-use-cxa-atexit -march=native -m64 -mcmodel=kernel -mno-red-zone -mno-sse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -mno-sse4 -mno-sse4a -mno-3dnow -mno-avx -mno-avx2</li> <li>runtime environment, that is missing something</li> </ul>
[]
[ { "body": "<p>Your test code doesn't match your test output. &quot;Test.cpp&quot; isn't even valid C++ code!</p>\n<p>How does your massive amount of code do anything significantly different from the following eight lines?</p>\n<pre><code>template&lt;class T&gt;\nstruct Singleton {\n struct Token {};\n static T&amp; getInstance() {\n static T instance(Token{});\n return instance;\n }\n};\n</code></pre>\n<p>Example usage:</p>\n<pre><code>struct Widget { explicit Widget(Singleton&lt;Widget&gt;::Token); };\nWidget&amp; example = Singleton&lt;Widget&gt;::getInstance();\n</code></pre>\n<p>As for why the &quot;thread-safe statics&quot; feature doesn't work on your freestanding platform, I would suspect it's because your freestanding platform doesn't support thread-safe statics. :) Check the documentation for your toolchain to see how <code>static</code> variables are handled on that particular platform.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T01:01:09.150", "Id": "252345", "ParentId": "252318", "Score": "2" } }, { "body": "<p>After further thinking and reading I suspect the behaviour is caused by my incomplete C++ ABI.\nMy functions __xca_gaurd_aquire/__xca_guard_release are currently empty functions and I will go ahead to implement minimalistic versions and see if I get different results. Currently I belive that's the way to overcome my problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T06:54:33.600", "Id": "252356", "ParentId": "252318", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T14:17:51.633", "Id": "252318", "Score": "1", "Tags": [ "template", "singleton", "static" ], "Title": "Magic Static in Singleton Template" }
252318
<p>I have an Excel file with 2 columns, names and numbers. I want to know for each name what is the probability for each number. I prefer to do it in Java so I would be able to combine it with the rest of my project.</p> <p>Actually, I already did it, and it's works, but I think it's done in a primitive and inefficient way.</p> <p>Can you please suggest a better solution?</p> <p>I thought about java stream but didn't know how.</p> <h3>My code:</h3> <pre><code>import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class HospitalizationDistribution { public static void main(String[] args) { HashMap&lt;String, ArrayList&lt;Integer&gt;&gt; map = readData(&quot;procedure and hospitalization time.xlsx&quot;); HashMap&lt;String, HashMap&lt;Integer, Double&gt;&gt; allDisributions = makeDisribution(map); HashMap&lt;Integer, Double&gt; example = allDisributions.get(&quot;Partial mastectomy&quot;); System.out.println(&quot;Partial mastectomy:&quot;); for (Entry&lt;Integer, Double&gt; entry : example.entrySet()) { System.out.println(entry.getKey() + &quot;: &quot; + entry.getValue()); } } private static HashMap&lt;String, ArrayList&lt;Integer&gt;&gt; readData(String src){ HashMap&lt;String, ArrayList&lt;Integer&gt;&gt; map = new HashMap&lt;String, ArrayList&lt;Integer&gt;&gt;(); try { File file = new File(src); // creating a new file instance FileInputStream fis = new FileInputStream(file); // obtaining bytes from the file //creating Workbook instance that refers to .xlsx file XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sheet = wb.getSheetAt(0); // creating a Sheet object to retrieve object String procedure; int duration; for (Row row : sheet) { // iterating over excel file procedure = row.getCell(0).getStringCellValue(); duration = (int)row.getCell(1).getNumericCellValue(); if(map.get(procedure) == null) map.put(procedure, new ArrayList&lt;Integer&gt;()); map.get(procedure).add(duration); } wb.close(); } catch (Exception e) { e.printStackTrace(); } return map; } private static HashMap&lt;String, HashMap&lt;Integer, Double&gt;&gt; makeDisribution(HashMap&lt;String, ArrayList&lt;Integer&gt;&gt; map) { HashMap&lt;String, HashMap&lt;Integer, Double&gt;&gt; allDisributions = new HashMap&lt;String, HashMap&lt;Integer,Double&gt;&gt;(); String procedure; HashMap&lt;Integer, Double&gt; singleDisribution; ArrayList&lt;Integer&gt; durations; double sp; // single outcome probability for (Entry&lt;String, ArrayList&lt;Integer&gt;&gt; entry : map.entrySet()) { procedure = entry.getKey(); durations = entry.getValue(); singleDisribution = new HashMap&lt;Integer, Double&gt;(); sp = 1.0/durations.size(); Double p; for (Integer i : durations) { // summing identical outcomes probability p = singleDisribution.get(i); if(p == null) p = 0.0; singleDisribution.put(i, p + sp); } allDisributions.put(procedure, singleDisribution); } return allDisributions; } </code></pre> <h3>The output:</h3> <pre><code>Partial mastectomy: 3: 0.02233676975945018 4: 0.036082474226804134 5: 0.02920962199312716 6: 0.02233676975945018 7: 0.013745704467353955 8: 0.02577319587628867 9: 0.020618556701030934 10: 0.02233676975945018 11: 0.017182130584192445 13: 0.005154639175257732 . . . </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T14:23:01.240", "Id": "252319", "Score": "2", "Tags": [ "java", "excel" ], "Title": "Create a distribution from .xlsx file using Java" }
252319
<p><a href="https://leetcode.com/problems/valid-sudoku/" rel="noreferrer">Link here</a></p> <p>I'll include a solution in Python and C++ and you can review one. I'm mostly interested in reviewing the C++ code which is a thing I recently started learning; those who don't know C++ can review the Python code. Both solutions share similar logic, so the review will apply to any.</p> <hr /> <h2>Problem statement</h2> <blockquote> <p>Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:</p> </blockquote> <ul> <li>Each row must contain the digits 1-9 without repetition. Each column</li> <li>must contain the digits 1-9 without repetition. Each of the nine 3 x</li> <li>3 sub-boxes of the grid must contain the digits 1-9 without repetition.</li> </ul> <p><strong>Note:</strong></p> <p>A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules.</p> <p><strong>Example 1:</strong></p> <pre><code>Input: board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] Output: true </code></pre> <p><strong>Example 2:</strong></p> <pre><code>Input: board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. </code></pre> <p><code>valid_sudoku.py</code></p> <pre><code>def is_valid(board, empty_value='.', b_size=3): seen = set() size = b_size * b_size for row in range(size): for col in range(size): if (value := board[row][col]) == empty_value: continue r = f'0{row}{value}' c = f'1{col}{value}' b = f'2{row // b_size}{col // b_size}{value}' if r in seen or c in seen or b in seen: return False seen.update({r, c, b}) return True if __name__ == '__main__': g = [ [&quot;5&quot;, &quot;3&quot;, &quot;.&quot;, &quot;.&quot;, &quot;7&quot;, &quot;5&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;], [&quot;6&quot;, &quot;.&quot;, &quot;.&quot;, &quot;1&quot;, &quot;9&quot;, &quot;5&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;], [&quot;.&quot;, &quot;9&quot;, &quot;8&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;6&quot;, &quot;.&quot;], [&quot;8&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;6&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;3&quot;], [&quot;4&quot;, &quot;.&quot;, &quot;.&quot;, &quot;8&quot;, &quot;.&quot;, &quot;3&quot;, &quot;.&quot;, &quot;.&quot;, &quot;1&quot;], [&quot;7&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;2&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;6&quot;], [&quot;.&quot;, &quot;6&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;2&quot;, &quot;8&quot;, &quot;.&quot;], [&quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;4&quot;, &quot;1&quot;, &quot;9&quot;, &quot;.&quot;, &quot;.&quot;, &quot;5&quot;], [&quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;.&quot;, &quot;8&quot;, &quot;.&quot;, &quot;.&quot;, &quot;7&quot;, &quot;9&quot;], ] print(is_valid(g)) </code></pre> <p><strong>Stats:</strong></p> <pre><code>Runtime: 92 ms, faster than 81.70% of Python3 online submissions for Valid Sudoku. Memory Usage: 14.1 MB, less than 73.95% of Python3 online submissions for Valid Sudoku. </code></pre> <p>Here's an alternative solution using numpy, it's shorter and more readable but slower:</p> <pre><code>import numpy as np def is_valid(board, size=3, empty_value='.'): board = np.array(board) blocks = board.reshape(4 * [size]).transpose(0, 2, 1, 3).reshape(2 * [size * size]) for grid in [board, board.T, blocks]: for line in grid: non_empty = line[line != empty_value] if not len(non_empty) == len(set(non_empty)): return False return True </code></pre> <p><strong>Stats:</strong></p> <pre><code>Runtime: 172 ms, faster than 5.19% of Python3 online submissions for Valid Sudoku. Memory Usage: 30.2 MB, less than 11.10% of Python3 online submissions for Valid Sudoku. </code></pre> <p><code>valid_sudoku.h</code></p> <pre><code>#ifndef LEETCODE_VALID_SUDOKU_H #define LEETCODE_VALID_SUDOKU_H #include &lt;string_view&gt; #include &lt;unordered_set&gt; bool sudoku_check_update(const size_t &amp;row, const size_t &amp;col, const char &amp;value, const int &amp;block_size, std::unordered_set&lt;std::string_view&gt; &amp;seen); bool sudoku_check(const std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board, const char &amp;empty_value = '.'); void test1(); #endif //LEETCODE_VALID_SUDOKU_H </code></pre> <p><code>valid_sudoku.cpp</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string_view&gt; #include &lt;cmath&gt; #include &lt;unordered_set&gt; bool sudoku_check_update(const size_t &amp;row, const size_t &amp;col, const char &amp;value, const int &amp;block_size, std::unordered_set&lt;std::string_view&gt; &amp;seen) { std::string_view r, c, b; r = &quot;0-&quot; + std::to_string(row) + value; c = &quot;1-&quot; + std::to_string(col) + value; b = &quot;2-&quot; + std::to_string(row / block_size) + std::to_string(col / block_size) + value; for (const auto &amp;seen_id: {r, c, b}) { if (seen.find(seen_id) != seen.end()) return false; seen.insert(seen_id); } return true; } bool sudoku_check(const std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board, const char &amp;empty_value = '.') { std::unordered_set&lt;std::string_view&gt; seen; const auto row_size = board.size(); const int block_size = std::sqrt(row_size); for (size_t row = 0; row &lt; row_size; ++row) { for (size_t col = 0; col &lt; row_size; ++col) { auto value = board[row][col]; if (value == empty_value) continue; if (!sudoku_check_update(row, col, value, block_size, seen)) return false; } } return true; } void test1() { std::vector&lt;std::vector&lt;char&gt;&gt; v = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'} }; std::cout &lt;&lt; sudoku_check(v); } </code></pre> <p><strong>Stats:</strong></p> <pre><code>Runtime: 48 ms, faster than 17.98% of C++ online submissions for Valid Sudoku. Memory Usage: 20.4 MB, less than 22.55% of C++ online submissions for Valid Sudoku. </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:50:14.850", "Id": "497050", "Score": "3", "body": "Based on https://codereview.meta.stackexchange.com/questions/10574/are-you-allowed-to-ask-for-reviews-of-the-same-program-written-in-two-languages and others - though this is on-topic, for higher-quality answers we encourage separate languages to be posted in separate questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:05:47.970", "Id": "497052", "Score": "0", "body": "@Reinderien I understand and get the point behind why you might encourage separating languages, in the dual-language posts, I tried as much as I could making both share similar logic in order for people reviewing my code to focus on the algorithm rather than language specific reviews except for c++ which I started learning recently and this is totally not the case for python. Therefore whenever 2 answers in future questions that you might consider as being not very similar in the logic / algorithm, please point them and I'll separate them if necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T16:15:50.340", "Id": "497056", "Score": "0", "body": "There are other reasons: I think it's more convenient for people that don't know one language to review the other and also these being programming exercises, they most probably won't contain more than a function or 2 max, if I separate python code, I might end up with a post with minimal to no critical points at all unless the algorithm is inefficient, which will apply for both languages. I'm avoiding to waste your time reading the same description, the same logic in 2 separate posts while most optimizations will likely apply to c++ and general performance. That's my opinion anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T03:18:34.277", "Id": "497133", "Score": "0", "body": "Consider however, two answerers who know only one of the two languages respectively. If they both give perfect answers, to whom do you award the checkmark?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T03:25:24.480", "Id": "497134", "Score": "0", "body": "@Schism to the one with a better review overall" } ]
[ { "body": "<p>Minor (and Python), but I personally find this to be a little confusing:</p>\n<pre class=\"lang-python prettyprint-override\"><code>if (value := board[row][col]) == empty_value:\n continue\nr = f'0{row}{value}'\nc = f'1{col}{value}'\nb = f'2{row // b_size}{col // b_size}{value}'\n</code></pre>\n<p>You're using an assignment expression to assign a value, but then only use it in the false case. I think this would be much cleaner by using a plain-old assignment statement:</p>\n<pre class=\"lang-python prettyprint-override\"><code>value = board[row][col]\nif value == empty_value:\n continue\nr = f'0{row}{value}'\nc = f'1{col}{value}'\nb = f'2{row // b_size}{col // b_size}{value}'\n</code></pre>\n<p>I don't think the line saved is worth burying the creation of a variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:20:34.983", "Id": "497035", "Score": "0", "body": "Yeah, I might be abusing the walrus operator, it's cool I guess but maybe not necessary. How about the algorithm? Any improvements you can think of?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:33:38.123", "Id": "497043", "Score": "2", "body": "I don't see anything glaring. Your use of strings for `r`, `c` and `b` seemed odd initially, but I guess they may actually be faster/more memory efficient than other container types. You may get a tiny boost by changing `seen.update({r, c, b})` into three separate `add` lines to avoid the creation of the intermediate set. Whether or not that'll make a noticeable difference though, idk." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:43:19.357", "Id": "497048", "Score": "2", "body": "@bullseye Actually, nvm that. On 100 million additions, it's only a difference of ~2 seconds between three `add`s and one `update`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T01:54:20.877", "Id": "497122", "Score": "0", "body": "they look italic to me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:10:09.267", "Id": "497197", "Score": "1", "body": "I added some `lang-python` tags to help the markdown tool correctly format the code. See https://codereview.stackexchange.com/editing-help#syntax-highlighting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:12:48.747", "Id": "497199", "Score": "0", "body": "Normally, it goes by the language tags on the question, but since this one is (correctly) tagged with both Python and C++, it got a bit confused and needed a bit of extra help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:13:58.667", "Id": "497211", "Score": "0", "body": "@Edward: `<!-- language-all: lang-python -->` still works, for a smaller edit." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:13:10.740", "Id": "252323", "ParentId": "252320", "Score": "6" } }, { "body": "<h2>C++</h2>\n<p>It's simpler, and possibly faster to pass small plain data types like <code>size_t</code> and <code>char</code> by value, not by reference. So we should have:</p>\n<pre><code>bool sudoku_check_update(size_t row, size_t col, char value, int block_size,\n std::unordered_set&lt;std::string_view&gt; &amp;seen)\n\nbool sudoku_check(const std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board,\n char empty_value = '.')\n</code></pre>\n<hr />\n<p>More importantly: <code>std::string_view</code> <strong>cannot</strong> be used for storing strings. It does not own the string, it is just a pointer and a size.</p>\n<p>In doing something like this:</p>\n<pre><code>std::string_view r = &quot;0-&quot; + std::to_string(row) + value;\n</code></pre>\n<p>... we construct a temporary <code>std::string</code> and then assign it to a <code>string_view</code>. However, the temporary string goes out of scope at the end of this line!</p>\n<blockquote>\n<p>It has passed on. This string is no more. It has ceased to be. It's\nexpired and gone to meet its maker. This is a late string. It's a\nstiff. Bereft of life it rests in peace. If we hadn't nailed it to a\n<code>std::string_view</code> it would be pushing up the daisies. It has run-down\nthe curtain and joined the choir invisible. This is an ex-string.</p>\n</blockquote>\n<p>In other words, it's undefined behaviour to try and use that <code>string_view</code>. So <code>r</code>, <code>c</code> and <code>b</code> need to be <code>std::string</code>s themselves. And <code>seen</code> should be a <code>std::unordered_set&lt;std::string&gt;</code>.</p>\n<hr />\n<p>Re. <code>std::string_view</code>:</p>\n<p><code>std::string_view</code> points to a range of characters in memory. These characters could be stored in a <code>std::string</code>, in a <code>std::array</code>, a <code>std::vector</code> or in a string-literal.</p>\n<p>By using <code>std::string_view</code> we get the same interface (finding, comparison, substring creation) irrespective of what that underlying storage is. So it's useful as a common language between these types.</p>\n<p>Since <code>std::string_view</code> doesn't own the characters, it does no memory allocation or copying itself. This makes it useful for things like parsing long text files - we can search and compare in substrings without doing the copying that <code>std::string</code> would do.</p>\n<p>The trade-off is that we have to ensure that the lifetime of the actual string in memory is longer than that of the <code>string_view</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:29:06.590", "Id": "497078", "Score": "0", "body": "I'm not sure of the use-cases of `string` vs `string_view` I learned in previous posts / what I understood is that using `string_view` might be better for performance reasons but it's still unclear to me why use one and not the other and vice versa. Same goes to using pointers vs using references but of course this might be out of the scope of my question, I'm just mentioning it because you brought it up. As I'm at the start of my learning c++ curve so, I might be asking questions because I have not found actual use cases yet in which they are a requirement rather than option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:39:52.130", "Id": "497080", "Score": "0", "body": "Also same goes for value vs reference, what I understand is passing large objects like vectors / arrays(not optional in this case) and containers in general are better passed by reference to avoid making unnecessary copies or maybe I need to modify a non-local container." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:53:38.607", "Id": "497083", "Score": "0", "body": "Added some details about `std::string_view`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:59:33.373", "Id": "497084", "Score": "0", "body": "Re. pass-by-value vs pass-by-reference: yep, that's correct. For small objects, it's simpler to pass by value. You can think of pass-by-reference as passing a pointer. If the object is the same size or smaller than a pointer, it's probably faster to just pass the object itself. In practice the speed depends on compiler settings / optimizations and machine architecture." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T18:26:26.883", "Id": "497086", "Score": "0", "body": "Thanks, let me rephrase after your edit: `string_view` is better passed by a higher level function that has the actual string but the initial declaration should be a `string`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:04:46.993", "Id": "252328", "ParentId": "252320", "Score": "4" } }, { "body": "<p>Here are some suggestions for how you might be able to improve your code.</p>\n<h1>C++ version</h1>\n<h2>Use all of the required <code>#include</code>s</h2>\n<p>The type <code>std::vector&lt;std::vector&lt;char&gt;&gt;</code> is used in the definition of <code>sudoku_check()</code> in the header file, but <code>#include &lt;vector&gt;</code> is missing from the list of includes there.</p>\n<h2>Minimize the interface</h2>\n<p>The <code>.h</code> file is a declaration of the <em>interface</em> to your software. The <code>.cpp</code> is the <em>implementation</em> of that interface. It is good design practice to minimize the interface to just that which is needed by outside programs. For that reason, I would remove the <code>sudoku_check_update()</code> and <code>test1()</code> functions and just use this:</p>\n<pre><code>#ifndef LEETCODE_VALID_SUDOKU_H\n#define LEETCODE_VALID_SUDOKU_H\n\n#include &lt;vector&gt;\n\nbool sudoku_check(const std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board,\n const char &amp;empty_value = '.');\n\n#endif //LEETCODE_VALID_SUDOKU_H\n</code></pre>\n<h2>The implementation should include the interface header</h2>\n<p>As the title of this sections states, the implementation should include the interface header. This assures that the interface and implementation match, and eliminates errors. If we do that in this case, we see that the default value for <code>empty_value</code> is declared twice. It should only be declared once in the header file.</p>\n<h2>Make local functions <code>static</code></h2>\n<p>With the smaller interface as advocated above, the <code>sudoku_check_update</code> function becomes an implementation detail used only within the <code>.cpp</code> file. For that reason, it should be made <code>static</code> so the compiler knows that it's safe to inline the function.</p>\n<p>The keyword <code>static</code> when used with a function declaration specifies that the <em>linkage</em> is internal. In other words it means that nothing outside of that file can access the function. This is useful for the compiler to know because, for instance, if a <code>static</code> function is used only once and/or is small, the compiler has the option of putting the code inline. That is, instead of the usual assembly language <code>call</code>...<code>ret</code> instructions to jump to a subroutine and return from it, the compiler can simply put the code for the function directly at that location, saving the computational cost of those instructions and helping to assure cache predictions are correct (because normally cache takes advantage of <a href=\"https://en.wikipedia.org/wiki/Locality_of_reference\" rel=\"nofollow noreferrer\">locality of reference</a>.)</p>\n<p>Also read about <a href=\"https://en.cppreference.com/w/cpp/language/storage_duration\" rel=\"nofollow noreferrer\">storage class specifiers</a> to better understand what <code>static</code> does in other contexts and more generally <a href=\"https://en.cppreference.com/w/cpp/language/declarations\" rel=\"nofollow noreferrer\">declaration specifiers</a> for explanations of <code>constexpr</code> and more.</p>\n<h2>Fix the bug!</h2>\n<p>The code currently uses <code>string_view</code> inappropriately. A <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> is essentially a pointer to a string that exists. But your strings are composed and deleted dynamically, so this is an invalid use of <code>std::string_view</code>. If you replace all instances of <code>string_view</code> with <code>string</code>, the program works.</p>\n<p>Memory problems like this and concurrency errors are among the most difficult problems for programmers to detect and correct. As you gain more experience you will find that your ability to spot these problems and avoid them come more reflexively. There are many approaches to finding such errors. See <a href=\"https://codereview.stackexchange.com/questions/233625/leak-detection-simple-class/233637#233637\">Leak detection simple class</a> for some of them.</p>\n<h2>Write better test functions</h2>\n<p>The bug mentioned above was easily discovered by calling the function several times with varying inputs. Perhaps you already had a more extensive array of test functions, but if not, I highly recommend creating and applying them.</p>\n<h2>Use efficient data structures</h2>\n<p>If the goal of this code is to be efficient in terms of both run time and memory, there are a lot of improvements that could be made. First, the data structure <code>std::unordered_set&lt;std::string_view&gt;</code> is not optimal. Whenever we are working on a performance optimization, it's useful to measure. So I wrote a very simple test program based on my <a href=\"https://codereview.stackexchange.com/questions/58055/stopwatch-template\">stopwatch template</a>. It's here:</p>\n<pre><code>#include &quot;valid_sudoku.h&quot;\n#include &quot;stopwatch.h&quot;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;string&gt;\n\nint main(int argc, char* argv[]) {\n std::vector&lt;std::vector&lt;char&gt;&gt; v = {\n {'5', '3', '.', '.', '7', '.', '.', '.', '.'},\n {'6', '.', '.', '1', '9', '5', '.', '.', '.'},\n {'.', '9', '8', '.', '.', '.', '.', '6', '.'},\n {'8', '.', '.', '.', '6', '.', '.', '.', '3'},\n {'4', '.', '.', '8', '.', '3', '.', '.', '1'},\n {'7', '.', '.', '.', '2', '.', '.', '.', '6'},\n {'.', '6', '.', '.', '.', '.', '2', '8', '.'},\n {'.', '.', '.', '4', '1', '9', '.', '.', '5'},\n {'.', '.', '.', '.', '8', '.', '.', '7', '9'}\n };\n if (argc != 2) {\n std::cout &lt;&lt; &quot;Usage: &quot; &lt;&lt; argv[0] &lt;&lt; &quot; num_trials\\n&quot;;\n return 1;\n }\n auto iterations = std::stoul(argv[1]);\n\n Stopwatch&lt;&gt; timer{};\n\n bool valid{true};\n for (auto i{iterations}; i; --i) {\n valid &amp;= sudoku_check(v);\n }\n\n auto elapsed{timer.stop()};\n if (!valid) {\n std::cout &lt;&lt; &quot;The program failed!\\n&quot;;\n return 2;\n }\n std::cout &lt;&lt; iterations &lt;&lt; &quot; trials took &quot; &lt;&lt; elapsed &lt;&lt; &quot; microseconds\\n&quot;\n &quot; for an average of &quot; &lt;&lt; elapsed/iterations &lt;&lt; &quot; microseconds/trial\\n&quot;;\n}\n</code></pre>\n<p>When I run this on my machine with 1,000,000 trials, (with the bug noted above fixed as described) here's the result I get:</p>\n<blockquote>\n<p>1000000 trials took 1.44351e+07 microseconds\nfor an average of 14.4351 microseconds/trial</p>\n</blockquote>\n<p>Now let's think of a more efficient data structure. Instead of an <code>unordered_set</code>, we might use a set of fixed arrays. There are nine rows, nine columns and nine subsquares. Each of those either contains a number or it doesn't. To me, that suggests we could use a object like this:</p>\n<pre><code>using SeenType = std::array&lt;std::array&lt;std::array&lt;bool, 9&gt;, 9&gt;, 3&gt;;\n</code></pre>\n<p>This contains the 3 types (rows, columns, subsquares) and within each, 9 collections of 9 bits; one bit for each number. Let's rewrite the function to use this:</p>\n<pre><code>static bool sudoku_check_update(std::size_t row, std::size_t col, \n char value, SeenType &amp;seen) {\n static constexpr std::size_t block_size{3};\n static_assert(block_size * block_size == row_size, &quot;block_size must be the square root of row_size&quot;);\n const std::size_t block = col / block_size + block_size * (row / block_size);\n std::size_t dim{0};\n value -= '1'; // adjust from digits '1'-'9' to indices 0-8.\n for (const auto &amp;seen_id: {row, col, block}) {\n if (seen[dim][seen_id][value])\n return false;\n seen[dim][seen_id][value] = true;\n ++dim;\n }\n return true;\n}\n</code></pre>\n<p>Now re-run the program with a million trial as before:</p>\n<blockquote>\n<p>1000000 trials took 562153 microseconds\nfor an average of 0.562153 microseconds/trial</p>\n</blockquote>\n<p>So that one change made things <strong>25x faster</strong>. We could also use the fact that the dimensions are known to use a <code>std::array&lt;std::array&lt;char, 9&gt;, 9&gt;</code> instead of the vectors and use <code>constexpr</code> for those dimensions. Doing that change as well, we get this:</p>\n<blockquote>\n<p>1000000 trials took 160808 microseconds\nfor an average of 0.160808 microseconds/trial</p>\n</blockquote>\n<p>So now it is <strong>90x faster</strong>.</p>\n<h2>Prefer <code>{}</code> style initializations</h2>\n<p>You may notice that the code I write tends to use the <code>{}</code>-style of initialization. There are several reasons for this, including the fact that when you see it, it is always an initialization and can't be mistaken for a function call. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es23-prefer-the--initializer-syntax\" rel=\"nofollow noreferrer\">ES.23</a> for more details.</p>\n<h2>Pass values rather than references for short data types</h2>\n<p>Rather than passing <code>const size_t &amp;col</code> or <code>const char&amp; value</code>, it's generally better to pass those by value. This is often advantageous because the pointer is likely to be longer than the thing it's pointing to and because it allows the elimination of an indirection and memory lookup.</p>\n<h2>Move calculations from runtime to compile time where practical</h2>\n<p>It probably doesn't take up a lot of time, but this line is not as fast as it could be:</p>\n<pre><code>const int block_size = std::sqrt(row_size);\n</code></pre>\n<p>What this does is to convert <code>row_size</code> to a <code>double</code>, invokes the floating-point <code>sqrt</code> function and the converts the <code>double</code> back to an <code>int</code>. By contrast, we could just write this:</p>\n<pre><code>constexpr std::size_t block_size{3};\n</code></pre>\n<p>Now it takes no time at all at runtime because the value is known at compile time. It also eliminates having to pass the value and, as above, its definition can be put the only place it's actually needed, which is within the <code>sudoku_check_update</code> function.</p>\n<p>Generally, we prefer to move things from runtime to compile time for three reasons:</p>\n<ol>\n<li>programs are generally run more times than they are compiled, so we optimize for the more common occurrence</li>\n<li>the sooner we detect bugs, the cheaper and easier they are to fix</li>\n<li>it tends to make software smaller and, internally, simpler which improves loading speed, cache performance and simpler software tends to improve quality</li>\n</ol>\n<h1>Python version</h1>\n<h2>Avoid <code>continue</code> by restructuring the loop</h2>\n<p>There's nothing intrinsically wrong with your use of the walrus operator, but there seems to be little reason not to invert the sense of the comparison and simply process the update rather than using <code>continue</code>. It does not affect performance, but aids the human reader of the code in understanding program flow. I tend to put early &quot;bailout&quot; clauses early in a function to quickly reject invalid conditions, but avoid <code>continue</code> in loops; ultimately it's a question of readability and style in either C++ or Python.</p>\n<h2>Use more efficient data structures</h2>\n<p>What was true in C++ also works in Python. We can use the same ideas and speed up the code by a factor of 6:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_valid(board, empty_value='.', b_size=3):\n size = b_size * b_size\n seen = [[(size * [False]) for _ in range(size)] for _ in range(3)]\n for row in range(size):\n for col in range(size):\n if (value := board[row][col]) != empty_value:\n block = col // b_size + b_size * (row // b_size)\n dim = 0\n value = int(value) - 1\n for seen_id in [row, col, block]:\n if seen[dim][seen_id][value]:\n return False\n seen[dim][seen_id][value] = True\n dim += 1\n return True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T19:31:53.133", "Id": "497091", "Score": "0", "body": "Thanks, that's a very helpful review, I'll check and let you know if I have any questions. Also there is my other question [here](https://codereview.stackexchange.com/questions/252311/leetcode-longest-valid-parentheses) (if you have the time of course, if not, there are many points you mentioned here that would apply there as well)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:16:36.153", "Id": "497110", "Score": "0", "body": "@Edward, In your python version should the formula for `block` use integer division? `block = col // b_size + b_size * (row // b_size)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T01:09:41.050", "Id": "497117", "Score": "0", "body": "@RootTwo: Yes, you're right. I've fixed my answer now. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T02:32:59.810", "Id": "497131", "Score": "0", "body": "Edward there is no `++` in python, I think you meant `+= 1 ` same goes for semicolons, probably out of habit, but not required though. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T02:37:18.203", "Id": "497132", "Score": "1", "body": "@bullseye: Ha! You're absolutely correct. What was I saying about writing test code? :) I've fixed my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T10:55:00.090", "Id": "497149", "Score": "0", "body": "@Edward I'm currently going through your review and I have a few questions: 1) What is the meaning of *the function is to be made static so the compiler knows that it's safe to inline the function* I get your point behind `sudoku_check_update()` being an implementation detail and not being part of the interface, what I don't get is what is the significance of making it a static function probably because I don't understand what inlining functions is. 2) Difference between initialization in this form `auto i{iterations}` and `auto i = iterations`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:26:14.880", "Id": "497152", "Score": "0", "body": "@Edward continuing - 2) what I understand is the first `auto i{iterations}` is C style initialization but is there any difference between both other than style? 3) Why does the `string_view` bug impact performance rather than throw an error / break execution? 4) `static constexpr std::size_t block_size{3};` what does `static constexpr` do? the part that I did not get is when to determine moving calculations from runtime to compile time? or the other way around" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:26:33.010", "Id": "497153", "Score": "0", "body": "@Edward And finally in python: I used `continue` to avoid over nesting (just for readability), does it affect performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:53:48.787", "Id": "497155", "Score": "0", "body": "For C++: avoid nested vectors (and arrays) if possible, use one-dimensional vector and replace nested `bool` arrays with `std::bitset`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:58:56.013", "Id": "497195", "Score": "1", "body": "@bullseye: I've updated my answer to try to answer all of your questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:01:24.317", "Id": "497196", "Score": "0", "body": "@valsaysReinstateMonica: Normally, I'd agree with your advice, but in this case I tried it and found that the version using `std::bitset` and a single flat `array` was about 6% slower on my machine with my compiler. Machine is Intel i7 @ 3.40GHz running Fedora Linux and compiler is `gcc` 10.2.1 with -O2 optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:36:30.647", "Id": "497202", "Score": "0", "body": "@Edward thanks, that totally answers my concerns" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T19:14:26.477", "Id": "252338", "ParentId": "252320", "Score": "8" } } ]
{ "AcceptedAnswerId": "252338", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T14:24:57.947", "Id": "252320", "Score": "7", "Tags": [ "python", "c++", "programming-challenge" ], "Title": "Leetcode valid sudoku" }
252320
<p>This function takes a list/array of booleans and converts them to an array that counts the number of either True/False values found next to each other.</p> <p>I'd like to see this optimized for performance. It's not too slow, but I do use multiple loops with embedded if-else statements, I'm wondering if they're absolutely necessary.</p> <pre><code>import numpy as np x = np.random.uniform(1,100,100) b = x &gt; x.mean() #function start, input is b endarray = [] count = 0 instance = True while True: subarray = 0 while True: if count &gt;= len(b): endarray.append(subarray) break if b[count] == instance: subarray += 1 count += 1 else: endarray.append(subarray) instance = not instance break if count &gt;= len(b): break if len(endarray) % 2 != 0: endarray = np.append(endarray, 0) else: endarray = np.asarray(endarray) endarray = endarray.reshape(-1,2) </code></pre> <p>The output is a Nx2 array, where the left-hand values are always a count of Trues, and the right-hand values are always a count of Falses.</p> <p>After a sequence of False values are no longer continuous(a True value pops up), the next count of True values begin, and vice versa.</p> <h3>Example input</h3> <pre><code>b Out[31]: array([ True, True, True, False, True, True, True, True, False, False, True, False, False, True, False, False, False, False, True, False, False, False, True, True, True, True, False, False, True, False, False, False, False, False, False, True, True, False, True, True, False, False, True, False, False, True, False, False, True, False, True, False, True, False, True, True, True, False, True, False, True, True, True, True, False, False, True, False, True, True, True, True, True, True, False, True, True, False, True, True, False, False, True, False, True, False, False, True, True, True, True, False, False, False, False, False, True, True, True, True]) </code></pre> <h3>Example output</h3> <pre><code>endarray Out[32]: array([[3, 1], [4, 2], [1, 2], [1, 4], [1, 3], [4, 2], [1, 6], [2, 1], [2, 2], [1, 2], [1, 2], [1, 1], [1, 1], [1, 1], [3, 1], [1, 1], [4, 2], [1, 1], [6, 1], [2, 1], [2, 2], [1, 1], [1, 2], [4, 5], [4, 0]]) </code></pre> <p>Edit: I wanted to add an updated version of this code, the one in the answer below is not technically correct in all regards. But this was entirely derived from it:</p> <pre><code>m = np.append(b[0], np.diff(b)) _, c = np.unique(m.cumsum(), return_index=True) out = np.diff(np.append(c, len(b))) if b[0] == False: out = np.append(0, out) if len(out) % 2: out = np.append(out, 0) out = out.reshape(-1, 2) </code></pre>
[]
[ { "body": "<h3>Using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a></h3>\n<p>What you are looking for is <code>itertools.groupby</code>. When there is an odd number of groups then we use <code>try-except</code> block here.</p>\n<pre><code>from itertools import groupby\n\nget_grp_len = lambda grp: len([*grp])\n\n\ndef transform(b):\n if len(b) == 0: # if not b wouldn't work since your `b` is ndarray\n return []\n it = groupby(b)\n out = []\n for _, grp in it:\n try:\n t_size = get_grp_len(grp)\n f_size = get_grp_len(next(it)[1])\n out.append([t_size, f_size])\n except StopIteration:\n out.append([t_size, 0])\n return out\n\n\nprint(transform(b)) # `b` taken from the question itself.\n# same output as expected output posted in question.\n</code></pre>\n<h3><a href=\"https://numpy.org/doc/stable/\" rel=\"nofollow noreferrer\"><code>NumPy</code></a> has a lot of vectorized operations</h3>\n<p><code>NumPy</code> has many vectorized operations, you have to find the correct ones. Not an expert but the below approach should do good.</p>\n<p>The idea here is to find the index of the first value from each group and then take the difference.</p>\n<ul>\n<li>We check if <em>i</em>th element is not equal to <em>i+1</em>th element.</li>\n<li>Now use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.ndarray.cumsum.html#:%7E:text=Return%20the%20cumulative%20sum%20of%20the%20elements%20along%20the%20given%20axis.\" rel=\"nofollow noreferrer\"><code>np.ndarray.cumsum</code></a> to give each group a unique sequential number.</li>\n<li>Then use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.unique.html\" rel=\"nofollow noreferrer\"><code>np.unique</code></a> to get first index of value from each group.</li>\n<li>Find the difference between <em>i+1</em>th value and <em>i</em>th to get size of each grp. We can use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.diff.html\" rel=\"nofollow noreferrer\"><code>np.diff</code></a></li>\n</ul>\n<hr />\n<pre><code>m = b != (np.r_[np.nan, b[:-1]]) \n_, c = np.unique(m.cumsum(), return_index=True)\n#print(c)\n# array([ 0, 3, 4, 8, 10, 11, 13, 14, 18, 19, 22, 26, 28, 29, 35, 37, 38,\n# 40, 42, 43, 45, 46, 48, 49, 50, 51, 52, 53, 54, 57, 58, 59, 60, 64,\n# 66, 67, 68, 74, 75, 77, 78, 80, 82, 83, 84, 85, 87, 91, 96])\n\n# np.unique gives the index of the first occurrence, our `b` len is 100\n# and `c` stopped at 96. we need to add the last index + 1 to it.\n\nout = np.diff(np.r_[c, len(b)])\n\n# Now, reshape your array, if it's of odd length add a 0 at end.\nif len(out) % 2:\n out = np.r_[out, 0].reshape(-1, 2)\nout = out.reshape(-1, 2)\nprint(out)\n# same output mentioned in the question.\n</code></pre>\n<h3>Using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/index.html\" rel=\"nofollow noreferrer\"><code>Pandas</code></a>'s <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.groupby.html\" rel=\"nofollow noreferrer\"><code>GroupBy</code></a></h3>\n<p>A lot of times <code>pandas</code> and <code>NumPy</code> are used together so might as well post <code>pandas</code> code too.</p>\n<pre><code>import pandas as pd\ns = pd.Series(b)\ng = s.ne(s.shift()).cumsum()\nout = s.groupby(g).size().to_numpy()\n# repeat same step as we did in above solution add a 0 if len is odd.\n\nif len(out)%2:\n out = np.r_[out, 0].reshape(-1, 2)\nout = out.reshape(-1, 2)\nprint(out)\n</code></pre>\n<hr />\n<h3>Code Review</h3>\n<p>Everything's good as far as I can see, well-named variables, proper indentation but too many <code>if</code> :p</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T20:57:30.563", "Id": "497096", "Score": "1", "body": "nicely done! The numpy code is ~3x faster than what I made. The `if` statement in the numpy code also needs to be reversed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T04:28:49.517", "Id": "497137", "Score": "0", "body": "@Estif `np.r_` is written in pure python to make it a little faster replace `np.r_` with `np.hstack`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T21:02:21.697", "Id": "497246", "Score": "0", "body": "I believe `np.append` is actually a bit faster in this case" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T18:30:54.497", "Id": "252334", "ParentId": "252321", "Score": "2" } } ]
{ "AcceptedAnswerId": "252334", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T14:55:19.790", "Id": "252321", "Score": "4", "Tags": [ "python", "numpy" ], "Title": "Counting Sequential Booleans" }
252321
<p><strong>Background</strong> <br /> I am currently participating in a tic-tac-toe coding challenge. During their move, each participant is given the board state and their team, X or O. The blank board is: <br /> <code>[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]</code><br /> With 'X' and 'O' being added to the board, for example: <br /> <code>[[' ',' ',' '],[' ','X',' '],[' ','O',' ']]</code><br /> I have developed a minimax algorithm with alpha-beta pruning in <strong>Python 2.7</strong> and it plays perfectly (Please see code).<br /> Link to challenge rules: <a href="https://ccpc.codecraftworks.com/python" rel="nofollow noreferrer">https://ccpc.codecraftworks.com/python</a></p> <p><strong>Problem</strong><br /> The algorithm will always win or tie. In the event of a tie, the winner is determined by the computation time. I need to decrease the <strong>average time taken per move</strong> from 0.195 seconds to less than 500,000 nanoseconds (0.0005 seconds)</p> <p><strong>Possible Reasons for the Problem</strong></p> <ol> <li>Incorrect implementation of minimax algorithm</li> <li>Incorrect implementation of alpha beta pruning.</li> </ol> <p><strong>Possible Solutions</strong><br /> I have tried to separate the min and max functions and apply them separately, however that didn't work. I searched stack overflow for other possible ways to decrease computation time in my program, but I couldn't find anything.</p> <p><strong>Code</strong><br /> Note 1: getGameState(), getTeam(), and submitMove(row, col) are predefined functions provided by the back end of the coding challenge . You can test the code by uploading the file here: <a href="https://ccpc.codecraftworks.com/" rel="nofollow noreferrer">https://ccpc.codecraftworks.com/</a></p> <pre><code>team = getTeam() value_dict = { &quot;X&quot;: 1, &quot;tie&quot;: 0, &quot;O&quot;: -1 } def winner(board): for i in range(len(board)): if board[i][0] == board[i][1] and board[i][1] == board[i][2]: if board[i][0] == &quot;X&quot;: return &quot;X&quot; if board[i][0] == &quot;O&quot;: return &quot;O&quot; for i in range(len(board[0])): if board[0][i] == board[1][i] and board[1][i] == board[2][i]: if board[0][i] == &quot;X&quot;: return &quot;X&quot; if board[0][i] == &quot;O&quot;: return &quot;O&quot; if board[0][0] == board[1][1] and board[1][1] == board[2][2]: if board[0][0] == &quot;X&quot;: return &quot;X&quot; if board[0][0] == &quot;O&quot;: return &quot;O&quot; if board[2][0] == board[1][1] and board[1][1] == board[0][2]: if board[2][0] == &quot;X&quot;: return &quot;X&quot; if board[2][0] == &quot;O&quot;: return &quot;O&quot; for row in board: for cell in row: if cell == ' ': return &quot;continue&quot; return &quot;tie&quot; def minimax(board, depth, is_max, n, alpha = float('-inf'), beta = float('inf')): check_winner = winner(board) if check_winner != &quot;continue&quot;: return value_dict[check_winner] if is_max: best_score = float('-inf') for i in range(n): for j in range(n): if board[i][j] == &quot; &quot;: board[i][j] = &quot;X&quot; score = minimax(board, depth+1, False, n, alpha, beta) board[i][j] = &quot; &quot; best_score = max(score, best_score) alpha = max(alpha, score) if beta &gt;= alpha: pass return best_score else: best_score = float('inf') for i in range(n): for j in range(n): if board[i][j] == &quot; &quot;: board[i][j] = &quot;O&quot; score = minimax(board, depth+1, True,n, alpha, beta) board[i][j] = &quot; &quot; best_score = min(score, best_score) beta = min(beta, score) if alpha &gt;= beta: pass return best_score def calcMove(): board = getGameState() if team ==&quot;X&quot;: score = - 2 x = -1 y = -1 for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == ' ': board[i][j] = &quot;X&quot; curr_score = minimax(board,0,False, len(board)) board[i][j] = ' ' if curr_score &gt; score: score = curr_score x = i y = j elif team ==&quot;O&quot;: score = 2 x = 1 y = 1 for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == ' ': board[i][j] = &quot;O&quot; curr_score = minimax(board,0,True, len(board)) board[i][j] = ' ' if curr_score &lt; score: score = curr_score x = i y = j submitMove(x,y) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T20:15:24.927", "Id": "497094", "Score": "1", "body": "Is there anything in the rule that prevents a lookup table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T21:28:26.167", "Id": "497098", "Score": "0", "body": "There is not, that is why I made the `value_dict` lookup table at the beginning of the program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:27:08.210", "Id": "497113", "Score": "0", "body": "Is that average time of yours for when you start the game or for when the opponent starts the game or did you average both cases? (And same question about that average time of the opponent.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:43:36.707", "Id": "497114", "Score": "1", "body": "Geez again... out of curiosity, I just submitted a solution that always just simply makes a random possible move. And ... I won! So they don't even play perfectly. And it even only took me four moves. At the end they report my average time as \"1063544\". Yeah, without unit. And my individual times were 1829389, 2224877, 1873029, and 1517514 ns. How come my average is much lower than all of those, you ask? Because they divided the sum by 7. And there's pretty much no way my solution took anywhere near that much time unless they're running it on a pocket calculator. OMG that site is so bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:51:07.960", "Id": "497115", "Score": "0", "body": "Indeed, the site has some weird ways of calculating the average time. I just used the time at the very bottom of the \"console window\" as the average time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T01:10:21.077", "Id": "497118", "Score": "0", "body": "But was it when you started the game, when the opponent started the game, or did you average both cases?" } ]
[ { "body": "<p>Here's a simple way to make it about 10 times faster <em>and</em> better: If the board is empty, make a <em>random</em> move instead of your search.</p>\n<p>It's faster because the trees for subsequent moves are smaller than for the first move. And it's better because... well, if your perfect player plays against another perfect player, then it doesn't matter. But if your opponent is <em>not</em> perfect, then you'll still have to come across its weakness if you want to win. And you're more likely to come across it if you don't always do the same.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T23:45:45.633", "Id": "497105", "Score": "0", "body": "I tried this, and it decreased the first move's time by a lot. I then made the program submitMove(0,0) without any randomness, and it decreased the time further. However, the average time with this implemented is still greater than the average time of the opponent. I gave this answer an upvote, and will give accepted answer, if there are no other answers. Thanks for the help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T23:51:06.863", "Id": "497106", "Score": "0", "body": "Could I apply heuristic pruning?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:19:44.570", "Id": "497111", "Score": "0", "body": "@DapperDuck Don't know about heuristic pruning, it's been a long time since I last wrote some alpha-beta minimax. If you want a very fast solution, maybe try [this strategy](https://en.wikipedia.org/wiki/Tic-tac-toe#Strategy)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T00:24:44.877", "Id": "497112", "Score": "0", "body": "Oh and I'd suggest to really wait for other answers, as I'm not really reviewing much." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T22:45:28.683", "Id": "252342", "ParentId": "252322", "Score": "3" } }, { "body": "<p>There are a few thing you can do to speed up your code.</p>\n<h1>len(...)</h1>\n<p>There are several places where you have loops like:</p>\n<pre><code> for i in range(len(board)):\n for j in range(len(board[0])):\n</code></pre>\n<p>It looks like you are trying to write code which will work for a variety of board sizes, like 3x3, 4x4, 3x4, 7x9. But ...</p>\n<pre><code>if board[0][0] == board[1][1] and board[1][1] == board[2][2]:\n</code></pre>\n<p>... your board will only ever be 3x3, and you've got that hard-coded in your <code>winner()</code> logic. Accept that you aren't writing general purpose code, and use the number <code>3</code>, or a constant <code>N</code> defined as 3. You'll save the overhead of a function lookup, function call, and argument passing.</p>\n<h1>Chained comparison operators</h1>\n<pre><code> if board[i][0] == board[i][1] and board[i][1] == board[i][2]:\n</code></pre>\n<p>This looks up the value of <code>board[i][1]</code> at least once, and possibly twice. It is not going to change, so there is no need to look up the value for the second comparison. Simply use Python's <a href=\"https://docs.python.org/2.7/library/stdtypes.html#comparisons\" rel=\"nofollow noreferrer\">chained comparison operators</a>:</p>\n<pre><code> if board[i][0] == board[i][1] == board[i][2]:\n</code></pre>\n<h1>Repeated lookups</h1>\n<pre><code>for i in range(len(board)):\n if board[i][0] == board[i][1] and board[i][1] == board[i][2]:\n</code></pre>\n<p>How many times is <code>board[i]</code> looked up in this loop? Maybe four times? In order to do that, <code>board</code> must be looked up in the local dictionary, then <code>i</code> must be looked up in the local dictionary, and then <code>board[i]</code> must be evaluated. Again, it doesn't change.</p>\n<p>When you have a loop <code>for idx in range(len(thing)):</code> and you only ever use <code>thing[idx]</code> inside the loop, you're better off looping over the object itself:</p>\n<pre><code>for row in board:\n if row[0] == row[1] == row[2]:\n</code></pre>\n<h1>Don't test for return values, then return those values:</h1>\n<p>You've determined that all three cells contain the same value. Now, if the first cell is an 'X', you return an 'X'. Otherwise, if the first cell is an 'O' you return an 'O':</p>\n<pre><code> if board[i][0] == &quot;X&quot;:\n return &quot;X&quot;\n if board[i][0] == &quot;O&quot;:\n return &quot;O&quot;\n</code></pre>\n<p>That is a lot of indexing, lookups, and comparisons. Instead, how about:</p>\n<pre><code> if row[0] != ' ':\n return row[0]\n</code></pre>\n<h1>Remove unnecessary work</h1>\n<p>Consider:</p>\n<pre><code> board[i][j] = &quot;X&quot;\n curr_score = minimax(board,0,False, len(board))\n board[i][j] = ' '\n</code></pre>\n<p>and</p>\n<pre><code>def minimax(board, depth, is_max, n, alpha = float('-inf'), beta = float('inf')):\n check_winner = winner(board)\n ...\n</code></pre>\n<p>The <code>winner(board)</code> function checks all 3 rows, all 3 columns, and both diagonals to determine the winner, if there is one.</p>\n<p>If the move <code>board[i][j] = &quot;X&quot;</code> is at <code>i=0</code>, <code>j=1</code>, it is only necessary to check 1 row (row 0) and one column (column 1); checking all 3 is wasted effort. If <code>i == j</code>, then the down diagonal needs to be checked. If <code>i + j == 2</code>, then the up diagonal needs to be checked. You've gone from exhaustive 8 directions to check down to 2, 3, or 4. That should save you a bit of time. But you'd have to pass the location into the minimax function.</p>\n<h1>Useless code</h1>\n<p>This code does nothing.</p>\n<pre><code> if beta &gt;= alpha:\n pass\n</code></pre>\n<p>If the condition is true, a statement which does nothing is executed. In other words, time got wasted. You probably meant to code something else...</p>\n<h1>PEP 8</h1>\n<p>The <a href=\"https://pep8.org\" rel=\"nofollow noreferrer\">Style Guide for Python</a> enumerates coding conventions that all Python programs should follow.</p>\n<p>These include:</p>\n<ul>\n<li>One space after each comma (violated in <code>minimax(board,0,False, len(board))</code>)</li>\n<li><code>snake_case</code> should be used for variable and function names. <code>calcMove()</code> violates this. (<code>getGameState()</code>, <code>getTeam()</code>, and <code>submitMove(row, col)</code> also violate this, but as you've pointed out, they're predefined from the coding challenge, so they're excused.). Oh, never mind, <code>calcMove()</code> is not predefined, but it a required name for the challenge framework.</li>\n</ul>\n<h1>Available moves</h1>\n<p>You are spending a lot of time searching for available moves. You search the entire board looking for a space where you can make a move. When you find one, you tentatively make a move, and call <code>minimax</code>, which again searches the entire board looking for a space where you can make a move. With 9 possible moves, this translates to <span class=\"math-container\">\\$9^9 = 387,420,489\\$</span> checks for whether a cell is a space!</p>\n<p>Instead, in <code>calcMove</code>, you could build a list of available moves:</p>\n<pre><code>valid_moves = [(i, j) for i in range(3) for j in range(3) if board[i][j] == ' ']\n</code></pre>\n<p>With this list of moves, you would select one, and pass a copy of that list of valid moves to minimax with that move removed. Then you would select the next one, and again pass a copy of that list of moves to minimax with this new move removed instead, and so on. The minimax function would do the same: for each move in the list of valid moves, make that tentative move and pass a copy of the valid moves without the current move. For 9 possible moves, this translates to <span class=\"math-container\">\\$9*8*7*6*5*4*3*2*1 = 9! = 362,880\\$</span> move tests, an improvement of 1000-fold over the exhaustive enumeration of each move and testing for the space.</p>\n<h1>Tie</h1>\n<p>With the <code>valid_moves</code> list, checking for no valid removes remaining is simply <code>len(valid_moves) == 0</code>, or equivalently, <code>not valid_moves</code>. No need to search all 9 cells looking for a space.</p>\n<h1>Obvious moves</h1>\n<p>Similarly, <code>len(valid_moves) == 9</code> means you’ve got an empty board, and can make a fast good move, like claiming the centre spot, or picking a random corner.</p>\n<p>Also, <code>len(valid_moves) == 8</code> would mean your opponent has made the first move. If <code>board[1][1] == ' '</code> is still available, it is probably your best move. If their first move was the centre, then you could pick a random corner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T16:08:55.073", "Id": "497204", "Score": "0", "body": "It's not \\$9^9\\$ but less than \\$9!*9\\$ (less because of early wins)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T16:32:48.063", "Id": "497206", "Score": "0", "body": "@HeapOverflow D'oh. I mucked that up, didn't I? I should have questioned that 1000-fold improvement. A 9-fold improvement (9! * 9 / 9!) would be closer to the truth. I'll have to run a test to get the actual numbers, and correct my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T19:19:20.977", "Id": "497452", "Score": "0", "body": "Thanks for your answer! This was really helpful!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T06:02:52.420", "Id": "252354", "ParentId": "252322", "Score": "2" } }, { "body": "<h1>Use numbers</h1>\n<p>Comparing strings is slow and expensive, numbers are what computers love the most. Comparing numbers will much <strong>much</strong> faster in this case. So instead of using <code>X</code> and <code>O</code>, use <code>1</code> and <code>0</code>.</p>\n<p>I prefer using an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> in scenarios like this.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Player(Enum):\n o = 0\n x = 1\n\nPlayer.x.value == 1\nPlayer.o.value == 0\n</code></pre>\n<p>The same applies to your return values, don't use <code>tie</code> and <code>continue</code>, assign them to numbers, and use them instead. Again, the comparison of strings is slow and expensive. Comparison of integers is a single instruction.</p>\n<p>If you are getting the board in the form of a string array, I suggest you convert it to an integer one.</p>\n<hr />\n<h1>Optimzing <code>winner()</code></h1>\n<p>Your original code</p>\n<pre class=\"lang-py prettyprint-override\"><code>def winner(board):\n for i in range(len(board)):\n if board[i][0] == board[i][1] and board[i][1] == board[i][2]:\n if board[i][0] == &quot;X&quot;:\n return &quot;X&quot;\n if board[i][0] == &quot;O&quot;:\n return &quot;O&quot;\n\n for i in range(len(board[0])):\n if board[0][i] == board[1][i] and board[1][i] == board[2][i]:\n if board[0][i] == &quot;X&quot;:\n return &quot;X&quot;\n if board[0][i] == &quot;O&quot;:\n return &quot;O&quot;\n\n if board[0][0] == board[1][1] and board[1][1] == board[2][2]:\n if board[0][0] == &quot;X&quot;:\n return &quot;X&quot;\n if board[0][0] == &quot;O&quot;:\n return &quot;O&quot;\n\n if board[2][0] == board[1][1] and board[1][1] == board[0][2]:\n if board[2][0] == &quot;X&quot;:\n return &quot;X&quot;\n if board[2][0] == &quot;O&quot;:\n return &quot;O&quot;\n\n for row in board:\n for cell in row:\n if cell == ' ':\n return &quot;continue&quot;\n return &quot;tie&quot;\n</code></pre>\n<h2>Algorithm for checking winner</h2>\n<p>I'm afraid that this will disappoint you, but hard-coding the 8 directions is going to be significantly faster.</p>\n<p>Following the previous two suggestions, which is two use a single-dimensional array of <strong>numbers</strong> to represent the board</p>\n<pre class=\"lang-py prettyprint-override\"><code>def winner(board):\n if board[0][0] == board[0][1] == board[0][2] != Color.empty.value: return board[0][0]\n if board[1][0] == board[1][1] == board[1][2] != Color.empty.value: return board[1][0]\n if board[2][0] == board[2][1] == board[2][2] != Color.empty.value: return board[2][0]\n if board[0][0] == board[1][0] == board[2][0] != Color.empty.value: return board[0][0]\n if board[0][1] == board[1][1] == board[2][2] != Color.empty.value: return board[0][1]\n if board[0][2] == board[1][2] == board[2][2] != Color.empty.value: return board[0][2]\n if board[0][0] == board[1][1] == board[2][2] != Color.empty.value: return board[0][0]\n if board[0][2] == board[1][1] == board[2][0] != Color.empty.value: return board[0][2]\n\n \n for row in board:\n for elem in row:\n if elem == Color.empty.value: return None\n\n return TIE \n</code></pre>\n<h2>Benchmarks</h2>\n<p>I'll measure thee execution time of the <code>winner()</code> function</p>\n<p>Old</p>\n<pre class=\"lang-py prettyprint-override\"><code># Iterations | Time taken(s)\n# -----------------------------------------\n# 10 ** 6 | 1.823\n# 10 ** 7 | 18.843\n</code></pre>\n<p>New</p>\n<pre class=\"lang-py prettyprint-override\"><code># Iterations | Time taken(s)\n# -----------------------------------------\n# 10 ** 6 | 0.855 ( previously 1.823 )\n# 10 ** 7 | 8.277 ( previously 18.843)\n</code></pre>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:10:19.177", "Id": "497167", "Score": "0", "body": "How \"much **much** faster\" are such int comparisons? I get about 30 ns for string and about 27 ns for int. I don't think that deserves a \"much **much**\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:14:55.560", "Id": "497168", "Score": "0", "body": "What do your benchmarks measure? I guess calls of the `winner` function? With what `board`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:20:54.593", "Id": "497169", "Score": "0", "body": "@HeapOverflow The older one uses string, the new uses int" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:21:54.240", "Id": "497170", "Score": "0", "body": "@HeapOverflow In my tests, working with a string board proved to be much slower, because every win call itself would have 8 comparisons, and a few more in `minimax`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:23:47.113", "Id": "497171", "Score": "0", "body": "@HeapOverflow sorry about that, I though I had specified what I was measuring. You're right it's the `winner` function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:28:11.367", "Id": "497172", "Score": "0", "body": "@HeapOverflow Every time minimax is called, `winner` is called. Which makes a total of about 9 string comparisons for every minimax call. An Integer comparison is a single bitwise instruction" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:30:27.447", "Id": "497173", "Score": "0", "body": "\"single bitwise instruction\" - You seem to be confusing Python with assembly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:30:35.183", "Id": "497174", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116421/discussion-between-aryan-parekh-and-heap-overflow)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T19:19:28.583", "Id": "497453", "Score": "1", "body": "Thanks for your answer! This was really helpful!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T07:31:15.040", "Id": "252357", "ParentId": "252322", "Score": "2" } }, { "body": "<p><strong>If you want speed, sacrifice memory</strong>. Precompute the best move for each of the 765 positions (exploiting symmetry) and dump into in a dict, probably using a <a href=\"https://en.wikipedia.org/wiki/Bitboard\" rel=\"nofollow noreferrer\">bitboard</a> to represent a position (for example, you can encode an entire game position into a single 32 bit integer <code>0b00000000ooooooooo000000xxxxxxxxx</code> where <code>o</code> and <code>x</code> are nine bits for each square that can be occupied<sup><a href=\"https://gist.github.com/ggorlen/65b17915c8670926481400b15675898a#file-tictactoe-c-L28\" rel=\"nofollow noreferrer\">1</a></sup>). Look up the best move per turn in your data structure.</p>\n<p>After this, it's all micro-optimizations. Eliminating branches and loops are generally good ideas with side benefits for increased readability and reduced <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a> (fewer bugs).</p>\n<p>There's no need to check for wins until at least the 5th move was made. Draws are pointless to check until the board is full. With a bitboard, moves and win/draw state check operations can boil down to masks and shifts. Then again, if you've precomputed everything, you can store the outcome in a couple of bit flags per state.</p>\n<p>All of these optimizations are minor relative to the precomputation and table lookup, though. Writing a domain-specific implementation with a bunch of branches should also be pretty fast, but still seems likely to be slower than the hash table lookup and a lot more fuss.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T01:30:19.770", "Id": "497478", "Score": "2", "body": "While interesting ideas, this answer does not even attempt to provide review comments on the code the OP provided. All answers on _Code Review_ must actually provide a review of the existing code, or are invalid answers, off topic for the _Code Review_ site, and subject to deletion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T03:12:55.120", "Id": "497482", "Score": "0", "body": "That's a bit surprising--[this answer](https://codereview.stackexchange.com/a/252342/171065) remarks less directly on OP's code but I don't see any comments to this effect there and it has three upvotes. I'm addressing OP's code on a high level and reviewing their overall design (reliance on branch-heavy code, checking win/draw conditions even when they're impossible, fundamentally using minimax) but not digging into a line-by-line analysis. How detailed do I need to be to qualify as on-topic and why is the other answer acceptable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T03:15:37.717", "Id": "497483", "Score": "1", "body": "I feel this answer is good and there shouldn't be an issue with it. If applied with @AJNeufeld's logic, then even superbrain's answer would be off-topic, but it isn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T03:17:38.507", "Id": "497484", "Score": "0", "body": "BTW, don't recommend bitboards in python. The bitwise operations are very slow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T03:37:24.173", "Id": "497485", "Score": "0", "body": "Thanks for that. You'd have to benchmark against the alternative which is representing a position with tuples or other hashable objects as keys to the move lookup dict--OP's 2d lists won't work. Manipulating these complex structures has a cost as well and even if bit operations are slower than you'd expect, I'd be surprised if they can't compete with typical object ops. The point is that you need something hashable and integers are just great for that. As my review points out, the critical part is that everything is precomputed so it's sort of splitting hairs either way." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T08:29:03.103", "Id": "252445", "ParentId": "252322", "Score": "0" } } ]
{ "AcceptedAnswerId": "252354", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:12:40.990", "Id": "252322", "Score": "5", "Tags": [ "python", "algorithm", "python-2.x" ], "Title": "Decrease Computation Time for Python Tic-Tac-Toe Minimax Algorithm" }
252322
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a>. After digging into the thing that <a href="https://quuxplusone.github.io/blog/2018/06/12/perennial-impossibilities/#detect-the-first-argument-type-of-a-function" rel="nofollow noreferrer">detecting the argument type of a function</a>, I found that it is possible to simplify the <code>T1</code> parameter in <a href="https://codereview.stackexchange.com/q/252225/231235">last implementation</a> with <code>boost::callable_traits::args_t</code> syntax in <a href="https://www.boost.org/doc/libs/develop/libs/callable_traits/doc/html/callable_traits/reference.html#callable_traits.reference.ref_args" rel="nofollow noreferrer"><code>Boost.CallableTraits</code> library</a>. As the result, <code>recursive_count_if</code> template function can be used exactly as the following code.</p> <pre><code>std::vector&lt;std::vector&lt;std::string&gt;&gt; v = {{&quot;hello&quot;}, {&quot;world&quot;}}; auto size5 = [](std::string s) { return s.size() == 5; }; auto n = recursive_count_if(v, size5); </code></pre> <p>The implementation of <code>recursive_count_if</code> function with automatic type deducing:</p> <pre><code>#include &lt;boost/callable_traits.hpp&gt; // recursive_count_if implementation template&lt;class T1, class T2&gt; requires (is_iterable&lt;T1&gt; &amp;&amp; std::same_as&lt;std::tuple&lt;std::iter_value_t&lt;T1&gt;&gt;, boost::callable_traits::args_t&lt;T2&gt;&gt;) auto recursive_count_if(const T1&amp; input, const T2 predicate) { return std::count_if(input.begin(), input.end(), predicate); } // transform_reduce version template&lt;class T1, class T2&gt; requires (is_iterable&lt;T1&gt; &amp;&amp; !std::same_as&lt;std::tuple&lt;std::iter_value_t&lt;T1&gt;&gt;, boost::callable_traits::args_t&lt;T2&gt;&gt;) auto recursive_count_if(const T1&amp; input, const T2 predicate) { return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp; element) { return recursive_count_if(element, predicate); }); } </code></pre> <p>The used <code>is_iterable</code> concept:</p> <pre><code>template&lt;typename T&gt; concept is_iterable = requires(T x) { *std::begin(x); std::end(x); }; </code></pre> <p><strong>The constraints of usage</strong></p> <p>Because the type in the input lambda function plays the role of termination condition, you can not use <code>auto</code> keyword as generic lambdas here. If the lambda function like <code>[](auto element) { }</code> is passed in, compiling errors will pop up. If you want to use generic lambdas, maybe you can choose <a href="https://codereview.stackexchange.com/q/252225/231235">the previous version <code>recursive_count_if</code> function</a> due to the termination condition is separated.</p> <p><a href="https://godbolt.org/z/EnKW4o" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>This version of <code>recursive_count_if</code> template function is boost-dependent, and the type of termination condition can be deduced automatically from input lambda parameter.</p> </li> <li><p>Why a new review is being asked for?</p> <p>In my opinion, the requires-clause of <code>recursive_count_if</code> template function is a little complex and it's boost-dependent. If there is any simpler way to do this, please let me know.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T16:43:17.557", "Id": "497207", "Score": "1", "body": "Just curious, why `recursive`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:32:54.970", "Id": "497216", "Score": "0", "body": "@bipll In order to make API more generic, the recursive technique used here to deal with **arbitrary** level nested iterables, including something like `std::vector<std::vector<std::vector<std::string>>>` or `std::vector<std::vector<std::vector<std::vector<std::string>>>>`..." } ]
[ { "body": "<h1>Don't try to deduce the predicate's parameter type</h1>\n<p>As <a href=\"https://codereview.stackexchange.com/questions/252053/a-recursive-count-if-function-for-various-type-arbitrary-nested-iterable-impleme#comment496788_252154\">Quuxplusone mentioned</a> in the comments of the predecessor question, you should not try to determine the type of the predicate function's parameter, this is bound to fail. And indeed the problem immediately starts when you look at your predicate:</p>\n<pre><code>auto size5 = [](std::string s) { return s.size() == 5; };\n</code></pre>\n<p>And think: hey, that's making a copy of <code>s</code>, I should pass that by const reference instead:</p>\n<pre><code>auto size5 = [](const std::string &amp;s) { return s.size() == 5; };\n</code></pre>\n<p>Now it fails the <code>requires</code> clauses of your functions. You might be able to add some more tricks to cast away cv-qualifiers and references before comparing the types with <code>std::same_as</code>, but that does not cover all possible situations either. For example, I could write a lambda which allows any type of <code>std::basic_string</code> to be checked:</p>\n<pre><code>auto size5 = []&lt;typename T&gt;(std::basic_string&lt;T&gt; s) { return s.size() == 5; };\n</code></pre>\n<p>As I suggested in the comments, you just want to write a concept that checks if the predicate can be <em>applied</em> to the argument it is fed, you don't need to check the types themselves. Here is a possible implementation:</p>\n<pre><code>template&lt;typename Pred, typename T&gt;\nconcept is_applicable_to_elements = requires(Pred predicate, const T &amp;container)\n{\n predicate(*container.begin());\n};\n\ntemplate&lt;class T1, class T2&gt; requires is_applicable_to_elements&lt;T2, T1&gt;\nauto recursive_count_if(const T1&amp; input, const T2 predicate)\n{\n return std::count_if(input.begin(), input.end(), predicate);\n}\n\ntemplate&lt;class T1, class T2&gt;\nauto recursive_count_if(const T1&amp; input, const T2 predicate)\n{\n return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp; element) {\n return recursive_count_if(element, predicate);\n });\n}\n</code></pre>\n<p>Note that since all the templates used <code>is_iterable()</code>, you can remove that requirement, although if you keep it you get nicer error messages if you accidentily try to apply <code>recursive_count_if()</code> on something that does not support iterating over.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T16:37:43.780", "Id": "252375", "ParentId": "252325", "Score": "1" } } ]
{ "AcceptedAnswerId": "252375", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T15:40:58.990", "Id": "252325", "Score": "2", "Tags": [ "c++", "recursion", "c++20" ], "Title": "A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++" }
252325
<p>Is it good practice to keep the connection strings for websites in another folder outside of the site folder?</p> <p>For example, here is the htdocs structure. I am working on site3:</p> <pre><code>htdocs&gt; site1&gt; site2&gt; site3&gt; index.php include&gt; database.php site4&gt; </code></pre> <p>Using the above, here is the database.php connection file for site3:</p> <pre><code>&lt;?php $host = 'xx.xxx.x.xx'; $dbname = 'mydatabase'; define ('DB_USER', 'dbusername'); define ('DB_PASSWORD', 'dbpassword'); try{ $dbc = new PDO(&quot;mysql:dbname=$dbname;host=$host&quot;, DB_USER, DB_PASSWORD); $dbc-&gt;SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ echo &quot;Conneciton failed: &quot; . $e-&gt;getMessage() . &quot;&lt;br/&gt;&quot;; } ?&gt; </code></pre> <p>So what I want to do is move the connection information into another folder, called 'connections'. This is where I'll keep the actual connection info.</p> <p>Here is the revised htdocs structure, with the connections directory:</p> <pre><code>htdocs&gt; site1&gt; site2&gt; site3&gt; index.php include&gt; database.php site4&gt; connections&gt; site3conn.php </code></pre> <p>Within the connections directory, here is site3conn.php:</p> <pre><code>&lt;?php $host = 'xx.xxx.x.xx'; $dbname = 'mydatabase'; define ('DB_USER', 'dbusername'); define ('DB_PASSWORD', 'dbpassword'); ?&gt; </code></pre> <p>So now, the database.php connection file for site3 will pull in the connection string from the connections directory. As follows:</p> <pre><code>&lt;?php require(&quot;D:\htdocs\connections\site3conn.php&quot;); try{ $dbc = new PDO(&quot;mysql:dbname=$dbname;host=$host&quot;, DB_USER, DB_PASSWORD); $dbc-&gt;SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ echo &quot;Conneciton failed: &quot; . $e-&gt;getMessage() . &quot;&lt;br/&gt;&quot;; } ?&gt; </code></pre> <p>Please note, both examples allow me to successfully connect to the dB. But I want to use the revised format.</p> <p>I, of course, need to make sure users cannot navigate to the connections folder. Unsure how I can do that.</p> <p>With that said, is this good practice? Is this more secure or less secure or neither? Is there a better way?</p> <p>Appreciate your thoughts.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T05:47:21.943", "Id": "497139", "Score": "0", "body": "Whether clients can navigate to the connections folder is matter of web server setup, no matter where the folder is in the directory tree. Putting it outside a project folder does not make much sense though, unless multiple sites share a connection (credentials). The common approach is to have a project folder and in it a configs folder and public folder and only the public folder is configured to be accessible through web server. The public folder should contain only index.php and static assets like js, css, images etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T05:48:16.880", "Id": "497140", "Score": "0", "body": "All configs, php sources, etc are then outside the public folder, thus inaccessible from web, but still inside project folder keeping it centralized..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T05:54:04.393", "Id": "497141", "Score": "0", "body": "PS i am posting it as comment because I haven't really reviewed your code. Your questions don't really fit the scope of this site. I'm not voting to close either because there is some reviewable code, but I don't think that's your focus. You seem to be concerned more about design than the actual code..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T12:01:21.923", "Id": "497156", "Score": "0", "body": "Pretty much all commentators gave good advice here. If your project is manageable I mean won't be a huge MVC type of application then you can stick to your option.\n\nBut don't do stuff like this:\nrequire(\"D:\\htdocs\\connections\\site3conn.php\"); you're hardcoding the path to the file which only resides in your computer, now image what's gonna happen if you upload this code to a different server, you need to use relative path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:04:06.667", "Id": "497179", "Score": "0", "body": "@Erasus - I was using a path inside the site dB connection file that looked like this: include(\"../../connections/site3conn.php\") , but I kept getting an error that read \"system cannot find path specified. When I switched over to the absolute path, I no longer got the error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:07:44.347", "Id": "497182", "Score": "0", "body": "@slepic - I think I see what you're saying. It's like when you're setting up Docker; you keep the Dockerfile and the Docker-compose.yml file in the project folder, but outside of your public folder, where your actual web files are located. Does that sound about right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:29:06.017", "Id": "497189", "Score": "0", "body": "@JohnBeasley I understand what you are saying but that's not how you should be doing it, if you upload your files to some server it simply won't work. So know that the absolute path you specified there is only usable in your own environment. Everywhere else you will need to change it. You should be able to work it out with relative path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:37:38.443", "Id": "497190", "Score": "0", "body": "@Erasus - Understood, and thank you for your input." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T17:35:55.467", "Id": "252330", "Score": "1", "Tags": [ "php", "pdo" ], "Title": "Good practice for dB connections" }
252330
<p>This is an object-oriented Chess game. So far, I have implemented the <code>pawn</code> and <code>board</code> functionalities and I would love to get a review early on before diving deep into the project.</p> <h2>piece.py</h2> <pre><code># piece.py from abc import ABC, abstractmethod class Piece(ABC): def __init__(self, color): if color.lower() != 'black' and color.lower() != 'white': raise ValueError('Invalid color argument') self.color = color.lower() def can_move(self): pass </code></pre> <h2>pawn.py</h2> <pre><code># pawn.py from piece import Piece class Pawn(Piece): def __init__(self, color, co_ordinates): super().__init__(color) self.co_ordinates = co_ordinates self.first_move = True def can_move(self, board_list, co_ordinates): new_row, new_column = co_ordinates if self.color == 'black': return self.__can_move_black(board_list, new_row, new_column) if self.color == 'white': return self.__can_move_white(board_list, new_row, new_column) def __can_move_black(self, board_list, row, column): location_is_empty = board_list[row][column] == 0 if (self.co_ordinates[0] + 1 == row) and location_is_empty: return True if self.first_move and location_is_empty: self.first_move = False return self.co_ordinates[0] + 2 == row and self.co_ordinates[1] == column; lhs_is_valid = self.co_ordinates[0] + 1 == row and self.co_ordinates[1] - 1 == column rhs_is_valid = self.co_ordinates[0] + 1 == row and self.co_ordinates[1] + 1 == column if rhs_is_valid or lhs_is_valid: if not location_is_empty and board_list[row][column].color != self.color: return True; else: return False def __can_move_white(self, board_list, row, column): location_is_empty = board_list[row][column] == 0 if (self.co_ordinates[0] - 1 == row) and location_is_empty: return True if self.first_move and location_is_empty: self.first_move = False return self.co_ordinates[0] - 2 == row and self.co_ordinates[1] == column lhs_is_valid = self.co_ordinates[0] - 1 == row and self.co_ordinates[1] - 1 == column rhs_is_valid = self.co_ordinates[0] - 1 == row and self.co_ordinates[1] + 1 == column if rhs_is_valid or lhs_is_valid: if not location_is_empty and (board_list[row][column].color != self.color): return True; else: return False def board_repr(self): return self.color[0] + 'p' def __repr__(self): return 'Pawn(%s, %r)' % (self.color, self.co_ordinates) </code></pre> <h2>board.py</h2> <pre><code># board.py from pawn import Pawn class Board: def __init__(self): self.board_list = [ [ 0 for i in range(8)] for i in range(8) ] self.__init_pieces() def __init_pieces(self): self.__init_pawns() def __init_pawns(self): row = 1 for column in range(8): self.board_list[row][column] = Pawn('Black', (row, column)) row = 6 for column in range(8): self.board_list[row][column] = Pawn('White', (row, column)) def draw(self): for row in self.board_list: for column in row: if column != 0: print(column.board_repr(), end=' ') else: print(column, end=' ') print() def move(self, piece, co_ordinates): if piece != 0 and piece.can_move(self.board_list, co_ordinates): row, column = co_ordinates if self.__can_capture(row, column): self.board_list[row][column] = 0 piece_row, piece_column = piece.co_ordinates piece.co_ordinates = co_ordinates self.board_list[row][column], self.board_list[piece_row][piece_column] = self.board_list[piece_row][piece_column], self.board_list[row][column] else: print('Invalid move') def __can_capture(self, row, column): location_is_empty = self.board_list[row][column] == 0 if not location_is_empty: return True else: return False def __promote(self, piece, new_piece): new_piece.co_ordinates = piece.co_ordinates row, column = new_piece.co_ordinates board_list[row][column] = new_piece if __name__ == '__main__': board = Board(); board.move(board.board_list[1][0], (3,0)) board.move(board.board_list[6][1], (4,1)) board.move(board.board_list[3][0], (4,1)) board.move(board.board_list[0][0], (4,1)) #board.move(pawn, (4,1)) board.draw(); </code></pre>
[]
[ { "body": "<h2>Abstract classes</h2>\n<p><code>can_move</code> is suspicious. Can move where? Chess moves are coordinate-dependent, so I would expect that this method accept the same parameters as your child, i.e. <code>board_list</code> and <code>co_ordinates</code>.</p>\n<p>Also, you're not properly using ABC. You need <code>can_move</code> to be an <code>@abstractmethod</code>.</p>\n<h2>Stringly-typed colours</h2>\n<p>Not only is using strings for black and white a troubled idea, you're baking some bugs into your application. You do case-sensitive comparison to <code>black</code> and <code>white</code>, but then initialize with <code>Black</code> and <code>White</code>. Instead, represent player with a boolean or an <code>Enum</code>.</p>\n<h2>Comprehensions</h2>\n<pre><code>[ 0 for i in range(8)] for i in range(8)\n</code></pre>\n<p>first, you shouldn't reuse an iteration variable at two different levels of nesting. Second, these don't actually need names at all, and can be <code>_</code>.</p>\n<h2>Don't repeat yourself</h2>\n<pre><code> row = 1\n for column in range(8):\n self.board_list[row][column] = Pawn('Black', (row, column))\n row = 6\n for column in range(8):\n self.board_list[row][column] = Pawn('White', (row, column))\n</code></pre>\n<p>can be</p>\n<pre><code>for row, colour in ((1, 'Black'), (6, 'White')):\n for column in range(8):\n # ...\n</code></pre>\n<h2>Boolean expressions</h2>\n<pre><code> if not location_is_empty:\n return True\n else:\n return False\n</code></pre>\n<p>can simply be</p>\n<pre><code>return not location_is_empty\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T20:12:16.433", "Id": "497093", "Score": "0", "body": "\"Don't repeat yourself\" applies also to can_move_black vs. can_move_white, which may remain but should call a common function for the real work in terms of one or two extra parameters (a sign for direction certainly - and I would use the home row number instead of a first_move flag)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T18:58:05.720", "Id": "252336", "ParentId": "252332", "Score": "3" } }, { "body": "<h1>Don't encode player turn as a string</h1>\n<pre class=\"lang-py prettyprint-override\"><code>turn = &quot;black&quot;\nturn = &quot;white&quot;\n</code></pre>\n<p>You're using a string for something which can be represented by a simple boolean value.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if color.lower() == &quot;black&quot;:\n</code></pre>\n<p>While the above may seem simple, when performed over and over again it <strong>will</strong> slow down your program. Comparison of strings is slow and expensive. However, comparing two numbers is much faster, a single computer instruction.</p>\n<p>Your best bet here is probably to use an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a>, or a plain variable in your class that will represent a boolean / integral value</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Color:\n white = 0 # or False\n black = 1 # or True\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>Color.white.value\nColor.black.value\n</code></pre>\n<hr />\n<h1>Code structure</h1>\n<pre class=\"lang-py prettyprint-override\"><code>class Pawn(Piece):\n #...\n</code></pre>\n<p>Careful! What you have done now is created your own <code>Pawn</code> class that already has quite a few methods. By doing this you have forced yourself to create <strong>five</strong> more classes representing a piece.</p>\n<ul>\n<li>pawn, bishop, knight, rook, queen, king</li>\n</ul>\n<p>What you will notice is a loooot of repetition. I can say that for sure because your <code>Pawn</code> class already has two nearly identical methods. Your program will be very slow since your board instead of having simple numbers to represent pieces, it will have huge class objects. Move generation would a nightmare. Re-think your code structure. Do you really have to represent individual pieces using separate classes?</p>\n<p>What is it that computers love? Numbers. It's the fastest <strong>and</strong> simplest way. Each piece gets a certain value. Black pieces would be negative, white pieces would be positive. This will also be very useful for <a href=\"https://www.chessprogramming.org/Evaluation\" rel=\"nofollow noreferrer\">evaluation</a>. Once you have your values assigned, you can simply initialize the board like</p>\n<pre class=\"lang-py prettyprint-override\"><code>board = [\n[rook.value, knight.value, ....],\n# ...\n</code></pre>\n<p>You now have a direct map of the pieces. Move-generation becomes much easier and <strong>faster</strong></p>\n<hr />\n<h1>Representing moves</h1>\n<p>Right now since you are starting, A move is just <code>row</code> and <code>col</code>. That doesn't stay, once you begin your move-generator you will realize you need a few more attributes. To list them</p>\n<ul>\n<li>Old position</li>\n<li>New position</li>\n<li>Castling</li>\n<li>En-passant</li>\n<li>Promotion</li>\n</ul>\n<p>You need to maintain both the old position and new position if a player wants to <em>undo</em> a move. The pawn is evil, <a href=\"https://en.wikipedia.org/wiki/En_passant\" rel=\"nofollow noreferrer\">en-passant</a> and <a href=\"https://en.wikipedia.org/wiki/Promotion_(chess)#:%7E:text=Promotion%20in%20chess%20is%20a,square%20on%20the%20same%20move.\" rel=\"nofollow noreferrer\">pawn promotion</a> are two very special kinds of moves since they don't follow any of the usual rules, which requires you to keep an extra attribute. All of this is best represented by a <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">data class</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>@dataclass\nclass Move:\n old_position : int\n new_position : int\n ...\n</code></pre>\n<hr />\n<p><a href=\"https://www.chessprogramming.org/Main_Page\" rel=\"nofollow noreferrer\"><strong>chessprogramming.org</strong></a> is an excellent resource for this topic. It has HUGE amounts of information, everything you need for this topic. It will surely help you.</p>\n<p><a href=\"https://python-chess.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\"><strong>python-chess</strong></a> is a chess library in Python that implements all of these ideas. I don't suggest you directly use it, but seeing its interface can give you nice ideas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T20:02:56.190", "Id": "497092", "Score": "3", "body": "Great review, thanks for the link :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T19:14:17.973", "Id": "252337", "ParentId": "252332", "Score": "4" } } ]
{ "AcceptedAnswerId": "252336", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T18:01:59.880", "Id": "252332", "Score": "3", "Tags": [ "beginner", "python-3.x", "object-oriented", "chess" ], "Title": "Chess game object-oriented" }
252332
<p>Inspired by another Q I finally made a version that groups permutable regions into parentheses. Non-ambigous sequences are outside of parens.</p> <p>Here the original problem:</p> <blockquote> <p>Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed.</p> </blockquote> <p>I don't do any counting. For <code>ABCDEFGHIJKLM</code> I get:</p> <p><code>(ABC)DEFGHIJ(AAABAC)</code></p> <p>which means: a group &quot;123&quot; with three possibilities (ABC, LC or AV ), then a one-solution streak &quot;45678910&quot;, then a large group &quot;111213&quot; with many (13) possibilities.</p> <p>The idea is to say 3x13=39 is the solution, but for longer groups some combinatorics is needed. I calculated 13 by hand...</p> <p>Output (4 examples):</p> <pre><code>1234567891011121314151617181920212223242526 [Code] (ABC)DEFGHIJ(AAABAC)(AD)(AE)(AF)(AG)(AH)(AI)T(BABBBC)(BD)(BE)(BF) [Decoded: single, grouped] 314159265358979323846 [Code] C(AD)(AE)I(BF)ECEHIGIC(BC)HDF [Decoded: single, grouped] 11011 [Code] AJ(AA) [Decoded: single, grouped] 22202 [Code] (BB)TB [Decoded: single, grouped] 18446744073709551616 [Code] (AH)DDFGD******* Error: zero 30-90 </code></pre> <p>The code is quite long and complicated. The parens seem to be correct now - no single presudo-groups anymore, like <code>FGHJ(A)</code>.</p> <p>Is there a simpler way to achieve this?</p> <p>The basic idea still seems straight forward, but I end up with two screens full of ifs. (But it is done in one pass)</p> <p>Or is it silly to decode / reconstruct the message when it is scrambled like that?</p> <pre><code>/* Decode Fawlty 0x10-shift code (leading zeros lost) A=1, B=2, ..., Z=26 &quot;111&quot; can thus be &quot;AAA&quot;, &quot;AK&quot; or &quot;KA&quot; Orig. Q. was: How to count the possible combinations in a message? This puts freely permutable regions into parentheses, giving only the single-digit interpretation. For above &quot;111&quot;, output would be &quot;(AAA)&quot; */ #include &lt;stdio.h&gt; void parse_msg(char *msg) { char c, cprev, cnext; int i; /* Start in a state like after a high digit 3..9 */ cprev = '9'; for (i = 0; msg[i] != '\0'; i++) { c = msg[i]; cnext = msg[i+1]; /* Make sure 'cnext' is all the look-ahead that is needed */ /* pull a far ahead &quot;10&quot; or &quot;20&quot; into cnext as '\0' */ if (cnext != '\0') if (msg[i+2] == '0') cnext = '\0'; /* &quot;10&quot; and &quot;20&quot; are special cases, get rid of them */ if (cnext == '0') { if (cprev &lt;= '2') printf(&quot;)&quot;); if (c == '1') printf(&quot;J&quot;); if (c == '2') printf(&quot;T&quot;); if (c &gt;= '3') { printf(&quot;******* Error: zero 30-90\n&quot;); return; } cprev = '9'; // reset to outside-of-group i++; // extra skip in msg continue; } /* ONE: Always open a &quot;(&quot; group, unless cnext is the (fake or real) null byte */ if (c == '1') { if (cprev &gt;= '3') if (cnext == '\0') cprev = '9'; else { printf(&quot;(&quot;); cprev = c; } printf(&quot;A&quot;); continue; } /* TWO: Maybe open before, or close after, plus set cprev */ if (c == '2') { /* 32*: is closed, can open */ if (cprev &gt;= '3') { /* 32\0: dont open, but mark as closed */ if (cnext == '\0') { printf(&quot;B&quot;); cprev = '9'; continue; } /* 321-926: open before */ if (cnext &lt;= '6') printf(&quot;(&quot;); } printf(&quot;B&quot;); /* &quot;127&quot;, &quot;229&quot;: is open, must close */ if (cprev &lt;= '2' &amp;&amp; cnext &gt;= '7' ) { printf(&quot;)&quot;); cprev = '9'; continue; } cprev = c; continue; } /* c == '3' or higher are left */ /* THREE+: No opening */ printf(&quot;%c&quot;, c + 0x10 ); /* if open, then close group &quot;)&quot; after printing */ if (cprev == '1' || cprev == '2' &amp;&amp; c &lt;= '6' ) printf(&quot;)&quot;); /* 3..9 marks state as &quot;closed&quot; */ cprev = c; } /* End of 'msg' reached: close if opened */ if (cprev &lt;= '2') printf(&quot;)&quot;); printf(&quot; [Decoded: single, grouped] \n&quot;); return; } int main(void) { char *msg = &quot;1234567891011121314151617181920212223242526&quot;; printf(&quot;%s [Code]\n&quot;, msg); parse_msg(msg); msg = &quot;314159265358979323846&quot;; printf(&quot;\n%s [Code]\n&quot;, msg); parse_msg(msg); msg = &quot;11011&quot;; printf(&quot;\n%s [Code]\n&quot;, msg); parse_msg(msg); msg = &quot;22202&quot;; printf(&quot;\n%s [Code]\n&quot;, msg); parse_msg(msg); msg = &quot;18446744073709551616&quot;; printf(&quot;\n%s [Code]\n&quot;, msg); parse_msg(msg); return 0; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:16:11.517", "Id": "497365", "Score": "0", "body": "The introduction of this question doesn't really explain a lot. You should explain everything to a reader that has not followed the other question, or you should at least link to the other question." } ]
[ { "body": "<p>You might use a decoding key, an array which has stored the encrypted values for each character, then you use a nested loop construction. This would shorten your code significantly and you might be able to change the encryption key more easily.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:03:36.770", "Id": "497250", "Score": "0", "body": "There is nothing _encrypted_ here, all data is only _encoded_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:46:04.950", "Id": "497334", "Score": "0", "body": "This is the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:14:56.357", "Id": "497364", "Score": "0", "body": "Are you saying that encoding and encryption are the same? No, they are not. Encryption is about secrecy, encoding is just a transformation to another set of symbols, without the intention of keeping anything secret." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T23:34:28.307", "Id": "497470", "Score": "0", "body": "Intention is irrelevant, transformation is relevant, you have no idea, please stop talking nonsense." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T06:53:23.130", "Id": "252355", "ParentId": "252343", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T23:11:33.960", "Id": "252343", "Score": "3", "Tags": [ "c", "parsing" ], "Title": "Decode alphabet encoded message" }
252343
<p>I'm working on a project where I need to get all followers from a specific user and store this info in a database. I have done this and so far it suits my needs, but I'd like to make it more &quot;professional&quot; and would love to hear your suggestions.</p> <p>The first code is <strong>twitter.py</strong> and the 2nd one is <strong>app.py</strong></p> <pre><code>import requests class TwitterAPI(): def __init__(self): with open('token.ini') as ini: self.token = ini.readline() def get_follower(self, action, **kwargs): params = kwargs.keys() if 'user_id' not in params and 'screen_name' not in params: raise TypeError('Incorrect parameters, expecting `user_id` or `screen_name`') url = { 'list': 'https://api.twitter.com/1.1/followers/ids.json', 'info': 'https://api.twitter.com/1.1/users/show.json' } r = requests.get( url[action], params = kwargs, headers = {'Authorization': 'Bearer ' + self.token}, ) return r.json() if r.status_code == 200 else r.status_code </code></pre> <hr /> <pre><code>import twitter import sqlite3 from datetime import datetime conn = sqlite3.connect('twitter_analytics.sqlite3') c = conn.cursor() api = twitter.TwitterAPI() followers = api.get_follower(action='list', screen_name='Croves') c.execute(&quot;INSERT INTO user(twitter_screen_name, created_at) VALUES(?, ?)&quot;, ('Croves', datetime.now())) conn.commit() user_id = c.lastrowid for count, follower in enumerate(followers['ids']): info = api.get_follower(action='info', user_id=follower) c.execute(&quot;&quot;&quot; INSERT INTO user_followers(user_id, id_str, name, screen_name, location, url, description, protected, verified, followers_count, friends_count, profile_banner_url, profile_image_url_https, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) &quot;&quot;&quot;, ( user_id, info.get('id_str'), info.get('name'), info.get('screen_name'), info.get('location'), info.get('url'), info.get('description'), info.get('protected'), info.get('verified'), info.get('followers_count'), info.get('friends_count'), info.get('profile_banner_url'), info.get('profile_image_url_https'), datetime.now() )) if count % 10 == 0: conn.commit() conn.commit() conn.close() </code></pre>
[]
[ { "body": "<p>A few suggestions:</p>\n<h2>PEP-8</h2>\n<p>Some selected excerpts <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">from pep-8</a>:</p>\n<ul>\n<li><p>Avoid extraneous whitespace immediately inside parentheses, brackets or braces:</p>\n</li>\n<li><p>Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter</p>\n</li>\n<li><p>Surround top-level function and class definitions with two blank lines.</p>\n</li>\n<li><p>Use blank lines in functions, sparingly, to indicate logical sections.</p>\n</li>\n<li><p>Imports should be grouped in the following order:</p>\n<ul>\n<li>Standard library imports.</li>\n<li>Related third party imports.</li>\n<li>Local application/library specific imports.</li>\n</ul>\n<p>You should put a blank line between each group of imports.</p>\n</li>\n</ul>\n<h2>Token</h2>\n<p>Reading the token in the constructor of your API wrapper is a very bad behaviour. Your constructor should instead be initialised with the same, and the caller needs to provide proper tokens.</p>\n<h2>Functions</h2>\n<p>You currently have a single function doing 2 different tasks/actions. Instead, split it to do one thing each.</p>\n<h2>Return values/error handling</h2>\n<p>The return type of your API wrapper is inconsistent. In case of error, it just returns an integer value, whereas in the caller (<code>app.py</code>) you are always assuming that the result will never be an integer (no errors ever?).</p>\n<p>Raise an exception in the wrapper itself if the API fails, or the caller should have conditional check to validate the same.</p>\n<h2>sqlite3 bulk operation</h2>\n<p>The sqlite3 package has a method <code>executemany</code> to perform bulk insert in a single pass. Check the docs for <a href=\"https://devdocs.io/python%7E3.8/library/sqlite3#sqlite3.Cursor.executemany\" rel=\"nofollow noreferrer\">the same here</a>.</p>\n<h2><code>if __name__</code> block</h2>\n<p>Put execution logic of your script inside the <code>if __name__ == &quot;__main__&quot;</code> block. A more descriptive explanation can be checked <a href=\"https://stackoverflow.com/a/419185/1190388\">on Stack Overflow</a>.</p>\n<hr />\n<h2>Example rewrite</h2>\n<h3><code>twitter.py</code></h3>\n<pre><code>import requests\n\n\nclass TwitterAPI:\n API_URL = &quot;https://api.twitter.com/1.1&quot;\n\n def __init__(self, api_token: str):\n self.token = api_token\n self.headers = {\n &quot;Authorization&quot;: f&quot;Bearer {self.token}&quot;\n }\n\n def _request(self, url, **params) -&gt; dict:\n response = requests.get(\n url,\n params=params,\n headers=self.headers,\n )\n if not response.ok:\n raise Exception(&quot;API returned invalid response.&quot;)\n return response.json()\n\n def get_user_info(self, user_id: str) -&gt; dict:\n return self._request(\n f&quot;{self.API_URL}/users/show.json&quot;,\n user_id=user_id\n )\n\n def get_followers(self, screen_name: str) -&gt; dict:\n return self._request(\n f&quot;{self.API_URL}/followers/ids.json&quot;,\n screen_name=screen_name,\n )\n</code></pre>\n<code>app.py</code>\n<pre><code>from datetime import datetime\nimport sqlite3\n\nimport twitter\n\nSQLITE_DB = &quot;twitter_analytics.sqlite3&quot;\nTWITTER_SCREEN_NAME = &quot;Croves&quot;\n\n\ndef initialise_sqlite(db_name: str):\n connection = sqlite3.connect(db_name)\n cursor = connection.cursor()\n return connection, cursor\n\n\ndef get_api_token() -&gt; str:\n with open('token.ini') as ini:\n return ini.readline()\n\n\ndef get_followers_info(api: twitter.TwitterAPI, follower_ids: list):\n for user_id in follower_ids:\n user_info = api.get_user_info(user_id=user_id)\n yield [\n user_info.get('id_str'),\n user_info.get('name'),\n user_info.get('screen_name'),\n user_info.get('location'),\n user_info.get('url'),\n user_info.get('description'),\n user_info.get('protected'),\n user_info.get('verified'),\n user_info.get('followers_count'),\n user_info.get('friends_count'),\n user_info.get('profile_banner_url'),\n user_info.get('profile_image_url_https'),\n ]\n\n\ndef main():\n token = get_api_token()\n connection, cursor = initialise_sqlite(SQLITE_DB)\n api = twitter.TwitterAPI(token)\n followers = api.get_followers(screen_name=TWITTER_SCREEN_NAME)\n cursor.execute(\n &quot;INSERT INTO user(twitter_screen_name, created_at) VALUES (?, ?)&quot;,\n (TWITTER_SCREEN_NAME, datetime.now())\n )\n connection.commit()\n user_id = cursor.lastrowid\n user_followers_info = [\n (user_id, *follower_info, datetime.now())\n for follower_info in get_followers_info(api, followers[&quot;ids&quot;])\n ]\n cursor.executemany(\n &quot;&quot;&quot;\n INSERT INTO\n user_followers(\n user_id, id_str, name, screen_name, location, url,\n description, protected, verified, followers_count,\n friends_count, profile_banner_url, profile_image_url_https,\n created_at\n )\n VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n &quot;&quot;&quot;,\n user_followers_info,\n )\n connection.commit()\n connection.close()\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<h2>Note</h2>\n<p>The above is an example rewrite. You can (and should) modify</p>\n<ul>\n<li>aggregating the followers' information</li>\n<li>a wrapper for interaction with sqlite3 etc.</li>\n<li>threading call for gathering information about followers in parallel</li>\n</ul>\n<p>etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:19:13.993", "Id": "497254", "Score": "0", "body": "Thanks a lot for your comment. Your syntax is very different from mine `def get_user_info(self, user_id: str) -> dict:` what the arrow dict and the str mean? How can I learn this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T12:04:44.967", "Id": "497294", "Score": "0", "body": "@Croves That's type hinting: https://devdocs.io/python~3.8/library/typing" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:44:28.483", "Id": "252366", "ParentId": "252346", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T01:02:30.417", "Id": "252346", "Score": "2", "Tags": [ "python" ], "Title": "Twitter API wrapper" }
252346
<p>I have a table that has buttons per row that makes views/edit an item in a modal and they have a layout like so:</p> <pre class="lang-html prettyprint-override"><code>&lt;td&gt; &lt;button class=&quot;btn btn-sm btn-default&quot; onclick=&quot;setModalMode('view', '8')&quot; data-toggle=&quot;modal&quot; data-target=&quot;#license-add&quot; data-id=&quot;8&quot;&gt; &lt;i class=&quot;far fa-eye&quot;&gt;&lt;/i&gt; &lt;/button&gt; &amp;nbsp; &lt;button class=&quot;btn btn-sm btn-info&quot; onclick=&quot;setModalMode('update', '8')&quot; data-toggle=&quot;modal&quot; data-target=&quot;#license-add&quot; data-id=&quot;8&quot;&gt; &lt;i class=&quot;far fa-edit&quot;&gt;&lt;/i&gt; &lt;/button&gt; &amp;nbsp; &lt;button class=&quot;btn btn-sm btn-danger&quot; onclick=&quot;setModalMode('delete', '8')&quot; data-toggle=&quot;modal&quot; data-target=&quot;#license-add&quot; data-id=&quot;8&quot;&gt; &lt;i class=&quot;far fa-trash-alt&quot;&gt;&lt;/i&gt; &lt;/button&gt; &lt;/td&gt; </code></pre> <p>It calls the <code>setModalMode</code> functiton and toggles the mode of the modal:</p> <pre class="lang-javascript prettyprint-override"><code>let modal = 'div#license-add'; let $form = $('form#modal-form'); let modalMode = ''; // this is used by my AJAX function to point what URL should my requests go let rowObjects = []; // this gets filled up by values on a different function everytime my table generates function setModalMode(mode, id) { loadingOverlay(false, modal); modalMode = mode; let title = 'Modal title'; let inputsDisabled = false; let hasData = true; let needsButton = true; let isDelete = false; if (mode === 'add') { title = 'Add new license'; hasData = false; } else if (mode === 'update') { title = 'Updating license'; } else if (mode === 'view') { title = 'Viewing license'; needsButton = false; inputsDisabled = true; } else if (mode === 'delete') { title = 'Delete this license?'; inputsDisabled = true; isDelete = true; } else { return; } if (hasData) { let data = rowObjects['license', id]; $form.find('input#email').val(data.email); $form.find('input#key').val(data.activation_key); $form.find('input#expiration').val(moment(data.expiration).format('MM/DD/YYYY')); $form.find('select#type-select').val(data.type); $form.find('input#hidden-id').val(data.id); } else { $form.find(':input').val(''); } if (needsButton) { if (isDelete) { $('#deleteButton', modal).show(); $('#submitButton', modal).hide(); } else { $('#deleteButton', modal).hide(); $('#submitButton', modal).show(); } } else { $('#submitButton', modal).hide(); $('#deleteButton', modal).hide(); } $('h4#modal-title', modal).text(title); $form.find(':input').prop('disabled', inputsDisabled); } </code></pre> <p>Although the code does its job perfectly well, I feel like my code is a mess of <code>if</code> statements</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T02:11:37.630", "Id": "497123", "Score": "2", "body": "What does the `id` come from? Is it, for example, in sequential ascending order in `<tr>`s of the table, or is its value dynamic and not really predictable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T02:14:34.330", "Id": "497124", "Score": "0", "body": "@CertainPerformance it comes from the JSON file on the server and being placed there by DataTables' `column` option. It's predictable since it's the \"primary\" key of the item." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T02:16:50.180", "Id": "497126", "Score": "0", "body": "Yes, but it can skip (eg, 0,1,2,4,7,10,...) if some items are deleted on the server" } ]
[ { "body": "<p><strong>Avoid inline handlers</strong> - <a href=\"https://stackoverflow.com/a/59539045\">they have</a> way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with <code>addEventListener</code> instead.</p>\n<p>While you could iterate over all buttons and add a listener to each, consider using event delegation instead: add a single click listener to the table, and on click, if the click was on a button, examine the button's attributes or index to see which one was clicked, and examine the <code>data-id</code> attribute to get the ID.</p>\n<p>Something along the lines of:</p>\n<pre><code>&lt;td&gt;\n &lt;button data-mode=&quot;view&quot; class=&quot;btn btn-sm btn-default&quot; data-toggle=&quot;modal&quot; data-target=&quot;#license-add&quot; data-id=&quot;8&quot;&gt;\n &lt;i class=&quot;far fa-eye&quot;&gt;&lt;/i&gt;\n &lt;/button&gt;\n &amp;nbsp;\n &lt;button data-mode=&quot;update&quot; class=&quot;btn btn-sm btn-info&quot; data-toggle=&quot;modal&quot; data-target=&quot;#license-add&quot; data-id=&quot;8&quot;&gt;\n &lt;i class=&quot;far fa-edit&quot;&gt;&lt;/i&gt;\n &lt;/button&gt;\n &amp;nbsp;\n &lt;button data-mode=&quot;delete&quot; class=&quot;btn btn-sm btn-danger&quot; data-toggle=&quot;modal&quot; data-target=&quot;#license-add&quot; data-id=&quot;8&quot;&gt;\n &lt;i class=&quot;far fa-trash-alt&quot;&gt;&lt;/i&gt;\n &lt;/button&gt;\n&lt;/td&gt;\n</code></pre>\n<pre><code>$(table).on('click', 'button', function() {\n const { id, mode } = this.dataset;\n // ...\n});\n</code></pre>\n<p><strong>Always use <code>const</code></strong> when you can - see <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6</a>. <code>let</code> permits reassignment, which makes the code's intent harder to understand at a glance - whenever a developer sees a <code>let</code>, they may well think &quot;This was declared with <code>let</code>, not <code>const</code>, so I need to be on the lookout for where this will get reassigned.&quot;</p>\n<p><strong>Give functions names with verbs</strong> - the <code>loadingOverlay</code> function might be more readable if it was named something like <code>showLoadingOverlay</code> or <code>loadOverlay</code> or something of the sort. (not sure what it does)</p>\n<p><strong>Accidental use of the comma operator</strong> - <code>rowObjects['license', id]</code> is equivalent to <code>rowObjects[id]</code>. Did you mean <code>rowObjects['license' + id]</code>? Consider using a linter to warn you about these sorts of potential mistakes automatically.</p>\n<p><strong>Array keys should be numeric only</strong> - if your keys are going to contain non-numeric strings like <code>license</code>, or if you aren't going to have all elements of an array filled, use an object instead:</p>\n<pre><code>const rowObjects = {};\n</code></pre>\n<p><strong>Assigning titles concisely</strong> can be done by making an object indexed by <code>mode</code> string. When you need to figure out the title to set, just look up the property on the object: see below.</p>\n<p><strong>Abstract separate functionality into functions</strong> - see <a href=\"https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop\" rel=\"nofollow noreferrer\">this anecdote</a>. While you don't have to go <em>that</em> far, if you have a non-trivial block of code that does something somewhat separate from the rest of the code in a section, consider putting it into a function instead. I'd put the population of the <code>$form</code> into a function - see below.</p>\n<p><strong>Button toggling</strong> Instead of <code>needsButton</code> and <code>inputsDisabled</code>, consider hiding both buttons by default, then showing one or the other depending on whether <code>delete</code>, or something other than <code>view</code> was pressed:</p>\n<pre><code>const titlesByMode = {\n add: 'Add new license',\n update: 'Updating license',\n view: 'Viewing license',\n delete: 'Delete this license?',\n};\n$(table).on('click', 'button', function() {\n showLoadingOverlay(false, modal);\n const { id, mode } = this.dataset;\n modalMode = mode;\n if (mode === 'add') {\n $form.find('input').val('');\n } else {\n populateForm(id);\n }\n $form.find(':input').prop('disabled', mode === 'view' || mode === 'delete');\n\n $('h4#modal-title', modal).text(titlesByMode[mode]);\n // Hide both buttons by default:\n $('#submitButton', modal).hide();\n $('#deleteButton', modal).hide();\n if (mode === 'delete') {\n $('#deleteButton', modal).show();\n } else if (mode !== 'view') {\n $('#submitButton', modal).show();\n }\n});\n\nconst populateForm = (id) =&gt; {\n const data = rowObjects['license' + id];\n\n $form.find('input#email').val(data.email);\n $form.find('input#key').val(data.activation_key);\n $form.find('input#expiration').val(moment(data.expiration).format('MM/DD/YYYY'));\n $form.find('select#type-select').val(data.type);\n $form.find('input#hidden-id').val(data.id);\n};\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T03:31:11.870", "Id": "497135", "Score": "0", "body": "The comma in my `rowObjects['license', id]` is intentional, since I'm also using it for other row types (eg `rowObjects['type', id]`, `...['foo', id]`, etc) but with your tips, I would change it to be proper." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T03:07:26.263", "Id": "252350", "ParentId": "252348", "Score": "3" } }, { "body": "<p>You have four modes and for each of them, you need to render UI respectively. So my suggestion is to write four functions to do that. For flexibility's sake in each function, you can have any rendering logic you want. The parts of logic that are duplicated across different modes can be extracted to separate functions. Also, if you want your code to look even cleaner I suggest using a framework like React because of the JSX.</p>\n<p>Here is my solution:</p>\n<pre><code>let modal = 'div#license-add';\nlet $form = $('form#modal-form');\nlet rowObjects = []; // this gets filled up by values on a different function everytime my table generates\nrowObjects[8] = {\n email: 'test@test.com',\n activation_key: 'activation_key',\n expiration: 123,\n type: 'type',\n id: 'id'\n}\n\nconst fillInputs = ($form, { email, activation_key, expiration, type, id }) =&gt; {\n $form.find('input#email').val(email);\n $form.find('input#key').val(activation_key);\n $form.find('input#expiration').val(moment(expiration).format('MM/DD/YYYY'));\n $form.find('select#type-select').val(type);\n $form.find('input#hidden-id').val(id);\n}\n\nconst hideButtons = () =&gt; {\n $('#deleteButton', modal).hide();\n $('#submitButton', modal).hide();\n}\n\nconst showDeleteButton = () =&gt; {\n $('#deleteButton', modal).show();\n $('#submitButton', modal).hide();\n}\n\nconst showSubmitButton = () =&gt; {\n $('#deleteButton', modal).hide();\n $('#submitButton', modal).show();\n}\n\nconst setTitle = (title) =&gt; {\n $('h4#modal-title', modal).text(title);\n}\n\nconst toggleInputs = ($form, isDisabled) =&gt; {\n $form.find(':input').prop('disabled', isDisabled);\n}\n\nconst clearInputs = ($form) =&gt; {\n $form.find(':input').val('');\n}\n\nconst viewMode = ($form, data) =&gt; function () {\n fillInputs($form, data);\n hideButtons();\n setTitle('Viewing license');\n toggleInputs($form, true);\n};\n\nconst addMode = ($form) =&gt; function () {\n clearInputs($form);\n showSubmitButton();\n setTitle('Add new license');\n toggleInputs($form, false);\n};\n\nconst updateMode = ($form, data) =&gt; function () {\n fillInputs($form, data);\n showSubmitButton();\n setTitle('Updating license');\n toggleInputs($form, false);\n};\n\nconst deleteMode = ($form, data) =&gt; function () {\n fillInputs($form, data);\n showDeleteButton();\n setTitle('Delete this license?');\n toggleInputs($form, true);\n};\n\nfunction setModalMode(mode, id) {\n const funcByMode = (mode) =&gt; ({\n 'add': addMode,\n 'view': viewMode,\n 'update': updateMode,\n 'delete': deleteMode,\n }[mode]);\n\n const getUpdater = funcByMode(mode);\n const updateUI = getUpdater($form, rowObjects[id]);\n updateUI();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T14:12:00.687", "Id": "252484", "ParentId": "252348", "Score": "2" } } ]
{ "AcceptedAnswerId": "252350", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T02:01:41.393", "Id": "252348", "Score": "3", "Tags": [ "javascript", "jquery", "html" ], "Title": "JavaScript function that reuses a modal for adding, deleting, and viewing an item" }
252348
<p>So I'm learning typescript and I'm making a simple functional PubSub system. I want the user to be able to define topics and the data for those topics. So far I've got the below code, but I really want to improve it.</p> <p>I'm not sure if I can get rid of the <code>unknown</code> in <code>&lt;T extends Record&lt;string,unknown&gt;&gt;</code>. I don't think that's a huge issue for me. I'd really like to get rid of the Set&lt;Subscriber&gt; part of the map that holds the subscribers. I tried something simple like Set&lt;Subscriber&lt;T[keyof T]&gt;&gt; but then it complains below where I am using <code>&lt;R extends keyof T&gt;</code>. Maybe that's the part that needs fixing?</p> <p>Any and all suggestions welcome of course!</p> <pre><code>type Subscriber&lt;R&gt; = (data: R) =&gt; void; const pubSubber = &lt;T extends Record&lt;string, unknown&gt;&gt;() =&gt; { const subscribers = new Map&lt;keyof T, Set&lt;Subscriber&lt;any&gt;&gt;&gt;(); return { subscribe: &lt;R extends keyof T&gt;(topic: R, subscriber: Subscriber&lt;T[R]&gt;) =&gt; { const current = (subscribers.get(topic) || new Set()) as Set&lt; Subscriber&lt;T[R]&gt; &gt;; current.add(subscriber); subscribers.set(topic, current); return () =&gt; current.delete(subscriber); }, publish: &lt;R extends keyof T&gt;(topic: R, data: T[R]) =&gt; { const toCall = Array.from((subscribers.get(topic) || [])) as Subscriber&lt;T[R]&gt;[]; toCall.map((f) =&gt; f(data)); }, }; }; type Topics = { gear_with_radius: { center: number; radius: number; }; outside: { help: boolean; }; }; const myPubSubber = pubSubber&lt;Topics&gt;(); myPubSubber.publish('gear_with_radius', { center: 10, radius: 5 }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:15:23.627", "Id": "497243", "Score": "0", "body": "There is something strange there. You are using `subscribers.get(topic)` as a `list`, but according to the type it should be `set`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:19:43.040", "Id": "497244", "Score": "0", "body": "@KiraLT - yes, you are correct, my mistake. I'm missing an `Array.from`, will edit." } ]
[ { "body": "<p>I have a few pointers regarding your snippet.</p>\n<h2>Return type</h2>\n<p>Let's start with <code>pubSubber</code> function return type. It's very nice that typescript infers types, but it also a good way to make a mistake. The bad thing about it is that you can accidentally change the return type without knowing it. If you use this function somewhere in the app there is a chance that typescript will notify you about the change. But if you are creating a library and don't have tests, you will change the return type without any error.</p>\n<p>Personally, I like the rule to always specify return type (unless using inline arrow functions). I even use the lint rule to enforce this.</p>\n<h2>Don't use any</h2>\n<p>Change <code>any</code> to <code>unknown</code>. In this case, maybe it doesn't matter at least at the moment, but in the future, you may change this code. With <code>any</code> you can do anything and typescript won't say anything. With <code>unknown</code> you can't do anything, unless you cast it or use type <a href=\"https://www.typescriptlang.org/docs/handbook/advanced-types.html\" rel=\"nofollow noreferrer\">Type Guard</a></p>\n<pre><code>const subscribers = new Map&lt;keyof T, Set&lt;Subscriber&lt;any&gt;&gt;&gt;()\n</code></pre>\n<h2>Don't use cast if possible</h2>\n<p>Let's look into this line.</p>\n<pre><code>const current = (subscribers.get(topic) || new Set()) as Set&lt;\n Subscriber&lt;T[R]&gt;\n&gt;;\n</code></pre>\n<p><code>current</code> real type is <code>Set&lt;Subscriber&lt;any&gt;&gt;</code>, but you cast it to <code>Subscriber&lt;T[R]&gt;</code>. But in this example, there is no point having cast at all, because even without it the code is correctly typed. This function implementation works with any type, so you can leave it as it is. As for the outer interface, it can be more strict.</p>\n<pre><code>const current = subscribers.get(topic) || new Set()\ncurrent.add(subscriber);\nsubscribers.set(topic, current);\nreturn () =&gt; current.delete(subscriber);\n</code></pre>\n<p>Second example is a bit better:</p>\n<pre><code>const toCall = Array.from((subscribers.get(topic) || [])) as Subscriber&lt;T[R]&gt;[];\ntoCall.map((f) =&gt; f(data))\n</code></pre>\n<p>You already had one mistake because of this cast. Also, I don't see any reason to convert <code>Set</code> to the list. You can just loop the <code>Set</code>. And if you combine it with optional chaining, it will look like:</p>\n<pre><code>subscribers.get(topic)?.forEach(f =&gt; f(data));\n</code></pre>\n<h2>Better typing</h2>\n<p>In the previous section, I mentioned <code>casts</code>. But removing casts in theory you lose some typings (adding also lose some typings, dilemma...). Let's try to have full correct typings without any cast. So to start with we need to change <code>Map</code> to <code>Object</code>. <code>Map</code> types do not allow relations between key and value (e. g.: <code>a</code> key must-have number value`).</p>\n<p>Example of relation-based subscribers list:</p>\n<pre><code>const subscribers: {\n [P in keyof T]?: Set&lt;Subscriber&lt;T[P]&gt;&gt;\n} = {}\n</code></pre>\n<h2>Final solution</h2>\n<p>So the final solution can looks like:</p>\n<pre><code>type Subscriber&lt;R&gt; = (data: R) =&gt; void;\ntype BaseTopics = Record&lt;string, unknown&gt;\n\ninterface PubSubber&lt;T extends BaseTopics&gt; {\n subscribe: &lt;R extends keyof T&gt;(topic: R, subscriber: Subscriber&lt;T[R]&gt;) =&gt; () =&gt; void\n publish: &lt;R extends keyof T&gt;(topic: R, data: T[R]) =&gt; void\n}\n\nfunction pubSubber&lt;T extends BaseTopics&gt;(): PubSubber&lt;T&gt; {\n const subscribers: {\n [P in keyof T]?: Set&lt;Subscriber&lt;T[P]&gt;&gt;\n } = {}\n return {\n subscribe(topic, subscriber) {\n const current = subscribers[topic] || new Set();\n current.add(subscriber);\n subscribers[topic] = current;\n return () =&gt; current.delete(subscriber);\n },\n publish(topic, data) {\n subscribers[topic]?.forEach(f =&gt; f(data));\n },\n };\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T21:23:58.890", "Id": "252389", "ParentId": "252352", "Score": "4" } } ]
{ "AcceptedAnswerId": "252389", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T04:02:44.567", "Id": "252352", "Score": "5", "Tags": [ "typescript" ], "Title": "getting inferences working with typescript pubsubber" }
252352
<p>This is my code for an assignment. The task is to take a user input in form of a sequence of parenthesis' followed by an E to mark its end and determine whether it is a correct sequence (as an example <code>(()())E</code> is correct, <code>)(()((E</code> is incorrect) and if incorrect determine how many parentheses at the start you need to remove and how many to add at the end for it to be correct.</p> <p>The code works. But it's super long and I wondered if there were any improvements I could do on it.</p> <pre><code>public class Main { public static String enter(){ String enter = &quot;&quot;; char nextValue ='A'; while (nextValue!='E'){ nextValue = In.readChar(); enter += nextValue; } return enter; } /*User Input. I know this could be done with ArrayList or scanner, but we haven't had these yet in classes. So I did it by converting the user inputs into a string, then storing that string into an array in main with &quot;char []sequence = enter.toCharArray();&quot;*/ public static char[] removeParenthesisPairs(char[] a){ for(int i=0; i&lt;a.length; i++){ if(a[i]=='('){ a[i]='F'; outerloop: for(int j=i+1; j&lt;a.length;j++){ if(a[j]==')'){ a[j]='F'; break outerloop; } if(j==a.length-1){ a[i]='('; } } } } return a; } /*I remove all the correct pairs from the sequence. I look for a ( and turn it into an F [to signal it's removed] and search the rest of the sequence for a ) and turn that into an F too. If there is no ) I turn the F back into (. This part I really don't like, it looks super clunky. Also I have read that the &quot;break outerloop&quot; thing I'm using here is bad practice, but I havent figured out any other way to accomplish the same result.*/ public static boolean checkIfCorrect(char[] a){ for(int i=0;i&lt;a.length-1;i++){ if(a[i]!='F'){ return false; } } return true; } /* I check if the sequence is correct. If there are only F left in the array, that means all entries were able to form pairs of () and the original sequence was correctly parenthesised.*/ public static int subtract(char[] a){ int count = 0; for(int i=0; i&lt;a.length;i++){ if(a[i]==')'){ count += 1; } } return count; } // Check how many ) have to be subtracted at the beginning of the sequence. public static int add(char[] a){ int count = 0; for(int i=0; i&lt;a.length;i++){ if(a[i]=='('){ count += 1; } } return count; } /*Check how many ( are still left in the sequence and need a ) added to form a pair. I am kinda repeating myself here in the subtract() and add() methods, they are essentially doing the same thing. The only way I have figured out for a method to return two values is by making a class. But it seems even more convoluted to add new classes or is it preferable to this solution?*/ public static void main(String[] args) { String enter= enter(); char []sequence = enter.toCharArray(); removeParenthesisPairs(sequence); boolean correct = checkIfCorrect(sequence); int additional = add(sequence); int removed = subtract(sequence); Out.println(correct); Out.println(&quot;removed = &quot; + removed + &quot; und additional = &quot; + additional); } /*I'm required by the assignment to have the boolean correct, int additional and int removed like this. So I can't just do &quot;Out.println(&quot;removed = &quot; + subtract(sequence)+ &quot; und additional = &quot; + add(sequence));&quot;*/ } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:03:43.840", "Id": "497251", "Score": "3", "body": "What should happen for `())(E`? Do you always remove things from the start up to the error, and add `)` to balance it out (removed = 3, additional = 1)? Or do you scan through and say we're going to ignore 1 impossible `)` then add one `)` at the end to balance it (removed = 1, additional = 1)?" } ]
[ { "body": "<p><code>break</code> is not a bad thing. Labels and <code>goto</code> are normally avoided. You are just breaking out of one loop, so you can just delete the <code>outerloop:</code> label and <code>break;</code> normally.</p>\n<hr />\n<p>Comments at a method level are normally given with <code>/** ... */</code> (JavaDoc syntax) above the method.</p>\n<hr />\n<p>The trend is to avoid updating arrays in place (mutating), and instead just prefer returning new copies of the array (think of things as immutable), because when you mutate things it <em>can sometimes be</em> harder to keep track of state and easier to write incorrect code.</p>\n<p>That's not to say it's <em>wrong</em> to do it with mutation. However, it might be better to keep mutation under control in the <code>private</code> parts of your code, so that if somebody re-uses your code, <em>they</em> don't have to worry about sequencing the method calls in the right order.</p>\n<hr />\n<p>Presumably <code>In</code> is something provided by your course? Since I didn't have that, I just did the <code>Scanner</code> implementation to test with.</p>\n<hr />\n<p>Here's your own code again, just with small changes as per the above comments, and formatted with 4 spaces (which seems to be more common these days).</p>\n<pre><code>import java.util.Scanner;\n\npublic class Main {\n\n public static void process(String s) {\n char[] sequence = s.toCharArray();\n removeParenthesisPairs(sequence);\n \n /*\n * I'm required by the assignment to have the boolean correct, int additional\n * and int removed like this. So I can't just do &quot;Out.println(&quot;removed = &quot; +\n * subtract(sequence)+ &quot; und additional = &quot; + add(sequence));&quot;\n */\n boolean correct = checkIfCorrect(sequence);\n int additional = add(sequence);\n int removed = subtract(sequence);\n System.out.println(correct);\n System.out.println(&quot;removed = &quot; + removed + &quot; und additional = &quot; + additional);\n }\n \n /**\n * I remove all the correct pairs from the sequence. I look for a ( and turn it\n * into an F [to signal it's removed] and search the rest of the sequence for a\n * ) and turn that into an F too. If there is no ) I turn the F back into (.\n * This part I really don't like, it looks super clunky.\n */\n private static char[] removeParenthesisPairs(char[] a) {\n for (int i = 0; i &lt; a.length; i++) {\n if (a[i] == '(') {\n a[i] = 'F';\n for (int j = i + 1; j &lt; a.length; j++) {\n if (a[j] == ')') {\n a[j] = 'F';\n break;\n }\n if (j == a.length - 1) {\n a[i] = '(';\n }\n }\n }\n }\n return a;\n }\n\n /**\n * I check if the sequence is correct. If there are only F left in the array,\n * that means all entries were able to form pairs of () and the original\n * sequence was correctly parenthesised.\n */\n private static boolean checkIfCorrect(char[] a) {\n for (int i = 0; i &lt; a.length - 1; i++) {\n if (a[i] != 'F') {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Check how many ) have to be subtracted at the beginning of the sequence.\n */\n private static int subtract(char[] a) {\n int count = 0;\n for (int i = 0; i &lt; a.length; i++) {\n if (a[i] == ')') {\n count += 1;\n }\n }\n return count;\n }\n\n /**\n * Check how many ( are still left in the sequence and need a ) added to form a\n * pair. I am kinda repeating myself here in the subtract() and add() methods,\n * they are essentially doing the same thing. The only way I have figured out\n * for a method to return two values is by making a class. But it seems even\n * more convoluted to add new classes or is it preferable to this solution?\n */\n private static int add(char[] a) {\n int count = 0;\n for (int i = 0; i &lt; a.length; i++) {\n if (a[i] == '(') {\n count += 1;\n }\n }\n return count;\n }\n\n public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in)) {\n process(scanner.next());\n }\n }\n\n}\n</code></pre>\n<hr />\n<p>Before I looked at your code, I attempted the problem myself. Here's what I came up with - take from it what you will or leave it. I think our two versions produce different outputs for some inputs - that could be different interpretations of the problem, or one of us has got bugs! (Edit: Actually, they do seem to be the same after all).</p>\n<pre><code>import java.util.Scanner;\n\npublic class Parens {\n\n public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in)) {\n System.out.print(&quot;Input: &quot;);\n Parens.displayBalancing(scanner.next());\n System.out.println();\n }\n\n System.out.println(&quot;Extra tests cases&quot;);\n for (String test : new String[] { &quot;(()())E&quot;, &quot;)(()((E&quot;, &quot;())(E&quot; }) {\n Parens.displayBalancing(test);\n }\n }\n\n public static void displayBalancing(String s) {\n Parens.Changes changes = balance(s);\n System.out.format(&quot;removed: %-2d additional: %-2d correct: %-5b input: %s\\n&quot;,\n changes.removed, changes.additional, changes.isNoChanges(), s);\n }\n\n public static class Changes {\n int removed;\n int additional;\n\n Changes(int remove, int add) {\n this.removed = remove;\n this.additional = add;\n }\n\n public boolean isNoChanges() {\n return removed == 0 &amp;&amp; additional == 0;\n }\n }\n\n public static Changes balance(String s) throws IllegalArgumentException {\n return balance(s.toCharArray(), 0, 0);\n }\n\n private static Changes balance(char[] characters, final int remove, final int add)\n throws IllegalArgumentException {\n int open = 0;\n for (char c : characters) {\n switch (c) {\n case '(':\n open++;\n break;\n case ')':\n if (open == -remove) {\n // got close paren but none are open\n return balance(characters, remove + 1, add);\n }\n open--;\n break;\n case 'E':\n if (open != add - remove) {\n // got E but some parens are still open\n return balance(characters, remove, add + 1);\n }\n // balanced\n return new Changes(remove, add);\n default:\n throw (new IllegalArgumentException(\n String.format(&quot;Unexpected character '%c'&quot;, c)));\n }\n }\n throw (new IllegalArgumentException(&quot;String didn't contain an E&quot;));\n }\n\n}\n</code></pre>\n<p>Then I realised your approach was actually pretty good. This should work too:</p>\n<pre><code> public static Changes balance2(String s) {\n while (s.contains(&quot;()&quot;)) {\n s = s.replace(&quot;()&quot;, &quot;&quot;);\n }\n int remove = 0;\n int add = 0;\n for (char c: s.toCharArray()) {\n if (c == 'E') {\n break;\n } else if (c == '(') {\n add++;\n } else if (c == ')') {\n remove++;\n }\n }\n return new Changes(remove, add);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T00:21:10.157", "Id": "252394", "ParentId": "252358", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T09:10:54.237", "Id": "252358", "Score": "8", "Tags": [ "java", "homework", "balanced-delimiters" ], "Title": "Parenthesis-realigning program" }
252358
<p>I'm trying to optimize my solution to the following question:</p> <blockquote> <p>given a regular expression with chars and special char '*', (star which is a joker we can replace with any string), and a string, write a program which determines if the regular expression can represent that string or not. for example: &quot;a'*b&quot; can represent &quot;aaaacbbbb&quot; , in contrast &quot;a'*b'*c&quot; cant represent &quot;aaaabcccccccccb&quot;</p> </blockquote> <p>I solved the problem and inserted the code below, I want to optimize either space or time, and if possible to make it more readable or shorter.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int compareHelper(char *s, char *regex, int star); int compareStrings(char *s, char *r); int main() { printf(&quot;%d\n&quot;, compareStrings(&quot;aaaacbbb&quot;, &quot;a*b&quot;)); printf(&quot;%d\n&quot;, compareStrings(&quot;aaaabccccccccb&quot;, &quot;a*b*c&quot;)); return 0; } //aaaaacbbb //a*b int compareStrings(char *s, char *r) { return compareHelper(s, r, 0); } int compareHelper(char *s, char *regex, int star) { if (*s == '\0' &amp;&amp; *regex == '\0') { return 1; } else if (*regex == '*') { return compareHelper(s, regex + 1, 1); // star is seen hence will be set to true. } else { if (!star) { if (*s != *regex) { // star was not seen and they differ in char return 0; } else { return compareHelper(s + 1, regex + 1, star); } } else { while (*s &amp;&amp; *s != *regex) { s++; } if (*s == '\0') return 0; else { return compareHelper(s + 1, regex + 1, 0) | compareHelper(s + 1, regex, 1); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T21:26:14.813", "Id": "497247", "Score": "0", "body": "Looks like someone doesn't know what regular expressions are. Where is that from? And what's up with those single-quotes in \"a'*b'*c\"?" } ]
[ { "body": "<p>Move your <code>main()</code> to the bottom, so you don't have to declare other functions, it's also less prone to errors.</p>\n<p><code>'*'</code> is not called a <em>star</em>, but it's called an <em>asterisk</em>.</p>\n<p>Instead of using an additional function for hiding the argument <code>int star</code>, which acts as a memory, reduce to only one function and use a <code>static int star</code> as a function variable within that function.</p>\n<p>I find your approach of a self calling recursive function interesting. You should make sure that it becomes never to an infinity loop, by counting each calls, probably within another <code>static int</code> function variable.</p>\n<p>Please add some more comments, especially about the functionality of your function.</p>\n<p>PS What happens when your search pattern argument begins with an asterisk, like <code>&quot;*a*b*c&quot;</code>?</p>\n<p>PPS if your goal is to achieve the most performant solution, a self calling recursive function is not the fastest way to accomplish. Using a clever loop would be faster, you might even just use a <code>goto</code> to jump back to your function top line.</p>\n<p>Example:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n//uncomment the following line when using threads\n//#include &lt;threads.h&gt;\n\n\nint compareStrings(char *s, char *regex)\n{\n //uncomment thread_local when using threads\n /*thread_local*/ static int star = 0;\n \n START:\n if (*s == '\\0' &amp;&amp; *regex == '\\0')\n {\n return 1;\n } else if (*regex == '*')\n {\n //return compareHelper(s, regex + 1, 1); // star is seen hence will be set to true.\n regex++;\n star = 1;\n goto START;\n } else\n {\n if (!star)\n {\n if (*s != *regex)\n { // star was not seen and they differ in char\n return 0;\n } else\n {\n //return compareHelper(s + 1, regex + 1, star);\n s++;\n regex++;\n goto START;\n }\n\n } else\n {\n while (*s &amp;&amp; *s != *regex)\n {\n s++;\n }\n if (*s == '\\0') return 0;\n else\n {\n //I'm pretty sure your return statement can be reduced to a more elementar statement.\n //PS I'm not reducing it for you.\n //return compareHelper(s + 1, regex + 1, 0) | compareHelper(s + 1, regex, 1);\n star = 0;\n int a = compareStrings(s + 1, regex + 1);\n star = 1;\n int b = compareStrings(s + 1, regex);\n \n return a | b;\n }\n }\n }\n}\n\nint main()\n{\n printf(&quot;%d\\n&quot;, compareStrings(&quot;aaaacbbb&quot;, &quot;a*b&quot;));\n printf(&quot;%d\\n&quot;, compareStrings(&quot;aaaabccccccccb&quot;, &quot;a*b*c&quot;));\n return 0;\n\n}\n</code></pre>\n<p>PPPS please rethink about that statement: <code>return compareHelper(s + 1, regex + 1, 0) | compareHelper(s + 1, regex, 1);</code>, it probably can be simplified.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T12:53:41.850", "Id": "497161", "Score": "0", "body": "`*` is quite often called \"star\". At least round here, that is - it may vary by location." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T12:55:50.057", "Id": "497162", "Score": "0", "body": "There's no need for `goto` there - just use an ordinary loop (the non-`goto` cases all return, unless I'm missing something)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T12:58:50.923", "Id": "497163", "Score": "0", "body": "@TobySpeight I agree, but for an ordinary loop, OP would probably have to rewrite his entire function. A `goto` is a fast way to achieve higher performance with less work. PS I'm pretty sure OP's implementation of `return compareHelper(s + 1, regex + 1, 0) | compareHelper(s + 1, regex, 1);` is producing a lot of overhead, thus reducing performance. Some clever use of `if...if else...else` would surely help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:04:17.907", "Id": "497164", "Score": "0", "body": "I don't think encouraging the use of `goto` is a good thing; it might be a good idea to show how that's just a stepping stone to the loop (which is trivial from what you show here)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:05:34.857", "Id": "497165", "Score": "0", "body": "Yes, I would also try to rewrite the entire function. `goto` is probably not needed in this scenario." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:08:50.223", "Id": "497166", "Score": "1", "body": "Seriously, it's just a matter of removing the `goto`s and replacing the `START:` label with `for (;;)`. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:30:41.943", "Id": "497175", "Score": "1", "body": "The `static` variable is wrong here. There is absolutely no need to have a global variable here. The function that checks whether the pattern matches the string must be side-effect free." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:03:51.217", "Id": "497178", "Score": "0", "body": "@RolandIllig No, `static` variable is needed, because the function calls itself. It became a necessity when I removed the helper function of OP, because that acted as a memory. But I agree with you, that there is for sure a solution without the need of a `static` variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:06:06.960", "Id": "497181", "Score": "0", "body": "The `static` variable is wrong because it makes the code fail mysteriously in a multi-threaded environment, as soon as the function is called from two threads at the same time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:13:50.903", "Id": "497184", "Score": "0", "body": "@RolandIllig just use `#include <threads.h>` **...** `thread_local static int star = 0;`, it's not that hard and your program won't mysteriously fail in a multi-threaded environment ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:20:27.240", "Id": "497186", "Score": "0", "body": "That's a good idea. You should really put that suggestion into your answer itself, instead of publishing the broken code that it is right now." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:58:51.900", "Id": "252364", "ParentId": "252360", "Score": "2" } }, { "body": "<pre><code>// The main function that checks if two given strings \n// match. The first string may contain wildcard characters \nbool match(char *first, char *second)\n{\n // If we reach at the end of both strings, we are done\n if (*first == '\\0' &amp;&amp; *second == '\\0')\n return true;\n\n // Make sure that the characters after '*' are present\n // in second string. This function assumes that the first\n // string will not contain two consecutive '*'\n if (*first == '*' &amp;&amp; *(first + 1) != '\\0' &amp;&amp; *second == '\\0')\n return false;\n\n // If the first string contains '?', or current characters\n // of both strings match\n if (*first == *second)\n {\n return match(first + 1, second + 1);\n }\n\n // If there is *, then there are two possibilities\n // a) We consider current character of second string\n // b) We ignore current character of second string.\n if (*first == '*')\n return match(first + 1, second) || match(first, second + 1);\n return false;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:07:49.177", "Id": "497183", "Score": "2", "body": "Your \"answer\" does not qualify as a code review. You have merely written some code of your own, without even trying to discuss the original code. This makes your \"answer\" off-topic here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:10:57.800", "Id": "497327", "Score": "0", "body": "`You have merely written some code of your own` He did it again! He already has written the OP! How confusing. And ridiculous." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:50:16.437", "Id": "252368", "ParentId": "252360", "Score": "-2" } }, { "body": "<p>The code you wrote can be improved in lots of places. I'll go through it from top to bottom.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n</code></pre>\n<p>Perfect until now. The <code>#include</code> lines from the C standard library should be in alphabetic order. I cannot say whether you did this intentionally or not since there's a 50-50 chance. :)</p>\n<pre class=\"lang-c prettyprint-override\"><code>int compareHelper(char *s, char *regex, int star);\n</code></pre>\n<p>This function should be declared as <code>static</code>, since it is local to this file. To do this, replace the <code>int compareHelper</code> with <code>static int compareHelper</code>.</p>\n<p>The <code>compare</code> in the function name is wrong. Typically, to compare two things, they have to be of the same or at least a compatible type. The technical type here is <code>char *</code>, but on a more abstract level, <code>s</code> is an arbitrary string while <code>regex</code> is a string with some constraints. Instead of <code>compare</code>, this function should be called <code>match</code>.</p>\n<p>The type of the string parameters should be <code>const char *</code> instead of <code>char *</code> since this function does not modify the characters of these strings.</p>\n<p>The type of the parameter <code>star</code> should be <code>bool</code> instead of <code>int</code>. To get this type, you have to add <code>#include &lt;stdbool.h&gt;</code> along with the other <code>#include</code> lines.</p>\n<p>The name of the parameter <code>regex</code> is wrong. The word <code>regex</code> means regular expression, and this is a fixed term with a precise definition. Your patterns are not regular expressions, therefore the parameter name confuses the reader. Better call it <code>pattern</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>int compareStrings(char *s, char *r);\n</code></pre>\n<p>Again, the <code>compare</code> should rather be <code>match</code>, the parameter types should get an additional <code>const</code>, and the return type should be <code>bool</code> instead of <code>int</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>int main()\n{\n printf(&quot;%d\\n&quot;, compareStrings(&quot;aaaacbbb&quot;, &quot;a*b&quot;));\n printf(&quot;%d\\n&quot;, compareStrings(&quot;aaaabccccccccb&quot;, &quot;a*b*c&quot;));\n return 0;\n}\n</code></pre>\n<p>The empty parentheses <code>()</code> in the function declaration of <code>main</code> mean that the function can take any number of parameters. In C, this is only allowed for legacy code from 1990 and earlier. In modern code, write <code>(void)</code> instead to clearly say that there must be no parameters.</p>\n<pre class=\"lang-c prettyprint-override\"><code>//aaaaacbbb\n//a*b\n</code></pre>\n<p>This is the beginning of documentation, which is a good idea. To be useful for other readers, you should write in whole sentences though, for example:</p>\n<blockquote>\n<pre class=\"lang-c prettyprint-override\"><code>// See if the string s matches the pattern p.\n// In the pattern, '*' matches an arbitrarily long sequence of arbitrary characters.\n</code></pre>\n</blockquote>\n<pre class=\"lang-c prettyprint-override\"><code>int compareHelper(char *s, char *regex, int star)\n{\n if (*s == '\\0' &amp;&amp; *regex == '\\0')\n {\n return 1;\n } else if (*regex == '*')\n</code></pre>\n<p>After the <code>return 1</code>, the <code>else</code> is unnecessary. I would write the code like this instead:</p>\n<blockquote>\n<pre class=\"lang-c prettyprint-override\"><code> if (*s == '\\0' &amp;&amp; *regex == '\\0') {\n return 1;\n }\n\n if (*regex == '*') {\n ...\n</code></pre>\n</blockquote>\n<p>This way, your code has one topic per paragraph. The empty line between the topics clearly marks a pointer where the reader may stop reading and take a deep breath, before starting to read the next paragraph.</p>\n<p>The rest of the code looks fine, except for this line:</p>\n<pre class=\"lang-c prettyprint-override\"><code>return compareHelper(s + 1, regex + 1, 0) | compareHelper(s + 1, regex, 1);\n</code></pre>\n<p>The operator <code>|</code> means a logical or, and it always evaluates both operands. This means that <code>compareHelper</code> is called twice, even if the left-hand side already evaluates to <code>true</code>. This is not necessary. To only evaluate the necessary parts of the condition, replace the <code>|</code> operator with <code>||</code>.</p>\n<p>All in all, the code is not too long. What makes it look verbose is that you put each <code>{</code> or <code>}</code> on its own line. You can rewrite it like this:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdbool.h&gt;\n\nint compareHelper(const char *s, const char *regex, bool star)\n{\n if (*s == '\\0' &amp;&amp; *regex == '\\0')\n return true;\n\n if (*regex == '*')\n return compareHelper(s, regex + 1, 1); // star is seen hence will be set to true.\n\n if (!star) {\n if (*s != *regex)\n return false; // star was not seen and they differ in char\n else\n return compareHelper(s + 1, regex + 1, star);\n }\n\n // seen a star; look for the text after the star\n while (*s &amp;&amp; *s != *regex)\n s++;\n\n if (*s == '\\0')\n return 0;\n\n return compareHelper(s + 1, regex + 1, 0) || compareHelper(s + 1, regex, 1);\n}\n</code></pre>\n<p>Some people will complain that &quot;you must always use braces in <code>if</code> and <code>while</code> statements&quot;, but that's not necessary. If you properly indent your code or let your IDE format the code automatically, the indentation properly expresses the relation of the code pieces to each other. The typical example is:</p>\n<pre class=\"lang-c prettyprint-override\"><code>if (condition)\n goto fail;\n goto fail;\n</code></pre>\n<p>Modern compilers not only translate the source code to machine code, they also check for various possible bugs in the code. <a href=\"https://developers.redhat.com/blog/2016/02/26/gcc-6-wmisleading-indentation-vs-goto-fail/\" rel=\"nofollow noreferrer\">Wrong indentation like in the above snippet</a> is one of them.</p>\n<p>And <a href=\"https://github.com/NetBSD/src/blob/6d560de87d182b1762fbc04e97f0401c504e1759/usr.bin/make/str.c#L268\" rel=\"nofollow noreferrer\">here's a complete implementation</a> that also matches character ranges like <code>[A-Z]</code>. The code looks remarkably similar to yours, which is good. If you take that code and remove the part that handles the <code>[A-Z]</code> part, it will be very similar to your code. Actually, taking other people's code and editing it just trying to understand it is an efficient way of thinking about why each of these lines of code is actually necessary.</p>\n<p>While reading that code, you may notice that your code might fail for <code>str_match(&quot;a good game&quot;, &quot;a *game&quot;)</code>. You should verify that the search after the star looks at every possible position in the string, not only the first time the letter <code>g</code> appears.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:48:47.263", "Id": "497192", "Score": "0", "body": "The lack of braces `{` and `}` reduces the maintainability of the code. I agree they take up vertical space but I live with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:07:30.720", "Id": "497228", "Score": "0", "body": "@Roland Illig, I very much appreciate your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T21:58:54.020", "Id": "497249", "Score": "0", "body": "@pacmaninbw That's exactly what I predicted: \"Some people will complain\". But I also explained in which environment (automatically formatted code) the braces are completely redundant and just take up screen space. Your argument \"reduces the maintainability of the code\" is quite abstract, it could mean anything." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:57:31.847", "Id": "252371", "ParentId": "252360", "Score": "4" } }, { "body": "<p>This (non recursive) solution has more lines, but simpler ones. The <code>break</code> out of the inner loop was not so easy to find -- first I had no <code>else</code>, and more <code>continue</code> and braces...</p>\n<pre><code>#include &lt;stdio.h&gt;\n\n/* Return 0 if matches. Otherwise some high number */\nint glob_str(char *glob, char *str) {\n\n int starred = 0, i;\n int jperm = 0, j;\n\n for (i = 0; glob[i] != '\\0'; i++) {\n \n if (glob[i] == '*') {\n starred = 1;\n continue;\n }\n if (starred) { \n for (j = jperm;;) {\n if (str[j] == '\\0') \n return i + 1000;\n if (str[j++] == glob[i]) \n break; \n }\n jperm = j; \n starred = 0;\n } \n else \n if (glob[i] != str[jperm++]) \n return i + 2000;\n }\n /* Check if str is unfinished - wildcard vs. regex */\n if (!starred &amp;&amp; str[jperm])\n return 99;\n /* Match */\n return 0;\n}\n\nint main() {\n char *string = &quot;abccccec&quot;;\n char *globex = &quot;abc*ec&quot;;\n int diff = glob_str(globex, string);\n printf(&quot;diff: %d (tried globex=%s on string=%s)\\n&quot;, diff, globex, string);\n return 0;\n}\n</code></pre>\n<p>The recursive version looks very short, like 4 lines. But if you format these lines into more regular chunks, it amounts to about the same.</p>\n<pre><code>bool match(char *first, char *second)\n{\n if (*first == '\\0' &amp;&amp; *second == '\\0')\n return true;\n\n if (*first == '*' &amp;&amp; *(first + 1) != '\\0' &amp;&amp; *second == '\\0')\n return false;\n\n if (*first == *second)\n return match(\n first + 1, second + 1);\n\n if (*first == '*')\n return \n match( first + 1, second) ||\n match( first, second + 1);\n\n return false;\n}\n</code></pre>\n<h2>Compact version</h2>\n<p>With pointers and <code>while</code>.</p>\n<p>After some rearrangements. The <code>g</code> and <code>s</code> variables are not necassary. But now it is clear where the pointers are incremented (<code>str++</code> in two places). The first version makes a fuss about <code>j</code> and <code>jperm</code> -- I realize now that both pointers/indexes advance only forward.</p>\n<pre><code>int glob_str(char *glob, char *str) {\n\n int starred = 0;\n char g, s;\n\n while ((g = *glob++) != '\\0') {\n\n if (g == '*') {\n starred = 1;\n continue;\n }\n if (starred) {\n while ((s = *str++) != g)\n if (s == '\\0')\n return 1;\n starred = 0;\n }\n else\n if (*str++ != g)\n return 2;\n }\n if (!starred &amp;&amp; *str)\n return 99; \n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:28:44.907", "Id": "497306", "Score": "0", "body": "You have presented alternative solutions, but haven't reviewed the code. Please explain your reasoning (how your solution works and _why_ it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:39:26.183", "Id": "252383", "ParentId": "252360", "Score": "0" } } ]
{ "AcceptedAnswerId": "252383", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T11:05:05.923", "Id": "252360", "Score": "5", "Tags": [ "performance", "c", "pattern-matching" ], "Title": "Check if a given string matches a wildcard pattern" }
252360
<p>Hi I coded a simple app that allows user to generate border radius and then copy it to clipboard. <br></p> <p>I already found out how big is the impact from your reviews guys. My code is slowly improving. <br> If someone could point out mistakes etc. in my code I would be grateful.</p> <p><strong><a href="https://github.com/Isaayy/Small-JS-projects/tree/master/Border%20radius" rel="nofollow noreferrer">Repo on github</a></strong></p> <p>HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style/style.css&quot;&gt; &lt;title&gt;Border radius&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;main&gt; &lt;div class=&quot;header&quot;&gt; &lt;h2&gt;CSS border radius&lt;/h2&gt; &lt;p class=&quot;description&quot;&gt;CSS property rounds the corners of an element's outer border edge.&lt;/p&gt; &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius&quot; target=&quot;_blank&quot;&gt;Learn more&lt;/a&gt; &lt;/div&gt; &lt;div class='container'&gt; &lt;div class=&quot;inputs&quot;&gt; &lt;input type=&quot;text&quot;&gt; &lt;input type=&quot;text&quot;&gt; &lt;input type=&quot;text&quot;&gt; &lt;input type=&quot;text&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;copyBtn&quot;&gt; &lt;img src=&quot;img/clipboard.svg&quot; alt=&quot;clipboard&quot;&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;shape&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;button class=&quot;resetBtn&quot;&gt; &lt;img src=&quot;img/refresh-outline.svg&quot; alt=&quot;refresh&quot;&gt; &lt;/button&gt; &lt;/main&gt; &lt;script src='script.js'&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>JS</p> <pre><code>'use strict'; const radiusSettings = document.querySelectorAll('input'); const copySettings = document.querySelector('.copyBtn'); const resetBtn = document.querySelector('.resetBtn'); const box = document.querySelector('.shape'); let settings = []; const clearSettings = () =&gt; { settings = []; }; const isUnit = (input) =&gt; { const units = ['px', 'in', 'pc', 'pt', 'em', 'rem', '%']; for (const unit of units) { if (input.includes(unit)) return true; } return false; }; const setRadius = (direction, value) =&gt; { if (!isUnit(value)) value = value + 'px'; // set px if input is without unit switch (direction) { case 'TL': box.style.borderTopLeftRadius = value; settings.push(['border-top-left-radius: ', value]); break; case 'TR': box.style.borderTopRightRadius = value; settings.push(['border-top-right-radius: ', value]); break; case 'BR': box.style.borderBottomRightRadius = value; settings.push(['border-bottom-right-radius: ', value]); break; case 'BL': box.style.borderBottomLeftRadius = value; settings.push(['border-bottom-left-radius: ', value]); break; } }; for (let i = 0; i &lt; radiusSettings.length; i++) { radiusSettings[i].addEventListener('blur', () =&gt; { if (radiusSettings[i].value) { switch (i) { case 0: setRadius('TL', radiusSettings[i].value); break; case 1: setRadius('TR', radiusSettings[i].value); break; case 2: setRadius('BR', radiusSettings[i].value); break; case 3: setRadius('BL', radiusSettings[i].value); break; } } }); } resetBtn.addEventListener('click', () =&gt; { for (let i = 0; i &lt; radiusSettings.length; i++) { radiusSettings[i].value = ''; box.style.borderRadius = 0; clearSettings(); } }); copySettings.addEventListener('click', () =&gt; { const el = document.createElement('textarea'); for (let i = 0; i &lt; settings.length; i++) { el.value += `${settings[i][0]}: ${settings[i][1]};\n`; } clearSettings(); document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); }); </code></pre> <p>CSS:</p> <pre><code>@import url(&quot;https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&amp;display=swap&quot;); *, *::after, *::before { padding: 0; margin: 0; -webkit-box-sizing: border-box; box-sizing: border-box; font-family: 'Roboto', sans-serif; } body { height: 100vh; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; background: #343434; } main { background-color: white; width: 50%; height: 30rem; border-radius: 10px; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; position: relative; } .header { background-color: #f1f1f1; text-align: center; padding: 2rem 2rem; border-radius: 10px; } .header h2 { font-weight: 500; font-size: 1.2rem; margin-bottom: 0.5rem; } .header .description { font-size: 0.9rem; font-weight: 300; } .header a { color: #da4453; text-decoration: none; font-size: 0.8rem; display: inline-block; margin-top: 0.4rem; font-weight: 500; } .container { -webkit-box-flex: 1; -ms-flex: 1; flex: 1; padding: 2rem 0; } .container .inputs { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .container .inputs input { padding: 0.5rem 0.5rem; text-align: center; width: 5rem; } .container .inputs input:not(:first-child) { margin-left: 1rem; } .container .shape { background: -webkit-gradient(linear, left top, right bottom, from(#bc4e9c), to(#f80759)); background: linear-gradient(to bottom right, #bc4e9c, #f80759); width: 15rem; height: 7rem; margin: 0 auto; position: relative; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); } .copyBtn { margin-left: 1rem; } .copyBtn img { width: 2rem; } .resetBtn { position: absolute; right: 1rem; top: 1rem; border: none; cursor: pointer; } .resetBtn img { width: 1.2rem; } /*# sourceMappingURL=style.css.map */ </code></pre>
[]
[ { "body": "<p><strong>Make Copy to Clipboard more prominent</strong> Unless you tell the user that the button on the right copies the rule to the clipboard, they probably won't know that's what it does. Consider adding text around it (or at least a tooltip), and maybe a <code>:hover</code> rule to clearly show that it's clickable. Maybe also consider adding a tooltip to the refresh button - it doesn't refresh the page, but it resets the input fields.</p>\n<p><strong>Use precise variable names</strong> <code>resetBtn</code> is a good name since it clearly indicates what the variable contains. <code>radiusSettings</code> and <code>copySettings</code>, not so much:</p>\n<ul>\n<li><p>One might well expect something named <code>settings</code> to be an object containing individual settings - but these are inputs and buttons, so better to call them that.</p>\n</li>\n<li><p><code>copySettings</code> contains a single element, so it shouldn't be plural. Maybe use <code>copyToClipboardButton</code>.</p>\n</li>\n<li><p>Given that you're working with DOM elements, the <code>input</code> in <code>const isUnit = (input) =&gt; {</code> sounds ambiguous - it's the input <em>string</em>, not an input <em>element</em>. Maybe call it <code>inputValue</code>.</p>\n</li>\n<li><p>The <code>settings</code> variable is an array of arrays of CSS rules. Maybe call it <code>cssRules</code> instead (or remove the variable entirely - see below)</p>\n</li>\n</ul>\n<p><strong>Prefer array methods</strong> Regarding <code>isUnit</code>, when you want to go through an array and do something, usually the first thing to consider is whether you can use any of the many <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Instance_methods\" rel=\"nofollow noreferrer\">array methods</a> to achieve it. Here, you can use <code>Array.prototype.some</code> - it's more semantic and concise than a <code>for</code> loop:</p>\n<pre><code>const units = ['px', 'in', 'pc', 'pt', 'em', 'rem', '%'];\nconst isUnit = inputValue =&gt; units.some(unit =&gt; inputValue.endsWith(unit));\n</code></pre>\n<p>(since these substrings always come at the end, better to use <code>endsWith</code> than <code>includes</code>)</p>\n<p><strong><code>settings</code> array</strong> This is structured as an array of arrays, but the inner sub-arrays are only used for the creation of a string later:</p>\n<pre><code>el.value += `${settings[i][0]}: ${settings[i][1]};\\n`;\n</code></pre>\n<p>How about putting <em>just</em> the string into the array instead, to avoid the unnecessary intermediate data structure, like this?</p>\n<pre><code>settings.push('border-top-left-radius: ' + value);\n</code></pre>\n<p>Or, even better:</p>\n<p><strong>Duplicate rules</strong> If someone changes a single input multiple times, they'll get duplicate rules, eg:</p>\n<pre><code>border-top-left-radius: : 1px;\nborder-top-left-radius: : 13px;\nborder-top-left-radius: : 135px;\n</code></pre>\n<p>Fix it by using an object indexed by rule name instead of an array for <code>settings</code>, so that prior rules with the same name get overwritten.</p>\n<p><strong><code>switch</code> is usually unnecessarily verbose and WET</strong> so I'd recommend avoiding it if it happens to be possible to refactor by using an object or array instead of <code>case</code>s. Here, your <code>setRadius</code> and input listeners can be replaced entirely with:</p>\n<pre><code>const shortRuleNames = ['top-left', 'top-right', 'bottom-right', 'bottom-left'];\nradiusInputs.forEach((input, i) =&gt; {\n input.addEventListener('click', () =&gt; {\n const ruleName = `border-${shortRuleNames[i]}-radius`;\n cssRules[ruleName] = input.value;\n });\n});\n</code></pre>\n<p><strong>Constructing the clipboard text</strong> As mentioned earlier, use array methods when possible. Your original approach:</p>\n<pre><code>for (let i = 0; i &lt; settings.length; i++) {\n el.value += `${settings[i][0]}: ${settings[i][1]};\\n`;\n}\n</code></pre>\n<p>can avoid the <code>for</code> loop by doing instead:</p>\n<pre><code>el.value = settings\n .map(items =&gt; `${items[0]}: ${items[1]}`)\n .join('\\n');\n</code></pre>\n<p>Or, by using the <code>cssRules</code> object instead of the <code>settings</code> object:</p>\n<pre><code>el.value = Object.values(cssRules).join('\\n');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:46:59.883", "Id": "497203", "Score": "0", "body": "thank you , I appreciate your time and effort" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:38:21.053", "Id": "252374", "ParentId": "252365", "Score": "1" } }, { "body": "<p>In my review, I won't give any specific guidelines of what you should or shouldn't do. Instead, I will try to express my thought process for improving your code. I hope that will be useful for you.</p>\n<p>I am reading the description of the problem you want to solve and running your application. Now I have a good understanding of what you want to achieve. I notice\nthe functionality of copying text to the clipboard. It's definitely independent of the main application logic so I immediately write the <code>copyToClipboard</code> function:</p>\n<pre><code>const copyToClipboard = (text) =&gt; {\n const el = document.createElement('textarea');\n el.style.position = 'absolute';\n el.style.top = '0';\n el.style.left = '0';\n el.value = text;\n\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n};\n</code></pre>\n<p>Does the application have a state? Yes, because you use it to generate CSS text for copying it to clipboard and to update styles in UI to show the end result. How state should look like? The simplest representation is an object:</p>\n<pre><code>const initialState = {\n topLeft: '0px',\n topRight: '0px',\n bottomRight: '0px',\n bottomLeft: '0px',\n}\n</code></pre>\n<p>Since we have a state we need to notify other parts of the code of its changes. Also, we need the ability to set and get a state. After a few iterations, I come up with the following class:</p>\n<pre><code>class State {\n constructor(initial) {\n this._state = initial;\n this._subscribers = [];\n }\n\n set(partialState) {\n this._state = { ...this._state, ...partialState };\n this.notify();\n }\n\n notify() {\n this._subscribers.forEach((cb) =&gt; cb(this._state));\n }\n\n get() {\n return this._state;\n }\n\n onUpdate(cb) {\n this._subscribers.push(cb);\n }\n}\n</code></pre>\n<p>The first thing I want to implement is updating box styles in UI reflected by updating the state. So I instantiate my state:</p>\n<pre><code>const state = new State(initialState);\n</code></pre>\n<p>I don't like that ordering of inputs in UI can affect business logic so I decide to use data attributes for inputs:</p>\n<pre><code>&lt;input type=&quot;text&quot; data-id=&quot;top-left&quot;&gt;\n&lt;input type=&quot;text&quot; data-id=&quot;top-right&quot;&gt;\n&lt;input type=&quot;text&quot; data-id=&quot;bottom-right&quot;&gt;\n&lt;input type=&quot;text&quot; data-id=&quot;bottom-left&quot;&gt;\n</code></pre>\n<p>Now I need a way to map identifiers in UI to keys of my state object so I write <code>idToKey</code> function that conveniently uses <code>object</code> instead of <code>switch</code> to make it more concise:</p>\n<pre><code>const idToKey = (id) =&gt; ({\n 'top-left': 'topLeft',\n 'top-right': 'topRight',\n 'bottom-right': 'bottomRight',\n 'bottom-left': 'bottomLeft',\n}[id]);\n</code></pre>\n<p>I want to save in the state only values with units so I write <code>normalize</code> function:</p>\n<pre><code>const normalize = (val) =&gt; {\n if (val === '') return normalize('0');\n const units = ['px', 'in', 'pc', 'pt', 'em', 'rem', '%'];\n return units.some((u) =&gt; val.endsWith(u)) ? val : `${val}px`;\n}\n</code></pre>\n<p>Now we have everything in place to add an event listener for the <code>blur</code> event for all inputs to update the state:</p>\n<pre><code>inputs.forEach((input) =&gt; {\n input.addEventListener('blur', ({ target }) =&gt; {\n state.set({ [idToKey(target.dataset.id)]: normalize(target.value) });\n })\n});\n</code></pre>\n<p>Next, we want to update UI so users will see changes. We subscribe to the state updates to reflect changes in the styles of the box. To clarify my intention I extract callback's body to separate function <code>updateBox</code>.</p>\n<pre><code>const updateBox = (box) =&gt; function ({ topLeft, topRight, bottomRight, bottomLeft }) {\n box.style.borderTopLeftRadius = topLeft;\n box.style.borderTopRightRadius = topRight;\n box.style.borderBottomRightRadius = bottomRight;\n box.style.borderBottomLeftRadius = bottomLeft;\n};\nstate.onUpdate(updateBox(document.querySelector('.shape')));\n</code></pre>\n<p>Since the state is updated and its changes reflected in UI we can proceed to copy to the clipboard button. We need a function for converting state to CSS text.</p>\n<pre><code>const toCSS = ({ topLeft, topRight, bottomRight, bottomLeft }) =&gt; {\n return [\n `border-top-left-radius: ${topLeft}`,\n `border-top-right-radius: ${topRight}`,\n `border-bottom-right-radius: ${bottomRight}`,\n `border-bottom-left-radius: ${bottomLeft}`,\n ].join('\\n');\n}\n</code></pre>\n<p>Finally we add event listener for the button:</p>\n<pre><code>document.querySelector('.copyBtn').addEventListener('click', () =&gt; {\n copyToClipboard(toCSS(state.get()));\n});\n</code></pre>\n<p>The only left thing is the reset button. To reset values we just need to update the state:</p>\n<pre><code>document.querySelector('.resetBtn').addEventListener('click', () =&gt; {\n state.set(initialState);\n});\n</code></pre>\n<p>After running the application I find that although the state is updated, users see old values in inputs. That's because UI inputs don't reflect changes in the state. To do this we need to get notified about state change and update all inputs: <code>Input blurred</code> -&gt; <code>Update state</code> -&gt; <code>Update all inputs</code>. In React it's called <code>controlled input</code>.</p>\n<pre><code>const inputs = document.querySelectorAll('input');\nconst syncInputs = (inputs) =&gt; function (data) {\n inputs.forEach((input) =&gt; {\n const key = idToKey(input.dataset.id);\n input.value = data[key];\n });\n}\nstate.onUpdate(syncInputs(inputs));\n</code></pre>\n<p>That's it. Here is the complete code:</p>\n<pre><code>class State {\n constructor(initial) {\n this._state = initial;\n this._subscribers = [];\n }\n\n set(partialState) {\n this._state = { ...this._state, ...partialState };\n this.notify();\n }\n\n notify() {\n this._subscribers.forEach((cb) =&gt; cb(this._state));\n }\n\n get() {\n return this._state;\n }\n\n onUpdate(cb) {\n this._subscribers.push(cb);\n }\n}\n\nconst idToKey = (id) =&gt; ({\n 'top-left': 'topLeft',\n 'top-right': 'topRight',\n 'bottom-right': 'bottomRight',\n 'bottom-left': 'bottomLeft',\n}[id]);\n\nconst initialState = {\n topLeft: '0px',\n topRight: '0px',\n bottomRight: '0px',\n bottomLeft: '0px',\n}\n\nconst state = new State(initialState);\n\nconst updateBox = (box) =&gt; function ({ topLeft, topRight, bottomRight, bottomLeft }) {\n box.style.borderTopLeftRadius = topLeft;\n box.style.borderTopRightRadius = topRight;\n box.style.borderBottomRightRadius = bottomRight;\n box.style.borderBottomLeftRadius = bottomLeft;\n};\nstate.onUpdate(updateBox(document.querySelector('.shape')));\n\nconst inputs = document.querySelectorAll('input');\nconst syncInputs = (inputs) =&gt; function (data) {\n inputs.forEach((input) =&gt; {\n const key = idToKey(input.dataset.id);\n input.value = data[key];\n });\n}\nstate.onUpdate(syncInputs(inputs));\nstate.notify();\n\nconst normalize = (val) =&gt; {\n if (val === '') return normalize('0');\n const units = ['px', 'in', 'pc', 'pt', 'em', 'rem', '%'];\n return units.some((u) =&gt; val.endsWith(u)) ? val : `${val}px`;\n}\n\ninputs.forEach((input) =&gt; {\n input.addEventListener('blur', ({ target }) =&gt; {\n const newState = { [idToKey(target.dataset.id)]: normalize(target.value) };\n state.set(newState);\n })\n});\n\nconst toCSS = ({ topLeft, topRight, bottomRight, bottomLeft }) =&gt; {\n return [\n `border-top-left-radius: ${topLeft}`,\n `border-top-right-radius: ${topRight}`,\n `border-bottom-right-radius: ${bottomRight}`,\n `border-bottom-left-radius: ${bottomLeft}`,\n ].join('\\n');\n}\n\nconst copyToClipboard = (text) =&gt; {\n const el = document.createElement('textarea');\n el.style.position = 'absolute';\n el.style.top = '0';\n el.style.left = '0';\n el.value = text;\n\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n};\n\ndocument.querySelector('.copyBtn').addEventListener('click', () =&gt; {\n copyToClipboard(toCSS(state.get()));\n});\n\ndocument.querySelector('.resetBtn').addEventListener('click', () =&gt; {\n state.set(initialState);\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T18:50:52.410", "Id": "252463", "ParentId": "252365", "Score": "1" } } ]
{ "AcceptedAnswerId": "252374", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:33:18.420", "Id": "252365", "Score": "1", "Tags": [ "javascript" ], "Title": "Border radius generator" }
252365
<p>We have two physical AWS S3s called in the code <code>s3Legacy</code> and <code>s3Cache</code>. They store the same data but with different S3 key structures.</p> <p>The fists solution shared below uses objects, the second does not.</p> <p><strong>Is the solution using objects an excessive abstraction or there are benefits to it?</strong> (There is no need to comment on the use of the <code>callback</code>.)</p> <p>Here is a version using objects:</p> <pre><code>// not all code is shown here for the sake of brevity module.exports.handle = (event, context, cb) =&gt; { const s3Sdk = new AWS.S3({ region: config.s3.region }); const s3Legacy = new S3(s3Sdk, config.s3.legacyBucketName); const s3Cache = new S3Cache(s3Sdk, config.s3.cacheBucketName); s3Legacy.putObject(key, event.body, callback); s3Cache.putObject({ unitId: event.pathParameters.unitId, timestamp: event.timestamp, eventId: event.id, eventFileName: event.id, body: event.body }, callback)' } </code></pre> <pre><code>class S3 { constructor(s3Sdk, bucketName) { this.s3Sdk = s3Sdk; this.bucketName = bucketName; } putObject(key, body, callback) { this.s3Sdk.putObject({ Bucket: this.bucketName, Key: key, Body: body }, (err, response) =&gt; { callback(err, response); }); } } </code></pre> <pre><code>class S3Cache extends S3 { constructor(s3Sdk, bucketName) { super(s3Sdk, bucketName); } putObject(params, callback) { const key = this.toS3Key( params.unitId, this.toTimestampObject(params.timestamp), params.eventId, params.eventFileName ); super.putObject(key, params.body, callback); } toS3Key(unitId, incidentTimestamp, incidentId, archiveIncidentObjectName) { return .... } toTimestampObject(timestamp) { return .... } } </code></pre> <p>Here is a version without using objects:</p> <pre><code>// not all code is shown here for the sake of brevity module.exports.handle = (event, context, cb) =&gt; { const s3 = new AWS.S3({ region: config.s3.region }); await s3.putObject({ Bucket: config.s3.legacyBucketName, Key: key, Body: event.body }).promise(); await s3.putObject({ Bucket: config.s3.cacheBucketName, Key: toS3Key(event.unitId, toTimestampObject(event.timestamp), event.eventId, event.eventId), Body: event.body }).promise(); } function toS3Key(unitId, incidentTimestamp, incidentId, archiveIncidentObjectName) { return .... } function toTimestampObject(timestamp) { return .... } </code></pre> <p>In this version of the code, both the service orchestration code (write to <code>s3Legacy</code> and if successful write to <code>s3Cache</code>) and the <code>s3Legacy</code>, <code>s3Cache</code>, the code constructing the S3 key resides in one source file.</p> <p>So this source file could <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle" rel="nofollow noreferrer">change for multiple unrelated reasons</a>. For example when we want to change the orchestration, change the order of writing to S3s or if we want to write to DynamoDB for example. The source file would also change if we need to change the S3 key schema.</p> <p>We set a pattern here that every new addition would be added to this single source file which size would grow as a result and the list of reasons for a change would also grow.</p> <p>While this example here is still small, calls only 2 services, I wonder whether extracting out the S3 code would set a better starting point for additional new development and enhancement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:33:21.050", "Id": "497231", "Score": "1", "body": "if this is going to be an aws lambda, then i think yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:56:07.377", "Id": "497274", "Score": "0", "body": "Would you please elaborate and explain why it maters how or where the code is executed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T08:40:43.103", "Id": "497286", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:12:41.920", "Id": "497299", "Score": "0", "body": "@BCdotWEB these kinds of questions and concerns are oftentimes brought up during code reviews as it was in this case. Does this explanation help or more information is needed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T14:06:26.303", "Id": "497316", "Score": "0", "body": "Regarding extracting out the S3 code, I think you should do it only when things get complicated or the source file gets big. In this case, you can make a folder or package with sources related to S3 and separate responsibilities there on the file level." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T14:36:35.167", "Id": "497317", "Score": "0", "body": "@AlekseiTirman I see where you are heading. I too don't like doing premature optimizations. However refactoring code at later time is risky, now you are touching S3 code but only adding DynamoDB to the mix for example. Then the code needs to be verified that it works when deployed. Most developers would end up adding new code directly to the `handle` vs taking the additional work and risks. I think most teams would not approve such refactoring, it is a hard sell to the business." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:30:58.527", "Id": "497323", "Score": "1", "body": "@OSGIJava the only solution I know is to cover code with tests to make refactoring safe." } ]
[ { "body": "<p>I think the use of <strong>classes</strong> here is excessive because of complexity added by their structure and inheritance. Since your objects have only one method <code>putObject</code> you can make abstraction on the function level. So you can just use closures to save state by returning a function that will put objects. In this case <code>s3Cache</code> will use only one function of <code>s3Legacy</code> as a dependency.</p>\n<p>Here is the code:</p>\n<pre><code>const s3Legacy = (sdk, bucket) =&gt; function putObject(key, body, callback) {\n sdk.putObject({ Bucket: bucket, Key: key, Body: body }, callback);\n}\n\nconst s3Cache = (putObjectLegacy) =&gt; function putObject(params, callback) {\n const toS3Key = (unitId, incidentTimestamp, incidentId, archiveIncidentObjectName) =&gt; 'implementation';\n const toTimestampObject = (timestamp) =&gt; 'implementation';\n\n const key = toS3Key(\n params.unitId,\n toTimestampObject(params.timestamp),\n params.eventId,\n params.eventFileName\n );\n\n putObjectLegacy(key, params.body, callback);\n}\n\nmodule.exports.handle = (event, context, cb) =&gt; {\n const s3Sdk = new AWS.S3({ region: config.s3.region });\n const putObjectLegacy = s3Legacy(s3Sdk, config.s3.legacyBucketName);\n const putObjectCache = s3Cache(s3Legacy(s3Sdk, config.s3.cacheBucketName));\n\n putObjectLegacy(key, event.body, callback);\n putObjectCache({\n unitId: event.pathParameters.unitId,\n timestamp: event.timestamp,\n eventId: event.id,\n eventFileName: event.id,\n body: event.body\n }, callback);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:43:44.887", "Id": "497311", "Score": "0", "body": "My response would not fit here so I added it to the very bottom of the original post. I would love to hear what you think." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T09:33:01.107", "Id": "252402", "ParentId": "252369", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T13:51:20.783", "Id": "252369", "Score": "2", "Tags": [ "javascript", "object-oriented" ], "Title": "Is this an excessive abstraction using objects?" }
252369
<p>New to Python/Selenium and learning on the fly with my first basic selenium script.</p> <p>Request user input - activate or deactivate. Open's website, loops through shop URL as well as activate/deactivate checkboxes.</p> <p>Would be grateful for some feedback on how to optimise the code.</p> <pre><code># IMPORTS import time from selenium import webdriver from selenium.webdriver.chrome.options import Options # X PATH LOCATIONS shop = '//*[@id=&quot;zz2_TopNavigationMenun1&quot;]/table/tbody/tr/td/a' product_range = '//*[@id=&quot;zz1_QuickLaunchMenun2&quot;]/td/table/tbody/tr/td/a' product_sale = '//*[@id=&quot;divBdyGroup_WG_Main&quot;]/table/tbody/tr[2]/td/a' product_record = '//*[@id=&quot;Enregistrer_HolWebArticlesCaisse_ctl00_m_g_a26e7d54_b496_4e0f_8176_7ddab403a0c0&quot;]' # WEB MAG URL webmag_login = 'URL' webmag_url = 'URL' # CONTROLS shopcodes = ['251' ,'257' ,'268' ,'271' ,'285' ,'411' ,'495' ,'787' ,'794' ,'838' ,'842' ,'847' ,'852' ,'857' ,'977' ,'978' ,'979' ,'A74' ,'A75' ,'A77' ,'A78' ,'B08' ,'C01' ,'C02' ,'D14' ,'D93' ,'E41' ,'E42' ,'E50' ,'G38' ,'G52' ,'G84' ,'G85' ,'G95' ,'R20' ,'R67'] # SHOP CODES TO CHECK plucodes = [&quot;2432&quot;] # PLU CODES TO CHECK # VARIABLES prompt = input(&quot;Do you want to \'activate\' or \'deactivate\' items?\n\n&quot;) # OPTIONS chrome_options = Options() # chrome_options.add_argument(&quot;--kiosk&quot;) driver = webdriver.Chrome(options=chrome_options) ################################################## print(&quot;\n[ --------------- ACTIVE PRODUCT CHECK ------------]\n\nShop codes to check :&quot;) print(shopcodes) print(&quot;\nPLU codes to check :&quot;) print(plucodes) print(&quot;\n[ ------------- STARTING MAIN SCRIPT --------------]\n&quot;) ################################################## def webmag_launch_login(): print(&quot;&gt;&gt;&gt; launch web driver&quot;) driver.get(webmag_login) # driver.fullscreen_window() print(&quot;&gt;&gt;&gt; open and login to webmag\n\n[ ------------ ITERATE THROUGH SHOPS --------------]\n&quot;) time.sleep(1) def webmag_nav_to_range_tick(): for Y in shopcodes: driver.get(webmag_url + Y) print(Y + &quot; - Login to Store&quot;) time.sleep(1) driver.find_element_by_xpath(product_range).click() time.sleep(1) driver.find_element_by_xpath(product_sale).click() time.sleep(1) print(&quot;[ - CHECKING ITEMS -- ]&quot;) for X in plucodes: # iterate through PLU CODES try: checkbox = &quot;//td[div=\'&quot; + X + &quot;\']/following-sibling::td/input[@type=\'checkbox\']&quot; productname = &quot;//td[div=\'&quot; + X + &quot;\']/following-sibling::td[1]&quot; result = driver.find_element_by_xpath(checkbox).is_selected() if result: print(X + &quot; - &quot; + driver.find_element_by_xpath(productname).text + &quot;\tPLU - already ticked&quot;) # print(driver.find_element_by_xpath(productname).text) else: driver.find_element_by_xpath(checkbox).click() print(X + &quot; - &quot; + driver.find_element_by_xpath(productname).text + &quot;\tPLU - ticked&quot;) time.sleep(1) except: print(X + &quot;- PLU - not found&quot;) time.sleep(1) # driver.find_element_by_xpath(shop).click() # SAVE BUTTON # driver.find_element_by_xpath(product_record).click() def webmag_nav_to_range_untick(): for Y in shopcodes: driver.get(webmag_url + Y) print(Y + &quot; - Login to Store&quot;) time.sleep(1) driver.find_element_by_xpath(product_range).click() time.sleep(1) driver.find_element_by_xpath(product_sale).click() time.sleep(1) print(&quot;[ - CHECKING ITEMS -- ]&quot;) for X in plucodes: # iterate through PLU CODES try: checkbox = &quot;//td[div=\'&quot; + X + &quot;\']/following-sibling::td/input[@type=\'checkbox\']&quot; productname = &quot;//td[div=\'&quot; + X + &quot;\']/following-sibling::td[1]&quot; result = driver.find_element_by_xpath(checkbox).is_selected() if result: print(X + &quot; - &quot; + driver.find_element_by_xpath(productname).text + &quot;\tPLU - unticked&quot;) driver.find_element_by_xpath(checkbox).click() else: print(X + &quot; - &quot; + driver.find_element_by_xpath(productname).text + &quot;\tPLU - already unticked&quot;) time.sleep(1) except: print(X + &quot;- PLU - not found&quot;) time.sleep(1) # driver.find_element_by_xpath(shop).click() # SAVE BUTTON # driver.find_element_by_xpath(product_record).click() # EXECUTE DEF if prompt == &quot;activate&quot;: webmag_launch_login() webmag_nav_to_range_untick() elif prompt == &quot;deactivate&quot;: webmag_launch_login() webmag_nav_to_range_tick() else: print(&quot;Script Ended&quot;) print(&quot;Script Finished Running&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T16:51:26.780", "Id": "497209", "Score": "0", "body": "It's fine to obscure your credentials, but please don't obscure the original `webmag_url`. Reviewers being able to access the site will be able to more meaningfully comment on the best way to interact with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:48:46.733", "Id": "497236", "Score": "0", "body": "Unfortunately the URL is not accessible outside the organisation network." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:51:37.150", "Id": "497237", "Score": "1", "body": "In that case could you [edit] your post to include a sample of the HTML that is being returned by the URL?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:54:54.727", "Id": "497239", "Score": "0", "body": "Appreciate where you guys are coming from. This platform and the eqtiquette is all new to me. Programming - HTML / Python is not my background. I literally studied \"Automate Boring Stuff\" earlier this week and managed to write this script. I'll need to figure out how to extract the website and upload it somewhere for users." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:51:02.963", "Id": "497258", "Score": "0", "body": "You don't appear to actually authenticate to the website, which points toward using Requests instead of Selenium." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T08:47:24.927", "Id": "497287", "Score": "0", "body": "The authentication for the website is in the form of a popup (Java?). Initially I tried to us the geckodriver and switch_to.alert(), but I couldn't get it to work after spending hours on it. I eventually switched to the Chrome driver and found that this method works : \n\n`driver.get(\"https://username:password@somewebsite.com/\")`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T14:36:33.110", "Id": "252372", "Score": "4", "Tags": [ "python", "selenium", "webdriver" ], "Title": "Python Selenium First Project - loop through pages and check/uncheck tick boxes" }
252372
<p><a href="https://stackoverflow.com/q/33592547/2704659">It's known</a> that something like this</p> <pre><code>await currentPage.NextPageRequest?.GetAsync(); </code></pre> <p>will throw <a href="https://docs.microsoft.com/en-us/dotnet/api/system.nullreferenceexception" rel="nofollow noreferrer">an NRE</a> if <code>NextPageRequest</code> is <code>null</code> because you cannot await null. <a href="https://stackoverflow.com/a/33592569/2704659">The solution</a> is to do something like this:</p> <pre><code>await (currentPage.NextPageRequest?.GetAsync(cancellationToken) ?? Task.FromResult(default(IUserMessagesCollectionPage))); </code></pre> <p>Is there a more-succinct way to do this, maybe in later versions of C#?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T16:30:23.397", "Id": "497205", "Score": "2", "body": "This is theoretical code, and in its current state is off-topic. Could you post an entire program that prompted this question?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T15:16:27.993", "Id": "252373", "Score": "1", "Tags": [ "c#" ], "Title": "Is there a more-succinct way to employ null conditional operator followed by an awaitable with await?" }
252373
<p>I tried to code the fizzbuzz program following the functional programming rules in javascript. Please check my code and give feedback. thank you.</p> <pre><code>const isDivisible = (number, fizz) =&gt; number % fizz === 0; const getSubstitutes = ( number, substitutes, { currentIndex = 0, result = &quot;&quot; } = {} ) =&gt; { if (currentIndex === substitutes.length) return result; const { divisor, substitute } = substitutes[currentIndex]; const newResult = result + (isDivisible(number, divisor) ? substitute : &quot;&quot;); return getSubstitutes(number, substitutes, { currentIndex: currentIndex + 1, result: newResult, }); }; const fizzBuzz = (number, substitutes, currentIndex = 1) =&gt; { if (number &lt; currentIndex) return; console.log(getSubstitutes(currentIndex, substitutes) || currentIndex); fizzBuzz(number, substitutes, ++currentIndex); }; const substitutes = [ { divisor: 3, substitute: &quot;fizz&quot;, }, { divisor: 5, substitute: &quot;buzz&quot;, }, ]; fizzBuzz(100, substitutes); </code></pre>
[]
[ { "body": "<p><strong>Parameter name</strong> <code>(number, fizz) =&gt; number % fizz === 0</code> The <code>fizz</code> isn't very indicative of what it represents. Consider <code>divisor</code> or <code>possibleDivisor</code> instead.</p>\n<p><strong>Avoid reassignment</strong> in functional programming: your <code>++currentIndex</code> reassigns that variable. If you needed recursion, pass the variable plus one instead of incrementing the variable and passing it: use <code>currentIndex + 1</code>.</p>\n<p><strong>Move required side-effects to the edges of the script</strong>, since you want a functional approach - make the <code>fizzBuzz</code> function functional by having it <em>return</em> a string which can be logged by the caller, instead of <code>fizzBuzz</code> itself log the results. (<code>console.log</code> is a side-effect, so including it in a function makes it non-functional)</p>\n<p><strong><code>getSubstitutes</code> recursion?</strong> The recursive approach used in <code>getSubstitutes</code>, while it <em>works</em>, seems a bit off to me. Functional programming excels at pure transformation of data (and in JavaScript, with object/array methods), and given the <code>substitutes</code> array, I think a <code>.filter</code> / <code>.map</code> would be a bit more appropriate, without any recursion.</p>\n<p><strong><code>fizzBuzz</code> recursion too?</strong> - if you feel like it, you can create an array of the values to be logged all at once by using <code>Array.from</code> instead of the somewhat imperative approach of incrementing and testing <code>currentIndex</code>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isDivisible = (number, divisor) =&gt; number % divisor === 0;\nconst getSubstitutes = (number, substitutes) =&gt; substitutes\n .filter(({ divisor }) =&gt; isDivisible(number, divisor))\n .map(({ substitute }) =&gt; substitute)\n .join('');\nconst fizzBuzz = (length, substitutes) =&gt; (\n Array.from(\n { length },\n (_, i) =&gt; getSubstitutes(i + 1, substitutes) || i + 1\n )\n .join('\\n')\n);\n\n\nconst substitutes = [\n {\n divisor: 3,\n substitute: \"fizz\",\n },\n {\n divisor: 5,\n substitute: \"buzz\",\n },\n];\nconsole.log(fizzBuzz(100, substitutes));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Recursion is useful in functional programming when you need <em>persistent state</em> (like with a game, or memoization), but it can make the logic somewhat difficult to understand at a glance - I'd only use it when other approaches don't work well, or when the recursive logic to implement is natural (like with a factorial).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T00:36:43.913", "Id": "497260", "Score": "0", "body": "Thank you very much for your answer. I want to is that in your code const getSubstitutes = (number, substitutes) => substitutes\n .filter(({ divisor }) => isDivisible(number, divisor))\n .map(({ substitute }) => substitute)\n .join(''); is the function inside filter a pure function? If not should I try to make it a pure function? and what would be a good approach to do it? Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:14:21.777", "Id": "497263", "Score": "0", "body": "Yes, everything there is pure - it causes no side-effects and depends only on the values of the parameters, producing the same result every time given the same input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T06:25:47.517", "Id": "497279", "Score": "0", "body": "But `substitutes.filter(({ divisor }) => isDivisible(number, divisor))` takes number variable from outside scope. `({ divisor }) => isDivisible(number, divisor)` in this function number is not a parameter." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:07:00.087", "Id": "252381", "ParentId": "252376", "Score": "3" } }, { "body": "<p>Overall it looks like you're missing out on most of the benefits of a functional approach and over-complicating your code. First glance it's basically impossible to work out what it's all doing without following each variable through everything.</p>\n<p>Per the previous answer you don't seem familiar with common functional techniques like using <code>.map</code>, pipelines, or avoiding side-effects</p>\n<p>Below is less a review of your code but a different solution that highlights the techniques you're missing so you can see them in action</p>\n<pre><code>const fizzOrBuzz = (a, b, aPhrase, bPhrase) =&gt; (\n (n) =&gt; (\n (n % (a*b) === 0) ? aPhrase + bPhrase :\n (n % a === 0) ? aPhrase :\n (n % b === 0) ? bPhrase :\n n\n )\n)\n\nconst generateNLengthArray = (n) =&gt; [ ...Array(n).keys()].map(i =&gt; i + 1)\n\nconst mapArrayTo = (f) =&gt; (array) =&gt; array.map(i =&gt; f(i)) \n\nconst joinArray = (array) =&gt; array.join('\\n')\n\nconst pipe = (...fns) =&gt; (x) =&gt; fns.reduce((v, f) =&gt; f(v), x) // One-liner pipeline pattern\n\nconst fizzbuzz = pipe(\n generateNLengthArray,\n mapArrayTo(fizzOrBuzz(3, 5, 'fizz', 'buzz')),\n joinArray\n)\n\nconsole.log(fizzbuzz(100))\n</code></pre>\n<p>One of the benefits of functional programming is breaking everything down into discrete, easily understandable functions, and then composing them together so it's crystal clear what's happening.</p>\n<p>In this case defining fizzbuzz as a pipeline of three separate functions makes it clear that you're 1. creating an array of a specific length. 2. mapping the values of that array to either fizz or buzz and 3. joining the results together</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:27:37.793", "Id": "252384", "ParentId": "252376", "Score": "5" } }, { "body": "<p>Suggestions from previous answers are great and I have nothing to add except for giving advice to not overuse functional programming in Javascript. Here is my solution:</p>\n<pre><code>const range = (max) =&gt; [...Array(max).keys()].map((i) =&gt; i + 1);\nconst fizzbuzz = (x) =&gt; {\n if (x % 3 === 0 &amp;&amp; x % 5 === 0) return 'FizzBuzz';\n if (x % 3 === 0) return 'Fizz';\n if (x % 5 === 0) return 'Buzz';\n return x.toString();\n};\nconst result = range(100).map(fizzbuzz);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T19:46:34.300", "Id": "497354", "Score": "1", "body": "definitely the most usable answer in practice" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:58:35.290", "Id": "252426", "ParentId": "252376", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T16:42:05.387", "Id": "252376", "Score": "3", "Tags": [ "javascript", "functional-programming", "fizzbuzz" ], "Title": "Functional programming FizzBuzz" }
252376
<p>Some friends and I were playing a board game and decided that the random dice rolls just weren't fair! So we came up with a scheme for making the rolls slightly more evenly distributed, and I implemented it in python. The class represents 2 six sided dice and makes the probability of a given combination coming up (there are 36 options for 2 dice) inversely proportional to the number of times it has come up previously - thereby ensuring the distribution tends to be more even than randomness allows:</p> <pre><code>from collections import Counter from typing import Tuple, Counter as TCounter import random class LoadedDice: &quot;&quot;&quot; Simulation of 2 Dice being rolled. Weights the random roll to try and tend to an even distribution &quot;&quot;&quot; def __init__(self, sides: int = 6) -&gt; None: self.sides = sides self.history: TCounter[int] = Counter(range(sides ** 2)) def roll(self) -&gt; Tuple[int, int]: result_index = self.get_weighted_random_roll_index() self.history[result_index] += 1 return self.roll_value_from_index(result_index) def get_weighted_random_roll_index(self) -&gt; int: roll_threshold = random.random() reciprocals_total = sum(self.reciprocals()) running_total = 0 for result_index, value in enumerate(self.reciprocals()): running_total += value / reciprocals_total if roll_threshold &lt;= running_total: return result_index def roll_value_from_index(self, index: int) -&gt; Tuple[int, int]: mod, remainder = divmod(index, self.sides) roll_1 = mod + 1 roll_2 = remainder + 1 return roll_1, roll_2 def reciprocals(self): for v in self.history.values(): yield 1 / v @property def roll_history(self) -&gt; TCounter[Tuple[int, int]]: result: TCounter[Tuple[int, int]] = Counter() for roll_index, count in self.history.items(): result[self.roll_value_from_index(roll_index)] += count return result @property def result_history(self) -&gt; TCounter[int]: result: TCounter[int] = Counter() for roll_index, count in self.history.items(): result[sum(self.roll_value_from_index(roll_index))] += count return result def __repr__(self): return repr(self.roll_history) </code></pre> <p>... which can be used like this:</p> <pre><code>especially_fair_dice = LoadedDice(6) # simulate 2 6-sided dice especially_fair_dice.roll() # returns the dice values results like (1,5) </code></pre> <h3>Feedback</h3> <p>I'd like some review on types, as I've never done them before, efficiency of my algorithm; I feel like it's a bit overly complicated, anything I've missed about pseudo-random numbers that make my approach undesirable etc.</p> <h3>Results</h3> <p>I plotted some of the results, for 100 rolls, the loaded die approach tends to perform better than random at keeping to the expected distribution, while still <em>feeling</em> random (that's the goal, interpret it as you wish, I don't know how to quantify it either:) <a href="https://i.stack.imgur.com/fhK7D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fhK7D.png" alt="comparison of rolls" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:21:08.187", "Id": "497212", "Score": "4", "body": "Though it doesn't affect my comment on the code or implementation, the whole premise of this problem is classically fallacious; read about the gambler's fallacy here: https://en.wikipedia.org/wiki/Gambler%27s_fallacy" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:23:38.930", "Id": "497213", "Score": "2", "body": "What is your intent with `1 / v ** 0`? You realize this will always evaluate to 1?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:29:34.470", "Id": "497214", "Score": "1", "body": "@Reinderien Oops, sorry good catch, that was me messing with the exponent (the higher the exponent, the more strongly it tends to the expectede). Edited out" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:33:21.290", "Id": "497217", "Score": "1", "body": "I should add that this is for short games with ~50 dice rolls, over a long game the random approach does of course tend towards expected, as should the loaded die (just the loaded die tends to expected faster)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T05:34:35.713", "Id": "497277", "Score": "1", "body": "You *do* know that dice have no memory, yes?" } ]
[ { "body": "<h2>Performance</h2>\n<p>If you intend on using this for (e.g.) large-scale Monte-Carlo simulation, consider moving to vectorized Numpy rather than base Python.</p>\n<h2>Direct generators</h2>\n<p>There's no need for <code>yield</code> here:</p>\n<pre><code> for v in self.history.values():\n yield 1 / v\n</code></pre>\n<p>Instead,</p>\n<pre><code>return (1/v for v in self.history.values())\n</code></pre>\n<h2>Counter initialization</h2>\n<p><code>roll_history</code> can be reduced, I think, to</p>\n<pre><code>return Counter(\n (\n sum(self.roll_value_from_index(roll_index)),\n count,\n )\n for roll_index, count in self.history.items()\n)\n</code></pre>\n<p>In other words, <code>Counter</code> accepts an iterable of key-count tuples. If the above generator expression seems unwieldy to you, write a separate method to yield roll-count pairs:</p>\n<pre><code> for roll_index, count in self.history.items():\n roll_1, roll_2 = self.roll_value_from_index(roll_index)\n yield roll_1 + roll_2, count\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:55:45.823", "Id": "497220", "Score": "1", "body": "What's the advantage of the \"Direct generators\" and how are they \"direct\"? One might as well say \"There's no need for `return` here\", arguing for the opposite." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:01:13.137", "Id": "497222", "Score": "1", "body": "@superbrain Direct in the sense that you don't need to split out a `for`-loop, and the method itself will not be a generator; it will simply return a generator object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:04:11.700", "Id": "497223", "Score": "1", "body": "Well you have a `for` clause instead. What's the advantage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:09:17.773", "Id": "497224", "Score": "1", "body": "Concision, in this case." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:42:01.687", "Id": "252379", "ParentId": "252377", "Score": "3" } }, { "body": "<p>By using the <code>weights</code> or <code>cum_weights</code> keyword argument, <code>random.choices()</code> can make a weighted selection from a population of objects. <code>get_weighted_random_roll_index</code> could be replace with:</p>\n<pre><code>def get_weighted_random_roll_index(self):\n choices = random.choices(range(self.sides**2), weights=self.reciprocals())\n return choices[0]\n</code></pre>\n<p><code>random.choices()</code> returns a list, which defaults to just 1 element. I use <code>return choices[0]</code> because it's easy to overlook a <code>[0]</code> at the end of the previous line.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:17:02.647", "Id": "252387", "ParentId": "252377", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T17:14:42.857", "Id": "252377", "Score": "3", "Tags": [ "python", "python-3.x", "game", "random", "combinatorics" ], "Title": "Creating some Loaded Dice to make our board game fairer" }
252377
<p>I have a solution to <a href="https://www.codewars.com/kata/the-fusc-function-part-2" rel="nofollow noreferrer">this CodeWars challenge</a> that's being rejected as &quot;too slow&quot;.</p> <p>Basically, write <code>public static BigInteger Fusc(BigInteger n)</code> given:</p> <blockquote> <ol> <li>fusc(0) = 0</li> <li>fusc(1) = 1</li> <li>fusc(2 * n) = fusc(n)</li> <li>fusc(2 * n + 1) = fusc(n) + fusc(n + 1)</li> </ol> </blockquote> <p>-- <a href="https://www.codewars.com/kata/the-fusc-function-part-1" rel="nofollow noreferrer">CodeWars description</a> (from part 1, which is formatted slightly nicer IMO)</p> <p>I have the class below. <code>FuscInner</code> is a literal, naïve implementation, to offer a &quot;known good&quot; answer if needed; it's slow, but that's fine. The trouble that I'm running into is that <code>FuscInnerTest</code> runs against my test driver in a quarter second, but times out on CodeWars.</p> <p>While I'm open to any suggestionst for cleaning up <code>FuscInnerTest</code> or <code>MediumInt</code>, my primary goal is to ascertain why it's running so poorly when I submit to CodeWars (of course, I don't know how many test cases it runs...).</p> <pre class="lang-c# prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Numerics; public class FuscSolution { public static BigInteger Fusc(BigInteger n) { //var timer = System.Diagnostics.Stopwatch.StartNew(); var answer = FuscInnerTest(n); //timer.Stop(); //Console.WriteLine($&quot;{n} {answer} : {timer.Elapsed}&quot;); //timer.Restart(); //answer = FuscInner(n); //timer.Stop(); //Console.WriteLine($&quot;{n} {answer} : {timer.Elapsed}&quot;); return answer; } private static BigInteger FuscInner(BigInteger n) { if (n == BigInteger.Zero) { return BigInteger.Zero; } if (n == BigInteger.One) { return BigInteger.One; } if (n % 2 == BigInteger.Zero) { return FuscInner(n / 2); } var half = n / 2; return FuscInner(half) + FuscInner(half + 1); } private static readonly Dictionary&lt;BigInteger, BigInteger&gt; _dict = new Dictionary&lt;BigInteger, BigInteger&gt; { { BigInteger.Zero, BigInteger.Zero }, { BigInteger.One, BigInteger.One }, { new BigInteger(3), new BigInteger(2) }, { new BigInteger(5), new BigInteger(3) }, }; private static BigInteger FuscInnerTest(BigInteger n) { // note: making this a Dictionary&lt;BigInteger, BigInteger&gt; worked quickly locally, too // the &quot;MediumInt&quot; is an attempt to reduce the number of BigInteger allocations, since // they're immutable var queue = new Dictionary&lt;BigInteger, MediumInt&gt; { { n, new MediumInt(1) }, }; BigInteger answer = BigInteger.Zero; while (queue.Any()) { var current = queue.Keys.Max(); if (_dict.ContainsKey(current)) { answer += _dict[current] * queue[current].ToBigInt(); queue.Remove(current); } else { Dequeue(current); var half = current / 2; Enqueue(half, current); if (!current.IsEven) { Enqueue(half + 1, current); } queue.Remove(current); } } return answer; void Dequeue(BigInteger toRemove) { if (queue.ContainsKey(toRemove)) { if (queue[toRemove].IsPositive()) { queue[toRemove].Decriment(); } else { queue.Remove(toRemove); } } } void Enqueue(BigInteger toAdd, BigInteger parent) { if (queue.ContainsKey(toAdd)) { queue[toAdd].Incriment(); } else { queue[toAdd] = new MediumInt(1); } if (parent != null) { if (queue.ContainsKey(parent)) { queue[toAdd].Add(queue[parent]); } } } } private class MediumInt { private const int max = 2_000_000; private const int min = -2_000_000; private BigInteger big = BigInteger.Zero; private int current = 0; public MediumInt(int initialValue) { current = initialValue; Normalize(); } public bool IsZero() { return big == BigInteger.Zero &amp;&amp; current == 0; } public bool IsPositive() { if (IsZero()) { return false; } if (current == 0 &amp;&amp; big &lt;= 0) { return false; } if (big == BigInteger.Zero &amp;&amp; current &lt;= 0) { return false; } if (big == BigInteger.Zero) { return current &gt; 0; } if (big &gt; BigInteger.Zero &amp;&amp; big &gt; Math.Abs(current)) { return true; } if (big &lt; BigInteger.Zero &amp;&amp; big &lt; Math.Abs(current)) { return true; } throw new Exception(&quot;IsPositive unknown state&quot;); } public void Incriment() { ++current; Normalize(); } public void Decriment() { --current; Normalize(); } public void Add(MediumInt value) { current += value.current; big += value.big; Normalize(); } public BigInteger ToBigInt() { return big + current; ; } private void Normalize() { if (current &gt; max || current &lt; min) { big += current; current = 0; } } } } </code></pre> <p>Driver code:</p> <pre class="lang-c# prettyprint-override"><code>Assert.AreEqual(BigInteger.Zero, FuscSolution.Fusc(BigInteger.Zero)); Assert.AreEqual(BigInteger.One, FuscSolution.Fusc(BigInteger.One)); Assert.AreEqual(BigInteger.One, FuscSolution.Fusc(new BigInteger(4))); Assert.AreEqual(new BigInteger(2), FuscSolution.Fusc(new BigInteger(3))); Assert.AreEqual(new BigInteger(3), FuscSolution.Fusc(new BigInteger(10))); Assert.AreEqual(new BigInteger(3), FuscSolution.Fusc(5)); Assert.AreEqual(new BigInteger(3), FuscSolution.Fusc(20)); Assert.AreEqual(new BigInteger(8), FuscSolution.Fusc(21)); Assert.AreEqual(new BigInteger(53), FuscSolution.Fusc(9007199254740991L)); // You need to pass these tests very quickly BigInteger twoPThous = BigInteger.Pow(2, 1000); Assert.AreEqual(new BigInteger(1001), FuscSolution.Fusc(twoPThous + BigInteger.One)); Assert.AreEqual(new BigInteger(1000), FuscSolution.Fusc(twoPThous - BigInteger.One)); Assert.AreEqual(new BigInteger(2996), FuscSolution.Fusc(twoPThous + 5)); Assert.AreEqual(new BigInteger(7973), FuscSolution.Fusc(twoPThous + 21)); Assert.AreEqual(new BigInteger(50245), FuscSolution.Fusc(twoPThous + 9007199254740991L)); var e = BigInteger.Parse(&quot;40441312560834288620677930197198699407914760287917495887121626854370117030034851815445037809554113527157810884542426113562558179684997500659084090344407986124994461497183&quot;); var a = BigInteger.Parse(&quot;4496047232746033439866332574607641115185289828815659836877207557974698638551430698226403383854431074455323285812344476437334109742500243442945967768558521790671067401423809250553312923996658420643391496408098163895264498830090255970293513331630261702288646149000136895514918279039816543329290294321200&quot;); Assert.AreEqual(e, FuscSolution.Fusc(a)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:13:43.077", "Id": "497261", "Score": "0", "body": "First i can see that you check if it 0 or 1 each iteration before calculations. Maybe reorder checks e.g. 3-4-1-2? Also you can use [`DivRem`](https://docs.microsoft.com/ru-ru/dotnet/api/system.numerics.biginteger.divrem?view=netframework-4.8) because you need both at once, also `IsEven`, `IsZero`, `IsOne` properties may help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T20:53:20.987", "Id": "497457", "Score": "0", "body": "The link you provided suggests using tail recursion, which C# does not support natively." } ]
[ { "body": "<p>The direct answer to my question of &quot;why is it timing out on submission&quot; turns out to be that it's running 10k super-large values. I suspect that this approach is a dead end</p>\n<p>Some stats that may be of interest about the last test case:</p>\n<ul>\n<li>runs through the <code>while</code> loop 1992 times</li>\n<li>performs work in <code>Normalize</code> 331 times across all <code>MediumInt</code> instances</li>\n<li>bumping <code>MediumInt</code>'s scratch values up to <code>long</code>s and setting the thresholds to +-4_500_000_000_000_000_000 only drops that count to 286</li>\n</ul>\n<p>My initial reading of the problem (and some poking to get a couple of random known-correct super-large expected/actual pairs) suggested that the test included only a few of those super-large values, to prevent the naïve recursive solution from working. But, looping over that last test case 10k times runs in just over 28 seconds (twice the 12-second limit).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:26:45.227", "Id": "252435", "ParentId": "252382", "Score": "1" } }, { "body": "<p>I don't understand your rationale for introducing the <code>MediumInt</code> class. You have written:</p>\n<pre><code>// the &quot;MediumInt&quot; is an attempt to reduce the number of BigInteger allocations, since\n// they're immutable\n</code></pre>\n<p>The <code>System.Numerics.BigInteger</code> is a struct so there's no heap allocation anyway. I haven't profiled your code so it may be faster but maybe not for the reason you think. Sometimes it can be helpful to have a wrapper to avoid having to key into a dictionary twice:</p>\n<pre><code>public class Counter\n{\n public BigInteger Current { get; set; }\n}\n\n\n// One example of using it:\nif (!someDictionary.TryGetValue(someKey, out Counter c)\n{\n someDictionary[someKey] = c = new Counter();\n}\nc.Current++;\n</code></pre>\n<p>This also shows something else you want to be doing, using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue\" rel=\"nofollow noreferrer\">TryGetValue</a>. If you're looking up in your dictionary as much as I expect, it will yield a good gain. Applying it to your Enqueue local function, using the simplified <code>Counter</code> class and fixing the brace style:</p>\n<pre><code>void Enqueue(BigInteger toAdd, BigInteger parent)\n{\n if (queue.TryGetValue(toAdd, out var counter))\n {\n counter.Value++;\n } \n else\n {\n queue[toAdd] = counter = new Counter { Value = new BigInteger(1) };\n }\n if (parent != null &amp;&amp; queue.TryGetValue(parent, out var parentCounter)) \n {\n counter.Value += parentCounter.Value;\n }\n}\n</code></pre>\n<p>All of this comes with the caveat that I have neither compiled nor run any of it. I can give it a test tomorrow and update if you don't try it before then. Have you attempted to work through the tail call recursion as the question suggests?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T20:47:26.320", "Id": "497815", "Score": "0", "body": "While BigInts are structs, my understanding is that they're immutable; thus, small operations (like incrementing/decrementing, like in Enqueue and Dequeue) get expensive because they instantiate a new instance. ... I've started looking at the tail call recursion, but I don't have enough math readily at hand to do it, alas." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T20:17:50.547", "Id": "252616", "ParentId": "252382", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T18:26:02.427", "Id": "252382", "Score": "0", "Tags": [ "c#", "performance", "time-limit-exceeded" ], "Title": "CodeWars kata Fusc function running too long, but very fast locally" }
252382
<p>I want to improve on my original solution to this problem, my solution is O(n^2) and I think it's possible to solve in less time</p> <blockquote> <p>You have two arrays: A and B. A contains ints and B has pairs: (element from A, the number of elements that are larger than that element and to the right of it in A). for example: A = [4,3,5] B = [(5,0), (3,1), (4,1)] Given array B, recreate array A</p> </blockquote> <pre><code>void originalArray(vector&lt;pair&lt;int,int&gt;&gt;&amp; pairVector) { sort(pairVector.begin(),pairVector.end()); int arr[pairVector.size()]; list&lt;int&gt; arrList; list&lt;int&gt;::iterator it; for(int i=pairVector.size()-1;i&gt;=0;i--){ it = arrList.begin(); advance(it, arrList.size()-pairVector[i].second); arrList.insert(it,pairVector[i].first); } it = arrList.begin(); for(int i=0;i&lt;arrList.size();i++){ arr[i]=*it; it++; } for (int i = 0; i &lt; pairVector.size(); i++) cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:56:40.737", "Id": "497240", "Score": "1", "body": "What makes this `O(n^2)`? I don't see a nested `for` loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:06:24.953", "Id": "497252", "Score": "3", "body": "@Casey `std::advance` takes linear time with lists." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T07:38:45.893", "Id": "497281", "Score": "1", "body": "@G.Sliepen As far as I can tell it does work. At least your example: https://godbolt.org/z/aaGWMd." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:26:10.120", "Id": "497305", "Score": "4", "body": "Welcome to Code Review! The code you posted is missing some important parts (`#include` and `using`, probably), which means we can't compile it. This makes it much harder to test different ways of achieving the same result. If you [edit] your question to make the code complete, that will improve its chances of attracting good answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:33:10.337", "Id": "497307", "Score": "3", "body": "A `main` function testing the example would be good, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:49:32.560", "Id": "497350", "Score": "0", "body": "@BlameTheBits Ahum, you're right, I made a copy&paste error that still managed to compile correctly but cause it to give the wrong output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T21:09:31.030", "Id": "497458", "Score": "1", "body": "`int arr[pairVector.size()];` -- This is not valid C++. This should be `std::vector<int> arr(pairVector.size());`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T08:42:42.557", "Id": "497502", "Score": "0", "body": "Can we assume A has unique elements? Or if A=[0,1,0,2] then B=[(0,2),(1,1),(0,1),(2,0)] is valid?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:47:53.090", "Id": "252385", "Score": "2", "Tags": [ "c++", "performance", "array", "interview-questions" ], "Title": "Create array given number of larger elements to right of each member" }
252385
<p>I tried to implement bubble sort in Assembly 8086.</p> <pre><code>datasg SEGMENT BYTE 'data' array DB 1, 3, 2, 5, 4 n DW 5 datasg ENDS stacksg SEGMENT BYTE STACK 'stack' DW 12 DUP(?) stacksg ENDS codesg SEGMENT PARA 'code' ASSUME CS:codesg, DS:datasg, SS:stacksg MAIN PROC FAR ; Pushing the previous data segment to keep it secure. PUSH DS XOR AX, AX PUSH AX MOV AX, datasg MOV DS, AX ;SI = i XOR SI, SI MOV CX, n DEC CX out: PUSH CX; Pushing CX to the stack before entering the second for loop XOR DI, DI MOV CX, n DEC CX SUB CX, SI in: MOV AH, array[DI] CMP AH, array[DI+1] JLE if_end XCHG AH, array[DI+1] MOV array[DI], AH if_end: INC DI LOOP in POP CX INC SI LOOP out XOR SI, SI ; Some garbage code to move array elements to AL register one by one to see them while debugging. MOV AL, array[SI] INC SI MOV AL, array[SI] INC SI MOV AL, array[SI] INC SI MOV AL, array[SI] INC SI MOV AL, array[SI] RETF MAIN ENDP codesg ENDS END MAIN </code></pre> <p>It seems to be working for the given example in the above code. I also tried it with different arrays and they all seem to work. I just want to learn if there is a way to improve it? Improvements like changing JMP codes to decrease the size of code or using AX with XCHG because that is faster.</p> <p>I also can't comprehend the idea of pushing CX to stack for using nested-for loops. If you would give some suggestion about it I would be very happy.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:52:12.403", "Id": "497259", "Score": "1", "body": "Great, but also drop bubble sort. If you're attempting a low-level, optimised implementation, best to use an algorithm that doesn't have implicit glaring performance issues." } ]
[ { "body": "<ul>\n<li><p>On your array that has 5 elements<br />\nthe 1st iteration of the outerloop (<code>CX=4</code>) has to do 4 compares in the innerloop<br />\nthe 2nd iteration of the outerloop (<code>CX=3</code>) has to do 3 compares in the innerloop<br />\nthe 3rd iteration of the outerloop (<code>CX=2</code>) has to do 2 compares in the innerloop<br />\nthe 4th iteration of the outerloop (<code>CX=1</code>) has to do 1 compare in the innerloop</p>\n<p>In your code you have initialized the outerloop counter correctly but you should see that the current value of the outerloop counter can serve as the initial value of the innerloop counter. You don't need to re-compute this!</p>\n</li>\n<li><p>When it comes to speed, <code>XCHG</code> with a memory operand is bad. Normally we would load 2 successive elements in 2 different registers, compare those, and if necessary write them back switched.<br />\nHowever because your array contains byte-sized elements, you can load 2 elements in 1 word-sized register, compare its low and high byte-sized halves, and if necessary xchg the halves and write the word register back. That's how I did it in below code.</p>\n</li>\n<li><p>The <code>LOOP</code> instruction has become infamous for being slow these days. You can easily replace it by the pair of instructions <code>dec cx</code> <code>jnz ...</code>.</p>\n</li>\n</ul>\n<pre><code> mov cx, n\n dec cx ; Max number of compares is (n - 1)\nouterloop:\n push cx ; (1) Preserve outerloop counter CX\n\n xor di, di\ninnerloop:\n mov ax, array[di]\n cmp al, ah\n jle if_end\n xchg al, ah\n mov array[di], ax\nif_end:\n inc di\n dec cx\n jnz innerloop\n\n pop cx ; (1) Restore outerloop counter CX\n dec cx\n jnz outerloop\n</code></pre>\n<blockquote>\n<p>I also can't comprehend the idea of pushing CX to stack for using nested-for loops. If you would give some suggestion about it I would be very happy.</p>\n</blockquote>\n<p>Pushing the outerloop counter <code>CX</code> is only necessary if the innerloop wants to use and change the <code>CX</code> register for its own purposes. We can easily re-write the above code and use e.g. <code>BX</code> to control the innerloop. Then we don't need to <code>push cx</code> or <code>pop cx</code>.</p>\n<pre><code> mov cx, n\n dec cx ; Max number of compares is (n - 1)\nouterloop:\n\n mov bx, cx\n xor di, di\ninnerloop:\n mov ax, array[di]\n cmp al, ah\n jle if_end\n xchg al, ah\n mov array[di], ax\nif_end:\n inc di\n dec bx\n jnz innerloop\n\n dec cx\n jnz outerloop\n</code></pre>\n<p>And while we're optimizing this, we can even write the innerloop <strong>without using a special loop counter</strong>. We can use the index register <code>DI</code> at the same time for indexing the memory and for counting. This method also speeds things up since the combo <code>cmp di, cx</code> <code>jb innerloop</code> can macro-fuse and give us some extra speed.</p>\n<pre><code> mov cx, n\n dec cx ; Max number of compares is (n - 1)\nouterloop:\n\n xor di, di\ninnerloop:\n mov ax, array[di]\n cmp al, ah\n jle if_end\n xchg al, ah\n mov array[di], ax\nif_end:\n inc di\n cmp di, cx\n jb innerloop\n\n dec cx\n jnz outerloop\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>stacksg SEGMENT BYTE STACK 'stack'\n DW 12 DUP(?)\nstacksg ENDS\n</code></pre>\n</blockquote>\n<p>Might I further suggest you set the stack to a more realistic value like 128 words?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T21:01:25.767", "Id": "252464", "ParentId": "252386", "Score": "1" } } ]
{ "AcceptedAnswerId": "252464", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:14:53.220", "Id": "252386", "Score": "3", "Tags": [ "performance", "sorting", "assembly" ], "Title": "How do I optimize the bubble sort in Assembly8086?" }
252386
<p>I have an assignment that I have completed, but I feel as though the way I went about solving the problems could be optimized a bit. As well, I don't know if I'm properly utilizing return statements. I'm relatively new to coding so I don't have the knowledge, but I would love to learn if anyone wants to go through and see if they can help me, even just pointing me in the right direction without actually giving me a definitive answer would be fantastic.</p> <p>Here is the problem: Write a program that displays, examines and manipulates a two dimensional array representing plane seats for a plane with 12 rows and 4 seats per row. Write methods for the following operations:</p> <p>fillSeatsRandomly:Fills the array with random values in range from 0 to 1. Zero represents an empty seat and one represents a reserved seat.</p> <p>displaySeats: Displays all the seats in the plane row by row. Empty seat is displayed as 0 and a reserved seat is displayed as X. Create vertical headings for the row numbers from 1 to 12 on the left hand side and horizontal column headings from A to D (for the 4 seats in the row).</p> <p>isSeatAvailable: Receives an integer representing a row number and a character representing a seat from A to D. This method tests if the specified seat is available, otherwise it returns false. This method displays an error message when the seat selection is invalid.</p> <p>reserveSeat: Reserves a specified seat. Receives two parameters: an integer representing a row number and a character representing a seat number from A to D. This method displays an error message when the seat is invalid.</p> <p>seatsAvailInRow: counts and returns number of seats available in given row. Receives an integer representing row number.</p> <p>findRowWithTwoSeats: This method look for the closest row with two adjacent available seats. If two adjacent seats are not available it returns 0.</p> <p>countSeatsAvail: counts the number of all seats available in the plane and returns that number.</p> <p>countTakenSeats: counts the number of all seats reserved in the plane and returns that number.</p> <p>Here is my code</p> <pre class="lang-java prettyprint-override"><code> public static void main(String[] args) { int[][] plane;//this is the array that will be plugged into the methods plane = fillSeatsRandomly();//creates the 12x4 array that will be used displaySeats(plane);//shows the user what seats are available/taken isSeatAvailable(plane);//allows the user to see if a seat is available reserveSeat(plane);//allows the user to reserve a seat displaySeats(plane);//shows the user their seat has been reserved seatsAvailInRow(plane);//shows how many seats are avail in given row findRowWithTwoSeats(plane);//finds closest row with adjacent seats countSeatsAvail(plane);//counts how many seats are available countTakenSeats(plane);//counts how many seats are taken } public static void displaySeats(int seats[][]) {//displays the seats System.out.print(&quot;\tA \tB \tC \tD \n&quot;); for (int row = 0; row &lt; seats.length; row++) { System.out.print(row + 1 + &quot;&quot;); for (int seatNum = 0; seatNum &lt; seats[row].length; seatNum++) { if (seats[row][seatNum] == 1) { System.out.print(&quot;\tX &quot;); } else { System.out.print(&quot;\t0 &quot;); } } System.out.println(); } } public static int[][] fillSeatsRandomly() {//fills seats randomly, returns //an array of seats either filled or empty int[][] rndm = new int[12][4]; for (int[] rndm1 : rndm) { for (int col = 0; col &lt; rndm1.length; col++) { rndm1[col] = (int) Math.round(Math.random()); } } return rndm;//return the array }//end of fillSeatsRandomly public static boolean isSeatAvailable(int[][] plane) {//asks user for input //checks if seat is available, returns true if it is and false if not Scanner input = new Scanner(System.in); int rowNum;//row number of the seat chosen int colNum = 4;//column of the seat chosen char seatSelect;//character of the seat chosen String str;//used to get char value for switch System.out.println(&quot;Choose which row you would like to check (1-12)&quot;); rowNum = input.nextInt() - 1; System.out.println(&quot;Choose which seat you would like: A,B,C, or D (Case&quot; + &quot; Sensitive)&quot;); str = input.next(); seatSelect = str.charAt(0); switch (seatSelect) { case 'A': colNum = 0; break; case 'B': colNum = 1; break; case 'C': colNum = 2; break; case 'D': colNum = 3; }//end of switch if (colNum &gt; 3 || colNum &lt; 0 || rowNum &gt; 11 || rowNum &lt; 0) { System.out.println(&quot;Invalid Selection&quot;); return false; }//end of if if (plane[rowNum][colNum] != 0) { System.out.println(&quot;Sorry, seat is taken&quot;); return false; } else { System.out.println(&quot;This seat is available&quot;); return true; }//end of else }//end of isSeatAvail public static int reserveSeat(int[][] plane) {//asks user for input //reserves a seat based on user input, returns updated value to array Scanner input = new Scanner(System.in); int rowNum;//Row number of seat chosen int colNum = 4;//Column number of seat chosen char seatSelect;//Character of seat chosen String str;//used to get char value for switch System.out.println(&quot;Choose which row you would like to reserve (1-12)&quot;); rowNum = input.nextInt() - 1; System.out.println(&quot;Choose which seat you would like: A,B,C, or D (Case&quot; + &quot; Sensitive)&quot;); str = input.next(); seatSelect = str.charAt(0); switch (seatSelect) { case 'A': colNum = 0; break; case 'B': colNum = 1; break; case 'C': colNum = 2; break; case 'D': colNum = 3; }//end of switch if (colNum &gt; 3 || colNum &lt; 0 || rowNum &gt; 11 || rowNum &lt; 0) { System.out.println(&quot;Invalid Selection&quot;); }//end of if if (plane[rowNum][colNum] != 0) { System.out.println(&quot;Sorry, seat is taken&quot;); } else { System.out.println(&quot;Your seat has been reserved&quot;); }//end of if else return plane[rowNum][colNum] = 1;//return updated array value } //end of reserveSeat public static int seatsAvailInRow(int[][] plane) {//checks how many seats //are available in a row determined by user input returns how many seats Scanner input = new Scanner(System.in); int rowNum; int rowSum = 0; int avail; System.out.println(&quot;Choose which row to see how many seats are&quot; + &quot; available (1-12)&quot;); rowNum = input.nextInt() - 1; for (int[] plane1 : plane) { rowSum = 0; for (int j = 0; j &lt; plane1.length; j++) { rowSum += plane[rowNum][j]; } //end of nested for } //end of for avail = 4 - rowSum; System.out.println(&quot;There is &quot; + avail + &quot; seat(s) available in that &quot; + &quot;row&quot;); return avail;//returns number of seats available }//end of seatsAvailInRow public static int findRowWithTwoSeats(int[][] plane) { //finds the closest //row that has 2 adjacent seats, returns row num, or 0 if none for (int i = 0; i &lt; plane.length; i++) { for (int j = 0; j &lt; plane[i].length; j++) { if (plane[i][0] + plane[i][1] == 0 || plane[i][1] + plane[i][2] == 0 || plane[i][2] + plane[i][3] == 0) { System.out.println(&quot;Row &quot; + (i + 1) + &quot; has adjacent seats&quot;); return i;//returns row num with adjacent seats }//end of if } //end of nested for } //end of for return 0;//returns 0 if there is no adjacent seats }//end of findRowWithTwoSeats public static int countSeatsAvail(int[][] plane) {//counts how many seats //are available on the plane, returns int value for number of seats int count = 0;//used to keep track of how many seats are available for (int i = 0; i &lt; plane.length; i++) { for (int j = 0; j &lt; plane[i].length; j++) { if (plane[i][j] == 0) { count++; }//end of if }//end of nested for }//end of for System.out.println(&quot;There are &quot; + count + &quot; seats available&quot;); return count;//returns the number of seats available }//end of countSeatsAvail public static int countTakenSeats(int[][] plane) {//counts number of seats //taken on the plane, returns int value for number of seats taken int count = 0;//used to keep track of how many seats are taken for (int i = 0; i &lt; plane.length; i++) { for (int j = 0; j &lt; plane[i].length; j++) { if (plane[i][j] == 1) { count++; } }//end of nested for }//end of for System.out.println(&quot;There are &quot; + count + &quot; seats taken&quot;); return count;//returns number of seats taken }//end of countTakenSeats }//end of class </code></pre>
[]
[ { "body": "<p>The main feedback is going to be that you aren't delivering in the right way. You only needed to create methods that could be used by a reservation system internally. You don't need to create the whole reservation system.</p>\n<p>You should start with defining a <code>Plane</code> as being this thing that &quot;has&quot; some <code>seats</code>:</p>\n<pre><code>class Plane {\n int[][] seats = new int[12][4];\n}\n</code></pre>\n<p>Then, <code>fillSeatsRandomly</code> sounds like they want you to write an operation that works on some particular <code>Plane</code> that can update the status of its seats.</p>\n<pre><code>class Plane {\n int[][] seats = new int[12][4];\n\n public void fillSeatsRandomly() {\n for ( int row = 0; row &lt; seats.length ; row ++ ) {\n // ...\n }\n }\n}\n</code></pre>\n<p>And so on. Think about it as though your Prof. is going to take your code and write <code>main</code> for themselves. Though you can, and probably should, write your own <code>main</code> function to demonstrate your understanding. Just <em>don't</em> prompt the user. Instead, have it do hard-coded things using the randomized plane.</p>\n<pre><code>class Plane {\n int[][] seats = new int[12][4];\n\n public void fillSeatsRandomly() {\n for ( int row = 0; row &lt; seats.length; row ++ ) {\n // ...\n }\n }\n\n public boolean isSeatAvailable(int row, char column) {\n // ...\n // return (... == 0);\n }\n\n // ...\n\n public static void main(String[] args) {\n Plane p = new Plane();\n p.fillSeatsRandomly();\n p.displaySeats();\n if (p.isSeatAvailable(4, 'C')) {\n p.reserveSeat(4, 'C');\n }\n // ...\n }\n}\n</code></pre>\n<p>I've dropped the word <code>static</code> from all but <code>main</code>. Do you understand why that is? If not, refresh yourself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T04:07:52.370", "Id": "252399", "ParentId": "252390", "Score": "3" } } ]
{ "AcceptedAnswerId": "252399", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T21:56:34.420", "Id": "252390", "Score": "2", "Tags": [ "java", "array" ], "Title": "Applying 2d Array To Methods Plus Return Statements (Java)" }
252390
<p>I am making a Ping Pong game using Html5 Canvas. I am concerned about the <code>movement(_b)</code> method. This method should move the computer paddle (up and down) vertically and follow the ball. Some sort of simple AI. Everything works like it should but there is a lot of repetition of if else blocks that might be handled differently. Like shorter code or at least a bit more elegant.</p> <p>The <code>_b</code> in the <code>movement(_b)</code> is parameter for the ball that will be passed as an argument.</p> <p>The keyword this refers to the computer paddle</p> <p>The code below might give you an idea of what I am talking about.</p> <pre><code>class Paddle { constructor(x, y, width, height, color) { this.x = x this.y = y this.width = width this.height = height this.color = color } // collision logic here... } class Ball { constructor(x, y, x_velocity, y_velocity, radius, color) { this.x = x; this.y = y; this.velocity = { x: x_velocity, y: y_velocity } this.radius = radius; this.color = color; this.isBouncingAllowed = true; } // movement logic here... } class ComputerPaddle extends Paddle { constructor(...args) { super(...args) } movement(_b) { let centerOfPaddle = this.y + this.height / 2; if (centerOfPaddle &lt; _b.y - 80) { this.y += 4 } else if (centerOfPaddle &gt; _b.y + 80) { this.y -= 4 } else if (centerOfPaddle &lt; _b.y - 60) { this.y += 2 } else if (centerOfPaddle &gt; _b.y + 60) { this.y -= 2 } else if (centerOfPaddle &lt; _b.y - 40) { this.y += 1 } else if (centerOfPaddle &gt; _b.y + 40) { this.y -= 1 } else if (centerOfPaddle &lt; _b.y - 20) { this.y += 0.5 } else if (centerOfPaddle &gt; _b.y + 20) { this.y -= 0.5 } } update(_ball_) { this.movement(_ball_) this.ballInteraction(_ball_) this.draw() } } let player = new PlayerPaddle(20, canvas.height / 2 - sizes.paddle.height / 2, sizes.paddle.width, sizes.paddle.height, 'red') let computer = new ComputerPaddle(canvas.width - (20 + sizes.paddle.width), canvas.height / 2 - sizes.paddle.height / 2, sizes.paddle.width, sizes.paddle.height, 'cyan') let ball = new Ball(250, 350, 5, 0, sizes.ball.radius, 'green') function animate() { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height) ball.update() player.update(ball) computer.update(ball) } animate(); </code></pre> <p>Any suggestions will be much appreciated.</p> <p>EDIT: I did add the Ball and Paddle constructors. The methods in the classes containing the movement and collision detection logic were not included because that code is over 100 lines long and probably not relevant for my question.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T08:39:07.300", "Id": "497284", "Score": "3", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T08:39:43.790", "Id": "497285", "Score": "1", "body": "Code Review requires concrete code from a project, **with sufficient context for reviewers to understand how that code is used**. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T09:02:42.200", "Id": "497288", "Score": "0", "body": "I asked this exact question with the exact title on stack overflow. However the moderators told me to ask this exact question with the exact title here and sent me a link. Thanks for the links anyway. I will have them in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T09:28:47.110", "Id": "497289", "Score": "2", "body": "This is not Stack Overflow, and its mods are not this SE's mods. We have own rules, please adhere to them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T09:31:05.547", "Id": "497290", "Score": "0", "body": "I will try my best in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T12:51:31.453", "Id": "497298", "Score": "0", "body": "The more code you give us to review the better the answers will be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:20:13.577", "Id": "497303", "Score": "1", "body": "Shame you shut this down as I had a much better answer than what you have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T08:54:12.210", "Id": "497390", "Score": "3", "body": "It's not too late to fix _this_ question to get it reopened. Just tell us more about what this code is designed to accomplish (\"AI to control a Pong paddle\", maybe?) and retitle the question accordingly. Add some detail about what `this` and `_b` are supposed to represent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T09:15:17.537", "Id": "497391", "Score": "0", "body": "I will edit the question. Thanks for the suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T10:02:17.113", "Id": "497392", "Score": "0", "body": "The question is edited. If there are other suggestions on how to improve the question let me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T13:37:55.143", "Id": "497413", "Score": "0", "body": "Does a `Paddle` extend a `Ball` or another common parent class, which has properties `y` and `height`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T14:09:00.867", "Id": "497416", "Score": "1", "body": "The class Paddle has properties y and x. . The class Ball is not connected to any other class. I will add some short piece of code from the Paddle constructor if it is helpful." } ]
[ { "body": "<p>To cut down on code you can pull <code>_b.y</code> to the left-hand side of the inequality and chain the ternary operator like so:</p>\n<pre><code>function movement(_b) {\n const centerOfPaddle = this.y + this.height / 2;\n const dist = centerOfPaddle - _b.y\n\n const delta = (\n dist &lt; -80 ? 4 :\n dist &lt; -60 ? 2 :\n dist &lt; -40 ? 1 :\n dist &lt; -20 ? .5 :\n dist &gt; 80 ? -4 :\n dist &gt; 60 ? -2 :\n dist &gt; 40 ? -1 :\n dist &gt; 20 ? -.5 :\n 0\n )\n\n this.y += delta\n}\n</code></pre>\n<p>The other option would be exploiting the symmetry of your breakpoints with something like</p>\n<pre><code>function movement(_b) {\n breakPoints = [\n { dist: 80, delta: 4 },\n { dist: 60, delta: 2 },\n { dist: 40, delta: 1 },\n { dist: 20, delta: .5 },\n ]\n\n const centerOfPaddle = this.y + this.height / 2;\n const distFromCenter = centerOfPaddle - _b.y\n\n b = breakPoints.find(e =&gt; \n ( distFromCenter &lt; -e.dist ) ||\n ( distFromCenter &gt; e.dist )\n )\n \n const delta = (\n ( distFromCenter &lt; -b.dist ) ? b.delta :\n ( distFromCenter &gt; b.dist ) ? -b.delta :\n 0\n )\n\n this.y += delta\n}\n</code></pre>\n<p>Maybe overkill for your problem but it lets you update the breakpoints and values you're evaluating a bit more easily if you need to change them</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:56:25.783", "Id": "497265", "Score": "1", "body": "Thanks for the feedback. The first example works great. The second one doesn't. Gives me error on this piece of code \"(distFromCenter < -b.dist) ? b.delta :\". The error is \"Uncaught TypeError: Cannot read property 'dist' of undefined\". Also i had to put let before breakPoints and b because this is class method and it didn't run without the let." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:07:03.343", "Id": "497268", "Score": "0", "body": "I didn't really test the second one beyond a couple values so not surprised. I'm guessing `breakPoints.find()` returns `undefined` for some range of values so there should be something that catches `b === undefined` and sets `delta=0` in that case before any reference to `b.dist` if that makes sense. My goal was more showing a potential way to exploit the symmetry of your problem than provide a a well tested solution. Hope you can see the overall goal!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:10:52.277", "Id": "497272", "Score": "0", "body": "Thanks for your answer. Much appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:23:10.207", "Id": "497273", "Score": "1", "body": "Made some changes to the code \" const delta = (\n (b === undefined) ? 0 : \n (distFromCenter < -b.dist) ? b.delta :\n (distFromCenter > b.dist) ? -b.delta :\n 0\n )\" and it works now. If some noob like me in the future needs it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:12:27.830", "Id": "252395", "ParentId": "252392", "Score": "4" } }, { "body": "<p>Using a mechanical refactoring approach, you could create an array of objects to encapsulate the offsets and values associated with each offset:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>movement(_b) {\n let centerOfPaddle = this.y + this.height / 2;\n\n let offsets = [\n { offset: 80, value: 4 },\n { offset: 60, value: 2 },\n { offset: 40, value: 1 },\n { offset: 20, value: 0.5 },\n ];\n\n for (const { offset, value } of offsets) {\n if (centerOfPaddle &lt; _b.y - offset) {\n this.y += value;\n break;\n } else if (centerOfPaddle &gt; _b.y + offset) {\n this.y -= value;\n break;\n }\n }\n}\n</code></pre>\n<p>Going further, you could do a more conceptual refactoring and figure out the math behind your logic. For example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>movement(_b) {\n let centerOfPaddle = this.y + this.height / 2;\n\n for (let i = 80, j = 4; i &gt;= 20; i -= 20, j /= 2) {\n if (centerOfPaddle &lt; _b.y - i) {\n this.y += j;\n break;\n } else if (centerOfPaddle &gt; _b.y + i) {\n this.y -= j;\n break;\n }\n }\n}\n</code></pre>\n<p>You could give those loop variables more appropriate names like <code>offset</code> and <code>value</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:59:02.967", "Id": "497266", "Score": "0", "body": "Hey thanks a lot for the help. The first example doesn't seems to work properly. No errors but it always gets this 0.5 speed. The second example works great." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:05:40.503", "Id": "497267", "Score": "0", "body": "Ah, that is because Object.entries does not guarantee the order of properties. You need to use an array instead. Let me add an example for that. In any case, the last example is probably best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:07:10.430", "Id": "497269", "Score": "0", "body": "I updated the first example to use an array instead. Now it should work as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:07:46.703", "Id": "497270", "Score": "0", "body": "give me a sec to try it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:08:37.563", "Id": "497271", "Score": "1", "body": "It works great. Thanks dude for the help. Have a nice day!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:15:55.947", "Id": "497300", "Score": "0", "body": "For the mathematical refactor section: `offset = centerOfPaddle - _b.y; bin = clamp(floor(abs(offset / 20)), 0, 3); direction = sign(offset); this.y += direction * 2**(bin - 1);`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:44:56.023", "Id": "252397", "ParentId": "252392", "Score": "8" } }, { "body": "<p>First, this kind of expressions:</p>\n<pre><code>centerOfPaddle &lt; _b.y - 80\n</code></pre>\n<p>can be rewritten as</p>\n<pre><code>centerOfPaddle - _b.y &lt; -80 \n</code></pre>\n<p>So let's put it in a variable:</p>\n<pre><code>let offset = centerOfPaddle - _b.y\n</code></pre>\n<p>Next, you have a mirror symmetry so let's not duplicate it for both sides, rather establish first which side it is, for example:</p>\n<pre><code>let invertFactor = 1\nif (offset &lt; 0){ invertFactor = -1 }\n</code></pre>\n<p>Now we can write a switch for only one of each of those thresholds and the invertFactor takes care of the left/right side:</p>\n<pre><code>switch(Math.floor(Math.abs(offset / 20))){\n case 4:\n this.y -= 4 * invertFactor\n break\n case 3:\n this.y -= 2 * invertFactor\n break\n case 2:\n this.y -= 1 * invertFactor\n break\n case 1:\n this.y -= 0.5 * invertFactor\n break\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T12:36:58.053", "Id": "497296", "Score": "0", "body": "The case numbers 4, 3, 2, 1 and the factors 4, 2, 1, 0.5 are closely related. `factor = 2 ^ (case_number - 2)` which translates to `const case_number = Math.floor(Math.abs(offset / 20)); this.y -= Math.pow(2, case_number - 2) * invertFactor;`. That looks even simpler than the math version by @elclanrs since it doesn't have a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T12:38:52.510", "Id": "497297", "Score": "0", "body": "One could also argue that `const invertFactor = offset < 0 ? -1 : 1;` is better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T09:16:52.650", "Id": "252401", "ParentId": "252392", "Score": "4" } }, { "body": "<h2>Pong</h2>\n<p>This code looks like part of a pong like game logic.</p>\n<p>With that in mind we can make some changes to the naming</p>\n<p>Replacing the function <code>movement</code> with <code>movePaddle</code> and the argument to<code> ball</code></p>\n<h3>Using a lookup table</h3>\n<p>Then in 3 steps</p>\n<ul>\n<li><p>Find the vertical distance to the ball from the paddle center.</p>\n</li>\n<li><p>Convert that distance to an index used to lookup speeds.</p>\n</li>\n<li><p>Use the sign of the distance to convert the speed to the correct sign.</p>\n</li>\n</ul>\n<p>Example</p>\n<pre><code>const SPEEDS = [0, 0.5, 1, 2, 4]; \n\nmovePaddle(ball) {\n const distance = ball.y - (this.y + this.height / 2);\n const idx = Math.min(Math.abs(distance / 20) | 0, SPEEDS.length - 1);\n this.y += SPEEDS[idx] * Math.sign(distance);\n}\n</code></pre>\n<h2>Smooth change</h2>\n<p>However I am guessing that the speeds are somewhat arbitrary and thus a functional approximation will do just as well. That the speed is a function of distance. A hermite curve looks like a close approximation.</p>\n<p>The result is a smooth change in speed as he ball gets closer , but depending on how the ball moves this will need to be tuned to get the correct look and feel.</p>\n<pre><code>const MAX_SPEED = 4;\nconst MIN_SPEED_CUTOFF = 0.5;\nconst DISTANCE_RANGE = 80;\n\n\nmovePaddle(ball) {\n const dist = (ball.y - (this.y + this.height / 2)) / DISTANCE_RANGE;\n const uDist = Math.abs(dist &lt; -1 ? -1 : dist &gt; 1 ? 1 : dist);\n const y = (uDist * uDist * (3 - 2 * uDist)) * MAX_SPEED; // hermite curve \n this.y += (y &lt; MIN_SPEED_CUTOFF ? 0 : y) * Math.sign(dist);\n}\n</code></pre>\n<h3>Further improvements</h3>\n<p>One can go further and use the balls distance from the paddle (horizontal) to calculate how long until the ball reaches the edge. This time can then be used to scale the speed so that the paddle can be at an exact position when the ball arrives.</p>\n<p>Also using the balls horizontal speed to workout if it is coming or going. Thus the paddle need move only when it needs to rather than track the ball all the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T04:17:47.037", "Id": "497490", "Score": "0", "body": "Thanks a lot. I really appreciate your effort. It helped me a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T04:24:54.893", "Id": "497491", "Score": "0", "body": "A honest question now. Do I change this to the accepted answer. I am asking because I don't want to be rude or unthankful to anyone and I am not sure what are the policies about these kind of things here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T05:19:40.930", "Id": "497493", "Score": "0", "body": "@HappyCoconut There is no policy in regard to accepting answers. Accept the answer that you feel most helped you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T02:29:23.630", "Id": "252471", "ParentId": "252392", "Score": "3" } } ]
{ "AcceptedAnswerId": "252471", "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T23:33:59.767", "Id": "252392", "Score": "6", "Tags": [ "javascript", "game" ], "Title": "AI to control a Ping Pong paddle" }
252392
<p>I am working on a small project that requires finding Von Neumann neighborhoods in a matrix. Basically, whenever there is a positive value in the array, I want to get the neighborhood for that value. I used an iterative approach because I don't think there's a way to do this in less than O(n) time as you have to check every single index to make sure all of the positive values are found. My solution is this:</p> <pre><code>is_counted = {} recursions = [] def populate_dict(grid, n): rows = len(grid) cols = len(grid[0]) for i in range(rows): for j in range(cols): if grid[i][j] &gt; 0: find_von_neumann(grid, i, j, n, rows, cols) return len(is_counted.keys()) def find_von_neumann(grid, curr_i, curr_j, n, rows, cols): #print(curr_i, curr_j) recursions.append(1) if n == 0: cell = grid[curr_i][curr_j] if cell &gt; 0: key = str(curr_i) + str(curr_j) if key not in is_counted: is_counted[key] = 1 if n &gt;= 1: coord_list = [] # Use Min so that if N &gt; col/row, those values outside of the grid will not be computed. for i in range(curr_i + min((-n), rows), curr_i + min((n + 1), rows)): for j in range(curr_j + min((-n), cols), min(curr_j + (n + 1), cols)): dist = abs((curr_i - i)) + abs((curr_j - j)) if n &gt;= dist &gt;= -n and i &gt;= 0 and j &gt;= 0 and i &lt; rows and j &lt; cols: coord_list.append([i, j]) for coord in coord_list: key = str(coord[0]) + str(coord[1]) if key not in is_counted: is_counted[key] = 1 neighbors = populate_dict([ [-1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1], [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1], [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1], [-1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [-1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], 2) print(neighbors) </code></pre> <p>I went with a hash table as my data structure but I believe that currently the worst case runtime would look very similar to O(n^2). For example if N (the distance factor) is equal to the amount of rows or columns AND every single value is positive, its going to be inefficient. Am I missing something with my solution, for example could using dynamic programming possibly help cut down on the runtime or is this already a good solution?</p> <p>I'm fairly new to algorithms and runtime analysis so please correct me if I messed up on anything in my own analysis of this , thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T04:32:37.640", "Id": "497275", "Score": "2", "body": "Please check that you posted the correct code. The indentation is wrong and both branches of the `if grid[coord[0]][coord[1]] < 1:` are the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T05:00:19.553", "Id": "497276", "Score": "0", "body": "@RootTwo you're right that logic was for a different approach I tried but forgot to change, also fixed the indentation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T14:02:27.893", "Id": "497315", "Score": "1", "body": "What is the result supposed to be? You forgot to describe the task." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:01:01.187", "Id": "497319", "Score": "0", "body": "@superbrain Sorry this is my first time using code review but I just updated it again and this matches my local code exactly. The task is to find the Von Neumann neighborhoods of every positive cell in the matrix and return the total number of cells that are in all Von Neumann neighborhoods in the matrix, but it does not need to return the locations of the neighborhoods themselves. Sorry for the mix up!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:36:17.340", "Id": "497362", "Score": "0", "body": "Do you actually care about these neighborhoods, or do you just want to know the number of grid cells within n steps of some positive value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:19:47.700", "Id": "497367", "Score": "0", "body": "At the moment no we don’t care about the neighborhoods, but we might @suberbrain" } ]
[ { "body": "<h2>Set vs. dict</h2>\n<p>So far as I can tell, you aren't really using the value in <code>is_counted</code>, so it is better represented as a set than a dictionary. Also, it shouldn't be global - this prevents re-entrance and hampers testing; instead, make it a return value of <code>find_von_neumann</code>, merged in turn into another set in <code>populate_dict</code> that is returned.</p>\n<h2>Iteration</h2>\n<p>This is both very dense and re-executes a number of things that can be pre-computed:</p>\n<pre><code> for i in range(curr_i + min((-n), rows), curr_i + min((n + 1), rows)):\n for j in range(curr_j + min((-n), cols), min(curr_j + (n + 1), cols)):\n \n</code></pre>\n<p>instead consider something like</p>\n<pre><code>i0 = curr_i + min((-n), rows)\ni1 = curr_i + min((n + 1), rows)\nj0 = curr_j + min((-n), cols)\nj1 = min(curr_j + (n + 1), cols)\n\nfor i in range(i0, i1):\n for j in range(j0, j1):\n</code></pre>\n<h2>Combined inequalities</h2>\n<p>You did the right thing here:</p>\n<pre><code>n &gt;= dist &gt;= -n\n</code></pre>\n<p>though I would find it more intuitive as</p>\n<pre><code>-n &lt;= dist &lt;= n\n</code></pre>\n<p>You should do the same for <code>i</code> and <code>j</code>:</p>\n<pre><code>0 &lt;= i &lt; rows and 0 &lt;= j &lt; cols\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T19:10:35.620", "Id": "497352", "Score": "2", "body": "This was awesome, thank you taking a look at it! I didn't even think to do those pre-computations and on our largest data set it made a very real difference" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:58:44.353", "Id": "252421", "ParentId": "252396", "Score": "3" } }, { "body": "<p>The indexing in these loops looks wrong:</p>\n<pre><code>if n &gt;= 1:\n\n coord_list = []\n # Use Min so that if N &gt; col/row, those values outside of the grid will not be computed.\n for i in range(curr_i + min((-n), rows), curr_i + min((n + 1), rows)):\n for j in range(curr_j + min((-n), cols), min(curr_j + (n + 1), cols)):\n dist = abs((curr_i - i)) + abs((curr_j - j))\n\n if n &gt;= dist &gt;= -n and i &gt;= 0 and j &gt;= 0 and i &lt; rows and j &lt; cols:\n\n coord_list.append([i, j])\n</code></pre>\n<p>The <code>if n &gt;= 1:</code> means <code>-n</code> is a negative number so <code>min((-n), rows)</code> always returns <code>-n</code>.</p>\n<p><code>dist</code> is the sum of two positive numbers (<code>abs((curr_i - i)) + abs((curr_j - j))</code>) so it is always positive and the test <code>dist &gt;= -n</code> is unnecessary.</p>\n<p>The comment says using <code>min</code> to keep <code>i</code> and <code>j</code> in the grid, but the calculations are not correct so <code>i</code> and <code>j</code> may be outside the grid. The later <code>if ... i &gt;= 0 and j &gt;= 0 ...</code> is filtering out the bad index values.</p>\n<p>I think you meant to do something like this (untested) code:</p>\n<pre><code> i_start = max(curr_i - n, 0)\n i_end = min(curr_i + n + 1, rows)\n j_start = max(curr_j - n, 0)\n j_end = min(curr_j + n + 1, cols)\n\n for i in range(i_start, i_end):\n for j in range(j_start, j_end):\n dist = abs((curr_i - i)) + abs((curr_j - j))\n\n if dist &lt;= n:\n\n coord_list.append([i, j])\n</code></pre>\n<p>The Von Neumann neighborhood has a diamond shape. So you could make <code>j_start</code> and <code>j_end</code> also depend on <code>abs(curr_i - i)</code>. That would check fewer cells and let you eliminate the test <code>dist &lt;= n</code>.</p>\n<p>Big-O complexity: <code>populate_dict</code> iterates over the entire grid, so it is O(rows x cols). <code>find_von_neumann</code> iterates over a diamond that with an area that grows as n^2 so it is O(n^2). Because <code>find_von_neumann</code> is called for every square in the grid, the over all complexity is O(rows x cols x n^2).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T19:17:15.460", "Id": "497353", "Score": "0", "body": "Good point on the min and dist comparisons being unnecessary. Also I guess I should have put this in the original post but is O(n^2) necessarily bad for these types of algorithms or is there a different to approach this then how I'm currently looking at it? It runs fast enough for anything that we'd need for at the moment but I have a feeling we'll be using this in future projects with possibly more data. Also thank you for taking the time to go through my code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T19:10:47.607", "Id": "252429", "ParentId": "252396", "Score": "3" } }, { "body": "<p>This doesn't look right:</p>\n<pre><code> for coord in coord_list:\n key = str(coord[0]) + str(coord[1])\n if key not in is_counted:\n is_counted[key] = 1\n</code></pre>\n<p>For example, both <code>coord = [1, 11]</code> and <code>coord = [11, 1]</code> have the same key <code>'111'</code>. Unless that's really intended, you should probably insert a non-digit character in the middle to distinguish the cases. Or, much simpler, just use <em>tuples</em> of ints like <code>(1, 11)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:21:11.443", "Id": "497368", "Score": "0", "body": "I didn’t even notice that, good catch! I was going to use a list as the key but forgot you can’t user mutable data structures as keys, but tuples sounds like the answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:07:27.937", "Id": "252432", "ParentId": "252396", "Score": "3" } } ]
{ "AcceptedAnswerId": "252429", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:36:36.383", "Id": "252396", "Score": "2", "Tags": [ "python", "performance", "algorithm", "matrix" ], "Title": "How can I optimize my Von Neumann neighborhood algorithm?" }
252396
<p>I've been programming in Go and I enjoy how easy it is to create descriptive errors and propagate them up the call stack. I wanted that sort of ease and consistency in C so I created a small error handling library to propagate errors and generate a sort of error code stack trace.</p> <p>I've been using C for 6 months so I'm not sure if I have designed this program well. I would appreciate feedback on the API and if it is well-structured. I am unsure if I am adhering well to software engineering best practices. I would also appreciate some feedback on the implementation itself, particularly for the 1. <code>SetNewError_()</code> function and 2. the callbacks (hooks) for the memory allocator and logging mechanisms in the <code>InitError()</code> function.</p> <p>This is essentially an array-based stack where the user can push error nodes which contain the metadata for a specific error. I tried to reduce usage of dynamic allocation as much as possible, so that the error handler itself isn't prone to failure. So no linked lists and no <code>malloc</code> for strings.</p> <p>I made a github repository here which contains everything, including the unit tests and examples. I might also appreciate feedback on if the repository is set up correctly, as I am fairly new to source control. <a href="https://github.com/birendpatel/XT" rel="noreferrer">https://github.com/birendpatel/XT</a></p> <p>Thank you!</p> <p>Library API: <strong>error.h</strong></p> <pre><code>/* * NAME: Copyright (c) 2020, Biren Patel * DESC: API for a lightweight error handling library * LISC: MIT License */ #ifndef ERROR_H #define ERROR_H /******************************************************************************* * DESC: modifiable macros * NOTE: each definition must be &gt;= 1 * @ ERROR_FNAME_SIZE : maximum chars alloted for file name * @ ERROR_FXNAME_SIZE : maximum chars alloted for function name * @ ERROR_DESC_SIZE : maximum chars alloted for error description *******************************************************************************/ #define ERROR_FNAME_SIZE 16 #define ERROR_FXNAME_SIZE 16 #define ERROR_DESC_SIZE 24 /******************************************************************************* * DESC: error handling and API set up *******************************************************************************/ #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdarg.h&gt; #ifndef __clang__ #ifndef __GNUC__ #error error.h recommends Clang or GCC for function attributes \ disable this directive to continue compilation #endif #endif #ifdef __STDC_VERSION__ #if __STDC_VERSION__ &gt;= 199901L #define ERROR_H_VA_ARGS_OK #endif #endif #if ERROR_FNAME_SIZE &lt; 1 #error error.h fname size is too small #endif #if ERROR_FXNAME_SIZE &lt; 1 #error error.h fxname size is too small #endif #if ERROR_DESC_SIZE &lt; 1 #error error.h desc size is too small #endif /******************************************************************************* * NAME: struct error_node_t * DESC: metadata container for a single error * @ code : error code * @ line : file line * @ fname : file name * @ fxname : function name * @ desc : error description *******************************************************************************/ struct error_node_t { int code; int line; char fname[ERROR_FNAME_SIZE]; char fxname[ERROR_FXNAME_SIZE]; char desc[ERROR_DESC_SIZE]; }; /******************************************************************************* * NAME: struct error_t * DESC: the error stack and end-user handle * @ cb_log : logging callback * @ tmp : placeholder (struct padding allows for it) * @ lost : tracks overflow statistics * @ cap : total capacity of stack * @ top : index of next available element * @ stack : LIFO unless overflow is imminent *******************************************************************************/ typedef struct error_t { void (*cb_log)(int code); int tmp; int lost; int cap; int top; struct error_node_t stack[]; } *error_t; /******************************************************************************* * NAME: InitError * DESC: initialize a variable with optional callbacks * OUTP: null if stdlib calloc failed * NOTE: stdlib calloc used when cb_calloc is NULL. release memory with free. * * @ n : maximum capacity of errors that can be held in error_t * * @ cb_calloc : callback for custom calloc which should have the same signature * as stdlib calloc and also return NULL on failure. Besides using * this for custom memory allocators, with a little extra effort * we can overload this pointer to load error_t onto the .DATA * segment instead of the heap. * * @ cb_log : callback for logging errors resulting from API failure. Yes, the * error handler itself can fail to handle errors! Use the enum * below to track the return codes. Errors are returned by the API * functions themselves. If cb_log is non-NULL then errors are both * returned and passed to cb_log(). One reason to do this is so you * can use the API lazily and have the cb_log passively check all * errors and abort/fail/etc if anything goes wrong. The CBLOG * enum suffix gives the function acronym. *******************************************************************************/ struct error_t *InitError ( int n, void *(*cb_calloc)(size_t num, size_t size), void (*cb_log)(int code) ); //use this to determine error_t byte size when using complex callbacks. #define ERROR_BYTES(n) \ (sizeof(struct error_t) + sizeof(struct error_node_t) * (size_t) n) //these are all possible codes that can be passed to cb_log. //ERROR_CBLOG_SUCCESS is never passed to cb_log //ERROR_SNE_VSNPRINTF_FAIL has a fallback mechanism so it's a partial failure. enum { ERROR_CBLOG_SUCCESS = 0 , ERROR_CBLOG_STDLIB_CALLOC_FAIL = 1 , ERROR_CBLOG_CUSTOM_CALLOC_FAIL = 2 , ERROR_CBLOG_ENIE_NULL_INPUT = 3 , ERROR_CBLOG_RMAE_NULL_INPUT = 4 , ERROR_CBLOG_RMRE_NULL_INPUT = 5 , ERROR_CBLOG_RSAE_NULL_INPUT = 6 , ERROR_CBLOG_RSRE_NULL_INPUT = 7 , ERROR_CBLOG_RE_NULL_INPUT = 8 , ERROR_CBLOG_AE_NULL_INPUT = 9 , ERROR_CBLOG_EE_NULL_INPUT = 10 , ERROR_CBLOG_NEE_NULL_INPUT = 11 , ERROR_CBLOG_SNE_NULL_INPUT = 12 , ERROR_CBLOG_SNE_VSNPRINTF_FAIL = 13 , ERROR_CBLOG_RAE_NULL_INPUT = 14 , ERROR_CBLOG_RAE_FPRINTF_FAIL = 15 , }; /******************************************************************************* * NAME: SetNewError_, SetNewError, SetNewDetailedError * DESC: push an error node onto the handle's stack * NOTE: nodes must use a zero code to indicate success * NOTE: to prevent uncontrolled format string exploit do not expose function * @ code : error code * @ line : line number at which SetNewError is called * @ fname : file name, not exceeding ERROR_FNAME_SIZE * @ fxname : function name, not exceeding ERROR_FXNAME_SIZE * @ desc : error description, not exceeding ERROR_DESC_SIZE * @ ... : optional format parameters for desc *******************************************************************************/ #if defined(__clang__) || defined(__GNUC__) __attribute__((__format__ (__printf__, 6, 7))) #endif bool SetNewError_ ( struct error_t *error, int code, int line, const char *fname, const char *fxname, const char *desc, ... ); #define SetNewError(error, code, desc) \ SetNewError_(error, code, __LINE__, __FILE__, __func__, desc) #ifdef ERROR_H_VA_ARGS_OK #define SetNewDetailedError(error, code, desc, ...) \ SetNewError_(error, code, __LINE__, __FILE__, __func__, desc, __VA_ARGS__) #endif /******************************************************************************* * NAME: SetNewErrorGo, SetNewDetailedErrorGo * DESC: wrappers for the commom goto resource cleanup idiom used in C *******************************************************************************/ #define SetNewErrorGo(error, code, desc, label) \ do \ { \ SetNewError(error, code, desc); \ goto label; \ } while (0) #ifdef ERROR_H_VA_ARGS_OK #define SetNewDetailedErrorGo(error, code, desc, label, ...) \ do \ { \ SetNewDetailedError(error, code, desc, __VA_ARGS__); \ goto label; \ } while (0) #endif //-*- //the tough part of the API is done. Below we just have some very simple stack //manipulation, error checking, and reporting functions. Most are overkill. You //will probably spend 99% of your time in RecentError() and ReportAllError(). /******************************************************************************* * NAME: EmptyNodesInError * DESC: calculate the remaining number of available nodes * OUTP: negative if input pointer is null *******************************************************************************/ int EmptyNodesInError(struct error_t *error); /******************************************************************************* * NAME: RemoveAllError * DESC: remove all error nodes from the stack * OUTP: false if input pointer is null *******************************************************************************/ bool RemoveAllError(struct error_t *error); /******************************************************************************* * NAME: RemoveRecentError * DESC: remove the error node at the top the stack * OUTP: false if input pointer is null *******************************************************************************/ bool RemoveRecentError(struct error_t *error); /******************************************************************************* * NAME: ResetAllError * DESC: completely reset and zero out the error handle to a fresh state * NOTE: RemoveAllError does synthetic removals and is therefore much faster *******************************************************************************/ bool ResetAllError(struct error_t *error); /******************************************************************************* * NAME: ResetRecentError * DESC: reset and zero out the error node at the top of the stack * NOTE: RemoveLastError does synthetic removals and is therefore much faster *******************************************************************************/ bool ResetRecentError(struct error_t *error); /******************************************************************************* * NAME: RecentError * DESC: Fetch the error code at the top of the stack * OUTP: negative number on null input and 0 on empty stack *******************************************************************************/ int RecentError(const struct error_t *error); /******************************************************************************* * NAME: AnyError * DESC: Check if any error code in the stack is nonzero * OUTP: If any error code is nonzero, return true. zero and empty returns false *******************************************************************************/ bool AnyError(const struct error_t *error); /******************************************************************************* * NAME: ExistsError * DESC: Check if any error code in the stack matches the argument * OUTP: true if match, false if no match or empty stack. *******************************************************************************/ bool ExistsError(const struct error_t *error, const int code); /******************************************************************************* * NAME: NotExistsError * DESC: Check if no error code in the stack matches the argument * OUTP: true if no match or empty stack, false if match *******************************************************************************/ bool NotExistsError(const struct error_t *error, const int code); /******************************************************************************* * NAME: ReportAllError * DESC: create a detailed trace of the error stack * @ stream : write target *******************************************************************************/ bool ReportAllError(struct error_t *error, FILE *stream); #endif </code></pre> <p>Implementation: <strong>error.c</strong></p> <pre><code>/* * NAME: Copyright (c) 2020, Biren Patel * DESC: Implementation for a lightweight error handling library * LISC: MIT License */ #include &quot;error.h&quot; #include &lt;string.h&gt; #include &lt;assert.h&gt; /******************************************************************************* prototypes */ static void SafeCopy(char *dest, const char *src, int n); /******************************************************************************* file macros */ #define LOG_ERROR_IF_FOUND(x) \ do \ { \ if (error-&gt;cb_log != NULL) error-&gt;cb_log((x)); \ } while (0) \ /******************************************************************************/ struct error_t *InitError ( int n, void *(*cb_calloc)(size_t num, size_t size), void (*cb_log)(int code) ) { if (n &lt;= 0) return NULL; //override stdlib with callback allocator //raw call to cb_log on error since struct isn't configured yet struct error_t *error = NULL; if (cb_calloc == NULL) { error = calloc(ERROR_BYTES(n), 1); if (error == NULL) { if (cb_log != NULL) cb_log(ERROR_CBLOG_STDLIB_CALLOC_FAIL); return NULL; } } else { error = cb_calloc(ERROR_BYTES(n), 1); if (error == NULL) { if (cb_log != NULL) cb_log(ERROR_CBLOG_CUSTOM_CALLOC_FAIL); return NULL; } } //hook the logging mechanism if available if (cb_log != NULL) error-&gt;cb_log = cb_log; else error-&gt;cb_log = NULL; error-&gt;cap = n; return error; } /******************************************************************************/ int EmptyNodesInError(struct error_t *error) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_ENIE_NULL_INPUT); return -1; } return error-&gt;cap - error-&gt;top; } /******************************************************************************* removal functions are just synthetic pops for speed, unlike the reset functions */ bool RemoveAllError(struct error_t *error) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RMAE_NULL_INPUT); return false; } error-&gt;top = 0; return true; } /******************************************************************************/ bool RemoveRecentError(struct error_t *error) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RMRE_NULL_INPUT); return false; } if (error-&gt;top != 0) { error-&gt;top--; } return true; } /******************************************************************************* completely zero out the struct instead of just decrementing the top pointer. This is helpful when we're inspecting memory maps and raw hex and whatever else where the synthetic pop would just muddy the output with gibberish. */ bool ResetAllError(struct error_t * error) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RSAE_NULL_INPUT); return false; } //capacity and logging hook need to survive the reset int n = error-&gt;cap; void (*cb_log)(int code) = error-&gt;cb_log; memset(error, 0, ERROR_BYTES(n)); error-&gt;cb_log = cb_log; error-&gt;cap = n; return true; } /******************************************************************************/ bool ResetRecentError(struct error_t * error) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RSRE_NULL_INPUT); return false; } if (error-&gt;top != 0) { memset(&amp;error-&gt;stack[error-&gt;top], 0, sizeof(struct error_node_t)); error-&gt;top--; } return true; } /******************************************************************************/ int RecentError(const struct error_t *error) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RE_NULL_INPUT); return -1; } if (error-&gt;top == 0) return 0; return error-&gt;stack[error-&gt;top - 1].code; } /******************************************************************************* sweep the entire stack for a nonzero code. */ bool AnyError(const struct error_t *error) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_AE_NULL_INPUT); return true; } if (error-&gt;top == 0) return false; int i = error-&gt;top; while (i--) { if (error-&gt;stack[i].code != 0) return true; } return false; } /******************************************************************************* This is handy for generating SQL-like idioms. Sweep the stack like AnyError but for a specific code. */ bool ExistsError(const struct error_t *error, const int code) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_EE_NULL_INPUT); return false; } if (error-&gt;top == 0) return false; int i = error-&gt;top; while (i--) { if (error-&gt;stack[i].code == code) return true; } return false; } /******************************************************************************/ bool NotExistsError(const struct error_t *error, const int code) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_NEE_NULL_INPUT); return false; } if (error-&gt;top == 0) return true; int i = error-&gt;top; while (i--) { if (error-&gt;stack[i].code == code) return false; } return true; } /******************************************************************************* Place an error on the stack, if the vsnprintf function fails we fall back on a straight copy without the va_args. the preprocessor pragmas temporarily disable any -Wformat-security warnings which will complain about non string literals being passed to vsnprintf. Since this is an error handling library, an end user shouldn't have access to control error descriptions so a string exploit is not an issue. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored &quot;-Wformat-security&quot; #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored &quot;-Wformat-security&quot; #endif bool SetNewError_ ( struct error_t *error, int code, int line, const char *fname, const char *fxname, const char *desc, ... ) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_SNE_NULL_INPUT); return false; } va_list args; va_start(args, desc); //prevent stack overflow by removing the oldest node if (error-&gt;top == error-&gt;cap) { if (error-&gt;cap != 1) { size_t bytes = sizeof(struct error_node_t) * (size_t) (error-&gt;top - 1); memmove(error-&gt;stack, error-&gt;stack + 1, bytes); } error-&gt;top--; error-&gt;lost++; } error-&gt;stack[error-&gt;top].code = code; error-&gt;stack[error-&gt;top].line = line; //copy fname and fxname by hand so that no possible error from snprint SafeCopy(error-&gt;stack[error-&gt;top].fname, fname, ERROR_FNAME_SIZE); SafeCopy(error-&gt;stack[error-&gt;top].fxname, fxname, ERROR_FXNAME_SIZE); //if vsnprintf fails then fall back to a safe copy on the raw format string if (desc == NULL) { error-&gt;stack[error-&gt;top].desc[0] = '\0'; } else { int status = vsnprintf(error-&gt;stack[error-&gt;top].desc, ERROR_DESC_SIZE, desc, args); if (status &lt; 0) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_SNE_VSNPRINTF_FAIL); SafeCopy(error-&gt;stack[error-&gt;top].desc, desc, ERROR_DESC_SIZE); } } error-&gt;top++; va_end(args); assert(error-&gt;top &lt;= error-&gt;cap &amp;&amp; &quot;top of stack exceeds capacity&quot;); return true; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif /******************************************************************************* Helper function for SetNewError_, safe copy to src as a fallback mechanism in the extremely rare case that vsnprintf fails. This leaves the format params in the description, but having some description is better than nothing. */ static void SafeCopy(char *dest, const char *src, int n) { assert(dest != NULL &amp;&amp; &quot;destination member on error stack is empty&quot;); assert(n != 0 &amp;&amp; &quot;destination member has impossible length of zero&quot;); size_t i = 0; size_t limit = (size_t) n; if (src == NULL) goto null_terminate; size_t end = strlen(src); while (i &lt; limit - 1) { if (i == end) goto null_terminate; else dest[i] = src[i]; i++; } null_terminate: dest[i] = '\0'; return; } /******************************************************************************/ bool ReportAllError(struct error_t *error, FILE *stream) { if (error == NULL) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RAE_NULL_INPUT); return false; } int i = error-&gt;top; int status = 0; status = fprintf(stream, &quot;\n-*-\nerror code stack trace:\n&quot;); if (status &lt; 0) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RAE_FPRINTF_FAIL); return false; } if (i == 0) { status = fprintf(stream, &quot;No error nodes found in stack\n&quot;); if (status &lt; 0) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RAE_FPRINTF_FAIL); return false; } } while (i--) { const int a = error-&gt;stack[i].code; const char *b = error-&gt;stack[i].desc; const char *c = error-&gt;stack[i].fname; const char *d = error-&gt;stack[i].fxname; const int e = error-&gt;stack[i].line; const char *call_fmt = &quot;%d. [error %d \&quot;%s\&quot; (%s:%s:%d)]\n&quot;; status = fprintf(stream, call_fmt, i, a, b, c, d, e); if (status &lt; 0) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RAE_FPRINTF_FAIL); return false; } } char *sum_fmt = &quot;\nsummary:\n%d errors collected in stack\n&quot;; status = fprintf(stream, sum_fmt, error-&gt;top); if (status &lt; 0) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RAE_FPRINTF_FAIL); return false; } const char *pop_fmt = &quot;%d errors disregarded at bottom of stack\n-*-\n&quot;; status = fprintf(stream, pop_fmt, error-&gt;lost); if (status &lt; 0) { LOG_ERROR_IF_FOUND(ERROR_CBLOG_RAE_FPRINTF_FAIL); return false; } return true; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>That certainly looks a lot better than the code I was writing with six months' experience!</p>\n<blockquote>\n<pre><code> #error error.h recommends Clang or GCC for function attributes \\\n disable this directive to continue compilation\n</code></pre>\n</blockquote>\n<p>If that's just &quot;recommends&quot;, then shouldn't this be a warning, rather than an error? Or change &quot;recommends&quot; to &quot;requires&quot; for more honesty!</p>\n<blockquote>\n<pre><code>struct error_node_t\n</code></pre>\n</blockquote>\n<p>Names ending in <code>_t</code> are reserved for use by the Standard Library, so avoid them.</p>\n<p>Here's a weakness of this library:</p>\n<blockquote>\n<pre><code>//these are all possible codes that can be passed to cb_log.\n</code></pre>\n</blockquote>\n<p>Sadly, this means the library is not <em>extensible</em> (library users can't add their own error codes, but need to have them present in the library). Solving that is a hard problem, so perhaps wise to defer that for a while.</p>\n<blockquote>\n<pre><code>#if defined(__clang__) || defined(__GNUC__)\n __attribute__((__format__ (__printf__, 6, 7)))\n#endif\n</code></pre>\n</blockquote>\n<p>This is really good: work with the compiler to help catch usage errors.</p>\n<blockquote>\n<pre><code>#define SetNewErrorGo(error, code, desc, label) \\\ndo \\\n{ \\\n SetNewError(error, code, desc); \\\n goto label; \\\n} while (0)\n</code></pre>\n</blockquote>\n<p>More good work - the <code>do ... while(0)</code> idiom is well-recognised practice for multi-statement macros.</p>\n<blockquote>\n<pre><code>if (error == NULL) \n{\n</code></pre>\n</blockquote>\n<p>It's simpler and idiomatic to use <code>!</code> operator on this pointer: <code>if (!error)</code>, unless your local coding standard requires an comparison.</p>\n<blockquote>\n<pre><code>#pragma GCC diagnostic ignored &quot;-Wformat-security&quot;\n</code></pre>\n</blockquote>\n<p>I experimented (with a few compilers) and never triggered the diagnostic this suppresses. So perhaps it can be removed?</p>\n<blockquote>\n<pre><code>static void SafeCopy(char *dest, const char *src, int n)\n</code></pre>\n</blockquote>\n<p>Good idea, though it's strange to accept a signed <code>int</code> and cast it to <code>size_t</code> (especially without checking whether it's negative). Much better to accept <code>size_t</code> directly (especially given the common pattern <code>char buf[SIZE]; SafeCopy(buf, src, sizeof buf);</code>). Also, we don't need to copy character-by-character:</p>\n<pre><code>static void SafeCopy(char *dest, const char *src, size_t n)\n{\n assert(dest);\n assert(n);\n\n if (!src) { src = &quot;&quot;; }\n\n size_t len = strlen(src);\n if (len &gt;= n) {\n len = n - 1;\n }\n\n memcpy(dest, src, len);\n dest[len] = '\\0';\n}\n</code></pre>\n<hr />\n<p>Although not part of this review, I did peek at the makefile in the git repository. If we used the standard <code>CC</code> and <code>CFLAGS</code> variables, we would be able to use the built-in rules to compile, and merely specify the dependencies in the makefile. And users could override those variables in the expected way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:29:20.107", "Id": "497340", "Score": "0", "body": "Thank you for this in-depth response! I have a couple of questions. For `if (error)` I am struggling to understand why this is equivalent `if (error == NULL)`. I thought that `NULL` pointers always evaluate to false. So that the only acceptable alternative is `if (!error)`. Am I missing something? Second, when you say this library is not extensible due to the cb_log enum codes, could you expand on that briefly? I believe what you're implying is that if I add more codes to the enum in the future, this makes it hard for users to go back and edit their programs which depend on the specific codes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:03:30.213", "Id": "497355", "Score": "0", "body": "You're right - I meant `!error` there. Sorry for that mistake. What I meant by \"not extensible\" is different to how you understood me: users aren't able to add their own return codes - they only get what's provided by the library. I hope that makes sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T00:07:40.130", "Id": "497374", "Score": "0", "body": "That comment on extensibility makes sense, thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T14:33:09.227", "Id": "252410", "ParentId": "252398", "Score": "2" } }, { "body": "<ul>\n<li><p><strong>DRY</strong>. Initialization can be streamlined:</p>\n<pre><code> if (cb_calloc == NULL) {\n cb_calloc = calloc;\n }\n error = cb_calloc(ERROR_BYTES(n), 1);\n ....\n</code></pre>\n<p>Along the same line, testing for <code>cb_log == NULL</code> is unnecessary. <code>error-&gt;cb_log</code> becomes equal to <code>cb_log</code> no matter what.</p>\n</li>\n<li><p><strong>Avoid special cases</strong>. Provide a fallback instead. Consider</p>\n<pre><code> if (cb_log == NULL) {\n cb_log = default_cb_log;\n }\n error-&gt;cb_log = cb_log;\n</code></pre>\n<p>This way the not-so-pretty <code>LOG_ERROR_IF_FOUND</code> goes away. The default callback could be as simple as <code>static void default_callback(....) {}</code>.</p>\n</li>\n<li><p><strong>Avoid <code>goto</code></strong>. <code>SafeCopy</code> doesn't need it. Consider</p>\n<pre><code> if (s == 0) {\n s = &quot;&quot;;\n }\n end = strlen(s);\n size_t to_copy = min(end, limit - 1);\n strncpy(dest, s, limit);\n</code></pre>\n</li>\n<li><p><strong>Use correct data structure</strong>. Since you <code>prevent stack overflow by removing the oldest node</code>, a circular buffer seems more reasonable (no need to <code>memmove</code> anything) than a stack.</p>\n</li>\n<li><p>It would be nice to see some usage examples.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T00:09:25.040", "Id": "497375", "Score": "0", "body": "This is a wonderful answer, thank you. Your comment on using a ring buffer instead led me to google around and I've realized that Open GL actually has a somewhat similar mechanism to queue up errors, which the user can then dequeue and take action. The default callback is awesome! I wish I could have accepted your answer too, as both were equally valuable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:17:00.437", "Id": "252433", "ParentId": "252398", "Score": "2" } } ]
{ "AcceptedAnswerId": "252410", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T02:10:58.170", "Id": "252398", "Score": "6", "Tags": [ "c", "error-handling", "stack", "logging", "callback" ], "Title": "Error Code Stack Trace and Propagation Library in C" }
252398
<p>This project is in chapter 5 introduced me to a whole new world of dictionary data structure. To put it briefly, I want to know whether the choice I took between lists, tuples, and dictionaries could've been justifiable calls or not. I'm also not that confident about where putting many return statements correctly and many other beginners' common mistakes that I probably have overlooked.</p> <p>The project's description and the code are shown below.</p> <pre><code>import pprint, copy # Argument from Automate BS with Python chessgood = { '1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} # Argument when key/value is ok but its representative value/key pair raises an error chessbad = {'9z': 'bemperor', '10a': 'wking', '3a': 'bprince'} # Argument when a piece is more than allowed (e.g., wpawn more than 8) chessbad2 = {'4a': 'wpawn', '4b': 'wpawn', '4c': 'wpawn','4d': 'wpawn', '4e': 'wpawn', '4f': 'wpawn', '4g': 'wpawn', '4h': 'wpawn', '5a': 'wpawn', '5i': 'wpawn'} def isvcb(dctnry): ''' In this chapter, we used the dictionary value {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} to represent a chess board. Write a function named isValidChessBoard() that takes a dictionary argument and returns True or False depending on if the board is valid. A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board. ''' ver = ('a','b','c','d','e','f','g','h') hor = (8, 7, 6, 5, 4, 3, 2, 1) bd = dict() for i in hor: for j in ver: bd.setdefault(str(i) + j, str(i) + j) bdcopy = copy.copy(bd) #pprint.pprint(bdu) side = ('b','w') piece = {'pawn': 8, 'knight': 2, 'bishop': 2, 'rook': 2, 'queen' : 1, 'king': 1} pcs = dict() for m in side: for n in piece: pcs.setdefault(m + n, piece[n]) temp = dict() for k,v in dctnry.items(): temp.setdefault(v, 0) temp[v] += 1 if k in bd and v in pcs and temp[v] &lt;= pcs[v]: bd[k] = v print('Input OK: ', k) elif k not in bd: bd = bdcopy print('Key(s) not in definition: ', k ) elif v not in pcs: bd = bdcopy print('Value(s) not in definition: ', v ) elif temp[v] &gt; pcs[v]: bd = bdcopy print('Value of this piece exceeds threshold: ', v ) pprint.pprint(bd) if bd == bdcopy: return False else: return True print('chessgood: ', isvcb(chessgood), '\n') print('chessbad: ', isvcb(chessbad), ' \n') print('chessbad2: ', isvcb(chessbad2), '\n') </code></pre> <p>I believe I covered all of the possible errors by error-checking using different arguments when calling the function, where:</p> <ol> <li>Key of the passed arguments are not on the matrix 1a - 8h</li> <li>Value of the passed arguments are outside from a combination of (white &amp; black) and ('pawn', 'knight', 'bishop', 'rook', 'queen', 'king')</li> <li>All of the value from passed arguments don't exceed the threshold of each piece so that each piece will have aat most 16 pieces (e.g. wpawn is notmore than 8, bking is no more than 1)</li> <li>Show all the invalid input on the command line</li> </ol> <p>If there are any other subtle restrictions that I haven't overseen. Please let me know :)</p> <p>The results are shown below:</p> <pre><code>Input OK: 1h Input OK: 6c Input OK: 2g Input OK: 5h Input OK: 3e {'1a': '1a', '1b': '1b', '1c': '1c', '1d': '1d', '1e': '1e', '1f': '1f', '1g': '1g', '1h': 'bking', '2a': '2a', '2b': '2b', '2c': '2c', '2d': '2d', '2e': '2e', '2f': '2f', '2g': 'bbishop', '2h': '2h', '3a': '3a', '3b': '3b', '3c': '3c', '3d': '3d', '3e': 'wking', '3f': '3f', '3g': '3g', '3h': '3h', '4a': '4a', '4b': '4b', '4c': '4c', '4d': '4d', '4e': '4e', '4f': '4f', '4g': '4g', '4h': '4h', '5a': '5a', '5b': '5b', '5c': '5c', '5d': '5d', '5e': '5e', '5f': '5f', '5g': '5g', '5h': 'bqueen', '6a': '6a', '6b': '6b', '6c': 'wqueen', '6d': '6d', '6e': '6e', '6f': '6f', '6g': '6g', '6h': '6h', '7a': '7a', '7b': '7b', '7c': '7c', '7d': '7d', '7e': '7e', '7f': '7f', '7g': '7g', '7h': '7h', '8a': '8a', '8b': '8b', '8c': '8c', '8d': '8d', '8e': '8e', '8f': '8f', '8g': '8g', '8h': '8h'} chessgood: True Key(s) not in definition: 9z Key(s) not in definition: 10a Value(s) not in definition: bprince {'1a': '1a', '1b': '1b', '1c': '1c', '1d': '1d', '1e': '1e', '1f': '1f', '1g': '1g', '1h': '1h', '2a': '2a', '2b': '2b', '2c': '2c', '2d': '2d', '2e': '2e', '2f': '2f', '2g': '2g', '2h': '2h', '3a': '3a', '3b': '3b', '3c': '3c', '3d': '3d', '3e': '3e', '3f': '3f', '3g': '3g', '3h': '3h', '4a': '4a', '4b': '4b', '4c': '4c', '4d': '4d', '4e': '4e', '4f': '4f', '4g': '4g', '4h': '4h', '5a': '5a', '5b': '5b', '5c': '5c', '5d': '5d', '5e': '5e', '5f': '5f', '5g': '5g', '5h': '5h', '6a': '6a', '6b': '6b', '6c': '6c', '6d': '6d', '6e': '6e', '6f': '6f', '6g': '6g', '6h': '6h', '7a': '7a', '7b': '7b', '7c': '7c', '7d': '7d', '7e': '7e', '7f': '7f', '7g': '7g', '7h': '7h', '8a': '8a', '8b': '8b', '8c': '8c', '8d': '8d', '8e': '8e', '8f': '8f', '8g': '8g', '8h': '8h'} chessbad: False Input OK: 4a Input OK: 4b Input OK: 4c Input OK: 4d Input OK: 4e Input OK: 4f Input OK: 4g Input OK: 4h Value of this piece exceeds threshold: wpawn Key(s) not in definition: 5i {'1a': '1a', '1b': '1b', '1c': '1c', '1d': '1d', '1e': '1e', '1f': '1f', '1g': '1g', '1h': '1h', '2a': '2a', '2b': '2b', '2c': '2c', '2d': '2d', '2e': '2e', '2f': '2f', '2g': '2g', '2h': '2h', '3a': '3a', '3b': '3b', '3c': '3c', '3d': '3d', '3e': '3e', '3f': '3f', '3g': '3g', '3h': '3h', '4a': '4a', '4b': '4b', '4c': '4c', '4d': '4d', '4e': '4e', '4f': '4f', '4g': '4g', '4h': '4h', '5a': '5a', '5b': '5b', '5c': '5c', '5d': '5d', '5e': '5e', '5f': '5f', '5g': '5g', '5h': '5h', '6a': '6a', '6b': '6b', '6c': '6c', '6d': '6d', '6e': '6e', '6f': '6f', '6g': '6g', '6h': '6h', '7a': '7a', '7b': '7b', '7c': '7c', '7d': '7d', '7e': '7e', '7f': '7f', '7g': '7g', '7h': '7h', '8a': '8a', '8b': '8b', '8c': '8c', '8d': '8d', '8e': '8e', '8f': '8f', '8g': '8g', '8h': '8h'} chessbad2: False </code></pre> <p>I believe my code is way longer than necessary but I also believe that the result being true should be kept as the first priority. So as someone who has no background in coding. Any input is greatly appreciated. Thank you :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T06:24:19.873", "Id": "497278", "Score": "3", "body": "Just a quick note: it's possible to have up to 9 queens per side, due to pawn promotion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:34:31.383", "Id": "497347", "Score": "0", "body": "Just wanted to throw in that this is an excellent amount of effort & thoughtfulness for someone without a background in coding. Keep with it :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:30:34.870", "Id": "497360", "Score": "1", "body": "I'll try to improve it further. Thank you for the input!" } ]
[ { "body": "<h2>Naming</h2>\n<p>Let's focus on a single variable, <code>dctnry</code> - a somewhat nasty abbreviation of dictionary. We of course shouldn't name it <code>dict</code> because that's a built-in, but neither name actually says what this is - a chess board that should simply be called <code>board</code>. You <em>can</em> indicate that it's a dictionary, but there's a better way to do it - type hints, like <code>board: Dict[str, str]</code>.</p>\n<p><code>isvcb</code> is likewise impenetrable and should instead be <code>is_valid</code> or <code>is_valid_board</code>. Also, the textbook made a poor decision in suggesting <code>isValidChessBoard</code> - the Python standard is lower_snake_case, i.e. <code>is_valid_chess_board</code>.</p>\n<p>Don't use the name <code>bd</code> - call it perhaps <code>full_board</code>, and <code>pieces</code> instead of <code>pcs</code>. <code>temp</code> needs a better name as well.</p>\n<p>Later down, your <code>piece</code> dictionary should be <code>pieces</code> because it's a collection.</p>\n<h2>Range</h2>\n<p><code>hor</code> should not use a manual tuple, and should instead use <code>range(8, 0, -1)</code>.</p>\n<h2>Boolean expressions</h2>\n<pre><code>if bd == bdcopy:\n return False\nelse:\n return True\n</code></pre>\n<p>should simply be</p>\n<pre><code>return bd != bdcopy\n</code></pre>\n<h2>Dictionary literals</h2>\n<pre><code>pcs = dict()\nfor m in side:\n for n in piece:\n pcs.setdefault(m + n, piece[n])\n</code></pre>\n<p>can simply be</p>\n<pre><code>pieces = {\n m + n: piece_value\n for m in side \n for n, piece_value in piece.items()\n}\n</code></pre>\n<p>I don't see a need for <code>setdefault</code>, since I think the indexes being visited will be unique.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:26:58.093", "Id": "497357", "Score": "0", "body": "Thank you for the input! I wrote `def is_valid_board(board_step: Dict[str, str]):` and it gave me a `NameError: name 'Dict' is not defined` even after importing module typing. This error seems to be solved right after I wrote `def is_valid_board(board_step: typing.Dict[str, str]):`. I changed parameters from `dctnry` to `board_step`, as you suggested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:27:34.797", "Id": "497358", "Score": "0", "body": "Are you using Python 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:29:20.617", "Id": "497359", "Score": "0", "body": "Yup! Python 3.8 (64-bit)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:42:27.937", "Id": "252416", "ParentId": "252400", "Score": "5" } }, { "body": "<p>This is my attempt. Comments are welcome! I couldn't figure out, how to check if the keys in the board are unique (because two pieces cannot be placed in the same field which would also give an invalid board). I tried with the len() and set() functions, but that didn't help.</p>\n<pre><code>board = {'1b': 'bking',\n '6a': 'wqueen',\n '3f': 'brook',\n '4h': 'bknight',\n '3e': 'wking',\n '6d': 'wbishop',\n '2g': 'wbishop',\n '5c': 'bpawn',\n '8g': 'bpawn',\n '7b': 'bpawn'}\n\nfieldInt = ['1', '2', '3', '4', '5', '6', '7', '8']\nfieldChar = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\npieceColor = ['b', 'w']\npieces = ['king', 'queen', 'knight', 'rook', 'bishop', 'pawn']\n\ndef boardInventory(board):\n # Makes an inventory of the board to be evaluated.\n count = {}\n for value in board.values():\n count.setdefault(value, 0)\n count[value] += 1\n return count\n\ndef boardCounter(board):\n # Checks if amounts of pieces are valid.\ncount = boardInventory(board)\nitem_total = 0\nfor value in count.values():\n item_total += value\n\n if count['bking'] == 1 and \\\n count['wking'] == 1 and \\\n 0 &lt;= count.get('bpawn', 0) &lt;= 8 and \\\n 0 &lt;= count.get('wpawn', 0) &lt;= 8 and \\\n count.get('brook', 0) &lt;= 2 and \\\n count.get('wrook', 0) &lt;= 2 and \\\n count.get('bknight', 0) &lt;= 2 and \\\n count.get('wknight', 0) &lt;= 2 and \\\n count.get('bbishop', 0) &lt;= 2 and \\\n count.get('wbishop', 0) &lt;= 2 and \\\n item_total &lt;= 32:\n return True\n else:\n return False\n\ndef fieldValidator(board):\n # Checks if the board contains valid fields.\n keyOK = 0\n for key in board.keys():\n if key[0] in fieldInt and key[1] in fieldChar:\n keyOK += 1\n else:\n return False\n if keyOK == len(board):\n return True\n\ndef pieceValidator(board):\n # Checks if the pieces are spelled correctly.\n valueOK = 0\n for value in board.values():\n if value[0] in pieceColor and value[1:] in pieces:\n valueOK += 1\n else:\n return False\n if valueOK == len(board):\n return True\n\ndef boardValidator(board):\n # Checks if the board is valid, depending on the tests above. Prints \n # an error message when board is invalid.\n if fieldValidator(board) and pieceValidator(board) and \\ \n boardCounter(board):\n print('This is a valid chess board!')\n elif fieldValidator(board) == False:\n print('Invalid chess board! There is a wrong field in your \\ \n board!')\n elif pieceValidator(board) == False:\n print('Invalid chess board! There is a wrong piece in your \\\n board!')\n elif boardCounter(board) == False:\n print('Invalid chess board! There is something wrong with the \\ \n allowed amount of pieces!')\n\nboardValidator(board)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T11:33:23.923", "Id": "253171", "ParentId": "252400", "Score": "0" } } ]
{ "AcceptedAnswerId": "252416", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T05:47:18.803", "Id": "252400", "Score": "5", "Tags": [ "python", "beginner", "algorithm", "python-3.x", "validation" ], "Title": "Chess Dictionary Validator from Automatic Boring Stuff with Python" }
252400
<p>I had a task where I had to build a stamp duty calculator, which calculates the tax or stamp duty first-time buyers(<code>ftb</code>) returning buyers (<code>rtb</code>), and second-home buyers (<code>shb</code>) had to pay when purchasing the home.</p> <p>These were the tax bands, although I think some of the percentages may be slightly wrong.</p> <pre><code>First Time Buyers 0 to £300,000 - 0% £300,001 to £925,000 - 5% £925001 to £1,500,000 - 10% £1,500,000 and above - 12% Returning Buyers 0 to £125,000 - 0% £125,001 to £250,000 - 2% £250,001 to £925,000 - 5% £925,001 to £1,500,000 - 10% £1,500,000 and above - 12% Second Home Buyers 0 to £125,000 - 3% £125,001 to £250,000 - 5% £250,001 to £925,000 - 8% £925,001 to £1,500,000 - 13% £1,500,000 and above - 15% </code></pre> <p>Here is my solution, I look forward to the feedback.</p> <pre><code>const stampDutyCalc = (price) =&gt; { let stampdutyObject = { ftb: 0, rtb: 0, shb: 0, }; firstTimeBuyerCalc(price, stampdutyObject); returningBuyerCalc(price, stampdutyObject); secondHomeBuyerCalc(price, stampdutyObject); return stampdutyObject; }; function firstTimeBuyerCalc(price, stampdutyObject) { if (price &lt;= 300000) { stampdutyObject.ftb += 0; } else if (price &gt; 300000 &amp;&amp; price &lt;= 925000) { stampdutyObject.ftb += price * 0.05; } else if (price &gt; 925000 &amp;&amp; price &lt;= 1500000) { stampdutyObject.ftb += (price - 925000) * 0.1 + (925000 - 300000) * 0.05; } else { stampdutyObject.ftb += (price - 1500000) * 0.12 + (1500000 - 925000) * 0.1 + (925000 - 300000) * 0.05; } } function returningBuyerCalc(price, stampdutyObject) { if (price &lt;= 125000) { stampdutyObject.rtb += 0; } else if (price &gt; 125000 &amp;&amp; price &lt;= 250000) { stampdutyObject.rtb += price * 0.02; } else if (price &gt; 250000 &amp;&amp; price &lt;= 925000) { stampdutyObject.rtb += (price - 250000) * 0.05 + (250000 - 125000) * 0.02; } else if (price &gt; 925000 &amp;&amp; price &lt;= 1500000) { stampdutyObject.rtb += (price - 925000) * 0.1 + (925000 - 250000) * 0.05 + (250000 - 125000) * 0.02; } else { stampdutyObject.rtb += (price - 1500000) * 0.12 + (1500000 - 925000) * 0.1 + (925000 - 250000) * 0.05 + (250000 - 125000) * 0.02; } } function secondHomeBuyerCalc(price, stampdutyObject) { if (price &lt;= 125000) { stampdutyObject.shb = price * 0.03; } else if (price &gt; 125000 &amp;&amp; price &lt;= 250000) { stampdutyObject.shb += (price - 125000) * 0.05 + 125000 * 0.03; } else if (price &gt; 250000 &amp;&amp; price &lt;= 925000) { stampdutyObject.shb += (price - 250000) * 0.08 + (250000 - 125000) * 0.05 + 125000 * 0.03; } else if (price &gt; 925000 &amp;&amp; price &lt;= 1500000) { stampdutyObject.shb += (price - 925000) * 0.13 + (925000 - 250000) * 0.08 + (250000 - 125000) * 0.05 + 125000 * 0.03; } else { stampdutyObject.shb += (price - 1500000) * 0.15 + (1500000 - 925000) * 0.13 + (925000 - 250000) * 0.08 + (250000 - 125000) * 0.0 + 125000 * 0.03; } } function returningBuyerCalc(price, stampdutyObject) { if (price &lt;= 125000) { stampdutyObject.rtb += 0; } else if (price &gt; 125000 &amp;&amp; price &lt;= 250000) { stampdutyObject.rtb += price * 0.02; } else if (price &gt; 250000 &amp;&amp; price &lt;= 925000) { stampdutyObject.rtb += (price - 250000) * 0.05 + (250000 - 125000) * 0.02; } else if (price &gt; 925000 &amp;&amp; price &lt;= 1500000) { stampdutyObject.rtb += (price - 925000) * 0.1 + (925000 - 250000) * 0.05 + (250000 - 125000) * 0.02; } else { stampdutyObject.rtb += (price - 1500000) * 0.12 + (1500000 - 925000) * 0.1 + (925000 - 250000) * 0.05 + (250000 - 125000) * 0.02; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:12:03.367", "Id": "497343", "Score": "0", "body": "Your bands are way wrong at present, because there’s no stamp duty (if you’re not buying a second home) up to £500,000, until 31 March next year. There’s also a 15% rate for some residential property purchases by corporations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T11:01:59.033", "Id": "497395", "Score": "0", "body": "@MikeScott the bands were given as part of the task. Which why I mentioned that I think some of the percentages are incorrect" } ]
[ { "body": "<p>In <code>stampDutyCalc</code> function you can avoid object mutation and just call your functions instead of putting the value <code>0</code>.</p>\n<p>In calculation functions there is no need to use <code>+=</code> because only one <code>if</code> branch is evaluated. You can just use <code>return</code> instead, e.g. <code>return price * 0.05</code>.</p>\n<p>Specific business rules of calculation are mixed with programming logic that makes them hard to understand and change.</p>\n<p>I suggest using a data-driven design and represent business rules as data.\nHere is the code for my solution:</p>\n<pre><code>const between = (from, to) =&gt; function (price) {\n return from &lt;= price &amp;&amp; price &lt;= to;\n}\n\nconst moreThan = (x) =&gt; function (price) {\n return price &gt;= x;\n}\n\nconst rules = {\n ftb: [\n [between(0, 300000), (price) =&gt; 0],\n [between(300001, 925000), (price) =&gt; price * 0.05],\n [between(925001, 1500000), (price) =&gt; (price - 925000) * 0.1 + (925000 - 300000) * 0.05],\n [moreThan(925001, 1500001), (price) =&gt; (price - 1500000) * 0.12 + (1500000 - 925000) * 0.1 + (925000 - 300000) * 0.05],\n ],\n rtb: [\n [between(0, 125000), (price) =&gt; 0],\n [between(125000, 250000), (price) =&gt; price * 0.02],\n [between(250001, 925000), (price) =&gt; (price - 250000) * 0.05 + (250000 - 125000) * 0.02],\n [between(925000, 1500000), (price) =&gt; (price - 925000) * 0.1 + (925000 - 250000) * 0.05 + (250000 - 125000) * 0.02],\n [moreThan(1500001), (price) =&gt; (price - 1500000) * 0.12 + (1500000 - 925000) * 0.1 + (925000 - 250000) * 0.05 + (250000 - 125000) * 0.02],\n ],\n shb: [\n // rules for shb\n ],\n}\n\nconst getCalc = (rules) =&gt; function calc(price) {\n const calcFor = (type) =&gt; {\n const rule = rules[type];\n const noMatch = [true, () =&gt; 0];\n const [, calc] = rule.find(([match]) =&gt; match(price)) || noMatch;\n return { [type]: calc(price) };\n }\n\n return Object.keys(rules).reduce((result, type) =&gt; ({ ...result, ...calcFor(type) }), {});\n}\n\nconst calc = getCalc(rules);\n\nconsole.log(calc(1500001));\nconsole.log(calc(250001));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:43:24.650", "Id": "497310", "Score": "0", "body": "Really like this solution, could please explain what the following line is doing exactly `return Object.keys(rules).reduce((result, type) => ({ ...result, ...calcFor(type) }), {});`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:52:53.410", "Id": "497312", "Score": "0", "body": "It takes keys of rules (`ftb`, `rtb`, `shb`) and for each rule makes an object, e.g. `{ ftb: 123 }`, by calculating result for each type of buyer. Then it merges them one by one in the resulting object using `reduce`, e.g. `{ ftb: 123, rtb: 222, shb: 11 }`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:22:54.333", "Id": "252408", "ParentId": "252403", "Score": "2" } }, { "body": "<h2>Hard coded</h2>\n<p>You have created yourself a future problem by hard coding the data in your code. When dealing with taxes (or any business logic) there is one certainty, and that is <em>change</em>.</p>\n<p>With the data embedded in the code, making even a minor change will take some effort and will be very prone to error.</p>\n<p>You need to create a data structure that allows you to make changes quickly and easily. You should only have to change a value once, in one location, not many times in many places.</p>\n<h2>Defining the data</h2>\n<p>The data is defined as an object, with only the data needed, if information can be deduced there is no need to include it.</p>\n<p>The example has a helper function <code>rate</code> to reduce the overhead of typing in <code>{level:10000, tax: 0.1}</code> over and over</p>\n<pre><code>const rate = (level, tax) =&gt; ({level, tax});\nconst brackets = {\n firstTime: [\n rate(300000, 0),\n rate(925000, 0.05),\n rate(1500000, 0.1),\n rate(Infinity, 0.12),\n ],\n returning: [\n rate(125000, 0),\n rate(250000, 0.02),\n rate(925000, 0.05),\n rate(1500000, 0.1),\n rate(Infinity, 0.12), \n ],\n second: [\n rate(125000, 0.03),\n rate(250000, 0.05),\n rate(925000, 0.08),\n rate(1500000, 0.13),\n rate(Infinity, 0.15), \n ],\n};\n</code></pre>\n<h3>Applying logic</h3>\n<p>With the data organised, the code can then just deal with the logic of how the duty is calculated:</p>\n<pre><code>function calculateDuty(price, bracket) {\n var duty = 0;\n var prevLevel = 0\n for (const rate of bracket) {\n if (rate.level &lt;= price) {\n duty += (rate.level - prevLevel) * rate.tax;\n prevLevel = rate.level;\n } else {\n return duty + (price - prevLevel) * rate.tax;\n }\n }\n}\n</code></pre>\n<p>And now you can get the duty for any bracket: <code>calculateDuty(price, brackets.firstTime)</code></p>\n<h2>Rewrite</h2>\n<p>Thus the whole thing becomes:</p>\n<pre><code>const rate = (level, tax) =&gt; ({level, tax});\nconst brackets = {\n firstTime: [rate(300000, 0), rate(925000, 0.05), rate(1500000, 0.1), rate(Infinity, 0.12)],\n returning: [rate(125000, 0), rate(250000, 0.02), rate(925000, 0.05), rate(1500000, 0.1), rate(Infinity, 0.12)],\n second: [rate(125000, 0.03), rate(250000, 0.05), rate(925000, 0.08), rate(1500000, 0.13), rate(Infinity, 0.15)],\n};\nconst stampDutyCalc = price =&gt; ({ \n ftb: calculateDuty(price, brackets.firstTime),\n rtb: calculateDuty(price, brackets.returning), \n shb: calculateDuty(price, brackets.second), \n});\n\nfunction calculateDuty(price, bracket) {\n var duty = 0, prevLevel = 0\n for (const rate of bracket) {\n if (rate.level &lt;= price) {\n duty += (rate.level - prevLevel) * rate.tax;\n prevLevel = rate.level;\n } else {\n return duty + (price - prevLevel) * rate.tax;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:43:28.983", "Id": "497349", "Score": "1", "body": "Well done! Separating data from policy is one of my favorite tricks for making things better. Nicely explained, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T10:01:20.613", "Id": "497508", "Score": "0", "body": "@Blindman67 I really liked this solution. Very clean. I think I knew what I was doing wasn't best but was struggling to figure out how to split out the common functionality." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:32:06.650", "Id": "252414", "ParentId": "252403", "Score": "7" } } ]
{ "AcceptedAnswerId": "252414", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T09:35:01.383", "Id": "252403", "Score": "3", "Tags": [ "javascript", "interview-questions", "calculator" ], "Title": "Build a stamp duty calculator for various types of buyers" }
252403
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a>. As <a href="https://codereview.stackexchange.com/a/252375/231235">G. Sliepen's answer</a> <code>Don't try to deduce the predicate's parameter type</code> and <a href="https://codereview.stackexchange.com/a/252154/231235">Quuxplusone's answer</a> mentioned <code>I think the user of this API should have to tell the function explicitly how many &quot;levels&quot; to unwrap downward</code>, I am trying to implement another version <code>recursive_count_if</code> template function with unwrap level parameter. Thanks to Quuxplusone for providing the hint of using <code>if constexpr</code> to achieve this.</p> <pre><code>template&lt;std::size_t unwrap_level, class T1, class T2&gt; requires (is_iterable&lt;T1&gt;) auto recursive_count_if(const T1&amp; input, const T2 predicate) { if constexpr (unwrap_level &gt; 1) { return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp; element) { return recursive_count_if&lt;unwrap_level - 1&gt;(element, predicate); }); } else { return std::count_if(input.begin(), input.end(), predicate); } } </code></pre> <p>The used <code>is_iterable</code> concept is as below. I keep it in order to get nicer error messages if user accidentily try to apply this <code>recursive_count_if()</code> on something that can not be iterated over.</p> <pre><code>template&lt;typename T&gt; concept is_iterable = requires(T x) { *std::begin(x); std::end(x); }; </code></pre> <p>Some test cases are as below. With this version <code>recursive_count_if</code>, you can always use <code>auto</code> keyword in the input lambda parameter.</p> <pre><code>// std::vector&lt;std::vector&lt;int&gt;&gt; case std::vector&lt;int&gt; test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector&lt;decltype(test_vector)&gt; test_vector2; test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); // use a lambda expression to count elements divisible by 3. int num_items1 = recursive_count_if&lt;2&gt;(test_vector2, [](auto&amp; i) {return i % 3 == 0; }); std::cout &lt;&lt; &quot;#number divisible by three: &quot; &lt;&lt; num_items1 &lt;&lt; '\n'; // std::deque&lt;std::deque&lt;int&gt;&gt; case std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(2); test_deque.push_back(3); std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); // use a lambda expression to count elements divisible by 3. int num_items2 = recursive_count_if&lt;2&gt;(test_deque2, [](auto&amp; i) {return i % 3 == 0; }); std::cout &lt;&lt; &quot;#number divisible by three: &quot; &lt;&lt; num_items2 &lt;&lt; '\n'; std::vector&lt;std::vector&lt;std::string&gt;&gt; v = { {&quot;hello&quot;}, {&quot;world&quot;} }; auto size5 = [](auto&amp; s) { return s.size() == 5; }; auto n = recursive_count_if&lt;2&gt;(v, size5); std::cout &lt;&lt; &quot;n:&quot; &lt;&lt; n &lt;&lt; std::endl; // std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; case std::vector&lt;decltype(test_vector2)&gt; test_vector3; test_vector3.push_back(test_vector2); test_vector3.push_back(test_vector2); test_vector3.push_back(test_vector2); std::cout &lt;&lt; recursive_count_if&lt;1&gt;(test_vector3, [test_vector2](auto&amp; element) { return std::equal(element.begin(), element.end(), test_vector2.begin()); }) &lt;&lt; std::endl; </code></pre> <p><a href="https://godbolt.org/z/7P6b7W" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>This version of <code>recursive_count_if</code> template function is with unwrap level parameter, you can always use <code>auto</code> keyword in the input lambda parameter.</p> </li> <li><p>Why a new review is being asked for?</p> <p>With the given unwrap level parameter, the behavior of <code>recursive_count_if</code> template function may be more clear and be easy to use. If there is any further possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<ol>\n<li><p>I would expect the predicate not have a generic <code>T</code>-type. <code>F</code> for function, or <code>Pred</code> for predicate would be normal.</p>\n</li>\n<li><p>I suggest not copying the predicate internally. Standard algorithms generally only copy it until they finally use it, and then only use that one single copy.</p>\n<p>To that end, wrap it in a <code>std::reference_wrapper</code> if it isn't already wrapped, and don't mark it <code>const</code> so mutable predicates still work.</p>\n<pre><code>if constexpr (std::is_same_v&lt;F, std::unwrap_reference_t&lt;F&gt;&gt;)\n return recursive_count_if&lt;unwrap_level&gt;(input, std::ref(predicate));\n</code></pre>\n</li>\n<li><p>Retaining your previous behavior for <code>unwrap_level == 0</code> would be interesting.</p>\n<p>Otherwise, make it an error.</p>\n</li>\n<li><p>You could give <code>unwrap_level</code> a useful default. Like <code>1</code> or maybe <code>0</code> if you implement the previous suggestion.</p>\n</li>\n<li><p>Not sure how far you want to go, but it would be nice if the function was more SFINAE-friendly if the template-arguments don't work together.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T12:49:13.463", "Id": "252406", "ParentId": "252404", "Score": "1" } } ]
{ "AcceptedAnswerId": "252406", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T11:19:26.923", "Id": "252404", "Score": "2", "Tags": [ "c++", "recursion", "c++20" ], "Title": "A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++" }
252404
<p>I have the following problem and I am new in Java:</p> <p>I have an initial capital of 10 000. I invest this initial capital of 10 000 in the bank for a interest rate per month of 0.04/12. My net income is 3000 per month and my expenses per month is 2000. I invest also my monthysavings = net income - expenses = 3000 - 2000 = 1000 in the bank for the interest rate of 0.04/12.</p> <p>I would like to calculate the amount of savings I will have in 300 months.</p> <p>I did the following code:</p> <blockquote> <pre><code>public class RetCalcJava { public double futureCapital( double interestRate , int nbOfMonths , int netIncome , int currentExpenses , double initialCapital) { double monthlySavings = netIncome - currentExpenses; double iniVal=0; double finalVal =0; double intermediate = 0; for (int i=0; i&lt; nbOfMonths; i++){ System.out.println(&quot;Boucle&quot; + i); if (i ==0) { iniVal = initialCapital * (1 + interestRate) + monthlySavings; intermediate = iniVal; System.out.println(&quot;intival&quot; + iniVal); } else { finalVal = intermediate * (1 + interestRate) + monthlySavings; intermediate = finalVal; System.out.println(&quot;finalVal&quot; + finalVal); } } return finalVal; </code></pre> <p>} }</p> </blockquote> <p>The main class is :</p> <pre><code>public class RetCalcMain { public static void main(String[] args) { RetCalcJava retcal = new RetCalcJava(); retcal.futureCapital(0.04/12, 300, 3000,2000,10000); } } </code></pre> <p>This code works. What do you think about my code? Is it optimized? What should I change?</p>
[]
[ { "body": "<p>Welcome to Code Review. Few suggestions:</p>\n<ul>\n<li><strong>Formatting</strong>: the code should be formatted to make it easier to read. Many IDEs support auto-formatting, or you can use an <a href=\"https://www.tutorialspoint.com/online_java_formatter.htm\" rel=\"nofollow noreferrer\">online formatter</a>.</li>\n<li><strong>Naming</strong>: the class name <code>RetCalcJava</code> shouldn't include Java as suffix, the extension .java already tells what type of file is. It's also hard to understand what a class called <code>RetCalc</code> does, consider a more meaningful name. I am not sure what <code>Boucle</code> means.</li>\n<li><strong>Typo and spacing</strong>: <code>iniVal</code>, <code>println(&quot;intival&quot; + iniVal)</code>. There are some typos and the result of the print is &quot;intival1000&quot;, it needs a space.</li>\n<li><strong>Static method</strong>: The method <code>futureCapital</code> does not need to use instance variables, so it can be <code>static</code>. By making it <code>static</code> we don't need to instantiate the class.</li>\n<li><strong>Formatting the output</strong>: the capital can be formatted as <code>541,267.20</code> instead of <code>541267.1989622512</code> using <code>System.out.printf</code> and <code>%,.2f</code>.</li>\n<li><strong>Accumulation</strong>:\n<pre><code>iniVal = initialCapital * (1 + interestRate) + monthlySavings;\nintermediate = iniVal;\nSystem.out.println(&quot;intival&quot; + iniVal);\nfor (int i = 1; i &lt; nbOfMonths; i++) {\n //...\n finalVal = intermediate * (1 + interestRate) + monthlySavings;\n intermediate = finalVal;\n // ...\n}\nreturn finalVal;\n</code></pre>\nThe temporary variables <code>intermediate</code> and <code>initVal</code> are not necessary, see the code below.</li>\n</ul>\n<h2>Revised code</h2>\n<pre><code>public class RetCalc {\n public static double futureCapital(double interestRate, int months, int netIncome, int currentExpenses,\n double initialCapital) {\n double monthlySavings = netIncome - currentExpenses;\n double capital = initialCapital;\n for (int i = 0; i &lt; months; i++) {\n capital = capital * (1 + interestRate) + monthlySavings;\n if (i == 0) {\n System.out.printf(&quot;Initial value: %,.2f%n&quot;, capital);\n } else {\n System.out.printf(&quot;Month: %d Capital: %,.2f%n&quot;, i + 1, capital);\n }\n }\n return capital;\n }\n\n public static void main(String[] args) {\n double futureCapital = RetCalc.futureCapital(0.04 / 12, 300, 3000, 2000, 10000);\n System.out.printf(&quot;Future capital: %,.2f%n&quot;, futureCapital);\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>Initial value: 11,033.33\nMonth: 2 Capital: 12,070.11\n...\nMonth: 300 Capital: 541,267.20\nFuture capital: 541,267.20\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T13:13:55.920", "Id": "252407", "ParentId": "252405", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>public double futureCapital(\n double interestRate\n , int nbOfMonths\n , int netIncome\n , int currentExpenses\n , double initialCapital) {\n</code></pre>\n</blockquote>\n<p>The idea behind the comma-first list separation is that it allows elements to be added to the end of the list without having to modify the current last item in the list. This produces fewer changes in source control.</p>\n<p>The problem is that, as you have implemented it, you have thrown away that advantage. Because you have put <code>) {</code> on the last line. So you are going to have to keep moving it if you were to add a new entry. If so, you might as well write in one of the more readable styles:</p>\n<pre><code>public double futureCapital(\n double interestRate,\n int nbOfMonths,\n int netIncome,\n int currentExpenses,\n double initialCapital) {\n</code></pre>\n<p>or (more common in Java)</p>\n<pre><code>public double futureCapital(double interestRate, int nbOfMonths, int netIncome,\n int currentExpenses, double initialCapital) {\n</code></pre>\n<p>You also name a variable <code>nbOfMonths</code>. What's an nb? I'm guessing it's an abbreviation of number. Contrast that with <code>monthCount</code>, which has the same number of characters but no abbreviations.</p>\n<p>I also prefer to name scalars (like <code>int</code> or <code>double</code>) with singular names and use plural names for arrays and collections. I.e. things over which I can iterate.</p>\n<p>In general, methods should have verb names. They do things. In this case, I would start with <code>calculate</code>. You could name the class something like <code>FutureCapital</code> or <code>ProjectedCapital</code>.</p>\n<p>Given that your class has no object properties, I would make the method static.</p>\n<p>Consider separating your output from your calculations. E.g. return an array of <code>balances</code> and then display those. That will make your program easier to modify in the future.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T07:12:20.853", "Id": "497380", "Score": "0", "body": "+1 for the comma-first list separation, I didn't know that. And for mentioning to use verbs in method names, I completely missed that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T03:37:10.087", "Id": "252439", "ParentId": "252405", "Score": "3" } }, { "body": "<pre class=\"lang-java prettyprint-override\"><code> , int nbOfMonths\n</code></pre>\n<p>Don't shorten names just because you can. It does make the code harder to read, understand and maintain in the long run. Even when variable names become longer, make them as descriptive as possible.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>double monthlySavings = netIncome - currentExpenses;\n</code></pre>\n<p>Don't use <code>double</code> or even <code>float</code> for money, it will come back to bite you. As it is with floating point numbers, they <em>will</em> have rounding errors which might or might not be a problem, but in my experience they always become one.</p>\n<p>Either use <code>int</code>/<code>long</code> with the smallest unit your currency has (like Cents), or use a <code>BigDecimal</code> with an appropriate <code>MathContext</code> to get accurate results.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i=0; i&lt; nbOfMonths; i++){\n</code></pre>\n<p>I'm a persistent opponent of single-letter variable names. In my opinion, you're only allowed to use single-letter variable names if you're dealing with dimensions. In this case, <code>i</code> could be <code>counter</code>, <code>monthCounter</code>.</p>\n<hr />\n<p>You could get much more descriptive, but also a lot more verbose and complex, by using a builder-pattern like mechanic. Assume the following class:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ReturnCalculator {\n protected BigDecimal capital;\n protected BigDecimal monthlyExpenses;\n protected BigDecimal monthlyNetIncome;\n protected int numberOfMonths;\n protected BigDecimal yearlyInterestRate;\n</code></pre>\n<p>Now, with that in place we are adding setters for every variable, like this one:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public ReturnCalculator setCapital(BigDecimal capital) {\n this.capital = capital;\n \n return this;\n}\n</code></pre>\n<p>Last but for sure not least, we add checks to the <code>calculateFutureCapital</code> method, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public BigDecimal calculateFutureCapital() {\n if (capital == null) {\n throw new IllegalArgumentException(&quot;\\&quot;capital\\&quot; is not set.&quot;);\n }\n // Repeat for every field.\n \n // return calculated value.\n}\n</code></pre>\n<p>We could also assume &quot;sane&quot; defaults for the values, but that is rather not transparent in this case, so we'd do better with the checks which throw if something is wrong.</p>\n<p>So, with that in place, we can use the class like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>BigDecimal futureCapital = new FutureCapitalCalculator()\n .setCapital(BigDecimal.valueOf(&quot;10000&quot;, MathContext.Decimal_128))\n .setMonthlyExpenses(BigDecimal.valueOf(&quot;2000&quot;, MathContext.Decimal_128))\n .setMonthlyNetIncome(BigDecimal.valueOf(&quot;3000&quot;, MathContext.Decimal_128))\n .setNumberOfMonths(300)\n .setYearlyInterestRate(BigDecimal.valueOf(&quot;0.04&quot;, MathContext.Decimal_128))\n .calculateFutureCapital();\n</code></pre>\n<p>It is quite a mouth full, though. We could further better this by moving the creation of the <code>BigDecimal</code> into the setters by adding overloads that just accept <code>String</code>s. That would shorten the usage to:</p>\n<pre class=\"lang-java prettyprint-override\"><code>BigDecimal futureCapital = new FutureCapitalCalculator()\n .setCapital(&quot;10000&quot;)\n .setMonthlyExpenses(&quot;2000&quot;)\n .setMonthlyNetIncome(&quot;3000&quot;)\n .setNumberOfMonths(300)\n .setYearlyInterestRate(&quot;0.04&quot;)\n .calculateFutureCapital();\n</code></pre>\n<p>Much better. As a further thought, we might rename our setters to <code>withCapital</code> or <code>useCapitalOf</code>, to have an even cleaner usage API.</p>\n<pre class=\"lang-java prettyprint-override\"><code>BigDecimal futureCapital = new FutureCapitalCalculator()\n .withCapital(&quot;10000&quot;)\n .withMonthlyExpenses(&quot;2000&quot;)\n .withMonthlyNetIncome(&quot;3000&quot;)\n .withNumberOfMonths(300)\n .withYearlyInterestRate(&quot;0.04&quot;)\n .calculateFutureCapital();\n</code></pre>\n<p>The upside is also, that we can reuse a single instance of the class (which, of course, limits the thread-safety).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T12:00:00.113", "Id": "252481", "ParentId": "252405", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T12:12:05.057", "Id": "252405", "Score": "6", "Tags": [ "java" ], "Title": "Calculate the amount of savings I will have in n months" }
252405
<p>I made a very simple OS in Assembly. But my code is too long. I want to make my code shorter.</p> <p>Here is my code:</p> <pre><code> BITS 16 start: mov ax, 07C0h add ax, 288 mov ss, ax mov sp, 4096 mov ax, 07C0h mov ds, ax mov si, text_string call print_string jmp $ text_string db 'OS', 0 print_string: mov ah, 0Eh .repeat: lodsb cmp al, 0 je .done int 10h jmp .repeat .done: ret times 510-($-$$) db 0 dw 0xAA55 </code></pre> <p>Makefile:</p> <pre><code>DIR=build build $(shell mkdir -p $(DIR)) $(shell nasm -f bin OS1.asm -o build/OS1.flp) $(shell mkisofs -no-emul-boot -o build/OS1.iso -b OS1.flp build) </code></pre> <p>Can I make this code shorter? Is it possible to do? If it is, how?</p> <p>(This code may be updated in my <a href="https://github.com/ArianKG" rel="nofollow noreferrer">GitHub</a> account.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:37:31.447", "Id": "497333", "Score": "2", "body": "If you scale this OS up, then the way to make it shorter is to compile (most of) it in C, with assembly sections only as needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T19:57:16.907", "Id": "497455", "Score": "0", "body": "What do you mean with \"OS\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T07:24:10.257", "Id": "497498", "Score": "0", "body": "@superbrain Operating System" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T13:06:15.233", "Id": "497520", "Score": "1", "body": "Ok, that's what I thought. But an operating system in 20 lines of assembly rather seems way too *short* to be true rather than too long. I wrote a lot of assembly for years but that was over 20 years ago, so now I can't understand what your code does but I'm curious. What does it do?" } ]
[ { "body": "<p>You initialize <code>ax</code> with the same value twice, so you could save one command by rearranging the code bit:</p>\n<pre><code>mov ax, 07C0h\nmov ds, ax\nadd ax, 288\nmov ss, ax\n</code></pre>\n<p>You could save 5 commands if you give up on <code>print_string</code> being a callable function and just inline its code. You won't need to initialize the stack registers and you won't need the <code>call</code> and <code>ret</code> commands.</p>\n<p>Of course, this will preclude reuse of the function if you decide to expand your OS.</p>\n<p>There is also a middle ground, though I think it is a bit hacky:<br />\nKeep a &quot;function like&quot; structure for <code>print_string</code> but avoid using <code>call</code> and <code>ret</code>.</p>\n<p>Instead, save the return address to <code>dx</code> and use <code>jmp</code>.</p>\n<p>I haven't actually tested this, but it does compile and should work:</p>\n<pre><code> BITS 16\n\nstart:\n mov ax, 07C0h\n mov ds, ax\n\n mov si, text_string\n mov dx, return_target\n jmp print_string\nreturn_target:\n jmp $\n\n\n text_string db 'OS', 0\n\n\nprint_string:\n mov ah, 0Eh\n\n.repeat:\n lodsb\n cmp al, 0\n jne .do_print\n jmp dx\n\n.do_print:\n int 10h\n jmp .repeat\n</code></pre>\n<p>You will be essentially creating your own non-standard calling convention, but you will save 3 commands as a result and still keep your printing code reusable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T17:20:41.277", "Id": "497439", "Score": "0", "body": "I see the benefit from not spending instructions on **creating a stack** but why avoid **using a stack**? The `int 10h` already uses the stack and so can `call print_string`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T17:47:59.300", "Id": "497441", "Score": "0", "body": "@SepRoland the OP asked how to make the code shorter, I interpreted it as \"do the same thing with less instructions\". I don't claim this code to be good in any way. Regarding the `int` instruction, I may have forgoten some some details as it has been a long time since I touched on assembly... So to be clear: will my proposed code result in some undefined behavior when `int 10h` is called due to stack registers being in unknown state?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T18:01:16.563", "Id": "497443", "Score": "1", "body": "The BIOS will have set up a stack, but it might not be very large (the original IBM PC used 256 bytes at the end of the Interrupt Vector Table). So while you can get away without setting up your own stack here, you cannot rely on using it for very long." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:52:14.613", "Id": "252425", "ParentId": "252411", "Score": "2" } }, { "body": "<blockquote>\n<p>Can I make this code shorter?</p>\n</blockquote>\n<ul>\n<li>If you use the <code>ORG 7C00h</code> directive, then loading the segment registers will be shorter code.</li>\n<li>You can choose to setup the stack below the bootloader and shave off that addition. Even if you leave the stack where you placed it before (above the bootloader), with <code>SS=0</code> the change would become <code>mov sp, 9E00h</code>.</li>\n<li>You avoid having to load the string address (and the need to come up with suitable label names) if you store the actual string directly beneath the <code>call</code> instruction and have the <em>print_string</em> routine jump back to behind the terminating zero.<br />\nThis technique becomes more interesting if more than 1 string is to be printed.</li>\n</ul>\n<pre><code> BITS 16\n ORG 7C00h\n\nstart:\n cld &lt;--- Not shorter but better!\n xor ax, ax\n mov ds, ax\n mov ss, ax\n mov sp, 7C00h\n\n call print_string\n db 'OS', 0\n jmp $\n\nprint_string:\n pop si\n mov bx, 7 &lt;--- Not shorter but better!\n mov ah, 0Eh\n.repeat:\n cs lodsb ; Need CS override since SI is an offset in code segment!\n cmp al, 0\n je .done\n int 10h\n jmp .repeat\n.done:\n jmp si\n\n\n times 510-($-$$) db 0\n dw 0xAA55\n</code></pre>\n<p>The <code>CS</code> segment override on the <code>LODSB</code> instruction is required unless you know that <code>DS</code> == <code>CS</code>. Many bootloaders will have a far jump at the top to ensure that this is the case. e.g. <code>jmp 0000h:7C05h</code> as the very first instruction. This will set <code>CS=0</code>.</p>\n<h2>Not shorter but better</h2>\n<ul>\n<li>Adding a <code>CLD</code> instruction makes sure that the <code>LODSB</code> instruction will function correctly.</li>\n<li>Passing all the required parameters to the BIOS.Teletype function is best. <code>BH</code> is DisplayPage and <code>BL</code> is GraphicsColor. If you <strong>know</strong> that the screen is in a text video mode then you can drop the setting for <code>BL</code> and just write <code>mov bh, 0</code> to select the video page.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T17:14:10.750", "Id": "252461", "ParentId": "252411", "Score": "5" } } ]
{ "AcceptedAnswerId": "252461", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:04:38.963", "Id": "252411", "Score": "3", "Tags": [ "assembly", "x86" ], "Title": "Very simple OS in Assembly" }
252411
<p><strong>Story</strong></p> <p>I'm trying to become more familiar with template metaprogramming and practice more of it. I need to use modular arithmetic to solve certain problems and so I decided to write a general purpose template for it.</p> <p><strong>Code</strong></p> <p><em>Include files</em></p> <pre class="lang-cpp prettyprint-override"><code>// Individual #include &lt;iostream&gt; #include &lt;chrono&gt; #include &lt;vector&gt; #include &lt;exception&gt; #include &lt;string&gt; #include &lt;type_traits&gt; // PCH #include &quot;bits/stdc++.h&quot; </code></pre> <p><em>Modular Arithmetic Template</em></p> <pre class="lang-cpp prettyprint-override"><code>namespace competitive_programming::utility::sfinae { template &lt;typename T, typename = void&gt; struct is_istream_streamable : std::false_type { }; template &lt;typename T&gt; struct is_istream_streamable &lt;T, std::void_t &lt;decltype(std::cin &gt;&gt; std::declval &lt;T&amp;&gt; ())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool is_istream_streamable_v = is_istream_streamable &lt;T&gt;::value; template &lt;typename T, typename = void&gt; struct is_ostream_streamable : std::false_type { }; template &lt;typename T&gt; struct is_ostream_streamable &lt;T, std::void_t &lt;decltype(std::cerr &lt;&lt; std::declval &lt;T&gt; ())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool is_ostream_streamable_v = is_ostream_streamable &lt;T&gt;::value; template &lt;typename T, typename = void&gt; struct has_begin_iterator : std::false_type { }; template &lt;typename T&gt; struct has_begin_iterator &lt;T, std::void_t &lt;decltype(std::declval &lt;T&gt; ().begin())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool has_begin_iterator_v = has_begin_iterator &lt;T&gt;::value; template &lt;typename T, typename = void&gt; struct has_end_iterator : std::false_type { }; template &lt;typename T&gt; struct has_end_iterator &lt;T, std::void_t &lt;decltype(std::declval &lt;T&gt; ().end())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool has_end_iterator_v = has_end_iterator &lt;T&gt;::value; template &lt;typename T&gt; constexpr bool has_begin_end_iterator_v = has_begin_iterator_v &lt;T&gt; &amp;&amp; has_end_iterator_v &lt;T&gt;; template &lt;typename T, typename = void&gt; struct is_mathematical : std::false_type { }; template &lt;typename T&gt; struct is_mathematical &lt;T, std::void_t &lt;decltype( std::declval &lt;T&amp;&gt; () += std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () -= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () *= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () /= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () %= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () &amp;= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () |= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () ^= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () &lt;&lt;= std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt; () &gt;&gt;= std::declval &lt;T&gt; (), ++std::declval &lt;T&amp;&gt; (), --std::declval &lt;T&amp;&gt; (), std::declval &lt;T&amp;&gt; ()++, std::declval &lt;T&amp;&gt; ()--, std::declval &lt;T&gt; () + std::declval &lt;T&gt; (), std::declval &lt;T&gt; () - std::declval &lt;T&gt; (), std::declval &lt;T&gt; () * std::declval &lt;T&gt; (), std::declval &lt;T&gt; () / std::declval &lt;T&gt; (), std::declval &lt;T&gt; () % std::declval &lt;T&gt; (), std::declval &lt;T&gt; () &amp; std::declval &lt;T&gt; (), std::declval &lt;T&gt; () | std::declval &lt;T&gt; (), std::declval &lt;T&gt; () ^ std::declval &lt;T&gt; (), std::declval &lt;T&gt; () &lt;&lt; std::declval &lt;T&gt; (), std::declval &lt;T&gt; () &gt;&gt; std::declval &lt;T&gt; (), +std::declval &lt;T&gt; (), -std::declval &lt;T&gt; () )&gt;&gt; : std::true_type { }; template &lt;typename T, typename = void&gt; struct is_comparable : std::false_type { }; template &lt;typename T&gt; struct is_comparable &lt;T, std::void_t &lt;decltype( std::declval &lt;T&gt; () == std::declval &lt;T&gt; (), std::declval &lt;T&gt; () != std::declval &lt;T&gt; (), std::declval &lt;T&gt; () &lt;= std::declval &lt;T&gt; (), std::declval &lt;T&gt; () &gt;= std::declval &lt;T&gt; (), std::declval &lt;T&gt; () &lt; std::declval &lt;T&gt; (), std::declval &lt;T&gt; () &gt; std::declval &lt;T&gt; (), std::declval &lt;T&amp;&gt;() = std::declval &lt;T&gt; (), static_cast &lt;bool&gt; (std::declval &lt;T&gt; ()) )&gt;&gt; : std::true_type { }; template &lt;typename T&gt; struct is_integer_type { static constexpr bool value = is_mathematical &lt;T&gt;::value &amp;&amp; is_comparable &lt;T&gt;::value; }; template &lt;typename T&gt; constexpr bool is_integer_type_v = is_integer_type &lt;T&gt;::value; template &lt;typename T, typename = void&gt; struct common_bigger_integer { using type = T; }; template &lt;typename T&gt; struct common_bigger_integer &lt;T, std::enable_if_t &lt;std::is_integral_v &lt;T&gt;, void&gt;&gt; { using type = int64_t; }; template &lt;typename T&gt; using common_bigger_integer_t = typename common_bigger_integer &lt;T&gt;::type; } namespace competitive_programming::utility::math { namespace sfinae = competitive_programming::utility::sfinae; template &lt;typename Integer, Integer Modulo&gt; class modular { static_assert(sfinae::is_integer_type_v &lt;Integer&gt;, &quot;class modular requires integer type&quot;); static_assert(Modulo &gt; 0, &quot;Modulo must be positive&quot;); using Common_Integer = std::decay_t &lt;sfinae::common_bigger_integer_t &lt;Integer&gt;&gt;; private: Common_Integer integer = Common_Integer(); const Common_Integer modulo = Modulo; void normalize () { if (integer &gt;= mod() || -integer &lt;= mod()) integer %= mod(); if (integer &lt; 0) integer += mod(); } public: modular (const modular&amp; m) : integer (m.integer) { } template &lt;typename T = Common_Integer&gt; modular (const T&amp; integer = T()) : integer (static_cast &lt;Common_Integer&gt; (integer)) { normalize(); } modular&amp; operator = (const modular&amp; m) { integer = m.integer; return *this; } constexpr Common_Integer mod () const { return modulo; } constexpr Common_Integer operator () () const { return integer; } constexpr Common_Integer&amp; operator () () { return integer; } template &lt;typename T&gt; constexpr explicit operator T() const { return static_cast &lt;T&gt; (integer); } modular&amp; operator += (const modular&amp; other) { integer += other.integer; if (integer &gt;= mod()) integer -= mod(); return *this; } modular&amp; operator -= (const modular&amp; other) { integer -= other.integer; if (integer &lt; 0) integer += mod(); return *this; } modular&amp; operator *= (const modular&amp; other) { return integer *= other.integer, normalize(), *this; } modular&amp; operator /= (const modular&amp; other) { return *this *= other.extended_euclidean_inverse().integer, normalize(), *this; } modular&amp; operator ++ () { return *this += 1; } modular&amp; operator -- () { return *this -= 1; } modular operator ++ (int) const { modular result (*this); *this += 1; return result; } modular operator -- (int) const { modular result (*this); *this -= 1; return result; } modular operator + () const { return *this; } modular operator - () const { return modular(-integer); } friend modular operator + (modular self, const modular&amp; other) { return self += other; } friend modular operator - (modular self, const modular&amp; other) { return self -= other; } friend modular operator * (modular self, const modular&amp; other) { return self *= other; } friend modular operator / (modular self, const modular&amp; other) { return self /= other; } friend bool operator == (const modular&amp; left, const modular&amp; right) { return left() == right(); } friend bool operator != (const modular&amp; left, const modular&amp; right) { return left() != right(); } friend bool operator &lt;= (const modular&amp; left, const modular&amp; right) { return left() &lt;= right(); } friend bool operator &gt;= (const modular&amp; left, const modular&amp; right) { return left() &gt;= right(); } friend bool operator &lt; (const modular&amp; left, const modular&amp; right) { return left() &lt; right(); } friend bool operator &gt; (const modular&amp; left, const modular&amp; right) { return left() &gt; right(); } // Assumes modulo is prime // Fermat's Little Theorem (https://www.wikiwand.com/en/Fermat%27s_little_theorem) modular fermat_inverse () const { modular inverse = *this; inverse.binary_exponentiate(mod() - 2); #ifdef LOST_IN_SPACE if (*this * inverse != 1) throw std::runtime_error(&quot;integer and modulo are not co-prime&quot;); #endif return inverse; } // Assumes modulo is prime // Euler's Totient Theorem (https://www.wikiwand.com/en/Euler%27s_theorem) modular euler_inverse () const { auto m = mod(); long double totient = mod(); for (Common_Integer i = 2; i * i &lt;= m; ++i) if (m % i == 0) { while (m % i == 0) m /= i; totient *= 1.0L - 1.0L / i; } if (m &gt; 1) totient *= 1.0L - 1.0L / m; Common_Integer phi = totient; modular inverse = *this; inverse.binary_exponentiate(phi - 1); #ifdef LOST_IN_SPACE if (*this * inverse != 1) throw std::runtime_error(&quot;integer and modulo are not co-prime&quot;); #endif return inverse; } // Assumes modulo is co-prime with integer // Extended Euclidean Algorithm (https://www.wikiwand.com/en/Extended_Euclidean_algorithm) modular extended_euclidean_inverse () const { Common_Integer u = 0, v = 1; Common_Integer a = integer, m = mod(); while (a != 0) { Common_Integer t = m / a; m -= t * a; u -= t * v; std::swap(a, m); std::swap(u, v); } #ifdef LOST_IN_SPACE if (m != 1) throw std::runtime_error(&quot;integer and modulo are not co-prime&quot;); #endif return u; } // Assumes power is non-negative modular binary_exponentiate (Common_Integer power) { auto base = *this; *this = 1; while (power &gt; 0) { if (power &amp; 1) *this *= base; base *= base; power &gt;&gt;= 1; } return *this; } modular abs () const { return *this; } std::string to_string () const { return std::to_string((*this)()); } friend auto operator &lt;&lt; (std::ostream&amp; stream, const modular&amp; m) -&gt; std::enable_if_t &lt;sfinae::is_ostream_streamable_v &lt;Common_Integer&gt;, std::ostream&amp;&gt; { return stream &lt;&lt; m(); } friend auto operator &gt;&gt; (std::istream&amp; stream, modular&amp; m) -&gt; std::enable_if_t &lt;sfinae::is_istream_streamable_v &lt;Common_Integer&gt;, std::istream&amp;&gt; { return stream &gt;&gt; m(), m.normalize(), stream; } }; } template &lt;typename Integer, Integer Modulo = Integer()&gt; using modular = competitive_programming::utility::math::modular &lt;Integer, Modulo&gt;; using mod998244353 = modular &lt;int, 998244353&gt;; using mod1000000007 = modular &lt;int, 1000000007&gt;; </code></pre> <p><em>Usage</em></p> <pre class="lang-cpp prettyprint-override"><code>// Example 1 int main () { int64_t n; std::cin &gt;&gt; n; mod998244353 y = 2; y.binary_exponentiate(n); std::vector &lt;mod998244353&gt; fibo (n + 1); fibo [0] = 0; fibo [1] = 1; for (int i = 2; i &lt;= n; ++i) fibo [i] = fibo [i - 1] + fibo [i - 2]; std::cout &lt;&lt; fibo [n] * y.fermat_inverse() &lt;&lt; '\n'; return 0; } // Example 2 namespace competitive_programming::utility { using namespace std::chrono; class timer { private: time_point &lt;steady_clock&gt; begin, end; public: #ifdef LOST_IN_SPACE timer () : begin (steady_clock::now()), end () { } ~timer () { end = steady_clock::now(); std::cerr &lt;&lt; &quot;\n\nDuration: &quot; &lt;&lt; duration &lt;double&gt; (end - begin).count() &lt;&lt; &quot;s\n&quot;; } #else timer () : begin (), end () { } ~timer () { } #endif }; } int main () { mod1000000007 m; std::cin &gt;&gt; m; // 42 { competitive_programming::utility::timer t; std::cout &lt;&lt; m.extended_euclidean_inverse() &lt;&lt; '\n'; // 23809524 // Duration: 0.0000641200s } { competitive_programming::utility::timer t; std::cout &lt;&lt; m.fermat_inverse() &lt;&lt; '\n'; // 23809524 // Duration: 0.0000082080s } { competitive_programming::utility::timer t; std::cout &lt;&lt; m.euler_inverse() &lt;&lt; '\n'; // 23809524 // Duration: 0.0007950880s } return 0; } </code></pre> <p><strong>Question and Others</strong></p> <p>Comments about code-style and other related guides are welcome as usual. I'd like to know if my code is optimally written in the math related part. It would be great to have comments on <code>is_mathematical</code> and <code>is_comparable</code> parts of the code. With C++20 I believe, the way I've done it simplifies a great deal in implementation verbosity with concepts. What other features may be added to the code (that I may have missed)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:15:52.290", "Id": "497321", "Score": "0", "body": "Note that I do know that I could simply use `std::is_integral` to check if a type is mathematical or not. Although, I'd like the template to be more general purpose and allow user-defined integer types too. Say that someone has a arbitrary multiprecision big integer implementation and would like to use a really big modulo (bigger than `std::numeric_limits <int>::max()`, my code would allow you to do that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:24:26.770", "Id": "497329", "Score": "0", "body": "Does the code make sense when `Integer` is a signed type?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:37:26.383", "Id": "497348", "Score": "0", "body": "@TobySpeight I'm not sure I understand your question completely. But, why not? Modular arithmetic doesn't distinguish between the signed-ness of types afaik." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T19:09:51.457", "Id": "497351", "Score": "0", "body": "@TobySpeight I think I understood your question. Did you mean to ask if the code supports modulo for negative numbers? As in: Is the modulo of -1 over mod 10 equal to 9? Yes, it fully supports negative inputs too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:07:55.020", "Id": "497356", "Score": "0", "body": "And it's happy with negative modulus, too? I'm a bit rusty on the definition of that; am I right in saying that `-1 % -10` == `9 % -10`? If so, all's well and good. (That was a real question, not a criticism)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-25T15:49:11.333", "Id": "497907", "Score": "0", "body": "Slight gripe with the title - this is just ordinary template programming, not _meta_programming." } ]
[ { "body": "<h1>Don't <code>#include &lt;bits/stdc++.h&gt;</code></h1>\n<p>You should <a href=\"https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.\">avoid <code>#include &lt;bits/stdc++.h&gt;</code></a>, as there are several issues with it, the most important being that it is just not standard C++. You are putting your classes in a <code>namespace competitive_programming</code>, so I can see where you are coming from, but please unlearn this.</p>\n<h1>Only write concepts that make sense</h1>\n<p>I see you wrote both <code>has_begin_iterator</code> and <code>has_end_iterator</code>. Does it ever make sense for a class to only have one of those, and do you ever expect to write a template where you only need one of them? I think it makes more sense to just have a single <code>is_container</code> or <code>is_iterable</code> concept.</p>\n<h1><code>is_mathematical</code> and <code>is_comparable</code> check too much</h1>\n<p>I think everyone would consider a <code>float</code> to be a &quot;mathematical&quot; type. However, since you check for the binary operators, this template will fail for <code>float</code>, <code>double</code>, <code>std::complex</code> and possibly other types as well. In fact, it also fails for <code>modular</code>! You might want to reduce the amount of operations you check for.</p>\n<p>Note that the word &quot;mathematical&quot; also doesn't imply a certain set of operations. In Mathematics, you can make types you can do math with, but which for example only support addition and subtraction operations. The closest that comes to what you mean is the word <a href=\"https://en.wikipedia.org/wiki/Arithmetic#Arithmetic_operations\" rel=\"nofollow noreferrer\">&quot;arithmetic&quot;</a>. So I suggest that you rename it <code>is_arithmetic</code>, and do not check for the logical and bitwise operations.</p>\n<p>There is a similar issue with <code>is_comparable</code>. You check for the presence of all comparison operators, but there are types where only some operators are valid. Consider for example <code>std::complex&lt;float&gt;</code>: it's an arithmetic type, you can certainly check whether two complex numbers are the same or not, however you cannot check if one number compares greater than another number; that operation does not make sense for complex numbers. So here it might make sense to split it up into an <code>is_equality_comparable</code> and perhaps something like <code>is_less_greater_than_comparable</code>. Note that most algorithms only require a single comparison operator to be available, either <code>==</code> or <code>&lt;</code>, and you don't want to unnecessarily restrict the types you accept.</p>\n<h1>Unnecesarily <code>template</code>d constructor</h1>\n<p>Why is the constructor for <code>class modular</code> a <code>template</code>? That way it will accept all types, even ones that don't make sense. Just make a non-templated constructor that accepts a <code>Common_Integer</code> parameter:</p>\n<pre><code>template &lt;typename Integer, Integer Modulo&gt;\nclass modular {\n ...\n modular (const Common_Integer &amp;integer = {})\n : integer (integer)\n { normalize(); }\n ...\n};\n</code></pre>\n<h1>Don't make a <code>templated</code> cast operator</h1>\n<p>You should not make a cast operator that is a template that accepts all possible types. You already have <code>operator()</code> for getting the <code>integer</code> out, C++ will implicitly handle valid casts for you. I would rather write:</p>\n<pre><code>mod998244353 y = 2;\nfloat x = y();\n</code></pre>\n<p>Than:</p>\n<pre><code>mod998244353 y = 2;\nauto x = static_cast&lt;float&gt;(y);\n</code></pre>\n<h1>Don't write unnecessary member function</h1>\n<p>Why does <code>class modular</code> have a member function <code>abs()</code> that just returns itself? Since the <code>integer</code> is always normalized, you know the value will never be negative, so this seems redundant. If you include an <code>abs()</code> function this suggests to a user that the class supports negative values, when it doesn't.</p>\n<h1>Be consistent using member functions from other member functions</h1>\n<p>I see this code:</p>\n<pre><code>void normalize () {\n if (integer &gt;= mod() || -integer &lt;= mod())\n ...\n}\n</code></pre>\n<p>Why directly access the member variable <code>integer</code>, but use the member function <code>mod</code> to get the value of the member variable <code>modulo</code>? This makes it look like something special is going on, when it's not. Here I would just directly access both member variabels:</p>\n<pre><code> if (integer &gt;= modulo || -integer &lt;= modulo)\n ...\n</code></pre>\n<p>There is one place where you did use a member fuction to get the value of <code>integer</code>:</p>\n<pre><code>std::string to_string () const { return std::to_string((*this)()); }\n</code></pre>\n<p>That looks very weird, again I would suggest directly accessing the member variable:</p>\n<pre><code>std::string to_string () const { return std::to_string(integer); }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T21:47:32.887", "Id": "497363", "Score": "0", "body": "Thank you for the comments and answer! I'll see to it that I make the recommended changes and remember the style guides in future as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T20:15:05.560", "Id": "252430", "ParentId": "252412", "Score": "3" } } ]
{ "AcceptedAnswerId": "252430", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:11:28.520", "Id": "252412", "Score": "4", "Tags": [ "c++", "c++17", "template-meta-programming" ], "Title": "Template Metaprogramming and Modular Arithmetic" }
252412
<p>I have some vanilla JavaScript for a website menu which works perfectly (thanks mainly to <a href="https://stackoverflow.com/users/1552587/titus">Titus</a> on Stack Overflow), opening and closing a sub-menu (toggling <code>&lt;ul class=&quot;hidden&quot;&gt;</code> ) if the UL's sibling button is clicked or closing the sub-menu if another button on the same level as the sibling is clicked, adjusting other CSS classes for the <code>&lt;li&gt;</code> elements appropriately. The code is specific to each level of the menu and I have repeated the code for several more menu levels, just changing each occurrence of '1' to '2' and then to '3' and so on (potentially there could be up to 10 levels; I already have 5 for testing purposes). Is there a way to use less lines of code whilst maintaining each level's independence?</p> <p>Here is the code for two levels:</p> <pre><code>const buttons1 = Array.from(document.querySelectorAll(&quot;.btn-level-1&quot;)); buttons1.forEach((button1) =&gt; { button1.addEventListener('click', () =&gt; { buttons1.filter(b1 =&gt; b1 != button1).forEach(b1 =&gt; { b1.classList.remove('opened'); b1.classList.add('not-open'); b1.nextElementSibling.classList.add('hidden') }); button1.nextElementSibling.classList.toggle('hidden'); button1.classList.toggle('not-open'); button1.classList.toggle('opened'); }); }); const buttons2 = Array.from(document.querySelectorAll(&quot;.btn-level-2&quot;)); buttons2.forEach((button2) =&gt; { button2.addEventListener('click', () =&gt; { buttons2.filter(b2 =&gt; b2 != button2).forEach(b2 =&gt; { b2.classList.remove('opened'); b2.classList.add('not-open'); b2.nextElementSibling.classList.add('hidden') }); button2.nextElementSibling.classList.toggle('hidden'); button2.classList.toggle('not-open'); button2.classList.toggle('opened'); }); }); </code></pre> <p>Demo HTML, CSS and another bit of JS in a snippet:</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>document.addEventListener('DOMContentLoaded', () =&gt; { document.getElementById("mainbody").addEventListener("click", closeMenu); function closeMenu(event) { if(event.target.type != "button") { let level1 = document.getElementsByClassName("level-1"); let level2 = document.getElementsByClassName("level-2"); let btnlevel1 = document.getElementsByClassName("btn-level-1"); let btnlevel2 = document.getElementsByClassName("btn-level-2"); for (let i = 0; i &lt; level1.length; i++) { level1[i].classList.add("hidden"); } for (let i = 0; i &lt; level2.length; i++) { level2[i].classList.add("hidden"); } for (let i = 0; i &lt; btnlevel1.length; i++){ btnlevel1[i].classList.remove("opened");} for (let i = 0; i &lt; btnlevel2.length; i++) { btnlevel2[i].classList.remove("opened");} } } const buttons1 = Array.from(document.querySelectorAll(".btn-level-1")); buttons1.forEach((button1) =&gt; { button1.addEventListener('click', () =&gt; { buttons1.filter(b1 =&gt; b1 != button1).forEach(b1 =&gt; { b1.classList.remove('opened'); b1.nextElementSibling.classList.add('hidden') }); button1.nextElementSibling.classList.toggle('hidden'); button1.classList.toggle('opened'); }); }); const buttons2 = Array.from(document.querySelectorAll(".btn-level-2")); buttons2.forEach((button2) =&gt; { button2.addEventListener('click', () =&gt; { buttons2.filter(b2 =&gt; b2 != button2).forEach(b2 =&gt; { b2.classList.remove('opened'); b2.nextElementSibling.classList.add('hidden') }); button2.nextElementSibling.classList.toggle('hidden'); button2.classList.toggle('opened'); }); }); })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.sticky-main-menu { position: fixed; top: 6rem; left: 0; right: 0; z-index: 9999; } .stickymenuwrapper { background-color: #fff; transition-duration: 0s; padding: 1rem; margin: 0 auto; z-index: 995; border: 1px solid gray; } .hmenu .hidden { display: none; } .hmenu ul { list-style: none; margin-bottom: 0; white-space: nowrap; padding: 0; } .hmenu ul.navbar { background-color: #f7a1d6; padding: 0 1rem; justify-content: center; display: flex; /* required for VSC */ /* text-align: center;*/ } .hmenu .navbar { line-height: 1.5; } .hmenu li ul { position: absolute; top: 100%; background-color: pink; padding: 0 12px 12px; } .hmenu ul[class^="level"] { background-color: white; position: relative; top: 100%; left: 0; padding: 1rem 0 1rem 1rem; margin-top: 0.5rem; } .hmenu ul.level-1 { position: absolute; /* ? */ top: 100%; left: 0; margin-top: 0; padding: 1rem; box-shadow: 0 2px 5px #acaaaa; } .hmenu ul.level-2, .hmenu ul.level-4{ background-color: #dedede; } .hmenu ul li:last-child { padding-bottom: 0; } .hmenu li.active&gt;a { text-decoration: underline; } .hmenu a.separator:hover { text-decoration: none; } .hmenu ul[class^="level"] li { margin-right: 1rem; } .hmenu li { position: relative; /* display: flex;*/ margin: 0; padding: 0 0 0.5rem; line-height: 1.5rem; } .hmenu li a { color: #0d6efd; } .hmenu li.parent { margin-right: 0; /* was 2rem */ } .hmenu .navbar&gt;li { padding: 0; margin: 0 0.5rem; display: flex; } .hmenu .navbar&gt;li.parent { margin-right: 2rem; } .hmenu .navbar&gt;li.divider.parent { margin-right: 0; } .hmenu .navbar&gt;li&gt;a { padding: 0.5rem 0 0.5rem 0.5rem; margin: 0 0 0 0; } .hmenu .navbar&gt;li:first-child&gt;a { padding: 0.5rem 0.5rem 0.5rem 0; margin-left: 0; } .hmenu li.heading&gt;a, .hmenu li.divider&gt;a, .hmenu li.separator&gt;a { text-decoration: none; padding-right: 2rem; } .hmenu li.separator-line { position: relative; height: 1rem; display: inline-block; width: 100%; } .hmenu li.separator-line span { display: none; } .hmenu li.separator-line:after { position: absolute; height: 0; top: 60%; width: 100%; border-top: 1px solid#8c8a8a; border-bottom: 1px solid lightgray; margin: 0 0; content: ""; } .hmenu ul.navbar&gt;li a { padding-top: 0.5rem; position: relative; } [type="button"] { -webkit-appearance: button; } [type="button"]:not(:disabled) { cursor: pointer; } .hmenu button, .hmenu button:focus { display: inline-flex; position: absolute; background: transparent; border: none; color: #0d6efd; height: 1.5rem; outline: none; padding: 0 0 0 .5rem; margin: 0; right: 0; width: 40px; top: 6px; } .hmenu li.linked button { position: relative; top: 0; } .hmenu li.linked button.btn-level-1 { top: 10px; } .hmenu .navbar &gt; li.linked.top-level { margin-right: 0.5rem; } .hmenu button.btn-level-1 { right: 0; position: absolute; top: 0; } .hmenu li button[class^="btn-level"]:after, .hmenu li a[class^="btn-level"]:after{ display: inline-flex; width: 0; height: 0; margin: 0 .5em; content: ""; transition: all .3s ease-out; position: absolute; top: 12px; cursor: pointer; right: -2rem; border-top: 10px solid; border-right: 8px solid transparent; border-left: 8px solid transparent; } .hmenu li.separator&gt;button[class^="btn-level"]:after, .hmenu li.separator&gt;a[class^="btn-level"]:after{ right: 0; } .hmenu li button[class^="btn-level"].opened, .hmenu li a[class^="btn-level"].opened{ color: red; } .hmenu li button[class^="btn-level"].opened:after, .hmenu li a[class^="btn-level"].opened:after{ border-top: none; border-bottom: 10px solid; border-right: 8px solid transparent; border-left: 8px solid transparent; top: 12px; right: 0; } .hmenu li.linked &gt; a[class^="btn-level"].opened:after { right: -2rem; } .hmenu li button.linked { display: inline-flex; position: relative; } .hmenu li button.linked:after{ top: 10px; right: 0; } .hmenu li button[class^="btn-level"].linked.opened:after{ top: 6px; right: 0; } .hmenu li button.btn-level-1.linked { display: inline-flex; position: relative; } .hmenu li button.btn-level-1:after, .hmenu li button.btn-level-1.opened:after { top: 30%; right: 0; } .hmenu li a.btn-level-1:after, .hmenu li a.btn-level-1.opened:after{ top: 40%; right: -2rem; } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-gb"dir="ltr"&gt; &lt;head&gt; &lt;meta charSet="utf-8" /&gt; &lt;link rel="stylesheet" href="menu-demo-2a.css"&gt; &lt;script type="text/javascript"&gt; // Fix for Firefox autofocus CSS bug // See: http://stackoverflow.com/questions/18943276/html-5-autofocus-messes-up-css-loading/18945951#18945951 &lt;/script&gt; &lt;/head&gt; &lt;body id="mainbody" class="outer"&gt; &lt;div id="stickymenuwrapper" class="stickymenuwrapper"&gt;&lt;p&gt;Click a triangle to open the sub-menu. Click it again to close the sub-menu or click the other triangle to open its menu and close the first. Clicking a triangle on the next level down will leave the top level open, but its siblings work in the same way. Clicking outside the menu but inside this box will also close the menu. The CSS for this layout is not finished and is not intended for narrow screens. I'm aware that the second triangle will overflow the pink background on a very narrow view. Please ignore that. &lt;/p&gt; &lt;div class="hmenu"&gt; &lt;ul id="menucontent" class="navbar"&gt; &lt;li class="item-103 deeper parent linked"&gt; &lt;a href="/" &gt;ITEM 1&lt;/a&gt; &lt;button class="btn-level-1 linked" type="button" name="btn-103"&gt;&lt;/button&gt; &lt;ul class="level-1 hidden not-separator"&gt; &lt;li class="item-104"&gt; &lt;a href="/" &gt;About us&lt;/a&gt; &lt;/li&gt; &lt;li class="item-107 divider deeper parent separator"&gt; &lt;a class="btn-level-2" type="button" &gt;Level 2 separator&lt;/a&gt; &lt;ul class="level-2 hidden separator"&gt; &lt;li class="item-108"&gt; &lt;a href="/" &gt;Lower article&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="item-141 deeper parent linked"&gt; &lt;a class="btn-level-2 heading" type="button" &gt;Menu heading&lt;/a&gt; &lt;ul class="level-2 hidden menu-heading"&gt; &lt;li class="item-142"&gt; &lt;a href="/" &gt;Article under menu heading&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="item-122 divider deeper parent"&gt; &lt;a class="btn-level-1" type="button"&gt;ITEM TWO&lt;/a&gt; &lt;ul class="level-1 hidden separator"&gt; &lt;li class="item-121"&gt; &lt;a href="/" &gt;Test level 2&lt;/a&gt; &lt;/li&gt; &lt;li class="item-134 deeper parent linked"&gt; &lt;a class="btn-level-2 heading" type="button" &gt;Test Two menu heading&lt;/a&gt; &lt;ul class="level-2 hidden menu-heading"&gt; &lt;li class="item-135"&gt; &lt;a href="/" &gt;Article under menu heading&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Duis ac lorem. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse potenti. Sed tincidunt varius arcu.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="menu-demo-2a.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:25:20.157", "Id": "497322", "Score": "1", "body": "Can you also add the HTML for the menu? This can give more context to what you're trying to achieve. We may even be able to suggest a better approach given that information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:46:40.340", "Id": "497325", "Score": "0", "body": "Our rules/guidelines are a little different than stack overflow. This could be a great question if you make a few changes. Please read our [guidelines on how to ask a good question](https://codereview.stackexchange.com/help/how-to-ask). The title should be about what the code does. Since the JavaScript code is affecting the HTML, it would be best to have the HTML in the question as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:47:25.973", "Id": "497335", "Score": "0", "body": "HTML added (and also now mentioned in title)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:30:57.157", "Id": "497345", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." } ]
[ { "body": "<p><strong>DRY</strong> The logic for <code>buttons1</code> and <code>buttons2</code> is identical, so condense it by making a function to which you pass a collection of buttons instead - or, iterate over an array of selectors.</p>\n<pre><code>for (const selector of [&quot;.btn-level-1&quot;, &quot;.btn-level-2&quot;]) {\n const buttons = document.querySelectorAll(selector);\n</code></pre>\n<p><strong>Use CSS rules instead of multiple classes</strong>, when possible - it'll reduce the number of moving parts in your JavaScript. Here, rather than having an <code>opened</code> and <code>not-open</code> class, apply a <em>default</em> style (say, for <code>not-open</code>) and then have the <code>opened</code> class override it.</p>\n<p>In addition, rather than <code>b1.nextElementSibling.classList.add('hidden')</code>, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator\" rel=\"nofollow noreferrer\">adjacent sibling combinator</a> in your CSS rules to select the sibling after an <code>open</code> button.</p>\n<p><strong>Avoid sloppy equality</strong> - it has <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">strange coercion rules</a> a script writer or reader should not be required to have memorized in order to understand the code. Always use <code>===</code> or <code>!==</code> - avoid <code>==</code> and <code>!=</code>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>for (const selector of [\".btn-level-1\", \".btn-level-2\"]) {\n const buttons = [...document.querySelectorAll(selector)];\n for (const button of buttons) {\n button.addEventListener('click', () =&gt; {\n buttons.filter(b =&gt; b !== button).forEach(b =&gt; {\n b.classList.remove('opened');\n });\n button.classList.toggle('opened');\n });\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>button {\n background-color: yellow;\n}\n.opened {\n background-color: orange;\n}\n\nbutton + span {\n display: none;\n}\n.opened + span {\n display: inline;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;\n &lt;button class=\"btn-level-1\"&gt;button level 1&lt;/button&gt;\n &lt;span&gt;description 1-1 (if you can see this, this button is open)&lt;/span&gt;\n&lt;/div&gt;\n&lt;div&gt;\n &lt;button class=\"btn-level-1\"&gt;button level 1&lt;/button&gt;\n &lt;span&gt;description 1-2 (if you can see this, this button is open)&lt;/span&gt;\n&lt;/div&gt;\n\n&lt;br&gt;&lt;br&gt;\n\n&lt;div&gt;\n &lt;button class=\"btn-level-2\"&gt;button level 2&lt;/button&gt;\n &lt;span&gt;description 2-1 (if you can see this, this button is open)&lt;/span&gt;\n&lt;/div&gt;\n&lt;div&gt;\n &lt;button class=\"btn-level-2\"&gt;button level 2&lt;/button&gt;\n &lt;span&gt;description 2-2 (if you can see this, this button is open)&lt;/span&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>With the new code, there are more fixes:</p>\n<p><strong>Menu closing</strong> To close the menu when a click occurs outside of it:</p>\n<ul>\n<li>Have the click listener check to see if the menu content is an ancestor of the clicked element - your current check of whether a <em>button</em> is clicked probably isn't intuitive for users, because even clicks inside the menu on a non-button will close it.</li>\n<li>Instead of iterating over all the different possible class descendants and remove the <code>opened</code> from them, a simple <code>querySelector</code> would be sufficient:</li>\n</ul>\n<pre><code>document.body.addEventListener('click', (e) =&gt; {\n if (!e.target.closest('#menucontent')) {\n // If click was outside of menu, close menu:\n document.querySelector('.opened')?.classList.remove('opened');\n }\n});\n</code></pre>\n<p><strong>Don't use <code>DOMContentLoaded</code></strong> unless you need to - it's unnecessarily enclosing your whole script in another level of indentation. You can avoid <code>DOMContentLoaded</code> by either putting the <code>&lt;script&gt;</code> tag at the bottom of the <code>&lt;body&gt;</code> (which you're doing), or by giving the script tag the <code>defer</code> attribute.</p>\n<p>Live demo with the new code:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>for (const selector of [\".btn-level-1\", \".btn-level-2\"]) {\n const buttons = [...document.querySelectorAll(selector)];\n for (const button of buttons) {\n button.addEventListener('click', () =&gt; {\n buttons.filter(b =&gt; b !== button).forEach(b =&gt; {\n b.classList.remove('opened');\n });\n button.classList.toggle('opened');\n });\n }\n}\ndocument.body.addEventListener('click', (e) =&gt; {\n if (!e.target.closest('#menucontent')) {\n // If click was outside of menu, close menu:\n document.querySelector('.opened')?.classList.remove('opened');\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>button + ul, a[type=button] + ul {\n display: none;\n}\nbutton.opened + ul, a[type=button].opened + ul {\n display: block;\n}\n.sticky-main-menu {\n position: fixed;\n top: 6rem;\n left: 0;\n right: 0;\n z-index: 9999;\n}\n\n.stickymenuwrapper {\n background-color: #fff;\n transition-duration: 0s;\n padding: 1rem;\n margin: 0 auto;\n z-index: 995;\n border: 1px solid gray;\n}\n\n.hmenu ul {\n list-style: none;\n margin-bottom: 0;\n white-space: nowrap;\n padding: 0;\n}\n\n.hmenu ul.navbar {\n background-color: #f7a1d6;\n padding: 0 1rem;\n justify-content: center;\n display: flex;\n /* required for VSC */\n /* text-align: center;*/\n}\n\n.hmenu .navbar {\n line-height: 1.5;\n}\n\n.hmenu li ul {\n position: absolute;\n top: 100%;\n background-color: pink;\n padding: 0 12px 12px;\n}\n\n.hmenu ul[class^=\"level\"] {\n background-color: white;\n position: relative;\n top: 100%;\n left: 0;\n padding: 1rem 0 1rem 1rem;\n margin-top: 0.5rem;\n}\n\n.hmenu ul.level-1 {\n position: absolute;\n /* ? */\n top: 100%;\n left: 0;\n margin-top: 0;\n padding: 1rem;\n box-shadow: 0 2px 5px #acaaaa;\n}\n\n.hmenu ul.level-2,\n.hmenu ul.level-4 {\n background-color: #dedede;\n}\n\n.hmenu ul li:last-child {\n padding-bottom: 0;\n}\n\n.hmenu li.active&gt;a {\n text-decoration: underline;\n}\n\n.hmenu a.separator:hover {\n text-decoration: none;\n}\n\n.hmenu ul[class^=\"level\"] li {\n margin-right: 1rem;\n}\n\n.hmenu li {\n position: relative;\n /* display: flex;*/\n margin: 0;\n padding: 0 0 0.5rem;\n line-height: 1.5rem;\n}\n\n.hmenu li a {\n color: #0d6efd;\n}\n\n.hmenu li.parent {\n margin-right: 0;\n /* was 2rem */\n}\n\n.hmenu .navbar&gt;li {\n padding: 0;\n margin: 0 0.5rem;\n display: flex;\n}\n\n.hmenu .navbar&gt;li.parent {\n margin-right: 2rem;\n}\n\n.hmenu .navbar&gt;li.divider.parent {\n margin-right: 0;\n}\n\n.hmenu .navbar&gt;li&gt;a {\n padding: 0.5rem 0 0.5rem 0.5rem;\n margin: 0 0 0 0;\n}\n\n.hmenu .navbar&gt;li:first-child&gt;a {\n padding: 0.5rem 0.5rem 0.5rem 0;\n margin-left: 0;\n}\n\n.hmenu li.heading&gt;a,\n.hmenu li.divider&gt;a,\n.hmenu li.separator&gt;a {\n text-decoration: none;\n padding-right: 2rem;\n}\n\n.hmenu li.separator-line {\n position: relative;\n height: 1rem;\n display: inline-block;\n width: 100%;\n}\n\n.hmenu li.separator-line span {\n display: none;\n}\n\n.hmenu li.separator-line:after {\n position: absolute;\n height: 0;\n top: 60%;\n width: 100%;\n border-top: 1px solid#8c8a8a;\n border-bottom: 1px solid lightgray;\n margin: 0 0;\n content: \"\";\n}\n\n.hmenu ul.navbar&gt;li a {\n padding-top: 0.5rem;\n position: relative;\n}\n\n[type=\"button\"] {\n -webkit-appearance: button;\n}\n\n[type=\"button\"]:not(:disabled) {\n cursor: pointer;\n}\n\n.hmenu button,\n.hmenu button:focus {\n display: inline-flex;\n position: absolute;\n background: transparent;\n border: none;\n color: #0d6efd;\n height: 1.5rem;\n outline: none;\n padding: 0 0 0 .5rem;\n margin: 0;\n right: 0;\n width: 40px;\n top: 6px;\n}\n\n.hmenu li.linked button {\n position: relative;\n top: 0;\n}\n\n.hmenu li.linked button.btn-level-1 {\n top: 10px;\n}\n\n.hmenu .navbar&gt;li.linked.top-level {\n margin-right: 0.5rem;\n}\n\n.hmenu button.btn-level-1 {\n right: 0;\n position: absolute;\n top: 0;\n}\n\n.hmenu li button[class^=\"btn-level\"]:after,\n.hmenu li a[class^=\"btn-level\"]:after {\n display: inline-flex;\n width: 0;\n height: 0;\n margin: 0 .5em;\n content: \"\";\n transition: all .3s ease-out;\n position: absolute;\n top: 12px;\n cursor: pointer;\n right: -2rem;\n border-top: 10px solid;\n border-right: 8px solid transparent;\n border-left: 8px solid transparent;\n}\n\n.hmenu li.separator&gt;button[class^=\"btn-level\"]:after,\n.hmenu li.separator&gt;a[class^=\"btn-level\"]:after {\n right: 0;\n}\n\n.hmenu li button[class^=\"btn-level\"].opened,\n.hmenu li a[class^=\"btn-level\"].opened {\n color: red;\n}\n\n.hmenu li button[class^=\"btn-level\"].opened:after,\n.hmenu li a[class^=\"btn-level\"].opened:after {\n border-top: none;\n border-bottom: 10px solid;\n border-right: 8px solid transparent;\n border-left: 8px solid transparent;\n top: 12px;\n right: 0;\n}\n\n.hmenu li.linked&gt;a[class^=\"btn-level\"].opened:after {\n right: -2rem;\n}\n\n.hmenu li button.linked {\n display: inline-flex;\n position: relative;\n}\n\n.hmenu li button.linked:after {\n top: 10px;\n right: 0;\n}\n\n.hmenu li button[class^=\"btn-level\"].linked.opened:after {\n top: 6px;\n right: 0;\n}\n\n.hmenu li button.btn-level-1.linked {\n display: inline-flex;\n position: relative;\n}\n\n.hmenu li button.btn-level-1:after,\n.hmenu li button.btn-level-1.opened:after {\n top: 30%;\n right: 0;\n}\n\n.hmenu li a.btn-level-1:after,\n.hmenu li a.btn-level-1.opened:after {\n top: 40%;\n right: -2rem;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"stickymenuwrapper\" class=\"stickymenuwrapper\"&gt;\n &lt;p&gt;Click a triangle to open the sub-menu. Click it again to close the sub-menu or click the other triangle to open its menu and close the first. Clicking a triangle on the next level down will leave the top level open, but its siblings work in the same\n way. Clicking outside the menu but inside this box will also close the menu. The CSS for this layout is not finished and is not intended for narrow screens. I'm aware that the second triangle will overflow the pink background on a very narrow view.\n Please ignore that. &lt;/p&gt;\n &lt;div class=\"hmenu\"&gt;\n &lt;ul id=\"menucontent\" class=\"navbar\"&gt;\n &lt;li class=\"item-103 deeper parent linked\"&gt;\n &lt;a href=\"/\"&gt;ITEM 1&lt;/a&gt;\n &lt;button class=\"btn-level-1 linked\" type=\"button\" name=\"btn-103\"&gt;&lt;/button&gt;\n &lt;ul class=\"level-1 not-separator\"&gt;\n &lt;li class=\"item-104\"&gt;\n &lt;a href=\"/\"&gt;About us&lt;/a&gt;\n &lt;/li&gt;\n &lt;li class=\"item-107 divider deeper parent separator\"&gt;\n &lt;a class=\"btn-level-2\" type=\"button\"&gt;Level 2 separator&lt;/a&gt;\n &lt;ul class=\"level-2 separator\"&gt;\n &lt;li class=\"item-108\"&gt;\n &lt;a href=\"/\"&gt;Lower article&lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li class=\"item-141 deeper parent linked\"&gt;\n &lt;a class=\"btn-level-2 heading\" type=\"button\"&gt;Menu heading&lt;/a&gt;\n &lt;ul class=\"level-2 menu-heading\"&gt;\n &lt;li class=\"item-142\"&gt;\n &lt;a href=\"/\"&gt;Article under menu heading&lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li class=\"item-122 divider deeper parent\"&gt;\n &lt;a class=\"btn-level-1\" type=\"button\"&gt;ITEM TWO&lt;/a&gt;\n &lt;ul class=\"level-1 separator\"&gt;\n &lt;li class=\"item-121\"&gt;\n &lt;a href=\"/\"&gt;Test level 2&lt;/a&gt;\n &lt;/li&gt;\n &lt;li class=\"item-134 deeper parent linked\"&gt;\n &lt;a class=\"btn-level-2 heading\" type=\"button\"&gt;Test Two menu heading&lt;/a&gt;\n &lt;ul class=\"level-2 menu-heading\"&gt;\n &lt;li class=\"item-135\"&gt;\n &lt;a href=\"/\"&gt;Article under menu heading&lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;p&gt;Duis ac lorem. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse potenti. Sed tincidunt varius arcu.&lt;/p&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:48:55.547", "Id": "497336", "Score": "0", "body": "I've removed the 'not-open' class (see new snippet) but I'm not sure about your comment regarding ==, === and != because only those are used (except where only = is allowed, e.g. `let i = 0`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:38:19.630", "Id": "497341", "Score": "0", "body": "You're using `b1 != button1` and `b2 != button2` - better to use strict equality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:20:08.243", "Id": "497344", "Score": "0", "body": "Sorry, I missed the `!==` instead of `!=`. The `DOMContentLoaded` is for Joomla. It won't work otherwise. I'll remove it from this snippet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T11:24:19.977", "Id": "497397", "Score": "0", "body": "Thank you so much. From potentially dozens of lines of code to just 16. Wonderful. I'm sorry I broke so many rules. I will carry on with my JavaScript beginner's course and next time I post here I hope it will be ok." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T16:03:46.087", "Id": "497429", "Score": "0", "body": "In my development site I have removed the `\"id=menucontent\"` from the top `<ul>` and have added a class `menucontent` instead. I then amended your `(!e.target.closest('#menucontent')` to `(!e.target.closest('.menucontent')` to avoid potential duplicate IDs on the same page, which could happen if the menu is displayed twice, e.g. top and bottom." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:38:26.653", "Id": "252415", "ParentId": "252413", "Score": "4" } } ]
{ "AcceptedAnswerId": "252415", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T15:16:53.890", "Id": "252413", "Score": "4", "Tags": [ "javascript", "beginner", "css" ], "Title": "HTML multi-level menu" }
252413
<p>im trying to migrate my very large swift view controller to mvvm but it still feels very large, can you guys give me any advice</p> <p>What this controller does is simple it shows a UIView on which i can draw the buttons that I display are here to manage the lines that i have drawn on the canvas.</p> <p>For example to delete the last line drawn, delete all lines, change the color etc ...</p> <p>What I want to do is to create my buttons while conforming to MVVM, so its not as ugly as my view controller is right now</p> <pre><code>@objc class VideoEditorViewController: UIViewController { let canvas = Canvas() let picker = UIColorPickerViewController() func setCanvasUI() { self.view.addSubview(canvas) canvas.backgroundColor = .clear let undoButton = CanvasButtonsViewModel(frame: .zero) undoButton.configure(with: CanvasModelButtonModel(image: UIImage(systemName: &quot;arrowshape.turn.up.left.fill&quot;)? .withTintColor(.white, renderingMode: .alwaysOriginal), width: 50, height: 50, backgroundColor: .white)) undoButton.addTarget(self, action: #selector(handleUndo), for: .touchUpInside) let colorPicker = CanvasButtonsViewModel(frame: .zero) colorPicker.configure(with: CanvasModelButtonModel(image: UIImage(systemName: &quot;pencil.circle&quot;)? .withTintColor(.white, renderingMode: .alwaysOriginal), width: 50, height: 50, backgroundColor: .white)) colorPicker.addTarget(self, action: #selector(ColorPicker), for: .touchUpInside) let trashCanButton = CanvasButtonsViewModel(frame: .zero) trashCanButton.configure(with: CanvasModelButtonModel(image: UIImage(systemName: &quot;trash&quot;)? .withTintColor(.white, renderingMode: .alwaysOriginal), width: 50, height: 50, backgroundColor: .white)) trashCanButton.addTarget(self, action: #selector(handleClear), for: .touchUpInside) let uploadViewButton = CanvasButtonsViewModel(frame: .zero) uploadViewButton.configure(with: CanvasModelButtonModel(image: UIImage(systemName: &quot;envelope&quot;)? .withTintColor(.white, renderingMode: .alwaysOriginal), width: 51, height: 48, backgroundColor: .white)) let test = CanvasButtonsViewModel(frame: .zero) test.configure(with: CanvasModelButtonModel(image: UIImage(systemName: &quot;pencil.circle&quot;)? .withTintColor(.white, renderingMode: .alwaysOriginal), width: 51, height: 48, backgroundColor: .white)) test.addTarget(self, action: #selector(testdraw), for: .touchUpInside) let stackView = UIStackView(arrangedSubviews: [ undoButton, trashCanButton, colorPicker, uploadViewButton, test ]) view.addSubview(stackView) stackView.axis = .vertical stackView.bringSubviewToFront(self.view) stackView.spacing = 30 stackView.snp.makeConstraints { (make) in make.right.equalTo(view.snp_rightMargin).offset(-20) make.top.equalTo(view.snp_topMargin) } canvas.frame = view.frame } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setCanvasUI() } override func viewDidLoad() { super.viewDidLoad() } } extension VideoEditorViewController: UIColorPickerViewControllerDelegate, UIImagePickerControllerDelegate { @objc func handleUndo() { canvas.undo() } @objc func handleClear() { canvas.undoAll() } @objc func ColorPicker() { present(picker, animated: true, completion: nil) canvas.setStrokeColor(color: picker.selectedColor) } @objc func testdraw() { if (canvas.isDrawable == false) { canvas.setDrawable(state: true) return } if (canvas.isDrawable == true) { canvas.setDrawable(state: false) return } } } </code></pre> <p>Canvas View :</p> <pre><code>import Foundation import UIKit import SnapKit class Canvas: UIView { private var strokeColor = UIColor.black private var strokeWidth: Float = 10 public var isDrawable: Bool = false public func setStrokeColor(color: UIColor) { self.strokeColor = color } public func setDrawable(state: Bool) { self.isDrawable = state } public func undo() { _ = lines.popLast() setNeedsDisplay() } public func undoAll() { lines.removeAll() setNeedsDisplay() } public func changeWidth(width: Float) { self.strokeWidth = width setNeedsDisplay() } public func draw() { guard let context = UIGraphicsGetCurrentContext() else { return } lines.forEach { (line) in context.setStrokeColor(line.color.cgColor) context.setLineWidth(CGFloat(line.strokeWidth)) context.setLineCap(.round) for(i, p) in line.points.enumerated() { if (i == 0) { context.move(to: p) } else { context.addLine(to: p) } } context.strokePath() } } override func draw(_ rect: CGRect) { super.draw(rect) if (isDrawable == true) { draw() } } var lines = [Line]() override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { lines.append(Line.init(strokeWidth: strokeWidth, color: strokeColor, points: [], drawable: isDrawable)) } override func touchesMoved(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { if (isDrawable == true) { guard let point = touches.first?.location(in: nil) else { return } guard var lastLine = lines.popLast() else { return } lastLine.points.append(point) lines.append(lastLine) print(point) setNeedsDisplay() } } } </code></pre> <p>Canvas Struct to draw lines :</p> <pre><code>struct Line { let strokeWidth: Float let color: UIColor var points: [CGPoint] var drawable: Bool } </code></pre> <p>My view model</p> <pre><code>final class CanvasButtonsViewModel: UIButton { let image: UIImageView = { let image = UIImageView() image.image = UIImage() image.image?.withTintColor(.white, renderingMode: .alwaysOriginal) return image }() func setConfig(size: CGFloat) -&gt; UIImage.SymbolConfiguration { let largeConfig = UIImage.SymbolConfiguration(pointSize: size, weight: .bold, scale: .large) return largeConfig } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) } func configure(with viewModel: CanvasModelButtonModel) { self.addSubview(image) image.image = viewModel.image image.frame = CGRect(x: 0, y: 0, width: viewModel.width, height: viewModel.height) } override func layoutSubviews() { super.layoutSubviews() } } </code></pre> <p>The model</p> <pre><code>struct CanvasModelButtonModel { let image: UIImage? let width: CGFloat let height: CGFloat let backgroundColor: UIColor? } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:24:35.740", "Id": "497330", "Score": "2", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"." } ]
[ { "body": "<pre class=\"lang-swift prettyprint-override\"><code>// General Comments\n/**\n - All view model should not be inherited from UIView nor UIViewController they should be their own separate classes/structs\n - The provided code is all view and UI logic which do not need view models\n */\nimport Foundation\nimport UIKit\nimport SnapKit\n\n@objc\nclass VideoEditorViewController: UIViewController {\n let canvas = Canvas()\n let picker = UIColorPickerViewController()\n \n // Life cycle functions should be at the top of the view controller after the variables and outlets\n override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n self.setCanvasUI()\n }\n // no need to have this function as it only calls its parent function\n override func viewDidLoad() {\n super.viewDidLoad()\n }\n \n func setCanvasUI() {\n self.view.addSubview(self.canvas)\n self.canvas.backgroundColor = .clear\n // You should seperate between each UIView with at least one space for readability\n let undoButton = CanvasButton(frame: .zero)\n let undoButtonModel = CanvasButtonModel(image: UIImage(systemName: &quot;arrowshape.turn.up.left.fill&quot;)?.withTintColor(.white, renderingMode: .alwaysOriginal), width: 50, height: 50, backgroundColor: .white)\n undoButton.configure(with: undoButtonModel)\n undoButton.addTarget(self, action: #selector(handleUndo), for: .touchUpInside)\n \n let colorPicker = CanvasButton(frame: .zero)\n let colorPickerModle = CanvasButtonModel(image:UIImage(systemName: &quot;pencil.circle&quot;)?.withTintColor(.white, renderingMode: .alwaysOriginal), width: 50, height: 50, backgroundColor: .white)\n colorPicker.configure(with: colorPickerModle)\n colorPicker.addTarget(self, action: #selector(ColorPicker), for: .touchUpInside)\n \n let trashCanButton = CanvasButton(frame: .zero)\n let trashCanModel = CanvasButtonModel(image: UIImage(systemName: &quot;trash&quot;)?.withTintColor(.white, renderingMode: .alwaysOriginal), width: 50, height: 50, backgroundColor: .white)\n trashCanButton.configure(with: trashCanModel)\n trashCanButton.addTarget(self, action: #selector(handleClear), for: .touchUpInside)\n \n let uploadViewButton = CanvasButton(frame: .zero)\n let uploadButtonModel = CanvasButtonModel(image:UIImage(systemName: &quot;envelope&quot;)?.withTintColor(.white, renderingMode: .alwaysOriginal), width: 51, height: 48, backgroundColor: .white)\n uploadViewButton.configure(with: uploadButtonModel)\n \n let test = CanvasButton(frame: .zero)\n let testModel = CanvasButtonModel(image: UIImage(systemName: &quot;pencil.circle&quot;)?.withTintColor(.white, renderingMode: .alwaysOriginal), width: 51, height: 48, backgroundColor: .white)\n test.configure(with: testModel)\n test.addTarget(self, action: #selector(testdraw), for: .touchUpInside)\n \n let stackView = UIStackView(arrangedSubviews: [\n undoButton,\n trashCanButton,\n colorPicker,\n uploadViewButton,\n test\n ])\n \n view.addSubview(stackView)\n \n stackView.axis = .vertical\n stackView.bringSubviewToFront(self.view)\n stackView.spacing = 30\n stackView.snp.makeConstraints { (make) in\n make.right.equalTo(view.snp_rightMargin).offset(-20)\n make.top.equalTo(view.snp_topMargin)\n }\n self.canvas.frame = view.frame\n }\n}\n\n// We should use this protocol to make sure than anyone who is using the canvas with these buttons should have these functions implemented. Although I would personally prefer to have all these buttons inside the Canvas UIView along with its functionalities\n@objc\nprotocol CanvasButtonsDelegate {\n func handleUndo()\n func handleClear()\n func colorPicker()\n func testdraw()\n}\n\nextension VideoEditorViewController: UIColorPickerViewControllerDelegate, UIImagePickerControllerDelegate, CanvasButtonsDelegate {\n // There should be at least one space between each function declaration\n @objc func handleUndo() {\n self.canvas.undo()\n }\n \n @objc func handleClear() {\n self.canvas.undoAll()\n }\n // function name should start with lower case\n @objc func colorPicker() {\n present(self.picker, animated: true, completion: nil)\n self.canvas.setStrokeColor(color: self.picker.selectedColor)\n }\n \n @objc func testdraw() {\n if (self.canvas.isDrawable == false) {\n self.canvas.setDrawable(state: true)\n return\n }\n if (self.canvas.isDrawable == true) {\n self.canvas.setDrawable(state: false)\n return\n }\n }\n}\n\nclass Canvas: UIView {\n private var strokeColor = UIColor.black\n private var strokeWidth: Float = 10\n public var isDrawable: Bool = false\n var lines = [Line]()\n \n public func setStrokeColor(color: UIColor) {\n self.strokeColor = color\n }\n \n public func setDrawable(state: Bool) {\n self.isDrawable = state\n }\n \n public func undo() {\n _ = self.lines.popLast()\n self.setNeedsDisplay()\n }\n public func undoAll() {\n self.lines.removeAll()\n self.setNeedsDisplay()\n }\n \n public func changeWidth(width: Float) {\n self.strokeWidth = width\n self.setNeedsDisplay()\n }\n \n public func draw() {\n guard let context = UIGraphicsGetCurrentContext() else { return }\n \n self.lines.forEach { (line) in\n context.setStrokeColor(line.color.cgColor)\n context.setLineWidth(CGFloat(line.strokeWidth))\n context.setLineCap(.round)\n for(i, p) in line.points.enumerated() {\n if (i == 0) {\n context.move(to: p)\n } else {\n context.addLine(to: p)\n }\n }\n context.strokePath()\n }\n }\n \n override func draw(_ rect: CGRect) {\n super.draw(rect)\n if (self.isDrawable == true) {\n self.draw()\n }\n }\n \n override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {\n self.lines.append(Line(strokeWidth: self.strokeWidth, color: self.strokeColor, points: [], drawable: self.isDrawable))\n }\n \n override func touchesMoved(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {\n if (self.isDrawable == true) {\n guard let point = touches.first?.location(in: nil) else { return }\n \n guard var lastLine = self.lines.popLast() else { return }\n lastLine.points.append(point)\n self.lines.append(lastLine)\n print(point)\n self.setNeedsDisplay()\n }\n }\n}\n\nfinal class CanvasButton: UIButton {\n let image: UIImageView = {\n let image = UIImageView()\n image.image = UIImage()\n image.image?.withTintColor(.white, renderingMode: .alwaysOriginal)\n return image\n }()\n \n override init(frame: CGRect) {\n super.init(frame: frame)\n }\n \n required init?(coder: NSCoder) {\n fatalError(&quot;init(coder:) has not been implemented&quot;)\n }\n \n func setConfig(size: CGFloat) -&gt; UIImage.SymbolConfiguration {\n let largeConfig = UIImage.SymbolConfiguration(pointSize: size, weight: .bold, scale: .large)\n return largeConfig\n }\n \n func configure(with viewModel: CanvasButtonModel) {\n self.addSubview(self.image)\n self.image.image = viewModel.image\n self.image.frame = CGRect(x: 0, y: 0, width: viewModel.width, height: viewModel.height)\n }\n \n override func layoutSubviews() {\n super.layoutSubviews()\n }\n}\n\n/**\n - CanvasButtonsViewModel should be CanvasButtonModel as it doesn't reflect anything related to view model concept\n - Also it should be Button not Buttons\n - CanvasModelButtonModel is just a model a container, not a view model\n - The naming convention is not being followed here ex: CanvasModelButtonModel. It should be CanvasButtonModel\n*/\nstruct CanvasButtonModel {\n let image: UIImage?\n let width: CGFloat\n let height: CGFloat\n let backgroundColor: UIColor?\n}\n\nstruct Line {\n let strokeWidth: Float\n let color: UIColor\n var points: [CGPoint]\n var drawable: Bool\n}\n</code></pre>\n<p>I'm failing to understand the reason behind writing the code in such a way so I will just provide a very simple example of MVVM pattern in iOS swift using UIKit</p>\n<pre class=\"lang-swift prettyprint-override\"><code>import Foundation\nimport UIKit\n\n// just a temp way to pass errors to the UI\nenum ViewModelError: Error {\n case loginFailed\n}\n\n// the list of action any UI is using the provided view model should handle\nprotocol ViewModelDelegate {\n func onLoginSuccess(response: NSObject)\n func onLoginFailuar(error: Error)\n}\n\n// so the view will only be able to access the available functionality of this view model and not the whole properties and functionalities\n// also for easier testing\n@objc\nprotocol ViewModelInterface {\n func login()\n}\n\n// will contain all the business and API calling logic like local validation, on network error, etc\nfinal class ViewModel: ViewModelInterface {\n \n var delegate: ViewModelDelegate?\n \n init(delegate: ViewModelDelegate? = nil) {\n self.delegate = delegate\n }\n \n @objc func login() {\n // async call here to login the user\n if true { // success\n self.delegate?.onLoginSuccess(response: NSObject())\n } else { // failed\n self.delegate?.onLoginFailuar(error: ViewModelError.loginFailed)\n }\n }\n}\n\n// will contain all the UI logic\nclass ViewController: UIViewController {\n // MARK:- Outlets\n let loginButton: UIButton = UIButton()\n \n // MARK:- ViewModel\n var vm: ViewModelInterface!\n \n // MARK:- Lifecycle\n override func viewDidLoad() {\n super.viewDidLoad()\n // set the view model delegate\n self.vm = ViewModel(delegate: self)\n \n // UI is dump and should not know what to do here and it is the view model responsibility to know what to do on any kind of events\n self.loginButton.addTarget(self.vm, action: #selector(self.vm.login), for: .touchDown)\n }\n}\n\nextension ViewController: ViewModelDelegate {\n func onLoginSuccess(response: NSObject) {\n // 1. save token in the user default\n // 2. navigate to home screen\n }\n \n func onLoginFailuar(error: Error) {\n // show error on the UI\n }\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T10:17:41.187", "Id": "256134", "ParentId": "252418", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T16:01:40.770", "Id": "252418", "Score": "1", "Tags": [ "swift", "mvvm" ], "Title": "Create buttons with MVVM architecture" }
252418
<p>Initial version of the code appeared as an answer to an SO <a href="https://stackoverflow.com/questions/64868937/how-to-scrape-a-table-and-its-links/64873079">question</a>. I refactored the code a bit and it works pretty well, IMHO. I get a solid <code>.csv</code> file with all the data from <a href="https://www.tdcj.texas.gov/death_row/dr_executed_offenders.html" rel="nofollow noreferrer">Texas Department of Criminal Justice's Death Row</a> page.</p> <p>What I was especially interested in was getting all offenders' last statement, if there was any, which the codes accomplishes.</p> <p>What I'd want to get here is some feedback on utilizing <code>pandas</code>, as I'm relatively new to it. Also, some memory efficiency suggestions would be nice too, I guess.</p> <p>For example, should I save the initial version of the <code>.csv</code> file and then read it so I can append the last statements? Or keeping everything in memory is fine?</p> <p>If you find any other holes, do point them out!</p> <p>The code:</p> <pre><code>import random import time import pandas as pd import requests from lxml import html base_url = &quot;https://www.tdcj.texas.gov/death_row&quot; statement_xpath = '//*[@id=&quot;content_right&quot;]/p[6]/text()' def get_page() -&gt; str: return requests.get(f&quot;{base_url}/dr_executed_offenders.html&quot;).text def clean(first_and_last_name: list) -&gt; str: name = &quot;&quot;.join(first_and_last_name).replace(&quot; &quot;, &quot;&quot;).lower() return name.replace(&quot;, Jr.&quot;, &quot;&quot;).replace(&quot;, Sr.&quot;, &quot;&quot;).replace(&quot;'&quot;, &quot;&quot;) def get_offender_data(page: str) -&gt; pd.DataFrame: df = pd.read_html(page, flavor=&quot;bs4&quot;) df = pd.concat(df) df.rename( columns={'Link': &quot;Offender Information&quot;, &quot;Link.1&quot;: &quot;Last Statement URL&quot;}, inplace=True, ) df[&quot;Offender Information&quot;] = df[ [&quot;Last Name&quot;, 'First Name'] ].apply(lambda x: f&quot;{base_url}/dr_info/{clean(x)}.html&quot;, axis=1) df[&quot;Last Statement URL&quot;] = df[ [&quot;Last Name&quot;, 'First Name'] ].apply(lambda x: f&quot;{base_url}/dr_info/{clean(x)}last.html&quot;, axis=1) return df def get_last_statement(statement_url: str) -&gt; str: page = requests.get(statement_url).text statement = html.fromstring(page).xpath(statement_xpath) text = next(iter(statement), &quot;&quot;) return &quot; &quot;.join(text.split()) def get_last_statements(offenders_data: list) -&gt; list: statements = [] for item in offenders_data: *names, url = item print(f&quot;Fetching statement for {' '.join(names)}...&quot;) statements.append(get_last_statement(statement_url=url)) time.sleep(random.randint(1, 4)) return statements if __name__ == &quot;__main__&quot;: offenders_df = get_offender_data(get_page()) names_and_urls = list( zip( offenders_df[&quot;First Name&quot;], offenders_df[&quot;Last Name&quot;], offenders_df[&quot;Last Statement URL&quot;], ) ) offenders_df[&quot;Last Statement&quot;] = get_last_statements(names_and_urls) offenders_df.to_csv(&quot;offenders_data.csv&quot;, index=False) </code></pre> <p>The scraping part is intentionally slow, as I don't want to abuse the server, but I do want to get the job done. So, if you don't have a couple of minutes to spare, you can fetch the <code>offenders_data.csv</code> file from <a href="https://yadi.sk/d/uSUMXxGv6bUMYw" rel="nofollow noreferrer">here</a>.</p>
[]
[ { "body": "<h2>Types</h2>\n<p>Here:</p>\n<pre><code>def clean(first_and_last_name: list) -&gt; str:\n</code></pre>\n<p><code>list</code> should more specifically be <code>List[str]</code>.</p>\n<h2>Fluent syntax</h2>\n<p>Consider using fluent syntax for your <code>clean</code>, which - in this case - is basically just a reformat:</p>\n<pre><code> return (\n &quot;&quot;.join(first_and_last_name)\n .replace(&quot; &quot;, &quot;&quot;)\n .replace(&quot;, Jr.&quot;, &quot;&quot;)\n .replace(&quot;, Sr.&quot;, &quot;&quot;)\n .replace(&quot;'&quot;, &quot;&quot;)\n .lower()\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T00:14:56.033", "Id": "497474", "Score": "0", "body": "@Carcigenicate Shiny, I didn't know that!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T17:23:23.783", "Id": "252462", "ParentId": "252422", "Score": "3" } } ]
{ "AcceptedAnswerId": "252462", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:17:14.620", "Id": "252422", "Score": "5", "Tags": [ "python", "python-3.x", "web-scraping", "pandas" ], "Title": "Getting death row inmates' last statement" }
252422
<p>My C program has to parse a fixed-length message like this:</p> <pre><code>uint8_t message[8] = {80, 75, 73, 71, 1, 1, 1, 1}; </code></pre> <p>another message could be:</p> <pre><code>uint8_t message[8] = {80, 75, 73, 71, 41, 42, 1, 1}; </code></pre> <p>The message contains an ASCII string and 1 shows the end of string. So the actual length of the first message is 4 and the second message is 6.</p> <p>I use this method to extract the message:</p> <pre><code>1. Counting the message length 2. Initializing a variable length array with this value. 3. Using memcpy to copy the bytes. </code></pre> <p><em>decoder.h</em></p> <pre><code>#ifndef DECODER_H_INCLUDED #define DECODER_H_INCLUDED #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #define LENGTH 100 void parse(uint8_t * message); void get_address(char * addr, int size); uint8_t get_size(void); #endif // DECODER_H_INCLUDED </code></pre> <p><em>decoder.c</em></p> <pre><code>#include &quot;decoder.h&quot; // Global variables in library uint8_t parsed_message[LENGTH]; uint8_t len = 0; void parse(uint8_t * message) { len = 0; for (int i = 0; i &lt; LENGTH; i++) { if (message[i] != 1) { parsed_message[i] = message[i]; len++; } else { parsed_message[i] = '\0'; len++; break; } } } void get_address(char * addr, int size) { memcpy(addr, parsed_message, size); } uint8_t get_size(void) { return len; } </code></pre> <p><em>In the main function:</em></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;decoder.h&quot; int main(void) { uint8_t input[8] = {80, 75, 73, 71, 1, 1, 1, 1}; parse(input); char addr[get_size()]; get_address(addr, get_size()); printf(&quot;==== %s ==== ADDRESS\n&quot;, addr); return 0; } </code></pre> <p>I use GCC compiler and C99 standard in ARM-Based 32-bit micro-controller.</p> <p>My question is that is this method safe? Or I should use another approach.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:11:28.690", "Id": "497342", "Score": "7", "body": "Please post the whole code as one, with the proper `#include`s also." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T11:25:36.787", "Id": "497398", "Score": "4", "body": "CodeReview is not for reviewing code snippets or hypothetical code. If you just want to know what a safe way is to copy the kinds of strings you get, try asking on [StackOverflow](https://stackoverflow.com/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T15:32:33.433", "Id": "497422", "Score": "1", "body": "@RolandIllig I edited my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T15:32:56.250", "Id": "497423", "Score": "2", "body": "@G.Sliepen Thanks for your note. I edited my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T16:52:46.080", "Id": "497432", "Score": "3", "body": "To anyone in the Close Question queue, the issues with this question have been corrected." } ]
[ { "body": "<h2>Overall Observations</h2>\n<p>The <code>int main(void)</code> function is correctly declared since no arguments are expected.</p>\n<p>The code definitely follows the Single Responsibility Principle and this is good!</p>\n<p>The use of portable include guards is good.</p>\n<p>The program would be more flexible if it accepted the message as input from either the console or a file (would require an alternate declaration for <code>main()</code>).</p>\n<h2>Use System Defined Constants</h2>\n<p>The <code>main()</code> function could be made more readable if the system defined constants <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\">EXIT_SUCCESS and EXIT_FAILURE</a> were used (only <code>EXIT_SUCCESS</code> in this case). These constants are included in the <code>stdlib.h</code> header file which is already included in the code.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &quot;decoder.h&quot;\n\nint main(void) {\n\n uint8_t input[8] = { 80, 75, 73, 71, 1, 1, 1, 1 };\n parse(input);\n\n char addr[get_size()];\n get_address(addr, get_size());\n printf(&quot;==== %s ==== ADDRESS\\n&quot;, addr);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<p>In C it is possible to have a variable that is global to a file, but does not impact the entire program by using the <code>static</code> keyword.</p>\n<pre><code>static uint8_t parsed_message[LENGTH];\nstatic uint8_t len = 0;\n</code></pre>\n<p>In the current implementation this compiles properly.</p>\n<p>If you are really going to use global variables throughout the program they should be declared as extern variables in the header file.</p>\n<pre><code>#ifndef DECODER_H_INCLUDED\n#define DECODER_H_INCLUDED\n\n#include &lt;stdint.h&gt;\n\n#define LENGTH 100\nextern uint8_t parsed_message[LENGTH];\nextern uint8_t len;\n\nvoid parse(uint8_t* message);\nvoid get_address(char* addr, int size);\nuint8_t get_size(void);\n\n#endif // DECODER_H_INCLUDED\n</code></pre>\n<h2>Header Files</h2>\n<p>Only include header files that are absolutely necessary to make the code compile in header files, it is better to include the necessary header files in the C source file. This makes the code clearer in the source file. In <code>decoder.h</code> the only necessary header file is <code>stdint.h</code>. This could affect compile time and cause link errors if include guards are missing. In most implementations of C a temporary source file is generated by the C pre-processor and all header files are copied into the temporary file.</p>\n<h2>Variable Types</h2>\n<p>It isn't clear from reviewing the program why the code is using <code>uint8_t</code> rather than <code>unsigned char</code>. The overall result would be the same and less header files would be necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T18:02:41.720", "Id": "497444", "Score": "1", "body": "Thanks for your answer. Data is received over network. Actually this code is part of a bigger program. My main problem is with using the VLAs. I would like to compare this method with dynamic memory allocation, i.e. using malloc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T18:04:17.783", "Id": "497445", "Score": "0", "body": "And about uint8_t, the libraries are already included in my toolchain libraries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T18:13:30.053", "Id": "497446", "Score": "0", "body": "@ImanH It should work with malloc() or calloc() parsed_message[] could be and allocated in parse(). The function parse could return a pointer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T18:18:29.200", "Id": "497447", "Score": "0", "body": "Does memory allocation have any preference over VLA?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T18:56:18.310", "Id": "497450", "Score": "0", "body": "@ImanH I'm sorry, what is VLA?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T19:09:09.380", "Id": "497451", "Score": "0", "body": "Variable length array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T20:45:11.723", "Id": "497456", "Score": "1", "body": "@ImanH C99 is the first version of C to support VLA, I really don't know how well it is supported in C. Memory allocation was the primary way to do this in C previously." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T16:43:09.367", "Id": "252460", "ParentId": "252424", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T17:48:28.927", "Id": "252424", "Score": "2", "Tags": [ "c" ], "Title": "Parsing a fixed-size message using variable length array in C" }
252424
<p>Here is the code that can be used for calculation of mathematical function, like <code>ax^2 + bx + c</code>.</p> <p>It is fast enough if you choose small length, otherwise if programmer don't know the small range, that code can be really slow. I've made it specially on C++ to be more fast.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; template&lt;class var&gt; var Module(var x){ if (x &gt;= 0) return x; else return x*-1; } class Linear { public: float resA, resB, resC; float err; float Predict(float a, float b, float c, float x) { return ((a * (x*x)) + (b*x) + c); } float Predict(float x) { return ((resA * (x * x)) + (resB * x) + resC); } float ErrorAv(float a, float b, float c, vector&lt;float&gt; input, vector&lt;float&gt; output) { float error = Module(Predict(a, b, c, input[0]) - output[0]); for (int i = 1; i &lt; input.size(); i++) error = (Module(Predict(a, b, c, input[i]) - output[i]) + error)/2; return error; } void LinearRegr(vector&lt;float&gt; input, vector&lt;float&gt; output, float maximum, float minimum = 0, float step = 1) { if (step == 0) step++; float a, b, c; float lastError = INFINITY; for (a = minimum; a &lt;= maximum; a += step) for (b = minimum; b &lt;= maximum; b += step) for (c = minimum; c &lt;= maximum; c += step) { float error = ErrorAv(a, b, c, input, output); if (error &lt; lastError) { lastError = error; resA = a; resB = b; resC = c; err = lastError; if (!lastError) return; } } } }; #include &lt;ctime&gt; int main(){ vector&lt;float&gt; input; //Input example. vector&lt;float&gt; output; //Output example. float a = 10.5, b = -7, c = 5.5; //Variables as search values. //Fill dataset: for (int i = 0; i &lt; 100; i++) { input.push_back(i); output.push_back((a * (i * i)) + (b * i) + c); } clock_t begin = clock(); //Start clock while searching a, b, c values Linear linear; linear.LinearRegr(input, output, 15, -10, 0.5); //Start searching. cout &lt;&lt; &quot;Time: ~&quot; &lt;&lt; double(clock() - begin) / CLOCKS_PER_SEC &lt;&lt; &quot; seconds.&quot; &lt;&lt; endl; cout &lt;&lt; linear.resA &lt;&lt; &quot;*x^2 + &quot; &lt;&lt; linear.resB &lt;&lt; &quot;x + &quot; &lt;&lt; linear.resC &lt;&lt; endl; //Enter results. } </code></pre> <p>As can see, <code>Linear.LinearRegr</code> function can get from 3 to 5 parameters. I dont need make the code super prettier(for me its already pretty), just want to work it faster.</p> <p><strong>How to optimize and make it faster?</strong></p>
[]
[ { "body": "<p>Couple suggestions</p>\n<h3>Just use <code>std::abs</code></h3>\n<p>It's in the <code>cmath</code> header. It's less about performance, and more about readability. Though it will likely have the same or better performance.</p>\n<h3>Be careful with float, double, and integer constants</h3>\n<p>When working with <code>float</code>, make sure to append <code>f</code> to the end. Like <code>1.0f</code>. If you use <code>double</code>, then you don't need to worry about this. Also, more than likely your target computer has little to no discernible performance difference between <code>float</code> and <code>double</code></p>\n<p>Also, be careful with <code>=</code> comparisons. When using float/double and doing equality operations, you run the issue of having an error and never actually getting perfect equality. Using <code>!</code> on the float is fine, because you should eventually hit <code>0</code> and that will trigger the break.</p>\n<pre><code>// this\nfor (c = minimum; c &lt;= maximum; c += step)\n// should be\nfor (c = minimum; c &lt; maximum; c += step)\n</code></pre>\n<h3>Use a better benchmark</h3>\n<p>I recommend Google Benchmark or quick-bench.com (it's GBench on the backend). You'll be able to see what differences your code is actually making, since it reruns the test to get a more consistent number. Google Benchmark has a lot of fun features so you can see what parameters affect your output</p>\n<h3>Use <code>const &amp;</code> for your input vectors</h3>\n<p>If you're not changing the vectors, make them <code>const refs</code> so the compiler knows it can take shortcuts</p>\n<h3>Know your standard algorithms</h3>\n<p>By rewriting ErrorAv to use <code>std::transform_reduce</code> when I load everything in Godbolt.org, the function appears to be inline</p>\n<pre><code> float ErrorAv(float a, float b, float c, vector&lt;float&gt; const &amp; input, vector&lt;float&gt; const &amp; output) { \n float error = abs(Predict(a, b, c, input[0]) - output[0]);\n return std::transform_reduce(std::next(cbegin(input)),cend(input),std::next(cbegin(output)),error,\n [](auto const &amp; error, auto const &amp; val){\n return (val + error)/2.0;\n }, // &quot;sum function&quot;\n [this,a,b,c](auto const &amp; i, auto const &amp; o){\n return abs(Predict(a, b, c, i) - o);\n }); // &quot;product function&quot;\n }\n</code></pre>\n<p>Since <code>std::transform_reduce</code> is a little strange, I'll try to explain it. Normally it takes two containers, multiplies corresponding elements together, then sums all the products together. You can overload this with lambdas, which is what I'm presenting. <code>std::transform_reduce</code> can be massively parallelized and take advantage of SIMD instructions, so it should provide noticeable speed up. <code>std::transform_reduce</code> lives in the <code>numeric</code> header (for good reason ;)). You'll need to compile for C++17, and if you can't, you can use <code>std::inner_product</code></p>\n<h3>Misc</h3>\n<ul>\n<li><p>Remove the last <code>err = lastError;</code> in your if-statement, in the hot-path of LinearRegr. It's not doing anything.</p>\n</li>\n<li><p>Put the uninitialized floats next to their loop initialization.</p>\n</li>\n</ul>\n<pre><code>// this\n float a,b,c;\n for (a = minimum; a &lt;= maximum; a += step)\n for (b = minimum; b &lt;= maximum; b += step)\n for (c = minimum; c &lt;= maximum; c += step)\n// should be\n for (float a = minimum; a &lt;= maximum; a += step)\n for (float b = minimum; b &lt;= maximum; b += step)\n for (float c = minimum; c &lt;= maximum; c += step)\n</code></pre>\n<h3>Final note</h3>\n<p>While Rosetta code doesn't always have the best code, <a href=\"https://rosettacode.org/wiki/Polynomial_regression#C.2B.2B\" rel=\"nofollow noreferrer\">check out their polynomial regression algorithm which runs in linear time</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:26:35.480", "Id": "252434", "ParentId": "252427", "Score": "2" } }, { "body": "<h1>Optimizing the algorithm</h1>\n<p>If <span class=\"math-container\">\\$M\\$</span> is the number of steps between <code>minimum</code> and <code>maximum</code>, and <span class=\"math-container\">\\$N\\$</span> is the size of the <code>input</code> and <code>output</code> vectors, then your algorithm has complexity <span class=\"math-container\">\\$\\mathcal{O}(N \\cdot M^3)\\$</span>. Also, it likely doesn't find the optimal solution unless you use a very small step size, and you have to choose <code>minimum</code> and <code>maximum</code> correctly. There are other algorithms that will both give you a guaranteed optimal solution without having to specify a range and a step size, and which have complexity <span class=\"math-container\">\\$\\mathcal{O}(N)\\$</span>. This is possible since the problem of <a href=\"https://en.wikipedia.org/wiki/Polynomial_regression#Matrix_form_and_calculation_of_estimates\" rel=\"nofollow noreferrer\">linear least squares</a> can be solved analytically, and can be implemented efficiently on a computer.</p>\n<p>If you don't want to go for the exact mathematical approach, and perhaps want to perform regressions of more complex functions that don't have an exact solution, then you might want to look into algorithms that approach the problem in a smarter way than just brute-forcing all possible values of the parameters. A typical solution to this kind of problem is to implement a <a href=\"https://en.wikipedia.org/wiki/Gradient_descent\" rel=\"nofollow noreferrer\">gradient descent</a> algorithm.</p>\n<h1>Choosing the right error function</h1>\n<p>The way you calculate the error (or rather the <a href=\"https://en.wikipedia.org/wiki/Errors_and_residuals\" rel=\"nofollow noreferrer\">residual</a> to be more precise) is quite strange. Normally one would try to minimize the sum of the squares of the difference between a data point and the predicted value. However, your error function is using the linear difference, and weighting it such that the first datapoint has the least weight, and the last datapoint weighs as much as all the other datapoints combined:</p>\n<pre><code>float error = Module(Predict(a, b, c, input[0]) - output[0]);\nfor (int i = 1; i &lt; input.size(); i++)\n error = (Module(Predict(a, b, c, input[i]) - output[i]) + error)/2;\n</code></pre>\n<p>Unless this is really the intended function, you should probably replace this with a function that calculates the <a href=\"https://en.wikipedia.org/wiki/Least_squares\" rel=\"nofollow noreferrer\">least squares</a> residual.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T15:12:01.213", "Id": "497418", "Score": "0", "body": "@Jenia The code you've posted here does not implement gradient descent." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T11:15:00.770", "Id": "252447", "ParentId": "252427", "Score": "4" } } ]
{ "AcceptedAnswerId": "252434", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T18:09:52.160", "Id": "252427", "Score": "3", "Tags": [ "c++", "performance", "algorithm", "machine-learning" ], "Title": "C++ performance: Linear regression in other way" }
252427
<p>I'm trying to solve <a href="https://www.codewars.com/kata/5679d5a3f2272011d700000d" rel="nofollow noreferrer">a skyscraper puzzle</a> for 6x6 boards using constraint programming and then backtracking. My solution works but is too slow, for certain cases, it takes up to 2 seconds and I was wondering how I could reduce this.</p> <p>Here is the structure of my algorithm:</p> <ol> <li><p>Create board of N size with each element having integers from 1 to 6 denoting all the possibilities ie: <code>[[[1,2,3,4,5,6] , [1,2,3,4,5,6,] , [1,2,3,4,5,6]]] </code> etc</p> </li> <li><p>Using the clues given, fill out values which I am certain of. ie: If clue is 1, then closest element is 6 , if clue is 6 then the row is [1,2,3,4,5,6]</p> </li> <li><p>Cross out possibilities if the value is already in column or row</p> </li> <li><p>If inside one row (or column) a list of possibilities has a value that none of the other have, then it becomes that number: ie: <code>[[1,2,3,4,5,6] , [1,2,3,4,5] , [1,2,3,4,5]]</code> becomes ``` [ 6 , [1,2,3,4,5] , [1,2,3,4,5]]</p> </li> </ol> <p>Finally, I have my backtracking algorithm, which according to Pycharm takes 98% of the time of execution:</p> <pre class="lang-py prettyprint-override"><code>def search(zero, clues, searchBoard): #zeros is a deepcopy of searchboard but with possibilities replaces with 0s ; search board is the board after being processed by first 4 steps find = empty(zero) # Checks for zeroes in a duplicate list findLeast = full(searchBoard) # Checks for elements that have more than one possibility if not find: return True else: row, col = findLeast # Fetches the index of the element with least amount of possibilities val = searchBoard[row][col] for i in val: # loops through those possibilties if is_valid_solution(zero, clues, 6, i, (row, col)): zero[row][col] = i # If the possibilitie works, insert it searchBoard[row][col] = i if search(zero, clues, searchBoard): # recursively do this (backtrack) until no more empty elements in the zeroes duplicate list return True zero[row][col] = 0 # else: reset, try again for different values searchBoard[row][col] = val return False def is_valid_solution(board, clues, n, num, pos): row = [num if i == pos[1] else board[pos[0]][i] for i in range(6)] col = [num if i == pos[0] else board[i][pos[1]] for i in range(6)] if row.count(num) &gt; 1: return False if col.count(num) &gt; 1: return False clue = clues[pos[1]] if clue != 0 and clue not in flatten(col): return False clue = clues[pos[0] + 6] if clue != 0 and clue not in flatten(row[::-1]): return False clue = clues[::-1][pos[1] + 6] if clue != 0 and clue not in flatten(col[::-1]): return False clue = clues[::-1][pos[0]] if clue != 0 and clue not in flatten(row): return False return True def verifyDistance(cell): visible = 0 max = 0 for i in range(len(cell)): if cell[i] &gt; max: visible += 1 max = cell[i] return visible def flatten(incompleted_row): possible_rows = [] d = list({1, 2, 3, 4, 5, 6} - set([x for x in incompleted_row if x != 0])) for perm in permutations(d): row = incompleted_row.copy() for e in perm: row[row.index(0)] = e possible_rows.append(row) possible_clues = set() for r in possible_rows: possible_clues.add(verifyDistance(r)) return list(possible_clues) def empty(puzzle): if 0 in chain.from_iterable(puzzle): return True return None def full(puzzle): pos = [] for i in range(len(puzzle)): # loop through the rows of the puzzle try: pos.append([(i, puzzle[i].index(min((x for x in puzzle[i] if isinstance(x, list)), key=len))), puzzle[i]]) # append the tuple (i , j) where i is the row number and j the column number, and the smallest list of possibilities in each row except ValueError: i += 1 try: champion, champion_len = pos[0][0], len(pos[0][1]) # unpack the pos list into the tuple, and the possibilties except IndexError: return None for t, sl in pos: if len(sl) &lt; champion_len: champion, champion_len = t, len(sl) # look for the smallest number of possibilities and return their index return champion <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:46:02.153", "Id": "497369", "Score": "0", "body": "Please add a description of the skyscraper puzzle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:19:04.367", "Id": "497407", "Score": "0", "body": "@RootTwo , fixed." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T20:24:22.237", "Id": "252431", "Score": "4", "Tags": [ "python", "performance", "algorithm", "python-3.x" ], "Title": "Optimizing recursive backtrack search algorithm in Skyscraper puzzle" }
252431
<p>I often find that when I am writing, refactoring, or reviewing code that I want to do some simple testing. There are many existing test frameworks such as <a href="https://github.com/google/googletest" rel="noreferrer">gtest</a> and <a href="https://sourceforge.net/projects/cppunit/" rel="noreferrer">cppunit</a> but my desire was to create something much simpler and with fewer features.</p> <p>Specifically, I have two use cases in mind:</p> <ol> <li>I have some test input values with known desired outputs</li> <li>I have an existing function that I want to optimize but keep correct</li> </ol> <p>For both of these, I've create a very simple pair of templated objects after studying my own use of such techniques in existing code. In looking at how I use such code, I find that I have three general uses:</p> <ol> <li>I want pretty color printing to the screen with good values in green and bad ones in red</li> <li>I want to redirect the output to a file without the pretty colors</li> <li>I want to run all the tests and just silently get a <code>bool</code> that indicates whether all tests passed</li> </ol> <p>Here are the templates I'd like to get reviewed.</p> <h2>testcase.h</h2> <pre><code>#ifndef EDWARD_TEST_CASE #define EDWARD_TEST_CASE #include &lt;string&gt; #include &lt;string_view&gt; #include &lt;vector&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; namespace edward { static const std::string CSI{&quot;\x1b[&quot;}; static const std::string RED{CSI + &quot;31m&quot;}; static const std::string GREEN{CSI + &quot;32m&quot;}; static const std::string RESET{CSI + &quot;0m&quot;}; static const std::string badgood[2][2]{ { &quot;[BAD] &quot;, &quot;[OK] &quot; }, { RED + &quot;[BAD] &quot; + RESET, GREEN + &quot;[OK] &quot;+ RESET }, }; template &lt;class InputType, class OutputType&gt; class TestCollection { struct TestCase { InputType input; OutputType expected; }; public: TestCollection(OutputType (*testfunc)(InputType), std::vector&lt;TestCase&gt; tests) : testfunc{testfunc} , tests{tests} {} bool testAll(bool verbose = true, bool color = true) const { return verbose ? verboseTest(color) : quietTest(); } private: bool quietTest() const { bool good{true}; for (const auto&amp; t : tests) { good &amp;= (testfunc(t.input) == t.expected); } return good; } bool verboseTest(bool color = true) const { bool good{true}; std::size_t i{0}; for (const auto&amp; t : tests) { auto result = testfunc(t.input); bool isOK = result == t.expected; good &amp;= isOK; std::cout &lt;&lt; badgood[color][isOK] &lt;&lt; &quot;Test #&quot; &lt;&lt; i &lt;&lt; &quot;: &quot; &lt;&lt; std::boolalpha &lt;&lt; &quot;got \&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\&quot;, expected \&quot;&quot; &lt;&lt; t.expected &lt;&lt; &quot;\&quot; from \&quot;&quot; &lt;&lt; t.input &lt;&lt; &quot;\&quot;\n&quot;; } return good; } OutputType (*testfunc)(InputType); std::vector&lt;TestCase&gt; tests; }; template &lt;class InputType, class OutputType&gt; class DynamicTest { public: DynamicTest(OutputType (*testfunc)(InputType), OutputType (*trustedfunc)(InputType)) : testfunc{testfunc} , trustedfunc{trustedfunc} {} bool test(InputType in, bool verbose = true, bool color = true) const { return verbose ? verboseTest(in, color) : quietTest(in); } private: bool quietTest(InputType in) const { return testfunc(in) == trustedfunc(in); } bool verboseTest(InputType in, bool color = true) const { OutputType result{testfunc(in)}; OutputType expected{trustedfunc(in)}; bool isOK{result == expected}; std::cout &lt;&lt; badgood[color][isOK] &lt;&lt; std::boolalpha &lt;&lt; &quot;got \&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\&quot;, expected \&quot;&quot; &lt;&lt; expected &lt;&lt; &quot;\&quot; from \&quot;&quot; &lt;&lt; in &lt;&lt; &quot;\&quot;\n&quot;; return isOK; } OutputType (*testfunc)(InputType); OutputType (*trustedfunc)(InputType); }; }; // end of namespace EDWARD #endif // EDWARD_TEST_CASE </code></pre> <p>Here is some sample test code that exercises both templates and illustrates the intended use. Note that these use this idiom to decide whether or not to print color:</p> <pre><code>bool color{static_cast&lt;bool&gt;(isatty(STDOUT_FILENO))}; </code></pre> <p>This works on Linux (or any POSIX compliant) machines but is not, to my knowledge, portable to Windows. Rather than make the template non-portable, I simply omit it from the templates and rely on the caller. Also note that the printing is only done to <code>std::cout</code> in the template. Here again, I found that it's the only way I used existing code, so I didn't incorporate features I've never used.</p> <h2>main.cpp</h2> <pre><code>#include &quot;testcase.h&quot; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;cmath&gt; #include &lt;functional&gt; #include &lt;unistd.h&gt; bool isInteger(const std::string&amp; n) { if (n.size() &gt; 1) { return std::all_of(n.begin() + 1, n.end(), isdigit) &amp;&amp; (isdigit(n[0]) || (n[0] == '-') || (n[0] == '+')); } return isdigit(n[0]); } void one() { bool verbose{true}; bool color{static_cast&lt;bool&gt;(isatty(STDOUT_FILENO))}; static const edward::TestCollection&lt;const std::string&amp;, bool&gt; tc{ isInteger, { {&quot;+&quot;, false}, {&quot;-&quot;, false}, {&quot;0&quot;, true}, {&quot;3&quot;, true}, {&quot;9&quot;, true}, {&quot;a&quot;, false}, {&quot;99a9&quot;, false}, {&quot;9909&quot;, true}, {&quot;&quot;, false}, {&quot;this test lies&quot;, true}, // deliberately bad test {&quot;-3.14&quot;, false}, {&quot;+32768&quot;, true}, {&quot;-32768&quot;, true}, }}; auto result{tc.testAll(verbose, color)}; std::cout &lt;&lt; &quot;All tests &quot; &lt;&lt; (result ? &quot;passed&quot; : &quot;did NOT pass&quot;) &lt;&lt; &quot;\n&quot;; } int square_it(int x) { return std::pow(x, 2); } void two() { bool verbose{true}; bool color{static_cast&lt;bool&gt;(isatty(STDOUT_FILENO))}; edward::DynamicTest&lt;int, int&gt; dt{[](int x)-&gt;int{return x*x;}, square_it }; bool result{true}; for (int i{-5}; i &lt; 5; ++i) { result &amp;= dt.test(i, verbose, color); } std::cout &lt;&lt; &quot;All tests &quot; &lt;&lt; (result ? &quot;passed&quot; : &quot;did NOT pass&quot;) &lt;&lt; &quot;\n&quot;; } int main() { one(); two(); } </code></pre> <p>I'm interested in a general review.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T23:00:18.450", "Id": "497370", "Score": "1", "body": "`namespace edward` not `namespace Edward`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T23:06:02.950", "Id": "497371", "Score": "1", "body": "@MartinYork Several style guidelines, including [google's](https://google.github.io/styleguide/cppguide.html#Namespace_Names) recommend all lowercase namespace names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T23:16:57.503", "Id": "497372", "Score": "1", "body": "I have seen googles style guide grow and improve over the years. But it was originally so bad I recommended avoiding it so I have not paid it much mind (I suppose it could have improved). But google style guide is designed for their internal use and internal tools so it has a lot of advice that really only has good justification because their internal tools require it. I see no good reason to make namespace lower case. But I don't care if they are either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T00:05:18.323", "Id": "497373", "Score": "3", "body": "Just read through the first few sections. I reject the google style guide as horrible to any project that is not an internal google project. There reasoning on most points are bad and seem to be written by people with little experience with C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T00:15:47.097", "Id": "497376", "Score": "1", "body": "I agree, but `boost` and `std` are also lowercase . It’s arbitrary so I went with the apparent majority." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T14:07:08.880", "Id": "497415", "Score": "0", "body": "Have you tried Doctest or Catch2? I've used both of them with your specific use cases. They're both really light weight and create good test benches." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T16:55:40.460", "Id": "497433", "Score": "0", "body": "If I had to maintain this code after you retired I might have a problem understanding why the namespace is `edward` or `Edward`." } ]
[ { "body": "<h2>C++ 17</h2>\n<p>Why limit yourself to C functions?</p>\n<pre><code>DynamicTest(OutputType (*testfunc)(InputType), OutputType (*trustedfunc)(InputType))\n</code></pre>\n<p>I would declare this as:</p>\n<pre><code>DynamicTest(std::function&lt;OutputType(InputType)&gt;&amp;&amp; testfunc, std::function&lt;OutputType(InputType)&gt;&amp;&amp; trustedfunc)\n</code></pre>\n<p>Also the C++ versions for function declarations are easier to read.</p>\n<hr />\n<p>When passing your test pass by reference and allow both copy and move semantics. Also do you want to force a vetor. Might be better to use an initializer list:</p>\n<pre><code>TestCollection(OutputType (*testfunc)(InputType), std::vector&lt;TestCase&gt; tests)\n// ^^^^^\n</code></pre>\n<p>Pass by value adds an unneeded copy.</p>\n<pre><code>TestCollection(OutputType (*testfunc)(InputType), std::vector&lt;TestCase&gt; const&amp; tests);\nTestCollection(OutputType (*testfunc)(InputType), std::vector&lt;TestCase&gt;&amp;&amp; tests);\nTestCollection(OutputType (*testfunc)(InputType), std::initializer_list&lt;TestCase&gt; const&amp; tests);\n// The last one allows you to build the test cases in place in the constructor.\n</code></pre>\n<hr />\n<p>With only minor modification to the code you factor out the following methods into a base class:</p>\n<pre><code> bool quietTest() const;\n bool verboseTest(bool color = true) const;\n</code></pre>\n<p>I would create a common base class with the following interface:</p>\n<pre><code> template&lt;typename C&gt;\n bool quietTest(C const&amp; tests) const;\n template&lt;typename C&gt;\n bool verboseTest(C const&amp; tests, bool color = true) const;\n</code></pre>\n<p>Then they can be called like this:</p>\n<pre><code>return verbose ? this-&gt;verboseTest(tests, color) : this-&gt;quietTest(tests);\n\n// and\n\nstd::vector&lt;TestCase&gt; data{TestCase{in, trustedfunc(in)}};\nreturn verbose ? this-&gt;verboseTest(data, color) : this-&gt;quietTest(data);\n</code></pre>\n<hr />\n<p>Be consistent.</p>\n<pre><code>namespace edward {\n// STUFF\n}; // end of namespace EDWARD\n\n ^ Don't need the semi-colon.\n</code></pre>\n<p>Be consistent in naming.</p>\n<pre><code>edward or EDWARD\n</code></pre>\n<p>I don't mind the lowercase <code>edward</code> but would avoid <code>EDWARD</code> but they should be the same. Somebody using a less powerful editor may copy and paste the EDWARD into a search to find the begining of the namespace.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T23:14:37.493", "Id": "252437", "ParentId": "252436", "Score": "8" } } ]
{ "AcceptedAnswerId": "252437", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T22:41:19.297", "Id": "252436", "Score": "7", "Tags": [ "c++", "unit-testing", "c++17", "template", "template-meta-programming" ], "Title": "Generic test case templates" }
252436
<p>I am trying to build a simple algorithm to achieve the best combination of values based on two params in an array of objects.</p> <p>The whole code is available <a href="https://codesandbox.io/s/volumetrics-kd9h5?file=/src/App.js" rel="nofollow noreferrer">here</a></p> <p>First I have an array holding objects. The items which will be analyzed and packed into volumes together. All of the values are in percentages.</p> <pre><code>const nonStackableItems = [ { id: 0, m2: 15, m3: 11, weight: 20 }, { id: 1, m2: 25, m3: 12, weight: 42 }, { id: 2, m2: 50, m3: 13, weight: 40 }, { id: 3, m2: 65, m3: 14, weight: 25 } ]; </code></pre> <p>The idea is to combine these objects into packages, respecting the <code>maximum</code> of 100% for each value (except for <code>m3</code> in this case, as all the packages should have enough <code>height</code> in this first analysis).</p> <p>The approach that I gave is just not good enough, as I am sorting this <code>array</code> by <code>m2</code> then by <code>weight</code>, call the <code>function</code> and then compare the length of both, and then choose the result that creates less volumes.</p> <p>This is the piece of code that does the calculations:</p> <pre><code>function nSVolHelper(arr, vol, param1, param2) { let newVol = { id: vol.length, m2: 0, m3: 0, weight: 0 }; for (let i = 0; i &lt; arr.length; i++) { const validation = newVol[param1] + arr[i][param1] &lt; 100 &amp;&amp; newVol[param2] + arr[i][param2] &lt; 100; if (validation) { newVol.m2 += arr[i].m2; newVol.m3 += arr[i].m3; newVol.weight += arr[i].weight; } if (!validation) { return nSVolHelper(arr.slice(i), [...vol, newVol], param1, param2); } } vol.push(newVol); return vol; } function nSVol(arr, param1, param2) { return nSVolHelper(arr, [], param1, param2); } </code></pre> <p>I would like to find a way of doing this without taking as a base the order of the <code>array</code>, to get the finest calculation without running unnecessary code, and I get the feeling that this approach of mine is just not reliable as well.</p> <p>As an example, for better understanding:</p> <p>If I pass the array sorted by <code>weight</code> I get a create 2 volumes.</p> <pre><code>console.log( &quot;call&quot;, nSVol( nonStackableItems.sort((a, b) =&gt; a.weight - b.weight), &quot;weight&quot;, &quot;m2&quot; ) </code></pre> <p>If I pass this same <code>array</code> sorted by <code>m2</code> I get 3 volumes.</p> <pre><code>console.log( &quot;call&quot;, nSVol( nonStackableItems.sort((a, b) =&gt; a.m2 - b.m2), &quot;weight&quot;, &quot;m2&quot; ) </code></pre> <p>This was the best approach that I could find, but I feel that there could be another way of thinking of this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T15:39:12.957", "Id": "497425", "Score": "0", "body": "What is the ideal combination output? Do you want to minimize the number of packages, or does it not matter and you just want to make the current implementation look cleaner?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T04:06:32.307", "Id": "497489", "Score": "0", "body": "@CertainPerformance Thanks for replying me back. I am not so good in math =) I wanna minimize the number of packages, get the most optimized combination of ```params```. Thanks in advance =)" } ]
[ { "body": "<p>You're right that your solution wouldn't be the most accurate. If I'm understanding your question right, what you just described is the Multi-dimensional 0-1 knapsack problem (see the &quot;Multi-dimensional knapsack problem&quot; heading in <a href=\"https://en.wikipedia.org/wiki/Knapsack_problem\" rel=\"nofollow noreferrer\">this</a> wikipedia page). Solving these kinds of problems is not easy for computers to do quickly, and the best algorithm to use can largely depend on the type of data you're expecting to receive.</p>\n<p>Are there very, very few items you're ever going to work with? How important is speed? Can you get away with a simple brute-force method, and try every possibility?</p>\n<p>How much does accuracy matter? Maybe the particular use case doesn't necessarily need the best answer, just a good enough answer. If so, the code you wrote would work just fine.</p>\n<p>Otherwise, I would read up a bit on the knapsack problem, and try googling &quot;Multi-dimensional 0-1 knapsack problem&quot; (multidimensional because you are working with multiple limits, not just weight. 0-1 because you either use the item or you don't, you can't use 1/2 an item in a package). My quick searching showed that there's a number of technical articles out there that address this exact issue. Knowing the name of the algorithm you need should help with finding more resources on it :).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T07:11:07.587", "Id": "253694", "ParentId": "252438", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T01:58:57.233", "Id": "252438", "Score": "2", "Tags": [ "javascript" ], "Title": "Best combination of a sum between two parameters in an array of objects" }
252438
<p>I have a very basic python script that reads a CSV file. I'm importing the csv module setting some empty list variables and getting the data I want. The problem is that I know there is a much more efficient way to get the data I just don't know how to do it and I feel very redundant in creating a reader object multiple times.</p> <p>The goal of the script is to read the csv and extract fields (header) and column cells under it.</p> <p>What I'm doing to accomplish this is creating multiple reader objects and looping each object to extract the data.</p> <p>The csv file is simple and will have more columns in the future:</p> <pre><code>routers,servers 192.168.1.1,10.0.1.1 192.168.1.2,10.0.1.2 </code></pre> <p>The code is simple:</p> <pre><code>import csv filename='Book2.csv' fields=[] rows=[] with open(filename, 'r') as csvfile_field: csvreader_group = csv.reader(csvfile_field) fields=next(csvreader_group) group1=fields[0] group2=fields[1] with open(filename, newline='') as csvfile_row1: csvreader_server = csv.DictReader(csvfile_row1) #print(str(group)) print(group1) for row1 in csvreader_server: server1 = row1[group1] print(server1) print('\n') with open(filename, newline='') as csvfile_row2: csvreader_server = csv.DictReader(csvfile_row2) print(group2) for row2 in csvreader_server: server2 = row2[group2] print(server2) </code></pre> <p>The results are:</p> <pre><code>routers 192.168.1.1 192.168.1.2 servers 10.0.1.1 10.0.1.2 </code></pre> <p>Can someone review this and suggest a more efficient way to extract the data without the opening of the same file multiple times with the same results?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:55:30.690", "Id": "497383", "Score": "1", "body": "Any reason not to parse it as a pandas `DataFrame` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:57:24.150", "Id": "497384", "Score": "0", "body": "I'm open to pandas for sure I even tried it but I couldn't get the results I was looking for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:58:47.433", "Id": "497385", "Score": "0", "body": "You need your output as a string?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:59:10.957", "Id": "497386", "Score": "0", "body": "What are your imports?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:00:27.377", "Id": "497387", "Score": "0", "body": "I'm just importing csv" } ]
[ { "body": "<p>IIUC:</p>\n<pre><code>df = pd.read_csv(filename)\nfor col in df:\n print(col,'\\n','\\n'.join[i for i in df[col]])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:54:39.327", "Id": "497388", "Score": "0", "body": "thank you for adding the pandas option" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:01:01.447", "Id": "252442", "ParentId": "252441", "Score": "0" } }, { "body": "<p>Here's how I would do it, without Pandas:</p>\n<pre><code>import csv\n\nfilename = 'Book2.csv'\n\nwith open(filename, 'r') as csvfile:\n reader = csv.reader(csvfile)\n fields = next(reader) # Reads header row as a list\n rows = list(reader) # Reads all subsequent rows as a list of lists\n\nfor column_number, field in enumerate(fields): # (0, routers), (1, servers)\n print(field)\n for row in rows:\n print(row[column_number])\n print('\\n')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:52:23.017", "Id": "497389", "Score": "0", "body": "thank you this one makes a lot of sense thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T20:02:37.887", "Id": "252443", "ParentId": "252441", "Score": "3" } } ]
{ "AcceptedAnswerId": "252443", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:54:26.523", "Id": "252441", "Score": "2", "Tags": [ "python", "python-3.x", "csv" ], "Title": "Python script to extract columns from a CSV file" }
252441
<p>I have 7000 CSV files that I want to do operation on. but the problem is that it takes to much time like it takes 13 seconds to process these files. What I need to know is which operation take more time.</p> <ol> <li>Opening and closing the files?</li> <li>Reading data from these files?</li> </ol> <p>I want to convert this program into multithreading or may be multiprocessing to achieve the goal. What would you suggest?</p> <ol> <li>MultiThreading in Python</li> <li>Multiprocessing in Python</li> <li>other</li> </ol> <pre><code>import time import os import sys import threading import concurrent.futures import locale locale.setlocale(locale.LC_ALL, '') no_of_files=0 def files_path(directory): global no_of_files file_path_list=[] for filename in sorted(os.listdir(directory)): if filename.endswith(&quot;.csv&quot;): no_of_files+=1 file_path = os.path.join(directory, filename) file_path_list.append(file_path) return file_path_list def process_file(file_path): file=open(file_path,'r') lines = 0 sum_of_lines=0 number_of_characters=0 for line in file: number_of_characters=len(line)+number_of_characters lines=lines+1 sum_of_lines=sum_of_lines+1 file.close() lines = ('{0:n}'.format(int(lines))) number_of_characters = '{0:n}'.format(int(number_of_characters)) print(str(file_path.split(&quot;/&quot;)[2])) print(&quot;\t&quot; + &quot;|Number of lines : &quot; + &quot;\t&quot; + &quot;\t&quot; + str(lines)) print(&quot;\t&quot; + &quot;|Number of characters : &quot; + &quot;\t&quot; + &quot;\t&quot; + str(number_of_characters)) if __name__ == '__main__': s=time.time() for i in range(320): directory = 'D:/Tickers/' all_files= files_path(directory) for file_path in all_files: process_file(file_path) e=time.time() print(f&quot;{no_of_files} takes {e-s}&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T13:24:37.413", "Id": "497412", "Score": "3", "body": "Welcome to Code Review! To help reviewers give you better answers, please add sufficient context to your question. Describe *what* the program is doing and *why* (that is, the purpose of the program). Better descriptions lead to better reviews! [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)" } ]
[ { "body": "<p><code>multiprocessing</code> might be a desirable approach in your case:</p>\n<p>You need to modify your <code>__main__</code> function to below:</p>\n<pre><code>from multiprocessing import Pool\n\nif __name__ == '__main__':\n s = time.time()\n directory = 'D:/Tickers/'\n all_files = files_path(directory)\n \n pool_file_list = []\n for _ in range(320):\n pool_file_list.extend(all_files)\n \n pool = Pool(os.cpu_count())\n pool.map(process_file, pool_file_list)\n \n pool.close()\n pool.join()\n \n e = time.time()\n print(f&quot;{no_of_files} takes {e - s}&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:11:44.973", "Id": "497402", "Score": "0", "body": "Should i import some package in order to run the Pool FUnction?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:12:54.503", "Id": "497403", "Score": "0", "body": "`from multiprocessing import Pool`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:13:09.533", "Id": "497404", "Score": "0", "body": "Updated in the answer, too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:14:09.983", "Id": "497405", "Score": "0", "body": "can you please explain a little bit these lines it will help me a lot. thank you so much for your time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:16:31.707", "Id": "497406", "Score": "0", "body": "You are just splitting your tasks across multiple cores on your machine. So, say you have 8 cores; you would ideally see 8x improvement" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:00:10.857", "Id": "252449", "ParentId": "252448", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T11:48:38.630", "Id": "252448", "Score": "-4", "Tags": [ "python", "python-3.x", "programming-challenge", "pandas", "multiprocessing" ], "Title": "How can I reduce the TIme Complexity. of the python program" }
252448
<p>I have two csv files, <code>pricat.csv</code> which contains objects I need to populate my DB with, and <code>mapping.csv</code> which specifies how the value in <code>pricat.csv</code> must be displayed in my DB, for ex: <code>'NW 17-18'</code> in <code>pricat.csv</code> has to be <code>'Winter Collection 2017/2018'</code> in my DB. Here the csvs, first row in both are the headers:</p> <pre><code>ean;supplier;brand;catalog_code;collection;season;article_structure_code;article_number;article_number_2;article_number_3;color_code;size_group_code;size_code;size_name;currency;price_buy_gross;price_buy_net;discount_rate;price_sell;material;target_area 8719245200978;Rupesco BV;Via Vai;;NW 17-18;winter;10;15189-02;15189-02 Aviation Nero;Aviation;1;EU;38;38;EUR;;58.5;;139.95;Aviation;Woman Shoes 8719245200985;Rupesco BV;Via Vai;;NW 17-18;winter;10;15189-02;15189-02 Aviation Nero;Aviation;1;EU;39;39;EUR;;58.5;;139.95;Aviation;Woman Shoes </code></pre> <h1></h1> <pre><code>source;destination;source_type;destination_type winter;Winter;season;season summer;Summer;season;season NW 17-18;Winter Collection 2017/2018;collection;collection EU;European sizes;size_group_code;size_group EU|36;European size 36;size_group_code|size_code;size EU|37;European size 37;size_group_code|size_code;size EU|38;European size 38;size_group_code|size_code;size EU|39;European size 39;size_group_code|size_code;size EU|40;European size 40;size_group_code|size_code;size EU|41;European size 41;size_group_code|size_code;size EU|42;European size 42;size_group_code|size_code;size 4;Boot;article_structure_code;article_structure 5;Sneaker;article_structure_code;article_structure 6;Slipper;article_structure_code;article_structure 7;Loafer;article_structure_code;article_structure 8;Mocassin;article_structure_code;article_structure 9;Sandal;article_structure_code;article_structure 10;Pump;article_structure_code;article_structure 1;Nero;color_code;color 2;Marrone;color_code;color 3;Brandy Nero;color_code;color 4;Indaco Nero;color_code;color 5;Fucile;color_code;color 6;Bosco Nero;color_code;color </code></pre> <p>In my <code>models.py</code> in Django I have three models: <code>Catalog</code> --&gt; <code>Article</code> --&gt; <code>Variation</code> the attributes of my models are manually named as <code>mapping.csv</code> specifies, for ex: <code>Variation</code> will not have a <code>color_code</code> attribute but <code>color</code>. To populate the DB I've created a custom Django command which reads the rows in <code>pricat.csv</code> and create istances like this:</p> <pre class="lang-py prettyprint-override"><code>x = Catalog.objects.get_or_create(brand=info[2], supplier=info[1], catalog_code=info[3], collection=map_dict[info[4]], season=map_dict[info[5]], size_group=map_dict[info[11]], currency=info[14], target_area=info[20]) y = Article.objects.get_or_create(article_structure=map_dict[info[6]], article_number=info[7], catalog=x[0]) z = Variation.objects.get_or_create(ean=info[0], article=y[0], size_code=info[12], color=map_col[info[10]], material=info[19], price_buy_gross=info[15], price_buy_net=info[16], discount_rate=info[17], price_sell=info[18], size=f'{map_dict[info[11]]} {info[12]}') </code></pre> <p><code>info</code> is a list of all the value in a <code>pricat.csv</code> row and <code>map_dict</code> and <code>map_col</code> are two dictionaries I create with two func() from the <code>mapping.csv</code>:</p> <pre class="lang-py prettyprint-override"><code>def mapping(map_file): with open(map_file, 'r') as f: f = [l.strip('\n') for l in f] map_dict = {} for l in f[1:19]: info = l.strip().split(';') source = info[0] destination = info[1] source_type = info[2] destination_type = info[3] map_dict[source] = destination map_dict[source_type] = destination_type return map_dict def mapping_color(map_file): with open(map_file, 'r') as f: f = [l.strip('\n') for l in f] map_dict = {} for l in f[19:]: info = l.strip().split(';') source = info[0] destination = info[1] source_type = info[2] destination_type = info[3] map_dict[source] = destination map_dict[source_type] = destination_type return map_dict map_dict = mapping('mapping.csv') map_col = mapping_color('mapping.csv') </code></pre> <p>I had to create two dict because a single one would have duplicate keys.</p> <p>The code works fine and the DB is populated as intended, but I feel the way I did the mapping is bad practice, also both my command and funcs relies on indeces so the values in my csvs have to be in that specific order to work. I would greatly appreciate any suggestion on how to improve my code or accomplish this task, I hope my explanation is clear.</p> <p>EDIT:</p> <pre class="lang-py prettyprint-override"><code>class Catalog(models.Model): brand = models.CharField(max_length=255) supplier = models.CharField(max_length=255) catalog_code = models.CharField(max_length=255, default=1, blank=True) collection = models.CharField(max_length=255) season = models.CharField(max_length=255) size_group = models.CharField(max_length=2) currency = models.CharField(max_length=3) target_area = models.CharField(max_length=255) def __str__(self): return self.brand def get_articles(self): return Article.objects.filter(catalog=self.pk) class Article(models.Model): article_structure = models.CharField(max_length=255) article_number = models.CharField(max_length=255) catalog = models.ForeignKey(Catalog, on_delete=models.CASCADE) def __str__(self): return f'{self.article_number} | {self.article_structure}' class Variation(models.Model): ean = models.CharField(max_length=255) article = models.ForeignKey(Article, on_delete=models.CASCADE) size_code = models.IntegerField() size = models.CharField(max_length=255, default=0) color = models.CharField(max_length=255) material = models.CharField(max_length=255) price_buy_gross = models.CharField(max_length=255) price_buy_net = models.FloatField() discount_rate = models.CharField(max_length=255, default=0) price_sell = models.FloatField() def __str__(self): return f'Ean: {self.ean}, article: {self.article}' </code></pre> <p>I've created a new <code>mapping()</code></p> <pre><code>def mapping(map_file): with open(map_file, 'r') as f: f = [l.strip('\n') for l in f] map_dict = {} for l in f[1:]: info = l.strip().split(';') source = info[0] destination = info[1] source_type = info[2] child_dict = {source: destination} map_dict[source_type] = map_dict.get(source_type, {source: destination}) map_dict[source_type].update(child_dict) return map_dict </code></pre> <p>It returns a nested dict, I'm trying to finda solution using this single nested dict instead of 2 dicts like before.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T17:13:29.200", "Id": "497437", "Score": "1", "body": "Please show more of your code, particularly the model classes for Catalog --> Article --> Variation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T17:24:41.357", "Id": "497440", "Score": "0", "body": "classes added @Reinderien" } ]
[ { "body": "<p>You can use the built-in <a href=\"https://docs.python.org/3/library/csv.html#csv.DictReader\" rel=\"nofollow noreferrer\">csv.DictReader</a> to easily create dictionaries from CSV files. How about this?</p>\n<pre><code>import csv\n\ndef create_mapping(map_file):\n with open(map_file) as csvfile:\n reader = csv.DictReader(csvfile, delimiter=';')\n mapping = {row['source']: row['destination'] \n for row in reader \n if row['source_type'] != 'color_code'}\n return mapping\n\nmap_dict = create_mapping('mapping.csv')\n</code></pre>\n<p>We are using <a href=\"https://docs.python.org/3.3/tutorial/datastructures.html?highlight=list%20comprehension#dictionaries\" rel=\"nofollow noreferrer\">dictionary comprehension</a> to create the dictionary.\nYou can do something similar for colors, then you want to have all the rows where <code>source_type</code> equals <code>color_code</code> (so <code>==</code> instead of <code>!=</code>). But perhaps it is a better idea put the color mappings into a different file. Furthermore, if you process the <code>pricat.csv</code> in a similar fashion:</p>\n<pre><code>with open('pricat.csv') as csvfile:\n reader = csv.DictReader(csvfile, delimiter=';')\n for row in reader:\n # process row \n</code></pre>\n<p>You'll be able to use the rows as dictionaries:</p>\n<pre><code>{'ean': '8719245200985',\n 'supplier': 'Rupesco BV',\n 'brand': 'Via Vai',\n 'catalog_code': '',\n 'collection': 'NW 17-18',\n 'season': 'winter',\n 'article_structure_code': '10',\n 'article_number': '15189-02',\n 'article_number_2': '15189-02 Aviation Nero',\n 'article_number_3': 'Aviation',\n 'color_code': '1',\n 'size_group_code': 'EU',\n 'size_code': '39',\n 'size_name': '39',\n 'currency': 'EUR',\n 'price_buy_gross': '',\n 'price_buy_net': '58.5',\n 'discount_rate': '',\n 'price_sell': '139.95',\n 'material': 'Aviation',\n 'target_area': 'Woman Shoes'}\n</code></pre>\n<p>So you can do something like:</p>\n<pre><code>y = Article.objects.get_or_create(article_structure=map_dict[row['article_structure_code']],\n article_number=row['article_number'], catalog=x[0])\n</code></pre>\n<p>This can still be refactored a bit, but now you are no longer dependent on the column numbers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T16:30:43.910", "Id": "497528", "Score": "0", "body": "Hi! I changed my mapping() (let me know what you think about it) but your use of csv.DictReader gave me a great insight and I think I'm going to come up with a very nice solution soon, if it works I'll accept your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T15:39:11.733", "Id": "252486", "ParentId": "252450", "Score": "3" } }, { "body": "<pre><code>class Command(BaseCommand):\n help = 'Create a catalog, accept csv as argument'\n\n def add_arguments(self, parser):\n parser.add_argument('file', nargs='+', type=str)\n parser.add_argument('map', nargs='+', type=str)\n\n def handle(self, *args, **options):\n\n map_dict = mapping(options['map'][0])\n\n with open(options['file'][0], 'r') as f:\n reader = csv.DictReader(f, delimiter=';')\n for row in reader:\n\n x = Catalog.objects.get_or_create(brand=row['brand'], supplier=row['supplier'],\n catalog_code=row['catalog_code'],\n collection=map_dict['collection'][row['collection']],\n season=map_dict['season'][row['season']],\n size_group=map_dict['size_group_code'][row['size_group_code']],\n currency=row['currency'], target_area=row['target_area'])\n if x[1]:\n logger_catalog.info(f'Created Catalog instance {x[0]}')\n y = Article.objects.get_or_create(article_structure=map_dict['article_structure_code'][row['article_structure_code']],\n article_number=row['article_number'], catalog=x[0])\n if y[1]:\n logger_catalog.info(f'Created Article instance {y[0]}')\n z = Variation.objects.get_or_create(ean=row['ean'], article=y[0], size_code=row['size_code'],\n color=map_dict['color_code'][row['color_code']],\n material=row['material'], price_buy_gross=row['price_buy_gross'],\n price_buy_net=row['price_buy_net'],\n discount_rate=row['discount_rate'], price_sell=row['price_sell'],\n size=map_dict['size_group_code|size_code'][f&quot;{row['size_group_code']}|{row['size_code']}&quot;])\n if z[1]:\n logger_catalog.info(f'Created Variation instance {z[0]}')\n</code></pre>\n<p>Finally I remake my Command, now it's indipendent from indeces so it will correctly populate the database even if the colums in the csv are in a different order.</p>\n<p>My mapping() func (see question) returns a nested dict, the keys of the parent dict are the columns names that need to be mapped and the values are dicts with this structure:<br />\n<code>{value_presented_in_csv: how_value_should_be_presented_in_DB}</code>.</p>\n<p>In my <code>Command</code> I iterate through each row of <code>pricat.csv</code> turning rows in dicts <code>{colum_name: value_presented_in_csv}</code>, if the data don't need to be mapped I get the value from my <code>row</code> dict like <code>brand=row['brand']</code>, if the data need to be mapped I get the value from my nested dict <code>map_dict</code> like this <code>map_dict[column_name][value_presented_in_csv]</code> (this gives me the value of the child dict that is <code>how_value_should_be_presented_in_DB</code>).</p>\n<p>It is better because doesn't relies on indeces no more, my first implementation works correctly only if the columns in <code>pricat.csv</code> are in that precise order;\nwith this new implementation the columns can be in any order and the DB would still be populate correctly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T18:31:02.047", "Id": "252494", "ParentId": "252450", "Score": "0" } } ]
{ "AcceptedAnswerId": "252486", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T12:13:03.760", "Id": "252450", "Score": "5", "Tags": [ "python", "csv", "django" ], "Title": "Mapping column names and values of a csv using another csv" }
252450
<p>I am learning typescript with React and come up with this small program that each button count how many time by clicking and record which button got click. Please help me to take a look if all the code are the best practice.</p> <pre><code>import * as React from &quot;react&quot;; import &quot;./styles.css&quot;; interface ButtonContainerProps { options: string[]; } interface ButtonProps { value: string; setSelectedOption(value: string): any; } const Button: React.FunctionComponent&lt;ButtonProps&gt; = (props): JSX.Element =&gt; { const { value, setSelectedOption } = props; const [count, setCount] = React.useState(0); const clickHandler = React.useCallback(() =&gt; { setCount(count + 1); setSelectedOption(value); }, [count, value, setSelectedOption]); return &lt;button onClick={clickHandler}&gt;{`${value}: ${count}`}&lt;/button&gt;; }; const Scoreboard: React.FunctionComponent&lt;{ selectedOption: null | string; }&gt; = ({ selectedOption }): JSX.Element =&gt; { return ( &lt;h2&gt; {selectedOption ? `The selected option is ${selectedOption}` : `Please click following button to make an option`} &lt;/h2&gt; ); }; const ButtonContainer: React.FunctionComponent&lt;ButtonContainerProps&gt; = ({ options }): JSX.Element =&gt; { const [selectedOption, setSelectedOption] = React.useState&lt;string | null&gt;( null ); return ( &lt;div&gt; &lt;Scoreboard selectedOption={selectedOption} /&gt; {options.map((option) =&gt; ( &lt;Button key={option} value={option} setSelectedOption={setSelectedOption} /&gt; ))} &lt;/div&gt; ); }; export default function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;h1&gt;Button Container&lt;/h1&gt; &lt;ButtonContainer options={[&quot;apple&quot;, &quot;orange&quot;, &quot;pear&quot;]} /&gt; &lt;/div&gt; ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T07:41:19.917", "Id": "497500", "Score": "1", "body": "Please do not update or remove the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question or can anonymize it after the fact. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p><strong><code>React.FunctionComponent</code> probably isn't necessary</strong> - it's boilerplate for every single component you have, and arguably makes typings a bit <em>worse</em>, not better. <a href=\"https://fettblog.eu/typescript-react-why-i-dont-use-react-fc/\" rel=\"nofollow noreferrer\">See this article</a>. For example, you could accidentally do:</p>\n<pre><code>&lt;Scoreboard selectedOption={selectedOption}&gt;{'The Scoreboard'}&lt;/Scoreboard&gt;\n</code></pre>\n<p>without an error being thrown because every <code>React.FunctionComponent</code> is typed as taking children, even if they're not used.</p>\n<p>To make the types more accurate, and to reduce the amount of boilerplate, consider using completely plain functions instead.</p>\n<p><strong>Declare variables close to where they'll be used</strong> The <code>ButtonContainerProps</code> is declared at the top of the script, but it isn't used until you scroll past 2 intermediate components - so if you see</p>\n<pre><code>const ButtonContainer: React.FunctionComponent&lt;ButtonContainerProps&gt; = ({\n</code></pre>\n<p>and you don't remember what <code>ButtonContainerProps</code> is, you'll have to scroll all the way back up to the top to see what it is. Or, even better:</p>\n<p><strong>If something is only going to be used once, consider whether it can be reasonably defined inline</strong>. For example:</p>\n<pre><code>const ButtonContainer: ({ options }: { options: string[] }) =&gt; {\n</code></pre>\n<p>I think that's plenty clear.</p>\n<p><strong>Let TS automatically infer return types</strong> when possible - unless explicitly typing a value is necessary to make the TS compile, or to make it easier for a reader to understand, you consider just leaving it off, like with the above <code>ButtonContainer</code>, since the boilerplate doesn't accomplish much. The capitalization of a component should make it clear that the function is a component that returns JSX.</p>\n<p><strong>Possible duplicate key</strong> It's probably pretty unlikely, but if the caller of <code>ButtonContainer</code> passes an array of strings that contains a duplicate, the <code>&lt;Button key={option}</code> will result in a duplicate key, which is a problem. If the buttons are completely static in the DOM, I'd make the <code>key</code> be the <em>index</em> of the element in the <code>options</code>:</p>\n<pre><code>{options.map((option, i) =&gt; (\n &lt;Button\n key={i}\n</code></pre>\n<p>Or filter out duplicates from the <code>options</code> before rendering.</p>\n<p><strong><code>value</code> name?</strong> One might normally expect a variable named <code>value</code> to contain something from the user that might change, like something in an input box, or a count of something. Here, the <code>value</code> being passed to <code>Button</code> is actually a <em>name</em> or label connected to the button (and the use of <code>value</code> alongside a stateful <code>count</code> variable might seem odd). Consider renaming it to <code>name</code> or <code>buttonLabel</code> or something of the sort. (Probably not <code>option</code>, since it's not related to <code>&lt;option&gt;</code>)</p>\n<p><strong><code>useCallback</code></strong> is useful when optimizing performance and reducing unnecessary re-renders when passing the callback as a prop to a child component. But here, there's just a <code>&lt;button&gt;</code> (not a child component) which'll only change on click (won't update frequently enough for the overhead of a function call to matter at all). The <code>useCallback</code> is introducing complication without accomplishing anything useful here; I'd consider removing it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T15:29:24.057", "Id": "252457", "ParentId": "252452", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T13:04:40.490", "Id": "252452", "Score": "1", "Tags": [ "react.js", "typescript" ], "Title": "Small Counter by typescript with React" }
252452
<p>I did a small countdown clock challenge in JavaScript. Please review it, thanks.</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 timeControls = document.querySelector('.timer__controls'); const timeLeft = document.querySelector('.display__time-left'); const endTime = document.querySelector('.display__end-time'); let interval; function secondsToHourMinSec(seconds) { const date = new Date(0); date.setSeconds(seconds); return date.toISOString().substr(11, 8); } function advanceCurrentTime(seconds) { const date = new Date(0); date.setSeconds(Math.floor(Date.now() / 1000) + seconds); return date.toLocaleTimeString().substr(0, 7); } function displayRemainingTime(seconds) { timeLeft.textContent = secondsToHourMinSec(seconds); } function displayEndTime(seconds) { endTime.textContent = `Be back at ${advanceCurrentTime(seconds)}`; } function displayTime(seconds) { displayRemainingTime(seconds); displayEndTime(seconds); interval = setInterval(function() { seconds--; if (seconds &lt; 0) { clearInterval(interval); return; } displayRemainingTime(seconds); }, 1000); } function startTimer(seconds) { clearInterval(interval); displayTime(seconds); } timeControls.addEventListener('click', e =&gt; { const button = e.target.closest('button'); if (button) startTimer(parseInt(button.dataset.time)); }); document.customForm.addEventListener('submit', function(e) { e.preventDefault(); const value = this.minutes.value; if (value.length !== 0) startTimer(parseInt(value) * 60); this.reset(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html { box-sizing: border-box; font-size: 10px; background: #8e24aa; background: linear-gradient(45deg, #42a5f5 0%, #478ed1 50%, #0d47a1 100%); } *, *:before, *:after { box-sizing: inherit; } body { margin: 0; text-align: center; font-family: "Inconsolata", monospace; } .display__time-left { font-weight: 100; font-size: 20rem; margin: 0; color: white; text-shadow: 4px 4px 0 rgba(0, 0, 0, 0.05); } .timer { display: flex; min-height: 100vh; flex-direction: column; } .timer__controls { display: flex; } .timer__controls&gt;* { flex: 1; } .timer__controls form { flex: 1; display: flex; } .timer__controls input { flex: 1; border: 0; padding: 2rem; } .timer__button { background: none; border: 0; cursor: pointer; color: white; font-size: 2rem; text-transform: uppercase; background: rgba(0, 0, 0, 0.1); border-bottom: 3px solid rgba(0, 0, 0, 0.2); border-right: 1px solid rgba(0, 0, 0, 0.2); padding: 1rem; font-family: "Inconsolata", monospace; } .timer__button:hover, .timer__button:focus { background: rgba(0, 0, 0, 0.2); outline: 0; } .display { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; } .display__end-time { font-size: 4rem; color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Countdown Timer&lt;/title&gt; &lt;link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css"&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="timer"&gt; &lt;div class="timer__controls"&gt; &lt;button data-time="20" class="timer__button"&gt;20 Secs&lt;/button&gt; &lt;button data-time="300" class="timer__button"&gt;Work 5&lt;/button&gt; &lt;button data-time="900" class="timer__button"&gt;Quick 15&lt;/button&gt; &lt;button data-time="1200" class="timer__button"&gt;Snack 20&lt;/button&gt; &lt;button data-time="3600" class="timer__button"&gt;Lunch Break&lt;/button&gt; &lt;form name="customForm" id="custom"&gt; &lt;input type="text" name="minutes" placeholder="Enter Minutes"&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="display"&gt; &lt;h1 class="display__time-left"&gt;&lt;/h1&gt; &lt;p class="display__end-time"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="scripts.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T14:44:55.270", "Id": "497417", "Score": "0", "body": "Looks great to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T15:38:00.547", "Id": "497424", "Score": "0", "body": "@CertainPerformance thanks" } ]
[ { "body": "<p>I have the following ideas for improvement of your code:</p>\n<ul>\n<li>Separate different concepts like timers and UI rendering to make them easy to understand and change.</li>\n<li>Use milliseconds for consistency with browser API.</li>\n<li>Separate formatting and calculation for dates and durations.</li>\n<li>Incapsulate mutable state in objects so it won't leak in your main application logic (<code>let interval</code>).</li>\n<li>Don't use the <code>substr</code> function to format time because this solution is not robust. Write custom formatter or use a library like <a href=\"https://momentjs.com/\" rel=\"nofollow noreferrer\">momentjs</a> instead.</li>\n</ul>\n<p>Here is my solution:</p>\n<pre><code>class Timer {\n constructor(duration, delay = 1000) {\n this._remaining = duration;\n this._delay = delay;\n this._callbacks = [];\n }\n\n start() {\n this._intervalId = setInterval(this._tick.bind(this), this._delay);\n }\n\n stop() {\n clearInterval(this._intervalId);\n }\n\n onTick(callback) {\n this._callbacks.push(callback);\n }\n\n _tick() {\n this._remaining -= this._delay;\n if (this._remaining &lt;= 0) this.stop();\n this._callbacks.forEach((cb) =&gt; cb(this._remaining));\n }\n}\n\nclass Timers {\n makeActive(timer) {\n this._activeTimer = timer;\n }\n\n stopActive() {\n if (this._activeTimer) this._activeTimer.stop();\n }\n}\n\n// I didn't change formatting implementation here because I am lazy\nconst formatHMS = (date) =&gt; date.toISOString().substr(11, 8);\nconst formatLocaleHMS = (date) =&gt; date.toLocaleTimeString().substr(0, 8);\n\nconst dateIn = (duration) =&gt; {\n const date = new Date(0);\n date.setMilliseconds(Date.now() + duration);\n return date;\n}\n\nconst durationToDate = (duration) =&gt; {\n const date = new Date(0);\n date.setMilliseconds(duration);\n return date;\n}\n\nconst timeControls = document.querySelector('.timer__controls');\nconst timeLeft = document.querySelector('.display__time-left');\nconst endTime = document.querySelector('.display__end-time');\n\nconst displayRemaining = (duration) =&gt; {\n timeLeft.textContent = formatHMS(durationToDate(duration));\n}\n\nconst displayEnd = (duration) =&gt; {\n endTime.textContent = `Be back at ${formatLocaleHMS(dateIn(duration))}`;\n}\n\nconst timers = new Timers();\n\nconst startAndUpdate = (duration) =&gt; {\n displayRemaining(duration);\n displayEnd(duration);\n\n const timer = new Timer(duration);\n timer.start();\n timer.onTick(displayRemaining);\n\n timers.stopActive();\n timers.makeActive(timer);\n};\n\nconst secondsToMs = (seconds) =&gt; seconds * 1000;\ntimeControls.addEventListener('click', (e) =&gt; {\n const button = e.target.closest('button');\n if (button) startAndUpdate(secondsToMs(parseInt(button.dataset.time)));\n});\n\nconst minutesToMs = (minutes) =&gt; secondsToMs(minutes * 60);\ndocument.customForm.addEventListener('submit', function (e) {\n e.preventDefault();\n const value = this.minutes.value;\n if (value !== '') startAndUpdate(minutesToMs(parseInt(value)));\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T12:09:11.417", "Id": "497515", "Score": "1", "body": "Using underscore to indicate private properties (though popular) is unsafe and is poor naming. Private must be enforced at a language level or it is pointless. Without enforcement you can not trust state and thus must code accordingly (you should consider them pubic and untrustable)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T13:47:32.140", "Id": "497523", "Score": "0", "body": "@Blindman67 it's just a convention because Javascript doesn't have private visibility. Actually, you can enforce it with a linter. What is your solution to this problem in Javascript?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T14:06:10.997", "Id": "497524", "Score": "2", "body": "I use closure inside object factories with heavy reliance on getters and setters to ensure a trustable state. The reason I made a comment is that the interval timer handle once lost can not be rediscovered (well not easily, it can be guessed but at the risk of stopping other intervals) . As the code stands the interval timer represents a potential memory leak. Consider using `setTimeout`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T14:14:02.343", "Id": "497525", "Score": "0", "body": "@Blindman67 so are you saying that because `_intervalId ` is public anyone can change it and the handler can be lost?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T14:25:08.477", "Id": "497526", "Score": "1", "body": "Yes and that loss is unrecoverable, a memory leak." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T06:40:52.117", "Id": "497586", "Score": "0", "body": "@Blindman67 I rewrote the implementation for the timer with closure and posted it https://jsfiddle.net/segf84uz/. Is that it? I like it more than class implementation too but it has one drawback — each object instance has a unique set of functions (they are not shared across all objects)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T08:52:26.137", "Id": "497591", "Score": "1", "body": "Looks good. When defining objects one must consider the number of instances and how often these instances are created. Parsed functions are cached on all but the oldest browsers and closure across the functions is the shared factory's scope This question's requirements are for a single instance and as such there will be no additional overhead when compared to class syntax. I find that only when creating 1000's of objects per second (animations) does the class (prototype) syntax offer any detectable performance benefit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T09:23:10.953", "Id": "497592", "Score": "1", "body": "@Blindman67 thank you for the advice. I will stick to the mutable state in closure in the future instead of using classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T03:02:33.767", "Id": "498204", "Score": "0", "body": "@blindman67 setTimeOut is also not a great alternative as it uses the unsafe eval() function under the hood.. https://idiallo.com/javascript/settimeout-and-setinterval-and-setevil" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T03:27:36.370", "Id": "498205", "Score": "0", "body": "@RyanStone Only if you pass it a string," } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T09:53:40.830", "Id": "252476", "ParentId": "252455", "Score": "0" } } ]
{ "AcceptedAnswerId": "252476", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T14:19:34.220", "Id": "252455", "Score": "2", "Tags": [ "javascript", "datetime" ], "Title": "Countdown click in JavaScript" }
252455
<p>I am trying to create class with connect to mysql database. And if there is max number of connections I want to wait and try it again. I figured out, how it can works, but I am not sure, if its the right way of doing it. So, my code looks like this:</p> <pre><code>&lt;?php class DbConnect { private $attemps = 1; private $errorCode; private $maxAttemps = 10; private $pdo; private $dsn = &quot;mysql:host=localhost;dbname=...;charset=utf8&quot;; private $options = [ PDO::ATTR_EMULATE_PREPARES =&gt; false, // turn off emulation mode for &quot;real&quot; prepared statements PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions /*PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC,*/ //make the default fetch be an associative array ]; public function __construct(){ $this-&gt;tryConnect(); while ($this-&gt;errorCode == 1040 &amp;&amp; $this-&gt;attemps &lt;= $this-&gt;maxAttemps) { usleep(pow(2, $this-&gt;attemps)*10000); $this-&gt;tryConnect(); } } protected function tryConnect(){ try { $this-&gt;pdo = new PDO($this-&gt;dsn, &quot;root&quot;, &quot;&quot;, $this-&gt;options); } catch (Exception $e) { error_log($e-&gt;getMessage()); $this-&gt;errorCode = $e-&gt;getCode(); $this-&gt;attemps++; } } } ?&gt; </code></pre> <p>Is there anything i should change? Thank you very much.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T06:18:43.547", "Id": "497496", "Score": "1", "body": "The class has no methods to work with the open connection. And if the connection fails 10 times it claims to have succeeded but actually it is not connected. So I would say the code does not work correctly and the question is probably missing some context..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T06:27:00.043", "Id": "497497", "Score": "1", "body": "Anyway, if connection pool is full you probably don't want php request processes to stack up and make even larger queue for open db connections. The 10 attempts can take up to cca 20 seconds, if client closes the connection, the server does not, and so the php process keeps waiting for db although there is nobody waiting for data any more. This might be a good thing in a background task that never runs multiple times simultaneously. But not for a client request handler. At least not in general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T09:40:49.003", "Id": "497505", "Score": "0", "body": "I can add public property which will contain if its connected or not and cut connection with set new Db object to null. I understand what you mean, but I have no idea how to make queue on server and then tell clients to connect, because its normall web hosting.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T09:56:20.967", "Id": "497506", "Score": "1", "body": "You better just inform the client that you cannot fulfill their request (with a 5xx response status) and have them retry later at their own will. Most users probably won't wait for the page to load after few seconds of nothing happening. They will just hit f5 or navigate away not knowing what's wrong, probably thinking the page is broken and never coming back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T10:01:25.130", "Id": "497509", "Score": "0", "body": "You think 509 Bandwidth Limit Exceeded (Apache)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T10:05:22.313", "Id": "497510", "Score": "0", "body": "More like 503. But that's not that important. Important is that you let the user know that the problem should fade away shortly and that they are welcome to retry later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T11:13:51.497", "Id": "497513", "Score": "0", "body": "And at least, can I change `private codeError` to `public error = null`, decrease `maxAttemps` to 3, in `while` compare any error that appears and then check, if `error` property contains something and based on this tell user, that traffic is probably temporarily full, try it again later?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T11:49:08.300", "Id": "497514", "Score": "0", "body": "Well, I guess you can. But it might not be the best approach. Regardless of that being the right design, the class currently breaks SRP, so I'll at least try to show you how I would implement it in the code so it follows the SOLID principles. But I'm on my phone now. I'll get back to you in the evening (eu time)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T22:32:35.597", "Id": "497571", "Score": "0", "body": "So, did you come up with something? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T13:20:42.747", "Id": "497610", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116559/discussion-between-tomas-kretek-and-slepic)." } ]
[ { "body": "<p>You code has several problems. Specificaly it breaks at least two of the SOLID principles, namely single responsibility and dependency inversion principles.</p>\n<p>Single responsibility is violated because the class is responsible for:</p>\n<ul>\n<li>connecting to db</li>\n<li>retrying connection</li>\n<li>whatever other methods provided by the class you did not show us</li>\n</ul>\n<p>Dependency inversion principle is violated because the class uses hardcoded values (although stored in instance properties).</p>\n<p>Let me first separate out the first responsibility. We don't really need OOP for that, so let me do it in FP style.</p>\n<pre><code>function createMyPdo(): \\PDO\n{\n $dsn = ...;\n $user = ...;\n $password = ...;\n $options = ...;\n return new \\PDO($dsn, $user, $password, $options);\n}\n</code></pre>\n<p>This function now opens a connection with hardcoded credentials. Although the credentials are hardocded and we would better pull those values off of maybe environment variables. It at least has just one responsibility and that is to open the specific database connection.</p>\n<p>Now lets implement the retry logic as a separate thing, that only depends on something that creates PDO instance.</p>\n<pre><code>function createPdoWithRetry(callable $factory, int $attempts): \\PDO\n{\n $attemptsMade = 0;\n while ($attempts &gt; $attemptsMade) {\n try {\n return $factory();\n } catch (\\PDOException $e) {\n if ($e-&gt;getCode() === 1040) {\n \\usleep(\\pow(2, $attempsMade) * 10000);\n ++$attemptsMade;\n } else {\n throw $e;\n }\n }\n }\n throw new \\RuntimeException(&quot;All $attemptsMade retry attempts exhausted.&quot;);\n}\n</code></pre>\n<p>Now I can easily open the connection with retry logic</p>\n<pre><code>$pdo = createPdoWithRetry(fn () =&gt; createMyPdo(), 20);\n</code></pre>\n<p>And I can also open a different connection using the same thing:</p>\n<pre><code>$pdo2 = createPdoWithRetry(fn () =&gt; createOtherPdo(), 20);\n</code></pre>\n<p>This approach still has some caveats:</p>\n<ul>\n<li>where createMyPdo could only throw PDOException, createPdoWithRetry can also throw a generic RuntimeException.</li>\n<li>the type of the <code>$factory</code> parameter has a very vague type, that we have to describe in a docblock and cannot be enforced by PHP runtime.</li>\n<li>createPdoWithRetry knows error code 1040 which is mysql specific, but the knowledge that mysql is used is only known to the createMyPdo function.</li>\n</ul>\n<p>Let's make it better by going back to OOP style and introducing an interface for the connection factory, including specific exceptions to be thrown (which will abstract away the 1040 speific mysql error code).</p>\n<pre><code>class DatabaseConnectionException extends \\Exception\n{\n}\n\nclass TooManyConnectionsException extends DatabaseConnectionException\n{\n}\n\ninterface DatabaseConnector\n{\n /**\n * @return \\PDO\n * @throws DatabaseConnectionException\n * @throws TooManyConnectionsException\n */\n public function createPdo(): \\PDO;\n}\n</code></pre>\n<p>As you can see I added some <code>@throws</code> annotations to:</p>\n<ul>\n<li>inform implementors of the interface which exception they can throw</li>\n<li>informs consumers of the interface which exceptions they can catch</li>\n</ul>\n<p>Although PHP cannot enforce the actual type of exceptions thrown from the implementations, documenting the exceptations makes it less likely that someone will implement it wrong.</p>\n<p>Now lets make an implementaton for our specific connection:</p>\n<pre><code>class MyDatabaseConnector implements DatabaseConnector\n{\n public function createPdo(): \\PDO\n {\n $dsn = ...;\n $user = ...;\n $password = ...;\n $options = ...;\n try {\n return new \\PDO($dsn, $user, $password, $options);\n } catch (\\PDOException $e) {\n if ($e-&gt;getCode() === 1040) {\n throw new TooManyConnectionsException($e-&gt;getMessage(), (int) $e-&gt;getCode(), $e);\n } else {\n throw new DatabaseConnectionException($e-&gt;getMessage(), (int) $e-&gt;getCode(), $e);\n }\n }\n }\n}\n</code></pre>\n<p>Now maybe you see why the credentials should not be hardocded, because the same code would work for any credentials. Hardcoding the credentials, we are doomed to repeat some code if we want to open a different connection.</p>\n<p>But I leave that up to you to find your way to the dependency inversion principle. Basically constructor of a class should accept things that the class instances need to know, rather then having the instances deciding on their own what those values should be (ie. pass the credentials through constructor, rather then hardocing the credentials withing the class).</p>\n<p>Anyway, to implement the retry logic we will use the same interface:</p>\n<pre><code>class RetryingDatabaseConnector implements DatabaseConnector\n{\n private DatabaseConnector $factory;\n private RetryDelayStrategy $delayStrategy;\n private int $maxAttempts;\n\n public function __construct(DatabaseConnector $factory, RetryDelayStrategy $delayStrategy, int $maxAttempts)\n {\n $this-&gt;factory = $factory;\n $this-&gt;delayStrategy = $delayStrategy;\n $this-&gt;maxAttempts = $maxAttempts;\n }\n\n public function createPdo(): \\PDO\n {\n $attemptsMade = 0;\n while ($this-&gt;maxAttempts &gt; $attemptsMade) {\n try {\n return $this-&gt;factory-&gt;createPdo();\n } catch (TooManyConnectionsException $e) {\n ++$attemptsMade;\n $this-&gt;delayStrategy-&gt;wait($attemptsMade)\n }\n }\n throw new TooManyConnectionsException(&quot;All $attemptsMade retry attempts exhausted.&quot;);\n }\n}\n</code></pre>\n<p>As you can see I have also extracted the delay logic to a separate interface, because exponentialy growing gaps between attempts is just one of many possible strategies. And again, you don't want to implement a new connector that would repeat a lot of the logic just to change to delay strategy.</p>\n<pre><code>interface RetryDelayStrategy\n{\n public function wait(int $attemptsMade): void;\n}\n\nclass ExponentialRetryDelayStrategy implements RetryDelayStrategy\n{\n private int $coefficient;\n private int $base;\n\n public function __construct(int $coefficient, int $base = 2)\n {\n $this-&gt;coefficient = $coefficient;\n $this-&gt;base = $base;\n }\n\n public function wait(int $attemptsMade): void\n {\n \\usleep(\\pow($this-&gt;base, $attempsMade) * $this-&gt;coefficient);\n }\n}\n</code></pre>\n<p>And finaly some consumer code. A controller that opens a database connection (to do something with it) and gives a user friendly messages if the connection fails and a more specific one if the connection fails specificaly because of too many open connections.</p>\n<pre><code>class MyController extends BaseController\n{\n private DatabaseConnector $connector;\n\n public function __construct(DatabaseConnector $connector)\n {\n $this-&gt;connector = $connector;\n }\n\n public function myControllerAction(Request $request): Response\n {\n try {\n $pdo = $this-&gt;connector-&gt;createPdo();\n } catch (TooManyConnectionsException $e) {\n return $this-&gt;send(503, &quot;Too many database connections.&quot;);\n } catch (DatabaseConnectionException $e) {\n return $this-&gt;send(503, &quot;Database unavailable.&quot;);\n }\n\n // do something with PDO here\n\n return $this-&gt;send(200, &quot;All done&quot;);\n }\n}\n</code></pre>\n<p>Now, you see the controller just depends on a <code>DatabaseConnector</code>. It doesn't really care if and how many times the connector will retry. It just cares that it can fail in a specific (TooManyConnectionsException) or an further unspecified (DatabaseConnectionException) way or, if it succeeds, it returns a PDO instance.\nAnd it will work no matter what connector you pass to it, as long as the interface is implemented correctly. And so you can change the implementation without touching the controller code. Again, thanks to single responsibility a dependency inversion principles.</p>\n<p>No matter which is used in the DI setup</p>\n<pre><code>$myConnector = new MyDatabaseConnector();\n// or maybe if we pull it to envs\n// $myConnector = new MyDatabaseConnector($_ENV['DB_DSN'], $_ENV['DB_USER'], $_ENV['DB_PASS']);\n$connector = $myConnector;\n</code></pre>\n<p>or</p>\n<pre><code>$delayStrategy = new ExponentialRetryDelayStrategy(10000, 2);\n$retryingConnector = new RetryingDatabaseConnector($myConnector, $delayStrategy, 20);\n$connector = $retryingConnector;\n</code></pre>\n<p>the controller code stays untouched</p>\n<pre><code>$controller = new MyController($connector);\n...\n$controller-&gt;run();\n</code></pre>\n<p>Also notice, how I avoided setting an <code>errorCode</code> and checking it in the controller. Instead we just throw exceptions. This forces the caller to actually handle the error or let it bubble up the stack and eventually stop execution of the program.\nThis is the prefered behaviour because if you would forget to check the error code, it really does not make sense to try to send sql queries over a &quot;not opened connection&quot;.</p>\n<p>Btw, if you are interested in design patterns, you can notice that:</p>\n<ul>\n<li>DatabaseConnector and its implementations are a factory method pattern</li>\n<li>RetryingDatabaseConnector and the interface follow the decorator pattern</li>\n<li>RetryDelayStrategy and its implementations are the strategy of the strategy design pattern and RetryingDatabaseConnector is the strategy consumer</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T10:39:05.070", "Id": "497597", "Score": "0", "body": "Thank you very much for your loooong reply. But now, I dont really know what to do, because this seems like whole new level of programming. I went throught interfaces and extending classes with classes etc. in past, but this whole logic is something.. I dont know how to say it. It seems like its from big practice, which I dont have and dont have any options to get some, from real world.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T11:05:17.650", "Id": "497601", "Score": "0", "body": "@TomášKretek yeah, I thought it might too high level for you. take your time, read it several times and try to understand the individual parts... The big message is that you should split your code into reusable pieces with single responsibilities. Don't try to stuck everything in one class. The program flow comes in stages (gather config, create objects, work with objects), don't be shy to represent each stage as a separate interface/class. Think what a class needs to do to fulfill its purpose, then outsource them - ask for them via constructor, but let the instantiator decide what to pass in" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T11:06:11.947", "Id": "497602", "Score": "0", "body": "And only ask for what you really need. If you ask for something with dozen of methods and only use one of them, then something is probably wrong. Your class there was doing a lot of stuff, probably has methods that you didn't include. But what consumers really want is to just get a PDO instance so they can work with it. That's the reason why you don't see any wrapper around the PDO instance in my implementation, it simply is not necesary, becase the other stages of the flow have already been resolved elsewhere..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T06:47:32.173", "Id": "252506", "ParentId": "252465", "Score": "1" } }, { "body": "<p>&quot;Too many connections&quot;...</p>\n<ul>\n<li>Use only one connection for the entire program. (There are rare exceptions.)</li>\n<li>Disconnect when finished.</li>\n<li>Decrease wait_timeout -- this will do the disconnect in case you forget to do it.</li>\n<li>Make sure no other system (eg, the web server) is causing excessive number of connections)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:03:06.170", "Id": "258905", "ParentId": "252465", "Score": "1" } } ]
{ "AcceptedAnswerId": "252506", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T21:12:07.333", "Id": "252465", "Score": "1", "Tags": [ "php", "object-oriented", "mysql", "database", "pdo" ], "Title": "Repeated DB connection at max user connections" }
252465
<p>I must create a function that accepts a string of names all separated by a comma.</p> <p>Example: <code>&quot;Jack,Matthew,John,Sam&quot;</code></p> <p>And return the string of names in the same order but spelled in reverse.</p> <p>Expected output: <code>&quot;kcaJ,wehttaM,nhoJ,maS&quot;</code></p> <p>I completed the function with an inner for loop but I would like to know if maybe running a single for loop and inside using a <code>Linq</code> function or something similar, would have been better?</p> <pre><code>public string Reverse(string s) { var names = s.Split(&quot;,&quot;); string temp = &quot;&quot;; for (int i = 0; i &lt; names.Length; i++) { for (int j = names[i].Length - 1; j &gt;= 0; j--) { temp += names[i].ElementAt(j); } temp += i == names.Length - 1 ? &quot;&quot; : &quot;,&quot;; } return temp; } </code></pre> <p>Anyway I found this problem very simple even though I tried taking my time on it, I found this solution almost immediately so I went with it. I am thinking maybe if I spent more time on it then I could have implemented this with some sort of <code>Linq</code> function to reverse the spelling of the names and removed the inner loop.</p> <p>Really any suggestions for improving this small function is appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T03:39:30.397", "Id": "497486", "Score": "1", "body": "Did you forget to `return temp`? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T04:03:24.087", "Id": "497487", "Score": "1", "body": "Nice catch, forgot that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T06:10:29.343", "Id": "497495", "Score": "0", "body": "Related : [*\"Easy way to reverse each word in a string\"*](https://stackoverflow.com/questions/5391198/easy-way-to-reverse-each-word-in-a-sentence)" } ]
[ { "body": "<p>Good code, few suggestions.</p>\n<hr />\n<p>Instead of having to check each and every time to make sure you can add a <code>&quot;,&quot;</code> or not, add it for all the cases, use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.trimend?view=net-5.0\" rel=\"nofollow noreferrer\">String.TrimEnd</a> to remove the extra leading <code>&quot;,&quot;</code></p>\n<pre class=\"lang-cs prettyprint-override\"><code> var names = s.Split(&quot;,&quot;);\n string temp = &quot;&quot;;\n\n for (int i = 0; i &lt; names.Length; i++)\n {\n for (int j = names[i].Length - 1; j &gt;= 0; j--)\n {\n temp += names[i].ElementAt(j);\n }\n temp += &quot;,&quot;;\n }\n return temp.TrimEnd(',');\n</code></pre>\n<p>With that change, we have the ability to <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in\" rel=\"nofollow noreferrer\">foreach</a> loop to further improve the readability of the code.</p>\n<pre class=\"lang-cs prettyprint-override\"><code> string temp = &quot;&quot;;\n foreach (var name in s.Split(','))\n {\n for (int j = name.Length - 1; j &gt;= 0; j--)\n {\n temp += name.ElementAt(j);\n }\n temp += &quot;,&quot;;\n }\n return temp.TrimEnd(',');\n</code></pre>\n<p>That's good. Although we can improve this further by using a better (faster and cleaner) method to reverse the individual names, and that is to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.tochararray?view=net-5.0\" rel=\"nofollow noreferrer\">String.ToCharArray</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.reverse?view=net-5.0\" rel=\"nofollow noreferrer\">Array.Reverse</a></p>\n<p>The idea is to convert the string into a character array, use the inbuilt <code>Reverse</code> method to reverse it, add it to <code>temp</code>.</p>\n<pre><code> string temp = &quot;&quot;;\n foreach (var name in s.Split(','))\n {\n char[] NameArray = name.ToCharArray();\n Array.Reverse(NameArray);\n\n temp = temp + new string(NameArray) + &quot;,&quot;;\n\n }\n return temp.TrimEnd(',');\n</code></pre>\n<p>You can also use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=net-5.0\" rel=\"nofollow noreferrer\">StringBuilder</a> which is slightly faster</p>\n<pre class=\"lang-cs prettyprint-override\"><code> StringBuilder reversed = new StringBuilder();\n\n foreach (var word in str.Split(','))\n {\n char[] singlesentence = word.ToCharArray();\n Array.Reverse(singlesentence);\n reversed.Append(singlesentence);\n reversed.Append(&quot;,&quot;);\n }\n return reversed.ToString().TrimEnd(',');\n</code></pre>\n<p>Nitpick:</p>\n<ul>\n<li><p>Prefer using a better name like <code>reversed</code> compared to <code>temp</code>, it tells more to the reader.</p>\n</li>\n<li><p>Use <code>string.Empty</code> and not <code>&quot;&quot;</code></p>\n</li>\n</ul>\n<hr />\n<h2>Benchmarks</h2>\n<p>Your original code</p>\n<pre class=\"lang-cs prettyprint-override\"><code> static public string Reverse(string s)\n {\n var names = s.Split(&quot;,&quot;);\n string temp = &quot;&quot;;\n\n for (int i = 0; i &lt; names.Length; i++)\n {\n for (int j = names[i].Length - 1; j &gt;= 0; j--)\n {\n temp += names[i].ElementAt(j);\n }\n temp += i == names.Length - 1 ? &quot;&quot; : &quot;,&quot;;\n }\n return temp;\n }\n</code></pre>\n<hr />\n<p>New</p>\n<pre class=\"lang-cs prettyprint-override\"><code> static public string Reverse2(string s)\n {\n \n string reversed = string.Empty;\n foreach (var name in s.Split(','))\n {\n char[] NameArray = name.ToCharArray();\n Array.Reverse(NameArray);\n\n reversed += new string(NameArray) + &quot;,&quot;;\n\n }\n return reversed.TrimEnd(',');\n }\n</code></pre>\n<hr />\n<p>New2</p>\n<pre class=\"lang-cs prettyprint-override\"><code> static public string Reverse3(string str)\n {\n StringBuilder reversed = new StringBuilder();\n\n foreach (var word in str.Split(','))\n {\n char[] singlesentence = word.ToCharArray();\n Array.Reverse(singlesentence);\n reversed.Append(singlesentence);\n reversed.Append(&quot;,&quot;);\n }\n return reversed.ToString().TrimEnd(',');\n }\n</code></pre>\n<hr />\n<p>Note that I have <code>static</code> to use the function without an object reference.</p>\n<p>I will use the following method to call the two functions multiple times, and benchmark it.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Perform(Func&lt;string, string&gt; Function, string names, int iterations, string type)\n{\n\n var watch = System.Diagnostics.Stopwatch.StartNew();\n for (int i = 0;i &lt; iterations;i++)\n Function(names);\n\n watch.Stop();\n\n var elapsed = watch.ElapsedMilliseconds;\n Console.WriteLine($&quot;Time taken for {type}: {elapsed} ms&quot;);\n}\n</code></pre>\n<pre class=\"lang-cs prettyprint-override\"><code> static void Main()\n {\n string names = &quot;Jack,Dylan,Bobby,Peter&quot;;\n const int iterations = 1000000;\n\n Perform(Reverse, names, iterations, &quot;Original&quot;);\n Perform(Reverse2, names, iterations, &quot;New&quot;);\n Perform(Reverse3, names, iterations, &quot;New2&quot;);\n \n }\n</code></pre>\n<p>Here are the results</p>\n<pre class=\"lang-cs prettyprint-override\"><code>/*\n&quot; Release &quot; Configuration\n\n Iterations | Original | New | New2\n-------------+-------------+-----------+--------\n 10 000 | 29 ms | 5 ms | 5 ms\n-------------+-------------+-----------+--------\n 100 000 | 226 ms | 54 ms | 43 ms\n-------------+-------------+-----------+--------\n 1 000 000 | 1763 ms | 442 ms | 405 ms\n\n\n*/\n</code></pre>\n<p><a href=\"https://dotnetfiddle.net/pvzZry\" rel=\"nofollow noreferrer\">Try it here</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T12:46:50.903", "Id": "497518", "Score": "3", "body": "But why use a StringBuilder instead of simply filling a collection and then applying String.Join afterwards (this also does away with the ugly `.TrimEnd(',')`)? Especially considering this: https://stackoverflow.com/questions/585860/string-join-vs-stringbuilder-which-is-faster (Quite frankly, even if the performance of a StringBuilder was better, I'd still opt for the String.Join approach since it is more readable IMHO.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T12:59:07.573", "Id": "497519", "Score": "0", "body": "@BCdotWEB Yeah that's true, the thing is String Builder is faster. If compactness and readability weigh-out performance in your project, you're welcome to use it :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T13:10:24.187", "Id": "497521", "Score": "0", "body": "@BCdotWEB You mean using `string.Join(\",\", str.Split(',').Select(x => new String(x.Reverse().ToArray())));` right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T13:29:25.067", "Id": "497522", "Score": "0", "body": "@BCdotWEB I've benchmarked the performance [here](https://dotnetfiddle.net/fgyt4h/). To me, the difference is too significant." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T05:12:17.823", "Id": "252473", "ParentId": "252467", "Score": "2" } }, { "body": "<p>You asked about Linq, so I decided to add a way to do it purely with Linq. This performs a bit worse than the StringBuilder examples, but is still <em>3x faster</em> than the original:</p>\n<pre><code>public static string ReverseWithLinq(string str)\n{\n return string.Join(\n ',', \n str\n .Split(',')\n .Select(w =&gt; new string(w.Reverse().ToArray())));\n}\n</code></pre>\n<p>P.S. I would typically prefer using framework capabilities as much as possible, and only optimize further when necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T03:09:44.580", "Id": "499575", "Score": "0", "body": "I just now saw this, thanks for posting this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T15:33:30.287", "Id": "252598", "ParentId": "252467", "Score": "2" } } ]
{ "AcceptedAnswerId": "252473", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-21T22:31:38.150", "Id": "252467", "Score": "3", "Tags": [ "c#", "strings", "array" ], "Title": "Converting a string into an array and returning the values spelled in reverse" }
252467
<p>I just wrote this decimal to Roman numeral converter, inspired by <a href="https://www.youtube.com/watch?v=_M4o0ExLQCs" rel="nofollow noreferrer">Kevlin Henney's</a> talk &quot;Get Kata&quot;.</p> <p>I have been reading the Rust docs little by little and this is one of my first attempts at some code.</p> <p>I'd like to get feedback on style, general rust idioms and how I could have implemented <strong>this</strong> algorithm in a more succinct manner.</p> <p>Code also available <a href="https://github.com/jamespeterschinner/kata" rel="nofollow noreferrer">here</a>.</p> <pre><code>use std::env; use std::io; use std::io::BufWriter; use std::io::Write; static BASE10_NUMERALS: [&amp;str; 7] = [&quot;I&quot;, &quot;X&quot;, &quot;C&quot;, &quot;M&quot;, &quot;X̄&quot;, &quot;C̄&quot;, &quot;M̄&quot;]; static CENTRE_NUMERALS: [&amp;str; 6] = [&quot;V&quot;, &quot;L&quot;, &quot;D&quot;, &quot;V̄&quot;, &quot;L̄&quot;, &quot;D̄&quot;]; struct Bases { base: usize } impl Iterator for Bases { type Item = usize; fn next(&amp;mut self) -&gt; Option&lt;usize&gt; { self.base = self.base - 1; Some(self.base) } } fn iter_bases(largest_base: usize) -&gt; Bases { Bases { base: largest_base } } fn encode((decimal_number, base, ): (char, usize, )) -&gt; String { let digit = decimal_number.to_digit(10).unwrap(); let max_base = CENTRE_NUMERALS.len(); if base &gt;= max_base { BASE10_NUMERALS[BASE10_NUMERALS.len() - 1] //This pow function is the main limiter for decimal size .repeat((10_u32.pow((base - max_base) as u32) * digit) as usize) } else { if digit == 9 { format!(&quot;{}{}&quot; , if base == 3 { &quot;Ī&quot;} else { BASE10_NUMERALS[base] } , BASE10_NUMERALS[base + 1] ) } else if digit &gt;= 5 { format!(&quot;{}{}&quot;, CENTRE_NUMERALS[ base], BASE10_NUMERALS[base] .repeat((digit - 5) as usize)) } else if digit == 4 { format!(&quot;{}{}&quot;, BASE10_NUMERALS[base], CENTRE_NUMERALS[base]) } else { // Less than 4 BASE10_NUMERALS[base].repeat(digit as usize) } } } fn main() { let args: Vec&lt;String&gt; = env::args().collect(); let mut writer = BufWriter::new(io::stdout()); let input = &amp;args[1]; for roman_numeral in input .chars() .zip(iter_bases(input.len())) .map(encode) { writer.write(roman_numeral.as_bytes()) .expect(&quot;Unable to write to stdout&quot;); } } </code></pre>
[]
[ { "body": "<h1><code>cargo fmt</code> and <code>cargo clippy</code></h1>\n<p>Use <code>cargo fmt</code> to format your code according to the official Rust\nStyle Guide.</p>\n<p>Clippy's suggestions:</p>\n<ul>\n<li><p>collapse <code>else { if .. }</code> into <code>else if ..</code>;</p>\n</li>\n<li><p>change <code>self.base = self.base - 1</code> to <code>self.base -= 1</code>;</p>\n</li>\n<li><p>use <code>write_all</code> instead of <code>write</code> when writing a slice of bytes,\nsince the latter only makes one writing attempt:</p>\n<blockquote>\n<p><code>io::Write::write(_vectored)</code> and <code>io::Read::read(_vectored)</code> are\nnot guaranteed to process the entire buffer. They return how many\nbytes were processed, which might be smaller than a given buffer’s\nlength. If you don’t need to deal with partial-write/read, use\n<code>write_all</code>/<code>read_exact</code> instead. (<a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#unused_io_amount\" rel=\"nofollow noreferrer\">source</a>)</p>\n</blockquote>\n</li>\n</ul>\n<h1>The interface</h1>\n<p>Instead of passing in a tuple, it is preferable to pass separate\nparameters:</p>\n<pre><code>fn encode(decimal_number: char, base: usize) -&gt; String {\n // ...\n}\n</code></pre>\n<p>Now, we notice that the interface is fairly curious. A better\nself-explanatory interface might simply be:</p>\n<pre><code>fn to_roman(number: u32) -&gt; String {\n // ...\n}\n</code></pre>\n<p>which can be coded to encapsulate calls to <code>encode</code> while avoiding\nrepetitive allocation.</p>\n<h1>Grouping <code>use</code> declarations</h1>\n<p>It's common to group <code>use</code> declarations together:</p>\n<pre><code>use std::{\n env,\n io::{self, BufWriter, Write},\n};\n</code></pre>\n<h1>The <code>Bases</code> utility</h1>\n<p><code>Bases</code> is not necessary — you can use <code>(0..n).rev()</code> to iterate\nfrom <code>n - 1</code> to <code>0</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T08:54:14.617", "Id": "497503", "Score": "0", "body": "Thanks! All great points, I really should have known about `(0..n).rev()`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T05:59:17.220", "Id": "252474", "ParentId": "252470", "Score": "3" } } ]
{ "AcceptedAnswerId": "252474", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T02:08:10.283", "Id": "252470", "Score": "4", "Tags": [ "rust", "roman-numerals" ], "Title": "Rust decimal to roman numeral kata" }
252470
<p>I have created a Reddit bot that goes through an &quot;x&quot; amount of posts. For each post it pulls all the comments from that post into a list then a data frame and then it loops over a CSV look for words that match a ticker in CSV file and then finally it spits out a sorted data frame.</p> <p>is there anything I could improve / more object-oriented code?</p> <h3>autho_dict structure</h3> <pre class="lang-py prettyprint-override"><code>autho = { 'app_id': '', 'secret': '', 'username': '', 'password': '', 'user_agent': &quot;&quot; } </code></pre> <h3>The rest of the code</h3> <pre class="lang-py prettyprint-override"><code>from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import re import os import praw import pandas as pd import datetime as dt class WallStreetBetsSentiment: def __init__(self, autho_dict, posts): self.__authentication = autho_dict self.__posts = posts self.__comment_list = [] self.__title_list = [] self.__ticker_list = pd.read_csv( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + &quot;\\dependencies\\ticker_list.csv&quot;) self.__sia = SentimentIntensityAnalyzer() @property # creates instance of reddit using authenticaton from app.WSBAuthentication def __connect(self): return praw.Reddit( client_id=self.__authentication.get(&quot;app_id&quot;), client_secret=self.__authentication.get(&quot;secret&quot;), username=self.__authentication.get(&quot;username&quot;), password=self.__authentication.get(&quot;password&quot;), user_agent=self.__authentication.get(&quot;user_agent&quot;) ) @property # fetches data from a specified subreddit using a filter method e.g. recent, hot def __fetch_data(self): sub = self.__connect.subreddit(&quot;wallstreetbets&quot;) # select subreddit new_wsb = sub.hot(limit=self.__posts) # sorts by new and pulls the last 1000 posts of r/wsb return new_wsb @property # saves the comments of posts to a dataframe def __break_up_data(self): for submission in self.__fetch_data: self.__title_list.append(submission.title) # creates list of post subjects, elements strings submission.comments.replace_more(limit=1) for comment in submission.comments.list(): dictionary_data = {comment.body} self.__comment_list.append(dictionary_data) return pd.DataFrame(self.__comment_list, columns=['Comments']) # saves all comments to a csv document saved in 'logs' def debug(self): save_file = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + &quot;\\logs&quot; return self.__break_up_data.to_excel(save_file + &quot;\\log-{}.xlsx&quot;.format( dt.datetime.now().strftime(&quot;T%H.%M.%S_D%Y-%m-%d&quot;)), sheet_name='Debug-Log') # loops though comments to find tickers in self.ticker_list def parser(self, enable_debug=bool): ticker_list = list(self.__ticker_list['Symbol'].unique()) # titlelist = list(df2['Titles'].unique()) comment_list = list(self.__break_up_data['Comments'].unique()) ticker_count_list = [] for ticker in ticker_list: count = [] sentiment = 0 for comment in comment_list: # count = count + re.findall((r'\s{}\s').format(ticker), str(comment)) count = count + re.findall((' ' + ticker + ' '), str(comment)) if len(count) &gt; 0: score = self.__sia.polarity_scores(comment) sentiment = score['compound'] # adding all the compound sentiments if len(count) &gt; 0: ticker_count_list.append([ticker, len(count), (sentiment / len(count))]) if enable_debug is True: self.debug() else: pass # ISSUE: the re.findall function would return match on AIN if someone says PAIN df4 = pd.DataFrame(ticker_count_list, columns=['Ticker', 'Count', 'Sentiment']) df4 = df4.sort_values(by='Count', ascending=False) return df4 </code></pre>
[]
[ { "body": "<h2>Underscores</h2>\n<p>Double-underscores, as in</p>\n<pre><code> self.__authentication = autho_dict\n self.__posts = posts\n self.__comment_list = []\n self.__title_list = []\n</code></pre>\n<p>are not a good idea. At most, use one underscore to indicate a private member variable (though this is not enforced in Python). Read <a href=\"https://stackoverflow.com/a/1301369/313768\">https://stackoverflow.com/a/1301369/313768</a> for more detail.</p>\n<h2>System-specific paths</h2>\n<pre><code>save_file + &quot;\\\\log-{}.xlsx&quot;.format(\n</code></pre>\n<p>makes it so that only Windows users can run this script. Consider <code>Path(save_file) / f'log-{now}.xlsx'</code> instead, and put <code>now</code> as a variable before your format call.</p>\n<h2>Backwards ISO8601?</h2>\n<pre><code>T%H.%M.%S_D%Y-%m-%d\n</code></pre>\n<p>is a curious format. It's non-sortable, non-standard and surprising to everyone who understands <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO8601</a>. If at all possible, use ISO format instead.</p>\n<h2>Redundant <code>else</code></h2>\n<p>Delete this:</p>\n<pre><code> else:\n pass\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T10:28:56.473", "Id": "497723", "Score": "0", "body": "Thank you for your thoughts. I was not aware of the standard practice for date/time. In terms of private variables should I only use them when I am using multiple classes that have identical function names?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T15:06:40.353", "Id": "497755", "Score": "1", "body": "Private variables are not the solution to name collision concerns. If you have multiple classes, the only time there will be a name collision is if there is an inheritance relationship between them, in which case the name overlap would be deliberate." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T22:22:57.183", "Id": "252567", "ParentId": "252472", "Score": "2" } } ]
{ "AcceptedAnswerId": "252567", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T02:50:02.450", "Id": "252472", "Score": "3", "Tags": [ "performance", "python-3.x", "pandas", "reddit" ], "Title": "Reddit bot in Python" }
252472
<p>So I am building a website. It will be only used inside our small company and it's not made for public use.</p> <p>What I want to achieve is the ability for user to maintain session after sign in for a prolonged period of time while also maintaining some sense of security and common sense.</p> <p>My website building experience is 2-3 weeks of building things with HTML/PHP/Bootstrap/JS where I mostly just lurk around and do research.</p> <p>So far, from what I have read, tried and found I was able to get a solution working, yet what I would like is for someone to take a look and tell me what is good and what is bad with my approach and how can I improve this.</p> <p>This is the file I created for working with <code>Cookies</code> and <code>Sessions</code>. This file will be included using <code>require()</code> on each and every page that can be accessed by web-site navigation (that means this won't be used on any 'back-end' files because that makes no sense I think).</p> <p>I will explain my thought process below in the comments to code.</p> <pre><code>&lt;?php // Firstly, we check if any session is set, because if the session is set, // then the user can still navigate the website and we don't need to do anything if (!isset($_SESSION['id'])) { // The session is not set. // Check if Cookie with pre-defined name that I thought of for my web-site exist if (isset($_COOKIE['info'])) { // Okay. We have no session but we have a cookie. Let us start a session then. // Getting hold of database handler. require_once(__DIR__ . '/../dbh/dbh.php'); // Preparing statement for accessing DB. $stmt = $connection-&gt;prepare(&quot;SELECT * FROM `users` WHERE `username`=?&quot;); // Information inside my Cookie is stored in an JSON encoded string, so we decode it. $info = json_decode($_COOKIE['info'], true); // Assign extracted information to variable for ease of use $username = $info['username']; $password = $info['password']; // Bind parameters and execute the statement we prepared $stmt-&gt;bind_param('s', $username); $stmt-&gt;execute(); // Get results of statement execution $result = $stmt-&gt;get_result()-&gt;fetch_assoc(); // The result may be `NULL` if the username we tried to find does not exist. // So if the username does not exist, then we can't start the session. if ($result !== NULL) { // The username exists so we can proceed further. // Assign `username` and `password` we got from query to variables for ease of use $db_username = $result['username']; $db_password = $result['password']; // Here we do an extra step of verifying user`s credentials just to be 100% sure if (strcmp($username, $db_username) == 0 &amp;&amp; strcmp($password, $db_password) == 0) { // Credentials are identical, so we can safely start a session for this user. session_start(); $_SESSION['id'] = $result['id']; $_SESSION['username'] = $result['username']; $_SESSION['password'] = $result['password']; // JSON encoding user's credentials for storing in a cookie. $info = array( 'username' =&gt; $username, 'password' =&gt; $password ); // We are going to set a refreshed cookie for to make sure // that this cookie expires only when the user doesn't // visit the website for a month. setcookie('info', json_encode($info), time() + 2592000); } } // This is an interesting part. // This `if` statement was created to avoid endless loop when user initially enters the website. // Here we check if the page is `index.php` and if it is, then we don't need to redirect user. if ($_SERVER['REQUEST_URI'] !== '/' &amp;&amp; $_SERVER['REQUEST_URI'] !== '/index.php') { header(&quot;Location: http://&quot; . $_SERVER['HTTP_HOST'] . &quot;/index.php&quot;); exit(); } } // Same thing as above, just in two different `if` statements. if ($_SERVER['REQUEST_URI'] !== '/' &amp;&amp; $_SERVER['REQUEST_URI'] !== '/index.php') { header(&quot;Location: http://&quot; . $_SERVER['HTTP_HOST'] . &quot;/index.php&quot;); exit(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T09:32:09.203", "Id": "497504", "Score": "0", "body": "You should not store the user's plain password in db. And definitely not in a cookie. Those are severe security issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T10:29:30.153", "Id": "497511", "Score": "0", "body": "@slepic the password is hashed using `md5`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T10:35:41.060", "Id": "497512", "Score": "0", "body": "Well that's slightly better. For the db. But you should use a proper password hashing algorithm anyway. For the cookie, that's a different story, it is a security issue to put password in a cookie no matter if it is hashed and how." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T18:12:15.397", "Id": "497535", "Score": "0", "body": "@slepic ok, I see what you saying, but if that's the case, how do I check if user is authentic one? If I don't store the password inside cookie I cannot check for authenticity since it will be enough to create a cookie with any username and you will be automatically logged in. What would be the way to authenticate user without storing password in cookies?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T18:28:40.567", "Id": "497537", "Score": "0", "body": "Well, you send the password in the body of a login request. Then if password matches a db entry, you store it's id in the session and respond with a set-cookie header containing the session id. In consecutive requests you check if session contains an id and if it does you can trust the request is coming from the session id owner (what a tautology) and unless the original user, who logged in, revealed the session cookie to someone else, we're pretty sure the consecutive requests are coming from the same client." } ]
[ { "body": "<h2><code>IF</code> logic</h2>\n<p><strong>All encompassing <code>if</code>s</strong></p>\n<p>Right off the bat you have two levels of nested <code>if</code> statements before we get to the main body of the code...</p>\n<pre><code>if (!isset($_SESSION['id'])) {\n if (isset($_COOKIE['info'])) {\n // Main code...\n }\n // Additional code...\n}\n</code></pre>\n<p>...which is unnecessary; you could just as easily merge them into one statement:</p>\n<pre><code>if (!isset($_SESSION['id']) &amp;&amp; isset($_COOKIE['info'])) {\n // Code here...\n}\n</code></pre>\n<p><strong>Repeated <code>if</code>s</strong></p>\n<p>The <em>first</em> of the duplicated <code>if</code> statements isn't needed. A simplified version of your code would look like the following...</p>\n<pre><code>if (true) {\n if (true) {\n // Do &quot;task&quot;\n }\n\n // Do &quot;task&quot;\n}\n</code></pre>\n<p>...notice that <code>if</code> the first condition is <code>true</code> then the <code>task</code> is carried out regardless of the state of the second condition. Which means that you don't need to repeat the code in the nested <code>if</code> statement because when that code block ends the <code>task</code> is completed anyway!</p>\n<p>The only reason that it isn't completed twice in your case is because you <code>exit</code> the script manually after it runs the first time.</p>\n<p><strong>String comparison</strong></p>\n<p>There's nothing <em>wrong</em> with using <code>strcmp</code> to compare two strings; however it is not needed in this scenario. You don't care whether one string is <em>greater or lesser</em> than the other you simply want to know if they are identical. The <code>===</code> comparison operator does exactly that: the values are either identical (<code>true</code>; equal and of same type) or they aren't (<code>false</code>). For example:</p>\n<pre><code>if ($username === $db_username &amp;&amp; $password === $db_password) {\n // Username and Password are correct...\n}\n</code></pre>\n<p>Additionally, you're using a loose comparison: it's better practice to use a strict comparison as your default choice as you have done later on in the script. Especially here when the output you're looking for is an integer.</p>\n<p>Whilst it may be true in <em>this circumstance</em> that the only <code>false</code> value output is <code>(int) 0</code> reusing the same logic somewhere else could lead to unexpected behaviour.</p>\n<p>Lastly, you compare both the username and the password. You don't need to do that. You've already compared the username in your query; if it didn't match then the record would never have been returned in the first place so the check is redundant.</p>\n<p><strong>Checking the <code>$result</code></strong></p>\n<p>Again, <em>technically</em>, there's nothing wrong here. And you are using the strict comparison operators mentioned earlier. But in this case, there is no need: the result of <code>fetch_assoc</code> will either be <em>a mysqli result set</em> or <code>null</code>. Which is equivalent to <code>true</code> or <code>false</code> so a strict comparison to <code>null</code> isn't required.</p>\n<p>Instead you can simply use:</p>\n<pre><code>if ($result) {\n</code></pre>\n<p>After all, if any <code>false</code> equivalent value was returned you wouldn't want to proceed. If you did then, at minimum, you would gain a bunch of <code>Notices</code> in your error log from trying to access non-existent array indexes.</p>\n<h2>Sessions</h2>\n<p>To put it bluntly, your first <code>if</code> statement never succeeds! You know this (I think) because you have implemented a work around with the duplicated <code>if</code> statements at the bottom of the code.</p>\n<p>If you think about it: you'd never end up in a loop because after the first time the code is called the <code>$_SESSION[&quot;id&quot;]</code> is set and therefore the opening <code>if</code> statement will evaluate to <code>false</code> on subsequent page loads.</p>\n<p>So then the question is, <strong><em>why does it loop?</em></strong></p>\n<p>The answer is simple: the <code>$_SESSION</code> super global doesn't exist until <strong>after</strong> <code>session_start();</code> is called. Up until that point...</p>\n<pre><code>$_SESSION === null;\n\n// And...\n\nisset($_SESSION) === false;\n</code></pre>\n<p>...no matter how many indexes you've assigned to it.</p>\n<p>So in your <code>if</code> statement <code>isset(...)</code> evaluates to <code>false</code> and is then <em>flipped</em> with the preceding <code>!</code> to <code>true</code> and therefore the code bock is executed.</p>\n<p>The solution then is to make sure <code>session_start();</code> is at the very top of your file.</p>\n<pre><code>&lt;?php\n\nsession_start();\n\nif (!isset($_SESSION[&quot;id&quot;])) {\n // Do something...\n}\n</code></pre>\n<p>Getting this right means you can do away with both of the duplicated <code>if</code> statements as now you won't have that endless loop.</p>\n<h2>Cookie management</h2>\n<p>You <strong>must</strong> delete the cookie if it doesn't match. You don't want random expired, useless, cookies sitting around. They may cause unexpected behaviour.</p>\n<p>Cookies should not contain the users password (especially not in plain text form). We don't really want user details like (e.g. username and email address) stored in cookies either. In the event that a cookie is <code>hijacked</code> it would make using that information much easier.</p>\n<p>Leaving both the username and password in the cookie means that if it were <code>stolen</code> then the attacker would have access to the account until the user changes their password worse still the attacker could change the password and lock out the real user!</p>\n<h2>Misc.</h2>\n<p><strong>Variable names</strong></p>\n<p>Names like <code>$connection</code> aren't very clear to a reader unfamiliar with your code (connection to what?). Much better to use a name with clear meaning such as <code>$mysqli</code> (because it's a mysqli object) or <code>$mysqliConnection</code>.</p>\n<p><strong>Storing credentials in <code>$_SESSION</code></strong></p>\n<p>You don't need to store anything apart from the <code>id</code>. Anything else can be looked up in the database based on the <code>id</code> because it is (or should be) a <code>PRIMARY KEY</code>.</p>\n<h2>Database and SQL</h2>\n<p><strong>Password storage</strong></p>\n<p>You <strong>must not</strong> store a users password in plain text form. There are so many reasons why it's hard to know where to begin, but here are two of the key reasons:</p>\n<ol>\n<li>If your database is leaked those passwords are accessible to the world</li>\n<li>Anyone with access to the database can see ALL your users' passwords\n<ul>\n<li>Inevitably a percentage of your users will reuse the same (or similar) passwords elsewhere which means anyone with access to the DB can now access other accounts (i.e. other websites) belonging to your users!</li>\n</ul>\n</li>\n</ol>\n<p>PHP has in built functions to hash and check passwords:</p>\n<pre><code>// Hash the password; on account creation\n\n$password = &quot;mySuperStrongPassword&quot;; // User enters\n$passwordHash = password_hash($password, PASSWORD_DEFAULT); // DB stores\n\n// Check the password against the DBs hash; on login\n\nif (password_verify($password, $passwordHash)) {\n // Succesfully matched the password!\n}\n</code></pre>\n<p><strong>SQL in prepare</strong></p>\n<p>For short queries it's okay to put them directly into the <code>prepare</code> method. It's good practice though to keep them in a separate variable - especially for longer and more complex ones. Keeping them separate means you have more flexibility in formatting the query without confusing the flow of the page.</p>\n<p><strong>Table names</strong></p>\n<p>It's good practice to <em>not user plurals</em> as database table names. There's no major flaw here but it makes your code nicer/easier to read because <em>usually</em> we're working on one individual record at a time:</p>\n<pre><code>// In SQL queries...\n\nSELECT user.email FROM user WHERE user.id = 123;\nSELECT users.email FROM users WHERE users.id = 123;\n\n// In PHP..\n\nwhile ( $user = $query-&gt;fetchObject() ) {\n echo $user-&gt;email;\n}\n</code></pre>\n<p><strong><code>SELECT *</code></strong></p>\n<p>There's no harm in using the <code>*</code> operator to <code>SELECT</code> all records - unless you're selecting a large number of rows, the table consists of a large number of columns, or the columns pack large volumes of data.</p>\n<p>For example, let's assume you're selecting all <em>employees</em> (e.g. 50 records) and each record has a <code>blob</code> for a profile picture. All of a sudden that's a much larger chunk of memory compared to the email address fields we were actually after!</p>\n<p>So, it's much better to be explicit about what fields you want returned when you can be. In your case we're only interested in the <code>password</code> and <code>id</code> columns:</p>\n<pre><code>SELECT id, password FROM `users` WHERE `username` = ?\n</code></pre>\n<hr />\n<h2>Persistent logon</h2>\n<p><strong>DB Structure</strong></p>\n<p>If you only wanted a user to be active on one device at a time then you could simply add a field (or two) to the <code>users</code> table.</p>\n<p>In most circumstances though it's preferred that users can logon on multiple devices; so we need to implement a one to many relationship in the database with the addition of a new <code>session</code> table. Which, on a simplistic level, will look something like:</p>\n<pre><code>CREATE TABLE session (\n id int AUTO_INCREMENT PRIMARY KEY,\n user_id int,\n cookie_id varchar(250),\n hash varchar(250),\n expires datetime\n);\n</code></pre>\n<p><strong>Code Example</strong></p>\n<p>Normal logon:</p>\n<pre><code>&lt;?php\n\nsession_start();\n\nrequire_once(__DIR__ . '/../dbh/dbh.php');\n\n$username = $_POST[&quot;username&quot;] ?? null;\n$password = $_POST[&quot;password&quot;] ?? null;\n$persistent = $_POST[&quot;persistent&quot;] ?? null;\n\nif ($username &amp;&amp; $password) {\n\n $logonSQL = &quot;SELECT id, password FROM user WHERE username = ?&quot;;\n $logonQuery = $mysqli-&gt;prepare($logonSQL);\n $logonQuery-&gt;bind_param(&quot;s&quot;, $username);\n $logonQuery-&gt;execute();\n\n $user = $logonQuery-&gt;get_result()-&gt;fetch_assoc();\n\n if ($user) {\n if (password_verify($password, $user[&quot;password&quot;])) {\n // Logged on\n $_SESSION[&quot;id&quot;] = $user[&quot;id&quot;];\n\n // Create cookie, if persistent is checked\n if ($persistent) {\n // Create a session cookie\n $cookieId = bin2hex(random_bytes(50));\n $hash = bin2hex(random_bytes(50));\n $dbHash = password_hash($hash, PASSWORD_DEFAULT);\n $expires = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;+30 days&quot;));\n\n $sessionSQL = &quot;\n INSERT INTO session\n (user_id, cookie_id, hash, expires)\n VALUES\n (?, ?, ?, ?)\n &quot;;\n $sessionQuery = $mysqli-&gt;prepare($sql);\n $sessionQuery-&gt;bind_param(&quot;isss&quot;, $user[&quot;id&quot;], $cookieId, $dbHash, $expires);\n $sessionQuery-&gt;execute();\n\n setcookie(&quot;rememberme&quot;, $cookieId.$hash, strtotime(&quot;+30 days&quot;));\n }\n } else {\n // Wrong credentials...\n }\n }\n}\n</code></pre>\n<p>Logon with cookie:</p>\n<pre><code>&lt;?php\n\nsession_start();\n\nif (!isset($_SESSION[&quot;id&quot;]) &amp;&amp; isset($_COOKIE[&quot;rememberme&quot;])) {\n list($cookieId, $hash) = str_split($_COOKIE[&quot;rememberme&quot;], 100);\n\n $sessionSQL = &quot;\n SELECT id, user_id, hash, expires\n FROM session\n WHERE cookieId = ?\n &quot;;\n $sessionQuery = $mysqli-&gt;prepare($sessionSQL);\n $sessionQuery-&gt;bind_param(&quot;s&quot;, $cookieId);\n $sessionQuery-&gt;execute();\n\n $session = $sessionQuery-&gt;get_result-&gt;fetch_assoc();\n\n if (\n password_verify($hash, $session[&quot;hash&quot;]) &amp;&amp;\n $session[&quot;expires&quot;] &gt; date(&quot;Y-m-d H:i:s&quot;)\n ) {\n // Successful login with cookies\n\n $_SESSION[&quot;id&quot;] = $session[&quot;user_id&quot;];\n\n $hash = bin2hex(random_bytes(50));\n $dbHash = password_hash($hash, PASSWORD_DEFAULT);\n $expires = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;+30 days&quot;));\n\n /**\n * Regenerating the hash\n *\n * You don't have to do this _every_ time but frequently enough\n * that the hash doesn't become _stale_.\n *\n * Regenerating the hash means that even if your cookie is\n * hijacked the next time the _real_ user logs on the session\n * will be scrubbed and the _attacker_ won't be able to log on\n * with the stolen cookie again.\n *\n */\n\n setcookie(&quot;rememberme&quot;, $cookieId.$hash, strtotime(&quot;+30 days&quot;));\n\n $updateSQL = &quot;\n UPDATE session\n SET \n expires = ?,\n hash = ?\n WHERE id = ?\n &quot;;\n $updateQuery = $mysqli-&gt;prepare($updateSQL);\n $updateQuery-&gt;bind_param(&quot;ssi&quot;, $expires, $hash, $session[&quot;id&quot;]);\n } else {\n // Session expired or logon credentials incorrect...\n // Delete cookie and session record\n \n setcookie(&quot;rememberme&quot;, &quot;&quot;, 1);\n \n unset($_SESSION[&quot;id&quot;]);\n\n $deleteSQL = &quot;DELETE FROM session WHERE id = ?&quot;;\n $deleteQuery = $mysqli-&gt;prepare($deleteSQL)\n $deleteQuery-&gt;bind_param(&quot;i&quot;, $session[&quot;id&quot;]);\n $deleteQuery-&gt;execute();\n }\n}\n</code></pre>\n<p>Log off:</p>\n<pre><code>if ($_GET[&quot;logout&quot;] ?? null) {\n if (isset($_COOKIE[&quot;rememberme&quot;])) {\n $cookieId = substr($_COOKIE[&quot;rememberme&quot;], 0, 100);\n\n $deleteSQL = &quot;DELETE FROM session WHERE cookie_id = ?&quot;;\n $deleteQuery = $mysqli-&gt;prepare($deleteSQL)\n $deleteQuery-&gt;bind_param(&quot;s&quot;, $cookieId);\n $deleteQuery-&gt;execute();\n\n setcookie(&quot;rememberme&quot;, &quot;&quot;, 1);\n }\n\n unset($_SESSION[&quot;id&quot;]);\n\n header(&quot;location: /safeplace.html&quot;);\n}\n</code></pre>\n<p><strong>Notes</strong></p>\n<ul>\n<li>The above code is untested, there's likely a few typos etc.</li>\n<li>The code also doesn't check to ensure that the <code>cookie_id</code> is unique in the DB\n<ul>\n<li>Very unlikely to happen on a small site</li>\n<li>Not a security problem, even if it did, because the worst case scenario is a session gets removed\n<ul>\n<li>Unless the <code>1 in 64^100</code> occurs and the hash/cookie_id are the same</li>\n</ul>\n</li>\n<li>Perhaps something to look at to ensure a consistent user experience</li>\n</ul>\n</li>\n<li>Implementing this code you'd probably want to <code>logout</code> any active user before trying to <code>logon</code> with new credentials\n<ul>\n<li>Save any bugs</li>\n</ul>\n</li>\n<li>You may also want to factor in things like garbage collection in the <code>session</code> table to remove expired sessions</li>\n<li>It's common practice that a <code>remember me</code> session doesn't have total access to the system\n<ul>\n<li>For example, you wouldn't let someone change their password without challenging them for the old password first!</li>\n<li>This helps prevent problems if/when cookies are stolen</li>\n</ul>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T17:28:50.813", "Id": "504751", "Score": "0", "body": "wow. This is incredible. It's been 2 months since I asked that question so by now I already know most of the stuff you described, but nevertheless I have to say - this is absolutely incredible answer and I still learned few things from it. Thank you very much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T02:32:26.190", "Id": "504802", "Score": "0", "body": "Haha thank you! I saw it had been here for a while (I've recently migrated from SO) without an answer and it caught my interest. Also I thought it was the kind of post that future readers might find helpful so deserved an answer... Good to hear you're making progress and that there were still some useful bits for you as well!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T15:27:17.917", "Id": "255762", "ParentId": "252475", "Score": "2" } } ]
{ "AcceptedAnswerId": "255762", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T09:24:36.947", "Id": "252475", "Score": "2", "Tags": [ "php" ], "Title": "Handling user sessions on website using $_COOKIE and $_SESSION" }
252475
<p>this is my 2nd project on Python. I created a game of Noughts and Crosses(Tic-Tac-Toe) that you can play against the computer. What are your thoughts on my implementation of the game? Is there anything I've missed or could improve upon?</p> <p>I did think about adding a figure window and making it more interactive by clicking on where you want to move however that seemed a bit too advanced.</p> <pre><code>import random import sys import numpy as np # Today we are going to make an interactive game in Python. # This is going to be a game of noughts and crosses! # Initialise grid and collection of X's or O's needed to win a game. grid = [[&quot;_&quot;, &quot;_&quot;, &quot;_&quot;], [&quot;_&quot;, &quot;_&quot;, &quot;_&quot;], [&quot;_&quot;, &quot;_&quot;, &quot;_&quot;]] print(np.asarray(grid)) # To make the output represent a grid instead of a list of lists. row_os = [&quot;O&quot;, &quot;O&quot;, &quot;O&quot;] row_xs = [&quot;X&quot;, &quot;X&quot;, &quot;X&quot;] coords_picked = [] # Create a loop to find all co-ordinates in our grid all_coords = [] for x in range(3): for y in range(3): all_coords.append((x, y)) turn = 0 remaining_coords = [] while turn &lt; 10: # Find status of each column column_1 = [row[0] for row in grid] column_2 = [row[1] for row in grid] column_3 = [row[2] for row in grid] # Find status of 2 diagonals main_diag = [row[i] for i, row in enumerate(grid)] counter_diag = [row[-i - 1] for i, row in enumerate(grid)] # Winning conditions for each player if (grid[0] == row_os or grid[1] == row_os or grid[2] == row_os) or ( column_1 == row_os or column_2 == row_os or column_3 == row_os) or (main_diag == row_os) or ( counter_diag == row_os): print(&quot;The computer has won!&quot;) sys.exit() elif (grid[0] == row_xs or grid[1] == row_xs or grid[2] == row_xs) or ( column_1 == row_xs or column_2 == row_xs or column_3 == row_xs) or (main_diag == row_xs) or ( counter_diag == row_xs): print(&quot;Well done, you have won!&quot;) sys.exit() else: # If nobody has won yet, take another turn if turn % 2 == 0: x_coord = input() y_coord = input() coords_picked.append((int(x_coord), int(y_coord))) grid[int(x_coord)][int(y_coord)] = &quot;X&quot; print(np.asarray(grid)) turn += 1 else: # Computer randomly picks a co-ordinate in the grid that has not been picked yet remaining_coords = list(set(all_coords) - set(coords_picked)) comp_coords = random.choice(remaining_coords) grid[comp_coords[0]][comp_coords[1]] = &quot;O&quot; coords_picked.append((comp_coords[0], comp_coords[1])) print(comp_coords) print(np.asarray(grid)) turn += 1 print(&quot;A draw?! We must play again!&quot;) </code></pre>
[]
[ { "body": "<p>I don't use <code>numpy</code>, and I'm getting errors when trying to use it on 3.9, but it seems unnecessary here. If you want to pretty-print a grid, that can be done succinctly using <code>join</code>:</p>\n<pre><code>def format_grid(grid):\n return &quot;\\n&quot;.join(&quot; &quot;.join(row) for row in grid)\n</code></pre>\n<p>Which, when you replace all uses of <code>asarray</code>, gives output like:</p>\n<pre><code>X _ _\n_ _ _\n_ _ O\n</code></pre>\n<p>I wouldn't import <code>numpy</code> just to help format. That's a heavy dependency for little gain.</p>\n<hr />\n<p>These lines:</p>\n<pre><code>grid = [[&quot;_&quot;, &quot;_&quot;, &quot;_&quot;], [&quot;_&quot;, &quot;_&quot;, &quot;_&quot;], [&quot;_&quot;, &quot;_&quot;, &quot;_&quot;]]\nrow_os = [&quot;O&quot;, &quot;O&quot;, &quot;O&quot;]\nrow_xs = [&quot;X&quot;, &quot;X&quot;, &quot;X&quot;]\n</code></pre>\n<p>Can make use of &quot;sequence multiplication&quot; to reduce the duplication:</p>\n<pre><code>SIDE_LENGTH = 3 \n\ngrid = [[&quot;_&quot;] * SIDE_LENGTH for _ in range(SIDE_LENGTH)]\nrow_os = [&quot;O&quot;] * SIDE_LENGTH \nrow_xs = [&quot;X&quot;] * SIDE_LENGTH\n</code></pre>\n<hr />\n<p>I'd change <code>all_coords</code>, <code>coords_picked</code>, and <code>remaining_coords</code> to be sets from the start. It isn't efficient to create them as lists, then convert them to sets whenever you want to use them. This unfortunately requires that <code>remaining_coords</code> be converted to a list before being given to <code>random.choice</code>, but that's still less conversions being done overall.</p>\n<p>You could probably just get rid of <code>remaining_coords</code> too and just use:</p>\n<pre><code>comp_coords = random.choice(list(all_coords - coords_picked))\n</code></pre>\n<p>You have it as a global variable, even though you're recalculating it each time anyways. It would be even more efficient though to not recalculate it each time, and instead make a copy of <code>all_coords</code> at the start, then <code>del</code> elements from the set as they're picked. That's probably an unnecessary level of optimization for here though.</p>\n<hr />\n<p>You can clean up the winning checks by making use of <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a> and comprehensions. First, change <code>column_1</code>, <code>column_2</code>, and <code>column_3</code> to:</p>\n<pre><code>columns = [[row[i]\n for row in grid]\n for i in range(SIDE_LENGTH)]\n</code></pre>\n<p>Whenever you're postfixing variable names with numbers, you probably want a list instead.</p>\n<p>Next, the conditions themselves:</p>\n<pre><code>if any((any(row == row_os for row in grid),\n any(col == row_os for col in columns),\n any(diag == row_os for diag in [main_diag, counter_diag]))):\n print(&quot;The computer has won!&quot;)\n sys.exit()\nelif any((any(row == row_xs for row in grid),\n any(col == row_xs for col in columns),\n any(diag == row_xs for diag in [main_diag, counter_diag]))):\n print(&quot;Well done, you have won!&quot;)\n sys.exit()\n</code></pre>\n<p>There's probably a better way of writing this still, but I haven't had my coffee yet. Basically, I'm again using a comprehensions (or rather, generator expressions) to reduce duplication. If you're writing <code>grid[0]</code>, <code>grid[1]</code>, <code>grid[2]</code> manually, you likely want to iterate over <code>grid</code> instead.</p>\n<p>You could also wrap that condition up in a function, then use the function in both places since each condition is basically the same.</p>\n<p>The inner <code>any</code>s could also be replaced with unpacking to make use of the outer <code>any</code>:</p>\n<pre><code>if any((*(row == row_os for row in grid),\n *(col == row_os for col in columns),\n *(diag == row_os for diag in [main_diag, counter_diag]))):\n</code></pre>\n<p>But I'm not sure that that's much better.</p>\n<hr />\n<p>You should add in error handling. When testing this, I got multiple errors. I accidentally entered <code>3</code> in, and got an <code>IndexError</code>, and accidentally pressed enter without entering a number and got a <code>ValueError</code>. Really, the user entering bad input should be expected and handled.</p>\n<hr />\n<hr />\n<p>At the end, I have:</p>\n<pre><code>import random\nimport sys\n\nSIDE_LENGTH = 3\n\n\ndef format_grid(grid):\n return &quot;\\n&quot;.join(&quot; &quot;.join(row) for row in grid)\n\n\ngrid = [[&quot;_&quot;] * SIDE_LENGTH for _ in range(SIDE_LENGTH)]\nrow_os = [&quot;O&quot;] * SIDE_LENGTH\nrow_xs = [&quot;X&quot;] * SIDE_LENGTH\ncoords_picked = set()\n\nprint(format_grid(grid)) # To make the output represent a grid instead of a list of lists.\n\n# Create a loop to find all co-ordinates in our grid\nall_coords = set()\nfor x in range(SIDE_LENGTH):\n for y in range(SIDE_LENGTH):\n all_coords.add((x, y))\n\nturn = 0\nremaining_coords = set()\n\nwhile turn &lt; 10:\n # Find status of each column\n columns = [[row[i]\n for row in grid]\n for i in range(SIDE_LENGTH)]\n\n # Find status of 2 diagonals\n main_diag = [row[i] for i, row in enumerate(grid)]\n counter_diag = [row[-i - 1] for i, row in enumerate(grid)]\n\n # Winning conditions for each player\n if any((any(row == row_os for row in grid),\n any(col == row_os for col in columns),\n any(diag == row_os for diag in [main_diag, counter_diag]))):\n print(&quot;The computer has won!&quot;)\n sys.exit()\n elif any((any(row == row_xs for row in grid),\n any(col == row_xs for col in columns),\n any(diag == row_xs for diag in [main_diag, counter_diag]))):\n print(&quot;Well done, you have won!&quot;)\n sys.exit()\n else:\n # If nobody has won yet, take another turn\n if turn % 2 == 0:\n x_coord = input()\n y_coord = input()\n coords_picked.add((int(x_coord), int(y_coord)))\n grid[int(x_coord)][int(y_coord)] = &quot;X&quot;\n print(format_grid(grid))\n turn += 1\n else:\n # Computer randomly picks a co-ordinate in the grid that has not been picked yet\n remaining_coords = all_coords - coords_picked\n comp_coords = random.choice(list(remaining_coords))\n grid[comp_coords[0]][comp_coords[1]] = &quot;O&quot;\n coords_picked.add((comp_coords[0], comp_coords[1]))\n print(comp_coords)\n print(format_grid(grid))\n turn += 1\n\nprint(&quot;A draw?! We must play again!&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T19:05:52.767", "Id": "497652", "Score": "0", "body": "Thanks for the tips and help, I'll make sure to add the corrections and exceptions!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T16:05:28.577", "Id": "252489", "ParentId": "252478", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T10:57:08.997", "Id": "252478", "Score": "5", "Tags": [ "python", "game", "tic-tac-toe" ], "Title": "Game of Noughts and Crosses Feedback" }
252478
<p>Implementation is based on the MVC design pattern, with callbacks to allow model and view to communicate with controller.</p> <p>Concerns:</p> <p>It's not ideal to have async code inside the model, i.e the model should be as close to a basic hashtable implementation as possible. However since we need to set a chain of calls to the view to animate things while in the middle of the model methods, I couldn't see another way.</p> <p>In the middle of animations the user trying to insert new keys would cause problems, so I temporarily disable the ability to click on the buttons. This works well from the clients point of view, but in terms of code I'm wondering if there's a cleaner way to do it.</p> <p>hashtable.ts</p> <pre><code>const enum ModelMessages { Searching, Found, UpdateVal, ExpandArray, NotFound, } // implementation of a hashtable with linear probing class HashTable { private readonly notifyController: (message: ModelMessages, arg: any) =&gt; void; private readonly LOAD_FACTOR: number; private keys: (number | null)[]; private entryCount: number; private arrayLength: number; constructor( initialCapacity: number, notify: (message: ModelMessages, arg: any) =&gt; void ) { this.notifyController = notify; this.LOAD_FACTOR = 0.75; this.keys = []; this.entryCount = 0; this.arrayLength = initialCapacity; } public async add(key: number): Promise&lt;void&gt; { let index; let offset = 0; do { index = this.hashFunction(key + offset); offset++; await this.notifyController(ModelMessages.Searching, index); } while (this.keys[index] !== undefined &amp;&amp; this.keys[index] !== key); await this.notifyController(ModelMessages.Found, index); await this.notifyController(ModelMessages.UpdateVal, [index, key]); this.entryCount += this.keys[index] === undefined ? 1 : 0; this.keys[index] = key; this.handleArrayResize(); } public async contains(key: number): Promise&lt;boolean&gt; { return (await this.getIndexOfKey(key)) !== -1; } public clear(): void { this.keys = []; this.entryCount = 0; } public async delete(key: number): Promise&lt;boolean&gt; { const index = await this.getIndexOfKey(key); if (index === -1) { return false; } this.keys[index] = null; await this.notifyController(ModelMessages.UpdateVal, [index, null]); return true; } private handleArrayResize(): void { if (this.arrayLength * this.LOAD_FACTOR &lt; this.entryCount) { this.expandArray(); } } private hashFunction(arg: number): number { return Math.abs(arg) % this.arrayLength; } private async expandArray(): Promise&lt;void&gt; { const oldKeyArray = this.keys; this.clear(); this.arrayLength *= 2; await this.notifyController(ModelMessages.ExpandArray, this.arrayLength); for (let i = 0; i &lt; this.arrayLength / 2; i++) { if (oldKeyArray[i] !== undefined &amp;&amp; oldKeyArray[i] !== null) { await this.add(&lt;number&gt;oldKeyArray[i]); } } } private async getIndexOfKey(key: number): Promise&lt;number&gt; { let index; let offset = 0; do { index = this.hashFunction(key + offset); await this.notifyController(ModelMessages.Searching, index); if (this.keys[index] === undefined) { await this.notifyController(ModelMessages.NotFound, index); return -1; } offset++; } while (this.keys[index] !== key); await this.notifyController(ModelMessages.Found, index); return index; } } </code></pre> <p>controller.ts</p> <pre><code>const hashtable = new HashTable(8, readMessageFromModel); const view = new View(8, readMessageFromView); async function readMessageFromView( message: ViewMessages, arg: any ): Promise&lt;void&gt; { switch (message) { case ViewMessages.Search: await hashtable.contains(&lt;number&gt;arg); break; case ViewMessages.Insert: await hashtable.add(&lt;number&gt;arg); break; case ViewMessages.Delete: await hashtable.delete(&lt;number&gt;arg); break; case ViewMessages.Clear: hashtable.clear(); view.resetArray(); break; default: throw &quot;View has notified controller with unsupported type&quot;; } } async function readMessageFromModel( message: ModelMessages, arg: any ): Promise&lt;void&gt; { switch (message) { case ModelMessages.Searching: await view.highlightSearching(&lt;number&gt;arg); break; case ModelMessages.Found: await view.highlightFound(&lt;number&gt;arg); break; case ModelMessages.NotFound: await view.highlightNotFound(&lt;number&gt;arg); break; case ModelMessages.UpdateVal: view.updateCellValueAt.apply(view, &lt;[number, number | null]&gt;arg); break; case ModelMessages.ExpandArray: view.expandArray(&lt;number&gt;arg); break; default: throw &quot;Model has notified controller with unsupported type&quot;; } } </code></pre> <p>view.ts</p> <pre><code>const enum ViewMessages { Insert, Search, Delete, Clear, } class View { private arrayLength: number; private readonly notifyController: (message: ViewMessages, arg: any) =&gt; void; private readonly ARRAY_WIDTH: number = 1500; constructor( defaultLength: number, notify: (message: ViewMessages, arg: any) =&gt; void ) { this.arrayLength = defaultLength; this.notifyController = notify; this.initialiseView(); } public async highlightFound(index: number): Promise&lt;void&gt; { await this.highlightGeneric(index, &quot;#32CD32&quot;); } public async highlightSearching(index: number): Promise&lt;void&gt; { await this.highlightGeneric(index, &quot;#33D5FF&quot;); } public async highlightNotFound(index: number): Promise&lt;void&gt; { await this.highlightGeneric(index, &quot;red&quot;); } public updateCellValueAt(index: number, val: number | null): void { if (val !== null) { this.getCellInDOM(index).innerHTML = `${val}`; } else { this.getCellInDOM(index).innerHTML = &quot;⚰️&quot;; } } public expandArray(newSize: number): void { this.arrayLength = newSize; this.resetArray(); } public resetArray(): void { this.clearArray(); this.createArrayInDOM(); } private async highlightGeneric(index: number, color: string): Promise&lt;void&gt; { this.getCellInDOM(index).style.backgroundColor = color; await this.delay(); this.getCellInDOM(index).style.backgroundColor = &quot;white&quot;; } private clearArray(): void { const array = this.getArrayinDOM(document.querySelector(&quot;#array&quot;)); array.innerHTML = &quot;&quot;; } private initialiseView(): void { this.createArrayInDOM(); this.addMenuClickListeners(); } private addMenuClickListeners(): void { document .querySelector(&quot;#search&quot;) ?.addEventListener(&quot;click&quot;, () =&gt; this.searchForKey()); document .querySelector(&quot;#insert&quot;) ?.addEventListener(&quot;click&quot;, () =&gt; this.insertKey()); document .querySelector(&quot;#delete&quot;) ?.addEventListener(&quot;click&quot;, () =&gt; this.deleteKey()); document .querySelector(&quot;#clear&quot;) ?.addEventListener(&quot;click&quot;, () =&gt; this.clear()); } private clear(): void { this.notifyController(ViewMessages.Clear, null); } private async notifyControllerWithInputValue( inputField: HTMLInputElement | null, message: ViewMessages ): Promise&lt;void&gt; { this.blockMenuButtons(); if (inputField !== null) { const input = &lt;HTMLInputElement&gt;inputField; if (!isNaN(parseInt(input.value))) { await this.notifyController(message, parseInt(input.value)); } } else { throw &quot;Input field argument was null&quot;; } this.enableMenuButtons(); } private searchForKey(): void { this.notifyControllerWithInputValue( document.querySelector(&quot;#search-input&quot;), ViewMessages.Search ); } private insertKey(): void { this.notifyControllerWithInputValue( document.querySelector(&quot;#insert-input&quot;), ViewMessages.Insert ); } private deleteKey(): void { this.notifyControllerWithInputValue( document.querySelector(&quot;#delete-input&quot;), ViewMessages.Delete ); } private blockMenuButtons(): void { this.getButtonInDOM(document.querySelector(&quot;#search&quot;)).style.pointerEvents = &quot;none&quot;; this.getButtonInDOM(document.querySelector(&quot;#insert&quot;)).style.pointerEvents = &quot;none&quot;; this.getButtonInDOM(document.querySelector(&quot;#delete&quot;)).style.pointerEvents = &quot;none&quot;; this.getButtonInDOM(document.querySelector(&quot;#clear&quot;)).style.pointerEvents = &quot;none&quot;; } private enableMenuButtons(): void { this.getButtonInDOM(document.querySelector(&quot;#search&quot;)).style.pointerEvents = &quot;auto&quot;; this.getButtonInDOM(document.querySelector(&quot;#insert&quot;)).style.pointerEvents = &quot;auto&quot;; this.getButtonInDOM(document.querySelector(&quot;#delete&quot;)).style.pointerEvents = &quot;auto&quot;; this.getButtonInDOM(document.querySelector(&quot;#clear&quot;)).style.pointerEvents = &quot;auto&quot;; } private getButtonInDOM(button: HTMLButtonElement | null): HTMLButtonElement { if (button === null) { throw &quot;Button supplied is null&quot;; } else { return &lt;HTMLButtonElement&gt;button; } } private createArrayInDOM(): void { const array = this.getArrayinDOM(document.querySelector(&quot;#array&quot;)); const row = document.createElement(&quot;tr&quot;); array.style.width = `${this.ARRAY_WIDTH}px`; array.append(row); for (let i = 0; i &lt; this.arrayLength; i++) { row.append(this.createCellInDOM(i)); } } private createCellInDOM(index: number): HTMLTableCellElement { const newCell = document.createElement(&quot;td&quot;); newCell.style.width = `${this.ARRAY_WIDTH / this.arrayLength}px`; newCell.style.height = `${this.ARRAY_WIDTH / this.arrayLength}px`; newCell.style.fontSize = `${(this.ARRAY_WIDTH / this.arrayLength) * 4}%`; newCell.className = &quot;cell&quot;; return newCell; } private getCellInDOM(index: number): HTMLTableCellElement { const arrayDOM = this.getArrayinDOM(document.querySelector(&quot;#array&quot;)); const rowDOM = arrayDOM.rows[0]; const cellDOM = rowDOM.cells[index]; return cellDOM; } private getArrayinDOM(array: HTMLTableElement | null): HTMLTableElement { if (array === null) { throw &quot;Element supplied is null&quot;; } else { return &lt;HTMLTableElement&gt;array; } } private delay(): Promise&lt;string&gt; { const delayTimeInMilliseconds = 300; return new Promise((resolve) =&gt; { setTimeout(resolve, delayTimeInMilliseconds); }); } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T11:29:18.257", "Id": "252479", "Score": "2", "Tags": [ "typescript", "dom", "hash-map" ], "Title": "Hashtable Visualizer in TypeScript" }
252479
<p>Here's the code I'm having trouble shortening. I am currently a beginner in Python 3.x.</p> <pre><code>from os import system def fibonacci(terms): count = 0 x = 0 y = 1 z = x + y if terms &lt;= 0: print(&quot;Enter a positive integer.&quot;) elif terms == 1: print(&quot;Fibonacci sequence in &quot; + str(terms) + &quot; terms.&quot;) print(x) else: print(&quot;Printing &quot; + str(terms) + &quot; terms.&quot;) while count &lt; terms: print(x) z = x + y x = y y = z count += 1 while True: user_input = int(input(&quot;How many terms? &quot;)) fibonacci(user_input) loop = input(&quot;Again? (Y/n) &quot;) if loop == &quot;Y&quot; or loop == &quot;&quot;: system(&quot;cls&quot;) else: exit() </code></pre> <p>I would appreciate if there will be someone who will be able to make this as efficient as possible.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-23T04:48:21.960", "Id": "497582", "Score": "2", "body": "Ahoy! Welcome to code review. I [changed the title](https://codereview.stackexchange.com/posts/252485/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate" } ]
[ { "body": "<h1>Separate responsibilities</h1>\n<p>Your functions should, where possible, limit themselves to doing one thing only. This is the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">single-responsibility principle</a>. In case of <code>fibonacci()</code>, I expect this function to just calculate the desired Fibonacci number, and not deal with user input and output. This shortens the function and makes it easier to reason about. So:</p>\n<pre><code>def fibonacci(terms):\n count = 0\n x = 0\n y = 1\n z = x + y\n\n while count &lt; terms:\n yield x\n z = x + y\n x = y\n y = z\n count += 1\n</code></pre>\n<p>Instead of printing the values, it <code>yield</code>s them. To print the values, use the following:</p>\n<pre><code>terms = int(input(&quot;How many terms? &quot;))\nfor number in fibonacci(terms):\n print(number)\n</code></pre>\n<p>You can even go futher and make <code>fibonacci()</code> an infinite generator, and leave it up to the caller to decide when to stop:</p>\n<pre><code>import itertools\n\ndef fibonacci():\n x = 0\n y = 1\n\n while True:\n yield x\n z = x + y\n x = y\n y = z\n\nterms = int(input(&quot;How many terms? &quot;))\nfor number in itertools.islice(fibonacci(), terms):\n print(number)\n</code></pre>\n<p>Here I used <a href=\"https://docs.python.org/2/library/itertools.html#itertools.islice\" rel=\"noreferrer\"><code>itertools.islice()</code></a> to take only the first <code>terms</code> items from the generator.</p>\n<p>If you want to handle invalid input gracefully, I suggest you write another function whose responsibility is asking the user for a postivive integer:</p>\n<pre><code>def get_positive_integer(prompt):\n while True:\n user_input = int(input(prompt))\n if ...: \n return user_input\n print(&quot;Enter a positive integer.&quot;)\n</code></pre>\n<h1>Avoid using <code>os.system()</code></h1>\n<p>Using <code>os.system()</code> to clear the screen is very inefficient and not portable. Of course it is prettier to clear the screen, but if it is not really important for your program, I would just not do it; portability is more important.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T16:45:19.203", "Id": "497529", "Score": "1", "body": "as an addition OP constructs: `print(\"Fibonacci sequence in \" + str(terms) + \" terms.\"` could use `format` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T16:45:51.990", "Id": "497530", "Score": "5", "body": "@Jean-FrançoisFabre Format is old, f-strings are good" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T16:46:17.037", "Id": "497531", "Score": "1", "body": "yeah, unless you're stuck with a legacy version of python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T16:48:09.673", "Id": "497533", "Score": "0", "body": "One drawback of f-strings is that they don't really work well in combination with [internationalization](https://stackoverflow.com/questions/49797658/how-to-use-gettext-with-python-3-6-f-strings)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T15:49:16.017", "Id": "252487", "ParentId": "252485", "Score": "14" } }, { "body": "<pre><code> z = x + y\n x = y\n y = z\n</code></pre>\n<p>is not idiomatic Python. Consider</p>\n<pre><code> x, y = y, x + y\n</code></pre>\n<hr />\n<p>Regarding optimization, since you want <em>all</em> terms, there is not much to optimize. <em>If</em> wanted a <em>specific</em> term, a matrix exponentiation would be a way to go.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T19:41:19.867", "Id": "252496", "ParentId": "252485", "Score": "7" } } ]
{ "AcceptedAnswerId": "252487", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T14:35:26.957", "Id": "252485", "Score": "6", "Tags": [ "python", "beginner", "python-3.x", "fibonacci-sequence" ], "Title": "Fibonacci sequence output" }
252485