body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I don't know if my test cases at the bottom cover every case, or if my mathematical logic in the reducer function is exactly right (referring to the math that starts with <code>(d1 + d2 &gt;= 10)</code>). More importantly I'm uncomfortable with the readability of this code as it's rather compact and difficult to parse, so any feedback is appreciated!</p> <p>(As an afterthought, I'm also not sure how this would scale if the question simply changed from adding two numbers to adding N numbers, since the carry digit wouldn't always be <code>1</code>.)</p> <p>It would be nice if all functions were one-liners, also. Two of them aren't.</p> <pre class="lang-js prettyprint-override"><code>/*** * Problem Statement: * Given two numbers `n1` and `n2`, write a function that returns * the number of carry operations required to add them digit-by-digit, * similar to pen-and-paper arithmetic with a `1` being carried as * the digits are added column-wise right-to-left, like this: * * 49 * + 55 * ---- * 104 * * The right-most column is 9+5=14, which is two digits, * so we carry the `1` and write `4`. That's a carry operation. * * The left-most column is 4+5=9, but we add the carried `1`, * so we write `10` before `4`. I don't know if this is a carry or not, but I assume not. * * In the end, we wrote `104`, and a single carry operation happened, * so `f(49, 55)` is `1`. Arguably the answer is `2`. * * More tests are below. */ // Here's my solution in JavaScript which is O(n): // Helper functions: const indexes = arr =&gt; arr.map((_, i) =&gt; i); const getDigits = n =&gt; n.toString().split('').map(Number); const getArithmeticRows = (n1, n2) =&gt; [n1, n2].map(n =&gt; getDigits(n).reverse()); /*** * `f(n1, n2)` takes two integers and returns the integer number * of carries required to add `n1` and `n2`. */ const numberOfCarryOperations = (n1, n2) =&gt; { const rows = getArithmeticRows(n1, n2), [row1, row2] = rows; return ((row1.length &gt; row2.length) ? indexes(row1) : indexes(row2)) .reduce((partialCarry, _, i) =&gt; { const [d1, d2] = rows.map(row =&gt; row[i] || 0); return partialCarry + ( ((d1 + d2 &gt;= 10) || (d1 === 9 &amp;&amp; partialCarry !== 0) || (d2 === 9 &amp;&amp; partialCarry !== 0)) ? 1 : 0 ); }, 0); }; // Tests: console.log(numberOfCarryOperations(44, 56)); // pass (1) console.log(numberOfCarryOperations(9999, 1)); // pass (4) console.log(numberOfCarryOperations(1, 9999)); // pass (4) console.log(numberOfCarryOperations(55, 49)); // pass (1) console.log(numberOfCarryOperations(50, 49)); // pass (0) console.log(numberOfCarryOperations(12345, 4)); // pass (0) console.log(numberOfCarryOperations(31, 24)); // pass (0) console.log(numberOfCarryOperations(56799, 5)); // pass (2) console.log(numberOfCarryOperations(6, 99999)); // pass (5) console.log(numberOfCarryOperations(66, 99999)); // pass (5) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:38:26.967", "Id": "516198", "Score": "1", "body": "There is a neat mathematical way. Number of carry operations when adding `x` and `y` in base `b` can be calculated using `(s(x) + s(y) - s(x+y)) / (b-1)` where `s(n)` is the sum of digits of `n` in base `b`, which is simply `n%b + s(n/b)` if `n>0` and `0` when `n==0`. - *This is because when a carry occurs, the current digit decreases by `b` and the next one increases by `1`, which is a change of `(b-1)` in the sum of digits.*" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T19:09:43.100", "Id": "261525", "Score": "1", "Tags": [ "javascript", "interview-questions" ], "Title": "Find the number of carry operations needed to add two numbers digit by digit" }
261525
<h2>taken from <a href="https://leetcode.com/problems/the-skyline-problem/" rel="nofollow noreferrer">leetcode.com</a>:</h2> <p>A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. [...] <a href="https://i.stack.imgur.com/l0jZA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l0jZA.png" alt="enter image description here" /></a></p> <p>please review this code. I'm most interested in feedback about OOP-Principles (SOLID, readability, etc.) and second most interested on performance.</p> <h2>class Solution</h2> <pre><code>public class Solution { public static void main(String[] args) { final int[][] input = {{2,9,10},{3,7,15},{5,12,12},{15,20,10},{19,24,8}}; Solution solution = new Solution(); System.out.println(&quot;amount : &quot;+solution.getSkyline(input)); } //this crude method is a HARD REQUIREMENT and may not be changed! public List&lt;List&lt;Integer&gt;&gt; getSkyline(int[][] buildings) { SkyLineConverter skyLineConverter = new SkyLineConverter(); SkyLine skyLine = skyLineConverter.convert(buildings); Set&lt;Edge&gt; edges = skyLine.getEdges(); return sortList(edges); } private List&lt;List&lt;Integer&gt;&gt; sortList(Set&lt;Edge&gt; edges) { List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;(); List&lt;Edge&gt; list = new ArrayList&lt;&gt;(edges); list.sort(Comparator.comparingInt(o -&gt; o.x)); for(Edge edge: list){ List&lt;Integer&gt; intList = new ArrayList&lt;&gt;(); intList.add(edge.x); intList.add(edge.height); result.add(intList); } return result; } } </code></pre> <h2>class SkyLineConverter</h2> <pre><code>public class SkyLineConverter { public SkyLine convert(int[][] raw) { BuildingConverter buildingConverter = new BuildingConverter(); List&lt;Building&gt; buildings = buildingConverter.convert(raw); return new SkyLine(buildings); } } </code></pre> <h2>class Building</h2> <pre><code>public class Building { public final int x; public final int width; public final int height; public Building(int x, int width, int height) { this.x = x; this.width = width; this.height = height; } } </code></pre> <h2>class BuildingConverter</h2> <pre><code>public class BuildingConverter { private static final int FROM_INDEX = 0; private static final int TO_INDEX = 1; private static final int HEIGHT_INDEX = 2; public List&lt;Building&gt; convert(int[][] raw) { List&lt;Building&gt; buildings = new ArrayList&lt;&gt;(); for (int[] buildingRaw: raw){ int x = buildingRaw[FROM_INDEX]; int width = buildingRaw[TO_INDEX] - buildingRaw[FROM_INDEX]; int height = buildingRaw[HEIGHT_INDEX]; buildings.add(new Building(x,width,height)); } return buildings; } } </code></pre> <h2>class Skyline</h2> <pre><code>public class SkyLine { private final int width; private final Set&lt;Edge&gt; edges = new HashSet&lt;&gt;(); private final List&lt;Building&gt; buildings; public SkyLine(List&lt;Building&gt; buildings) { this.buildings = buildings; Building mostRight = findMostRight(buildings); width = mostRight.x + mostRight.width; addEdge(); } private void addEdge() { buildings.forEach(b -&gt; { addEdge(b.x); addEdge(b.x + b.width); }); edges.add(new Edge(width, 0)); } private void addEdge(int x) { int skyline = getSkyLine(x); int previous = x == 0 ? 0 : getSkyLine(x - 1); if (previous &lt; skyline || previous &gt; skyline) { edges.add(new Edge(x, skyline)); } } private int getSkyLine(int x) { List&lt;Building&gt; aroundThisPoint = buildings.stream(). filter(b -&gt; b.x &lt;= x &amp;&amp; b.x + b.width &gt; x). collect(Collectors.toList()); return aroundThisPoint.stream().mapToInt(b -&gt; b.height).max().orElse(0); } private Building findMostRight(List&lt;Building&gt; buildings) { Optional&lt;Building&gt; mostRight = buildings.stream().reduce((a, b) -&gt; a.x &gt; b.x ? a : b); //noinspection OptionalGetWithoutIsPresent return mostRight.get(); } public Set&lt;Edge&gt; getEdges() { return edges; } } </code></pre> <h2>class Edge</h2> <pre><code>public class Edge { public final int x; public final int height; public Edge(int x, int height){ this.x = x; this.height = height; } } </code></pre>
[]
[ { "body": "<p>I noticed you have used stream library in most of your code, so I thought about increasing readability with less lines of code using streams if possible because other parts looks fine to me. In your <code>Solution</code> class you have the following method :</p>\n<pre><code>private List&lt;List&lt;Integer&gt;&gt; sortList(Set&lt;Edge&gt; edges) {\n List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();\n List&lt;Edge&gt; list = new ArrayList&lt;&gt;(edges);\n list.sort(Comparator.comparingInt(o -&gt; o.x));\n for(Edge edge: list){\n List&lt;Integer&gt; intList = new ArrayList&lt;&gt;();\n intList.add(edge.x);\n intList.add(edge.height);\n result.add(intList);\n }\n return result;\n}\n</code></pre>\n<p>You could directly iterate over the <code>edges</code> set combining <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--\" rel=\"nofollow noreferrer\"><code>Stream#sorted</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-\" rel=\"nofollow noreferrer\"><code>Stream#map</code></a>, so avoiding the need of explicitly instantiate a list like my method below:</p>\n<pre><code>private List&lt;List&lt;Integer&gt;&gt; sortList(Set&lt;Edge&gt; edges) {\n \n return edges.stream()\n .sorted(Comparator.comparingInt(edge -&gt; edge.x))\n .map(edge -&gt; List.of(edge.x, edge.height))\n .collect(Collectors.toList()); \n}\n</code></pre>\n<p>In your <code>BuildingConverter</code> class you have the following method:</p>\n<pre><code>public List&lt;Building&gt; convert(int[][] raw) {\n List&lt;Building&gt; buildings = new ArrayList&lt;&gt;();\n for (int[] buildingRaw: raw){\n int x = buildingRaw[FROM_INDEX];\n int width = buildingRaw[TO_INDEX] - buildingRaw[FROM_INDEX];\n int height = buildingRaw[HEIGHT_INDEX];\n buildings.add(new Building(x,width,height));\n }\n return buildings;\n}\n</code></pre>\n<p>It is possible streaming every row of your <code>int[][] raw</code> 2d array with <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#stream-int:A-\" rel=\"nofollow noreferrer\"><code>Arrays#stream</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-\" rel=\"nofollow noreferrer\"><code>Stream#map</code></a> obtaining the same expected result like below:</p>\n<pre><code>public List&lt;Building&gt; convert(int[][] raw) {\n\n return Arrays.stream(raw)\n .map(arr -&gt; new Building(arr[FROM_INDEX], \n arr[TO_INDEX] - arr[FROM_INDEX], \n arr[HEIGHT_INDEX]))\n .collect(Collectors.toList());\n}\n</code></pre>\n<p>In your class <code>SkyLine</code> you have the following two methods that can be simplified:</p>\n<pre><code>private int getSkyLine(int x) {\n List&lt;Building&gt; aroundThisPoint = buildings.stream().\n filter(b -&gt; b.x &lt;= x &amp;&amp; b.x + b.width &gt; x).\n collect(Collectors.toList());\n return aroundThisPoint.stream().mapToInt(b -&gt; b.height).max().orElse(0);\n}\n\nprivate Building findMostRight(List&lt;Building&gt; buildings) {\n Optional&lt;Building&gt; mostRight = buildings.stream().reduce((a, b) -&gt;\n a.x &gt; b.x ? a : b);\n //noinspection OptionalGetWithoutIsPresent\n return mostRight.get();\n}\n</code></pre>\n<p>In your <code>getSkyLine</code> method there is no need to instantiate an intermediate list that will be streamed, you can combine your code lines in a more succinct method:</p>\n<pre><code>private int getSkyLine(int x) {\n \n return buildings.stream()\n .filter(b -&gt; b.x &lt;= x &amp;&amp; b.x + b.width &gt; x)\n .mapToInt(b -&gt; b.height)\n .max()\n .orElse(0);\n}\n</code></pre>\n<p>Your <code>findMostRight</code> method could be simplified using the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#max-java.util.Collection-java.util.Comparator-\" rel=\"nofollow noreferrer\"><code>Collections#max</code></a> like below:</p>\n<pre><code>private Building findMostRight(List&lt;Building&gt; buildings) {\n\n return Collections.max(buildings, Comparator.comparingInt(b -&gt; b.x));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:09:40.603", "Id": "516173", "Score": "1", "body": "wow - java8 and streams are already so old and i still do not know how to use them properly - thank you very very much for these improvements!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T05:42:16.777", "Id": "516177", "Score": "1", "body": "@MartinFrank You are welcome, that also applies to me, I don't remember all the stream methods and without ide autocomplete I would be lost :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T06:28:30.377", "Id": "516178", "Score": "1", "body": "Thanks mdfst13 for the grammar corrections." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:31:00.567", "Id": "261554", "ParentId": "261533", "Score": "2" } } ]
{ "AcceptedAnswerId": "261554", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T04:46:49.253", "Id": "261533", "Score": "3", "Tags": [ "java", "object-oriented" ], "Title": "SkylineProblem in Java" }
261533
<p>I have made this <strong>Pagination</strong> Class in JS which takes the following configurations :-</p> <ul> <li>Total records</li> <li>Records per page</li> <li>Visible pages</li> </ul> <p>The idea is simple that any instance created using this <strong>Pagination</strong> class should be easy to use and separate the view logic from the pagination logic. I have also added few validations as per the configurations passed as of now.</p> <p>Below is the 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>// Records to paginate on const records = [ ...Array(346) .fill("") .map((val, index) =&gt; `Name-${val - index}`) ]; // Paginator Class class Paginator { constructor(totalRecords, recordsPerPage = 1, visiblePages = 1) { this.recordsPerPage = recordsPerPage; this.totalRecords = totalRecords; this.noOfPages = Math.ceil(this.totalRecords / this.recordsPerPage); this.visiblePages = visiblePages; this.activePage = 1; this.visiblePagesEndRange = visiblePages; // below validations can be improved and really not necessary for bare minimum pagination but ‍♂️ this.validate(); } validate() { if (this.recordsPerPage &lt;= 0) { this.recordsPerPage = 1; } if (this.visiblePages &lt;= 0) { this.visiblePages = 1; } if(this.totalRecords&lt;=0){ this.totalRecords = 1; } if (this.noOfPages &lt;= 0) { this.noOfPages = Math.ceil(this.totalRecords / this.recordsPerPage); } if (this.visiblePagesEndRange &lt;= 0) { this.visiblePagesEndRange = this.visiblePages; } if (this.visiblePages &gt; this.noOfPages) { this.visiblePages = this.noOfPages; this.visiblePagesEndRange = this.visiblePages; } if (this.recordsPerPage &gt; this.totalRecords) { this.recordsPerPage = this.totalRecords; } } gotoNextPage() { if (this.activePage &lt; this.noOfPages) { this.activePage += 1; if (this.activePage &gt; this.visiblePagesEndRange) { this.visiblePagesEndRange += this.visiblePages; this.visiblePagesEndRange = Math.min(this.visiblePagesEndRange, this.noOfPages); } } } gotoPrevPage() { if (this.activePage &gt; 1) { this.activePage -= 1; if (this.activePage % this.visiblePages === 0) { this.visiblePagesEndRange = this.activePage; } } } gotoFirstPage() { this.activePage = 1; this.visiblePagesEndRange = this.visiblePages; } gotoLastPage() { this.activePage = this.noOfPages; this.visiblePagesEndRange = this.noOfPages; } gotoPage(page) { this.activePage = page; } getVisiblePagesRange() { let beginningVisiblePage; let endingVisiblePage; // When the visiblepagesendrange % visiblepages is not zero (which means that all the pages cannot be fit in the visible pages range) and if our ending page range is equal to total no pages then the beginning would be equivalent to visble page range - ((visible page range mod visiblepage range) - 1) i.e the leftover pages until the end. if (this.visiblePagesEndRange % this.visiblePages !== 0 &amp;&amp; this.visiblePagesEndRange === this.noOfPages) { beginningVisiblePage = this.visiblePagesEndRange - ((this.visiblePagesEndRange % this.visiblePages) - 1); } // else we are always in a place where, current visible page end range - visible page range + 1 will return us the correct beginning position for the page range. else { beginningVisiblePage = this.visiblePagesEndRange - this.visiblePages + 1; } //Also endingActivePage would be simply equal visiblePagesEndRange. endingVisiblePage = this.visiblePagesEndRange; return { beginningVisiblePage, endingVisiblePage }; } getActivePageIndices() { // the beginning page index will be current active page multiplied by no of records. let beginningPageIndex = (this.activePage - 1) * this.recordsPerPage; // the ending page index will be minimum of total records and (beginning + records allowed per page); let endingPageIndex = Math.min( beginningPageIndex + this.recordsPerPage, this.totalRecords ); return { beginningPageIndex, endingPageIndex }; } } // All the render and using Paginator class logic comes here (function () { function nextPage() { paginator.gotoNextPage(); render(); } function prevPage() { paginator.gotoPrevPage(); render(); } function lastPage() { paginator.gotoLastPage(); render(); } function firstPage() { paginator.gotoFirstPage(); render(); } // Delegating event to the parent ul. function gotoPage(event) { if (event.target.nodeName === "BUTTON") { const page = parseInt(event.target.dataset.item); paginator.gotoPage(page); render(); } } const paginationPages = document.querySelector(".pagination__pages"); paginationPages.addEventListener("click", gotoPage); /* paginator object list which is of length 346 recordsPerPage = 6 visiblePages = 6 */ const paginator = new Paginator(records.length,6, 6); // Method to render the pagination buttons; function renderPages() { const paginationPages = document.querySelector(".pagination__pages"); let html = ""; let { beginningVisiblePage, endingVisiblePage } = paginator.getVisiblePagesRange(); for (let page = beginningVisiblePage; page &lt;= endingVisiblePage; page++) { const pageClass = paginator.activePage === page ? "pagination__page-btn--active" : "pagination__page-btn"; html += `&lt;li class='pagination__page'&gt; &lt;button data-item=${page} class=${pageClass}&gt;${page}&lt;/button&gt; &lt;/li&gt;`; } paginationPages.innerHTML = html; } // Method to render the list items function renderList() { const list = document.querySelector(".list"); const { beginningPageIndex, endingPageIndex } = paginator.getActivePageIndices(); let html = ""; for (let index = beginningPageIndex; index &lt; endingPageIndex; index++) { html += `&lt;li class='list__item'&gt;${records[index]}&lt;/li&gt;`; } list.innerHTML = html; } // Main render function function render() { renderPages(); renderList(); } render(); this.firstPage = firstPage; this.lastPage = lastPage; this.nextPage = nextPage; this.prevPage = prevPage; this.gotoPage = gotoPage; })();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.pagination__pages { display: inline-flex; list-style-type: none; padding: 0; } .pagination__page-btn{ border:1px solid black; } .pagination__navigate-btn { border:1px solid black; } .pagination__page-btn--active { border:1px solid black; background: #a3a3ff; } .list { list-style-type: none; padding: 0; } .app-container{ display:flex; flex-direction:column; align-items:center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;section class='app-container'&gt; &lt;ul class='list'&gt; &lt;/ul&gt; &lt;div class='pagination__wrapper'&gt; &lt;section class='pagination__items'&gt; &lt;button class='pagination__navigate-btn' onclick='firstPage()'&gt;First&lt;/button&gt; &lt;button class='pagination__navigate-btn' onclick='prevPage()'&gt;Prev&lt;/button&gt; &lt;ul class='pagination__pages'&gt; &lt;/ul&gt; &lt;button class='pagination__navigate-btn' onclick='nextPage()'&gt;Next&lt;/button&gt; &lt;button class='pagination__navigate-btn' onclick='lastPage()'&gt;Last&lt;/button&gt; &lt;/section&gt; &lt;/div&gt; &lt;/section&gt;</code></pre> </div> </div> </p> <p>I am interested in knowing the pitfalls of it and any scope of improvement for the same.</p>
[]
[ { "body": "<ol>\n<li>I think Paginator need only one change page</li>\n<li>in most cases, an Ajax request is required and we have to take care of this callback (<code>render</code> - is callback )</li>\n<li>we have to create methods for change limit (<code>changeMax</code>)</li>\n<li>we have to create methods for change locale (<code>changeLocale</code>)</li>\n<li>external code should not affect the paginator (<code>nextPage</code>, <code>prev</code> ... inside class Paginator) use callbacks</li>\n</ol>\n<p>Example</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 records = [\n ...Array(346)\n .fill(\"\")\n .map((val, index) =&gt; `Name-${val - index}`)\n];\n\nclass Paginator {\n\n constructor(max, visible, id, callback) {\n this.max = max;\n this.visible = Number(visible);\n this.id = id;\n this.offset = 0;\n this.pageEvent = callback;\n this.btnFirst = 'First';\n this.btnLast = 'Last';\n this.btnNext = 'Next';\n this.btnPrev = 'Prev';\n }\n\n\n init(total, max, current = 1) {\n this.total = Number(total);\n this.max = Number(max);\n this.pages = Math.ceil(this.total / this.max);\n this.goToPage(current);\n\n return this;\n }\n\n\n changeLocale(locale) {\n\n this.btnFirst = locale.first;\n this.btnLast = locale.last;\n this.btnNext = locale.next;\n this.btnPrev = locale.prev;\n this.render();\n }\n\n changeMax(max) {\n\n this.init(this.total, max, this.visible, this.id, this.pageEvent);\n }\n\n goToPage(page) {\n this.current = page;\n this.offset = Number((page - 1) * this.max);\n this.limit = Number(this.offset + this.max &lt; this.total ? this.max : this.total - this.offset);\n this.render();\n this.pageEvent(this.current, this.offset, this.limit);\n }\n\n render() {\n const id = this.id;\n let elem = document.getElementById(id);\n elem.innerHTML = '';\n if (this.pages &lt; 2) return;\n if (this.pages &lt;= this.visible) {\n for (let i = 1; i &lt;= this.pages; i++) {\n this.addElem(elem, i, i);\n }\n } else {\n this.addElem(elem, this.btnFirst, 1);\n\n if(this.current &lt;= this.visible) {\n for (let i = 1; i &lt;= this.visible; i++) {\n this.addElem(elem, i, i);\n }\n let next = (this.current + this.visible) - ((this.current + this.visible - 1)%this.visible);\n next = next &gt; this.pages ? this.pages : next;\n this.addElem(elem, '...');\n this.addElem(elem, this.btnNext, next);\n }\n\n else if(this.current &gt; this.visible &amp;&amp; this.current &lt; (this.pages - 1)) {\n let prev = (this.current - this.visible) - ((this.current + this.visible - 1)%this.visible);\n prev = prev &lt; 1 ? 1 : prev;\n let next = (this.current + this.visible) - ((this.current + this.visible - 1)%this.visible);\n next = next &gt; this.pages ? this.pages : next;\n this.addElem(elem, this.btnPrev, prev);\n this.addElem(elem, '...');\n for (let i = this.current; i &lt; this.current + this.visible; i++) {\n this.addElem(elem, i, i);\n }\n this.addElem(elem, '...');\n this.addElem(elem, this.btnNext, next);\n\n }\n\n else {\n this.addElem(elem, this.btnPrev, this.current - 1);\n this.addElem(elem, '...');\n for (let i = this.pages - this.visible; i &lt;= this.pages; i++) {\n this.addElem(elem, i, i);\n }\n\n }\n\n this.addElem(elem, this.btnLast, this.pages);\n }\n }\n\n\n addElem(elem, name, page = null) {\n let el = document.createElement(\"div\");\n const that = this;\n el.innerHTML =\n `&lt;p class=\"page ${this.current == page ? 'active': ''}\" &gt;${name}&lt;/p&gt;`;\n elem.appendChild(el);\n if(page) {\n el.addEventListener('click', event =&gt; {\n this.goToPage.call(that, page);\n });\n }\n\n }\n\n\n}\n\n\nconst pag = new Paginator(10, 3,'paginator', render);\n\ngetData(pag.offset, pag.max).then(res =&gt; {\n pag.init(records.length, 10);\n});\n\nfunction changeMax(max){\n pag.changeMax(max);\n}\n\n\nfunction changeLocale() {\n pag.changeLocale({first: \"Первая\", last: \"Последняя\", next: \"След\", prev: \"Пред\"});\n}\n\n\nfunction render(page, offset, limit) {\n\n getData(offset, limit).then((res) =&gt; {\n const elem = document.getElementById('data-list');\n elem.innerHTML = \"\";\n for(let i = 0; i &lt; res.data.length; i++ ) {\n let el = document.createElement(\"p\");\n el.innerHTML = `${res.data[i]}`;\n elem.appendChild(el);\n }\n });\n}\n\n\nfunction getData(offset, limit) {\n let res = [];\n for(let i = offset; i &lt; offset + limit; i++ ) {\n res.push(records[i]);\n }\n\n return Promise.resolve({\n data: res,\n total: records.length\n });\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#data-list p{\n margin: 2px;\n font-size:14px;\n}\n\n.change {\n cursor:pointer;\n color: green;\n}\n\n\n\n#paginator {\n width: 100%;\n display: flex;\n flex-direction: row;\n justify-content: flex-start;\n}\n\n#paginator .page {\n min-width: 15px;\n text-align:center;\n border: 1px solid #999;\n cursor: pointer;\n padding: 5px;\n}\n\n#paginator .page.active {\n color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"data-list\"&gt;\n&lt;/div&gt;\n\n\n\n&lt;div id=\"paginator\"&gt;&lt;/div&gt;\n\n&lt;select onchange=\"changeMax(this.options[this.selectedIndex].value)\"&gt;\n &lt;option value=\"10\"&gt; 10&lt;/option&gt;\n &lt;option value=\"20\"&gt; 20&lt;/option&gt;\n&lt;/select&gt;\n\n&lt;div class=\"change\" onclick=\"changeLocale()\"&gt;change locale to rus&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:28:44.473", "Id": "261586", "ParentId": "261536", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T06:45:51.380", "Id": "261536", "Score": "2", "Tags": [ "javascript", "pagination" ], "Title": "Client side Pagination implementation in vanilla js" }
261536
<h2>Scenarios / Requirements:</h2> <p>I am working on to convert the existing WebAPI Data Layer to <code>Dapper</code> from <code>EF</code>. The following are the major scenarios / my aim during the UoW implementation.</p> <ol> <li>Transaction handling for one database (database transaction).</li> <li>Transaction handling between database tables (Transaction Scope).</li> <li>Service methods calls another service methods to do some functionalities.</li> <li>Proper connection / UoW disposal.</li> <li>Need to allow DI for Repositories also.</li> <li>Connection creation should be hide from the service layer</li> </ol> <p><em><strong>My aim of this question is to :</strong></em></p> <ul> <li>Please look into my implementation and suggest any improvements or better practice</li> <li>Any code smell or issues</li> </ul> <p>I think it will be useful for others also</p> <h2>My Implementation</h2> <p>I searched for Dapper UoW and got <a href="https://stackoverflow.com/questions/31298235/how-to-implement-unit-of-work-pattern-with-dapper/45029588#45029588">this</a> stack overflow thread. I liked the answers of <a href="https://stackoverflow.com/users/5779732/amit-joshi">Amit Joshi</a> and <a href="https://stackoverflow.com/users/1734730/nathan-cooper">Nathan Cooper</a>. I just start from the answers and mix or extend both answers according to my needs.</p> <p>Thank you both of you for the helpful answers and also to <a href="https://stackoverflow.com/users/2421277/pim">pim</a> which was also nice.</p> <p>Here I created a sample WebAPI with 2 databases(Production and Purchase). We need to use Transaction Scope for transactions between database, we have to initialize the connection inside the Transaction Scope. So started the same way <code>@amit-joshi</code> implemented but the class name (Dal Session) I used from <code>@nathan-cooper</code>. In order to inject the repositories, I passed UOw context as parameter to the repositories as explained by <code>@nathan-cooper</code> with some changes.</p> <p>In order to handle multiple databases, I created 2 different UOw context and inject thorugh DI.Please find my code below;</p> <p><strong>Models:</strong></p> <pre><code> //Database Name : Production public class Product { public int ProductID { get; set; } public string Name { get; set; } public int ProductCategoryId { get; set; } } public class ProductCategory { public int ProductCategoryID { get; set; } public string Name { get; set; } public List&lt;Product&gt; Products { get; set; } } //Database Name : Purchase public class Vendor { public int VendorID { get; set; } public string Name { get; set; } public int CreditRating { get; set; } public List&lt;Product&gt; Products { get; set; } } </code></pre> <p><strong>DatabaseName Enum:</strong></p> <pre><code>public enum DatabaseConnectionName { Production, Purchase } </code></pre> <p><strong>Unit Of Work pattern:</strong></p> <pre><code>public interface IUnitOfWorkContext { UnitOfWork Create(); IDbConnection Connection { get; } IDbTransaction Transaction { get; } } public interface IProductionUnitOfWorkContext : IUnitOfWorkContext { } public interface IPurchaseUnitOfWorkContext : IUnitOfWorkContext { } public abstract class UnitOfWorkContextBase : IUnitOfWorkContext, IDisposable { private readonly IDbConnection _connection = null; private UnitOfWork _unitOfWork; private bool IsUnitOfWorkOpen =&gt; !(_unitOfWork == null || _unitOfWork.IsDisposed); public UnitOfWorkContextBase(DatabaseConnectionName connectionName) { _connection = new SqlConnection(Constants.Get(connectionName)); } public IDbConnection Connection { get { if (!IsUnitOfWorkOpen) { throw new InvalidOperationException( &quot;There is not current unit of work from which to get a connection. Call BeginTransaction first&quot;); } return _unitOfWork.Connection; } } public IDbTransaction Transaction { get { if (!IsUnitOfWorkOpen) { throw new InvalidOperationException( &quot;There is not current unit of work from which to get a connection. Call BeginTransaction first&quot;); } return _unitOfWork.Transaction; } } public UnitOfWork Create() { if (IsUnitOfWorkOpen) { throw new InvalidOperationException( &quot;Cannot begin a transaction before the unit of work from the last one is disposed&quot;); } _connection.Open(); _unitOfWork = new UnitOfWork(_connection); return _unitOfWork; } public void Dispose() { _unitOfWork.Dispose(); _connection.Dispose(); } } public class ProductionUnitOfWorkContext : UnitOfWorkContextBase, IProductionUnitOfWorkContext { public ProductionUnitOfWorkContext() :base(DatabaseConnectionName.Production) { } } public class PurchaseUnitOfWorkContext : UnitOfWorkContextBase, IPurchaseUnitOfWorkContext { public PurchaseUnitOfWorkContext() : base(DatabaseConnectionName.Purchase) { } } public sealed class UnitOfWork : IDisposable { public IDbConnection Connection { get; } = null; public IDbTransaction Transaction { get; private set; } = null; public bool IsDisposed { get; private set; } = false; public UnitOfWork(IDbConnection connection) { Connection = connection; } public void Begin() { Transaction = Connection.BeginTransaction(); } public void Commit() { Transaction.Commit(); Dispose(); } public void RollBack() { Transaction.Rollback(); Dispose(); } public void Dispose() { Transaction?.Dispose(); Transaction = null; IsDisposed = true; } } </code></pre> <p><strong>Autofac DI Registration:</strong></p> <pre><code> builder.RegisterType&lt;GeneralService&gt;() .As&lt;IGeneralService&gt;(); builder.RegisterType&lt;ProductionUnitOfWorkContext&gt;() .As&lt;IProductionUnitOfWorkContext&gt;().InstancePerLifetimeScope(); builder.RegisterType&lt;PurchaseUnitOfWorkContext&gt;() .As&lt;IPurchaseUnitOfWorkContext&gt;().InstancePerLifetimeScope(); builder.RegisterType&lt;ProductCategoryRepository&gt;() .As&lt;IProductCategoryRepository&gt;().InstancePerLifetimeScope(); builder.RegisterType&lt;ProductRepository&gt;() .As&lt;IProductRepository&gt;().InstancePerLifetimeScope(); builder.RegisterType&lt;VendorRepository&gt;() .As&lt;IVendorRepository&gt;().InstancePerLifetimeScope(); </code></pre> <p><strong>Service Methods:</strong></p> <pre><code>public class GeneralService : IGeneralService { private readonly IPurchaseUnitOfWorkContext _purchaseUoWContext; private readonly IProductionUnitOfWorkContext _productionUoWContext; private IVendorRepository _vendorRepo; private IProductRepository _ProductRepo; private IProductCategoryRepository _ProductCategoryRepo; public GeneralService(IPurchaseUnitOfWorkContext purchaseUoWContext, IProductionUnitOfWorkContext productionUowContext, IVendorRepository vendorRepository, IProductRepository productRepository, IProductCategoryRepository productCategoryRepo, IProductService productService) { _purchaseUoWContext = purchaseUoWContext; _productionUoWContext = productionUowContext; _vendorRepo = vendorRepository; _ProductRepo = productRepository; } //Simple insert without Transaction public void AddProductCategory(ProductCategory entity) { var unitOfWork = _productionUoWContext.Create(); try { var id = _ProductCategoryRepo.Add(entity); } catch (Exception) { throw; } } //Insert Products along with Category- Tranaction in Single Database (Production) public void AddProductCategoryAndProducts(ProductCategory entity) { var unitOfWork = _productionUoWContext.Create(); unitOfWork.Begin(); try { var categoryId = _ProductCategoryRepo.Add(entity); foreach (var product in entity.Products) { product.ProductCategoryId = categoryId; _ProductRepo.Add(product); } unitOfWork.Commit(); } catch (Exception) { unitOfWork.RollBack(); throw; } } //Insert 'Products along with Vendor - Transaction between databases public void AddVendor(Vendor entity) { try { using (TransactionScope scope = new TransactionScope()) { var purchaseUow = _purchaseUoWContext.Create(); var productionUoW = _productionUoWContext.Create(); var vendorId = _vendorRepo.Add(entity); foreach (var product in entity.Products) { product.ProductCategoryId = 1; var productId = _ProductRepo.Add(product); } scope.Complete(); } } catch (Exception ex) { throw; } } } </code></pre> <p><strong>Repositories</strong></p> <p>Skipping repositories as it already in the original answers. Currently dapper implemented as independent repository classes</p> <h2>Demerits Found:</h2> <ol> <li>In Transaction Scope scenario, no option to restrict developer to start transaction in the UoW.</li> <li>There is an UoW Creation issue, if the service calls to another service with in the same Database UoW context as the UOW is already created. Ex. Production Category service calls AddProduct method from Product Service (instead of product repository) it will fail as the ProductionUowContext already created UOW in the category service.</li> </ol> <p>Please share your views or improvement points</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T07:14:50.917", "Id": "261537", "Score": "0", "Tags": [ "c#", "repository", "asp.net-web-api", "dapper" ], "Title": "Dapper UOW with Multiple Databases" }
261537
<h1>Basic Description</h1> <h2>What is the program for?</h2> <p>This is just a hobby project for me to improve at coding, not a serious one.</p> <h2>What does the program do?</h2> <p>It can take a chess position (not including variations like chess960 etc.), and generate all legal moves from it. Draw and checkmates are not added yet.</p> <h1>File and function description</h1> <h2><code>main.cpp/hpp</code> - Currently only used for testing</h2> <p><strong>Note</strong> The functions here are just for debugging, thus don't matter much. Any feedback on how to write better code here is still appreciated though.</p> <ul> <li><code>perft()/perftDivide()</code> Perft test to check the move generation function.</li> <li><code>printStateTest()</code> Only used for debugging; prints the gameState.</li> </ul> <h2><code>gameState.cpp/hpp</code> - Basic board handling</h2> <ul> <li><code>gameState</code> - Game state class.</li> <li><code>addPiece()/deletePiece()/movePieceFromPos()</code> Pretty self-explanatory.</li> <li><code>initWithFEN()</code> Initialize game state with FEN notation.</li> <li><code>isSameColor()/isSameType()</code> Compare the color/type of two pieces.</li> <li><code>oppositeColor()</code> Make the piece an opponent's piece.</li> </ul> <h2><code>piece.hpp</code> - Defines the enum value of the pieces</h2> <h2><code>move.cpp/hpp</code> - Move handling</h2> <ul> <li><code>pieceMove</code> Move class.</li> <li><code>initMove()</code> Initialize pieceMove.</li> <li><code>applyMove()</code> Makes a move and updates the game state accordingly.</li> <li><code>cordAlgebraicToNum()</code> Converts an algebraic coordinate to the internal numeric format.</li> <li><code>cordNumToAlgebraic()</code> Opposite of the function above.</li> <li><code>moveToUCI()</code> Converts a piece move to UCI format.</li> </ul> <h2><code>moveGen.cpp/hpp</code> - Move generation</h2> <ul> <li><code>isInCheck()</code> Check if the selected side is in check. Doesn't use the function below, to increase performance .</li> <li><code>generatePseudoMoves()</code> Generate pseudo-legal moves.</li> <li><code>generateLegalMoves()</code> Filter legal moves from the function above.</li> <li><code>generateSlidingMoves()</code> Generate directional moves with specified depth.</li> <li><code>easyMask()</code> Generate move mask (see below).</li> <li><code>moveCanBeMade()</code> Testing if a move can be made without crossing the edge of the board.</li> </ul> <h1>What do I plan to add in the future?</h1> <ul> <li>Positional evaluation</li> <li>AI engine</li> </ul> <h1>What do I wish to improve?</h1> <p>As I plan to implement more features to the code, I'm looking for ways to improve the <strong>structure</strong> and <strong>performance</strong> of it. (e.g. Better algorithms, code style...)</p> <p>Any sort of help is appreciated, and thanks in advance!</p> <h1>The Code</h1> <h2><code>main.cpp</code></h2> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;map&gt; #include &quot;gameState.hpp&quot; #include &quot;pieces.hpp&quot; #include &quot;move.hpp&quot; #include &quot;moveGen.hpp&quot; #include &quot;main.hpp&quot; std::map&lt;std::string, int&gt; perftDivide (gameState currentState, int depth) { std::map&lt;std::string, int&gt; output; int sideToMove = currentState.whiteToMove ? COLOR_WHITE : COLOR_BLACK; std::vector&lt;pieceMove&gt; moveList = generateLegalMoves(currentState, sideToMove); for (int i = 0; i &lt; moveList.size(); ++i) { output[moveToUCI(moveList[i])] = perft(applyMove(currentState, moveList[i]), depth - 1); } return output; } int perft (gameState currentState, int depth) { int sideToMove = currentState.whiteToMove ? COLOR_WHITE : COLOR_BLACK; std::vector&lt;pieceMove&gt; moveList = generateLegalMoves(currentState, sideToMove); int positionNum = 0; if (depth == 0) { return 1; } if (depth == 1) { return moveList.size(); } for (int i = 0; i &lt; moveList.size(); ++i) { positionNum += perft(applyMove(currentState, moveList[i]), depth - 1); } return positionNum; } void printStateTest(gameState test) { //Temp function for printing class gameState std::map&lt;int, char&gt; pieces = { {9, 'P'}, {10, 'N'}, {11,'B'}, {12, 'R'}, {13, 'Q'}, {14, 'K'}, {17, 'p'}, {18, 'n'}, {19,'b'}, {20, 'r'}, {21, 'q'}, {22, 'k'} }; int temp; std::cout &lt;&lt; &quot;Board:\n&quot;; for (int i = 7; i &gt;= 0; --i) { for (int j = 0; j &lt; 8; ++j) { temp = test.board[i * 8 + j]; if (temp != 0) { std::cout &lt;&lt; pieces[temp]; } else { std::cout &lt;&lt; &quot;.&quot;; } } std::cout &lt;&lt; std::endl; } std::cout &lt;&lt; &quot;White To Move: &quot; &lt;&lt; (test.whiteToMove == 1) &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Castling Right: {&quot;; for (int i = 0; i &lt; 4; ++ i) { std::cout &lt;&lt; test.castlingRights[i] &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; &quot;}&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;En Passant: &quot; &lt;&lt; test.enPassant &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Move Clock: &quot; &lt;&lt; test.moveClock &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Moves: &quot; &lt;&lt; test.wholeTurn &lt;&lt; &quot;\n&quot;; } int main() { //Example usage gameState test = initWithFEN(&quot;rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8&quot;); printStateTest(test); std::cout &lt;&lt; &quot;Position &quot; &lt;&lt; perft(test, 4) &lt;&lt; &quot;\n&quot;; return 0; } </code></pre> <h2><code>main.hpp</code></h2> <pre><code>#ifndef main_h #define main_h #include &quot;gameState.hpp&quot; int perft (gameState currentState, int depth); std::map&lt;std::string, int&gt; perftDivide (gameState currentState, int depth); void printStateTest(gameState test); #endif /* main_h */ </code></pre> <h2><code>gameState.cpp</code></h2> <pre><code>#include &lt;string&gt; #include &quot;gameState.hpp&quot; #include &quot;pieces.hpp&quot; #include &quot;move.hpp&quot; std::map&lt;char, int&gt;charToPiece = { {'P', TYPE_PAWN}, {'N', TYPE_KNIGHT}, {'B', TYPE_BISHOP}, {'R', TYPE_ROOK}, {'Q', TYPE_QUEEN}, {'K', TYPE_KING}, }; bool isSameColor (int original, int reference) { return (original &amp; 24) == (reference &amp; 24); } bool isSameType (int original, int reference) { return (original &amp; 7) == (reference &amp; 7); } int oppsiteColor (int original) { int output; switch (original &amp; 24) { case 8: output = (original &amp; 7) | 16; break; case 16: output = (original &amp; 7) | 8; break; default: output = original; } return output; } gameState addPiece (gameState currentState, int pieceType, int position) { gameState newState = currentState; newState.board[position] = pieceType; return newState; } gameState deletePiece (gameState currentState, int position) { gameState newState = currentState; newState.board[position] = 0; return newState; } gameState movePieceFromPos (gameState currentState, int startPos, int endPos) { gameState newState = currentState; newState = addPiece(newState, newState.board[startPos], endPos); newState = deletePiece(newState, startPos); return newState; } gameState initWithFEN (std::string FEN) { gameState newState; std::vector&lt;std::string&gt; parts(6); //Seperate different parts int temp = 0; for (int i = 0; i &lt; FEN.size(); ++i) { if (FEN[i] == ' ') { ++temp; } else { parts[temp] += FEN[i]; } } //Setting up the board int rank = 7, file = 0, piece; std::string boardFEN = parts[0]; char current; for (int i = 0; i &lt; boardFEN.size(); ++i) { current = boardFEN[i]; if (current == '/') { file = 0; --rank; } else { if (isdigit(current)) { file += current - '0'; } else { piece = charToPiece[toupper(current)]; piece += isupper(current) ? COLOR_WHITE : COLOR_BLACK; newState.board[rank * 8 + file] = piece; ++file; } } } //Side to move newState.whiteToMove = (parts[1] == &quot;w&quot;); //Castling rights for (int i = 0; i &lt; parts[2].size(); ++i) { if (parts[2][i] == 'K') { newState.castlingRights[0] = true; } if (parts[2][i] == 'Q') { newState.castlingRights[1] = true; } if (parts[2][i] == 'k') { newState.castlingRights[2] = true; } if (parts[2][i] == 'q') { newState.castlingRights[3] = true; } } //En passant if (parts[3] == &quot;-&quot;) { newState.enPassant = -1; } else { newState.enPassant = cordAlgebraicToNum(parts[3]); } //Half move clock newState.moveClock = std::stoi(parts[4]); //Whole moves newState.wholeTurn = std::stoi(parts[5]); return newState; } #include &quot;gameState.hpp&quot; </code></pre> <h2><code>gameState.hpp</code></h2> <pre><code>#ifndef gameState_hpp #define gameState_hpp #include &lt;stdio.h&gt; #include &lt;vector&gt; #include &lt;string&gt; class gameState { public: std::vector&lt;int&gt; board = std::vector&lt;int&gt;(64); std::vector&lt;bool&gt; castlingRights = std::vector&lt;bool&gt;(4); bool whiteToMove; int enPassant, wholeTurn, moveClock; }; bool isSameColor (int original, int reference); bool isSameType (int original, int reference); int oppsiteColor (int original); gameState addPiece (gameState currentState, int pieceType, int position); gameState deletePiece (gameState currentState, int position); gameState movePieceFromPos (gameState currentState, int startPos, int endPos); gameState initWithFEN (std::string FEN); #endif /* gameState_hpp */ </code></pre> <h2><code>piece.hpp</code></h2> <pre><code>#ifndef pieces_hpp #define pieces_hpp #include &lt;stdio.h&gt; #include &lt;string&gt; #include &lt;map&gt; enum pieceType { //EMPTY = 0, TYPE_PAWN = 1, TYPE_KNIGHT = 2, TYPE_BISHOP = 3, TYPE_ROOK = 4, TYPE_QUEEN = 5, TYPE_KING = 6 }; enum pieceColor { COLOR_WHITE = 8, COLOR_BLACK = 16, COLOR_ANY = 24 }; #endif /* pieces_hpp */ </code></pre> <h2><code>move.cpp</code></h2> <pre><code>#include &quot;move.hpp&quot; #include &quot;gameState.hpp&quot; #include &quot;pieces.hpp&quot; pieceMove initMove (int start, int end, int flag) { pieceMove output; output.startSqr = start; output.endSqr = end; output.flag = flag; return output; } gameState applyMove (gameState currentState, pieceMove move) { //Make move gameState newState; newState = movePieceFromPos(currentState, move.startSqr, move.endSqr); newState.whiteToMove ^= 1; if (newState.whiteToMove) { ++newState.wholeTurn; } if (isSameType(newState.board[move.startSqr], TYPE_PAWN) || newState.board[move.endSqr] != 0) { newState.moveClock = 0; } else { ++newState.moveClock; } int castlingSide, isKingSide; for (int i = 0; i &lt; 8; i += 7) { for (int j = 0; j &lt; 8; j += 7) { if (move.startSqr == (i * 8 + j) || move.endSqr == (i * 8 + j)) { castlingSide = i == 0 ? 0 : 2; isKingSide = j == 0; newState.castlingRights[castlingSide | isKingSide] = false; } } if (move.startSqr == (i * 8 + 4) || move.endSqr == (i * 8 + 4)) { castlingSide = i == 0 ? 0 : 2; newState.castlingRights[castlingSide] = false; newState.castlingRights[castlingSide + 1] = false; } } switch (move.flag) { case FLAG_DOUBLE_JUMP: { newState.enPassant = move.endSqr; break; } case FLAG_EN_PASSANT: { newState.board[newState.enPassant] = 0; newState.enPassant = -1; break; } case FLAG_CASTLE: { int rookStartPosition = (move.startSqr - move.endSqr == 2) ? move.startSqr - 4 : move.startSqr + 3; int rookEndPosition = (move.startSqr - move.endSqr == 2) ? move.startSqr - 1 : move.startSqr + 1; newState = movePieceFromPos(newState, rookStartPosition, rookEndPosition); break; } case FLAG_PROMOTE_KNIGHT: { newState.board[move.endSqr] = (newState.board[move.endSqr] &amp; 24) | TYPE_KNIGHT; break; } case FLAG_PROMOTE_BISHOP: { newState.board[move.endSqr] = (newState.board[move.endSqr] &amp; 24) | TYPE_BISHOP; break; } case FLAG_PROMOTE_ROOK: { newState.board[move.endSqr] = (newState.board[move.endSqr] &amp; 24) | TYPE_ROOK; break; } case FLAG_PROMOTE_QUEEN: { newState.board[move.endSqr] = (newState.board[move.endSqr] &amp; 24) | TYPE_QUEEN; break; } } if (move.flag != FLAG_DOUBLE_JUMP) { newState.enPassant = -1; } return newState; } int cordAlgebraicToNum (std::string cordinate) { return (cordinate[0] - 'a') + (cordinate[1] - '1') * 8; } std::string cordNumToAlgebraic (int cordinate) { char rank = '1' + cordinate / 8; char file = (cordinate % 8) + ((int) 'a'); return std::string() + file + rank; } std::string moveToUCI (pieceMove move) { std::string output; output = cordNumToAlgebraic(move.startSqr) + cordNumToAlgebraic(move.endSqr); switch (move.flag) { case FLAG_PROMOTE_KNIGHT: { output += &quot;n&quot;; break; } case FLAG_PROMOTE_BISHOP: { output += &quot;b&quot;; break; } case FLAG_PROMOTE_ROOK: { output += &quot;r&quot;; break; } case FLAG_PROMOTE_QUEEN: { output += &quot;q&quot;; break; } } return output; } </code></pre> <h2><code>move.hpp</code></h2> <pre><code>#ifndef move_hpp #define move_hpp #include &lt;stdio.h&gt; #include &quot;gameState.hpp&quot; class pieceMove { public: int startSqr; int endSqr; int flag; }; enum moveFlag { FLAG_NONE = 0, FLAG_DOUBLE_JUMP = 1, FLAG_EN_PASSANT = 2, FLAG_CASTLE = 3, FLAG_PROMOTE_KNIGHT = 4, FLAG_PROMOTE_BISHOP = 5, FLAG_PROMOTE_ROOK = 6, FLAG_PROMOTE_QUEEN = 7 }; pieceMove initMove (int start, int end, int flag); gameState applyMove (gameState currentState, pieceMove move); int cordAlgebraicToNum (std::string cordinate); std::string cordNumToAlgebraic (int cordinate); std::string moveToUCI (pieceMove move); #endif /* move_hpp */ </code></pre> <h2><code>moveGen.cpp</code></h2> <pre><code>#include &quot;moveGen.hpp&quot; #include &quot;move.hpp&quot; #include &quot;gameState.hpp&quot; #include &quot;pieces.hpp&quot; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;math.h&gt; bool isInCheck (gameState currentState, int side) { int kingPosition = 0; for (int i = 0; i &lt; 64; ++i) { if (currentState.board[i] == (side | TYPE_KING)) { kingPosition = i; break; } } //Pawn attacks int opponentDirection; opponentDirection = side == COLOR_WHITE ? 8 : -8; for (int i = -1; i &lt; 2; i += 2) { if (moveCanBeMade(kingPosition, opponentDirection + i) &amp;&amp; currentState.board[kingPosition + i + opponentDirection] == oppsiteColor(side | TYPE_PAWN)) { return true; } } //Knight attacks std::vector&lt;int&gt; directions = {-17, -15, -10, -6, 6, 10, 15, 17}; int destination; for (int i = 0; i &lt; directions.size(); ++i) { if (moveCanBeMade(kingPosition, directions[i])) { destination = kingPosition + directions[i]; if (currentState.board[destination] == oppsiteColor(side | TYPE_KNIGHT)) { return true; } } } //King opposition directions = {-9, -8, -7, -1, 1, 7, 8, 9}; for (int i = 0; i &lt; directions.size(); ++i) { if (moveCanBeMade(kingPosition, directions[i])) { destination = kingPosition + directions[i]; if (currentState.board[destination] == oppsiteColor(side | TYPE_KING)) { return true; } } } //Rook and (non-diaganol) Queen attacks directions = {-8, -1, 1, 8}; for (int i = 0; i &lt; directions.size(); ++i) { destination = kingPosition; for (int j = 0; j &lt; 7; ++j) { //Can't move past the edge if (!moveCanBeMade(destination, directions[i])) { break; } destination += directions[i]; //Found an attack piece if ((currentState.board[destination] == oppsiteColor(side | TYPE_ROOK)) || (currentState.board[destination] == oppsiteColor(side | TYPE_QUEEN))) { return true; } //Obstructed by piece if (currentState.board[destination]) { break; } } } //Bishop and (diaganol) Queen attacks directions = {-9, -7, 7, 9}; for (int i = 0; i &lt; directions.size(); ++i) { destination = kingPosition; for (int j = 0; j &lt; 7; ++j) { //Can't move past the edge if (!moveCanBeMade(destination, directions[i])) { break; } destination += directions[i]; //Found an attack piece if ((currentState.board[destination] == oppsiteColor(side | TYPE_BISHOP)) || (currentState.board[destination] == oppsiteColor(side | TYPE_QUEEN))) { return true; } //Obstructed by piece if (currentState.board[destination]) { break; } } } return false; } std::vector&lt;pieceMove&gt; generatePseudoMoves (gameState currentState, int sideToMove) { int piece, type; pieceMove move; std::vector&lt;pieceMove&gt; pseudoMoves; for (int i = 0; i &lt; 64; ++i) { piece = currentState.board[i]; if (isSameColor(piece, sideToMove)) { type = piece &amp; 7; move.startSqr = i; switch (type) { case TYPE_PAWN: { bool isWhite = isSameColor(piece, COLOR_WHITE); int startingRank = isWhite ? 1 : 6; int promotionRank = isWhite ? 7 : 0; int forwardDirection = isWhite ? 8 : -8; //Forward move if (currentState.board[i + forwardDirection] == 0 &amp;&amp; moveCanBeMade(i, forwardDirection)) { if ((i + forwardDirection) / 8 != promotionRank) { pseudoMoves.push_back(initMove(i, i + forwardDirection, FLAG_NONE)); } else { //Promotion pseudoMoves.push_back(initMove(i, i + forwardDirection, FLAG_PROMOTE_KNIGHT)); pseudoMoves.push_back(initMove(i, i + forwardDirection, FLAG_PROMOTE_BISHOP)); pseudoMoves.push_back(initMove(i, i + forwardDirection, FLAG_PROMOTE_ROOK)); pseudoMoves.push_back(initMove(i, i + forwardDirection, FLAG_PROMOTE_QUEEN)); } //Double jump if (currentState.board[i + forwardDirection * 2] == 0 &amp;&amp; (i / 8) == startingRank) { pseudoMoves.push_back(initMove(i, i + forwardDirection * 2, FLAG_DOUBLE_JUMP)); } } //Diagonal capture int neighbor; for (int j = -1; j &lt; 2; j += 2) { neighbor = i + j; //Normal capture if (moveCanBeMade(i, j + forwardDirection) &amp;&amp; isSameColor(currentState.board[i], oppsiteColor(currentState.board[neighbor + forwardDirection]))) { if ((i + forwardDirection) / 8 != promotionRank) { pseudoMoves.push_back(initMove(i, neighbor + forwardDirection, FLAG_NONE)); } else { //Promotion pseudoMoves.push_back(initMove(i, neighbor + forwardDirection, FLAG_PROMOTE_KNIGHT)); pseudoMoves.push_back(initMove(i, neighbor + forwardDirection, FLAG_PROMOTE_BISHOP)); pseudoMoves.push_back(initMove(i, neighbor + forwardDirection, FLAG_PROMOTE_ROOK)); pseudoMoves.push_back(initMove(i, neighbor + forwardDirection, FLAG_PROMOTE_QUEEN)); } } //En passant if (moveCanBeMade(i, j + forwardDirection) &amp;&amp; isSameColor(currentState.board[i], oppsiteColor(currentState.board[neighbor])) &amp;&amp; currentState.enPassant == neighbor) { pseudoMoves.push_back(initMove(i, neighbor + forwardDirection, FLAG_EN_PASSANT)); } } break; } case TYPE_KNIGHT: { std::vector&lt;pieceMove&gt; moveList = generateSlidingMoves(currentState, i, {-17, -15, -10, -6, 6, 10, 15, 17}, 1); pseudoMoves.insert(std::end(pseudoMoves), std::begin(moveList), std::end(moveList)); break; } case TYPE_BISHOP: { std::vector&lt;pieceMove&gt; moveList = generateSlidingMoves(currentState, i, {-9, -7, 7, 9}, 7); pseudoMoves.insert(std::end(pseudoMoves), std::begin(moveList), std::end(moveList)); break; } case TYPE_ROOK: { std::vector&lt;pieceMove&gt; moveList = generateSlidingMoves(currentState, i, {-8, -1, 1, 8}, 7); pseudoMoves.insert(std::end(pseudoMoves), std::begin(moveList), std::end(moveList)); break; } case TYPE_QUEEN: { std::vector&lt;pieceMove&gt; moveList = generateSlidingMoves(currentState, i, {-9, -8, -7, -1, 1, 7, 8, 9}, 7); pseudoMoves.insert(std::end(pseudoMoves), std::begin(moveList), std::end(moveList)); break; } case TYPE_KING: { std::vector&lt;pieceMove&gt; moveList = generateSlidingMoves(currentState, i, {-9, -8, -7, -1, 1, 7, 8, 9}, 1); pseudoMoves.insert(std::end(pseudoMoves), std::begin(moveList), std::end(moveList)); int castlingRightsStart = sideToMove == COLOR_WHITE ? 0 : 2; //Kingside castle if (currentState.castlingRights[castlingRightsStart]) { if (!(currentState.board[i + 1] | currentState.board[i + 2]) &amp;&amp; !(isInCheck(currentState, sideToMove) || isInCheck(movePieceFromPos(currentState, i, i + 1), sideToMove))) { pseudoMoves.push_back(initMove(i, i + 2, FLAG_CASTLE)); } } //Queenside castle if (currentState.castlingRights[castlingRightsStart + 1]) { if (!(currentState.board[i - 1] | currentState.board[i - 2] | currentState.board[i - 3]) &amp;&amp; !(isInCheck(currentState, sideToMove) || isInCheck(movePieceFromPos(currentState, i, i - 1), sideToMove))) { pseudoMoves.push_back(initMove(i, i - 2, FLAG_CASTLE)); } } break; } } } } return pseudoMoves; } std::vector&lt;pieceMove&gt; generateLegalMoves (gameState currentState, int sideToMove) { std::vector&lt;pieceMove&gt; moveList, legalMoves, pseudoMoves = generatePseudoMoves(currentState, sideToMove); for (int i = 0; i &lt; pseudoMoves.size(); ++i) { if (!isInCheck(applyMove(currentState, pseudoMoves[i]), sideToMove)) { legalMoves.push_back(pseudoMoves[i]); } } return legalMoves; } std::vector&lt;pieceMove&gt; generateSlidingMoves (gameState currentState, int square, std::vector&lt;int&gt; directions, int maxDepth) { //Move generation for Knights, Rooks, Queens and Kings std::vector&lt;pieceMove&gt; possibleMoves; pieceMove move; int destination; for (int i = 0; i &lt; directions.size(); ++i) { destination = square; for (int j = 0; j &lt; maxDepth; ++j) { //Can't move pass the edge if (!moveCanBeMade(destination, directions[i])) { break; } destination += directions[i]; //Can't capture own piece if (isSameColor(currentState.board[square], currentState.board[destination])) { break; } move.endSqr = destination; possibleMoves.push_back(initMove(square, destination, FLAG_NONE)); //Can't move past captured pieces if (isSameColor(currentState.board[square], oppsiteColor(currentState.board[destination]))) { break; } } } return possibleMoves; } long long int easyMask (int direction) { //Prevent moving past the edge long long int mask = 0; int vertical, horizontal; vertical = (int) lround((float) direction / 8); horizontal = direction - vertical * 8; if (horizontal != 0) { if (horizontal &gt; 0) { for (int i = 0; i &lt; horizontal; ++i) { mask = mask | ( 0x101010101010101 &lt;&lt; (7 - i)); } } else { for (int i = 0; i &lt; (~horizontal + 1); ++i) { mask = mask | ( 0x101010101010101 &lt;&lt; i); } } } if (vertical != 0) { if (vertical &gt; 0) { for (int i = 0; i &lt; vertical; ++i) { mask = mask | ( 0xff00000000000000 &gt;&gt; (i * 8)); } } else { for (int i = 0; i &lt; (~vertical + 1); ++i) { mask = mask | ( 0xff &lt;&lt; (i * 8)); } } } return mask; } bool moveCanBeMade (int square, int direction) { return !((easyMask(direction) &gt;&gt; square) &amp; 1); } </code></pre> <h2><code>moveGen.hpp</code></h2> <pre><code>#ifndef moveGen_hpp #define moveGen_hpp #include &lt;stdio.h&gt; #include &lt;vector&gt; #include &quot;move.hpp&quot; #include &quot;gameState.hpp&quot; bool isInCheck (gameState currentState, int side); std::vector&lt;pieceMove&gt; generateSlidingMoves (gameState currentState, int square, std::vector&lt;int&gt; directions, int maxDepth); std::vector&lt;pieceMove&gt; generatePseudoMoves (gameState currentState, int sideToMove); std::vector&lt;pieceMove&gt; generateLegalMoves (gameState currentState, int sideToMove); long long int easyMask (int direction); bool moveCanBeMade (int square, int direction); #endif /* moveGen_hpp */ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T14:32:23.317", "Id": "516144", "Score": "10", "body": "Particularly for a new contributor this is an excellent first question - great formatting and layout." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T15:07:43.797", "Id": "516146", "Score": "2", "body": "Thank you! I made sure to write the question as clear as possible, to not waste people's time on making otherwise-simple-things out ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T18:28:21.067", "Id": "516156", "Score": "0", "body": "Is it a copy'n'paste error that you `#include \"gameState.hpp\"` at the end of gameState.cpp?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T00:21:44.653", "Id": "516170", "Score": "0", "body": "Huh. It seems like my compiler automatically added them." } ]
[ { "body": "<pre><code>std::map&lt;std::string, int&gt; perftDivide (gameState currentState, int depth) {\n std::map&lt;std::string, int&gt; output;\n</code></pre>\n<p>First thing I notice: <strong>name your types</strong>. You have a <code>map</code> as the result, and a local variable with the same kind of <code>map</code> ... are these the same kind of thing, or do they just coincidentally use the same data structure? And <em>what is it</em>?</p>\n<pre><code> int sideToMove = currentState.whiteToMove ? COLOR_WHITE : COLOR_BLACK;\n</code></pre>\n<p>Make that <code>const</code>. It doesn't change after you figure it out once.</p>\n<pre><code> std::vector&lt;pieceMove&gt; moveList = generateLegalMoves(currentState, sideToMove);\n</code></pre>\n<p>Use <code>auto</code>. And why is <code>sideToMove</code> an integer rather than an enumeration type?</p>\n<pre><code> for (int i = 0; i &lt; moveList.size(); ++i) {\n output[moveToUCI(moveList[i])] = perft(applyMove(currentState, moveList[i]), depth - 1);\n }\n</code></pre>\n<p>You're going through the entire container in order, so use the range-based <code>for</code> loop:</p>\n<pre><code>for (auto&amp; mv : moveList)\n output[moveToUCI(mv)] = perft(applyMove(currentState,mv), depth-1);\n</code></pre>\n<p>and that also takes care of the nit that you repeated <code>moveList[i]</code>. This is not a big deal for a vector, but more generally looking things up can be expensive. Don't do the same work multiple times in the same line!</p>\n<p>As for whether <code>mv</code>should be <code>const</code> as well, I can't tell just from looking here. Think about it. Add <code>const</code> throughout the code.</p>\n<hr />\n<p>You are passing <code>gamestate</code> by value. This deep copies the two vectors it contains, you know. That function doesn't appear to modify the gamestate in-place. So why are you passing it around <strong>by value</strong> everywhere?</p>\n<hr />\n<pre><code>std::map&lt;char, int&gt;charToPiece = {\n {'P', TYPE_PAWN},\n {'N', TYPE_KNIGHT},\n {'B', TYPE_BISHOP},\n {'R', TYPE_ROOK},\n {'Q', TYPE_QUEEN},\n {'K', TYPE_KING},\n};\n</code></pre>\n<p>This is a global variable, not <code>static</code> and not inside a namespace. You should be careful what global names you make, as this will become a problem when you combine libraries and other code.</p>\n<p>I expect this is a fixed lookup table? Why isn't it <code>const</code> or better yet <code>constexpr</code> if your version of the compiler handles that.\nBut still, for this use, that is a very expensive way to do it. This is better implemented as a function containing a <code>switch</code> statement.\nAnd, why is the map using <code>int</code> instead of the enumeration type?</p>\n<hr />\n<pre><code>class gameState {\npublic:\n std::vector&lt;int&gt; board = std::vector&lt;int&gt;(64);\n std::vector&lt;bool&gt; castlingRights = std::vector&lt;bool&gt;(4);\n bool whiteToMove;\n int enPassant, wholeTurn, moveClock; \n};\n</code></pre>\n<p>Those vectors are initialized to specific sizes... are they actually fixed size? Consider using an array instead of a <code>vector</code> if they will never change size!\nNote also that <code>std::vector&lt;bool&gt;</code> is weird. This may or may not bother you in this application.</p>\n<hr />\n<pre><code>pieceMove initMove (int start, int end, int flag) {\n pieceMove output;\n output.startSqr = start;\n output.endSqr = end;\n output.flag = flag;\n \n return output;\n}\n</code></pre>\n<p>I think you meant to write a <strong>constructor</strong>. Even your comment calls this &quot;initialize pieceMove&quot;. I see you wrote <code>pieceMove</code> as a class with all public data members and no functions, so it's just a plain <code>struct</code>. But maybe it <em>should</em> have member functions... you're just not using them right.</p>\n<hr />\n<pre><code>gameState initWithFEN (std::string FEN) {\n</code></pre>\n<p>Again, it appears that this should actually be a constructor for <code>gameState</code>.<br />\nYou are passing in <code>FEN</code> <strong>by value</strong>. Do you actually need to make a local copy of the string? Normally you should pass these as <code>const&amp;</code>, but it's even better to use <code>std::string_view</code>.</p>\n<pre><code> //Castling rights\n for (int i = 0; i &lt; parts[2].size(); ++i) {\n if (parts[2][i] == 'K') {\n newState.castlingRights[0] = true;\n }\n if (parts[2][i] == 'Q') {\n newState.castlingRights[1] = true;\n }\n if (parts[2][i] == 'k') {\n newState.castlingRights[2] = true;\n }\n if (parts[2][i] == 'q') {\n newState.castlingRights[3] = true;\n }\n }\n</code></pre>\n<p>Don't repeat blocks of code that only have one little thing like a single variable that's different between the copies. Copy/paste is <strong>not your friend</strong>.</p>\n<p>You're also repeating the indexinging of <code>parts[2]</code>.</p>\n<p>All your commented sections in this long function should really be separate functions. Functions should be <em>cohesive</em> and do one thing.</p>\n<p>To eliminate the duplicated statement, do the mapping of the letter to the index as a distinct step:</p>\n<pre><code>for (const auto L : parts[2]) {\n newState[castlingRights[castle_index(part)]=true;\n}\n</code></pre>\n<hr />\n<p><code>long long int</code> is compiler-specific as to how many bits it has. I think you are counting on it being a specific size. Also, you probably meant to be <code>unsigned</code> as you need the top bit for your bit flags as well. So use <code>std::uint64_t</code>.</p>\n<h1>Summary of issues to work on</h1>\n<ul>\n<li>Break up meandering functions into their individual helper functions.</li>\n<li>Declare names for various types you use like the <code>map</code>.</li>\n<li>Don't pass by value for non-simple types, most of the time.</li>\n<li><em>Use</em> the enumeration types you created. They are types, not just handy way to declare some constant <code>int</code>s.</li>\n<li>Use classes properly: data members private, functions that work on them are member functions.</li>\n<li>Use the special member functions for their proper role; i.e. constructors.</li>\n<li>use <code>const</code></li>\n<li>use range-based <code>for</code> loop when you can.</li>\n<li>Don't repeat code multiple times with only a single symbol changed between them.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T14:10:30.043", "Id": "516140", "Score": "0", "body": "Thanks! Although the functions in `main.cpp` is just for debugging purposes (thus its code doesn't matter much), I will keep these rules in mind when writing future functions. EDIT: The comment above is written before the answer edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T14:17:14.607", "Id": "516142", "Score": "0", "body": "Also, since I plan to add an evaluation and search functions, I think I'd probably want to have duplicates of the same `gameState`. Other programs I see that doesn't work the same way mostly use `makeMove()` & `unmakeMove()`. Wouldn't that make it more expensive?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:18:22.517", "Id": "516152", "Score": "0", "body": "I guess when you suggested replacing the 64 element vector with an array, you meant a `std::array`. Or?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T19:19:37.733", "Id": "516163", "Score": "1", "body": "@uri, He can use `std::array` or a plain built-in array. The need for `std::array` has been largely mitigated in later versions of the language, so I usually don't use that unless I actually need it (e.g. for a return value)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T20:53:06.577", "Id": "516262", "Score": "0", "body": "@JDługosz Out of curiosity, what is the meaning of \"meandering functions\"? Google didn't help me much (not a native)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T23:15:26.300", "Id": "516267", "Score": "2", "body": "\"better implemented as a function containing a switch statement.\" I would disagree with this. I prefer to only use `switch` when the code changes. If it's the same code, use a map of some sort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:57:56.713", "Id": "518340", "Score": "0", "body": "@MooingDuck a switch will be fast and efficient, and a map takes dynamic memory and is slow. If it's a sorted array and all constexpr operations to do the find, the switch can still optimize better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:02:32.460", "Id": "518341", "Score": "1", "body": "@ihavenoidea \"meandering\" Evocative of ([this](https://en.wikipedia.org/wiki/Meander_(art))) but actually comes from a slow flowing [meandering river](https://en.wikipedia.org/wiki/Meander). It means that the function does something, then does something else that's a different cohesive set of statements that's not cohesive with the previous group, the flows along into another different thing, etc. Think about floating down a lazy river with each bend showing you a different scene." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:54:05.677", "Id": "261546", "ParentId": "261538", "Score": "13" } }, { "body": "<p><em>Note: I'm just adding a few things to previous reviews.</em></p>\n<h1>Include Guards</h1>\n<pre><code>#ifndef main_h\n#define main_h\n...\n#endif /* main_h */\n</code></pre>\n<p>The only important thing for them is to be unique. For that reason, I'd add a sequence of random characters to its end, just to make sure it doesn't collide with other include guards. Also, since they are macros, all rules for macros apply. In particular, use <code>ALL_UPPERCASE_NAMES</code> and only use them for macros.</p>\n<p>Another thing I noticed there is that comment &quot;main_h&quot;. What's the information a casual reader is supposed to gain from it? Was <code>main_h</code> defined or undefined in the preceding section? Two suggestions: Firstly, the last <code>#endif</code> in a header file terminates the include guards, this barely worth worth documenting. If you want to be really safe, comment it with <code>include guard</code>.</p>\n<h1>Piece Definitions</h1>\n<pre><code>enum pieceType {\n //EMPTY = 0,\n TYPE_PAWN = 1,\n TYPE_KNIGHT = 2,\n TYPE_BISHOP = 3,\n TYPE_ROOK = 4,\n TYPE_QUEEN = 5,\n TYPE_KING = 6\n};\n</code></pre>\n<p>Some notes on this:</p>\n<ul>\n<li><code>TYPE_PAWN</code> looks like a macro, see my previous comment.</li>\n<li>Why is there no <code>TYPE_EMPTY</code>?</li>\n<li>I think newer C++ supports <code>enum class</code> types where the constants don't leak into the surrounding namespace. Using that, you could then use <code>pieceType::queen</code> to replace <code>TYPE_QUEEN</code>.</li>\n<li>With modern C++, you can also define the integer base type for an enumeration. Since you want performance and that is often tied to memory use, consider using <code>uint8_t</code>, which should be large enough.</li>\n</ul>\n<p>There is also an according enumeration named <code>pieceColor</code>. The two form a compound type that bit-packs different kinds of information into what is represented as <code>int</code> throughout your program. Firstly, this is undocumented, making it difficult to understand. However, much worse, is that you use <code>int</code> all the time! A chessboard field is not a number, and it makes your code harder to read. Even if you created a simple typedef, it would help people to understand the code. If you created a proper type (perhaps overloading operators <code>&amp;</code> and <code>|</code> for the enumeration) you could enjoy the type safety and expressiveness.</p>\n<h1>Flow Control</h1>\n<p>You have code like this:</p>\n<pre><code>for (...) {\n if (...) {\n ...\n // many lines of code\n ...\n }\n}\n</code></pre>\n<p>In order to understand it, you have to skip over the many lines of code. A simple <code>continue</code> would make it easier to understand. Similarly, in <code>oppsiteColor</code>, where you write to a temporary, then break from the switch, only to return the temporary. Just <code>return</code> here, simple as that.</p>\n<h1>Magic Numbers</h1>\n<p>In the context of chess, I can well live with 64 (cells) and 8 (width/height). Here though, you also have 7, 4, 6, 16, 24 and a bunch of others. Avoid that, it makes code hard to read.</p>\n<h1>Bit Operations On Booleans</h1>\n<pre><code>newState.whiteToMove ^= 1;\n</code></pre>\n<p>Don't. It works, but it's confusing. See &quot;Principle of Least Surprise&quot; as a general rule.</p>\n<h1>Vector vs. Arrays</h1>\n<p>For constant-size vectors like the cells of your board, use a <code>std::array</code>:</p>\n<ul>\n<li>Vectors are typically implemented with three pointers, one to the beginning and end of the allocated storage, a third representing the number of actually created elements (see <code>reserve()</code> and <code>resize()</code>). On a 64-bit machine, that's 24 octets on top of the actually required memory for the cells. Your cells should fit into 64 octets overall, maybe even less. Keeping things small, also makes them fast by making better use of CPU caches.</li>\n<li>Accessing elements of a vector requires first reading the start pointer, adding the index and then reading the element there. For a plain array, the indirection via the pointer is skipped, which improves performance.</li>\n<li>Using the <code>std::array</code> wrapper, you still get things like iterators, <code>size()</code> methods etc.</li>\n</ul>\n<h1>Unnecessarily Large Scope</h1>\n<pre><code>int piece;\nfor (int i = 0; i &lt; boardFEN.size(); ++i) {\n ...\n piece = charToPiece[toupper(current)];\n piece += isupper(current) ? COLOR_WHITE : COLOR_BLACK;\n newState.board[rank * 8 + file] = piece;\n ...\n}\n</code></pre>\n<p>Look at the use of <code>piece</code> in this code. It is never used between two loop iterations, which is again difficult to understand. Just use <code>auto piece = ...</code> exactly where it is used.</p>\n<p>Another general rule violated here is to avoid uninitialized variables. This also applies to e.g. your <code>gameState</code> type. It should have constructors exactly to prevent uninitialized variables.</p>\n<h1>General Note</h1>\n<p>I'm not sure about the rest of your development. In particular, I'm wondering if you have unit tests and benchmarks to track your progress. Also, in particular for optimizing things, using a profiler is a valuable tool. These are wide fields, just keep in mind that you need to look at these things at some point.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T00:54:19.297", "Id": "516172", "Score": "0", "body": "Thank you! I'll try to improve the code by utilizing these tips. Extra questions: 1. What do I need to change when using `array` instead of `vector`? A lot of things broke when I tried to replace it. 2. I'm thinking about replacing the magic numbers with `generateMove(horizontal, vertical)`. Wouldn't that take more computing resources?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:33:44.170", "Id": "516175", "Score": "3", "body": "@羅凋守WitherClubtw To create an `array`, you need to specify its size. In `gameState.hpp`, the line `std::vector<int> board` would become `std::array<int, 64> board`. See here: https://en.cppreference.com/w/cpp/container/array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T07:53:53.930", "Id": "516184", "Score": "2", "body": "I don't understand what you mean with your second question. The way to avoid magic numbers is simply to define named constants. Those don't cost additional computing resources, since they are replaced at compile time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T02:30:21.453", "Id": "518272", "Score": "1", "body": "@羅凋守WitherClubtw: Another speed advantage to `std::array<char, 64> board` is that the size is a compile-time constant, so for example copying one can be done with a fixed sequence of two 32-byte AVX load and store instructions like `vmovdqu ymm0, [rdi]`, instead of needing to loop at all. (Or 4x 16-byte vectors are available on multiple ISAs without enabling any special ISA extensions). And removing a level of indirection: the data is right there, instead of pointed-to by the members of a `std::vector`. Note the use of `char` instead of `int`, usually 1/4 the size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T08:21:27.103", "Id": "518294", "Score": "0", "body": "@uil Thanks for the clarification. I was thinking of some algorithm that evaluates at compile time, but didn't know how to do it (I didn't know `constexpr` was a thing). As for the array part, I couldn't get it to work with built-in`array`(direct substituting doesn't work). But I guess `std::array` works fine, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T09:25:05.037", "Id": "518300", "Score": "0", "body": "Nevermind, I forgot to initialize the `array`s. It was so stupid of me." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T18:35:53.363", "Id": "261556", "ParentId": "261538", "Score": "9" } } ]
{ "AcceptedAnswerId": "261546", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T09:07:01.387", "Id": "261538", "Score": "18", "Tags": [ "c++", "performance", "chess" ], "Title": "Chess engine for C++" }
261538
<p>In a previous question, <a href="https://codereview.stackexchange.com/questions/261338/java-logger-of-doom">Java logger (of doom!)</a>, I had posted my own logger, written in Java. I have since taken the answers from that question and a few of my own things to update it.</p> <p>New code:</p> <pre><code>/* * Syml, a free and open source programming language. * Copyright (C) 2021 William Nelson * mailto: catboardbeta AT gmail DOT com * Syml is free software, licensed under MIT license. See LICENSE * for more information. * * Syml is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package personal.williamnelson; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Logger implements Closeable { public File logfile = new File(&quot;&quot;); protected FileOutputStream fos; protected OutputStreamWriter osw; protected DateTimeFormatter dtf = DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm:ss&quot;); // example: 2021/27/5 12:07:23 public void init(File fileToLog) { try { logfile = fileToLog; if (fileToLog.exists()) { clearFile(fileToLog); } else { if(!fileToLog.createNewFile()) { System.out.println(&quot;An unrecognized error occurred while creating the logfile.&quot;); } } } catch (IOException e) { //NOSONAR System.out.println(&quot;An error occurred while creating a logfile. Are you sure that '&quot; + logfile.toString() + &quot;' is a valid filename?&quot;); System.exit(1); } try { fos = new FileOutputStream(fileToLog, true); osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); clearFile(fileToLog); } catch (IOException e) { System.out.println(&quot;An unrecognized error occurred while start logging stream and &quot; + &quot;writing to log stream, despite passing all tests.&quot;); } } public void log(Object o, int logType) throws IOException { // logType should be 0 = INFO, 1 = WARN, 2 = ERROR, 3 = FATAL osw.write(getTime() + &quot;: &quot;); printErrorType(logType); osw.write(o.toString() + '\n'); } public void log(int i, int logType) throws IOException { osw.write(getTime() + &quot;: &quot;); printErrorType(logType); osw.write(String.valueOf(i) + '\n'); } private String getTime() { LocalDateTime ldtNow = LocalDateTime.now(); return ldtNow.format(dtf); } private void clearFile(File file) throws IOException { FileOutputStream fosClearer = new FileOutputStream(file, false); OutputStreamWriter oswClearer = new OutputStreamWriter(fosClearer); oswClearer.write(&quot;&quot;); oswClearer.close(); } private void printErrorType(int errorType) throws IOException { switch (errorType) { case 0: osw.write(&quot;INFO: &quot;); break; case 1: osw.write(&quot;WARN: &quot;); break; case 2: osw.write(&quot;ERROR: &quot;); break; case 3: osw.write(&quot;FATAL: &quot;); break; default: throw new IllegalArgumentException(&quot;Parameter 'logType &quot; + &quot;of 'personal.williamnelson.Logger.log'&quot; + &quot; must be one of the following: \n&quot; + &quot; 0: INFO\n&quot; + &quot; 1: WARN\n&quot; + &quot; 2: ERROR\n&quot; + &quot; 3: FATAL\n&quot;); } } public void close() throws IOException { osw.close(); } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Why use an <code>int</code> to indicate the log type when you can just use an <code>enum</code>\nThat way, you could just write the enum to the <code>OutputStreamWriter</code> directly (while avoiding the worry of receiving an incorrect logType: <code>IllegalArgumentException</code>):</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class Logger implements Closeable {\n public enum LogType {\n FATAL, ERROR, WARN, INFO, DEBUG, TRACE;\n }\n ...\n public void log(Object o, LogType logType) throws IOException {\n osw.write(getTime() + &quot;: &quot; + logType + &quot;: &quot; + o.toString() + &quot;\\n&quot;);\n }\n}\n</code></pre>\n<p>Also, you could just rewrite the <code>log(int, LogType)</code> method to reuse <code>log(Object, LogType)</code>, to avoid duplicated code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public void log(int i, LogType logType) throws IOException {\n log(Integer.valueOf(i), logType);\n}\n</code></pre>\n<p>Regarding code style, there is no need to write an if-else-if this way:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (foo) {\n doSomething();\n} else {\n if (bar) {\n doSomethingElse();\n }\n}\n</code></pre>\n<p>Unless you wished to do something in the <code>else</code> block, but outside the inner <code>if</code>, it is more readable to write it as such:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (foo) {\n doSomething();\n} else if (bar) {\n doSomethingElse();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:36:22.400", "Id": "516153", "Score": "0", "body": "I never would have even thought to use an enum, and I totally forgot about DEBUG and TRACE. Also, where did I use a strange if statement like that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T18:12:38.497", "Id": "516247", "Score": "0", "body": "@catboardbeta In you `init` method" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:22:04.133", "Id": "261553", "ParentId": "261542", "Score": "3" } }, { "body": "<p>Looking at your <code>init()</code> function and your <code>try/catch</code> blocks, shouldn't it be better to use <code>System.err.println</code> instead of <code>System.out.println</code> when you catch an <code>IOException</code>?</p>\n<p>On the same lines, if this is supposed to be a generic class, shouldn't the consumer be doing the error handling? You should just hand them the <code>IOException</code> (add a <code>throws IOException</code> to your <code>init()</code> function and remove your <code>try/catch</code> blocks) and then force the consumer to handle it instead. This way the consumer has more control on what happens if something wrong happens.</p>\n<hr>\n<p>Also, what is that extra <code>log(int i, int logType)</code> doing there? Shouldn't <code>int</code> get boxed into <code>log(Object o, int logType)</code>?</p>\n<p>On the topic of that, you should definitely use <code>enums</code> (<a href=\"https://codereview.stackexchange.com/a/261553/243229\">as @m-alorda said</a>). It makes your code much easier to read and use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T20:32:12.800", "Id": "261558", "ParentId": "261542", "Score": "2" } }, { "body": "<ul>\n<li>Is there a reason <code>logfile</code> can't be an argument of the constructor? The way I see it, a <code>Logger</code> that hasn't had <code>init()</code> called is just guaranteed to be in an invalid state and entirely useless until <code>init</code>ed, so calling <code>init</code> in the constructor just seems like a good way to guarantee the <code>Logger</code> is in a useful state. Am I missing something?</li>\n<li>I can imagine a situation where some application may want to run part of its code even though the logging isn't working, but since <code>init</code> calls <code>System.exit()</code> that doesn't seem to even be an option. Unless there's some particular reason <code>init</code> (or the <code>Logger</code> constructor) must never be allowed to throw exceptions, it should probably do that, rather than <code>System.exit()</code></li>\n<li>It feels a bit weird that <code>clearFile</code> can clear files other than the designated <code>logfile</code>. Especially since <code>logfile</code> is the only file that's ever passed to it, not that a logger should ever want to work with any other files anyway. Wouldn't it make more sense to just have it operate on the log file directly since a logger shouldn't really need to touch any other files anyway?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T21:03:13.467", "Id": "261559", "ParentId": "261542", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:05:44.907", "Id": "261542", "Score": "2", "Tags": [ "java", "file", "logging", "file-structure" ], "Title": "Java logger (of doom!), updated" }
261542
<p>I need a program same as I wrote but using loops. (if else for etc.) . Program is that enter a number and get each digits of number like that: number is 123456. I'm beginner, I can't create the logic and can't combine loops. Can anybody help me about that situation?</p> <pre><code>1.digits is 6 2.digits is 5 3.digits is 4 4.digits is 3 5.digits is 2 6.digits is 1 7.digits is 0 8.digits is 0 9.digits is 0 </code></pre> <p>.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int number,first,second,third,fourth,fifth,sixth,seventh,eighth,ninth; cout&lt;&lt; &quot;Enter a number (&lt;999999999): &quot; &lt;&lt; endl; cin&gt;&gt;number; first = number%10; second = number/10%10; third = number/100%10; fourth = number/1000%10; fifth = number/10000%10; sixth = number/100000%10; seventh = number/1000000%10; eighth = number/10000000%10; ninth = number/100000000%10; cout&lt;&lt;&quot;1. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;first&lt;&lt;endl; cout&lt;&lt;&quot;2. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;second&lt;&lt;endl; cout&lt;&lt;&quot;3. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;third&lt;&lt;endl; cout&lt;&lt;&quot;4. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;fourth&lt;&lt;endl; cout&lt;&lt;&quot;5. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;fifth&lt;&lt;endl; cout&lt;&lt;&quot;6. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;sixth&lt;&lt;endl; cout&lt;&lt;&quot;7. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;seventh&lt;&lt;endl; cout&lt;&lt;&quot;8. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;eighth&lt;&lt;endl; cout&lt;&lt;&quot;9. digit is&quot;&lt;&lt;&quot; &quot;&lt;&lt;ninth&lt;&lt;endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T16:35:56.977", "Id": "516149", "Score": "1", "body": "Welcome to Code Review! Unfortunately, we don't write code to order, we simply _review_ code you've written, and might make suggestions that improve it. Depending on your problem, another site of the [StackExchange network](//stackexchange.com/) can help you. Please see our [help/on-topic] for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T16:38:03.197", "Id": "516150", "Score": "2", "body": "BTW, once you have it working as you want, please do ask for a review, as you have some bad habits (`using namespace std`, for one, and `std::endl` instead of plain newline, for another) that you could improve on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T19:05:04.947", "Id": "516160", "Score": "0", "body": "@TobySpeight - I am not sure that there is any site which writes code to order. StackOverflow can help with actual programming problems, but only when the poster has tried something and is running into trouble." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T19:06:14.937", "Id": "516161", "Score": "1", "body": "Can I suggest that you try an online tutorial first? Then, once you have tried to write the code with loops, if you are still having problems, you can post a question on Stack Overflow. If you search \"C++ tutorial loops\", you should find several options which should help you get started. Good luck!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T20:05:39.513", "Id": "516164", "Score": "0", "body": "I subscribe to \"Ask a 5th grader\" what something means and to the average 5th grader, the first digit would be the leftmost digit or greatest non-zero power of 10. And that same 5th grader would tell me that I took a long winded approach to tell you I think the digits are presented in the wrong order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T13:59:20.617", "Id": "516207", "Score": "0", "body": "It's unfortunate that this was closed. I suggested the OP post the code here (it was on SO) to get feedback on his bad habits etc. His mistake was including the full text of the original request for help as well; the code _does compile_ and _does run_ as it is (without loops), so it should be just fine to post here so we can tell him not to use `using namespace std;` and all the usual stuff. The \"question\" should be replaced with a note saying this code was referred, rather than being closed." } ]
[ { "body": "<p>I suggested you post here; it qualifies as it is working/compiling code. In the original post on Stack Overflow people might answer you on explaining how to do looping. Here, we just review what you wrote.</p>\n<p><code>using namespace std;</code><br />\nDon't do that. There are posts here explaining why not in detail.</p>\n<p><code>int number,first,second,third,fourth,fifth,sixth,seventh,eighth,ninth;</code><br />\nYou put this as the very first line in the function.<br />\nDon't declare all variables at the top! Declare them when you are ready to use them and only when you are ready to initialize them. Keep them in the smallest scope necessary.</p>\n<p>Also, in C++ we generally don't list a bunch of variables in one declaration like that. Of course, the larger design issue is that <code>first</code> through <code>ninth</code> are not actually needed, but that's not the subject here.</p>\n<p><code>cout&lt;&lt; &quot;Enter a number (&lt;999999999): &quot; &lt;&lt; endl;</code><br />\nDon't use <code>endl</code>. Rather, just output a <code>'\\n'</code> character. Here, that can be included in the string with the prompt.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T19:26:36.487", "Id": "261557", "ParentId": "261551", "Score": "3" } }, { "body": "<h2>Organize the data and access by index</h2>\n<p>The code as it is written is readable and does the job, but it is cumbersome and not easy to make more flexible. I think this is what you are getting at when asking about loops.</p>\n<p>First of all, when you want a group of common variables, and you find yourself using names like &quot;first&quot;, &quot;second&quot;, and so on, take this as a hint to use some kind of container for them, and access them by index. If the size is fixed, you can use an array:</p>\n<pre><code>const int size = 0;\nint digits[size];\n</code></pre>\n<p>If you do not have a fixed number of digits, use a vector:</p>\n<pre><code> std::vector&lt;int&gt; digits;\n</code></pre>\n<p>Then you can add the digits as you extract them, however many they are.</p>\n<p>Using an array or a vector will simplify the code and make it much easier to modify later. It will also make it possible for you to use a loop, which is your original question. When you can access each digit by an index, rather than a name, you can use a loop to do what is needed for each digit, accessing the array by index (or iterator, in the case of the vector).</p>\n<p>Once you are doing this in a loop, you can improve the code further by stopping when you have no more digits (after the division, you are left with zero</p>\n<h2>Avoid 'magic numbers'</h2>\n<p>In general, avoid hardcoded numbers like <code>999999999</code> or <code>100000</code>. For the former, if you use a constant instead of a hardcoded number, it is easier to modify later. Often limits like this are used in more than one place in the code, and you won't want to hunt for them and change all of them later. Note that <code>100000</code> and its friends in your code are being used as multiples of 10 -- you can calculate them as you go -- put the 10 into a variable and multiply again for the next digit (this is another hint which should help you convert this to use a loop).</p>\n<h2>Avoid polluting your namespace, especially with <code>std</code></h2>\n<pre><code>using namespace std;\n</code></pre>\n<p><code>std</code> defines common functionality with quite generic names. The namespace limits the scope of the name, avoiding possible name conflicts; see <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this StackOverflow post</a> for more details.</p>\n<h2>Take control of i/o</h2>\n<p>Decide when you want to flush the buffer, when you have a unit of output. std::endl does not only write a newline, it flushes the buffer. In this little program, that may not matter, but it is better practice to <em>choose</em> when to do this, or minimize it when possible. Writing to the screen, or a file, etc., is much much slower than writing to RAM (where the buffer is).</p>\n<p>If you just need the newline, use <code>'\\n'</code>. The buffer will be flushed when it is full, or the program ends, etc.; in short, when it must be. See <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n?rq=1\">this question and its higher rated answers</a> for more information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T10:01:57.373", "Id": "516191", "Score": "0", "body": "Thank you to Toby Speight (and, later, JDługosz) for mentioning the issue with std::endl. I was not aware of it and had to look up why; I learned something new; I'm just sharing what I learned along with what I had wanted to say!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T14:00:50.963", "Id": "516208", "Score": "0", "body": "`const int size = 0;` should be `constexpr size_t size = 0`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T09:24:46.740", "Id": "261571", "ParentId": "261551", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T16:31:05.203", "Id": "261551", "Score": "0", "Tags": [ "c++", "beginner" ], "Title": "Get Each Digits of Number with Using Loops in C++" }
261551
<p>I had this <a href="https://codereview.stackexchange.com/questions/261387/python-trivia-game-getting-questions-and-answers-off-a-website" title="This Stackexchange post">trivia game</a>, and from the review I got I improved my game. One of the improvements I made was this short function, to check the correctness of an answer (so if the correct answer was &quot;Yellowstone park in Wyoming&quot;, &quot;Yellowstone park&quot; could be accepted. The code I have below works, but I would like it to be smarter, as the current code is simple. Any ideas? Thanks.</p> <pre><code>def check(answer, correct, percentage): matches = 0 if len(answer) &lt; len(correct): for x in range(len(answer)): if answer[x] == correct[x]: matches += 1 total = len(correct) else: for x in range(len(correct)): if answer[x] == correct[x]: matches += 1 total = len(answer) matches_percentage = (matches/total * 100) if matches_percentage &gt;= percentage: return True else: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T22:15:26.353", "Id": "516167", "Score": "2", "body": "the requirements are not clear enough. e.g. will \"park in\" be a good answer in your example? is the order of the words important? e.g. will \"Wyoming Yellowstone\" have the same rank as \"Yellowstone Wyoming\"? define better requirements and then the implementation can be discussed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:15:06.707", "Id": "516174", "Score": "1", "body": "Take a look at [`difflib.SequenceMatcher`](https://docs.python.org/3.9/library/difflib.html#sequencematcher-examples) in the standard library. It has a `ratio()` method that returns a similarity score on a scale of 0.0 to 1.0." } ]
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code> if matches_percentage &gt;= percentage:\n return True\n else:\n return False\n</code></pre>\n<p>is a verbose way of writing</p>\n<pre class=\"lang-py prettyprint-override\"><code> return matches_percentage &gt;= percentage\n</code></pre>\n<p>In <code>matches_percentage = (matches/total * 100)</code>, the parentheses are unnecessary.</p>\n<p>You could compute <code>total</code> with just one <code>max(...)</code> expression:</p>\n<pre><code>total = max(len(correct), len(answer))\n</code></pre>\n<p>That just leaves comparing successive elements of <code>correct</code> and <code>answer</code> and counting matches until you run out of terms from one list or the other. The <code>zip(...)</code> function is ideal for that.</p>\n<pre><code>matches = sum(a == b for a, b in zip(correct, answer))\n</code></pre>\n<p>I believe that reduces your function to four statements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T01:52:16.763", "Id": "261562", "ParentId": "261561", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T21:57:14.470", "Id": "261561", "Score": "0", "Tags": [ "beginner", "python-3.x" ], "Title": "Short function to check if an entered answer is close to a correct one" }
261561
<p>When I need a singleton class in my Ruby code (for example, single logger for multiple classes) I usually use code like this:</p> <pre><code>class Parent_Singleton @singleton = nil def self.new @singleton || (@singleton = super) end end </code></pre> <p>This approach allows me to avoid using the module <code>Singleton</code> (because I don't want to use a special method <code>instance</code> to get an object of this class, I just want to use the usual <code>Parent_Singleton.new</code> in any part of my code to get my singleton object).</p> <p>Another advantage of this approach is the ability to avoid using class variables <code>@@singleton</code> which of course is a <a href="https://rubystyle.guide/#no-class-vars" rel="nofollow noreferrer">bad practice</a> because of its behavior in inheritance. My code doesn't have this issue:</p> <pre><code>class Child_Singleton &lt; Parent_Singleton end p1 = Parent_Singleton.new p2 = Parent_Singleton.new c1 = Child_Singleton.new c2 = Child_Singleton.new p1 == p2 # =&gt; true c1 == c2 # =&gt; true p1 == c1 # =&gt; false p2 == c2 # =&gt; false </code></pre> <p>If I need to store some variable data in my class, it's also not a problem:</p> <pre><code>class Parent_Class @singleton = nil @some_data = '' class &lt;&lt; self def new @singleton || (@singleton = super) end def some_data @some_data end def some_data=(value) @some_data = value end end end class First_Child_Class &lt; Parent_Class end class Second_Child_Class &lt; Parent_Class end Parent_Class.some_data = 'Parent' First_Child_Class.some_data = 'First_Child' Second_Child_Class.some_data = 'Second_Child' puts Parent_Class.some_data # =&gt; Parent puts First_Child_Class.some_data # =&gt; First_Child puts Second_Child_Class.some_data # =&gt; Second_Child </code></pre> <p>So my question is: if this code is bad, what's wrong with it? If this code is good, why the most of the examples worldwide suggest using either <code>Singleton</code> module (with <code>instance</code> method) or class variable-based singleton classes instead?</p>
[]
[ { "body": "<p>The Singleton module in Ruby for instance also guarantees synchronised access, e.g. if multiple threads try to create an instance your implementation would not work.</p>\n<p><a href=\"https://github.com/ruby/ruby/blob/master/lib/singleton.rb#L112-L168\" rel=\"nofollow noreferrer\">https://github.com/ruby/ruby/blob/master/lib/singleton.rb#L112-L168</a></p>\n<p>It's also a convention (in other programming languages too) to call the method <code>instance</code> or <code>getInstance</code>. Calling several times <code>new</code> and always getting the same instance seems not very accurate.</p>\n<p>I'm not sure I understand the use case of storing data beside the object rather than in the actual object.</p>\n<p>Btw: In Ruby, classes are spelled in CamelCase and not Snake_Case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T02:55:56.327", "Id": "263943", "ParentId": "261563", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T02:32:43.677", "Id": "261563", "Score": "2", "Tags": [ "object-oriented", "ruby", "singleton" ], "Title": "Singleton in Ruby without using Singleton module or class variable" }
261563
<p>I have a for loop where I either increment or decrement the value of <code>i</code> by 1 each iteration. If <code>start</code> is greater than <code>end</code> I have to decrement <code>i</code> and if <code>end</code> is greater than <code>start</code> I have to increment <code>i</code></p> <p>I had written the for loop like so below, in order to keep it always starting at <code>i = start</code> and ending at <code>i = end</code></p> <p>However, with the pattern, I realize that I cannot include the iteration where <code>i = end</code>, which with a normal for loop, I could have done with <code>&lt;=</code> or <code>&gt;=</code> respectively.</p> <p>What's the cleanest way to write this code?</p> <pre><code>void foo(const int &amp; start, const int &amp; end) { if (start == end) return; int iterChange(1); if (start &gt; end) iterChange = -1; // if start value is greater, we move in reverse for (int i = start; i != end; i = i + iterChange) { // do something with i } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T06:47:57.340", "Id": "516179", "Score": "0", "body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T14:57:23.873", "Id": "516214", "Score": "0", "body": "this has been asked before. See my answer at https://codereview.stackexchange.com/questions/260416/implementing-range-from-to-with-step/260438#260438" } ]
[ { "body": "<p>I'm not much of a C++ programmer, I usually just write in C, but this is what I'd do:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;algorithm&gt;\n#include &lt;cstdio&gt;\n\nvoid foo(int start, int end)\n{\n for (int i = std::min(start, end); i &lt; std::max(start, end); ++i) {\n std::printf(&quot;%d\\n&quot;, i);\n }\n}\n\nint main()\n{\n foo( 0, 5);\n foo(-2, 6);\n foo( 8, -7);\n}\n</code></pre>\n<p>Outputs:</p>\n<pre class=\"lang-none prettyprint-override\"><code>0\n1\n2\n3\n4\n-2\n-1\n0\n1\n2\n3\n4\n5\n-7\n-6\n-5\n-4\n-3\n-2\n-1\n0\n1\n2\n3\n4\n5\n6\n</code></pre>\n<p>Basically, the trick is just to always start at the lower bound, and go to the higher bound. With this trick, you don't have to do anything special to avoid cases where <code>start == end</code>. And, if you want the loop to be inclusive on both bounds, make the <code>i &lt;</code> a <code>i &lt;=</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T10:48:32.270", "Id": "516192", "Score": "1", "body": "If the arguments are ass-backwards, OP's solution will enumerate from largest to smallest index. Your solution iterates always in increasing order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:10:35.527", "Id": "518342", "Score": "1", "body": "@coderodde sure, that makes sense to me. If that's really a requirement, then I guess your solution is the way to go, but I didn't really get that as a critical part of the existing code. The inner comment just says to \"do something with `i`\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T00:18:37.027", "Id": "526556", "Score": "0", "body": "start -> end direction matters in my case so this solution doesn't work" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:16:16.767", "Id": "261565", "ParentId": "261564", "Score": "4" } }, { "body": "<p><strong>Advice 1</strong></p>\n<p>You don't need to pass the parameters via references.</p>\n<p><strong>Advice 2</strong></p>\n<p>For <code>iterChange</code>, you can use the <code>?:</code> operator.</p>\n<p><strong>Advice 3</strong></p>\n<p>You can write <code>i += iterChange</code> instead of <code>i = i + iterChange</code>.</p>\n<p><strong>Advice 4</strong></p>\n<p>I would rename <code>iterChange</code> to <code>iterDelta</code>.</p>\n<p><strong>Advice 5</strong></p>\n<p>You don't really need <code>if (start == end) return;</code></p>\n<p><strong>Summa summarum</strong></p>\n<p>All in all, I thought about the following implementation:</p>\n<pre><code>void foo(const int start, const int end)\n{\n int iterDelta = start &gt; end ? -1 : 1;\n\n for (int i = start; i != end; i += iterDelta)\n {\n std::cout &lt;&lt; i &lt;&lt; &quot;\\n&quot;;\n }\n}\n</code></pre>\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:20:25.257", "Id": "261566", "ParentId": "261564", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T02:59:55.123", "Id": "261564", "Score": "0", "Tags": [ "c++" ], "Title": "cleaner for loop that accommodates direction" }
261564
<p>This program asks the user for a players name, # of goals, saves, games played, etc. This information is ten organized on a .txt file along with the time the information was logged. users can also compare the players based on # of goals, Assists and saves made.</p> <p>If anything can be improved, cleaned or replaced let me know.</p> <p>Main:</p> <pre><code>import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args){ Path path = Paths.get(&quot;/Users/Coding/Desktop/myFile.txt&quot;).toAbsolutePath(); try( BufferedWriter out = new BufferedWriter(new FileWriter(String.valueOf(path)))){ Player player = new Player(out, path); player.menu(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>Player:</p> <pre><code>import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; public class Player { Path path; BufferedWriter out; Scanner scan; HashMap&lt;String, int[]&gt; map; public Player(BufferedWriter out, Path path) { this.out = out; this.scan = new Scanner(System.in); this.map = new HashMap&lt;&gt;(); this.path = path; } public void menu() throws IOException { String task; out.write(&quot;Name GP G A P S S%\n&quot;); do { System.out.print(&quot;What would you like to do today? 1: Add Data, 2: Get The Top Player, 3: Exit the Program: &quot;); task = scan.nextLine(); switch (task) { case &quot;1&quot; -&gt; addData(); case &quot;2&quot; -&gt; getTopPlayers(); case &quot;3&quot; -&gt; { System.out.println(&quot;Goodbye!&quot;); System.exit(0); } } } while (!task.equals(&quot;3&quot;)); } void addData() { boolean cont; do try { System.out.print(&quot;Player First Name: &quot;); String firstName = scan.nextLine() + &quot; &quot;; System.out.print(&quot;Player Last Name: &quot;); String lastName = scan.nextLine(); String fullName = firstName.concat(lastName); System.out.print(&quot;Enter Number of Games Played: &quot;); int gamesPlayed = Integer.parseInt(scan.nextLine()); System.out.print(&quot;Enter Number of Goals Made: &quot;); int goals = Integer.parseInt(scan.nextLine()); System.out.print(&quot;Enter Number of Assists Made: &quot;); int assists = Integer.parseInt(scan.nextLine()); System.out.print(&quot;Enter Number of Points Scored: &quot;); int points = Integer.parseInt(scan.nextLine()); System.out.print(&quot;Enter Number of Saves Made: &quot;); int saves = Integer.parseInt(scan.nextLine()); System.out.print(&quot;Enter Number of Shots Made: &quot;); int shotsOnGoal = Integer.parseInt(scan.nextLine()); int[] data = {gamesPlayed, goals, assists, points, saves, shotsOnGoal}; DateTimeFormatter log = DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm:ss&quot;); LocalDateTime time = LocalDateTime.now(); String logTime = log.format(time); map.put(fullName, data); out.write(&quot;==================================\n&quot;); out.write(fullName + &quot; : &quot; + Arrays.toString(data) + &quot; (&quot; + logTime + &quot;)&quot;); out.flush(); out.newLine(); cont = false; } catch (NumberFormatException | IOException e) { System.out.println(&quot;Enter Valid Input&quot;); cont = true; } while (cont); } void getTopPlayers() { int index = 0; System.out.println(&quot;What Stat Do You Want To Find? Goals, Assists, Points, Saves: &quot;); String choice = scan.nextLine().trim().toLowerCase(); switch (choice) { case &quot;goals&quot; -&gt; index = 1; case &quot;assists&quot; -&gt; index = 2; case &quot;points&quot; -&gt; index = 3; case &quot;saves&quot; -&gt; index = 4; default -&gt; System.out.println(&quot;Not A Valid&quot;); } int finalIndex = index; var max = map.values().stream().mapToInt(e -&gt; e[finalIndex]).max().getAsInt(); for (Map.Entry&lt;String, int[]&gt; entry : map.entrySet()) { if (entry.getValue()[index] == max) { System.out.println(entry.getKey());// Print the key with max value break; } } } } </code></pre>
[]
[ { "body": "<h1><code>Path</code></h1>\n<p>The use of <code>Path</code> is a bit pointless.</p>\n<ul>\n<li>There is no need to use an absolute path to access the file.</li>\n<li>Converting the <code>Path</code> to a <code>String</code> seems wrong. Conversion to a <code>File</code> with the method <code>.toFile()</code> would make more sense.</li>\n<li>IF you convert to a <code>String</code>, then the method <code>.toString()</code> may be more conventional than using <code>String.valueOf()</code>.</li>\n<li>You pass the path to the <code>Player</code> class but don't use it in there.</li>\n</ul>\n<p>So either directly use a <code>String</code>:</p>\n<pre><code>String path = &quot;/Users/Coding/Desktop/myFile.txt&quot;;\n\ntry (Writer out = new BufferedWriter(new FileWriter(path))) {\n</code></pre>\n<p>or convert to a File:</p>\n<pre><code>Path path = Paths.get(&quot;/Users/Coding/Desktop/myFile.txt&quot;); // .toAbsolutePath is not needed\n\ntry (Writer out = new BufferedWriter(new FileWriter(path.toFile()))) {\n</code></pre>\n<h1>Names</h1>\n<p>Choose variable and class names that represent their use and make reading the code easier. For example, the class <code>Player</code> doesn't represent &quot;a player&quot;, so that's a bad name. Instead it's the main class of the application, so something like <code>PlayerStatsApp</code> would be better.</p>\n<p>Also the name <code>out</code> for the <code>BufferedWriter</code> is easily confused with <code>System.out</code>. <code>fileOutput</code> or <code>writer</code> would be a better names. (See also the remarks to the <code>BufferedWriter</code> further down).</p>\n<p>Also <code>scan</code> should be called <code>scanner</code>, and <code>map</code> is also too generic. Something like <code>players</code> or <code>playerStats</code> would be better.</p>\n<h1>Program to interfaces</h1>\n<p>The <code>Player</code> class doesn't need to &quot;know&quot; that you are specifically passing in a <code>BufferedWriter</code>, instead declare the constructor parameter and field simply as a <code>Writer</code>.</p>\n<p>And the map field should be similarly just declared a <code>Map</code> instead of a <code>HashMap</code>.</p>\n<h1>Bug/Hidden feature</h1>\n<p>In <code>getTopPlayers</code> when the user enters an invalid number you output an error message, but still execute the logic with the index <code>0</code> which actually returns the player(s) with the most games.</p>\n<p>Instead use the <code>switch</code> expression actually as an expression, and catch the error case with a value such as <code>-1</code>. Example:</p>\n<pre><code>void getTopPlayers() {\n System.out.println(&quot;What Stat Do You Want To Find? Games, Goals, Assists, Points, Saves: &quot;);\n String choice = scan.nextLine().trim().toLowerCase();\n\n int index = switch (choice) {\n case &quot;games&quot; -&gt; 0; // New case to properly access &quot;games played&quot;\n case &quot;goals&quot; -&gt; 1;\n case &quot;assists&quot; -&gt; 2;\n case &quot;points&quot; -&gt; 3;\n case &quot;saves&quot; -&gt; 4;\n default -&gt; -1;\n }\n\n if (index == -1) {\n System.out.println(&quot;Not A Valid&quot;);\n return;\n }\n\n // ...\n}\n</code></pre>\n<p>(This also makes <code>index</code> &quot;final-like&quot;, so you no longer need to make the <code>finalindex</code> copy.)</p>\n<h1>Data structure</h1>\n<p>Storing the data in a <code>Map</code> is a pointless, since you are not using it as a map. Also while storing the stats in an array makes accessing the separate fields simple with the index, it doesn't make good readable code.</p>\n<p>Instead create a class to store all the data of a player (name and stats) and store them in a list. For example:</p>\n<pre><code>class PlayerStats { // Or maybe just &quot;Player&quot;\n\n private final String firstName;\n private final String lastName;\n\n private final int gamesPlayed;\n private final int goalsMade;\n // etc.\n\n PlayerStats(String firstName, String lastName, int gamesPlayed, int goalsMade /* etc. */) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.gamesPlayed = gamesPlayed;\n this.goalsMade = goalsMade;\n }\n\n public String getFirstName() {\n return firstName\n }\n\n public String getLastName() {\n return lastName\n }\n\n public int getGamesPlayed() {\n return gamesPlayed;\n }\n\n public int getGoalsMade() {\n return goalsMade;\n }\n // etc.\n\n public String getFullName() {\n return firstName + &quot; &quot; + lastName;\n }\n}\n</code></pre>\n<p>However this makes accessing them a bit more advanced. Instead of an index you have to use method references. Following on from the example above for <code>getTopPlayers()</code> the <code>switch</code> becomes:</p>\n<pre><code>Function&lt;PlayerStats, Integer&gt; method = switch (choice) {\n case &quot;games&quot; -&gt; PlayerStats::getGamesPlayed;\n case &quot;goals&quot; -&gt; PlayerStats::getGoalsMade;\n // etc.\n default -&gt; null;\n }\n\nif (method == null) {\n System.out.println(&quot;Not A Valid&quot;);\n return;\n}\n</code></pre>\n<p>And then, when you use a list instead of a map (<code>List&lt;PlayerStats&gt; playersStats</code>) the logic becomes (using a stream for the second part, too):</p>\n<pre><code>var max = playersStats.stream().mapToInt(method).max().getAsInt();\n\nplayersStats.stream()\n .filter(player -&gt; method.apply(player) == max)\n .forEach(player -&gt; System.out.println(player.getFullName()));\n</code></pre>\n<p>(BTW, it is possible to do this logic with a single loop/stream.)</p>\n<h1>Separation of concerns</h1>\n<p>One thing I'd should mention is separation of concerns. One method (or class) should not contain (for example) input and output functions on the one hand and functional logic on the other hand. But this answer is long enough now, so I won't go into that further right now.</p>\n<h1>Other</h1>\n<p>Catching <code>IOException</code> and just printing stack is pointless. That is what happens when the exception isn't caught anyway. Only catch exceptions if you specifically can do something about it.</p>\n<p>Don't exit a program somewhere in the middle with <code>System.exit(0);</code>. Instead just let it run to the end of the <code>main</code> method. In this case, since you catch that case in the <code>while</code> expression, just remove the line.</p>\n<p>Catching the <code>NumberFormatException</code> for all inputs at once makes input a bit irritating, if you have to start from the start any time you mistype.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T23:53:54.220", "Id": "518809", "Score": "0", "body": "Couple problems updating the code. 1: The Stats arent printed onto the text file when the List is printed. 2: ClassCastException on the line `var max = playerData.stream().mapToInt((ToIntFunction<? super PlayerData>) method).max().getAsInt();` I was getting an error on 'method' and so the IDE suggested to cast ToIntFunction" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:23:09.770", "Id": "262764", "ParentId": "261568", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T06:39:25.440", "Id": "261568", "Score": "2", "Tags": [ "java", "array", "hash-map", "file" ], "Title": "Sports DataSheet" }
261568
<p>I got this question as a coding challenge and was unable to get it done under 50 milliseconds (my solution takes &gt;100 ms) :D</p> <p>Would you please review my code and share any idea how to do this within 50ms?</p> <p>Problem Description One of our customers, a multinational company that manufactures industrial appliances, has an internal system to procure (purchase) all resources the company needs to operate. The procurement is done through the company's own ERP (Enterprise Resource Planning) system.</p> <p>A typical business process represented by the ERP system is procure-to-pay, which generally includes the following activities:</p> <ul> <li>create purchase request</li> <li>request approved</li> <li>create purchase order</li> <li>select supplier</li> <li>receive goods</li> <li>pay invoice</li> </ul> <p>Whenever the company wants to buy something, they do so through their ERP system.</p> <p>The company buys many resources, always using their ERP system. Each resource purchase can be considered a case, or single instance of this process. As it happens, the actual as-is process often deviates from the ideal to-be process. Sometimes purchase requests are raised but never get approved, sometimes a supplier is selected but the goods are never received, sometimes it simply takes a long time to complete the process, and so on. We call each unique sequence of activities a variant.</p> <p>The customer provides us with extracted process data from their existing ERP system. The customer extracted one of their processes for analysis: Procure-to-pay. The logfiles contain three columns:</p> <p>activity name case id timestamp We want to analyse and compare process instances (cases) with each other.</p> <p>Acceptance Criteria</p> <ul> <li>Aggregate cases that have the same event execution order and list the 10 variants with the most cases.</li> <li>As that output is used by other highly interactive components, we need to be able to get the query results in well under 50 milliseconds.</li> </ul> <p>Notes:</p> <ul> <li>The sample data set is not sorted, please use the timestamp in the last column to ensure the correct order.</li> <li>The time required to read the CSV file is not considered part of the 50 milliseconds specified in the acceptance criteria.</li> </ul> <p>Sample data: the actual file contains 62,000 rows is <a href="https://docs.google.com/spreadsheets/d/1XUtqFUoZno-7ICF97Kxv43VRBCt5UYBkC6OfUJDNNUc/edit?usp=sharing" rel="nofollow noreferrer">here</a></p> <pre><code>CaseID;ActivityName;Timestamp 100430035020241420012015;Create purchase order item;2015-05-27 12:44:47.000 100430035020261980012015;Create MM invoice by vendor;2015-07-13 00:00:00.000 100430035020119700012015;Reduce purchase order item net value;2015-02-13 10:24:02.000 100430035020066380012015;Change purchase order item;2015-01-23 09:39:33.000 100430035020232560012015;Change purchase order item;2015-05-11 07:58:29.000 100430031000134820012015;Clear open item;2015-07-28 23:59:59.000 100430035020241250012015;Remove payment block;2015-06-04 16:36:26.000 100430035020193960012015;Enter goods receipt;2015-03-12 20:00:06.000 100430031000151590012015;Clear open item;2015-11-24 23:59:59.000 100430031000129230012015;Post invoice in FI;2015-06-01 12:00:37.000 100430035020228280012015;Create MM invoice by vendor;2015-04-07 00:00:00.000 100430031000113630012015;Clear open item;2015-03-24 23:59:59.000 100430035020260940012015;Enter goods receipt;2015-07-16 15:07:49.000 100430035020244540012015;Create purchase order item;2015-06-02 11:06:11.000 </code></pre> <p>my rejected code</p> <pre><code>fun main(args: Array&lt;String&gt;) { val eventlogRows = CSVReader.readFile(&quot;samples/Activity_Log.csv&quot;) val begin = System.currentTimeMillis() val grouped = eventlogRows.groupBy { it.caseId } val map = hashMapOf&lt;String, Int&gt;() grouped.forEach { val toSortedSet = it.value.toSortedSet(compareBy { it.timestamp }) val hash = toSortedSet.joinToString { it -&gt; it.eventName } map[hash] = map[hash] ?: 0 + 1 } val sortedByDescending = map.entries.sortedByDescending { it.value } val end = System.currentTimeMillis() println(String.format(&quot;Duration: %s milliseconds&quot;, end - begin)) } </code></pre> <p>CSVReader.java</p> <pre><code>import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; public class CSVReader { public static List&lt;EventlogRow&gt; readFile(String fileName) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm:ss.SSS&quot;).withZone(ZoneId.of(&quot;UTC&quot;)); try (InputStreamReader reader = new InputStreamReader(new FileInputStream(fileName))) { try (CSVParser csvParser = new CSVParser(reader, CSVFormat.newFormat(';').withFirstRecordAsHeader())) { return csvParser.getRecords().stream() .map(record -&gt; new EventlogRow( record.get(0), record.get(1), LocalDateTime.parse(record.get(2), formatter).atOffset(ZoneOffset.UTC))) .collect(Collectors.toList()); } } catch (IOException e) { throw new RuntimeException(&quot;IOException while reading file&quot;, e); } } } </code></pre> <p>EventlogRow.java</p> <pre><code>import java.time.OffsetDateTime; public class EventlogRow { String caseId; String eventName; OffsetDateTime timestamp; public EventlogRow(String caseId, String eventName, OffsetDateTime timestamp) { this.caseId = caseId; this.eventName = eventName; this.timestamp = timestamp; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T08:45:50.220", "Id": "516188", "Score": "1", "body": "`Aggregate cases that have the same event execution order and list the 10 variants with the most cases` - this phrase is not clear to me. Your method doesn't return anything and prints just duration, what is the purpose of it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T08:56:45.503", "Id": "516189", "Score": "0", "body": "as far as I understand, this phrase means to aggregate the cases by its id and then find the 10 variants (variant is sequence of events for one case ) thats showed the most" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T08:59:51.817", "Id": "516190", "Score": "0", "body": "and yes you are right my code should return the first 10 items of sortedByDescending" } ]
[ { "body": "<p>Disclaimer: I do not know Kotlin, only a bit of Java.</p>\n<h2>Extract the solution to a function</h2>\n<pre><code>private fun topTenCaseFlows(eventLogRows: List&lt;EventLogRow&gt;): List&lt;Pair&lt;String, Int&gt;&gt; {\n val grouped = eventLogRows.groupBy { it.caseId }\n val map = hashMapOf&lt;String, Int&gt;()\n grouped.forEach {\n val toSortedSet = it.value.toSortedSet(compareBy { it.timestamp })\n val hash = toSortedSet.joinToString { it -&gt; it.eventName.orEmpty() }\n map[hash] = map[hash] ?: 0 + 1\n }\n\n val sortedByDescending = map.entries.sortedByDescending { it.value }\n return sortedByDescending.take(10).map { Pair(it.key, it.value) };\n}\n</code></pre>\n<p>Now you have something that takes in the data and returns the top 10.</p>\n<p>If you look at the top 10 at this point you may be surprised that the counts are all 1.</p>\n<h2>Bugs</h2>\n<p><code>map[hash] ?: 0 + 1</code> is interpreted as <code>map[hash] ?: (0 + 1)</code> so parentheses are needed: <code>(map[hash] ?: 0) + 1</code></p>\n<p>The top 10 counts are now much larger than 1 but there's still more.</p>\n<hr />\n<p>Look at case <code>100430035020119700012015</code>:</p>\n<pre><code>100430035020119700012015;Reduce purchase order item net value;2015-02-13 10:24:02.000 \n100430035020119700012015;Enter goods receipt;2015-02-13 10:35:18.000 \n100430035020119700012015;Change purchase order item;2015-02-13 10:24:02.000 \n100430035020119700012015;Change purchase order item;2015-02-13 10:24:02.000 \n100430035020119700012015;Create purchase order item;2015-01-28 06:05:07.000 \n100430035020119700012015;Reduce purchase order item quantity;2015-02-13 10:35:54.000 \n100430035020119700012015;Change purchase order item;2015-02-13 10:35:54.000 \n100430035020119700012015;Change purchase order item;2015-02-13 10:35:54.000 \n100430035020119700012015;Reduce purchase order item quantity;2015-02-13 10:24:02.000 \n100430035020119700012015;Create MM invoice by vendor;2015-02-11 00:00:00.000 \n100430035020119700012015;Reduce purchase order item net value;2015-02-13 10:35:54.000 \n100430035020119700012015;Post invoice in MM;2015-02-23 07:41:59.000 \n100430035020119700012015;Clear open item;2015-03-10 23:59:59.000 \n</code></pre>\n<p>Some events have identical timestamps, <code>2015-02-13 10:24:02.000</code> and <code>2015-02-13 10:35:54.000 </code>.</p>\n<p>It's debatable (and underspecified) what happens first when the timestamps are identical, but all the events certainly happened.</p>\n<pre><code>val hash1 = it.value.toSortedSet(compareBy { it.timestamp }).joinToString { it.eventName.orEmpty() }\nval hash2 = it.value.sortedWith(compareBy(EventLogRow::timestamp, EventLogRow::eventName)).joinToString { it.eventName.orEmpty() }\n</code></pre>\n<p><code>hash1</code> and <code>hash2</code> are not identical. Using a sortedSet discards the entries with duplicate timestamps.</p>\n<h2>Timing</h2>\n<p>Timing Java methods is not straight forward. Typically a single run is not representative of the actual time in real usage.</p>\n<p>Kotlin has a built-in function to time a block, <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.system/measure-time-millis.html\" rel=\"nofollow noreferrer\"><code>measureTimeMillis</code></a>.</p>\n<p>Doing a bit of warmup allows the Java jit to do its thing and reduce the run time significantly:</p>\n<pre><code>fun main(args: Array&lt;String&gt;) {\n val eventlogRows = CSVReader.readFile(&quot;samples/Activity_Log.csv&quot;)\n\n for (i in 0 until 10) {\n topTenCaseFlows(eventLogRows)\n }\n\n var counts: List&lt;Pair&lt;String, Int&gt;&gt; = listOf()\n val timeInMillis = measureTimeMillis {\n counts = topTenCaseFlows(eventLogRows)\n }\n\n println(String.format(&quot;Duration: %s milliseconds&quot;, timeInMillis))\n println(counts.joinToString(separator = &quot;\\r\\n&quot;) { String.format(&quot;%s: %d&quot;, it.first, it.second) })\n}\n\nprivate fun topTenCaseFlows(eventLogRows: List&lt;EventLogRow&gt;): List&lt;Pair&lt;String, Int&gt;&gt; {\n val grouped = eventLogRows.groupBy { it.caseId }\n val map = hashMapOf&lt;String, Int&gt;()\n grouped.forEach {\n val hash = it.value.sortedWith(compareBy(EventLogRow::timestamp, EventLogRow::eventName)).joinToString { it.eventName.orEmpty() }\n map[hash] = (map[hash] ?: 0) + 1\n }\n\n val sortedByDescending = map.entries.sortedByDescending { it.value }\n return sortedByDescending.take(10).map { Pair(it.key, it.value) };\n}\n\n</code></pre>\n<p>In my testing it goes from &gt;100ms to &lt;50ms</p>\n<h2>Style</h2>\n<p>I prefer the method chaining style from LINQ so this is how I would write it:</p>\n<pre><code>private fun topTenCaseFlows(eventLogRows: List&lt;EventLogRow&gt;): List&lt;Pair&lt;String, Int&gt;&gt; {\n return eventLogRows.groupBy { it.caseId }\n .map { case -&gt;\n case.value.sortedWith(compareBy(EventLogRow::timestamp, EventLogRow::eventName))\n .joinToString { it.eventName.orEmpty() }\n }\n .groupingBy { it }.eachCount()\n .entries.sortedByDescending { it.value }\n .take(10)\n .map { Pair(it.key, it.value) }\n}\n</code></pre>\n<p>Note: You can remove <code>EventLogRow::eventName</code> if you would prefer use the event order from the file. According to the documentation both <code>groupBy</code> and <code>sortedWith</code> guarantee stable ordering with regards to entry order on duplicate keys.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:43:48.520", "Id": "518383", "Score": "0", "body": "Thank you @Johnbot for taking the time to review my code and for the bugs and style suggestions. I appreciate! \n\none more question, do you see another way to implement the logic (different algorithm, data structure,.. ) under 50ms without the warmup of the Java jit trick?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:13:20.350", "Id": "262617", "ParentId": "261570", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T08:13:18.707", "Id": "261570", "Score": "2", "Tags": [ "java", "kotlin" ], "Title": "Aggregate data from a huge list under 50ms" }
261570
<p>I've written this class to wrap a collection of bytes and interpret them as 16-bit floats. It's supposed to work like <code>memoryview(buf).cast('f')</code> or <code>array.array('f', buf)</code> I'm trying to avoid converting back and forth between values as much as possible. cPython does not currently support using the format code <code>'e'</code> as the format argument to <code>array.array</code>.</p> <p>The motivation is to support 16bit floating point arrays from this RFC: <a href="https://www.rfc-editor.org/rfc/rfc8746.html#name-types-of-numbers" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc8746.html#name-types-of-numbers</a> as part of this decoder: <a href="https://github.com/agronholm/cbor2" rel="nofollow noreferrer">https://github.com/agronholm/cbor2</a></p> <p>Is there anything else I can add or take away?</p> <pre><code>import struct from collections.abc import Sequence class Float16Array(Sequence): &quot;&quot;&quot; Takes a bytes or bytearray object and interprets it as an array of 16-bit IEEE half-floats Behaves a bit like if you could create an array.array('e', [1, 2, 3.7]) &quot;&quot;&quot; def __init__(self, buf): self.hbuf = memoryview(buf).cast('H') @staticmethod def _to_h(v): &quot;convert float to an unsigned 16 bit integer representation&quot; return struct.unpack('H', struct.pack('e', v))[0] @staticmethod def _to_v(h): &quot;convert 16-bit integer back to regular float&quot; return struct.unpack('e', struct.pack('H', h))[0] def __len__(self): return len(self.hbuf) def __eq__(self, other): if isinstance(other, self.__class__): return self.hbuf == other.hbuf if isinstance(other, Sequence): if len(self) != len(other): return False for hval, oval in zip(self.hbuf, other): try: if hval != self._to_h(oval): return False except struct.error: return False return True else: raise NotImplemented def __getitem__(self, key): if isinstance(key, slice): return self.__class__(self.hbuf[key].cast('B')) item = self.hbuf[key] return self._to_v(item) def __contains__(self, value): try: return self._to_h(value) in self.hbuf except struct.error: return False def __reversed__(self): for item in reversed(self.hbuf): yield self._to_v(item) def index(self, value, start=0, stop=None): buf = self.hbuf[start:stop] try: buf_val = self._to_h(value) except struct.error: raise TypeError('value must be float or int') from None for i, v in enumerate(buf): if v is buf_val or v == buf_val: return i raise ValueError def count(self, value): try: buf_val = self._to_h(value) except struct.error: raise TypeError('value must be float or int') from None return sum(1 for v in self.hbuf if v == buf_val) def __repr__(self): contents = ', '.join('{:.2f}'.format(v).rstrip('0') for v in self) return self.__class__.__name__ + '(' + contents + ')' if __name__ == '__main__': my_array = Float16Array(struct.pack('eeee', 0.1, 0.1, 72.0, 3.141)) assert 0.1 in my_array assert my_array.count(72) == 1 assert my_array.count(0.1) assert my_array == [0.1, 0.1, 72.0, 3.141] print(list(reversed(my_array))) print(my_array) assert my_array[0:-1] == Float16Array(struct.pack('eee', 0.1, 0.1, 72.0)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:15:09.683", "Id": "516232", "Score": "1", "body": "Why are you packing like this? Embedded application, network application, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T09:46:12.170", "Id": "518304", "Score": "1", "body": "@Reinderien This is for packed arrays from this specification https://www.rfc-editor.org/rfc/rfc8746.html#name-types-of-numbers and is intended to be an example of an extended data type for this decoder: https://github.com/agronholm/cbor2 I will add this to the question." } ]
[ { "body": "<p>Having studied further, I think the biggest thing I'm missing is a <code>__hash__</code> method like this:</p>\n<pre><code>def __hash__(self):\n if self.hbuf.readonly and self._hash is None:\n self._hash = hash((self.__class__.__name__, self.hbuf.tobytes()))\n return self._hash\n elif self._hash is not None:\n return self._hash\n else:\n raise ValueError('cannot hash, underlying bytes are read-write')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T17:28:06.323", "Id": "262689", "ParentId": "261573", "Score": "0" } }, { "body": "<ul>\n<li>Add PEP484 type hints</li>\n<li>In your <code>to_h</code> and <code>to_v</code>, consider tuple-unpacking the return value from <code>struct</code> to get a free assertion that there is only one item</li>\n<li><code>NotImplemented</code> is not a very friendly way to handle comparison of disparate types. I would far sooner expect <code>return False</code>.</li>\n<li>Move your testing code into a function to avoid namespace pollution</li>\n<li>Single-quotes are not standard for docstrings; use triple quotes instead</li>\n<li>your <code>__repr__</code> was broken and used <code>__name</code> where it needed <code>__name__</code></li>\n<li>Have you considered replacing most of this with a Numpy <a href=\"https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.float16\" rel=\"nofollow noreferrer\">half-precision</a> array created via <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html\" rel=\"nofollow noreferrer\">frombuffer</a>?</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import struct\nfrom collections.abc import Sequence\nfrom typing import Union, Any, Iterable, Optional\n\n\nclass Float16Array(Sequence):\n &quot;&quot;&quot;\n Takes a bytes or bytearray object and interprets it as an array of\n 16-bit IEEE half-floats\n\n Behaves a bit like if you could create an array.array('e', [1, 2, 3.7])\n &quot;&quot;&quot;\n def __init__(self, buf: bytes):\n self.hbuf = memoryview(buf).cast('H')\n\n @staticmethod\n def _to_h(v: float) -&gt; int:\n &quot;&quot;&quot;convert float to an unsigned 16 bit integer representation&quot;&quot;&quot;\n i, = struct.unpack('H', struct.pack('e', v))\n return i\n\n @staticmethod\n def _to_v(h: int) -&gt; float:\n &quot;&quot;&quot;convert 16-bit integer back to regular float&quot;&quot;&quot;\n f, = struct.unpack('e', struct.pack('H', h))\n return f\n\n def __len__(self) -&gt; int:\n return len(self.hbuf)\n\n def __eq__(self, other: Any) -&gt; bool:\n if isinstance(other, self.__class__):\n return self.hbuf == other.hbuf\n\n if not isinstance(other, Sequence):\n return False\n\n if len(self) != len(other):\n return False\n\n for hval, oval in zip(self.hbuf, other):\n try:\n if hval != self._to_h(oval):\n return False\n except struct.error:\n return False\n\n return True\n\n def __getitem__(self, key: Union[int, slice]) -&gt; float:\n if isinstance(key, slice):\n return self.__class__(self.hbuf[key].cast('B'))\n item = self.hbuf[key]\n return self._to_v(item)\n\n def __contains__(self, value: float) -&gt; bool:\n try:\n return self._to_h(value) in self.hbuf\n except struct.error:\n return False\n\n def __reversed__(self) -&gt; Iterable[float]:\n for item in reversed(self.hbuf):\n yield self._to_v(item)\n\n def index(self, value: float, start: int = 0, stop: Optional[int] = None) -&gt; int:\n buf = self.hbuf[start:stop]\n try:\n buf_val = self._to_h(value)\n except struct.error:\n raise TypeError('value must be float or int') from None\n for i, v in enumerate(buf):\n if v is buf_val or v == buf_val:\n return i\n raise ValueError\n\n def count(self, value: Union[float, int]) -&gt; int:\n try:\n buf_val = self._to_h(value)\n except struct.error:\n raise TypeError('value must be float or int') from None\n return sum(1 for v in self.hbuf if v == buf_val)\n\n def __repr__(self) -&gt; str:\n contents = ', '.join('{:.2f}'.format(v).rstrip('0') for v in self)\n return f'{self.__class__.__name__}({contents})'\n\n\ndef test():\n my_array = Float16Array(struct.pack('eeee', 0.1, 0.1, 72.0, 3.141))\n assert 0.1 in my_array\n assert my_array.count(72) == 1\n assert my_array.count(0.1)\n assert my_array == [0.1, 0.1, 72.0, 3.141]\n print(list(reversed(my_array)))\n print(my_array)\n assert my_array[0:-1] == Float16Array(struct.pack('eee', 0.1, 0.1, 72.0))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2>Suggested (numpy)</h2>\n<p>No custom code; the equivalent test is:</p>\n<pre><code>def test_new():\n data = (0.1, 0.1, 72.0, 3.141)\n my_array = np.array(data, dtype=np.float16)\n assert 0.1 in my_array\n assert np.sum(my_array == 72) == 1\n assert np.sum(my_array == 0.1) == 2\n assert np.all(np.isclose(my_array, data, rtol=1e-4, atol=1e-4))\n print(my_array[::-1])\n print(my_array)\n assert np.all(np.isclose(\n my_array[:-1],\n np.array(data[:-1], dtype=np.float16),\n ))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T17:25:45.533", "Id": "521763", "Score": "0", "body": "That's great thank you! In most cases I would use Numpy, but I didn't want to add additional dependencies to the library I'm working on (except as optional extras)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T17:27:44.860", "Id": "521764", "Score": "0", "body": "That doesn't sound like very solid rationale. `numpy` is a very common secondary dependency in the pip ecosystem, and in fact it's likely that some of your users would want `numpy` compatibility for other reasons anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T17:54:40.643", "Id": "521765", "Score": "0", "body": "It's not common in the embedded or IoT worlds. There are no off the shelf builds of numpy for arm32 or big-endian architectures, both of which we have been asked to support. I'm planning to make it an optional dependency for the server side since numeric array tags have recently been added to the CBOR specs. In that case numpy is of course the best option." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-06T20:24:10.843", "Id": "263822", "ParentId": "261573", "Score": "2" } } ]
{ "AcceptedAnswerId": "263822", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T11:01:13.267", "Id": "261573", "Score": "6", "Tags": [ "python", "python-3.x", "floating-point" ], "Title": "An IEEE half-float implementation in python similar to array.array, is there any way I could make this more efficient?" }
261573
<p>I have implemented Binary_Search in python (I think), and my own method for <code>range</code> objects. I want to know if there is any way to improve this code, here it is:</p> <pre><code>def findAmountString(string, char): amount = 0 for n in range(len(string)): if string[n] == char: amount += 1 return amount def findrange(rangeToFind): constList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] rangeNum = 1 rangeToFind = list(str(rangeToFind)) del rangeToFind[0:6] del rangeToFind[-1] start = &quot;&quot; stop = &quot;&quot; step = &quot;&quot; for n in range(len(rangeToFind)): if rangeToFind[n] in constList: if rangeNum == 1: start += rangeToFind[n] elif rangeNum == 2: stop += rangeToFind[n] else: step += rangeToFind[n] if rangeToFind[n] == &quot;,&quot;: rangeNum += 1 if step == &quot;&quot;: step = &quot;1&quot; return [int(start), int(stop), int(step)] def search(newData, value): if isinstance(newData, range): #This was my own method for 'range' rangeData = findrange(newData) if rangeData[0] &gt; value or rangeData[1]-1 &lt; value or value % rangeData[2] != 0: return False return True else: #This is called the 'binary_search' method (I think) newData = set(newData) while len(newData) != 1: if newData[int(len(newData)/2)] &gt; value: newData = newData[:int(len(newData)/2)] else: newData = newData[int(len(newData)/2):] return newData[0] == value </code></pre> <p>Is there any way to improve this code?</p> <p>Side Note: I purposely didn't put Binary_Search in the Title because I didn't know if the code I coded was using Binary_Search.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:18:13.687", "Id": "516194", "Score": "0", "body": "Is there any use of the `findAmountString` function you have posted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:41:46.580", "Id": "516199", "Score": "0", "body": "Have you read about the `bisect` module?" } ]
[ { "body": "<ul>\n<li>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP8</a> guidelines for naming functions and variables</li>\n<li>Avoid multiple statements on one line: <code>if string[n] == char: amount += 1</code></li>\n<li><strong>Documentation</strong>. Your code is rather hard to read, as more or less nothing is documented. What is the prupose of <code>search</code> and <code>findRange</code>? What do these magic numbers mean: <code>del range_to_find[0:6]</code>, <code>del range_to_find[-1]</code>? You should provide type annotations, docstrings and maybe the occasional comment to explain some functionality in more detail.</li>\n</ul>\n<hr />\n<p><strong><code>findAmountString</code> -&gt; <code>find_amount_string</code></strong></p>\n<p>Three steps to improve this function:</p>\n<ol>\n<li>Never iterate over indices in Python:</li>\n</ol>\n<pre><code>def find_amount_string(string, char):\n amount = 0\n \n for c in string:\n if c == char:\n amount += 1\n \n return amount\n</code></pre>\n<ol start=\"2\">\n<li><a href=\"https://www.w3schools.com/python/python_lists_comprehension.asp\" rel=\"nofollow noreferrer\">List comprehension</a> / <a href=\"https://djangostars.com/blog/list-comprehensions-and-generator-expressions/\" rel=\"nofollow noreferrer\">Generator expression</a> / Functional approach</li>\n</ol>\n<pre><code>def find_amount_string(string, char):\n return sum(1 for c in string if c == char)\n</code></pre>\n<ol start=\"3\">\n<li>Using built-ins</li>\n</ol>\n<pre><code>def find_amount_string(string, char):\n return string.count(char)\n</code></pre>\n<p>As you can see, we're now only wrapping built-in <code>count</code>, so I'd say we don't need that function anymore. Also, this function isn't used at all in the code provided, so it might not have been needed in the first place.</p>\n<hr />\n<p><strong><code>findRange</code> -&gt; <code>find_range</code></strong></p>\n<p>As far as I can tell this function works, but it's really hard to understand why at first glance. It's also not clear why you would want to manually reconstruct <code>start, stop, step</code> from a given <code>range</code> object instead of just getting the <code>range.start, range.stop, range.step</code> attributes from the object. It's also not a reinventing-the-wheel situation, as you're just deconstructing an exsting object and putting it back together with less functionality in a very round-about way. I would say nothing about this function is a good idea.</p>\n<hr />\n<p><code>search</code></p>\n<p>This function looks like its only purpose is to replace Python's <code>in</code> operator. So if this is not a programming exercise, you should probably replace all calls like <code>search(new_data, value)</code> by <code>value in new_data</code>. But let's treat it as a programming exercise, as that's probably the purpose of your implementation:</p>\n<p><strong>Functionality for <code>range</code> objects</strong></p>\n<p>Instead of hardcoding indices you should use tuple unpacking:</p>\n<pre><code>start, stop, step = find_range(new_data)\n\nif start &gt; value or stop - 1 &lt; value or value % step != 0:\n return False\n\nreturn True\n</code></pre>\n<p>However, your implementation will provide incorrect results if <code>range.start % range.step != 0</code>. Consider this simple example:</p>\n<pre><code>print(list(range(3, 10, 2))) # [3, 5, 7, 9]\nprint(search(range(3, 10, 2), 5)) # False\n</code></pre>\n<p>You need to replace <code>value % step != 0</code> by either <code>value % step != start % step</code> or <code>(value - start) % step != 0</code>.</p>\n<p>This can also be simplified to</p>\n<pre><code>start, stop, step = find_range(new_data)\nreturn start &lt;= value &lt; stop and (value - start) % step == 0\n</code></pre>\n<p>As I said, <code>find_range</code> provides no additional benefit here, so this will also work:</p>\n<pre><code>return new_data.start &lt;= value &lt; new_data.stop and (value - new_data.start) % new_data.step == 0\n</code></pre>\n<p>This is probably similiar to Python's own implementation of <code>value in range</code>.</p>\n<p><strong>Functionality for everything <code>else</code></strong></p>\n<p>This function does not work for anything but <code>range</code> objects, your <code>else</code> clause will fail since <code>'set' objects are not subscriptable</code>.</p>\n<p>The approach used is binary search, but I haven't checked its correctness for all cases. Please be aware that even a correct binary search implementation will only work for sorted data.</p>\n<p>Here is some <a href=\"https://www.geeksforgeeks.org/python-program-for-binary-search/\" rel=\"nofollow noreferrer\">further reading</a> on recursive and iterative binary search implementations in Python if you're interested. As stochastic13 correctly points out, the current approach unnecessarily harms runtime.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:46:06.813", "Id": "261578", "ParentId": "261575", "Score": "8" } }, { "body": "<p>Nice attempt. @riskypenguin's answer is great, I am just adding this to cover some extra points like the optimization (time-complexity) part.</p>\n<h3>Optimization</h3>\n<p>I assume you are familiar with the big-O notation. Mention in the comments if not, will try to add a small explanatory addendum.</p>\n<ol>\n<li><code>range</code> objects: It is commendable that you use <code>str</code> to get the name of the object so that you don't have to convert it to a list which might be O(n). However, you can do it much simply.\n<ul>\n<li>The python <code>range</code> object has a very efficient implementation. You can directly use the <code>in</code> operation to check membership and it will work in almost O(1) <a href=\"https://stackoverflow.com/questions/57929556/python-in-operator-time-complexity-on-range\">time</a>. Therefore, for the first part of your code, simply returning <code>value in newData</code> will work</li>\n<li>Alternatively, you can also get the <code>start, stop, step</code> arguments directly from a <code>range</code> object by using <code>newData.start, newData.stop, newData.step</code> if you want to continue using your code.</li>\n</ul>\n</li>\n<li><code>lists</code> (I assume you will always get sorted lists in this code, otherwise you cannot use binary search)\n<ul>\n<li>The main point of binary search is to not have to go over all the arguments (O(n)) to find whether the element is present or not. But, your code keeps slicing the list and assigning it to the name <code>newData</code>. This creates a separate list every time you slice and assign (see the time complexity of the list slicing operation <a href=\"https://stackoverflow.com/questions/13203601/big-o-of-list-slicing\">here</a>). Hence you get a much worse time complexity than the expected O(log n) for binary search.</li>\n<li>In order to solve this, you should keep track of the first and last elements of your current <code>newData</code> only, since they are the minimum and the maximum elements in the list. You can additionally keep track of the number of elements in the <code>newData</code> (halved every time) to keep using your <code>while</code> condition to finish searching. (see bottom)</li>\n</ul>\n</li>\n</ol>\n<h3>Shortening</h3>\n<ol>\n<li>Assuming that you wanted to use the long-version of the <code>range</code> searching code, you can significantly shorten it. You can split the string to quickly get the <code>start, step, stop</code>. That'll save you all the complex <code>rangeNum</code> logic.</li>\n<li>Moreover, instead of using <code>del</code> you can just index the string to get the substring which is a bit cleaner (doesn't matter much in efficiency)</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def findrange(rangeToFind):\n rangeToFind = str(rangeToFind)\n rangeToFind = rangeToFind[6:len(rangeToFind) - 1]\n step = 1\n cutRange = rangeToFind.split(&quot;, &quot;)\n if len(cutRange) == 2:\n start, stop = cutRange\n else:\n start, stop, step = cutRange\n return [int(start), int(stop), int(step)]\n\n</code></pre>\n<h3>External Library</h3>\n<p>Also, I assume at least some reason of coding this part is to learn/code-without-using the built-in libraries. But just in case it comes in handy later, you can look at the <code>bisect</code> library in python. There are several others for specific binary searching too, but for vanilla lists, <code>bisect</code> will do.</p>\n<h3>Suggested modification</h3>\n<p>This might not be the cleanest version. Keeping it here as an example of what I meant by a slicing-free implementation</p>\n<pre class=\"lang-py prettyprint-override\"><code>def searchlist(data, value):\n max_val = len(data) - 1\n min_val = 0\n found = False\n while max_val - min_val &gt; 1:\n if data[(max_val + min_val) // 2] &lt; value:\n min_val = (max_val + min_val) // 2 + 1\n else:\n max_val = (max_val + min_val) // 2\n if data[max_val] == value or data[min_val] == value:\n return True\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:59:10.090", "Id": "516202", "Score": "0", "body": "Overall agreed. The first line of `findrange` needs to be changed to `rangeToFind = str(rangeToFind)`, as `split` will fail for lists. Also `start = \"\"` and `stop = \"\"` initializations are redundant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:59:56.000", "Id": "516203", "Score": "0", "body": "@riskypenguin Yes, my bad. Altering both" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T02:58:47.887", "Id": "518274", "Score": "1", "body": "Since you're showing alternate versions that don't use `step = \"1\"` / `int(step)`, perhaps comment on how crazy it is to use strings when you could be using integers? (With `0` instead of the empty string.) Even though we don't know what the real purpose of the original code was, or why it's written that way, I'd be surprised if concatenating decimal digits(?) was optimal, if that's what it's even doing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:52:28.407", "Id": "261580", "ParentId": "261575", "Score": "4" } } ]
{ "AcceptedAnswerId": "261578", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T11:50:04.660", "Id": "261575", "Score": "1", "Tags": [ "python", "python-3.x", "reinventing-the-wheel", "binary-search" ], "Title": "Search Method In Python / Python 3.9" }
261575
<p>This project I'm dealing with will read the size of free memory segments and size of processes from a text file and then will try to allocate a memory partition for each process using the first-fit, best-fit and worst-fit allocation algorithms. Below is the first part of the code I wrote.</p> <pre><code>import sys filename = sys.argv[1] with open(filename, &quot;r&quot;) as file: free_memory = file.readline().strip().split(',') process_size = list(map(int, file.readline().strip().split(','))) file = open(&quot;output.txt&quot;,&quot;w&quot;) #---------------------------# #First-Fit Memory Allocation# #---------------------------# file.write(f&quot;First-Fit Memory Allocation\n{'-'*60}\n&quot;) file.write(f&quot;start =&gt; {' '.join(free_memory)}\n&quot;) memory = list(map(int, free_memory)) memory_str = list(free_memory) for process in process_size: data = f&quot;{process} =&gt; &quot; allocated = False for index in range(len(memory)): if not allocated and memory[index] &gt;= process: memory[index] -= process memory_str[index] = memory_str[index][:-1*len(str(process))] memory_str[index] += f&quot;{process}*&quot; if(memory[index] != 0): memory_str[index] += f&quot; {memory[index]}&quot; allocated = True data += f&quot;{memory_str[index]} &quot; if(not allocated): data = f&quot;{process} =&gt; not allocated, must wait&quot; file.write(data+'\n') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:53:35.133", "Id": "516218", "Score": "0", "body": "Please show an example input file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T18:13:31.927", "Id": "516248", "Score": "1", "body": "There appears to be [this duplicate question](https://codereview.stackexchange.com/q/261590/120114) - does the input there suffice as the input here?" } ]
[ { "body": "<p>I think from a prior question the input is:</p>\n<pre><code>300,600,350,200,750,125\n115,500,358,200,375\n</code></pre>\n<p>I believe the assignment asked for a simplification of the code as it is a little convoluted at the moment. I'll try to clean it up a bit.</p>\n<p>I've added what I guess are the other additional &quot;strategies&quot; as well.</p>\n<p>I think the major difference between the given code and what I am going to offer is that the original maintains a string and integer version of the memory regions for what looks like the purpose of flagging a region as &quot;in use&quot; with a <code>*</code>. I'm going to use a tuple to indicate the <code>(size, availability)</code> of the memory block. then when printing we can look to add the flag as appropriate.</p>\n<p>At the moment, our strategy is set to &quot;First Fit&quot;:</p>\n<pre><code>## ---------------------------\n## We print a nice display of memory in a few places so let's make a method to do that\n## ---------------------------\ndef format_memory(memory_blocks):\n return ' '.join(str(x[0]) + (&quot;&quot; if x[1] else &quot;*&quot;) for x in memory_blocks)\n## ---------------------------\n\n## ---------------------------\n## Pick one of these to be your fit_strategy.\n## ---------------------------\ndef get_fit_strategy(key):\n def find_candidates(memory_blocks, process_size):\n return [(idx, val) for (idx, val) in enumerate(memory_blocks) if val[1] and val[0] &gt;= process_size]\n\n def first_fit(memory_blocks, process_size):\n candidates = find_candidates(memory_blocks, process_size)\n return next((candidate[0] for candidate in candidates), None)\n\n def best_fit(memory_blocks, process_size):\n candidates = find_candidates(memory_blocks, process_size)\n candidates = sorted(candidates, key=lambda x: x[1][0])\n return next((candidate[0] for candidate in candidates), None)\n\n def worst_fit(memory_blocks, process_size):\n candidates = find_candidates(memory_blocks, process_size)\n candidates = sorted(candidates, reverse=True, key=lambda x: x[1][0])\n return next((candidate[0] for candidate in candidates), None)\n \n ## ---------------------------\n ## keep the name and the implementation aligned.\n ## ---------------------------\n strategies = {\n &quot;first&quot; : {&quot;nm&quot;: &quot;First Fit&quot;, &quot;fn&quot;: first_fit},\n &quot;best&quot; : {&quot;nm&quot;: &quot;Best Fit&quot;, &quot;fn&quot;: best_fit},\n &quot;worst&quot; : {&quot;nm&quot;: &quot;Worst Fit&quot;, &quot;fn&quot;: worst_fit}\n }\n ## ---------------------------\n\n ## ---------------------------\n ## get a strategy falling back to &quot;first&quot;\n ## ---------------------------\n selected_strategy = strategies.get(key, strategies[&quot;first&quot;])\n ## ---------------------------\n\n ## ---------------------------\n ## when called, return the name and implementation of our strategy\n ## ---------------------------\n return (selected_strategy[&quot;nm&quot;], selected_strategy[&quot;fn&quot;])\n ## ---------------------------\n\nfit_strategy_name, get_free_block_index = get_fit_strategy(&quot;first&quot;)\n## ---------------------------\n\n## ---------------------------\n## Read our two lines of input.\n## ---------------------------\nwith open(&quot;memory.txt&quot;, &quot;r&quot;) as input_file:\n ## list of tuples(size, is_available)\n memory_blocks = [(int(x), True) for x in input_file.readline().split(',')]\n\n ## list of process requirements\n process_sizes = [int(x) for x in input_file.readline().split(',')]\n## ---------------------------\n\n## ---------------------------\n## Append each &quot;line&quot; to print to a list of lines to be printed at the end\n## ---------------------------\nresults = []\nresults.append(f&quot;{ fit_strategy_name } Memory Allocation&quot;)\nresults.append(f&quot;{ '-' * 60 }&quot;)\nresults.append(f&quot;start =&gt; { format_memory(memory_blocks) }&quot;)\n## ---------------------------\n\n## ---------------------------\n## For each process (an entry in process_sizes) attempt to find a block of memory\n## ---------------------------\nfor process_size in process_sizes:\n\n ## ---------------------------\n ## Using our selected strategy find the index (or None) of a block that is\n ## &quot;free&quot; and &quot;big enough&quot;\n ## ---------------------------\n index = get_free_block_index(memory_blocks, process_size)\n ## ---------------------------\n\n ## ---------------------------\n ## There was no appropriate block found to host this process\n ## ---------------------------\n if index is None:\n results.append(f&quot;{ process_size } =&gt; not allocated, must wait&quot;)\n continue\n ## ---------------------------\n\n ## ---------------------------\n ## Insert a new memory block representing what will be the remaining memory after we\n ## allocate process_size memory out of memory_blocks[index] flagging it as available\n ## ---------------------------\n remaining_allocation = memory_blocks[index][0] - process_size\n if remaining_allocation:\n memory_blocks.insert(index+1, (remaining_allocation, True))\n ## ---------------------------\n\n ## ---------------------------\n ## Allocate our memory flagging it as unavailable (False)\n ## ---------------------------\n memory_blocks[index] = (process_size, False)\n ## ---------------------------\n\n results.append(f&quot;{ process_size } =&gt; { format_memory(memory_blocks) }&quot;)\n## ---------------------------\n\n## ---------------------------\n## now write the results that we stored in the list\n## ---------------------------\nwith open(&quot;output.txt&quot;,&quot;w&quot;) as output_file:\n output_file.write('\\n'.join(results))\n## ---------------------------\n</code></pre>\n<p>When run it will produce a file (<code>output.txt</code>) with the following contents:</p>\n<pre><code>First Fit Memory Allocation\n------------------------------------------------------------\nstart =&gt; 300 600 350 200 750 125\n115 =&gt; 115* 185 600 350 200 750 125\n500 =&gt; 115* 185 500* 100 350 200 750 125\n358 =&gt; 115* 185 500* 100 350 200 358* 392 125\n200 =&gt; 115* 185 500* 100 200* 150 200 358* 392 125\n375 =&gt; 115* 185 500* 100 200* 150 200 358* 375* 17 125\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:23:10.250", "Id": "262640", "ParentId": "261581", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T13:03:21.787", "Id": "261581", "Score": "2", "Tags": [ "python", "memory-management" ], "Title": "Contiguous memory allocation using first-fit algorithm" }
261581
<p>I'm trying to build out some DeFi position tracking pages in Google Sheets. I want to pull from the Zapper API (or other APIs) to track trades, positions, gains, losses, fees...etc. This is my first crack at tracking a position on SushiSwap.</p> <p>I tried to make re-usable functions and organize the code so it's easy to understand/work with.</p> <p>I'd love some insight on better ways to write the functions and/or organize the code. I think this could be a big project and I want to make sure I'm using a good system to write code and organize things. Basically, am I on the right track? Where could I do better?</p> <pre><code>// function to grab the API data and parse it. // returns an array function pullAndParseAPISushi (walletAddress, networkName){ var apiKEY = &quot;96e0cc51-a62e-42ca-acee-910ea7d2a241&quot;; // API key from Zapper var url = &quot;https://api.zapper.fi/v1/staked-balance/masterchef?addresses%5B%5D=&quot;+ walletAddress + &quot;&amp;network=&quot; + networkName + &quot;&amp;api_key=&quot; + apiKEY; // assembles the API URL with the wallet address and network name var response = UrlFetchApp.fetch(url); // pulls data from the API var theparsedJSONdata = JSON.parse(response); // parses the JSON response from the API return theparsedJSONdata // returns the parsed array } // access level 2 of the json data - it gets at the array of values after the wallet address /** this is the key line that breaks open the data. Need this for next level data */ /** first level is the wallet address, second level is the big array, third level is the reward tokens...etc. */ function createTheArray(parsedDataFromJson, walletAddress) { var levelTwo = parsedDataFromJson[walletAddress][0] // 'breaks through' the first array var lastArrayReturn = []; /** creates and loads an array with all the various pairs */ for (const key in levelTwo){ //console.log(key + &quot; -&gt; &quot; + levelTwo[key]) var tempArray = new Array(0) // not sure why new array has argument for 0 tempArray.push(key,levelTwo[key]) // stores each pair in a sigle array lastArrayReturn.push(tempArray) // loads smaller arrays into larger, single array; 2D array } // lastArrayReturn is an array of arrays for level 2 data (i.e. the data after the wallet address in the JSON object) console.log(lastArrayReturn) return lastArrayReturn } // transposes a given array function transposeArray(theArray){ var result = new Array(theArray[0].length); for(var i=0; i &lt; result.length; i++){ result[i] = new Array(theArray.length); for(var j = 0; j &lt; result[i].length; j++){ result[i][j] = theArray[j][i] } } console.log(&quot;the transposed array is: &quot; + result) return result } // putting the array from the api parse into the Sushi Data Pull sheet function placeSushiData (anArray) { theSushiArray = transposeArray(anArray) // call a function to transpose the array let ss = SpreadsheetApp.getActiveSpreadsheet(); // get active spreadsheet let targetSheet = ss.getSheetByName('Sushi Data Pull'); // the tab where the data is going let targetRange = targetSheet.getRange(1,4, theSushiArray.length, theSushiArray[0].length); // set the targe range of cells let targetDateRange = targetSheet.getRange(2,3,1,1); // range for the timestamp; 2nd row, 3rd column targetRange.setValues(theSushiArray); // sets cells in the target range to the values in the array targetDateRange.setValue(new Date()); // puts time stamp in the date column } // fuction to run the data pull and placement function runTheProgram(){ var walletAddress = &quot;0x00000000000000000000000000&quot;; var networkName = &quot;polygon&quot;; var dataArray = pullAndParseAPISushi(walletAddress, networkName) var adjustedArray = createTheArray(dataArray, walletAddress) placeSushiData(adjustedArray) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:12:16.460", "Id": "516215", "Score": "0", "body": "Note that your question is still too generic. It seems your code is about stock data, yet the word \"stock\" isn't in the title. Why not? Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask). The site standard is for the title to **simply state the task accomplished by the code**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:57:06.407", "Id": "516226", "Score": "0", "body": "@BCdotWEB In the body I explain that I'm working with data from defi protocols." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T06:02:09.540", "Id": "518279", "Score": "0", "body": "Please read the guidelines WRT question titles and follow them." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T13:21:40.643", "Id": "261582", "Score": "0", "Tags": [ "javascript", "array", "google-apps-script", "google-sheets" ], "Title": "Pulling data from an API and working with it in Google Sheets" }
261582
<p>I have this code which I use to append data to a JSON file. It will be helpful if someone could suggest pointers on:</p> <ul> <li>Reducing file opening and closing</li> <li>Make the <code>write_json</code> function efficient</li> </ul> <p>and other general pointers. Thanks a lot.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define ENTRIES_PER_LOG 10000 static int packet_count = 0; static char filename[100] = &quot;output.json&quot;; int write_json(const char *json){ packet_count++; // create file if it doesn't exist FILE* fp = fopen(filename, &quot;r&quot;); if (!fp) { fp = fopen(filename, &quot;w&quot;); if (!fp) return 0; fputs(&quot;[]&quot;, fp); fclose(fp); } // add the document to the file fp = fopen(filename, &quot;rb+&quot;); if (fp) { // check if first is [ fseek(fp, 0, SEEK_SET); if (getc(fp) != '[') { fclose(fp); return 0; } // is array empty? int is_empty = 0; if (getc(fp) == ']') is_empty = 1; // check if last is ] fseek(fp, -1, SEEK_END); if (getc(fp) != ']') { fclose(fp); return 0; } // replace ] by , fseek(fp, -1, SEEK_END); if (!is_empty) fputc(',', fp); // append the document fputs(json, fp); // close the array fputc(']', fp); fclose(fp); return 1; } return 0; } int main(){ int i; for(i = 0; i &lt; 10000; i++){ char json[100] = &quot;&quot;; sprintf(json, &quot;{\&quot;a\&quot;:%d}&quot;, packet_count); write_json(json); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:48:59.327", "Id": "516217", "Score": "1", "body": "Why are you `printf`-ing your entire output?" } ]
[ { "body": "<p>A few thoughts:</p>\n<ol>\n<li>You first open the file for reading. If this succeeds, the next thing you do (without closing the file) is another fopen with a different mode. I am not sure what you are trying to accomplish by doing this, but it doesn't look like it makes sense.</li>\n<li>I <em>think</em> that you are trying to see whether the file exists, create it if it doesn't, and then open it so you can read and write. If I understand you correctly, then mode &quot;a+b&quot; opens the file for reading and writing. It appends if the file exists; it does not delete the contents. This should be sufficient.</li>\n<li>JSON is a text file. I am not sure why you are opening it in binary mode. I would expect to see &quot;a+&quot;</li>\n<li>I'm pretty sure there are working libraries to handle reading and writing JSON files from a C program...you might try searching for one</li>\n</ol>\n<p>I am out of time; if I have time tomorrow night I will try to see if I can refine this or add more thoughts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:04:51.930", "Id": "262634", "ParentId": "261585", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:27:01.537", "Id": "261585", "Score": "2", "Tags": [ "c" ], "Title": "Appending data to JSON file in C" }
261585
<p>The following code was written with the intent to be as <em>efficient</em> as possible, where efficiency includes speed of execution, memory usage, and lines of code, all in support of the primary design constraint that it can change the payload argument <em>buffer</em> in-place (from the calling function's perspective).</p> <p>In its current state:<br /> It does successfully change the buffer in place. This has been tested with a 20Kb text file, and removing all occurrences of up to 26 character values, all from the set of ASCII printable characters. There is no reason I can think of that prevents the sizes of these two arguments from being larger - I just have not run any that are larger.</p> <p>Because the function uses <code>strdup</code> to create a working buffer, speed of execution is affected. And, I am pretty sure it is more verbose than it probably could be in terms of lines of code, which also potentially could affect speed of execution. I believe there could be some positive effects from compiler optimizations.</p> <p>Recommendations for improvements in speed of execution, size of code and memory usage will be appreciated.</p> <h2>Code:</h2> <pre><code>//////////////////////////////////////////////////////////////////////////// // // Description: Removes all occurrences of characters contained // in 'remove buffer' from 'str' buffer. // // // Inputs char *str - buffer containing text to be modified // char * remove - buffer containing characters to be removed // // Outputs char *str - modified in place. // // returns void // // Example: char buffer[] = {&quot;some string with^ sev!eral ***ch###ar@ to&amp; remove\n&quot;}; // char s_rem[] = {&quot;^@&amp;*)(#!\n&quot;}; // remove_chars(buffer, s_rem); // //////////////////////////////////////////////////////////////////////////// void remove_chars(char *str, char *remove) { const char *o = remove;//original location keeper const char *oStr = str;//original location keeper int found = 0; char *dup = strdup(str); if(dup) { const char *oDup = dup; while(*str)//walk through string { while(*remove)//walk through unwanted list for each string char { if(*str == *remove)//compare characters, one-by-one { remove = o;//place unwanted list to beginning of array found = 1; break; } else { remove++; } } if(found) { str++;//skip unwanted character if found found = 0; } else { *dup = *str;// move both pointers if unwanted not found dup++; str++; } remove = o; } *dup = 0;//NULL terminate dup = oDup;//bring pointer to original location str = oStr;//bring pointer to original location strcpy(str, dup); //place updated string into original free(dup); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T19:16:52.127", "Id": "516251", "Score": "7", "body": "\"efficiency includes [...] lines of code\" -- really? What exactly do you mean with that? You could write most of your code in a single line, but that's nonsense in most contexts and so is optimizing LOC." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:29:37.793", "Id": "518347", "Score": "2", "body": "@uli - I tried to provide wording that would define the constraints without being overly restrictive. Perhaps I could have said _reasonable and straight forward reductions in_ ***size*** _of code, well shy of obfuscation_. But unlike some of the other programming areas on Stackoverflow, there must be a little room left for opinion and interpretation on Code Review" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:22:56.960", "Id": "518372", "Score": "1", "body": "\"`str` is changed and returned\", yet function returns void ;)" } ]
[ { "body": "<blockquote>\n<p>all in support of the primary design constraint that it can change the payload argument buffer in-place</p>\n</blockquote>\n<p>However, the current implementation is not in-place, it builds a string in temporary space and then copies that back over the input. From the point of view of the caller that is in-place, but it isn't <em>really</em> in-place. This algorithm could be totally in-place. That would mean that characters of the input are copied inside the input itself, to either a place before the current location or exactly at the current location (never to a location that's further along), neither of which is a problem (the characters that are modified are not needed again later in this function), so temporary working space is not necessary.</p>\n<blockquote>\n<pre><code> remove = o;//place unwanted list to beginning of array\n ...\n remove = o;\n</code></pre>\n</blockquote>\n<p>The first one is redundant, the position gets reset later anyway. Personally I would do it like the code below, to make this logic &quot;more local&quot; (vs spread out) and also more like &quot;not messing up values&quot; (vs &quot;making a mess and then cleaning it up&quot;):</p>\n<pre><code>char *remove_tmp = remove;\nwhile (*remove_tmp)\n{\n etc\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:16:17.883", "Id": "516233", "Score": "0", "body": "Suggested changes to moving the `remove` pointers are good, I will use that. But I do not follow what you are saying about `This algorithm could be totally in-place.`. Yes, this would be desirable, but can you please expound a little more on _how_ to do that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:23:11.517", "Id": "516236", "Score": "2", "body": "@ryyker well I'm not sure what to explain because you basically just do it. Nothing really needs to change in your implementation, you just take something out. This algorithm already has the property that it won't change data that it needs later, only data that it is already done with: the write pointer cannot overtake the read pointer (they can be the same, they start out the same, but them being the same is still OK)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:27:24.427", "Id": "516238", "Score": "0", "body": "The only nuance I'd add here is that after shrinking in-place, you should follow up with a `realloc`. The implementation is efficient enough to understand that for shrinks no copying needs to be done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:38:13.557", "Id": "516243", "Score": "4", "body": "@Reinderien I'm conflicted on that, as that also bars the function from being used on strings that weren't malloced (or calloced). It would be easy to return the new length though, that would make it convenient for the caller to realloc if it knows that's appropriate (and is potentially useful for other purposes of course)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:44:56.373", "Id": "516244", "Score": "0", "body": "yep, that's safer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:36:19.317", "Id": "261589", "ParentId": "261588", "Score": "6" } }, { "body": "<p>Your execution time is <span class=\"math-container\">\\$O(len(str)*len(remove))\\$</span> which is slow.</p>\n<p>Since you're restricting yourself to ASCII you can create a LUT like so</p>\n<pre><code>bool remove_lut[256]= {false};\nwhile(*remove) remove_lut[*((unsigned char*)remove++)] = true;\n</code></pre>\n<p>Then remove the entire section where you scan the input for all charges in remove. And replace <code>found</code> with <code>remove_lut[*((unsigned char*)str)] == true</code>.</p>\n<p>This should give you a speed up of a factor <span class=\"math-container\">\\$O(len(remove))\\$</span>.</p>\n<p>Also as was previously pointed out, your code is not really in-place... Typically you'd do something like:</p>\n<pre><code>unsigned char* in = str;\nunsigned char* out = str;\nwhile(*in){\n if(!remove_lut[*in]){\n *out = *in;\n out++;\n }\n in++;\n}\n*out = '\\0';\n</code></pre>\n<h3>Edit</h3>\n<p>So I called to memory this lovely question from SO about <a href=\"//stackoverflow.com/q/11227809\">why sorting and then processing is faster than just processing</a>. Branch prediction, or rather branch misprediction, can cost a significant amount of CPU time, especially if you're branching on input data.</p>\n<p>So I wrote a branchless version of my code above:</p>\n<pre><code>static void remove_chars(char *restrict str, const char *restrict remove)\n{\n signed char lut[256] = {0};\n for (; *remove; remove++)\n lut[(unsigned char)*remove] = -1;\n\n while(*str &amp;&amp; !lut[(unsigned char)*str]){\n str++;\n }\n\n const char *in = str;\n char *out = str;\n while (*in)\n {\n signed char mask = lut[(unsigned char)*in];\n // Bit-fiddling here because GCC refuses to omit a CMOV\n // which would likely be faster than this ugly hack. \n *out = (~mask &amp; (*in)) | (mask &amp; (*out));\n\n // This emits branching code unfortunately\n //*out = mask ? *out : *in;\n\n out += mask + 1;\n in++;\n }\n *out = *in;\n}\n</code></pre>\n<p>Note that this code will have much a more consistent runtime but the best case is slightly slower than the code up top. However the worst case time is much improved.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:10:43.930", "Id": "518445", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/126104/discussion-on-answer-by-emily-l-remove-all-unwanted-characters-from-a-string-bu)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T00:33:54.020", "Id": "518511", "Score": "0", "body": "I commented about this elsewhere, but this branchless version can actually go about twice as fast (thanks for actually testing it) if you just always store, and optimize the mask updates to avoid a latency bottleneck. See [my answer](https://codereview.stackexchange.com/questions/261588/remove-all-unwanted-characters-from-a-string-buffer-in-place/262677#262677) on this question. (commenting here for future readers.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:02:00.393", "Id": "518652", "Score": "0", "body": "_\"...because GCC refuses to omit a CMOV\"_ Did you mean _emit_? BTW, several parts of this post are novel to me. look up table, and methods to incorporate branchless among them. Also spurred lots of amazing side comments. Thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:17:12.013", "Id": "261591", "ParentId": "261588", "Score": "16" } }, { "body": "<s>\nAside from the other comments about \"for real actually in-place\", which are true, I think the biggest miss here is that you should be using [strpbrk][1] rather than doing your own scanning.\n</s>\n<p>This really depends on the expected number of bad characters in the string, and the size of the replacement table. If both are low, for large strings <code>strpbrk</code> can be fast. However, as the number of replacement characters increases, it is nowhere near as fast as Emily's LUT method. With this rudimentary testbed,</p>\n<pre><code>#include &lt;assert.h&gt;\n#include &lt;limits.h&gt;\n#include &lt;stdbool.h&gt;\n#include &lt;stddef.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;time.h&gt;\n\n\nstatic void remove_orig(char *restrict str, const char *restrict remove)\n{\n const char *o = remove;//original location keeper\n const char *oStr = str;//original location keeper\n int found = 0;\n char *dup = strdup(str);\n if (dup)\n {\n const char *oDup = dup;\n while(*str)//walk through string\n {\n while(*remove)//walk through unwanted list for each string char\n {\n if(*str == *remove)//compare characters, one-by-one\n {\n remove = o;//place unwanted list to beginning of array\n found = 1;\n break;\n }\n else\n {\n remove++;\n }\n }\n if(found)\n {\n str++;//skip unwanted character if found\n found = 0;\n }\n else\n {\n *dup = *str;// move both pointers if unwanted not found\n dup++;\n str++;\n }\n remove = o;\n }\n *dup = 0;//NULL terminate\n dup = oDup;//bring pointer to original location\n str = oStr;//bring pointer to original location\n strcpy(str, dup); //place updated string into original\n free(dup);\n }\n}\n\n\nstatic void remove_lut(char *restrict str, const char *restrict remove)\n{\n bool lut[256] = {false};\n for (; *remove; remove++)\n lut[*remove] = true;\n\n const char *in = str;\n char *out = str;\n while (*in)\n {\n if (!lut[*in])\n {\n *out = *in;\n out++;\n }\n in++;\n }\n *out = '\\0';\n}\n\n\nstatic void remove_branchless(char *restrict str, const char *restrict remove)\n{\n signed char lut[256] = {0};\n for (; *remove; remove++)\n lut[(unsigned char)*remove] = -1;\n\n while(*str &amp;&amp; !lut[(unsigned char)*str]){\n str++;\n }\n\n const char *in = str;\n char *out = str;\n while (*in)\n {\n signed char mask = lut[(unsigned char)*in];\n // Bit-fiddling here because GCC refuses to omit a CMOV\n // which would likely be faster than this ugly hack.\n *out = (~mask &amp; (*in)) | (mask &amp; (*out));\n\n // This emits branching code unfortunately\n //*out = mask ? *out : *in;\n\n out += mask + 1;\n in++;\n }\n *out = *in;\n}\n\n\nstatic void remove_strpbrk(char *restrict str, const char *restrict remove)\n{\n char *out = str;\n const char *bad_end = str;\n do\n {\n const char *good_start = bad_end,\n *good_end = strpbrk(good_start, remove);\n if (!good_end)\n {\n strcpy(out, good_start);\n return;\n }\n\n int n_good = good_end - good_start;\n if (out != good_start)\n memcpy(out, good_start, n_good);\n out += n_good;\n\n const char *bad_start = good_end;\n bad_end = bad_start + strspn(bad_start, remove);\n } while (bad_end);\n\n *out = '\\0';\n}\n\n\nstatic void remove_chux1(char *restrict str, const char *restrict remove)\n{\n // Form table of remove character flags\n unsigned char flags[UCHAR_MAX + 1] = { 0 };\n const unsigned char *uremove = (const unsigned char *) remove;\n while (*uremove) {\n flags[*uremove] = 1;\n uremove++;\n }\n\n const unsigned char *ustr = (const unsigned char *) str;\n unsigned char *target = ustr;\n while (*ustr) {\n if (flags[*ustr] == 0) {\n *target++ = *ustr;\n }\n ustr++;\n }\n *target = '\\0';\n}\n\n\nstatic void remove_chux2(char *restrict str, const char *restrict remove)\n{\n // Form table of remove character flags\n signed char flags[UCHAR_MAX + 1] = { 0 };\n const unsigned char *uremove = (const unsigned char *) remove;\n while (*uremove) {\n flags[*uremove] = -1;\n uremove++;\n }\n\n unsigned char *target = (unsigned char *) str;\n const unsigned char *ustr = target;\n do {\n *target = *ustr;\n target += 1 + flags[*ustr];\n } while (*ustr++);\n}\n\n\nstatic void remove_tspeight(char *restrict s, const char *restrict r)\n{\n char *d = s + strcspn(s, r); /* destination pointer - start at first removal */\n const char *p = d; /* source */\n\n while (*p) {\n p += strspn(p, r); /* skip to next non-removed char */\n size_t n = strcspn(p, r); /* count of characters to keep */\n memmove(d, p, n);\n d += n;\n p += n;\n }\n *d = *p; /* terminate the string */\n return s;\n}\n\n\nstatic void remove_pcordes(char *restrict str, const char *restrict remove)\n{\n static_assert(UCHAR_MAX &lt;= 65536, &quot;Huge CHAR_BITS would use too much stack space for our lookup table&quot;);\n unsigned char keep_lut[UCHAR_MAX+1]; // increment output pointer or not after storing this char\n // be careful to only index with unsigned char: on some implementations (including x86), char is signed and thus can be negative.\n memset(keep_lut, 1, sizeof(keep_lut));\n const unsigned char *uremove = (const unsigned char*)remove;\n do {\n keep_lut[*uremove] = 0;\n }while(*uremove++); // including terminating 0\n\n const unsigned char *uin = (const unsigned char*)str;\n while(keep_lut[*uin]){ // lut[0] = 0 catches end of string\n uin++;\n }\n // uin points at first char to *not* keep (or the terminating 0)\n // either way, doesn't need to be copied\n // and we can potentially avoid dirtying cache or page on end-of-string\n\n if (!*uin)\n return (char*)uin;\n\n char *out = (char*)uin; // overwrite the char to remove\n //++uin; // with the *next* char... by doing pre-increment in the loop\n unsigned char c;\n do\n { // clang / gcc: 7 uops branchless, should be only 6\n c = *++uin;\n //size_t inc = keep_lut[c]; // doing this after the store helps clang, hopefully doesn't hurt CPU that can do memory disambiguation to see that it's not a reload of the recent store.\n *out = c;\n out += keep_lut[c]; // non-kept characters get overwritten next iter.\n } while(c);\n\n //*out = *in; // done as part of the final iteration\n return out; // pointer to the terminating 0 (because lut[0] = 0).\n}\n\n\ntypedef void(*method_t)(char *restrict, const char *restrict);\nstatic const method_t methods[] =\n{\n remove_orig,\n remove_lut,\n remove_branchless,\n remove_strpbrk,\n remove_chux1,\n remove_chux2,\n remove_tspeight,\n remove_pcordes,\n};\nconst int n_methods = sizeof(methods)/sizeof(*methods);\nstatic const char *names[] = {\n &quot;orig&quot;, &quot;lut&quot;, &quot;branchless&quot;, &quot;strpbrk&quot;, &quot;chux1&quot;, &quot;chux2&quot;, &quot;tspeight&quot;, &quot;pcordes&quot;,\n};\n\nstatic void test()\n{\n for (int i = 0; i &lt; n_methods; i++)\n {\n printf(&quot;Testing %s\\n&quot;, names[i]);\n\n char in1[] = &quot;abcdef&quot;;\n methods[i](in1, &quot;dba&quot;);\n assert(!strcmp(in1, &quot;cef&quot;));\n\n char in2[] = &quot;abcdef&quot;;\n methods[i](in2, &quot;abc&quot;);\n assert(!strcmp(in2, &quot;def&quot;));\n\n char in3[] = &quot;abcdef&quot;;\n methods[i](in3, &quot;def&quot;);\n assert(!strcmp(in3, &quot;abc&quot;));\n }\n}\n\n\nstatic void compare(int percent_bad, int to_remove)\n{\n printf(&quot;\\nInitializing comparison for %d%% bad chars, %d to remove...\\n&quot;, percent_bad, to_remove);\n const size_t n = 1048576;\n char *orig_input = malloc(n + 1), *input = malloc(n + 1), *bad_chars = malloc(to_remove + 1);\n assert(orig_input);\n assert(input);\n assert(bad_chars);\n\n for (size_t i = 0; i &lt; to_remove; i++)\n bad_chars[i] = ' ' + i;\n bad_chars[to_remove] = '\\0';\n\n const char first_good = ' ' + to_remove;\n\n for (size_t i = 0; i &lt; n; i++)\n {\n if (rand() % 100 &lt; percent_bad)\n orig_input[i] = bad_chars[rand() % to_remove];\n else\n orig_input[i] = first_good + rand() % 16;\n }\n orig_input[n] = '\\0';\n\n for (int m = 0; m &lt; n_methods; m++)\n {\n double total_s = 0;\n const int n_reps = 100;\n for (int i = 0; i &lt; n_reps; i++)\n {\n memcpy(input, orig_input, n);\n struct timespec start, end;\n assert(!clock_gettime(CLOCK_MONOTONIC, &amp;start));\n methods[m](input, bad_chars);\n assert(!clock_gettime(CLOCK_MONOTONIC, &amp;end));\n total_s += end.tv_sec - start.tv_sec\n + 1e-9*(end.tv_nsec - start.tv_nsec);\n }\n printf(&quot;%10s %.1lf ms\\n&quot;, names[m], total_s/n_reps * 1e3);\n }\n\n free(orig_input);\n free(input);\n}\n\n\nint main()\n{\n test();\n srand(0);\n compare(1, 4);\n compare(80, 4);\n compare(1, 32);\n compare(80, 32);\n return 0;\n}\n</code></pre>\n<p>in this environment (I'm too lazy to install clang):</p>\n<ul>\n<li>Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz</li>\n<li>Linux manjaro 5.4.118-1-MANJARO #1 SMP PREEMPT Tue May 11 17:46:18 UTC 2021 x86_64 GNU/Linux</li>\n<li><code>gcc -O3 -march=native --std=c18 -Wall -s -D_GNU_SOURCE</code></li>\n</ul>\n<pre><code>Initializing comparison for 1% bad chars, 4 to remove...\n orig 4.7 ms\n lut 0.8 ms\nbranchless 1.0 ms\n strpbrk 0.4 ms\n chux1 0.8 ms\n chux2 0.7 ms\n tspeight 0.4 ms\n pcordes 0.7 ms\n\nInitializing comparison for 80% bad chars, 4 to remove...\n orig 8.2 ms\n lut 2.7 ms\nbranchless 1.2 ms\n strpbrk 3.2 ms\n chux1 2.6 ms\n chux2 0.7 ms\n tspeight 3.3 ms\n pcordes 0.6 ms\n\nInitializing comparison for 1% bad chars, 32 to remove...\n orig 25.5 ms\n lut 0.8 ms\nbranchless 1.0 ms\n strpbrk 1.1 ms\n chux1 0.8 ms\n chux2 0.8 ms\n tspeight 1.1 ms\n pcordes 0.6 ms\n\nInitializing comparison for 80% bad chars, 32 to remove...\n orig 20.2 ms\n lut 3.0 ms\nbranchless 1.2 ms\n strpbrk 11.1 ms\n chux1 2.5 ms\n chux2 0.7 ms\n tspeight 11.3 ms\n pcordes 0.6 ms\n</code></pre>\n<p>So for the purposes of this question, it's good to think about the existence of <code>strpbrk</code> / <code>strspn</code> but know why not to use them - basically the reasons that @PeterCordes has enumerated in the comments. The differences are exacerbated to varying degrees based on the density of bad characters in the text, as demonstrated above.</p>\n<p>For some incidental review coverage,</p>\n<ul>\n<li>Use <code>const</code> for the second argument</li>\n<li>Use <code>restrict</code> for both</li>\n<li>Mark your translation-unit-local methods <code>static</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:27:34.427", "Id": "518331", "Score": "1", "body": "Comments are not for extended discussion; the conversation has been [moved to chat](https://chat.stackexchange.com/rooms/126076/discussion-on-answer-by-reinderien-remove-all-unwanted-characters-from-a-string)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T20:39:45.430", "Id": "518404", "Score": "0", "body": "Specifically, see comments for some details on how glibc `strpbrk` / `strcspn` works (in asm for a few ISAs, but unfortunately not SIMD except on POWER8), and some SIMD ideas that could be worth it for large strings (where more time to build the accept/reject set is worth it). Or for special cases like a small-enough accept/reject set with x86 SSE4.2 string instructions, either 16 chars or less, or 8 ranges or less." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T00:49:19.697", "Id": "518423", "Score": "0", "body": "Interesting results, I expected my code to be faster but not by that big of a margin when bad characters was so small. Out of curiosity would you be willing to include a few data points with larger and smaller bad word strings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T01:19:41.140", "Id": "518424", "Score": "0", "body": "@EmilyL. Sure; done! Commentary in chat." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T12:40:59.027", "Id": "518451", "Score": "2", "body": "I posted [an answer](https://codereview.stackexchange.com/questions/261588/remove-all-unwanted-characters-from-a-string-buffer-in-place/262677#262677) with a more efficient branchless version of @EmilyL.'s branchless code. If you're interested in throwing that into the mix, if compiled with clang it should run about 1.5 cycles per input byte on Intel Sandybridge-family (e.g. Haswell / Skylake), similar on Zen1, and maybe a bit faster on Zen2 or Ice Lake. GCC wastes an instruction, so 1.75 cycles per input byte (front-end bottleneck). I didn't test it, only looked at the asm on Godbolt." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T21:04:01.560", "Id": "518500", "Score": "1", "body": "For posterity can you mention the environment in which you are running" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:23:44.823", "Id": "261592", "ParentId": "261588", "Score": "7" } }, { "body": "<h1>Error Handling</h1>\n<p>If <code>strdup()</code> fails, your function fails but it doesn't signal failure in any way. To me, that's a complete no-go, because that means that you can't guarantee anything! In this case, the way to fix it is of course to modify the buffer in-place, as others suggested.</p>\n<h1>Flow Control</h1>\n<p>There is a section</p>\n<pre><code>void remove_chars(char *str, char *remove)\n{\n ...\n if (...) {\n // many lines of code\n }\n}\n</code></pre>\n<p>Returning early would make the code easier to understand, you don't have to skip down to see nothing happens if the condition is not met. Also, you don't need to indent the code in between giving you more space. This won't change the speed of your code. However, keeping things easy to understand is helpful when optimizing code without accidentally breaking it.</p>\n<h1>Unnecessarily Large Scope</h1>\n<p>Check out <code>found</code>, which is only ever used once per iteration of the outer loop. It could be declared and initialized there instead. You could then avoid the redundant reset of the variable to its initial value, overall making the code easier to understand. It might even make it faster, though this is so simple that any better compiler will figure that out itself.</p>\n<h1>Const</h1>\n<p>The second buffer isn't modified, right? So do make it <code>char const*</code> instead! This doesn't make the code faster, but makes it easier to get right when the compiler catches accidental modifications.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:13:07.597", "Id": "518368", "Score": "0", "body": "Good and straight forward points all around. It appears you're in good company with some of them. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T19:35:02.207", "Id": "261594", "ParentId": "261588", "Score": "5" } }, { "body": "<h1>Include the correct headers</h1>\n<p>We're missing <code>&lt;string.h&gt;</code> for <code>strcpy()</code>. We're also missing <code>&lt;stlib.h&gt;</code> for <code>free()</code> (but see below).</p>\n<h1>Don't ignore compiler warnings</h1>\n<p>Ensure you have every reasonable warning enabled, and pay attention to what your compiler tells you. For example:</p>\n<blockquote>\n<pre><code>void remove_chars(char *str, char *remove)\n{\n const char *oStr = str;\n …\n str = oStr;\n}\n</code></pre>\n</blockquote>\n<p>You probably intended to write</p>\n<pre><code> char *const oStr = str;\n</code></pre>\n<h1>Stick to standard library functions</h1>\n<p>Unless you're writing code that only makes sense on POSIX platforms, don't use functions such as <code>strdup()</code> that are not portable Standard C.</p>\n<h1>Improve the interface</h1>\n<p>We have no reason to modify the contents of <code>remove</code>, so pass it as a <code>const char*</code>. And make life easier for the caller by returning the modified string, to enable more chaining of functions.</p>\n<h1>Modify the string in-place</h1>\n<p>Allocation functions such as <code>strdup()</code> can fail (and when that happens, we should report the failure, rather than surprising the user by doing nothing).</p>\n<p>We don't need to allocate memory, and can write a function that always succeeds. That reduces the amount of error-handling required, eliminates the need for <code>&lt;stdlib.h&gt;</code>, and gives a significant speed boost: the allocation is the most time-consuming part of the function.</p>\n<h1>Use library functions</h1>\n<p>Instead of looping over <code>remove</code> manually, we could use <code>strchr()</code> to determine whether it contains a given character. Better yet, we can use <code>strcspn()</code> to find the next character to remove.</p>\n<hr />\n<h1>Modified function</h1>\n<pre><code>#include &lt;string.h&gt;\n\n// Removes from S all occurrences of characters contained in R\n// Returns S after modification\nchar *remove_chars(char *const s, const char *const r)\n{\n char *d = s + strcspn(s, r); /* destination pointer - start at first removal */\n const char *p = d; /* source */\n\n while (*p) {\n p += strspn(p, r); /* skip to next non-removed char */\n size_t n = strcspn(p, r); /* count of characters to keep */\n memmove(d, p, n);\n d += n;\n p += n;\n }\n *d = *p; /* terminate the string */\n return s;\n}\n</code></pre>\n<p>Demo:</p>\n<pre><code>#include &lt;stdio.h&gt;\nint main(void)\n{\n char s[] = &quot;Code Review Stack Exchange&quot;;\n const char *vowels = &quot;AEIOUaeiou&quot;;\n printf(&quot;%s\\n&quot;, remove_chars(s, vowels));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:14:33.807", "Id": "518343", "Score": "0", "body": "Several excellent points, in particular those under_Modify the string in-place_. Very straight forward implementation. I will test/benchmark and comment. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T10:58:45.870", "Id": "518444", "Score": "1", "body": "I wouldn't return the modified string; I'd return a pointer to the new 0 terminator in the string (or the new length): that's information the caller might have to recalculate if you threw it away. Don't repeat [the design mistakes](https://stackoverflow.com/a/51547604/224132) of C standard library functions like `strcpy` / `strcat`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T08:12:58.613", "Id": "262610", "ParentId": "261588", "Score": "5" } }, { "body": "<p><strong>Use <code>const</code> and <code>restrict</code></strong></p>\n<p>For linear improvements, <code>restrict</code> allows select optimizations as code can assume the two strings do not overlap.</p>\n<pre><code>// void remove_chars(char *str, char *remove)\nvoid remove_chars(char * restrict str, const char * restrict remove)\n</code></pre>\n<p><code>const</code> allows <code>remove_chars()</code> to be called with a <code>const</code> remove string.</p>\n<hr />\n<p><strong>Assuming ASCII makes for brittle code</strong></p>\n<p>Rather than assume ASCII (0-127), allow full range <code>char</code>.</p>\n<p>As <code>char</code> may be signed, fold characters to the <code>unsigned char</code> range.</p>\n<hr />\n<p><strong>Avoid multiple trips down each string</strong></p>\n<p>Once each is enough.</p>\n<hr />\n<p><strong>Avoid O(<code>strlen(str)*strlen(remove)</code>) runtime</strong></p>\n<p>Instead O(<code>strlen(str)+strlen(remove)</code>) runtime.</p>\n<hr />\n<p>Sample code</p>\n<pre><code>void remove_chars(char * restrict str, const char * restrict remove) {\n // Form table of remove character flags\n unsigned char flags[UCHAR_MAX + 1] = { 0 };\n const unsigned char *uremove = (const unsigned char *) remove;\n while (*uremove) {\n flags[*uremove] = 1;\n uremove++; \n }\n\n const unsigned char *ustr = (const unsigned char *) str;\n unsigned char *target = ustr;\n while (*ustr) { \n if (flags[*ustr] == 0) {\n *target++ = *ustr;\n }\n ustr++;\n }\n *target = '\\0';\n}\n</code></pre>\n<p>Note: Given internal remove table, <code>restrict</code> no longer needed.</p>\n<p><strong>Return value</strong></p>\n<p>Not a real performance issue, yet consider returning something useful. Easy to implement ideas include:</p>\n<ul>\n<li><p><code>char *remove_chars()</code> and return the original <code>src</code>. This mimics many <code>str...()</code>.</p>\n</li>\n<li><p><code>char *remove_chars()</code> and return the pointer to the <em>null character</em>. Useful to 1) know the length with a subtraction 2) know were to append in various <em>string</em> processing without another <code>strlen()</code>.</p>\n</li>\n<li><p><code>size_t remove_chars()</code> and return the string length.</p>\n</li>\n<li><p><code>bool remove_chars()</code> and return length changed indication.</p>\n</li>\n</ul>\n<hr />\n<p><strong>Too much fun</strong></p>\n<p>Another idea: The replacement loop can be simplified to one that always copies the the character. It is just if the destination pointer is incremented.</p>\n<pre><code>void remove_chars(char * restrict str, const char * restrict remove) {\n // Form table of remove character flags\n signed char flags[UCHAR_MAX + 1] = { 0 };\n const unsigned char *uremove = (const unsigned char *) remove;\n while (*uremove) {\n flags[*uremove] = -1;\n uremove++;\n }\n\n unsigned char *target = (unsigned char *) str;\n const unsigned char *ustr = target;\n do {\n *target = *ustr;\n target += 1 + flags[*ustr];\n } while (*ustr++);\n}\n\nint main() {\n char str[100] = &quot;Hello World&quot;;\n remove_chars(str, &quot; &quot;);\n printf(&quot;&lt;%s&gt;\\n&quot;, str); // &lt;HelloWorld&gt;\n remove_chars(str, &quot;dH&quot;);\n printf(&quot;&lt;%s&gt;\\n&quot;, str); // &lt;elloWorl&gt;\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:31:58.300", "Id": "518332", "Score": "1", "body": "Wow, I'm going to enjoy dissecting this code for understanding. With this implementation (reduced complexity) et.al it appears to be a Ferrari in C. Several subtleties offered here that I don't yet understand, but will look them up before asking. I'll comment again after some research and benchmark tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:24:29.797", "Id": "518345", "Score": "1", "body": "I have a question concerning this implementation: Why do you convert the pointers (`char*` to `unsigned char*`) instead of converting the elements? Pointer casts usually have a smell to them, which I'd prefer to avoid. For the first loop, I would have used `flags[(unsigned char)*remove] = 1;` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:47:50.627", "Id": "518386", "Score": "0", "body": "I think it's only the description that assumes ASCII - the program itself appears completely encoding-agnostic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T18:01:07.850", "Id": "518391", "Score": "0", "body": "@TobySpeight OP's testing was self-described as \"all from the set of ASCII printable characters\" and so conveyed that emphasis. True that OP's code is fairly encoding-agnostic (aside from archaic non-2's complement oops with `while(*str)` mis-handling -0)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T19:26:27.543", "Id": "518398", "Score": "2", "body": "@uli The standard library string functions have \"For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value).\" So I do likewise. Your suggestion differs from this answer concerning the soon to be gone (C2x) non-2's compliment encoding as `(unsigned char)*remove` incorrectly treats -0 as a _null character_." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:39:00.300", "Id": "262619", "ParentId": "261588", "Score": "5" } }, { "body": "<p><strong><code>return</code> something useful that you already calculate</strong>, in case the caller has a use for it. In this case, return a pointer to the new 0 terminator in the string (or the new length): that's information the caller might have to recalculate if you threw it away. Don't repeat <a href=\"https://stackoverflow.com/a/51547604/224132\">the design mistakes</a> of C standard library functions like <code>strcpy</code> / <code>strcat</code>.</p>\n<hr />\n<h3>Branchless in-place filtering, about 2x speedup over Emily's version</h3>\n<p>In-place filtering should actually be in-place: don't copy any characters that don't need to move, and don't write at all if there are no characters in the <code>remove</code> set present. Besides the obvious saving in work, this avoids dirtying any cache lines that don't need to change. (And potentially setting the &quot;dirty&quot; bit on a whole page, or even saving a copy-on-write, e.g. on a <code>mmap(MAP_PRIVATE)</code> mapping of a file, or even causing I/O on a <code>MAP_SHARED</code> in-place modification of a file mapping, if the first 4k for example don't contain any chars to remove.)</p>\n<p>But once you do need to write (to copy later characters over into place, to fill the gap from characters you're omitting), <strong>you can actually do less work by unconditionally storing,</strong> and just incrementing the destination pointer or not. (By adding a 0 or 1 from a lookup table). (Emily's version is branchless, but does quite a bit of work to select which character to store back. But that doesn't matter; we're going to eventually overwrite it, with the terminating <code>0</code> if we won't find another keeper character first.)</p>\n<p>This version compiles to 6 µops in the inner loop (on a modern x86-64) with clang 12 <code>-O3</code>, so should run at about 1.5 cycles per char for large strings (after building the LUT) on a CPU like Skylake. It's branchless other than the loop-exit condition, so it shouldn't suffer from mispredicts when encountering a random mix of keep / remove characters. Or 7 µops with GCC because it wastes an instruction. (At least I got it not to load twice: I found and reported <a href=\"https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100922\" rel=\"nofollow noreferrer\">GCC bug #100922</a> while working on this.)</p>\n<p>Repeated stores to the same address is something that CPUs can absorb pretty handily. <a href=\"http://(https://stackoverflow.com/questions/54217528/are-there-any-modern-cpus-where-a-cached-byte-store-is-actually-slower-than-a-wo)\" rel=\"nofollow noreferrer\">Modern x86 has fully efficient byte stores</a>, and microarchitectures that don't (for other ISAs) often can do merging in the store buffer to coalesce multiple stores into the same word into one full-word commit to L1d cache. It's likely that store coalescing hardware can handle overlaps efficiently.</p>\n<p>Building a lookup table is the same idea that glibc <code>strcspn</code> / <code>strspn</code> use internally.</p>\n<p>(I used @Emily's code as a starting point, but independently had the idea of making it branchless. Aggressive use of <code>unsigned char</code> was already my choice from looking at the asm, and @chux's answer <a href=\"https://codereview.stackexchange.com/questions/261588/remove-all-unwanted-characters-from-a-string-buffer-in-place/#comment518391_262619\">and comments</a> point out that it's actually <em>better</em> (more portable) to read <code>char</code> data through an <code>unsigned char*</code>, avoiding the possibility of a DeathStation 9000 where <code>while(*ptr++)</code> can be false for a non-2's-complement <code>-0</code> if <code>char</code> is a signed type.)</p>\n<p>I'm not sure I like <code>unsigned char *uin</code> as a variable name (unsigned input). I probably should have called it <code>ustr</code>.</p>\n<pre><code>#include &lt;stddef.h&gt;\n#include &lt;string.h&gt;\n#include &lt;limits.h&gt;\n#include &lt;assert.h&gt;\n\n// returns a pointer to the (new) terminating zero in str\nchar *remove_chars_unconditional_write(char *restrict str, const char *restrict remove)\n{\n static_assert(UCHAR_MAX &lt;= 65536, &quot;Huge CHAR_BITS would use too much stack space for our lookup table&quot;);\n unsigned char keep_lut[UCHAR_MAX+1]; // increment output pointer or not after storing this char\n // be careful to only index with unsigned char: on some implementations (including x86), char is signed and thus can be negative.\n memset(keep_lut, 1, sizeof(keep_lut));\n const unsigned char *uremove = (const unsigned char*)remove;\n do {\n keep_lut[*uremove] = 0;\n }while(*uremove++); // including terminating 0\n\n const unsigned char *uin = (const unsigned char*)str;\n while(keep_lut[*uin]){ // lut[0] = 0 catches end of string\n uin++;\n }\n // uin points at first char to *not* keep (or the terminating 0)\n // either way, doesn't need to be copied\n // and we can potentially avoid dirtying cache or page on end-of-string\n\n if (!*uin)\n return (char*)uin;\n\n char *out = (char*)uin; // overwrite the char to remove\n //++uin; // with the *next* char... by doing pre-increment in the loop\n unsigned char c;\n do\n { // clang / gcc: 7 uops branchless, should be only 6\n c = *++uin;\n //size_t inc = keep_lut[c]; // doing this after the store helps clang, hopefully doesn't hurt CPU that can do memory disambiguation to see that it's not a reload of the recent store.\n *out = c;\n out += keep_lut[c]; // non-kept characters get overwritten next iter.\n } while(c);\n\n //*out = *in; // done as part of the final iteration\n return out; // pointer to the terminating 0 (because lut[0] = 0).\n}\n</code></pre>\n<p>(My code often ends up littered with performance-tuning alternatives and notes on compiler output. That's probably not something you want in your actual final code long-term. I left it in because how it compiles now, with current compiler versions, is relevant for performance comparisons with other answers.)</p>\n<p>The final loop <a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlJvoCqAZ0wAFAB4gA5AAYppAFZdSrZrVAB9LclIj2yAnjqVMtdAGFUrAK4BbWiACcpU%2BgAyeWpgBydgEaYxCAAzABMpAAOqEKERrSWNvZOkdGxdB5evrYBQWG6mPqGdAwEzMQECXYOznqYBnElZQQZPv6BIeFCpeWVSTXdzZ6t2e1hAJS6qNbEyBxSAPTzAKShwZ7INlgA1EvB5l3oWFQAdAi72EsyAIIra7Qb1tu7%2BwTEnsCn55c3q%2BubmDs9qw8LZCEJPsELtdbn9HgDnswhCJyhDsFstostjRiFsusxDMgNIjkQRvt9McRMARprQhFtmFsop4CIEtkQ2QgARAvAB3MZswKg2j495bABegVQW08uNe32QCDKWwAVJTbKgAG6YDQKspCDTWe50fBFYWsDQ8t4siC6nGqzBdN4GWVkLZoWkEN2Ku2Ux14Z1qzWYMZkgDsACFvuj0XiCUSkYECBABOYABJXABKGgAslcABqA8y7AAiWwAbABWCvBMukHahUKp6zAAFpzMacMASQAKgwtjypqx0FtrCI2agpbZrArZcxkABrXEROcA7FbKY41gT%2BfWCJs5h%2BdgrUIh4KR67Rke0vDALzD21beeYTARDQ2UkV8Mp9NZ3N5lbhpwSwVsWuzhpe0aYusaqmJ6UwEBE1ieky9CsiQWy0KgnrMFQLI4l0JCigQCB4HStpRpB8xbAEbplJgVDWKw47rrQrAAJ7SmYmDiP2hAIFeMS3pg97eiALG4qgtgAiCETsFJ9AinQdIQLC%2BDqFs4gABxlhMXpKqRuI3ne9JmByo60bQ1EAl4wAilqxwUeiUm2CISZPi%2Bb5IXWnB1jEEqoFQEDua%2B75jKe55XJe7pdAJRnCXpdrTJg6paoCpY2kpnqGoJxm2sqYyBlqYGOVs6BSksEYlZewWeR%2B4bKklKWYMBpYllsMjFRe0YVcWPIkewEANYVzWhJGo3hRBl5QfcmxEYKngiupHVdSV0VZdeQkiUqDUym1GUerFm0JfljqdZF0Z9XgA01e%2BwH1dYngtSGEbopit2fh1IFpe1tEEAqDpbK465UC67xVdGD20AB0NniVPUlZikOMqgzJ0viWJ4MQMUPuyyqYQQyqPs%2Be4QOhxEAnhQqLcA7Uhl1r1UZgfGsjyzBsXWZUOrQYBSJ6XjxeyNFoBEeDCQjVFqMOPIAiwllRCy9B4Gw7H0hqKPDvg5RsaKLD/euOLLi24muAAtAFJt%2BuoFElXgIMQGAYA7bQdPnZNlLUsQlk2t6%2BWQ2d6Krd6Krwd93tlL7j1ngz65asQlqEBTnIJcxw3i9Do1%2B1Hk0QZiPJ8RyAJ49xBMJccZfURxZWihElIm9ByWwZxBdbFuqARCV2VxVtOLIP70ZlTslX0xByDfcq6fhpnEXZxi8x%2BdqnrrN9N1IXdvcgWBOdUVX6nEQZOF4c3BGUlsnKsBEZGqOodYIG39GMSrnNCNzvOn9MnrmKIAgcujsulZOyUSCV1IswbIN5rCKUsuyEQid0aEB5nSfG9ItiUi3MwYcAVm6UlmPQWUJBMAOWHpeZUIc2q91hkQ6MpDRptRXnVdeoEs6YkwrQE2T4IieltHOPCdIWxwVjvHAgCsMLF2lHhQhrtB6lkugNZA4VxYkKQmPSO4FZ7/y8PSOky5yjA2blQBaTEE7EEgSVd2NJ1yryYVRFCh92TkwFMQKmhglroggO9cMn1WrBFLDIMYEj4bXCkBMVg0gKzyAcLIeQqBpDmAktMWY9ZgicHkAQaQcgwqkHnCEUMxxOCVmCBWbgwRggyFDDIbStYQlSG4OEtJUTpDyCECAGQpBUmRImHAWASA0C2BFuwMgFAMq9Kuu0ZAGw1DAE4KEGQLT9GsB4ZQPwdTSB%2BAWsQNi0hkmkB6fJAgAB5ViGzImkCwLYCZ7BlmazqIYLUTTjncTqEhOYWzmQFGWcCPwxj1mWCwJslJbxbB/ImPwRgLALk8D4HQAgwgxCSGOUoHyV9NDaBUHgPwTTIATDbqaO5Js9mhC2BbAg6ASy3msJwTghKzkzDON4oQ842KqCfCbZgGpxAVimYSgA6srRpBRrlxBMGYXoDgfKuBaFkHIygogxFNCK6VqRTQSraEEHytR6jFAGPKtV/KNW0EaOUZVIxVW6C1VYKoyg8SGqGJK9onAJhCA3LMLgwTQm1OOdEqQWkywmzLNwN0SKthTOODIENWwIC4EIOhW4PktiWGGf0xJ9q40pLqRkrJoRHDHArDITgSTVgFMcBWTSuaVDSBqaQCJchSCesac01pabSCdMQCgSSfTAjkEoD09tQQWCOL9cAV4hp5x8CugsiASzjmrOFOsv52zJK7IOexS5yVzlzGrVc%2BotzlkPOQE8udryqnVo%2BV8tiPznn/JBECyF9AmBsA4BCkFMKJDLKUOEJFIAtA6lRei%2BAWKOFxFxXs4IhKDiktoOSylJseWsFYHywogqICuG1S4MwRqpU%2BRlWkeI5qkiYcVXEdDdr8gIc1U0FD6rTQGsGJkFVlqzWJFFaapoRHVUOqdQ%2B11UgwmVuWZ6zM2Y/VbGAGMtkxBh3hsjUQHEMa6zxp7Ykk8KaG3tImFk4pxxilae0zpst1T3XVtrboetbT0lcdCAZ%2BpUhU2qdILHGIxhuBAA%3D%3D\" rel=\"nofollow noreferrer\">compiles like this (Godbolt)</a> with clang 12 <code>-O2 -march=haswell</code>, also shown compiling nicely for AArch64.</p>\n<pre><code>.LBB0_4: #\n movzx ecx, byte ptr [rdi] # zero-extending byte load from input string\n mov byte ptr [rax], cl # store it to the output position\n movzx edx, byte ptr [rsp + rcx] # index the LUT with it\n add rax, rdx # add the LUT result to the output pointer\n inc rdi # unconditionally increment the input pointer\n test rcx, rcx\n jne .LBB0_4 # }while( (uint64_t)c != 0 );\n ...\n ret # with char *out in RAX\n</code></pre>\n<p>With fusion of the test+jne, that's 6 uops for the front-end. Skylake is 4-wide, Zen is 5 instructions / 6 uops wide, whichever is narrower. IceLake is 5-wide. So we're not quite achieving 1 character per cycle even on the widest x86 cores (although the back-end could keep up with that: 2 loads + 1 store per clock on Haswell and later, and on Zen2 and later.)</p>\n<p>(For very sparse occurrences of remove characters, read-only scan and memcpy can save enough front-end bandwidth to be worth it, actually hitting 2 loads per clock to check 1 char per clock. <code>strpbrk</code> / <code>memcpy</code> loops can achieve that, at the cost of rebuilding the LUT on every call to <code>strpbrk</code>. <code>memcpy</code> internally uses wide 16 or 32-byte copies. <a href=\"https://code.woboq.org/userspace/glibc/sysdeps/x86_64/strcspn.S.html#77\" rel=\"nofollow noreferrer\">glibc's x86-64 asm <code>strpbrk</code></a> just uses scalar code, but with some loop unrolling.)</p>\n<p>Using a <code>size_t keep_lut[UCHAR_MAX+1]</code> would allow a memory-source add (which can <a href=\"https://stackoverflow.com/questions/26046634/micro-fusion-and-addressing-modes\">remain as a single uop even with an indexed addressing mode on Haswell and later</a>, and AMD), instead of movzx/add, but would require zeroing 8x 256 = 2kiB of memory, and pollute that much more L1d cache.</p>\n<hr />\n<h3>SIMD</h3>\n<p>If you wanted to make a version specifically for x86-64 with SSE4.2 string instructions, you could check for <code>remove</code> being either &lt;= 16 bytes, or for being expressible as up to 8 ranges. Then you can find how many contiguous keep characters there are, 16 bytes at a time. <a href=\"https://www.strchr.com/strcmp_and_strlen_using_sse_4.2\" rel=\"nofollow noreferrer\">https://www.strchr.com/strcmp_and_strlen_using_sse_4.2</a> explains the match-any and ranges functionality, and aggregation, of <code>_mm_cmpistrz</code> (asm <code>pcmpistri</code>). That gives you the <em>index</em> of the first match / non-match, so you can do a vector store and increment your output pointer by that much. (Assuming the read pointer is far enough ahead of your write pointer if you're not just storing single bytes. So probably you want to read the next input vector <em>before</em> storing this one.)</p>\n<p>(Or even better, <a href=\"https://stackoverflow.com/a/54585515/224132\">only 1 range</a> or even a single character can be done with SSE2 or AXV2.)</p>\n<p>With a really high removal percentage, you might switch strategy to looking for contiguous remove characters.</p>\n<p>AVX512VBMI2 (Ice Lake) has <a href=\"https://github.com/HJLebbink/asm-dude/wiki/VPCOMPRESS\" rel=\"nofollow noreferrer\"><code>vpcompressb</code></a> which is a byte shuffle that left-packs a vector according to a compare mask. So if you can get any kind of SIMD compare to detect accept vs. reject, you could use it to do all the work of filtering a whole vector of 16, 32, or 64 chars at once. In only 2 uops. (Or 6 or 8 for a masked store to memory).</p>\n<p>For the more general case of <code>strcspn</code>, I commented (<a href=\"https://chat.stackexchange.com/rooms/126076/discussion-on-answer-by-reinderien-remove-all-unwanted-characters-from-a-string\">moved to chat</a>) with some ideas about what one might be able to do with SIMD. (And what glibc's <code>strcspn</code> actually does do, including POWER8 <a href=\"https://code.woboq.org/userspace/glibc/sysdeps/powerpc/powerpc64/power8/strspn.S.html#20\" rel=\"nofollow noreferrer\">where it can make a 256-bit bitmap</a> in a vector, instead of byte array, because vector instructions are useful for selecting a bit from a 256-bit vector. But on x86-64 it's just building and using a LUT with unrolled scalar loops, so building the LUT once yourself and amortizing that over multiple spans for keep characters is a big win.)</p>\n<p>I also found a C-with-Intel-intrinsics implementation of some C standard string algorithms using SIMD, getting a speedup for large strings for <code>strcspn</code> by brute-force looping SSE4.2 <code>_mm_cmpistri</code> over the LUT checking 16 bytes at a time for any matches.<br />\n<a href=\"https://github.com/novemberizing/eva/blob/main/docs/extension/string/README.md\" rel=\"nofollow noreferrer\">https://github.com/novemberizing/eva/blob/main/docs/extension/string/README.md</a>\nThat could probably be adapted for this, and might do well if the distance between remove elements is long enough.</p>\n<p>Actually developing a SIMD version is outside the scope of this code review; ask on Stack Overflow if you get stuck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T15:52:03.593", "Id": "518465", "Score": "1", "body": "Interesting, did you benchmark the code? I would be interested in the results, I entertained the idea of a keep-lut but didn't try it because of time (it was 4 AM for me) and that I feared the memcpy would be too expensive as overhead for short inputs. I like the use of zero terminator in the LUT to elide the check for the string end from the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T21:19:40.820", "Id": "518501", "Score": "0", "body": "@EmilyL.: setting to 1 instead of 0 gets compilers to load a vector constant from `.rodata` instead of `pxor xmm0,xmm0`, but other than that the array init and loop are basically identical. (In hand-written asm, I would have used `pcmpeqd xmm0,xmm0` / SSSE3 `pabsb xmm0,xmm0` to make a vector of all-ones, or maybe `rep stosq`, but it's very hard (with intrinsics) to get compilers to not do constant propagation and thus not load a constant from memory). I haven't benchmarked it, just looked at the main loop to predict performance based on the front-end bottleneck and lack of other bottlenecks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:03:51.070", "Id": "518502", "Score": "1", "body": "I ran the benchmark by Reinderein with your version and it's about twice the speed of my hacky bit-fiddle version and extremely consistent (as expected). Interestingly it still loses out to strpbrk when the bad chars rate is low and bad chars count is low, which I guess is due to the large number of unconditional store instructions, or maybe there's some SIMD magic happening. Or up to 40x improvement under the test conditions over OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:08:33.897", "Id": "518503", "Score": "0", "body": "@EmilyL.: possibly just to strpbrk's loop unrolling, which you don't get in compiler-generated code. Or to the front-end throughput bottleneck of doing a store and load+add, instead of just a search and then doing the copying with a high-performance SIMD memcpy. glibc `strpbrk` just builds a LUT and uses it with pure scalar code. (https://code.woboq.org/userspace/glibc/sysdeps/x86_64/strcspn.S.html#77). Note that it should probably be using `movzbl` loads: the `movb` loads merging into the low byte of RCX were copied from the IA32 version, which made sense for P5 Pentium's slow movzx." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:15:18.750", "Id": "518504", "Score": "0", "body": "@EmilyL.: And BTW, using the LUT to handle the end-of-string detection in the read-only scan was inspired by glibc's `strpbrk` which does the same thing." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T12:36:35.493", "Id": "262677", "ParentId": "261588", "Score": "5" } } ]
{ "AcceptedAnswerId": "261591", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:10:07.747", "Id": "261588", "Score": "8", "Tags": [ "performance", "c", "strings" ], "Title": "Remove all unwanted characters from a string buffer, in-place" }
261588
<p>The program will read size of free memory partitions and size of processes from a text file and then will try to allocate a memory partition for each process using the first-fit algorithm.</p> <p>Input example:</p> <pre><code>300,600,350,200,750,125 115,500,358,200,375 </code></pre> <p>My code for the implementation:</p> <pre><code>import sys filename = sys.argv[1] with open(filename, &quot;r&quot;) as file: free_memory = file.readline().strip().split(',') process_size = list(map(int, file.readline().strip().split(','))) file = open(&quot;output.txt&quot;,&quot;w&quot;) #---------------------------# #First-Fit Memory Allocation# #---------------------------# file.write(f&quot;First-Fit Memory Allocation\n{'-'*60}\n&quot;) file.write(f&quot;start =&gt; {' '.join(free_memory)}\n&quot;) memory = list(map(int, free_memory)) memory_str = list(free_memory) for process in process_size: data = f&quot;{process} =&gt; &quot; allocated = False for index in range(len(memory)): if not allocated and memory[index] &gt;= process: memory[index] -= process memory_str[index] = memory_str[index][:-1*len(str(process))] memory_str[index] += f&quot;{process}*&quot; if(memory[index] != 0): memory_str[index] += f&quot; {memory[index]}&quot; allocated = True data += f&quot;{memory_str[index]} &quot; if(not allocated): data = f&quot;{process} =&gt; not allocated, must wait&quot; file.write(data+'\n') </code></pre> <p>My code works so far but I want to reformat my code to make it simpler and more readable. Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:11:04.847", "Id": "516229", "Score": "1", "body": "Welcome to Code Review. What Python version did you write this for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:11:50.377", "Id": "516230", "Score": "4", "body": "This is a duplicate of https://codereview.stackexchange.com/questions/261581/contiguous-memory-allocation-using-first-fit-algorithm . Are you the same user, is this in the same class, or what?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:46:31.027", "Id": "261590", "Score": "2", "Tags": [ "python", "memory-management" ], "Title": "Fit memory allocation" }
261590
<p>My function needs to check if some nested object is empty. For flat objects, there is no need of recursion, and a very basic function could be the following (inspired to <a href="https://www.php.net/manual/en/function.empty.php" rel="nofollow noreferrer">PHP empty</a>):</p> <pre><code>empty = function (mixedVar) { var undef var key var i var len var emptyValues = [undef, null, '']; for (i = 0, len = emptyValues.length; i &lt; len; i++) { if (mixedVar === emptyValues[i]) { return true } } if (typeof mixedVar === 'object') { for (key in mixedVar) { if (mixedVar.hasOwnProperty(key)) { return false } } return true } return false } </code></pre> <p>Now, supposed that the object has several levels of nesting, a recursive version may be needed. It worths nothing that <a href="https://codereview.stackexchange.com/a/261252/104793">this</a> version adds a &quot;empty&quot; array to pass as input what can be considered as an empty:</p> <pre><code> /** * Check if an object is empty recursively * @param {Object} mixedVar * @param {Array} emptyValues * @param {Number} iter current iteratiom, defaults 0 * @param {Number} deep recursions levels, defaults 3 * @returns {Boolean} true if object is empty */ emptyDeep: function(mixedVar, emptyValues = [undefined, null, ''], iter=0, deep=3) { var i, len for (i = 0, len = emptyValues.length; i &lt; len; i++) { if (mixedVar === emptyValues[i]) { return true } } if (typeof mixedVar === 'object') { for (const item of Object.values(mixedVar)) { if(iter&gt;=deep) { return false } else if (!this.emptyDeep(item, emptyValues, ++iter, deep)) { return false } } return true } return false } </code></pre> <p>This function has also <code>iter</code> and <code>deep</code> variables to control the recursion exit guard at some level of nesting, by defaults 3. The problem is that with very big objects (order of 10 KB) it turns out that this functions becomes very slow as the object size, and nesting levels grow (like deep &gt; 3). As results the whole Node IO loop will be affected. As alternative to this, I have tried this approach, that tries to check the empty for &quot;almost&quot; flatten object, at one level of nesting, and without any recursion:</p> <pre><code> /** * Check if a flatten object is empty * @param {*} obj * @returns */ emptyFlatten: function(obj) { if(this.empty(obj)) return true; if(Array.isArray(obj)) { return obj.filter(val =&gt; this.empty(val)).length==obj.length; } const keys = Object.keys(obj); return keys.map(key =&gt; obj[key]).filter(val =&gt; this.empty(val)).length==keys.length; } </code></pre> <p>that will work for structures like</p> <pre><code>[] {}, { A: {}, B: [], C:null, D:undefined } </code></pre> <p>but not for a 3 levels object like:</p> <pre><code>{ A: {}, B: { C: [] } } </code></pre> <p>So, how to optimize the function <code>emptyDeep</code> to make it fast for few levels of recursion (let's say deep &lt;= 3)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T04:25:35.130", "Id": "518277", "Score": "1", "body": "This seems like a sort of odd use case. Do you really have objects with literally no values in it that are so incredibly large that they're locking up your program? Could you describe the nature of this use case, because it's rather unusual. How many elements are expected to be in these structures? Most nested structures typically have a value of some sort in them, and it only takes 1 value to make it nonempty, so you'd probably need some kind of thousand or million-sized empty nested structure or be calling this test repeatedly in a critical path to meaningfully harm performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:54:43.610", "Id": "518337", "Score": "1", "body": "There is a bug in `emptyDeep` It will only check the first 3 (using default depth) sub objects because you use an assignment operation on `itter` eg `++itter` should be `itter + 1`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:34:14.130", "Id": "518349", "Score": "0", "body": "@Blindman67 right! thanks a lot for the fix!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T18:17:06.533", "Id": "261593", "Score": "0", "Tags": [ "javascript" ], "Title": "JavaScript optimize a function to check if a nested object is empty" }
261593
<p>This is for a cheap VPS I use for personal projects. I like having a message of the day displaying system info on login; I wanted to add the status of my docker containers to it, to see if all are running and whatnot.</p> <p>The scripts I found online for this displayed all the containers, but since I run mailcow for my email and it has 10+ containers in that single docker-compose project, the MOTD was much too long for my liking. So I decided to write my own although I've never written anything in Bash before this.</p> <p>My script lists Docker containers and their status, but containers that are part of a docker-compose project are condensed into one as if they were a single container with the name of the compose project. If a container of a docker-compose project isn't running then the status of the &quot;condensed container&quot; is changed to &quot;partial&quot;, and the container that isn't running is listed with its full name.<br /> <a href="https://i.imgur.com/2ssVVQu.png" rel="nofollow noreferrer">Screenshot (highlighted with a box is the output of the script)</a></p> <p>My concerns about this are:</p> <ul> <li>I don't want to miss out on relevant info (other than the amount of time a container has been up for; I don't care about that), I'm not too familiar with docker and possible status a container could have and whether my way of doing <code>...!= &quot;Up&quot;</code> to check the status is good enough.</li> <li>When a compose project has all its containers stopped/exited (any status that isn't &quot;Up&quot;) I'd like to &quot;condense&quot; it again, since at the moment if that's the case then it will display partial, even though all its containers are not running, then it also list all of its containers. I don't know how I'd achieve this without running multiple chained <code>docker ps</code> commands that would slow down the script considerably. For now I'm content that a compose project having all its containers being down isn't something frequent.</li> <li>I'm not too happy with the way I order the containers. I use two arrays put what I want near the top in one, and then what I want near the bottom in the second. I then concat the arrays. Not sure if this matters or if there's a cleaner way of doing it.</li> <li>Any unforeseen effects, or any way this doesn't work how I intended (outlined above) that is caused by my relative unfamiliarity with Docker or complete unfamiliarity with Bash scripts. And lastly and super minor, almost not worth mentioning: my choice of wording for saying &quot;partial&quot; when not all compose project's containers are running. Couldn't think of any better word, not sure if there is one.</li> </ul> <pre><code>#!/bin/bash COLUMNS=2 # colors green=&quot;\e[1;32m&quot; yellow=&quot;\e[1;33m&quot; red=&quot;\e[1;31m&quot; blue=&quot;\e[36;1m&quot; undim=&quot;\e[0m&quot; mapfile -t containers \ &lt; &lt;(docker ps -a --format='{{.Label &quot;com.docker.compose.project&quot;}},{{.Names}},{{.Status}}' \ | sort -r -k3 -t &quot;,&quot; \ | awk -F '[ ,]' -v OFS=',' '{ print $1,$2,$3 }') declare -A upper_containers # To later concat with the ones I want to display first at the top declare -A lower_containers for i in &quot;${!containers[@]}&quot;; do IFS=&quot;,&quot; read proj_name name status &lt;&lt;&lt; ${containers[i]} if [[ -n $proj_name ]]; then # is docker-compose color=$green; if [[ &quot;$status&quot; != &quot;Up&quot; ]]; then lower_containers[$name]=&quot;${name}:,${red}${status,,}${undim},&quot;; color=$yellow; status=&quot;partial&quot;; fi upper_containers[$proj_name]=&quot;${blue}${proj_name}:,${color}${status,,}${undim},&quot; else # not docker-compose if [[ &quot;$status&quot; != &quot;Up&quot; ]]; then lower_containers[$name]=&quot;${name}:,${red}${status,,}${undim},&quot;; else upper_containers[$name]=&quot;${name}:,${green}${status,,}${undim},&quot;; fi fi done; i=1 out=&quot;&quot; containers=(&quot;${upper_containers[@]}&quot; &quot;${lower_containers[@]}&quot;) for el in &quot;${containers[@]}&quot;; do out+=$el if [ $(($i % $COLUMNS)) -eq 0 ]; then out+=&quot;\n&quot; fi i=$(($i+1)) done; out+=&quot;\n&quot; printf &quot;\ndocker status:\n&quot; printf &quot;$out&quot; | column -ts $',' | sed -e 's/^/ /' printf &quot;\n\n&quot; </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code># colors\ngreen=&quot;\\e[1;32m&quot;\nyellow=&quot;\\e[1;33m&quot;\nred=&quot;\\e[1;31m&quot;\nblue=&quot;\\e[36;1m&quot;\n</code></pre>\n</blockquote>\n<p>You don't know what kind of terminal (if indeed a terminal) that output will be going to, so don't hard-code these terminal-specific codes.</p>\n<p>Instead, use <code>tput</code> which will generate the right strings for terminals that support them:</p>\n<pre><code>green=$(tput setaf 2)\nyellow=$(tput setaf 3)\nred=$(tput setaf 1)\nblue=$(tput setaf 4)\n</code></pre>\n<hr />\n<p>Don't set <code>COLUMNS</code> yourself globally for the script - normally Bash sets this automatically to the terminal's correct number of columns, and setting it to 2 will certainly confuse many applications.</p>\n<p>It looks like you meant to create a variable for your own use - don't use all-caps for your own variables, to avoid collisions like this with environment variables that affect child processes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T11:00:09.237", "Id": "518309", "Score": "0", "body": "Ah thanks, was wondering why the colors were a bit different on my laptop and pc, didn't think much of it. When you say \"if indeed a terminal\", since the script is located in /etc/update-motd.d/ along my other MOTD messages is it not guaranteed to be a terminal? Also if am I fine with making a differently named variable / just lower case columns if I want always 2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T11:44:19.370", "Id": "518314", "Score": "0", "body": "Yes, use a lower-case name so that you're not setting `COLUMNS` which already has a meaning." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T07:37:49.583", "Id": "262609", "ParentId": "261597", "Score": "2" } }, { "body": "<h3>Addressing your concerns</h3>\n<blockquote>\n<ul>\n<li>I don't want to miss out on relevant info (other than the amount of time a container has been up for; I don't care about that), I'm not\ntoo familiar with docker and possible status a container could have\nand whether my way of doing ...!= &quot;Up&quot; to check the status is good\nenough.</li>\n</ul>\n</blockquote>\n<p>I don't know docker compose very well either, but I have some ideas here:</p>\n<ul>\n<li>When it's not docker compose, the status value will be always printed. So when &quot;Up&quot; is no longer good enough, you will see it in the output, and then you can take appropriate action.</li>\n<li>When it's docker compose, the status value will be printed for <code>$name</code>, but not for <code>$proj_name</code> (where you print &quot;partial&quot; instead). This seems ok too, because again, the original value gets printed, so the logic in the previous point works for this one too.</li>\n</ul>\n<blockquote>\n<ul>\n<li>When a compose project has all its containers stopped/exited (any status that isn't &quot;Up&quot;) I'd like to &quot;condense&quot; it again, since at the moment if that's the case then it will display partial, even though all its containers are not running, then it also list all of its containers. I don't know how I'd achieve this without running multiple chained docker ps commands that would slow down the script considerably. For now I'm content that a compose project having all its containers being down isn't something frequent.</li>\n</ul>\n</blockquote>\n<p>You can do with a single docker ps command,\nstoring data about projects, to process in a second pass.\nThe data you would store:</p>\n<ul>\n<li>A regular array of unique project names</li>\n<li>An associative array <code>any_container_up</code> to track for each project if any of its containers was up</li>\n<li>An associative array <code>any_container_down</code> to track for each project if any of its containers was down</li>\n</ul>\n<p>You could populate these data structures in the first pass over the output of docker ps.\nNext, you could loop over the project names,\nand decide based on <code>any_container_up[$proj_name]</code> and <code>any_container_down[$proj_name]</code> the correct status for the project itself:</p>\n<ul>\n<li>if <code>any_container_up[$proj_name]</code> and <code>any_container_down[$proj_name]</code> -&gt; partial: some containers are up, others are down</li>\n<li>else if <code>any_container_up[$proj_name]</code> -&gt; all containers are up</li>\n<li>else -&gt; all containers are down</li>\n</ul>\n<blockquote>\n<ul>\n<li>I'm not too happy with the way I order the containers. I use two arrays put what I want near the top in one, and then what I want near the bottom in the second. I then concat the arrays. Not sure if this matters or if there's a cleaner way of doing it.</li>\n</ul>\n</blockquote>\n<p>As written, the last few containers up and the first few containers down may appear on the same line. So for each line I would have to scan horizontally, which is a mental burden. It seems to me that the different statuses are significant enough that they would deserve to be listed with a clean break in between. I would even split to 3 groups: up, partial, down.</p>\n<blockquote>\n<ul>\n<li>Any unforeseen effects, or any way this doesn't work how I intended (outlined above) that is caused by my relative unfamiliarity with Docker or complete unfamiliarity with Bash scripts. And lastly and super minor, almost not worth mentioning: my choice of wording for saying &quot;partial&quot; when not all compose project's containers are running. Couldn't think of any better word, not sure if there is one.</li>\n</ul>\n</blockquote>\n<p>The script looks pretty good to me, I don't see major causes for concern.</p>\n<p>As for the wording of &quot;partial&quot;, it felt natural to me, and I'm very sensitive to naming.</p>\n<p>And on that note... I didn't like the names <code>upper_containers</code> and <code>lower_containers</code>. My first assumption was that &quot;upper&quot; and &quot;lower&quot; refers to uppercasing and lowercasing names, that these are data structures for formatting. (Then of course I saw that's not the case, I'm just sharing my initial impressions.) I would rename these to <code>containers_up</code> and <code>containers_down</code>.</p>\n<h3>Looping in Bash</h3>\n<p>Instead of:</p>\n<blockquote>\n<pre><code>for i in &quot;${!containers[@]}&quot;; do\n IFS=&quot;,&quot; read proj_name name status &lt;&lt;&lt; ${containers[i]}\n</code></pre>\n</blockquote>\n<p>It would be simpler this way:</p>\n<pre><code>for container in &quot;${containers[@]}&quot;; do\n IFS=&quot;,&quot; read proj_name name status &lt;&lt;&lt; ${container}\n</code></pre>\n<p>Instead of:</p>\n<blockquote>\n<pre><code>containers=(&quot;${upper_containers[@]}&quot; &quot;${lower_containers[@]}&quot;)\nfor el in &quot;${containers[@]}&quot;; do\n</code></pre>\n</blockquote>\n<p>You could write:</p>\n<pre><code>for container in &quot;${upper_containers[@]}&quot; &quot;${lower_containers[@]}&quot;; do\n</code></pre>\n<h3>Using arithmetic evaluation</h3>\n<p>Instead of this:</p>\n<blockquote>\n<pre><code>if [ $(($i % $COLUMNS)) -eq 0 ]; then\n out+=&quot;\\n&quot;\nfi\ni=$(($i+1))\n</code></pre>\n</blockquote>\n<p>It would be simpler to use <em>arithmetic evaluation</em>:</p>\n<pre><code>if (( i % COLUMNS == 0 )); then\n out+=&quot;\\n&quot;\nfi\n((++i))\n</code></pre>\n<p>For more info about arithmetic evaluation, see the <strong>ARITHMETIC EVALUATION</strong> section in <code>man bash</code>.</p>\n<h3>Odd semicolons</h3>\n<p>Several lines end with unnecessary <code>;</code> that can be simply removed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:50:37.780", "Id": "531967", "Score": "1", "body": "What a brilliant and comple response, thank you! I didn't even think to ask about the loops, but i did feel like they were clunky. Regarding the semi-colons is not using them a convention? Or is it because I was inconsistent in my usage (which I hadn't noticed)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:57:40.857", "Id": "531969", "Score": "0", "body": "@DavidPH Your loop is find, I didn't think it's clunky. My suggestion on it is rather cosmetic. The semi-colons in Bash are to separate commands. Since the newline already has that effect, a semi-colon is completely unnecessary there, therefore it shouldn't be there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:33:33.787", "Id": "531997", "Score": "1", "body": "Yeah by clunky I meant as in I never liked the way they looked, but didn't consider there being alternatives. Also thanks for pointing out, didn't notice I hadn't upvoted that months ago." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T09:56:45.457", "Id": "269606", "ParentId": "261597", "Score": "2" } } ]
{ "AcceptedAnswerId": "269606", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T20:34:14.987", "Id": "261597", "Score": "1", "Tags": [ "performance", "bash", "linux", "docker" ], "Title": "Bash script (to be used as a login MOTD message) that displays status of docker-compose projects, and individual docker containers" }
261597
<p>The code below is a Haskell implementation of Needleman-Wunsch algorithm for sequence alignment (and string edit distance). It's an experiment in trying to closely imitate the dynamic programming method as it would be implemented in imperative languages. Hence my use of mutable arrays and ST monad.</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} import Data.Array.ST import Data.List import Control.Monad.ST import Control.Monad -- Primitive edit operations data Operation a = Subst a a -- match is a special case of substitution | Insert a | Delete a deriving (Show, Eq) -- Operation costs data Costs a = Costs { delete :: a -&gt; Int, insert :: a -&gt; Int, subst :: a -&gt; a -&gt; Int } defaultCost :: (Eq a) =&gt; Costs a defaultCost = Costs { delete = const 1, insert = const 1, subst = \x y -&gt; if x == y then 0 else 10 } data Transform a = Transform [Operation a] Int -- Given cost functions, describe a series of transformation taking the input string to the output string alignWithCost :: Costs a -&gt; [a] -- ^ input string -&gt; [a] -- ^ output string -&gt; Transform a alignWithCost Costs{..} inputString outputString = let inputLen = length inputString outputLen = length outputString alignWithCostST = do array &lt;- newArray ((0, 0), (inputLen, outputLen)) $ Transform [] 0 :: ST s (STArray s (Int, Int) (Transform a)) -- To get from x1 ... xn to the empty string, perform n deletions -- the sequence of transforms is placed in reverse order ; later transform can then be appended with (:) let initials = map reverse $ inits inputString forM_ (zip [0 .. inputLen] initials) $ \(i, initial) -&gt; do writeArray array (i, 0) $ Transform (map Delete initial) (sum $ map delete initial) -- To get from the empty string to x1 ... xn to the empty string, perform n insertions let initials = map reverse $ inits outputString forM_ (zip [0 .. outputLen] initials) $ \(i, initial) -&gt; do writeArray array (0, i) $ Transform (map Insert initial) (sum $ map insert initial) -- To get from x1 ... xn to y1 ... ym, you either -- * go from x1 ... xn to y1 ... y(m-1) and insert ym (top) -- * delete xn and go from x1 ... x(n-1) to y1 ... ym (left) -- * substitute xn for ym go from x1 ... x(n-1) to y1 ... y(m-1) (diag) -- Pick whichever way is least costly forM_ (zip [1 .. inputLen] inputString) $ \(i, cIn) -&gt; do forM_ (zip [1 .. outputLen] outputString) $ \(j, cOut) -&gt; do Transform alignmentSeqLeft initCostLeft &lt;- readArray array (i - 1, j) Transform alignmentSeqTop initCostTop &lt;- readArray array (i, j - 1) Transform alignmentSeqDiag initCostDiag &lt;- readArray array (i - 1, j - 1) let costLeft = initCostLeft + delete cIn costTop = initCostTop + insert cOut costDiag = initCostDiag + subst cIn cOut minCost = min costLeft $ min costTop costDiag let toWrite | minCost == costLeft = (Delete cIn):alignmentSeqLeft | minCost == costTop = (Insert cOut):alignmentSeqTop | minCost == costDiag = (Subst cIn cOut):alignmentSeqDiag writeArray array (i, j) $ Transform toWrite minCost Transform operations cost &lt;- readArray array (inputLen, outputLen) -- Reverse the sequence of transforms to original order: earlier transforms before return $ Transform (reverse operations) cost in runST alignWithCostST align :: Costs a -&gt; [a] -- ^ input string -&gt; [a] -- ^ output string -&gt; [Operation a] align costs inputString outputString = operations where Transform operations _ = alignWithCost costs inputString outputString alignDefault :: (Eq a) =&gt; [a] -- ^ input string -&gt; [a] -- ^ output string -&gt; [Operation a] alignDefault = align defaultCost printAlignSeq :: (a -&gt; Char) -&gt; [Operation a] -&gt; IO () printAlignSeq display tokens = do forM_ tokens $ \case Insert _ -&gt; putStr $ &quot;_&quot; Delete x -&gt; putStr $ [display x] Subst x _ -&gt; putStr $ [display x] putStrLn &quot;&quot; forM_ tokens $ \case Insert x -&gt; putStr $ [display x] Delete _ -&gt; putStr $ &quot;_&quot; Subst x _ -&gt; putStr $ [display x] putStrLn &quot;&quot; </code></pre> <p>Here are some test runs:</p> <pre class="lang-hs prettyprint-override"><code>*Main&gt; printAlignSeq id $ alignDefault &quot;a beautiful bike&quot; &quot;a big bike&quot; a beauti_ful bike a b____ig___ bike *Main&gt; printAlignSeq id $ alignDefault &quot;accgcag&quot; &quot;ccgacag&quot; accg_cag _ccgacag *Main&gt; printAlignSeq id $ alignDefault &quot;sinusoidal&quot; &quot;cosine&quot; __sin_usoidal cosine_______ </code></pre> <p>Any comments or feedback is welcome! I am particularly interested in the following points:</p> <ul> <li>Is this a good way to implement dynamic programming algorithms in Haskell?</li> <li>Is this a good way to mimic mutability in a language like Haskell?</li> <li>I am worried about memory issues: is there any unnecessary thunk build-up? how can I tell? (I really struggle to understand that!)</li> </ul>
[]
[ { "body": "<p>I wouldn't worry about using mutability here. Sometimes it pays to just be straightforward and stick closely to something that you know works.</p>\n<ul>\n<li><p>You're not using <code>ScopedTypeVariables</code>.</p>\n</li>\n<li><p>As far as the interface, <code>Costs</code> has no reason to be a <code>data</code> type. It is clearer from the user's perspective to say simply</p>\n<pre><code>type Costs a = Operation a -&gt; Int\n-- replacements for record accessors\n-- delete costs x = costs (Delete x)\n-- insert costs x = costs (Insert x)\n-- subst costs x y = costs (Subst x y)\n-- e.g.\ndefaultCost :: Eq a =&gt; Costs a\ndefaultCost (Subst x y) | x == y = 0\n | otherwise = 10\ndefaultCost (Insert _) = 1\ndefaultCost (Delete _) = 1\n</code></pre>\n<p>No more <code>RecordWildCards</code>.</p>\n</li>\n<li><p><code>Transform</code> currently also has no reason to exist: the only point it might have is documentation, but you haven't given it any! The <code>Int</code> is particularly mysterious at first sight. You should make it into a record with named fields (which will probably be self documenting enough). While you're at it, the total cost should be strict (I believe your code has a minor space leak in this field). &quot;Accumulator&quot; fields often should be strict.</p>\n<pre><code>data Transform a = Transform { transformOps :: [Operation a], transformCost :: !Int }\n</code></pre>\n</li>\n<li><p>Taking a look at the main function</p>\n<pre><code>alignWithCost costs input output = runST $ do -- no need to do strange things with lets\n let inputLen = length input\n outputLen = length output\n -- (array? really?)\n -- (if you're going to comment about how the algorithm works, you should explain what this is)\n -- each partials[i, j] will eventually be the minimal transform from (take i input) to (take j output)\n -- also, the transformOps of the partials are reversed for efficient appending with (:)\n partials &lt;- newArray ((0, 0), (inputLen, outputLen)) $ Transform [] 0 :: ST s (STArray s (Int, Int) (Transform a))\n\n let -- (a little vocabulary goes a long way)\n addOp op (Transform ops totalCost) = Transform (op : ops) (costs op + totalCost)\n -- (zip truncates; I find zipping with the infinite list cleaner)\n -- (there is no need to reverse each of the inits separately when we can write this iteratively)\n -- (your wasted space was here: I believe each Transform made in these loops would hang onto the corresponding list from the inits until you would start evaluating things down in the nested loop)\n -- (in this version, without the strictness annotation from before, this would still build some annoying thunks in the cost field)\n -- (compared to the total space usage though, I suspect it might be moot either way)\n -- for each partials[i, 0]: to get from x1 ... xi to the empty string, perform i deletions\n forM_ (zip [1..] input) $ \\(i, del) -&gt;\n -- (if we're mimicking imperative languages, may as well use all the application operators we have to sell it ;))\n writeArray partials (i, 0) =&lt;&lt; addOp (Delete del) &lt;$&gt; readArray partials (i - 1, 0)\n -- for each partials[0, i]: to get from the empty string to y1 .. yi, perform i insertions\n forM_ (zip [1..] output) $ \\(i, ins) -&gt;\n writeArray partials (0, i) =&lt;&lt; addOp (Insert ins) &lt;$&gt; readArray partials (0, i - 1)\n\n -- for all the rest of the partials[i &gt; 0, j &gt; 0]:\n -- to get from x1 ... xi to y1 ... yj, either:\n -- * transform x1 ... x(i-1) to y1 ... yj, then delete xi (using partials[i - 1, j] = &quot;left&quot;)\n -- * transform x1 ... xi to y1 ... y(j-1), then insert yj (using partials[i, j - 1] = &quot;up&quot;)\n -- * transform x1 ... x(i-1) to y1 ... y(j-1), then substitute xi with yj (using partials[i - 1, j - 1] = &quot;diag&quot;)\n -- take the one with minimal cost\n forM (zip [1..] input) $ \\(i, xi) -&gt;\n forM (zip [1..] output) $ \\(j, yj) -&gt; do\n -- (so! very! clean!)\n left &lt;- addOp (Delete xi ) &lt;$&gt; readArray partials (i - 1, j )\n up &lt;- addOp (Insert yj) &lt;$&gt; readArray partials (i , j - 1)\n diag &lt;- addOp (Subst xi yj) &lt;$&gt; readArray partials (i - 1, j - 1)\n writeArray partials (i, j) $ minimumBy (comparing transformCost) [left, up, diag]\n\n Transform ops cost &lt;- readArray partials (inputLen, outputLen)\n return $ Transform (reverse ops) cost\n</code></pre>\n<p>Having written all that, I do think that perhaps mutability actually is entirely unnecessary here. We can just use a single immutable array with an intricate recursion pattern:</p>\n<pre><code>alignWithCost costs input output = Transform (reverse ops) cost\n where inputLen = length input\n outputLen = length output\n xs = listArray (0, inputLen - 1) input\n ys = listArray (0, outputLen - 1) output\n -- partials[i, j] is the minimum cost transform from (take i input) to (take j output)\n -- the transformOps are stored in reverse for efficient appending with (:)\n partials = array ((0, 0), (inputLen, outputLen)) [((i, j), partial i j) | i &lt;- [0..inputLen], j &lt;- [0..outputLen]]\n addOp op (Transform ops cost) = Transform (op : ops) (costs op + cost)\n -- this calculates each of the partials[i, j], potentially in terms of some of the partials[n &lt; i, m &lt; j]\n partial 0 0 = Transform [] 0 -- empty string to empty string\n partial i 0 = addOp (Delete $ xs ! (i - 1)) $ partials ! (i - 1, 0) -- (take i input) to []: delete each element\n partial 0 j = addOp (Insert $ ys ! (j - 1)) $ partials ! (0, j - 1) -- [] to (take j output): insert each element\n partial i j = minimumBy (comparing transformCost) [left, up, diag] -- (take (i - 1) input ++ [del]) to (take (j - 1) output ++ [ins]); choose of the following the minimal cost:\n where del = xs ! (i - 1)\n ins = ys ! (j - 1)\n left = addOp (Delete del ) $ partials ! (i - 1, j ) -- transform (take (i - 1) input) to (take j output) and delete del\n up = addOp (Insert ins) $ partials ! (i , j - 1) -- transform (take i input) to (take (j - 1) output) and insert ins\n diag = addOp (Subst del ins) $ partials ! (i - 1, j - 1) -- transform (take (i - 1) input) to (take (j - 1) output) and substitute del with ins\n Transform ops cost = partials ! (inputLen, outputLen)\n</code></pre>\n<p>Yes, that's legal! (And it seems to work.) This is basically getting to heart of what memoization/dynamic programming is: <code>partial</code> is a recursive algorithm &quot;at heart&quot;, but we've simply taken the recursive calls and redirected them to a lookup table (the transformation <code>partials ! (x, y)</code> &lt;-&gt; <code>partial x y</code>). In Haskell, we can trust laziness to populate that table as needed instead of writing it ourselves. We use an array over a list because lists are not meant for random access.</p>\n</li>\n<li><p>For the helper functions, I can't say much, except that now <code>align</code> can just be</p>\n<pre><code>align costs input output = transformOps $ alignWithCost costs input output\n</code></pre>\n</li>\n<li><p><code>printAlignSeq</code> can probably be</p>\n<pre><code>printAlignSeq display ops = do\n putStrLn $ flip map ops $ \\case\n Insert _ -&gt; '_'\n Delete x -&gt; display x\n Subst x _ -&gt; display x\n putStrLn $ flip map ops $ \\case\n Insert y -&gt; display y\n Delete _ -&gt; '_'\n Subst _ y -&gt; display y\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:01:03.003", "Id": "518361", "Score": "0", "body": "Thanks for taking the time to write this excellent review! I can see the benefit of array+recursion+laziness to get some form of memoization going on. I'd be interested to know how this solution compares to the ST-based solution in terms of memory footprint." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T06:34:54.047", "Id": "262606", "ParentId": "261599", "Score": "2" } } ]
{ "AcceptedAnswerId": "262606", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T22:34:20.730", "Id": "261599", "Score": "3", "Tags": [ "array", "haskell", "dynamic-programming" ], "Title": "Haskell implementation of Needleman-Wunsch" }
261599
<p>I'm 16 years old and no one to help me, no one to give any advice or constructive criticism, I'm aimless. I'll leave the link to my last code (github), a program that sends an email to everyone registered in the database. I would like some advice and project/content ideas for me to evolve. Evaluate my project sincerely.</p> <p>Class that connects to the database and sends the email:</p> <pre><code> import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.swing.JOptionPane; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JavaMailUtil { Connection conn; PreparedStatement ps; ResultSet rs; String sender = &quot;testemailforjava16@gmail.com&quot;; String senderPassword = &quot;*******&quot;; private static Connection connectionToMySql() throws SQLException { Connection conn = DriverManager.getConnection(&quot;jdbc:mysql://localhost:3306/emailproject?useTimezone=true&amp;serverTimezone=UTC&quot;, &quot;root&quot;, &quot;&quot;); return conn; } public void sendEmail(String title, String text) { conn = null; ps = null; rs = null; try { conn = connectionToMySql(); ps = (PreparedStatement) conn.prepareStatement(&quot;select * from users&quot;); rs = ps.executeQuery(); while (rs.next() ) { Properties prop = new Properties(); prop.put(&quot;mail.smtp.auth&quot;, true); prop.put(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;); prop.put(&quot;mail.smtp.host&quot;, &quot;smtp.gmail.com&quot;); prop.put(&quot;mail.smtp.port&quot;, &quot;587&quot;); Session session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sender, senderPassword); } }); Message message = prepareMessage(session, sender, rs.getString(2), text, title); Transport.send(message); } } catch (Exception e) { JOptionPane.showMessageDialog(null, &quot;Error!&quot;); e.printStackTrace(); return; } finally { try { if (conn != null) { conn.close(); } if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); } } JOptionPane.showMessageDialog(null, &quot;Email successfully sent!&quot;); } private static Message prepareMessage(Session session, String sender, String recepient, String text, String title) { try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient)); message.setSubject(title); message.setText(text); return message; } catch (Exception e) { Logger.getLogger(JavaMailUtil.class.getName()).log(Level.SEVERE, null, e); } return null; } } </code></pre> <p>Swing Part:</p> <pre><code>package windows; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import project.JavaMailUtil; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; import javax.swing.JTextArea; import javax.swing.SwingConstants; public class MainWindow { private JFrame frame; private JTextField txtTitle; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainWindow window = new MainWindow(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow() { initialize(); } /** * Initialize the contents of the frame. */ public void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); JLabel lbl1 = new JLabel(&quot;Title:&quot;); lbl1.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 18)); lbl1.setBounds(10, 81, 43, 26); frame.getContentPane().add(lbl1); JLabel lbl2 = new JLabel(&quot;Text:&quot;); lbl2.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 18)); lbl2.setBounds(10, 133, 43, 26); frame.getContentPane().add(lbl2); txtTitle = new JTextField(); txtTitle.setHorizontalAlignment(SwingConstants.CENTER); txtTitle.setFont(new Font(&quot;Tahoma&quot;, Font.BOLD, 15)); txtTitle.setBounds(54, 77, 342, 37); frame.getContentPane().add(txtTitle); txtTitle.setColumns(10); JButton buttonSend = new JButton(&quot;Send Email&quot;); buttonSend.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 16)); buttonSend.setBounds(269, 227, 127, 23); frame.getContentPane().add(buttonSend); JTextArea txtText = new JTextArea(); txtText.setFont(new Font(&quot;Tahoma&quot;, Font.BOLD, 15)); txtText.setBounds(54, 136, 342, 80); frame.getContentPane().add(txtText); txtText.setLineWrap(true); txtText.setWrapStyleWord(true); JLabel lblNewLabel = new JLabel(&quot;Automatic Sender&quot;); lblNewLabel.setFont(new Font(&quot;Tahoma&quot;, Font.BOLD | Font.ITALIC, 23)); lblNewLabel.setBounds(95, 22, 243, 37); frame.getContentPane().add(lblNewLabel); JButton buttonUsers = new JButton(&quot;Users&quot;); buttonUsers.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 16)); buttonUsers.setBounds(54, 227, 83, 23); frame.getContentPane().add(buttonUsers); // TODO buttonSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JavaMailUtil javaMailUtil = new JavaMailUtil(); buttonSend.setText(&quot;Sending...&quot;); JOptionPane.showMessageDialog(null, &quot;Sending... Wait the alert!&quot;); javaMailUtil.sendEmail(txtTitle.getText(), txtText.getText()); buttonSend.setText(&quot;Send Email&quot;); } }); } } </code></pre> <p>Link: <a href="https://github.com/DaviRibeiro-prog/JAVA/tree/main/EmailSenderProject/src" rel="nofollow noreferrer">https://github.com/DaviRibeiro-prog/JAVA/tree/main/EmailSenderProject/src</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:17:28.417", "Id": "518371", "Score": "1", "body": "Just be aware that we can only review/comment on the code that is actually in the question, not all the code in the repository." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T21:10:48.520", "Id": "518414", "Score": "1", "body": "Welcome to Code Review! 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://codereview.meta.stackexchange.com/a/1765)." } ]
[ { "body": "<p>Welcome in the fantastic world of development.</p>\n<p>There is this great acronym in software development: <strong>S.O.L.I.D.</strong>. You can refer to it at any time to evaluate the quality of your code.</p>\n<p>However, in a two classes project, many of them are overkill. But there is one that you should try to use at all stages:</p>\n<ul>\n<li><strong><em>&quot;S&quot;</em></strong> for &quot;Single responsibility&quot;</li>\n</ul>\n<blockquote>\n<p>Every class and method should have one responsibility</p>\n</blockquote>\n<p>Your <code>JavaMailUtil</code> is responsible to connect to the database, retrieve the users and send emails. This is a bit too much.</p>\n<p>You should better extract some functionalities to different classes. I see three main roles of your actual code:</p>\n<ol>\n<li>Connect to the database</li>\n<li>Retrieve the users</li>\n<li>Send an email</li>\n</ol>\n<p>The <em><strong>D</strong>ata <strong>A</strong>ccess <strong>O</strong>bject</em> and the _<strong>Factory</strong> are two <em>design patterns</em> that you can use apply in you program.</p>\n<p>The <em><strong>Factory</strong></em> will be used to get a connection to the database. While the _<strong>DAO</strong> can be used to get a list of users from that connection. Finally, your <code>JavaMailUtil</code> can use that <em><strong>DAO</strong></em> to retrieve the users.</p>\n<ul>\n<li>Another good principle is the <strong>&quot;D&quot;</strong> for &quot;Dependency inversion&quot;.</li>\n</ul>\n<p>The issue with the code above is that the <code>JavaMailUtil</code> has a strong dependency on your <em><strong>DAO</strong></em> to access the users. And, again, his role is to send emails, not retrieve users. A good solution is to pass the users as a parameter.</p>\n<p>So you'll need a new class that will be responsible to retrieve the users and call the <code>sendEmail</code> method. It can be your <code>MainWindow</code> but ideally it is another class that should receive the command from the user facing interface and translate them to some actions on your program. Those classes are called <em>controllers</em> and are part of the <em><strong>M</strong>odel <strong>V</strong>iew <strong>C</strong>ontroller</em> pattern which is widely used in user facing applications.</p>\n<p>I admit that I did not provide direct advice on your code. But with those few paragraphs you ave enough to learn and improve your program quite a bit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T01:57:35.140", "Id": "518425", "Score": "0", "body": "I made a new post updating the code based on your comment, if you want check it out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:03:20.907", "Id": "262616", "ParentId": "262601", "Score": "3" } } ]
{ "AcceptedAnswerId": "262616", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T02:01:37.097", "Id": "262601", "Score": "2", "Tags": [ "java", "sql", "email" ], "Title": "program that sends an email to everyone registered in the database" }
262601
<p>This script gathers domains listed from sources in <a href="https://raw.githubusercontent.com/T145/the-blacklist/master/sources.json" rel="nofollow noreferrer">this JSON file</a> and compiles them into one text file. Text files that have a similar key under the <code>whitelists</code> directory will have any matching domains removed. Any tips and tricks are welcome!</p> <p><strong>build.sh</strong></p> <pre class="lang-sh prettyprint-override"><code>#!/usr/bin/env bash set -eu if ! test -d sources; then jq -r 'to_entries[] | [.key, .value.url] | @tsv' sources.json | gawk -F'\t' '{ if ($2 ~ /\.tar.gz$/ || /\.zip$/) { printf &quot;%s\n out=%s.%s\n&quot;,$2,$1,gensub(/^(.*[/])?[^.]*[.]?/, &quot;&quot;, 1, $2) } else { printf &quot;%s\n out=%s.txt\n&quot;,$2,$1 } }' | aria2c -i- -q -d sources --max-concurrent-downloads=10 --optimize-concurrent-downloads=true --auto-file-renaming=false --realtime-chunk-checksum=false --async-dns-server=[1.1.1.1:53,1.0.0.1:53,8.8.8.8:53,8.8.4.4:53,9.9.9.9:53,9.9.9.10:53,77.88.8.8:53,77.88.8.1:53,208.67.222.222:53,208.67.220.220:53] fi jq -r 'keys[] as $k | &quot;\($k)#\(.[$k] | .rule)&quot;' sources.json | while IFS=$'#' read -r key rule; do fpath=$(find -P -O3 sources -type f -name &quot;$key*&quot;) target=&quot;sources/$key.txt&quot; case $fpath in *.tar.gz) if [[ $key == 'utcapitole' ]]; then tar -xOzf $fpath --wildcards-match-slash --wildcards '*/domains' else tar -xOzf $fpath fi &gt;$target ;; *.zip) zcat $fpath &gt;$target ;; *) ;; esac gawk -i inplace &quot;$rule&quot; $target if test -f &quot;whitelists/$key.txt&quot;; then while read host; do gawk -i inplace &quot;!/$host/&quot; $target done &lt;&quot;whitelists/$key.txt&quot; fi done cat sources/*.txt | sort -u -S 75% --parallel=4 &gt;|black_domains.txt gawk '{ print &quot;0.0.0.0 &quot; $0; }' black_domains.txt &gt;black_ipv4.txt gawk '{ print &quot;:: &quot; $0; }' black_domains.txt &gt;black_ipv6.txt tar -czf black_domains.tar.gz black_domains.txt tar -czf black_ipv4.tar.gz black_ipv4.txt tar -czf black_ipv6.tar.gz black_ipv6.txt </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T07:41:51.793", "Id": "520162", "Score": "0", "body": "Do you need compatibility? Do you need to reduce dependencies other than POSIX document?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T14:29:21.980", "Id": "520231", "Score": "0", "body": "@tailsparkrabbitear I've reposted a improved script here: https://codereview.stackexchange.com/questions/263036/generating-a-domain-and-ip-blacklist-with-bash If you're interested in contributing to it: https://github.com/T145/the-blacklist/blob/master/scripts/create_builds.bash" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T02:25:05.290", "Id": "262602", "Score": "2", "Tags": [ "bash", "linux", "posix", "sh", "awk" ], "Title": "The Blacklist v2" }
262602
<p>I'm implementing a system, which requires an order to be active. I have a class called Yritys, which is the customer account who would have credits.</p> <p>1 credit would mean 1 day of service use.</p> <p>Yritys (company) has properties for credit (amount of credit) and OrderStartDate (when the original order was placed, credits were bought)</p> <p>in the mongoDbRepository we Set Order like this:</p> <pre><code> public async Task&lt;DateTime&gt; SetOrder(int companyId, int amount) { var filter = Builders&lt;Yritys&gt;.Filter.Eq(_C =&gt; _C.yritysId, companyId); var company = await _companyCollection.Find(filter).FirstAsync(); company.OrderStartDate = DateTime.Today; company.credit = amount; await _companyCollection.ReplaceOneAsync(filter, company); return company.OrderStartDate; } </code></pre> <p>Order Update method:</p> <pre><code>public async Task&lt;DateTime&gt; UpdateOrder(int companyId, int amount) { var filter = Builders&lt;Yritys&gt;.Filter.Eq(_x =&gt; _x.yritysId, companyId); var company = await _companyCollection.Find(filter).FirstAsync(); if (GetRemainingOrder(companyId) &gt; 0) { company.credit += amount; } await _companyCollection.ReplaceOneAsync(filter, company); return company.OrderStartDate; } </code></pre> <p>Check for Remaining order:</p> <pre><code>public int GetRemainingOrder(int companyId) { var filter = Builders&lt;Yritys&gt;.Filter.Eq(_c =&gt; _c.yritysId, companyId); var company = _companyCollection.Find(filter).First(); var expiryDate = company.OrderStartDate.AddDays(company.credit); if (expiryDate == DateTime.MinValue) { return 0; } if (DateTime.Compare(expiryDate, DateTime.UtcNow) == 1) { //order is active return (int)MathF.Floor((float)(expiryDate - DateTime.UtcNow).TotalDays); } // order not active: credits = 0 return 0; } </code></pre> <p>And lastly we print the date when the order expires</p> <pre><code>public string GetDueDate(int companyId) { var filter = Builders&lt;Yritys&gt;.Filter.Eq(company =&gt; company.yritysId, companyId); var company = _companyCollection.Find(filter).First(); int credits = company.credit; if (credits &gt; 0) { DateTime dueDateInTheFuture = company.OrderStartDate.AddDays(credits); return $&quot;{dueDateInTheFuture.Day}.{dueDateInTheFuture.Month}.{dueDateInTheFuture.Year}&quot;; } else return &quot;Tee uusi tilaus&quot;; } </code></pre> <p>Is there a better way to implement a credit-based order system in asp.net?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T10:43:03.847", "Id": "518306", "Score": "0", "body": "`which requires an order to be active` active for what ? please give us more details on this part of your business requirement. and what does the credits used for in the system ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:25:17.793", "Id": "518373", "Score": "0", "body": "In `public async Task<DateTime> SetOrder(int companyId, int amount)` is `amount` the number of credits purchased?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T02:59:13.850", "Id": "262603", "Score": "1", "Tags": [ "c#", "asp.net-mvc" ], "Title": "Credit based order system" }
262603
<p>Given a (long) string <code>src</code>, generate substrings (up to) <code>len</code> characters long on demand by iterating over <code>src</code> and <em>shifting</em> the reading frame by <code>shift</code> characters every time.</p> <p><a href="https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/stream/StreamSupport.html#stream(java.util.Spliterator,boolean)" rel="nofollow noreferrer"><code>StreamSupport.stream</code></a> works for me, but is there a better (more idiomatic) way to do this, for example, by using a method like <a href="https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/stream/Stream.html#iterate(T,java.util.function.Predicate,java.util.function.UnaryOperator)" rel="nofollow noreferrer"><code>Stream.iterate</code></a> and providing a <code>Predicate</code> and <code>UnaryOperator</code>?</p> <pre><code>/** * Streams strings of length up to len. Each streamed string is created from the string src by removing * first &quot;shift&quot; characters and adding last &quot;shift&quot; characters. The shifting starts from 2nd string onward. It's * like traversing the given string by a fixed length frame that shifts forward &quot;shift&quot; characters at a time. * * @param src the source string, e.g. &quot;abcde&quot; * @param len max length of the string to be streamed, no string streamed from this method will exceed this length, e.g. 2 * @param shift integer shift-width to traverse src, e.g. 1 * @return a Stream of strings, e.g. the above will stream &quot;ab&quot;, &quot;bc&quot;, &quot;cd&quot;, and &quot;de&quot; */ private static Stream&lt;String&gt; streamStrings(String src, int len, int shift) { Iterator&lt;String&gt; traverser = new Iterator&lt;&gt;() { private int i = 0, j = Math.min(len, src.length()); // substring(i, j) is what we need @Override public boolean hasNext() { return i &lt; j &amp;&amp; j &lt;= src.length(); } @Override public String next() { String n = src.substring(i, j); i += shift; if (j &lt; src.length()) j = Math.min(i + len, src.length()); else j = i + len; return n; } }; return StreamSupport.stream(Spliterators.spliteratorUnknownSize(traverser, Spliterator.SIZED), false); } </code></pre> <h2>Sample Call and Output</h2> <pre><code>streamStrings(&quot;abcdef&quot;, 3, 2).forEach(System.out::println); //abc //cde //ef </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:38:25.623", "Id": "518323", "Score": "1", "body": "Hi and welcome to Code Review. I rolled back the last two edits. For one the last edit you made incorporates feedback from an answer you have received. To avoid \"answer invalidation\", we do not allow such edits here. For more information check out *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. I'm also rolling back the title rollback you performed, but I'm not attached to my formulation... The title should describe what the code does, not what your review request is." } ]
[ { "body": "<p>You should generally avoid multiple variable initializations on one line:</p>\n<pre><code>private int i = 0;\nprivate int j = Math.min(len, src.length());\n</code></pre>\n<p>is more readable.</p>\n<hr />\n<p><strong>EDIT:</strong> The following suggestion is left in for reference, but is based on an incorrect assumption.</p>\n<p>From your sample output I would assume the following desired behaviour as well:</p>\n<pre><code>streamStrings(&quot;abcdef&quot;, 2, 1).forEach(System.out::println);\n\n// ab\n// bc\n// cd\n// de\n// ef\n// f\n</code></pre>\n<p>which your implementation does not produce. I don't think you need the condition inside <code>next()</code> at all, the following should suffice instead:</p>\n<pre><code>j = Math.min(i + len, src.length());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:08:22.083", "Id": "518316", "Score": "0", "body": "No, once the last character is taken, it should end. `ab, bc, cd, de, ef` is the desired output for your call (that my code produces)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:23:00.007", "Id": "518318", "Score": "1", "body": "Ah I see, then my second point is not applicable for your use case. I would suggest adding comments to the if-block as the way it‘s written might be confusing to some readers (as it was for me)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:29:17.263", "Id": "518319", "Score": "0", "body": "Done; maybe you can edit your answer as well. Also, looking for the suggestion about a more idiomatic way of doing it. Is my code idiomatic enough (although I see that `StringSupport` is documented to be useful for library writers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:36:12.500", "Id": "518321", "Score": "0", "body": "Will do, once I‘m back at my PC. Sadly I don‘t have a lot of useful advice regarding idiomatic Streams in Java. I hope you‘ll get some useful answers!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T11:08:10.790", "Id": "262611", "ParentId": "262604", "Score": "3" } }, { "body": "<ul>\n<li><a href=\"https://google.github.io/styleguide/javaguide.html#s4.1.1-braces-always-used\" rel=\"nofollow noreferrer\">Braces</a> should always be used even if the body of the <code>if</code> or <code>else</code> contains only a single statement.</li>\n<li>Missing input validation: <code>shift=0</code> causes an infinite loop.</li>\n<li><a href=\"https://google.github.io/styleguide/javaguide.html#s4.8.2-variable-declarations\" rel=\"nofollow noreferrer\">One variable per declaration</a>: as @riskypenguin also suggested, avoid declarations in one line like <code>int i = 0, j = Math.min(len, src.length());</code></li>\n</ul>\n<hr />\n<p>Using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html\" rel=\"nofollow noreferrer\">IntStream</a> could be an alternative:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static Stream&lt;String&gt; streamStrings(String src, int len, int shift) {\n long n = (long) Math.ceil( (double) (src.length() - len) / shift ) + 1;\n return IntStream.range(0, src.length())\n .filter(i -&gt; i % shift == 0)\n .mapToObj(i -&gt; src.substring(i, Math.min(i + len, src.length())))\n .limit(n);\n}\n</code></pre>\n<p>Where:</p>\n<ul>\n<li><strong>n</strong>: is the number of strings</li>\n<li><strong>IntStream.range(0, src.length()).filter(i -&gt; i % shift == 0)</strong>: is a cluncky way to iterate from 0 to <code>src.length()</code> incrementing by <code>shift</code>. In Python would be <code>range(0, len(src), shift)</code>.</li>\n<li><strong>limit(n)</strong>: limits the stream to <code>n</code> substrings.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T08:23:56.087", "Id": "518598", "Score": "1", "body": "An alternative way to iterate would be to use `String.iterate(0, i -> i + shift)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T20:49:06.337", "Id": "525478", "Score": "0", "body": "@RoToRa I don't follow. Can you explain more?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:55:11.277", "Id": "262639", "ParentId": "262604", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T06:23:56.303", "Id": "262604", "Score": "3", "Tags": [ "java", "functional-programming", "stream" ], "Title": "Streaming substrings of a string" }
262604
<p>Design a program to calculate the salaries of a company's employees based on the following data:</p> <ul> <li>Number of hours worked.</li> <li>The work shift performed: Morning (m), Afternoon (t), Night (n).</li> <li>The ordinary hourly rate for each of the workers ($ 37.0).</li> </ul> <p>For the calculation of the gross salary, take into account that the afternoon shift is paid at $1.20 more than the ordinary rate, the evening shift is paid at $1.20 more than the ordinary rate, and the night shift is paid at $1.50 more than the ordinary rate.</p> <p>For the calculation of the net salary, certain discounts are made only to those on the night shift according to the following table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">gross salary</th> <th>discount</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">From 2000 to 5000</td> <td>15%</td> </tr> <tr> <td style="text-align: right;">From 8000 to 10000</td> <td>17%</td> </tr> </tbody> </table> </div> <p>You want to print the net salary of each worker.</p> <pre class="lang-py prettyprint-override"><code>ht = int(input('Number of hours worked: ')) tt = str(input('\nm. Morning\nt. Afternoon\nn. Night\n\nOption:: ')) if tt == 'm': r = (0) elif tt == 'a': r = float(1.2*ht) elif tt == 'n': r = float(1.5*ht) s1 = float(ht*37) sb = float(s1+r) if r == 0: sn = float(sb) elif r == (1.2*ht): sn = float(sb) elif r == (1.5*ht): if sb &gt;= 2000 and sb &lt;= 5000: sn = float(sb*0.15) elif sb &gt;= 8000 and sb &lt;=10000: sn = float(sb*0.17) else: sn = float(sb) print('Net salary:',sn) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T07:01:55.423", "Id": "518283", "Score": "0", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T07:02:42.263", "Id": "518284", "Score": "0", "body": "Is there an \"evening\" shift (mentioned in the hourly rates, but not in the list of shifts)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T18:25:37.997", "Id": "518394", "Score": "0", "body": "This should likely be tagged \"homework\"" } ]
[ { "body": "<p>Why do we convert hours worked to <code>int</code>? It seems unethical to steal the workers' partial hours.</p>\n<p>If we don't enter a valid shift identifier, then we silently pay the lowest rate instead of reporting the error.</p>\n<p>The variable names are completely uninformative. It's hard to work out what each means.</p>\n<p>Comparing floating-point numbers for equality (e.g. <code>r == (1.2*ht)</code>) is fragile and shouldn't be done. In this case, we seem to be using it as a proxy for testing <code>tt</code>, so just replace (e.g. <code>tt == 'a'</code>). Given that the first two cases are the same, we only need to test for <code>tt == 'n'</code>.</p>\n<p>All the numeric quantities in the question are baked into the code (we're mixing <em>mechanism</em> with <em>policy</em>). Work out how we can separate these data, so that it's easier to change the rates of pay and discounts in future when these values need updating.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T07:24:32.043", "Id": "262607", "ParentId": "262605", "Score": "1" } }, { "body": "<p>My guess is that this is homework, though you haven't specified. There's at least one major problem with the question you were given: my read is that there are actually <em>four</em> shifts, &quot;evening&quot; included. Also &quot;salary&quot; seems like a strange term for hourly pay. Salaried employees usually don't track hours, though this may be regional.</p>\n<p>It's highly doubtful that a &quot;salary discount of 15%&quot; means &quot;multiply the salary by 15%&quot;; I would expect instead &quot;multiply the salary by (1 - 15%)&quot;.</p>\n<p>Consider adding some structure to your program by representing the shift types as an enumeration. Also, you should be calling into the locale-specific currency formatter.</p>\n<p>All of these, with most of @TobySpeight's feedback also included, suggest:</p>\n<pre><code>from enum import Enum\nfrom locale import currency, setlocale, LC_ALL\nfrom typing import Dict\n\n\nsetlocale(LC_ALL, '')\n\n\nBASE_RATE = 37\nRATES: Dict[str, float]\n\n\nclass Shift(Enum):\n MORNING = 'm'\n AFTERNOON = 'a'\n EVENING = 'e'\n NIGHT = 'n'\n\n global RATES\n RATES = {\n MORNING: 0,\n AFTERNOON: 1.20,\n EVENING: 1.20,\n NIGHT: 1.50,\n }\n\n @property\n def rate(self) -&gt; float:\n return BASE_RATE + RATES[self.value]\n\n def net_pay(self, hours: float) -&gt; float:\n gross = hours * self.rate\n if self is not self.NIGHT:\n return gross\n\n if 2000 &lt;= gross &lt;= 5000:\n discount = 0.15\n elif 8000 &lt;= gross &lt;= 10000:\n discount = 0.17\n else:\n discount = 0\n return gross * (1 - discount)\n\n @classmethod\n def from_stdin(cls) -&gt; 'Shift':\n prompt = '\\n'.join(\n f'{s.value}. {s.name.title()}'\n for s in cls\n ) + '\\nOption: '\n return cls(input(prompt))\n\n\nhours = float(input('Number of hours worked: '))\nshift = Shift.from_stdin()\nprint('Net pay:', currency(shift.net_pay(hours)))\n</code></pre>\n<p>which produces</p>\n<pre><code>Number of hours worked: 100\nm. Morning\na. Afternoon\ne. Evening\nn. Night\nOption: n\nNet pay: $3272.50\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T19:20:03.713", "Id": "262647", "ParentId": "262605", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T06:30:43.177", "Id": "262605", "Score": "0", "Tags": [ "python" ], "Title": "Calculate salary from time worked" }
262605
<p>I am a bit concerned about style (functions, variable names, spacings, etc.). I am also not sure about whether I should return error or panic. What do you think?</p> <pre class="lang-golang prettyprint-override"><code>//SortStructs sorts user-made structs, given that &quot;a&quot; is a pointer to slice of structs //and key's type (which is name of a field by which struct would be sorted) is one of the basic GO types //which will be sorted in ascending order when asc is true and the other way around, fields must be exported func SortStructs(a interface{}, key string, asc bool) error { var ( fName string fPos int valSlice []reflect.Value ) if a == nil { return errors.New(&quot;mysort: given interface is empty&quot;) } structSlicePointer := reflect.ValueOf(a) if structSlicePointer.Kind() != reflect.Ptr { return errors.New(&quot;mysort: given interface is not pointer&quot;) } else if structSlicePointer.Elem().Kind() != reflect.Slice { return errors.New(&quot;mysort: given interface is not pointer to slice&quot;) } //append single structs here for i := 0; i &lt; structSlicePointer.Elem().Len(); i++ { valSlice = append(valSlice, structSlicePointer.Elem().Index(i)) } if valSlice[0].Kind() != reflect.Struct { return errors.New(&quot;mysort: interface is not a struct&quot;) } //search for key here sl := valSlice[0] for ; fPos &lt; sl.NumField(); fPos++ { //range over fields and search for match with key fName = sl.Type().Field(fPos).Name if fName == key { break } } if fPos == sl.NumField() &amp;&amp; fName != key { return errors.New(&quot;mysort: key not found&quot;) } else if !basicGoType(sl.FieldByName(key)) { return errors.New(&quot;mysort: key is not a basic go type&quot;) } sortReflect(valSlice, 0, len(valSlice)-1, key, asc) return nil } func basicGoType(a reflect.Value) bool { return a.Kind() == reflect.Bool || a.Kind() == reflect.Int || a.Kind() == reflect.Int8 || a.Kind() == reflect.Int16 || a.Kind() == reflect.Int32 || a.Kind() == reflect.Int64 || a.Kind() == reflect.Uint || a.Kind() == reflect.Uint8 || a.Kind() == reflect.Uint16 || a.Kind() == reflect.Uint32 || a.Kind() == reflect.Uint64 || a.Kind() == reflect.Complex64 || a.Kind() == reflect.Complex128 || a.Kind() == reflect.Float32 || a.Kind() == reflect.Float64 || a.Kind() == reflect.String } func aLessThanBReflect(a reflect.Value, b reflect.Value) bool { switch a.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: int1 := a.Int() int2 := b.Int() return int1 &lt; int2 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: uint1 := a.Uint() uint2 := b.Uint() return uint1 &lt; uint2 case reflect.Bool: bool1 := a.Bool() bool2 := b.Bool() return !bool1 &amp;&amp; bool2 case reflect.Float32, reflect.Float64: float1 := a.Float() float2 := b.Float() return float1 &lt; float2 case reflect.Complex64, reflect.Complex128: complex1 := a.Complex() complex2 := b.Complex() if real(complex1) == real(complex2) { return imag(complex1) &lt; imag(complex2) } return real(complex1) &lt; real(complex2) case reflect.String: str1 := a.String() str2 := b.String() return str1 &lt; str2 } return false } //This is Hoare partition scheme adapted for this code func partitionReflect(a []reflect.Value, low, high int, key string, asc bool) int { pivot := a[int((high+low)/2)] low -= 1 high += 1 for { if asc { low += 1 for a[low].FieldByName(key) != pivot.FieldByName(key) &amp;&amp; aLessThanBReflect(a[low].FieldByName(key), pivot.FieldByName(key)) { low += 1 } high -= 1 for a[high].FieldByName(key) != pivot.FieldByName(key) &amp;&amp; !aLessThanBReflect(a[high].FieldByName(key), pivot.FieldByName(key)) { high -= 1 } } else { low += 1 for a[low].FieldByName(key) != pivot.FieldByName(key) &amp;&amp; !aLessThanBReflect(a[low].FieldByName(key), pivot.FieldByName(key)) { low += 1 } high -= 1 for a[high].FieldByName(key) != pivot.FieldByName(key) &amp;&amp; aLessThanBReflect(a[high].FieldByName(key), pivot.FieldByName(key)) { high -= 1 } } if low &gt;= high { return high } //allocate memory for struct and copy a[low]'s value here //couldn't do temp := a[low].Interface() because it shared 1 memory adress temp := reflect.New(a[low].Type()).Interface() temp = a[low].Interface() a[low].Set(a[high]) a[high].Set(reflect.ValueOf(temp)) } } func sortReflect(a []reflect.Value, low, high int, key string, asc bool) { if low &lt; high { p := partitionReflect(a, low, high, key, asc) sortReflect(a, low, p, key, asc) sortReflect(a, p+1, high, key, asc) } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:30:12.897", "Id": "518727", "Score": "0", "body": "Did you write this just for fun to learn reflection, or is it something you intend to use in real code? The use of reflection for this kind of thing is rare and frowned on in Go, because it's error prone (errors happen at runtime, not compile time) and slow. You can just rewrite it with a one-liner call to `sort.Slice`, like [this](https://play.golang.org/p/JWQ--rjKX-j)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T07:47:08.407", "Id": "518749", "Score": "1", "body": "I wrote it just for the sake of it, I wanted to implement sorting myself" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T07:32:00.027", "Id": "262608", "Score": "3", "Tags": [ "sorting", "go" ], "Title": "I recently wrote sort of structs in golang" }
262608
<p>The first time I used <code>strtok</code>, it felt, well, weird. But after a while, I became quite used to it. In a way it was simple. Soon after reading a bunch of Stack Overflow comments and posts about this function, I came to realize that this isn't what I <em>should</em> use in the long run.</p> <p>Personally, my biggest problem with <code>strtok</code> was that it was a destructive function. So today I just wanted to make a version of it that <strong>non-destructive</strong>.</p> <p>So the way this new version is going to be used, is just the same as <code>strtok</code>.</p> <pre><code>token = get_token while token is valid (do something with the token) token = get_token </code></pre> <p>The only change I made (to make my job somewhat easier) is instead of a <code>char *</code> delimiter, I'm taking an <code>int</code>. So the function signature is now</p> <pre class="lang-c prettyprint-override"><code>char *tokenize(const char *__src, int delim); </code></pre> <p>Before looking at the source code, let me show you how much identical this function is in regard to the <code>strtok</code> function using a snippet.</p> <pre class="lang-c prettyprint-override"><code>char string[] = &quot;The exec() functions return only if an error has occurred. The return &quot; &quot;value is - 1, and errno is set to indicate the error.&quot;; char *token = tokenize(string, ' '); while (token) { printf(&quot;'%s'\n&quot;, token); token = tokenize(NULL, ' '); } </code></pre> <p><em>This solution is made from an educational perspective, nothing more. I'm not claiming this to be a viable alternative to <code>strtok</code>.</em></p> <hr /> <h4>To briefly explain how I've written this function</h4> <p>The function returns a <code>malloc</code>'d <code>char *</code> that contains the token. Instead of allocating just the amount of memory required to store the substring, it allocates 8 more bytes to store the index address from the source <code>char *</code> that will be used in the next iteration to look for the next token.</p> <p>It also frees the previous <code>malloc</code>'d block upon each iteration. Yes, if you don't go through the whole string, you'll have a memory leak (or you'll have to add a weird call to <code>free</code> yourself with the correct address, <code>- sizeof(char *)</code> being the offset).</p> <p>I'm using <code>assert</code> to handle the errors, as it's faster and simple enough for this situation, and most importantly gets the job done.</p> <hr /> <h4>The source</h4> <pre class="lang-c prettyprint-override"><code>char *tokenize(const char *__src, int delim) { static const char *src; static char *token; const char *start_pos_loc; if (__src) { src = __src; } if (!token) { start_pos_loc = src; } else { memcpy(&amp;start_pos_loc, token - sizeof(char *), sizeof(char *)); free((void *)token - sizeof(char *)); } size_t substring_length = 0; const char *ptr; for (ptr = start_pos_loc; *ptr != 0 &amp;&amp; *ptr != delim; ptr++) { substring_length++; } if (!substring_length) { return NULL; } // Skipping the final delimiter. ptr++; token = malloc(substring_length + 1 + sizeof(char *)); assert(token); memcpy(token, &amp;ptr, sizeof(char *)); token += sizeof(char *); memcpy(token, start_pos_loc, substring_length); token[substring_length] = 0; return token; } </code></pre> <p>One of the things that I'm mostly looking forward to, is knowing if I'm using <code>const</code> correctly or not.</p> <p>Apart from that, take the following <code>main</code> function for example:-</p> <pre class="lang-c prettyprint-override"><code>int main() { char string[] = &quot;Hello World! How is life now?&quot;; char *token = tokenize(string, ' '); while (token) { printf(&quot;'%s'\n&quot;, token); token = tokenize(NULL, ' '); } return 0; } </code></pre> <p>After running it under valgrind, I'm getting this error:-</p> <pre><code>==42519== Conditional jump or move depends on uninitialised value(s) ==42519== at 0x109287: tokenize (in /home/debdut/Documents/cpp/a.out) ==42519== by 0x1093F9: main (in /home/debdut/Documents/cpp/a.out) </code></pre> <p>Any idea where might this be coming from?</p> <p>Thank you : )</p>
[]
[ { "body": "<blockquote>\n<pre><code> token = malloc(substring_length + 1 + sizeof(char *));\n assert(token);\n</code></pre>\n</blockquote>\n<p>This <code>assert()</code> is wrong. You're claiming that <code>malloc()</code> can't return a null pointer - but it can, and does.</p>\n<p>You'll need to examine <code>token</code> and return a failure indicator if it's null, before the <code>assert()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:02:14.293", "Id": "262614", "ParentId": "262613", "Score": "0" } }, { "body": "<p>Your code is too complicated.</p>\n<p>No wonder you try to simplify by using debugging-constructs for release error-detection.</p>\n<ol>\n<li><p>Don't try to shoehorn a third variable somewhere into the dynamic allocation. The awkwardness is unneeded. Especially as you only need two static pointers: the returned token, and the resume position.</p>\n</li>\n<li><p>You have the choice: <code>free()</code>+<code>malloc()</code> or <code>realloc()</code>/<code>free()</code>. The former potentially wastes time.</p>\n</li>\n</ol>\n<pre><code>char* tokenize(const char* restrict s, int c) {\n static const char *p\n static char *r;\n s = p = s ? s : p;\n assert(s);\n if (!*s) {\n free(r);\n r = 0;\n return 0;\n }\n while (*p &amp;&amp; *p != c)\n ++p;\n r = realloc(r, p - s + 1);\n if (!r) {\n fprintf(stderr, &quot;Could not allocate memory for a token.\\n&quot;);\n abort();\n }\n memcpy(r, s, p - s);\n r[p - s] = 0;\n if (*p) ++p;\n return r;\n}\n</code></pre>\n<p>That was done under the assumption that you really want <code>tokenize()</code> to manage the token. There are other arguably better designs:</p>\n<ol>\n<li><p>Simply handing it off to the caller and letting him free it when its time. Probably not significantly less efficient, often better as a copy is needed anyway.</p>\n</li>\n<li><p>Simply return start- and end-pointer, and let the caller do whatever he wants. Simpler and more flexible, though often more cumbersome to use.</p>\n</li>\n</ol>\n<p>Possible alternative reentrant design:</p>\n<pre><code>typedef struct tokenize_context {\n const char *input;\n char *token;\n} tokenize_context;\n\nchar* tokenize(tokenize_context* restrict p, int c) {\n assert(p &amp;&amp; p-&gt;input);\n if (!*p-&gt;input) {\n free(p-&gt;token);\n p-&gt;token = 0;\n return 0;\n }\n const char* const begin = p-&gt;input;\n while (*p-&gt;input &amp;&amp; *p-&gt;input != c)\n ++p-&gt;input;\n p-&gt;token = realloc(p-&gt;token, p-&gt;input - begin + 1);\n if (!p-&gt;token) {\n fprintf(stderr, &quot;Could not allocate memory for a token.\\n&quot;);\n abort();\n }\n memcpy(p-&gt;token, begin, p-&gt;input - begin);\n p-&gt;token[p-&gt;input - begin] = 0;\n if (*p-&gt;input) ++p-&gt;input;\n return p-&gt;token;\n}\n</code></pre>\n<p>Used like:</p>\n<pre><code>tokenize_context ctx{&quot;The quick brown fox jumps over the lazy dog.&quot;};\nwhile (tokenize(&amp;ctx, ' ')) {\n // Use ctx.token, or return-value from the above call\n // May steel ctx.token by setting to 0\n // May free ctx.token for early stop\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:00:07.960", "Id": "262622", "ParentId": "262613", "Score": "1" } } ]
{ "AcceptedAnswerId": "262622", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T12:26:34.823", "Id": "262613", "Score": "1", "Tags": [ "c", "strings", "memory-management" ], "Title": "A [non-destructive] better (not really) `strtok` function" }
262613
<p>I was working on one telgram bot, and when finally i made everything i discovered that it is extremely slow. def s takes 5-7 seconds to get result and send it to user, i tried to optimise it with methods from other sites, but it didn't work. How can i optimise it?</p> <pre><code>import telebot import pyscp from googlesearch import search scp = &quot;scp-&quot; bot = telebot.TeleBot(&quot;NO&quot;) def extract_arg(arg): return arg.split()[1:] @bot.message_handler(commands=['o']) def o(message): global status status = extract_arg(message.text) try: object = status[0] except Exception as e: object =&quot;7777&quot; l = scp + object url = &quot;scpfoundation.net/&quot; + l ru_wiki = pyscp.wikidot.Wiki('scpfoundation.net') p = ru_wiki(l) try: k = ('{}'.format(p.title)) text = (f'&lt;a href=&quot;{url}&quot;&gt;{k}&lt;/a&gt;') except Exception as e: text=&quot;Простите, этот номер не присвоен не одному из объектов&quot; bot.send_message(message.chat.id, text,parse_mode='HTML') def extract_argument(argument): return argument.split()[3:] @bot.message_handler(commands=['s']) def s(m): status1 = m.text status2 = status1.replace('/s', &quot;&quot;) f = open(&quot;base.txt&quot;, &quot;r&quot;) searchlines = [line.strip() for line in f. readlines() if line.strip()] f.close() out = [] out1=[] try: for i, line in enumerate(searchlines): if status2.lower() in line.lower(): for l in searchlines[i : i + 1]: out.append(l.split(maxsplit=1)[0]) out1.append(l.split(maxsplit=1)[1]) except Exception as e: bot.send_message(m.chat.id, &quot;Простите, не смог ничего найти.&quot;,parse_mode='HTML') pass finalout = list(set(out)) number = len(finalout) g, nm, count, count1, gey =[], int(&quot;0&quot;), int(&quot;0&quot;), int(&quot;0&quot;), [] while (nm&lt;number): url = 'http://scpfoundation.net/' try: ru_wiki = pyscp.wikidot.Wiki('scpfoundation.net') p = ru_wiki(finalout[count]) k = ('{}'.format(p.title)) gey.append(k) result = &quot; &quot;.join ([url, finalout[count]]) g.append(f'&lt;a href=&quot;{result}&quot;&gt;{k}&lt;/a&gt;') except Exception as e: pass count+=1 count1+=1 nm+=1 numbeer=int('0') counter=int('0') ka = search(f'{status2} site:scpfoundation.net', num_results=4) while (numbeer&lt;5): try: ru_wiki = pyscp.wikidot.Wiki('scpfoundation.net') p = ru_wiki(ka[counter]) kj = ('{}'.format(p.title)) if (kj not in gey and &quot;forum&quot; not in ka[counter] and &quot;draft&quot; not in ka[counter] and &quot;fragment&quot; not in ka[counter]): result = ka[counter] g.append(f'&lt;a href=&quot;{result}&quot;&gt;{kj}&lt;/a&gt;') except Exception as e: pass numbeer+=1 counter+=1 story = '\n'.join(g) try: bot.send_message(m.chat.id, story,parse_mode='HTML') except Exception as e: bot.send_message(m.chat.id, &quot;Простите, ничего не найдено.&quot;, parse_mode='HTML') @bot.message_handler(commands=['help']) def help(t): bot.send_message(t.chat.id, &quot;/o — поиск по номеру; /s — поиск по названию; /help — это сообщение; /join — присоеденится к сообществу; /faq — ответы на частые вопросы&quot;,parse_mode='HTML') @bot.message_handler(commands=['join']) def join(j): joiner=(f'&lt;a href=&quot;http://scpfoundation.net/system:join&quot;&gt;Подай простую заявку!&lt;/a&gt;') bot.send_message(j.chat.id, joiner,parse_mode='HTML') @bot.message_handler(commands=['faq']) def faq(f): faqer=(f'&lt;a href=&quot;http://scpfoundation.net/faq&quot;&gt;Читать тут.&lt;/a&gt;') bot.send_message(f.chat.id, faqer,parse_mode='HTML') bot.polling() </code></pre> <p>The problem is with <code>while (numbeer&lt;5)</code> 5 is number of urls i grab from google search, and less urls i grab less times it need. I can't reduce the numbers of urls, so maybe i can optimise another part of code to reduce the time?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:27:05.397", "Id": "518330", "Score": "0", "body": "What does the code do? Why does a \"telegram bot\" need to fetch 5 urls ?" } ]
[ { "body": "<p>There are a number of issues, but I'm guessing that the major slowdown in <code>s()</code> is due to the unnecessarily repeated calls to <code>pyscp.wikidot.Wiki('scpfoundation.net')</code>.</p>\n<p>This web request is done once for each match in <code>searchlines</code> and then done 5 more times again. I'm assuming this is the exact same data retrieved every time.</p>\n<p>You should do this only once in <code>s()</code> at most in my opinion then use the saved result inside your while loops.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:42:46.860", "Id": "518351", "Score": "0", "body": "What are other issues? This answer helped me very much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:56:55.927", "Id": "518357", "Score": "0", "body": "When you `enumerate(searchlines)` in `s()` for example, you have a nested `for` loop that returns you `l` but you already know `l` as `line` from the outer loop, So that inner `for` is not likely doing anything to help. (unless of course I have misinterpreted things)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:39:49.730", "Id": "518376", "Score": "0", "body": "It helps me to split line in right way, but thx" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:58:35.070", "Id": "262628", "ParentId": "262615", "Score": "1" } } ]
{ "AcceptedAnswerId": "262628", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:02:55.500", "Id": "262615", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "telegram" ], "Title": "Optimizing telegram bot" }
262615
<p>I'm doing the following challenge from leetcode.com, that requires merging a list of lists. <a href="https://leetcode.com/problems/merge-k-sorted-lists/" rel="nofollow noreferrer">https://leetcode.com/problems/merge-k-sorted-lists/</a></p> <p>This is the challenge:</p> <blockquote> <p>You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.</p> <p>Merge all the linked-lists into one sorted linked-list and return it.</p> </blockquote> <p>This is my code. It looks correct, but a test shows &quot;Time limit exceeded&quot; upon submission. How can I make it faster?</p> <pre><code>(define (all-empty? lists) (andmap false? lists)) (define (least-lists-head lists) (exact-round (apply min (map (lambda (lst) (if (false? lst) +inf.0 (list-node-val lst))) lists)))) (define (least-list-head-removed lists remove-head) (if (empty? lists) lists (if (not (equal? (if (car lists) (list-node-val (car lists)) #f) remove-head)) (cons (car lists) (least-list-head-removed (cdr lists) remove-head)) (cons (if (not (false? (car lists))) (list-node-next (car lists)) #f) (cdr lists))))) (define (merge-lists lists merged-list) (if (all-empty? lists) (list-node-next merged-list) (list-node (least-lists-head lists) (merge-lists (least-list-head-removed lists (least-lists-head lists)) merged-list )))) (define (merge-k-lists lists) (merge-lists lists (list-node -1 #f))) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:14:51.800", "Id": "518369", "Score": "2", "body": "Welcome to the Code Review Community. It would be helpful if you quoted the text of the programming challenge in the question and the `title` told us about what the code does. We get a lot of questions about optimizing code so the question is hard to identify without more information. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:23:55.953", "Id": "262618", "Score": "0", "Tags": [ "programming-challenge", "racket" ], "Title": "Merging a list of lists" }
262618
<p>code climate tells me this block of code has a Cognitive Complexity of 7 (exceeds 5 allowed). Any ideas how I would refactor this to reduce complexity?</p> <pre><code>const validateDays = (param, days, dateValues) =&gt; { if (!days || !param) { return; } else if (param === 'from' &amp;&amp; dateValues) { const disabledDays = { before: days.before, after: parse(dateValues['to']) }; return { disabledDays }; } else if (param === 'to' &amp;&amp; dateValues) { const disabledDays = { before: parse(dateValues['from']), after: days.after }; return { disabledDays }; } else { return { days }; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:04:10.137", "Id": "518326", "Score": "0", "body": "sometimes code just is as complex as it is. Do **you** think your code is too complex? Or do you just want to get CodeClimate to shut up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:57:14.910", "Id": "518339", "Score": "1", "body": "@Vogel612 I agree sometimes code is just complex. But improving readability will certainly help us understand it better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:19:45.400", "Id": "518344", "Score": "2", "body": "Please follow out guidelines WRT the title: https://codereview.stackexchange.com/help/how-to-ask" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:06:43.887", "Id": "518364", "Score": "1", "body": "As @BCdotWEB the title should tell us what the code does rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:56:36.150", "Id": "518388", "Score": "1", "body": "@MalcolmMaima Welcome to CR! In addition to the suggestions for improvement so far, it's worth explaining the specification for this code in English. What is it supposed to validate? What do some sample calls look like? This context might lead to a fundamentally different approach that totally avoids the complexity problem. I also notice the post is tagged [tag:react.js] but I don't see any obvious connection to React per se, so you might want to justify why the tag is present by describing the larger app context as an [edit](https://codereview.stackexchange.com/posts/262621/edit) to your post" } ]
[ { "body": "<p>Since every <code>if</code> statement also has a <code>return</code>, you don't need the <code>else</code>, you can just start the next <code>if</code> without typing <code>else</code>.</p>\n<p>This reduces the &quot;indentation&quot; and keeps the code &quot;flat&quot; (for lack of better words) and I think this would reduce the complexity, although I'm not familiar with &quot;Code climate&quot;.</p>\n<p>I think the nested if-else-if-else structure actually goes one level deeper each time, causing the warning that you have.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:23:27.260", "Id": "262624", "ParentId": "262621", "Score": "1" } }, { "body": "<h2>Complexity</h2>\n<p>Any code metric associated with readability is a subjective quantity. Cognitive complexity is one such metric and should be viewed with a good dose of skepticism.</p>\n<p>Personally (to make up a metric) I would give your code a value of 1 where values over 0 are bad.</p>\n<p>Why does it get 1? Because you use the same clause 2 times, which is 1 too many.</p>\n<p>The value <code>dateValues</code> is checked twice</p>\n<pre><code> } else if (param === 'from' &amp;&amp; dateValues) {\n ...\n } else if (param === 'to' &amp;&amp; dateValues) {\n ...\n</code></pre>\n<p>Checking the value only once means no redundancy</p>\n<pre><code> } else if (dateValues) {\n if (param === 'from') {\n ...\n } else if (param === 'to') {\n ...\n }\n }\n\n</code></pre>\n<h2>Cognitive Complexity</h2>\n<p>Which in my book is a dumber version of cyclic complexity.</p>\n<p>Both metrics (cyclic and cognitive) can be reduced not by reducing complexity, but by tricking the parser into thinking the code is less complex.</p>\n<p>Thus the following will likely get a lesser score than your original.</p>\n<pre><code>const validateDays = (param, days, dateValues) =&gt; {\n const dirs = {\n get from: () =&gt; ({before: days.before, after: parse(dateValues.to)}),\n get to: () =&gt; ({before: parse(dateValues.from, after: days.after)}), \n };\n return days &amp;&amp; param ? (dateValues ? dirs[param] ?? {days} : {days}) : undefined; \n}\n</code></pre>\n<p>However there are many here that consider nested ternaries as extremely complex (not my view).</p>\n<h2>Code quality</h2>\n<p>Personally I consider the bugs per line multiplied by line count the best metric for code quality.</p>\n<p>Bugs per lines is a quantity defined by each coder. New coders have high values and this value goes down as you gain experience. The actual value is very hard to know, hence we can revert to the scalar line count as a good approximation. On average coders have a bug per line of ~ 1/100</p>\n<p>Reducing line count is the best thing new coders can do to increase code quality.</p>\n<p>Thus using the if else style your code can be</p>\n<pre><code>const validateDays = (param, days, dateValues) =&gt; {\n if (!(days &amp;&amp; param)) { return }\n var res = {days};\n if (dateValues) {\n if (param === &quot;from&quot;) {\n res = {disabledDays: {before: days.before, after: parse(dateValues.to)}};\n } else if (param === &quot;to&quot;) {\n res = {disabledDays: {before: parse(dateValues.from), after: days.after}};\n }\n }\n return res;\n}\n</code></pre>\n<p>Has a line count of 12 as opposed to your 19 lines, and may also get a lower cognitive complexity score.</p>\n<p>or</p>\n<pre><code>const validateDays = (param, days, dateValues) =&gt; {\n if (!(days &amp;&amp; param)) { return }\n var res = {days};\n if (dateValues) {\n param === &quot;from&quot; &amp;&amp;\n (res = {disabledDays: {before: days.before, after: parse(dateValues.to)}});\n param === &quot;to&quot; &amp;&amp;\n (res = {disabledDays: {before: parse(dateValues.from), after: days.after}});\n }\n return res;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:14:44.333", "Id": "518479", "Score": "0", "body": "Love your approach, definitely super helpful. Do get a complexity of 6 still above the threshold but I guess I can work with that for now" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:48:56.150", "Id": "262638", "ParentId": "262621", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:48:50.593", "Id": "262621", "Score": "0", "Tags": [ "javascript", "react.js" ], "Title": "How to refactor and reduce complexity of this code" }
262621
<p>An Object-relational mapper built using PHP.</p> <p><strong>This question is related to this old question.</strong> (<a href="https://codereview.stackexchange.com/q/261272/218131">Object relational mapper - optimize in memory data representation and code improvements</a>)</p> <h6>This was done for educational purposes, and curious to know what kind of improvement has to be done to use in production.**</h6> <h6>Please refer to the complete source code in the Github repository - (<a href="https://github.com/maleeshagimshan98/infinite-simple-orm" rel="nofollow noreferrer">https://github.com/maleeshagimshan98/infinite-simple-orm</a>)</h6> <p>Below, I've described the internal workings...</p> <ul> <li><p><em>Entity Manager Class</em></p> <ul> <li><p>This is the main instance we are interacting with.</p> </li> <li><p>Use it to retrieve and Create/Update data</p> </li> <li><p>It uses Entity objects and their attributes to build the query and execute the query.</p> </li> <li><p>Handles associations with other Entities using entity attributes (<code> $Entity-&gt;associations-&gt;get()</code>)</p> </li> <li><p>Uses <code>ChangeTracker</code> class to track changes made to retrieved objects and update them on the database accordingly.</p> </li> </ul> </li> <li><p><em>Entity Class</em></p> <ul> <li><p>Represent an entity in the database.</p> </li> <li><p>Has attributes of entity and column mappings to attributes for respective table</p> </li> <li><p>Has associations info that Entity has.</p> </li> </ul> </li> <li><p>Entity class structure is here,</p> <ul> <li><strong>Entity class</strong> <ul> <li><em>associations</em> are managed using <code>AssociatedEntityContainer</code> class.</li> <li><em>attribs</em> - attribute to column mapping, managed by <code>AttributeMapContainer</code> class</li> </ul> </li> </ul> </li> </ul> <h4>AttributeMapContainer Class</h4> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity's Attribute Map Container Class */ namespace Infinite\DataMapper\Entity; /** * Associated entity container */ class AttributeMapContainer { /** * entity attributes map - [ 'attribute' =&gt; 'column_name'] * * @var array */ protected $attrib_map = []; /** * inverse of attribute mapping to column * * @var array */ protected $attrib_map_inverse = []; /** * entity's primary keys * * @var array */ protected $primary = []; /** * entity's properties (eg - autoIncrement) * * @var array */ protected $properties = []; /** * read-only properties in entity (eg - AUTO INCREMENTED values) * * @var array */ protected $readOnlyProps = [ &quot;autoIncrement&quot; ]; /** * constructor */ public function __construct () { } /** * get a single attribute_map element * * @param string $attrib attrib_map element name * @return string attribute_map element * @throws \Exception */ protected function map ($attrib = null) { if (!isset($this-&gt;attrib_map[$attrib])) { throw new \Exception(&quot;Undefined_Attribute&quot;); } return $this-&gt;attrib_map[$attrib]; } /** * get entity's primary keys * * @return array */ public function primary () { return $this-&gt;primary; } /** * set primary key * * @param object $attrib * @return void */ protected function setPrimaryKey ($key) {//echo \json_encode($key); if ($key-&gt;primary !== false) { $this-&gt;primary[] = $key-&gt;primary; } } /** * set entity's properties * * @param object $properties object containing properties of entity attribute * @return void */ protected function setProperties ($properties) { if (isset($properties[&quot;autoIncrement&quot;])) { $this-&gt;properties[&quot;autoIncrement&quot;][] = $properties[&quot;autoIncrement&quot;]; } } /** * get entity attribute's properties * * @param string $name property name (eg - autoIncrement) * @return array * @throws \Exception */ public function getProperties ($name) { if (!isset($this-&gt;properties[$name])) { throw new \Exception(&quot;Undefined_Property&quot;); } return $this-&gt;properties[$name]; } /** * sets the attribute's name with respect of configuration options * * @param string $attribName attribute name entity * @param string|object $attrib attribute options (if any), or (similar as $attribName) * @return object */ protected function parseAttribute ($attribName,$attrib) { $result = (object) [&quot;name&quot; =&gt; &quot;&quot;, &quot;primary&quot; =&gt; false, &quot;properties&quot; =&gt; []]; //if property is an association if ($attribName === &quot;_assoc&quot;) { $result = false; return $result; } if (\is_object($attrib)) { if (!empty($attrib-&gt;name)) { $result-&gt;name = $attrib-&gt;name; } if (isset($attrib-&gt;primary) &amp;&amp; $attrib-&gt;primary == true) { //attribs with primary key, but no name comes here $result-&gt;primary = $attrib-&gt;name ?? $attribName; $result-&gt;name = $attrib-&gt;name ?? $attribName; } if (isset($attrib-&gt;autoIncrement) &amp;&amp; $attrib-&gt;autoIncrement == true) { $result-&gt;properties[&quot;autoIncrement&quot;] = $attrib-&gt;name ?? $attribName; } } elseif (is_string($attrib)) { $result-&gt;name = $attrib; } return $result; } /** * set entity's attributes * * @param string|object $attrib * @return void */ public function init ($attrib) { foreach ($attrib as $key =&gt; $values) { $attribute = $this-&gt;parseAttribute($key,$values); if ($attribute) { //setting the attribute mapping to columns $this-&gt;set($key,$attribute-&gt;name); $this-&gt;setPrimaryKey($attribute); if (\count($attribute-&gt;properties) &gt; 0) { $this-&gt;setProperties($attribute-&gt;properties); } } } } /** * get writable attributes of entity, mapped to columns * * @return array */ public function getWritableAttribsMapped () { try { $readOnly = []; foreach ($this-&gt;readOnlyProps as $key) { $readOnly = array_merge($readOnly,$this-&gt;getProperties($key)); } return array_diff($this-&gt;getMapped(),$readOnly); } catch (\Exception $e) { return $this-&gt;getMapped(); } } /** * get column names of entity attributes * * @param mixed $attribute * @return string|array * @throws \Exception */ public function getMapped ($attribute = null) { if (empty($attribute)) { return array_values($this-&gt;attrib_map); } if (is_array($attribute)) { $arr = []; foreach ($attribute as $key) { $arr[] = $this-&gt;map($key); } return $arr; } return $this-&gt;map($attribute); /** if $attribute === String */ } /** * map entity attributes of column names * * @param string $attribute * @return string|array * @throws \Exception */ protected function mapAttribs ($attribute) { if ($attribute === null) { return array_keys($this-&gt;attrib_map_inverse); //check } if (!is_null($attribute) &amp;&amp; !isset($this-&gt;attrib_map_inverse[$attribute])) { throw new \Exception(&quot;Undefined_Attribute&quot;); } else { $attrib; foreach ($this-&gt;attrib_map_inverse as $key =&gt; $val) { //PUT THIS LOGIC INTO THE COMMON CLASS if ($key === $attribute) { $attrib = $val; break; } } return $attrib; } } /** * get entity's attributes * * @param mixed $attribute attribute name/s * @return array */ public function getAttribs ($attribute = null) { if (\is_array($attribute)) { $arr = []; foreach($attribute as $key) { $arr[] = $this-&gt;mapAttribs($key); } return $arr; } return $this-&gt;mapAttribs($attribute); } /** * set entity attributes and mapping column names * * @param string $name * @param string $attrib * @return void */ public function set ($name,$attrib) { $this-&gt;attrib_map[$name] = $attrib; $this-&gt;setInverseMap($attrib,$name); } /** * set attrb_map's inverse * * @param string $name * @param string $attrib * @return void */ protected function setInverseMap ($name,$attrib) { $this-&gt;attrib_map_inverse[$name] = $attrib; } /** * get attrib_map's inverse * * @return array */ public function getInverseMap () { return $this-&gt;attrib_map_inverse; } } </code></pre> <h3>AssociatedEntityContainer Class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Associated Entity Container Class */ namespace Infinite\DataMapper\Entity; /** * Associated entity container */ class AssociatedEntityContainer { /** * entity association data * * @var array */ protected $associations = []; protected $associationKeys = []; /** * currently associated entities on this entity * * @var array */ protected $currentAssociated = []; /** * constructor */ public function __construct () { } /** * get an association * * @param string $association * @return string * @throws \Exception */ public function get ($association = null) { if (empty($association)) { return $this-&gt;associations; } if (!isset($this-&gt;associations[$association])) { throw new \Exception(&quot;Undefined_Association&quot;); } return $this-&gt;associations[$association]; } /** * get associations key names * * @return array */ public function getAssociationKeys () { return $this-&gt;associationKeys; } /** * set an association * * @param object $data * @return void * @throws \Exception */ public function set ($data) { foreach ($data as $key =&gt; $value) { $this-&gt;associationKeys[] = $key; if (empty($value-&gt;target)) { throw new \Exception(&quot;Target_Entity_Undefined&quot;); return; //IMPORTANT CHECK WHAT HAPPENS IN CASE OF ERROR } $this-&gt;associations[$key] = $value; } } } ?&gt; </code></pre> <h3>Entity Class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * base class for defining entities * in the database */ namespace Infinite\DataMapper; use Infinite\DataMapper\Entity\AttributeMapContainer; use Infinite\DataMapper\Entity\AssociatedEntityContainer; use Infinite\DataMapper\Entity\EntityResult; /** * Entity class * represents an entity */ class Entity { protected $qb; /** * entity name * * @var string */ public $entityName; /** * entity's attributes * * @var Infinite\DataMapper\Entity\AttributeContainer */ public $attribs; /** * entity's property names * * @var Infinite\DataMapper\Entity\EntityResult object */ protected $entityResult; /** * entity table's name * * @var string */ protected $entity_table = &quot;&quot;; /** * entity associations with other entities * * @var Infinite\DataMapper\Entity\AssociatedEntityContainer */ public $associations; /** * entity's data limit - for pagination * * @var integer */ protected $limit = 10; /** * constructor * * @param string $name database table name of the entity * @param array|object $attribs * @return void * @throws \Exceptions */ public function __construct ($attribs,$name) { if (!$attribs) { throw new \Exception(&quot;Invalid_Entity_Definition&quot;); } $this-&gt;attribs = new AttributeMapContainer(); $this-&gt;associations = new AssociatedEntityContainer(); $this-&gt;entity_table = $name; $this-&gt;init($attribs,$name); } /** * get entity table * * @return string */ public function table () : string { return $this-&gt;entityTable; } /** * get entity's name * * @return string */ public function name () { return $this-&gt;entityName; } /** * get primary key * * @return string|array */ public function primary () { return $this-&gt;attribs-&gt;primary(); } /** * initialize entity's properties * * @param string|array $prop * @return void */ public function initProps ($prop) { if (!$prop) { return; } if (is_array($prop)) { foreach ($prop as $key) { $this-&gt;$key = null; } return; } $this-&gt;$prop = null; } /** * validate data with defined data types * * @param mixed - data * @return boolean */ public function validate ($props) { } /** * map entity attributes from configuration * * @param object $attribs entity attributes * @param string $name entity table name * @return AttributeMapContainer attribute map container */ protected function init ($attribs,$name) : AttributeMapContainer { /* TESTING */ //echo \json_encode($attribs); $keys = []; if ($this-&gt;entity_table == &quot;&quot;) { $this-&gt;entity_table = $name; } $this-&gt;attribs-&gt;init($attribs); if (isset($attribs-&gt;_assoc)) { $this-&gt;associations-&gt;set($attribs-&gt;_assoc); } //$this-&gt;initEntityResult(); return $this-&gt;attribs; } /** * initialize EntityResult object * * @return void */ protected function initEntityResult () { $keys = $this-&gt;attribs-&gt;getAttribs(); $keys = array_merge($keys,$this-&gt;associations-&gt;getAssociationKeys()); return new EntityResult($keys,$this-&gt;entityName); //always return a new instance } /** * get entity result object * * @return Infinite\DataMapper\Entity\EntityResult object */ public function getEntityResult () { return $this-&gt;initEntityResult(); } /** * format column names with table name * * @param string|array $columns * @return mixed */ protected function withTable ($columns) { if (is_string($columns)) { return $this-&gt;entityTable.&quot;.&quot;.$columns; } if (is_array($columns)) { $formattedColumns = []; foreach ($columns as $key) { $formattedColumns[] = $this-&gt;entityTable.&quot;.&quot;.$key; } return $formattedColumns; } } /** * get entity attributes' column names (any or all) * * @param string|array $attributeName * @return string|array */ public function mapAttribsToColumn ($attributeName = null) { if (\is_null($attributeName)) { return $this-&gt;withTable($this-&gt;attribs-&gt;getMapped()); } if (is_array($attributeName)) { $columns = []; foreach ($attributeName as $val) { $columns[] = $this-&gt;withTable($this-&gt;attribs-&gt;getMapped($val)); } return $columns; } return $this-&gt;withTable($this-&gt;attribs-&gt;getMapped($attributeName)); /* $attributeName === String */ } /** * map column names to entity attributes * * @param mixed $data * @param EntityResult $entityResult * @return EntityResult entity result object */ protected function mapColumnsToAttribs ($data,$entityResult) { $inverseMap = $this-&gt;attribs-&gt;getInverseMap(); foreach ($inverseMap as $key =&gt; $val) { $entityResult-&gt;$val = $data-&gt;$key; } return $entityResult; } /** * hydrate entity with the data fetched from database * * @param array|object $data fetched data from database * @return self */ public function hydrate ($data) { $data = (object) $data; $arr = []; $entityResult = $this-&gt;initEntityResult(); //always returns a new instance return $this-&gt;mapColumnsToAttribs($data,$entityResult); } /** * set a field value * * @param string $attribute attribute name * @param mixed $value attribute's value * @return void * @throws \Exception */ public function set ($attribute,$value) { /** Throws \Exception if attribute not found */ $this-&gt;attribs-&gt;getAttrib($attribute); $this-&gt;$attribute = $value; } /** * get an indexed array of data for insertion, based on entity's atrributes * (only entity owned attributes) * returns an indexed array containing values * * @param [type] $data * @return array */ public function insertProps ($entity) { $arr = []; $attribs = $this-&gt;attribs-&gt;getWritableAttribsMapped(); foreach ($attribs as $key) { $attrib = $this-&gt;attribs-&gt;getAttribs($key); $arr[] = $entity-&gt;$attrib; } return $arr; } } ?&gt; </code></pre> <h2>Entity Manager</h2> <ul> <li>Entity Manager class structure <ul> <li><code>EntityContainer</code> class - containing all entities.</li> <li><code>queryDb</code> class - for querying database.</li> <li><code>QueryBuilderWrapper</code> class - wrapping <code>Enmvs\FluentPdo\Query</code> query bulder class.</li> </ul> </li> </ul> <h3>EntityContainer Class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity Container Class */ namespace Infinite\DataMapper; /** * Entity container */ class EntityContainer { /** * full qualified class name for the entity * * @var string */ protected $base_class_name = &quot;\Infinite\DataMapper\Entity\\&quot;; /** * database schema * * @var object */ protected $dbSchema; /** * entities - [...,\Infinite\DataMapper\Entity\ENTITY_CLASS_NAME] * * @var array */ protected $entities = []; /** * constructor */ public function __construct ($entityDefinition = null) { if(!empty($entityDefinition)) { $this-&gt;parseEntityDefinition($entityDefinition); } } //... /** * create an entity on the go * * @param string $name entity name * @return \Infinite\DataMapper\Entity entity object */ public function entity ($name) { $entityDef = $this-&gt;getDefinition($name); if (!$entityDef) { throw new \Exception(&quot;Undefined_Entity&quot;); } $entityClass = $this-&gt;base_class_name.&quot;$name&quot;; return $this-&gt;entities[$name] = new $entityClass($entityDef,$name); } /** * parse database entity definition * * @param [type] $schema JSON object defining the db schema * @return void */ protected function parseEntityDefinition ($schema) { $arr = []; foreach ($schema as $key =&gt; $val) { $arr[$key] = $val; } $this-&gt;dbSchema = (object) $arr; } /** * get entity definitions * * @param string $name * @return mixed */ protected function getDefinition ($name) { //echo json_encode($name); return $this-&gt;dbSchema-&gt;$name ?? false; } /** * checks if current entities count is zero * * @return boolean */ public function is_empty () { return count($this-&gt;entities) == 0; } /** * Get an entity * * @param string $entity Entity name * @return \Infinite\DataMapper\Entity object * @throws \Exception */ public function get ($entity) { if (empty($this-&gt;entities[$entity])) { return $this-&gt;entity($entity); //throw new \Exception(&quot;Undefined_Entity&quot;); } return $this-&gt;entities[$entity]; } /** * get all entities * * @return array */ public function getAll () { return $this-&gt;entities; } /** * set entity * * @param string $name * @param Infinite\DataMapper\Entity $entity entity object * @return void */ public function set ($name,$entity) { $this-&gt;entities[$name] = $entity; } } ?&gt; </code></pre> <p><strong>For the context of this question other <code>queryDb</code>, <code>QueryBuilderWrapper</code> classes are not relevant, thus not shown here.</strong></p> <h3>Entity Manager class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity Manager class */ namespace Infinite\DataMapper; include_once dirname(__DIR__).&quot;/Products.php&quot;; include_once dirname(__DIR__).&quot;/sku.php&quot;; include_once dirname(__DIR__).&quot;/product_sku.php&quot;; include_once dirname(__DIR__).&quot;/orders.php&quot;; use Infinite\DataMapper\EntityContainer; use Infinite\DataMapper\Entity\EntityResult; use Infinite\DataMapper\ChangeTracker; use Infinite\DataMapper\QueryBuilder\QueryBuilderWrapper; use Infinite\DataMapper\QueryDb; use Infinite\DataMapper\Pagination; /** * Entity manager class */ class EntityManager { /** * PDOConnection * * @var \PDO object */ private $connection; /** * Entities * * @var Infinite\DataMapper\EntityContainer * */ public $entities; /** * current entity * * @var Infinite\DataMapper\Entity */ protected $currentEntity; /** * current associated entities * * @var Infinite\DataMapper\EntityContainer */ protected $currentAssociated; /** * sql statement created when queriying entities * * @var \PDOStatement */ protected $sqlStatement; /** * sql statements created when inserting data * have multiple sql statements * execute all in one transaction * * @var array */ protected $sqlStatementStack = []; /** * CRUD action - select,insert,update,delete * * @var string */ protected $action = &quot;&quot;; /** * constructor * * @param object $config * @return void */ public function __construct (object $config) { $this-&gt;initConfig($config); } /** * initialize Entity manager with configuration * * @param object $config configuration object * @return void * @throws \Exception */ protected function initConfig (object $config) { if (empty($config-&gt;connection)) { throw new \Exception(&quot;Database_Connection_Not_Found&quot;); } $this-&gt;connection = $config-&gt;connection; //CONSIDER REMOVING THIS PROPERTY $this-&gt;entities = new EntityContainer(json_decode(file_get_contents(dirname(__DIR__).&quot;/config/entity_definition.json&quot;))); $this-&gt;currentAssociated = new EntityContainer(); $this-&gt;queryBuilder = new QueryBuilderWrapper($this-&gt;connection); $this-&gt;queryDb = new QueryDb($this-&gt;connection); } /** * return a new entity result object of a respective entity class - when inserting new data * * @param string $entity entity name * @return Infinite\DataMapper\Entity\EntityResult Entity result object * @throws \Exception */ public function entity (string $entityName) { return $this-&gt;entities-&gt;entity($entityName)-&gt;getEntityResult(); } /** * set current entity * * @param string $entity entity name * @return void */ protected function setCurrentEntity ($entity) { $this-&gt;currentEntity = $this-&gt;entities-&gt;get($entity); } /** * clear current entity * * @return void */ protected function clearCurrentEntity () { $this-&gt;currentEntity = null; } /** * prepare basic parts of query string * for getting an entity from database * * @param \Infinite\DataMapper\Entity\ $entity entity object * @return void */ protected function prepareGet ($entity) { /* TESING */ //echo \json_encode($entity); $this-&gt;sqlStatement = $this-&gt;queryBuilder-&gt;from($entity-&gt;table()) -&gt;select($entity-&gt;mapAttribsToColumn()); return $this-&gt;sqlStatement; } /** * get entity from database * * @param string $entity entity name * @param array|null $id get a row based on id [column_name,value] * @return self * @throws \Exception */ public function get ($entity,$id = null) { $this-&gt;action = &quot;select&quot;; $this-&gt;setCurrentEntity($entity); //echo json_encode($this-&gt;currentEntity); $sql = $this-&gt;prepareGet($this-&gt;currentEntity); if (!empty($id)) { $sql = $sql-&gt;where([ $this-&gt;currentEntity-&gt;mapAttribsToColumn($id[0]) =&gt; $id[1] ]); } return $this; /** TESTING */ //echo json_encode(); } /** * associate entities in the result * * @param string $entity associated entity name * @param mixed $joiningEntityId entity id (or foreign key) of associated entity * @return self * @throws \Exception */ public function associate ($entity,$joiningEntityId = null) { $associated = $this-&gt;currentEntity-&gt;associations-&gt;get($entity); $target = $this-&gt;entities-&gt;get($associated-&gt;target); $this-&gt;currentAssociated-&gt;set($associated-&gt;target,$target); //IMPORTANT - CHECK IF THIS IS NEEDED - $target $this-&gt;sqlStatement = $this-&gt;sqlStatement-&gt;leftJoin([ $target-&gt;mapAttribsToColumn($associated-&gt;refer), $this-&gt;currentEntity-&gt;mapAttribsToColumn($associated-&gt;inverse) ])-&gt;select($target-&gt;mapAttribsToColumn()); if (is_array($joiningEntityId)) { $this-&gt;sqlStatement = $this-&gt;sqlStatement-&gt;where( [ $target-&gt;mapAttribsToColumn($joiningEntityId[0]) =&gt; $joiningEntityId[1] ] ); } return $this; } /** * hydrate entity with data fetched from database * * @param array|object $res data fetched from database * @return array */ protected function hydrate ($res) { $this-&gt;tracker = new ChangeTracker(); if (!$res) { return $res; } $currentEntity = $this-&gt;currentEntity; $entityCollection = []; foreach ($res as $key) { $result = $currentEntity-&gt;hydrate($key); //keep track of objects if (!$this-&gt;currentAssociated-&gt;is_empty()) { $result = $this-&gt;hydrateAssociated($result,$key); } $this-&gt;tracker-&gt;addTracking($currentEntity-&gt;name(),$result); $entityCollection[] = $result; } //echo json_encode($entityCollection); return $entityCollection; } /** * hydrate associated entity of the current entity * (only single object from result set, * run this multiple times to hydrate all entities, and associated ones) * * @param Infinite\DataMapper\Entity\EntityResult $entity entiy result object * @param array|object $data data fetched from database * @return Infinite\DataMapper\Entity\EntityResult */ protected function hydrateAssociated ($entity,$data) { $associated = $this-&gt;currentAssociated-&gt;getAll(); foreach ($associated as $key =&gt; $value) { $assocEntityResult = $this-&gt;entities-&gt;entity($key)-&gt;hydrate($data); $entity-&gt;set($key,$assocEntityResult); //$this-&gt;tracker-&gt;addTracking($assoc-&gt;name(),$assoc); } return $entity; } /** * insert data to database - create an insert query * * @param EntityResult $entity entity result object * @param mixed $value values to be inserted * @return void */ protected function insertData ($entity,$value = null) { $this-&gt;action = &quot;insert&quot;; $this-&gt;setCurrentEntity($entity-&gt;name()); if (isset($value)) { $entity-&gt;__setFromObj((object)$value); // $value must be an object } $writableAttribs = $this-&gt;currentEntity-&gt;attribs-&gt;getWritableAttribsMapped(); $insertDataArr = $this-&gt;currentEntity-&gt;insertProps($entity); $sqlStatement[] = $this-&gt;queryBuilder-&gt;insert( $this-&gt;currentEntity-&gt;table(), $writableAttribs, $insertDataArr )-&gt;getSqlString(); //echo $sqlStatement[0]; $sqlStatement[] = $insertDataArr; $this-&gt;sqlStatementStack[] = $sqlStatement; //ONLY MAIN ENTITY IS BEING INSERTED } /** * process primary keys to ypdate entities * * @param EntityResult $entityResult entity result object * @return array */ protected function processPrimaryKeys ($entityResult) { $this-&gt;setCurrentEntity($entityResult-&gt;name()); $primaryKey = $this-&gt;currentEntity-&gt;primary(); $primaryKeyValues = []; $values = []; foreach ($primaryKey as $key) { $attrInverseMap = $this-&gt;currentEntity-&gt;attribs-&gt;getInverseMap(); $primaryKeyMapped = $attrInverseMap[$key]; //check $primaryKeyValues[$key] = $entityResult-&gt;$primaryKeyMapped; $values[] = $entityResult-&gt;$primaryKeyMapped; } return [&quot;pk&quot; =&gt; $primaryKeyValues, &quot;values&quot; =&gt; $values]; } /** * update entity values in database * * @param EntityResult $entity entity result object * @param array $changes - array with key =&gt; values of changes (keys have been mapped to column names) * @return void */ protected function updateData ($changes,$primaryKeys) { $this-&gt;action = &quot;update&quot;; $sqlStatement[] = $this-&gt;queryBuilder-&gt;update( $this-&gt;currentEntity-&gt;table(), $changes, $primaryKeys[&quot;pk&quot;] )-&gt;getSqlString(); $sqlStatement[] = array_merge(array_values($changes),$primaryKeys[&quot;values&quot;]); $this-&gt;sqlStatementStack[] = $sqlStatement; } /** * process changed properties of EntityResult to update * * @param EntityResult $entity entity result object * @param array $changes associated array with changes * @return void */ protected function processChanges ($entity,$changes) { if (isset($changes[&quot;_assoc&quot;])) { $assocChanges = $changes[&quot;_assoc&quot;]; $primaryChanges = array_diff($changes,$assocChanges); foreach ($assocChanges as $key =&gt; $value) { //IMPORTANT - ADD NECESSARY UPDATES FOR ASSOCIATED ENETITIES $this-&gt;updateData();//check } } else { $primaryChanges = $changes; } $this-&gt;updateData($primaryChanges,$this-&gt;processPrimaryKeys($entity)); } /** * save an entity to database * insert new row if new data, or update if retrieved entity has been changed * * @param EntityResult $entity entity object * @param array $values associated array of values - [&quot;column_1&quot; =&gt; &quot;value&quot;, &quot;column_2&quot; =&gt; &quot;value&quot;] * @return void */ public function save ($entity,$values = null) { $firstState = $this-&gt;tracker-&gt;isTracked($entity); //check if ($firstState) { $this-&gt;setCurrentEntity($firstState-&gt;name()); $assoc = $this-&gt;currentAssociated-&gt;getAll(); $changes = $this-&gt;tracker-&gt;getChanges($entity,$assoc,$this-&gt;entities); if (!$changes) { return; // if no changes, no need to save } $this-&gt;processChanges($entity,$changes); } else { $this-&gt;insertData($entity,$values); return $this; } return $this; } /** * delete an entity from database * * @return void */ public function delete () { } /** * execute the current CRUD Action statement * * @return void */ public function go ($data = null) { if ($this-&gt;action === 'select') { $res = $this-&gt;queryDb-&gt;select((object) [ &quot;sql&quot; =&gt; $this-&gt;sqlStatement-&gt;getSqlString(), &quot;data&quot; =&gt; $data ]); $this-&gt;currentAssociated-&gt;clear(); /* TESTING */// echo $sql; /* TESTING */ //echo json_encode($res); return $this-&gt;hydrate($res); //return $this-&gt;result($res); } if ($this-&gt;action === &quot;insert&quot;) { $isDone = true; //CHECK $this-&gt;queryDb-&gt;transaction(); foreach ($this-&gt;sqlStatementStack as $sql) { $isDone = $this-&gt;queryDb-&gt;insert((object)[ &quot;sql&quot; =&gt; $sql[0], &quot;data&quot; =&gt; $sql[1] ]); } if ($isDone) { $this-&gt;queryDb-&gt;commit(); //IMPORTANT - IF ONE OF QUERY FAILS, ALL WILL BE FAILED } else { $this-&gt;queryDb-&gt;rollback(); } return $isDone; } if ($this-&gt;action === &quot;update&quot;) { return $this-&gt;queryDb-&gt;batchWrite($this-&gt;action,$this-&gt;sqlStatementStack); } } </code></pre> <h3>EntityResult class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity's result object */ namespace Infinite\DataMapper\Entity; /** * Entity's result object class */ class EntityResult { /** * timestamp of the creation of this instance * * @var integer */ private $__createdAt; /** * name of entity of this object belong * * @var string */ protected $entityName; /** * entity attributes * * @var array */ protected $props = []; /** * constructor * @param array $props properties of entity */ public function __construct ($props,$name) { $this-&gt;__createdAt = explode(&quot;.&quot;,microtime(true))[1]; $this-&gt;entityName = $name; if ($this-&gt;is_assoc($props)) { foreach ($props as $key =&gt; $value) { $this-&gt;props[] = $key; $this-&gt;$key = $value; } } else { foreach ($props as $key) { $this-&gt;props[] = $key; $this-&gt;$key = &quot;&quot;; } } } final public function __getCreatedTime () { return $this-&gt;__createdAt; } /** * return entity name of this object belongs * * @return string $entityName entity name */ public function name () { return $this-&gt;entityName; } /** * check if an array is an associative array or not * * @param array $array * @return boolean */ protected function is_assoc ($array) { foreach (array_keys($array) as $k =&gt; $v) { if ($k !== $v) { return true; } } return false; } /** * __call magic method - use to * dynamically create set and get methods * * @return mixed */ public function __call ($name,$args) { $functionName = strtolower($name); $isGetter = explode(&quot;get&quot;,$functionName); $isSetter = explode(&quot;set&quot;,$functionName); if (is_array($isGetter) &amp;&amp; count($isGetter) &gt; 1) { if ($this-&gt;props($isGetter[1])) { return $this-&gt;$isGetter[1]; } } if (\is_array($isSetter) &amp;&amp; count($isSetter) &gt; 1) { if ($this-&gt;props($isSetter[1])) { $this-&gt;set($isSetter[1],$args); } } } /** * clone this instance, to keep track of changes * clones properties even if it is an object * * @return void */ public function __clone () { foreach ($this-&gt;props as $prop) { if (\is_object($this-&gt;$prop)) { $this-&gt;$prop = clone $this-&gt;$prop; } } } /** * get instance's property names as an associative array * * @param object $data - object with data * @return array */ public function getAssocArray() { $arr = []; foreach($this-&gt;props as $key) { if (isset($this-&gt;$key)) { $arr[$key] = $this-&gt;$key; } }//echo json_encode($arr); return $arr; } /** * get entity result object's properties in an indexed array * * @return array */ public function getPropsArray () { $arr = []; foreach ($this-&gt;props as $key) { $arr[] = $this-&gt;$key; } return $arr; } /** * get a single attribute * * @param string $attrib * @return string attribute * @throws \Exception */ protected function props ($prop = null) { if (empty($prop)) { return $this-&gt;props; } if (!isset($this-&gt;$prop)) { throw new \Exception(&quot;Undefined_Property&quot;); } return $this-&gt;$prop; } /** * get entity's attributes * * @param mixed $attribute * @return string|array * @throws \Exception */ public function get ($prop = null) { try { if (is_array($prop)) { $arr = []; foreach ($prop as $key) { $arr[] = $this-&gt;props($key); } return $arr; } return $this-&gt;props($prop); } catch (\Exception $e) { if ($e-&gt;getMessage() == &quot;Undefined_Property&quot; ) //IMPORTANT - CONSIDER ADDING &amp;&amp; $prop !== null { return $this-&gt;props(); } } } /** * set a property * * @param string $name property name * @param mixed $prop property value * @return void */ public function set ($name,$prop) { try { $this-&gt;props($name); $this-&gt;$name = $prop; } catch (\Exception $e) { if ($e-&gt;getMessage() === &quot;Undefined_Property&quot;) { return; } } } /** * set object proprties from an associative array * * @param array $array an associative array of object props and values * @return void */ public function __setFromObj ($obj) { foreach ($this-&gt;props() as $key) { if (!isset($obj-&gt;$key)) { continue; //CHECK } $this-&gt;$key = $obj-&gt;$key; } } } ?&gt; </code></pre> <h3>ChangeTracker class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Changes tracker for EntityResult objects */ namespace Infinite\DataMapper; use Infinite\DataMapper\Entity\EntityResult; /** * class for tracking changes in EntityResult object */ class ChangeTracker { /** * timestamps of creation time of EntityResult objects * * @var array */ protected $__createdTimes = []; /** * first state of EntityResult. * clone of actual EntityResult * * @var EntityResult */ protected $currentFirstState; /** * detected changes of EntityResult and it's associations * * @var array */ protected $changes = []; /** * EntityManager's current entity * * @var Infinite\DataMapper\Entity entity object */ protected $entity; /** * constructor */ public function __construct () { } /** * add tracking of entity result object * * @param string $currentEntityName name of current entity * @param EntityResult $result Entity result object * @return void */ public function addTracking ($currentEntityName,$result) { $this-&gt;__createdTimes[$currentEntityName][$result-&gt;__getCreatedTime()] = clone $result; //keep track of objects } /** * get the first state of stored EntityResult * * @return EntityResult */ public function getFirstState () { return $this-&gt;currentFirstState; } /** * set changed properties and values * * @param array $changes * @return void */ protected function setChanges ($changes) { if ($changes) { $this-&gt;changes = array_merge($this-&gt;changes,$changes); } } /** * set changes association values * * @param string $key name of associated property * @param array $changes array of changed properties and values * @return void */ protected function setChangedAssoc ($key,$changes) { $this-&gt;changes[&quot;_assoc&quot;][$key] = $changes; } /** * check if EntityResult object is a tracked one * and if tracked, return it's first state, cloned by entity manager * * @param EntityResult $entity entity result object * @return EntityResult|false */ public function isTracked ($entity) { $created = $entity-&gt;__getCreatedTime(); $entityName = $entity-&gt;name(); if (!isset($this-&gt;__createdTimes[$entityName])) { //IMPORTANT - TRY CHECKING LENGTH OF THIS ARRAY INSTEAD OF ISSET return false; } if (isset($this-&gt;__createdTimes[$entityName][$created])) { $this-&gt;currentFirstState = $this-&gt;__createdTimes[$entityName][$created]; return $this-&gt;__createdTimes[$entityName][$created]; } } /** * compare $this-&gt;currentFirstState's associations * by traversing through properties * * @param string $key key of $this-&gt;firstEntity * @param EntityResult $object object to be compared * @return array|boolean */ protected function compareAssociations ($key,$object) { $changes = []; $entity = $this-&gt;entityContainer-&gt;get($object-&gt;name()); //associated entity /* * strictly only iterate over $this-&gt;currentFirstState */ foreach ($this-&gt;currentFirstState-&gt;$key as $prop =&gt; $val) { //TRY CHECKING IF $object-&gt;$key is set, (BUT MAY BE EQUAL TO NULL) if ($object-&gt;$prop != $val) { $mapped = $entity-&gt;attribs-&gt;getMapped($prop); $changes[$mapped] = $object-&gt;$prop; } } return count($changes) &gt; 0 ? $changes : false; //IF NO CHANGE DETECTED, RETURN FALSE } /** * compare firstState with current state of entity result * * @param string $key object key, which need to be checked * @param EntityResult $firstState first state of entity result * @param EntityResult $current current state of entity result * @return mixed */ public function compareChanges ($key,$current) { $changes = []; //comparing object, to check if values changed //STRICTLY USE == operator if (\is_object($current-&gt;$key) &amp;&amp; ($this-&gt;currentFirstState-&gt;$key == $current-&gt;$key)) { return false; } //IMPORTANT, STRICT TYPE CHECKING if ($current-&gt;$key === $this-&gt;currentFirstState-&gt;$key) { return false; //IF NO CHANGE DETECTED, RETURN FALSE } else { $mapped = $this-&gt;entityContainer-&gt;get($this-&gt;currentFirstState-&gt;name())-&gt;attribs-&gt;getMapped($key); $changes[$mapped] = $current-&gt;$key; //store value changes return $changes; } } /** * get changed properties in EntityResult * * @param EntityResult $firstState first state object copy of Entity Result * @param EntityResult $current current Entity Result * @return array|boolean * @throws \Exception */ public function getChanges ($current,$associatedEntities,$entityContainer) { $this-&gt;entityContainer = $entityContainer; foreach ($this-&gt;currentFirstState as $key =&gt; $value) { if (array_search($key,$associatedEntities) !== false) { // if prop is an associated entity, if (!($current-&gt;$key instanceof EntityResult)) { throw new \Exception(&quot;Associated_Entity_Not_Instance_Of_EntityResult&quot;); } //greedy way, skip traversing if entity not changed if ($this-&gt;currentFirstState-&gt;$key == $current-&gt;$key) { continue; } $this-&gt;setChangedAssoc($key,$this-&gt;compareAssociations($key,$current-&gt;$key)); continue; } $this-&gt;setChanges($this-&gt;compareChanges($key,$current)); } return count($this-&gt;changes) &gt;0 ? $this-&gt;changes : false; } } ?&gt; </code></pre> <p><strong>Reasons for posting this question and what I'm looking for</strong></p> <ul> <li>Any improvements in the in-memory representation of <strong>relationships, entity attributes. (data structure)</strong></li> <li>Mostly I'm bothered about using foreach loops in most places.</li> <li>Any improvement for the code and for the code structure is welcome.</li> <li>What kind of improvements to be done to use in production?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T11:22:19.053", "Id": "520772", "Score": "0", "body": "“_Mostly I'm bothered about using foreach loops in most places._” would you rather have a different loop style, or hope/expect to achieve the same functionality without a loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T12:27:22.750", "Id": "520775", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ For most parts, I hope to reduce the number of loops, or any other clever way of implementing functionality but also keeping the current performance or making it higher than present." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:09:58.230", "Id": "262623", "Score": "0", "Tags": [ "algorithm", "php", "library", "orm" ], "Title": "Object Relational Mapper - improvements to use in production" }
262623
<p>Below is an implementation of a UTF-8 string to UTF-16 string. Kind of like <code>MultiByteToWideChar</code> on Win32, but it's cross-platform and <code>constexpr</code>. Passing null as the output simply calculates the size. It works in my testing.</p> <pre><code>#include &lt;stddef.h&gt; namespace utf_converter { namespace detail { constexpr bool utf8_trail_byte(char8_t const in, char32_t&amp; out) noexcept { if (in &lt; 0x80 || 0xBF &lt; in) return false; out = (out &lt;&lt; 6) | (in &amp; 0x3F); return true; } // Returns number of trailing bytes. // -1 on illegal header bytes. constexpr int utf8_header_byte(char8_t const in, char32_t&amp; out) noexcept { if (in &lt; 0x80) { // ASCII out = in; return 0; } if (in &lt; 0xC0) { // not a header return -1; } if (in &lt; 0xE0) { out = in &amp; 0x1F; return 1; } if (in &lt; 0xF0) { out = in &amp; 0x0F; return 2; } if (in &lt; 0xF8) { out = in &amp; 0x7; return 3; } return -1; } } // namespace detail constexpr ptrdiff_t utf8_to_utf16(char8_t const* u8_begin, char8_t const* const u8_end, char16_t* u16out) noexcept { ptrdiff_t outstr_size = 0; while (u8_begin &lt; u8_end) { char32_t code_point = 0; auto const byte_cnt = detail::utf8_header_byte(*u8_begin++, code_point); if (byte_cnt &lt; 0 || byte_cnt &gt; u8_end - u8_begin) return false; for (int i = 0; i &lt; byte_cnt; ++i) if (!detail::utf8_trail_byte(*u8_begin++, code_point)) return -1; if (code_point &lt; 0xFFFF) { if (u16out) *u16out++ = static_cast&lt;char16_t&gt;(code_point); ++outstr_size; } else { if (u16out) { code_point -= 0x10000; *u16out++ = static_cast&lt;char16_t&gt;((code_point &gt;&gt; 10) + 0xD800); *u16out++ = static_cast&lt;char16_t&gt;((code_point &amp; 0x3FF) + 0xDC00); } outstr_size += 2; } } return outstr_size; } } // namespace utf_converter // Example test on Windows where wchar_t is utf16 #include &lt;Windows.h&gt; int main() { using utf_converter::utf8_to_utf16; char8_t constexpr u8[] = u8&quot;\u7EDD\u4E0D\u4F1A\u653E\u5F03\u4F60&quot;; auto constexpr u16sz = utf8_to_utf16(u8, u8 + sizeof u8, nullptr); char16_t u16[u16sz]; utf8_to_utf16(u8, u8 + sizeof u8, u16); MessageBoxW(nullptr, (wchar_t*)u16, L&quot;UTF-16 text&quot;, MB_OK); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:59:14.680", "Id": "518358", "Score": "1", "body": "Please do not edit code after the question has been answered, read [What should I not do when someone answers](https://codereview.stackexchange.com/help/someone-answers)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:00:41.013", "Id": "518360", "Score": "0", "body": "@pacmaninbw I intentionally didn't edit out anything answers mentioned. Not even one typo I had there. I am not sure what you're referring to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:02:42.377", "Id": "518362", "Score": "3", "body": "Everyone should see what the person that answered saw, that's the reason for the don't edit rule. I didn't roll back the edit because you are right it didn't affect the answer. Every edit made after an answer is flagged in the 2nd Monitor Chat room." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:06:34.317", "Id": "518363", "Score": "1", "body": "@pacmaninbw I see. It's nice to see this edits that invalidate answers are taken very seriously. It is, indeed, frustrating for answerers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:01:52.780", "Id": "518637", "Score": "2", "body": "No one pointed it out, but `code_point < 0xFFFF` should have been `code_point <= 0xFFFF`. I am not going to edit the question to not upset mods again though." } ]
[ { "body": "<p>Good job on general organization: use of namespace and nested detail namespace, use of different sized char types, marking things with noexcept, etc.</p>\n<hr />\n<p>Error: Why do you return <code>false</code> when the function expects a <code>ptrdiff_t</code>?</p>\n<hr />\n<p>Architecture: mixing function return values and &quot;out&quot; parameters or, worse yet, &quot;in/out&quot; parameters makes it harder to understand and read through quickly.</p>\n<p><code>utf8_header_byte</code> produces the byte count through the return value <em>and</em> the extracted bits from this first byte via an &quot;out&quot; parameter. <code>utf8_trail_byte</code> modifies a parameter with the decoded partial result and returns a status.</p>\n<hr />\n<p>The code like in <code>utf8_header_byte</code> always bugs me. I agree it's portable, and if it's constexpr the performance doesn't matter. But if the CPU provides a way to directly give you the number of leading <code>1</code> bits, it's just a lot of work for what could have been a single instruction. I would split the difference and implement this around a call to a function <code>count_leading_1_bits</code> that can have a portable implementation <em>or</em> call an intrinsic, through conditional compilation.</p>\n<pre><code>utf8_to_utf16(char8_t const* u8_begin,\n char8_t const* const u8_end,\n char16_t* u16out) noexcept {\n</code></pre>\n<p>Consider making this a template that takes any iterator, not just a raw pointer. You can use Concepts and constraints in C++20 to declare that both inputs need to be the same kind of iterator (or iterator/sentinel pair) and have <code>char8_t</code> as the <code>value_type</code> and has the necessary iterator category (does it work with forward single-pass iterators or does it require random access iterators?).</p>\n<p>Personally, I have a more basic function that consumes bytes from UTF-8 input and returns a single <code>char32_t</code>. Call that from your function, also break out the surrogate pair handling into another function. Your <code>utf8_to_utf16</code> function then loops calling the two helpers for input and output respectively.</p>\n<hr />\n<p>I also allow more than 3 leading bits in the head byte, allowing decoding of full 31-bit characters. The <em>input</em> function (decode a single character) supports this; an out of range character is reported in the <em>output</em> step that it can't be represented as UTF-16. Note that you need checking there anyway since 4-byte codes gives 22 bits, which lets you decode things beyond the range of surrogate pairs.</p>\n<p>You seem to be missing error checking in general. You return -1 if the number of continuation bytes is wrong, but you may have already output some characters OK. You don't report the error position, which is <em>very handy</em> to have in an error about being unable to load a file!</p>\n<p>You could have a configuration where errors are automatically replaced with the invalid-character character, or throws an exception that reports the details of the error position.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:42:35.253", "Id": "518350", "Score": "0", "body": "Thank you for the review! The false/ptrdiff_t is a typo. I can fix it right now if you don't mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:43:37.273", "Id": "518352", "Score": "0", "body": "I used clang-format with google style for indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:48:57.873", "Id": "518353", "Score": "0", "body": "my mistake re formatting. I saw `for (int i = 0; i < byte_cnt; ++i)\n if (!detail::utf8_trail_byte(*u8_begin++, code_point))\n return -1;` and this increments the pointer as it goes, checking all the bytes ahead of time. But it doesn't operate on a copy of the pointer, so how does it decode afterwards? So I thought, on a quick reading, that it must be checking each byte before decoding and processing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:51:26.060", "Id": "518354", "Score": "0", "body": "so... the real confusion is that the decoding is done via an in/out parameter, and the return value is an error/success status. I read it as a predicate asking if it's indeed a trail byte, not expecting the \"real work\" to be done on the side like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:53:18.910", "Id": "518355", "Score": "0", "body": "I could probably use `optional<char32_t>` instead of an in/out parameter. Would that be a better design?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:00:33.713", "Id": "518359", "Score": "1", "body": "re `optional` that would be less surprising to the reader, but also complicates the code in order to use it. Just throwing an exception if it can't return something would be simplest. But I think the code can be refactored... don't test and extract and merge in a single helper function; call a function to test the high two bits, then just do the merging in the loop whose job it is to decode UTF-8." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T19:22:47.603", "Id": "518397", "Score": "0", "body": "Using `optional` for error handling is also kinda abusing the semantics of `optional`. An `optional` return says to me “the thing I’m promising to give you may not be there, and that’s fine and normal”… not that the lack of value is an error. Eventually we’ll have something like [`expected`](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html), [`outcome`](https://ned14.github.io/outcome/), or whatever, and *those* would be the correct type to return. Until then, you could use something that would be drop-in compatible with one of those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T19:45:35.347", "Id": "518399", "Score": "0", "body": "@indi I think the main problem was creating helper functions. This should have been a single function, and spreading the functionality through 3 functions made it awkward to share data among them and handle errors as needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T22:07:16.773", "Id": "518418", "Score": "0", "body": "Yes, the helper function being awkward to share data is a sign of poor cohesion. They could be various member functions of an _object_ instead, or you could decompose the large function better and identify parts that are not only cohesive but potentially reusable. Think about the decomposition I mentioned in my answer, and comments elsewhere about what else I remembered about it." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:30:42.097", "Id": "262631", "ParentId": "262626", "Score": "8" } }, { "body": "<p>Adding to JDługosz's comments:</p>\n<h1>Rename <code>utf8_to_utf16()</code> to <code>convert()</code></h1>\n<p>Why? Because the function's argument types already restrict the input to UTF-8 and the output to UTF-16, and it's in the <code>utf_converter</code> namespace, so there is very little room for ambiguity. It will also allow you to add overloads for the reverse transformation, and for conversions to/from UTF-32.</p>\n<h1>Make it compatible with C++20 ranges</h1>\n<p>Since you marked the question with the C++20 tag, consider that someone might want to use <a href=\"https://en.cppreference.com/w/cpp/ranges/range\" rel=\"noreferrer\">ranges</a> instead of iterator pairs. Add an overload that takes the input as an input range, and writes the output to an output range. Basically, make it have the same interface as <a href=\"https://en.cppreference.com/w/cpp/algorithm/ranges/transform\" rel=\"noreferrer\"><code>std::ranges::transform()</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:07:49.957", "Id": "518365", "Score": "0", "body": "That reminds me... given primitives like I described (separate function to consume a single complete UTF-8 character and return it), you can simply _use it_ with functions like `transform` if/when you specifically want to convert to UTF-16. I wrote mine to work as range adaptors for Boost.Range library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:09:55.203", "Id": "518366", "Score": "0", "body": "@JDługosz Are you sure? There is no 1:1 mapping between elements in a `char8_t` string and a `char16_t` string, something `transform()` does expect. But maybe another algorithm could be used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T21:57:10.703", "Id": "518416", "Score": "0", "body": "I don't recall exactly, @G._Slipen. It's easy to make a forward iterator (using Boost's Iterator facade library) that consumes as many items as necessary from the byte iterator it was constructed with. I had packaged some things like case conversion and UTF handling to work with Boost.Range and other things in the same ecosystem. Current Range V3 stuff is more flexible than trying to compose iterators, though." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:56:09.113", "Id": "262633", "ParentId": "262626", "Score": "6" } }, { "body": "<p>Re-implementing this kind of low-level conversion seems a waste of effort when C++ goes to some length to provide these facilities for us:</p>\n<pre><code>#include &lt;codecvt&gt;\n#include &lt;locale&gt;\n</code></pre>\n\n<pre><code>return std::wstring_convert&lt;std::codecvt_utf8_utf16&lt;char16_t&gt;,char16_t&gt;{}.from_bytes(s);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:45:43.083", "Id": "518385", "Score": "3", "body": "[codecvt_utf8_utf16](https://en.cppreference.com/w/cpp/locale/codecvt_utf8_utf16) is deprecated. That's kind of why I implemented this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:53:49.233", "Id": "518387", "Score": "2", "body": "Yes, it's deprecated, but I don't think the intention is for everyone to reimplement basic functionality such as this. That said, I don't really understand *why* it's deprecated, or what the intention is..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:57:09.700", "Id": "518389", "Score": "3", "body": "Actually, the advice I took, when writing the above for myself a few months back, was [continue using it until a new standardized, more-secure version is done](//stackoverflow.com/a/43153057/4850040)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T07:21:38.490", "Id": "518432", "Score": "2", "body": "Yes, I follow precisely the same advice. It's highly likely that I found exactly that same SO Q&A whenever I saw the spurious deprecation warning being generated by a compiler near me some time ago. I use `codecvt` throughout multiple production codebases, except when building on Windows, where there is already a perfectly good and non-deprecated API: `MultiByteToWideChar` and `WideCharToMultiByte`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T05:42:03.760", "Id": "520086", "Score": "0", "body": "@CodyGray Your suggestion to use MultiByteToWideChar/WideCharToMultiByte. It's documented to produce composed results from uncomposed strings. If you want simple mechanical conversion, you can't use it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:44:36.970", "Id": "262642", "ParentId": "262626", "Score": "6" } }, { "body": "<h1>suggested architecture</h1>\n<h2>① decode UTF-8 stream</h2>\n<p>Construct with a <em>range</em> of UTF-8 encoded bytes, present the object as an iterator that provides complete 32-bit characters. It has another member function to give the current offset into the original input range, useful for error reporting.</p>\n<p>A <em>range</em> can be a modern C++20 range object, or separate begin/end iterators, or whatever works with the libraries you are already using. I mean that loosely as a (lower-case) concept.</p>\n<h3>functional decomposition</h3>\n<p>Stand-alone utility functions used by the above are modeled on the mbchar library: is it a prefix, what is its length.</p>\n<h3>Include error detection</h3>\n<p>One issue with <code>codecvt</code> is the lack of error handling and the presence of UTF-8 encoding as an actual attack vector. Being an object, it is easily configured with options to consume improper byte sequences and replace with the bad-character character, or throw an exception.</p>\n<h2>② Encode 32-bit characters as UTF-16</h2>\n<p>Construct an object around an output iterator to <code>char16_t</code> that presents as an output iterator taking <code>char32_t</code>. Doing the <code>*it++ = c32;</code> to it will write one or two items to the wrapped iterator.</p>\n<p>Again, configure errors to either replace an out-of-range or reserved character with the bad-character character or throw an exception.</p>\n<p>Helper functions can cleanly be made to identify a 32-bit character as being in range for UTF-16, being in a reserved block, being in the range of surrogate pairs, etc. <strong>Those are all simple predicates that take a char and return a status, and don't modify anything or do other processing.</strong></p>\n<p>You can see that having simple one-line named function for returning the first half and the second half surrogates are very simple if they are called already knowing that the character is in the proper range. And it makes the final encoding logic very readable.</p>\n<hr />\n<p>Note that these two jobs are separate, independant things.<br />\nYou can compose them using a simple <code>std::copy</code>, and you can make a convenience function that wraps this conversion task. But, they can be composed along with other code as well, allowing you to do things without requiring intermediate copies to be made. It's pretty neat how iterator transforms (in Boost's Range V2 library) and now C++20 ranges let you generate an efficient all-inlined piece of code from reusable parts with the things you need to swap out being inside a loop or otherwise deep inside another piece of code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:43:06.203", "Id": "518484", "Score": "1", "body": "Thank you for the review! I tried to implement your architecture in [this](https://codereview.stackexchange.com/q/262692/183642) follow-up question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T22:29:30.027", "Id": "262656", "ParentId": "262626", "Score": "5" } } ]
{ "AcceptedAnswerId": "262656", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:31:27.080", "Id": "262626", "Score": "5", "Tags": [ "c++", "c++20", "unicode" ], "Title": "UTF-8 to UTF-16 (char8_t string to char16_t string)" }
262626
<p>I'm reading Bruce Molay's book on Unix programming, and as an exercise I've implemented a copy of the <code>tail</code> command.</p> <p>My approach goes over the entire file once, to count newlines, then again to store their positions in an array, and finally a third time to print out the bytes past the position of the nth newline. I know this must be inefficient, though I'm not sure of the ideal way to go about it.</p> <p>Another point of uncertainty―to get around seeking restrictions on <code>stdin</code>, I write a copy of it to a temp file, then perform all operations on that. I think there's probably a way to do this without a temp file, though I'm not sure what it is.</p> <h1>tail1.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; #define BUFSIZE 4096 #define N_LINES 10 #define TMPFILE &quot;/tmp/stdin_tmpf.bin&quot; void oops(char *s1, char *s2) { fprintf(stderr, &quot;Error: %s\n(errno) &quot;, s1); perror(s2); exit(1); } unsigned count_chars(const char *str, char byte, int n_chars) { int cnt = 0; for (int i = 0; i &lt; n_chars; ++i) if (str[i] == byte) ++cnt; return cnt; } unsigned find_cutoff(int fd) { int linecnt, n_chars; int subpos, block; char cbuf[BUFSIZE]; subpos = block = linecnt = n_chars = 0; // count lines to allocate linelocs array while ((n_chars = read(fd, cbuf, BUFSIZE)) &gt; 0) linecnt += count_chars(cbuf, '\n', n_chars); if (linecnt &lt;= N_LINES) return 0; // array of positions of newlines int linelocs[linecnt]; linelocs[0] = 0; int loc_index = 0; if (lseek(fd, 0, SEEK_SET) == -1) oops(&quot;couldn't seek start&quot;, &quot;&quot;); while ((n_chars = read(fd, cbuf, BUFSIZE)) &gt; 0) { for (int i = 0; i &lt; n_chars; ++i) if (cbuf[i] == '\n') { loc_index++; subpos = i+1; linelocs[loc_index] = (BUFSIZE*block) + subpos; } block++; } return linelocs[linecnt - N_LINES]; } // create temporary file holding stdin contents int stdin_tmpf() { int out_fd, in_fd; int n_chars; char buf[BUFSIZE]; if ((in_fd = fileno(stdin)) == -1) oops(&quot;couldn't open stdin&quot;, &quot;&quot;); if ((out_fd = open(TMPFILE, O_RDWR | O_CREAT)) == -1) oops(&quot;failed to create tmpf&quot;, &quot;&quot;); while ((n_chars = read(in_fd, buf, BUFSIZE)) &gt; 0) if (write(out_fd, buf, n_chars) != n_chars) oops(&quot;read/write error&quot;, &quot;stdin_tmpf&quot;); if (lseek(out_fd, 0, SEEK_SET) == -1) oops(&quot;seek failure&quot;, &quot;stdin_tmpf&quot;); return out_fd; } int main(int argc, char **argv) { int in_fd, out_fd; bool cleanup = false; if (argc == 1) { in_fd = stdin_tmpf(); cleanup = true; } else if ((in_fd = open(argv[1], O_RDONLY)) == -1) oops(&quot;Couldn't open file&quot;, argv[1]); if ((out_fd = fileno(stdout)) == -1) oops(&quot;Couldn't open stdout&quot;, &quot;&quot;); unsigned cutoff = find_cutoff(in_fd); int n_chars; char buf[BUFSIZE]; if (lseek(in_fd, cutoff, SEEK_SET) == -1) oops(&quot;couldn't seek cutoff&quot;, &quot;&quot;); // TODO int to str while ((n_chars = read(in_fd, buf, BUFSIZE)) &gt; 0) if (write(out_fd, buf, n_chars) != n_chars) oops(&quot;couldn't write stdout&quot;, &quot;&quot;); if (close(in_fd) == -1 || close(out_fd) == -1) oops(&quot;couldn't close files&quot;, &quot;&quot;); if (cleanup &amp;&amp; unlink(TMPFILE) == -1) oops(&quot;failed to cleanup&quot;, TMPFILE); return 0; } </code></pre> <p>Quite new to C programming, I've been a Python programmer for many years. Any tips are greatly appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:28:08.757", "Id": "518374", "Score": "0", "body": "C++ might be a bit easier if you are coming from Python :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:45:08.083", "Id": "518377", "Score": "1", "body": "My (very) eventual goal is contributing to the Linux kernel, so I think that would be a bit off track" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:12:51.897", "Id": "518478", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a new question instead." } ]
[ { "body": "<h1>You only need one pass</h1>\n<p>Your solution to have three passes over the input has some big problems. Most notably, if the input is very large, you also need to create a large temporary file. But you now also have to deal with issues surrounding temporary files, like what if I run two instances of tail in parallel? What if someone created a symlink from <code>/tmp/stdin_tmpf.bin</code> to some other file?</p>\n<p>You can avoid all this by doing only a single pass over the input. The trick is that you know you only need to remember the last <code>N_LINES</code>, so just create a buffer for <code>N_LINES</code> lines. Start filling the buffer, and once it holds <code>N_LINES</code> lines, when you read in the next line, delete the oldest line. Once you finished reading the input, just write out the contents of the buffer.</p>\n<p>Note that this is also what the <a href=\"https://www.gnu.org/software/coreutils/\" rel=\"nofollow noreferrer\">coreutils</a> <a href=\"https://man7.org/linux/man-pages/man1/tail.1.html\" rel=\"nofollow noreferrer\">tail</a> program does.</p>\n<h1>Use <code>size_t</code> for sizes, counts and indices</h1>\n<p>I see you use <code>unsigned</code> and <code>int</code> interchangably for keeping track of counts, like <code>n_chars</code> and <code>cnt</code> in <code>count_chars()</code>. However, the right type to use is <a href=\"https://en.cppreference.com/w/c/types/size_t\" rel=\"nofollow noreferrer\"><code>size_t</code></a>. Do this whereever appropriate.</p>\n<h1>Reporting errors</h1>\n<p>I see you check every return value and report an error both to <code>stderr</code> and by exitting with a non-zero exit code. That's very good! However, I don't see why you both do a <code>fprintf(stderr, ...)</code> <em>and</em> call <code>perror()</code>. I think one is enough. Also, prefer using <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_FAILURE</code></a> as the exit code.</p>\n<p>If you are targetting Linux or BSD only, you might consider calling <a href=\"https://linux.die.net/man/3/err\" rel=\"nofollow noreferrer\"><code>err()</code></a> instead of your own <code>oops()</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:57:16.840", "Id": "518390", "Score": "0", "body": "Best way to allocate the buffer for `N_LINES`? Do I have to assume a maximum line length?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T18:15:43.240", "Id": "518392", "Score": "1", "body": "You should never assume a maximum line length. You could use the POSIX [`getline()`](https://man7.org/linux/man-pages/man3/getline.3.html) function to read lines (it will do the memory allocation for you), or use `fgets()` to read into a pre-allocated buffer, but then check if it read a newline, otherwise `realloc()` the buffer into something larger and call `fgets()` again to read the remainder of the line (and possibly repeat this multiple times for a single line)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:26:29.753", "Id": "262636", "ParentId": "262629", "Score": "3" } } ]
{ "AcceptedAnswerId": "262636", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:15:13.673", "Id": "262629", "Score": "3", "Tags": [ "c", "reinventing-the-wheel", "linux", "unix" ], "Title": "Writing a tail command clone" }
262629
<p>I created an algorithm for generating Latin Square. The algorithm uses the first n permutations (Not n!) orderings of a distinct row of numbers. This is then assigned to a 2d list.</p> <pre><code>import itertools def latin_square(rows, numbers): assert rows is not None, &quot;row is required to not be None&quot; assert rows &gt;= 0, &quot;row is required to be zero or more, including zero&quot; assert numbers is not None, &quot;numbers is required to not be None&quot; square = [[numbers[0] for row in range(rows)] for col in range(rows)] line = [] for row, line in enumerate(itertools.permutations(numbers, rows)): if row == rows: break for col in range(len(line)): square[row][col] = line[col] return square def test_latin_square(): assert latin_square(1, [1]) == [[1]] assert latin_square(2, [0, 1]) == [[0, 1], [1, 0]] assert latin_square(2, [-1, -2]) == [[-1, -2], [-2, -1]] assert latin_square(3, [3, 2, 1]) == [[3, 2, 1], [3, 1, 2], [2, 3, 1]] test_latin_square() </code></pre>
[]
[ { "body": "<p><strong>Functionality</strong></p>\n<p>Your code is incorrect, as you can see in your fourth test case:</p>\n<pre><code>latin_square(3, [3, 2, 1]) == [[3, 2, 1],\n [3, 1, 2],\n [2, 3, 1]]\n</code></pre>\n<p>This is not a latin square, since there are two 3s in the first column and two 1s in the third column. This seems like you wrote the code first and then copied its output to the test cases. It should obviously be the other way round.</p>\n<p>The most straight-forward approach would probably be simply rotating the list of <code>numbers</code> by one in either direction to get each next row. You should of course make sure to only use distinct numbers from the provided input list <code>numbers</code>.</p>\n<hr />\n<p><strong>Other suggestions</strong></p>\n<p>These suggestions will improve the existing implementation, but will <strong>not</strong> fix the incorrect functionality.</p>\n<hr />\n<p><code>assert</code> statements should only be used for testing, as they will be ignored in optimized mode. More about optimized mode <a href=\"https://stackoverflow.com/a/5142453/9173379\">here</a>. Rather you should check these conditions with an <code>if</code>-statement and raise meaningful errors (instead of <code>AssertionErrors</code>). <code>ValueError</code> or <code>TypeError</code> should be the most fitting here (but you could implement your own custom exceptions). One example:</p>\n<pre><code>if len(set(numbers)) &lt; rows:\n raise ValueError(f&quot;Number of distinct numbers must be greater than or equal to {rows=}&quot;)\n</code></pre>\n<p>You also don't need to explicitly check for <code>rows is None</code> and <code>numbers is None</code>, as <code>None</code> values will lead to a <code>TypeError</code> anyway. Manually checking and providing a meaningful message to the user usually doesn't hurt though.</p>\n<hr />\n<p><code>square = [[numbers[0] for _ in range(rows)] for _ in range(rows)]</code></p>\n<p>It's a well-known convention to name variables you don't use <code>_</code>. That immediately makes it clear to the reader that it's not used and removes unnecessary information.</p>\n<hr />\n<p>You're doing too much manual work:</p>\n<ol>\n<li>You don't need to fill <code>square</code> with values only to replace them later</li>\n<li>You don't need to initialize <code>line</code> at all</li>\n<li>You shouldn't (most likely ever) do this:</li>\n</ol>\n<pre><code>for col in range(len(line)):\n square[row][col] = line[col]\n</code></pre>\n<p>All this snippet does is set the value of <code>square[row]</code> to <code>list(line)</code>:</p>\n<pre><code>square = []\n\nfor row, line in enumerate(itertools.permutations(numbers, rows)):\n if row == rows:\n break\n\n square.append(list(line))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:45:14.430", "Id": "518384", "Score": "0", "body": "Could I replace the code with just sifting without generating permutations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T18:21:36.337", "Id": "518393", "Score": "0", "body": "I presume you mean shifting. Shifting will of course produce certain permutations, but you don't need `itertools.permutations` for it. Simply take `rows` number of distinct numbers for the first row, then keep shifting them (left or right) by one to get the subsequent row. You're very welcome to come back here for further feedback once you've implemented that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:40:03.137", "Id": "262637", "ParentId": "262630", "Score": "5" } } ]
{ "AcceptedAnswerId": "262637", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:24:53.687", "Id": "262630", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Generating a Latin Square" }
262630
<p><a href="https://docs.rs/roux/1.3.5/roux/" rel="nofollow noreferrer"><code>roux</code></a> is a Rust library that wraps the Reddit API. Neither Reddit nor <code>roux</code> provides a stream-like interface for obtaining the latest submissions automatically, so that's what I've implemented here.</p> <p>I'm learning Rust as a hobby (I'm a Python developer by trade) and this is my first &quot;serious&quot; Rust project. Please feel free to point out anything that sticks out to you. The following points are particularly interesting to me:</p> <ul> <li><p>Am I using references and owned values appropriately (e.g. no unnecessary cloning)?</p> </li> <li><p>Is the interface provided by my <code>lib.rs</code> fitting for this use case (async streaming of items) and idiomatic?</p> </li> <li><p>As a Rust newbie, the types in the <code>where</code> declarations are hard to understand. Would it be useful to introduce some aliases?</p> </li> <li><p>Is my approach to error handling OK?</p> </li> </ul> <p><code>lib.rs</code>:</p> <pre class="lang-rust prettyprint-override"><code>#![warn(missing_docs)] /*! Streaming API for `roux` Reddit's API does not provide &quot;firehose&quot;-style streaming of new posts and comments. Instead, the endpoint for retrieving the latest posts has to be polled regularly. This crate automates that task and provides a stream for a subreddit's posts (submissions). See [`stream_subreddit_submissions`] for details. # Logging This module uses the logging infrastructure provided by the [`log`] crate. */ use futures::{Sink, SinkExt}; use log::{debug, warn}; use roux::subreddit::responses::SubmissionsData; use roux::{util::RouxError, Subreddit}; use std::collections::HashSet; use std::marker::Unpin; use tokio::time::{sleep, Duration}; use tokio_retry::Retry; /// Error that may happen when streaming submissions #[derive(Debug)] pub enum SubmissionStreamError&lt;S&gt; where S: Sink&lt;SubmissionsData&gt; + Unpin, { /// An issue with getting the data from Reddit Roux(RouxError), /// An issue with sending the data through the sink Sink(S::Error), } /** Stream new submissions in a subreddit The subreddit is polled regularly for new submissions, and each previously unseen submission is sent into the sink. `sleep_time` controls the interval between calls to the Reddit API, and depends on how much traffic the subreddit has. Each call fetches the 100 latest items (the maximum number allowed by Reddit). A warning is logged if none of those items has been seen in the previous call: this indicates a potential miss of new content and suggests that a smaller `sleep_time` should be chosen. `retry_strategy` controls how to deal with errors that occur while fetching content from Reddit. See [`tokio_retry::strategy`]. */ pub async fn stream_subreddit_submissions&lt;S, R, I&gt;( subreddit: &amp;Subreddit, mut sink: S, sleep_time: Duration, retry_strategy: &amp;R, ) -&gt; Result&lt;(), SubmissionStreamError&lt;S&gt;&gt; where S: Sink&lt;SubmissionsData&gt; + Unpin, R: IntoIterator&lt;IntoIter = I, Item = Duration&gt; + Clone, I: Iterator&lt;Item = Duration&gt;, { // How many submissions to fetch per request const LIMIT: u32 = 100; let mut seen_ids: HashSet&lt;String&gt; = HashSet::new(); loop { let latest_submissions = Retry::spawn(retry_strategy.clone(), || subreddit.latest(LIMIT, None)) .await .map_err(SubmissionStreamError::Roux)? .data .children .into_iter() .map(|thing| thing.data); let mut latest_ids: HashSet&lt;String&gt; = HashSet::new(); let mut num_new = 0; for submission in latest_submissions { latest_ids.insert(submission.id.clone()); if !seen_ids.contains(&amp;submission.id) { num_new += 1; sink.send(submission) .await .map_err(SubmissionStreamError::Sink)? } } debug!( &quot;Got {} new submissions for r/{} (out of {})&quot;, num_new, subreddit.name, LIMIT ); if num_new == LIMIT &amp;&amp; !seen_ids.is_empty() { warn!( &quot;All received submissions for r/{} were new, try a shorter sleep_time&quot;, subreddit.name ); } seen_ids = latest_ids; sleep(sleep_time).await; } } </code></pre> <p><code>main.rs</code>:</p> <pre class="lang-rust prettyprint-override"><code>use futures::{channel::mpsc, Stream, StreamExt}; use roux::{subreddit::responses::SubmissionsData, Subreddit}; use tokio; use tokio::time::Duration; use tokio_retry::strategy::{jitter, ExponentialBackoff}; use subreddit_dumper; async fn submission_reader&lt;S&gt;(stream: &amp;mut S) where S: Stream&lt;Item = SubmissionsData&gt; + Unpin, { while let Some(submission) = stream.next().await { println!( &quot;New submission in r/{} by {}&quot;, submission.subreddit, submission.author ); } } #[tokio::main] async fn main() { // Initialize logging stderrlog::new() .module(module_path!()) .verbosity(3) .init() .unwrap(); let subreddit = Subreddit::new(&quot;AskReddit&quot;); let (mut submission_sender, mut submission_receiver) = mpsc::unbounded(); let retry_strategy = ExponentialBackoff::from_millis(100) .map(jitter) // add jitter to delays .take(3); // limit to 3 retries let (submission_res, _) = tokio::join!( subreddit_dumper::stream_subreddit_submissions( &amp;subreddit, &amp;mut submission_sender, Duration::from_secs(60), &amp;retry_strategy, ), submission_reader(&amp;mut submission_receiver), ); submission_res.unwrap(); } </code></pre>
[]
[ { "body": "<p>Your code is good for the most parts, however there are some improvements that can be made:</p>\n<p>The final line in your <code>main</code> method <code>submission_res.unwrap()</code> should be changed to handle the errors and maybe log them.</p>\n<hr />\n<p>Personally, I would change the structure of the library. Instead of calling the <code>async</code> method <code>stream_subreddit_submissions</code> with all the different configuration parameters, I would create a struct called <code>SubmissionsStream</code> that has two methods:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn new(\n subreddit: Subreddit,\n sink: S,\n sleep_time: Duration,\n retry_strategy: R,\n ) -&gt; SubmissionsStream\n</code></pre>\n<p>For creating the <code>SumbissionsStream</code> with all the configuration.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub async fn run(self) -&gt; Result&lt;(), SubmissionStreamError&lt;S::Error&gt;&gt; \n</code></pre>\n<p>For running the stream.</p>\n<p>I would also suggest to pull as much of the configuration creation inside of the <code>new()</code> method. For example you can change <code>new()</code> to create the <code>mpsc</code> channel inside and return the receiver, rather than passing the sender to it. However this would limit you from using a specific <code>mpsc</code> channel so I would leave it only as a suggestion and not something that you necessarily have to do.</p>\n<hr />\n<p><code>SubmissionStreamError</code> should implement the standard traits <code>Display</code> and <code>Error</code>.</p>\n<hr />\n<p>The logic for the seen ids can be optimised.</p>\n<p>When you are checking if an id has been seen or not in the <code>for</code> loop, and you find an id that has been seen, you can break from the loop because you would have seen all of the ids after it (iff <code>roux</code> returns the latest posts ordered by time, which seems to be the case from testing it).</p>\n<p>This means that you don't need to have two <code>HashSet</code>s and this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let mut latest_ids: HashSet&lt;String&gt; = HashSet::new();\n\nlet mut num_new = 0;\nfor submission in latest_submissions {\n latest_ids.insert(submission.id.clone());\n if !seen_ids.contains(&amp;submission.id) {\n num_new += 1;\n sink.send(submission)\n .await\n .map_err(SubmissionStreamError::Sink)?\n }\n}\n\n</code></pre>\n<p>can be simplified:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>\nlet mut num_new = 0;\n\nfor submission in latest_submissions {\n if !seen_ids.contains(&amp;submission.id) {\n seen_ids.insert(submission.id.clone());\n num_new += 1;\n sink.send(submission)\n .await\n .map_err(SubmissionStreamError::Sink)?\n } else {\n //If you reach a seen submission you\n // will have seen all other submissions after it.\n break;\n }\n}\n\n</code></pre>\n<hr />\n<p><strong>Final Code:</strong></p>\n<p><code>lib.rs</code></p>\n<pre class=\"lang-rust prettyprint-override\"><code>use futures::{Sink, SinkExt};\nuse log::{debug, warn};\nuse roux::subreddit::responses::SubmissionsData;\nuse roux::{util::RouxError, Subreddit};\nuse std::collections::HashSet;\nuse std::error::Error;\nuse std::fmt::{Debug, Display, Formatter};\nuse std::marker::Unpin;\nuse tokio::time::{sleep, Duration};\nuse tokio_retry::Retry;\n\n/// Error that may happen when streaming submissions\n#[derive(Debug)]\npub enum SubmissionStreamError&lt;SinkErr&gt; {\n /// An issue with getting the data from Reddit\n Roux(RouxError),\n /// An issue with sending the data through the sink\n Sink(SinkErr),\n}\n\nimpl&lt;S: Debug + Display&gt; Display for SubmissionStreamError&lt;S&gt; {\n fn fmt(&amp;self, f: &amp;mut Formatter&lt;'_&gt;) -&gt; std::fmt::Result {\n match self {\n SubmissionStreamError::Roux(roux_err) =&gt; {\n write!(f, &quot;{}&quot;, roux_err)\n }\n SubmissionStreamError::Sink(sink_err) =&gt; {\n write!(f, &quot;{}&quot;, sink_err)\n }\n }\n }\n}\n\nimpl&lt;S: Debug + Display&gt; Error for SubmissionStreamError&lt;S&gt; {}\n\npub struct SubmissionsStream&lt;S, R&gt; {\n subreddit: Subreddit,\n sink: S,\n sleep_time: Duration,\n retry_strategy: R,\n}\n\nimpl&lt;S, R, I&gt; SubmissionsStream&lt;S, R&gt;\nwhere\n S: Sink&lt;SubmissionsData&gt; + Unpin,\n R: IntoIterator&lt;IntoIter = I, Item = Duration&gt; + Clone,\n I: Iterator&lt;Item = Duration&gt;,\n{\n pub fn new(\n subreddit: Subreddit,\n sink: S,\n sleep_time: Duration,\n retry_strategy: R,\n ) -&gt; SubmissionsStream&lt;S, R&gt; {\n SubmissionsStream {\n subreddit,\n sink,\n sleep_time,\n retry_strategy,\n }\n }\n\n pub async fn run(self) -&gt; Result&lt;(), SubmissionStreamError&lt;S::Error&gt;&gt; {\n let SubmissionsStream {\n subreddit,\n mut sink,\n sleep_time,\n retry_strategy,\n } = self;\n\n const LIMIT: u32 = 100;\n let mut seen_ids: HashSet&lt;String&gt; = HashSet::new();\n\n loop {\n let latest_submissions =\n Retry::spawn(retry_strategy.clone(), || subreddit.latest(LIMIT, None))\n .await\n .map_err(SubmissionStreamError::Roux)?\n .data\n .children\n .into_iter()\n .map(|thing| thing.data);\n\n let mut num_new = 0;\n\n for submission in latest_submissions {\n if !seen_ids.contains(&amp;submission.id) {\n seen_ids.insert(submission.id.clone());\n num_new += 1;\n sink.send(submission)\n .await\n .map_err(SubmissionStreamError::Sink)?\n } else {\n //If you reach a seen submission you\n // will have seen all other submissions after it.\n break;\n }\n }\n\n debug!(\n &quot;Got {} new submissions for r/{} (out of {})&quot;,\n num_new, subreddit.name, LIMIT\n );\n if num_new == LIMIT &amp;&amp; !seen_ids.is_empty() {\n warn!(\n &quot;All received submissions for r/{} were new, try a shorter sleep_time&quot;,\n subreddit.name\n );\n }\n\n sleep(sleep_time).await;\n }\n }\n}\n</code></pre>\n<p><code>main.rs</code></p>\n<pre class=\"lang-rust prettyprint-override\"><code>use futures::{channel::mpsc, Stream, StreamExt};\nuse log::debug;\nuse roux::{subreddit::responses::SubmissionsData, Subreddit};\nuse tokio::time::Duration;\nuse tokio_retry::strategy::{jitter, ExponentialBackoff};\n\nasync fn submission_reader&lt;S&gt;(stream: &amp;mut S)\nwhere\n S: Stream&lt;Item = SubmissionsData&gt; + Unpin,\n{\n while let Some(submission) = stream.next().await {\n println!(\n &quot;New submission in r/{} by {}&quot;,\n submission.subreddit, submission.author\n );\n }\n}\n\n#[tokio::main]\nasync fn main() {\n // Initialize logging\n stderrlog::new()\n .module(module_path!())\n .verbosity(3)\n .init()\n .unwrap();\n\n let subreddit = Subreddit::new(&quot;AskReddit&quot;);\n let (submission_sender, mut submission_receiver) = mpsc::unbounded();\n let retry_strategy = ExponentialBackoff::from_millis(100)\n .map(jitter) // add jitter to delays\n .take(3); // limit to 3 retries\n\n let submission_stream = subreddit_dumper::SubmissionsStream::new(\n subreddit,\n submission_sender,\n Duration::from_secs(60),\n retry_strategy,\n );\n\n let (submission_res, _) = tokio::join!(\n submission_stream.run(),\n submission_reader(&amp;mut submission_receiver),\n );\n\n if let Err(stream_err) = submission_res {\n debug!(&quot;Error: {}&quot;, stream_err);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T17:06:35.460", "Id": "519521", "Score": "0", "body": "Thanks! One thing regarding your suggested improvement of checking for seen IDs: in your version, `seen_ids` seems to grow indefinitely. That's something I'd like to avoid, since one intended use case are long-running Reddit bots. I do like the idea of wrapping the functionality in a struct!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T12:45:29.843", "Id": "262846", "ParentId": "262635", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:20:42.763", "Id": "262635", "Score": "4", "Tags": [ "rust", "asynchronous" ], "Title": "Async streaming of Reddit posts" }
262635
<p>This code is for changing local user password on remote machines. According to security passwords of privilege accounts need to change once in a while. Script trying to connect to a machine and trying to change a password. Then build custom object with results of an attempt.</p> <pre><code>function Set-UserPassword { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 1)] [string]$User, [Parameter(Mandatory = $true, Position = 2)] [string]$NewPassword ) try { Set-LocalUser -Name $User -Password (ConvertTo-SecureString $NewPassword -AsPlainText -Force) -ErrorAction Stop $pwdSetResult = &quot;Password has been changed&quot; $isSuccess = $true } catch { $pwdSetResult = ($_.Exception).Message $isSuccess = $false } return [PSCustomObject]@{ 'ComputerName' = $env:COMPUTERNAME 'isSuccess' = $isSuccess 'Message' = $pwdSetResult } } function Set-UserPasswordRemotely { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 1)] [string]$ComputerName, [Parameter(Mandatory = $true, Position = 2)] [string]$User, [Parameter(Mandatory = $true, Position = 3)] [string]$NewPassword ) $param = @{ ComputerName = $ComputerName ScriptBlock = ${function:Set-UserPassword} ArgumentList = $User, $NewPassword ErrorAction = 'stop' } try { $invokeResult = (Invoke-Command @param).Message $isSuccess = (Invoke-Command @param).isSuccess } catch { $invokeResult = ($_.Exception).Message $isSuccess = $false } return [PSCustomObject]@{ 'ComputerName' = $ComputerName 'isSuccess' = $isSuccess 'Message' = $invokeResult } } $x = @() $x += Set-UserPasswordRemotely -ComputerName sm0017d -User localadmin -NewPassword &quot;dkuf1234&quot; $x += Set-UserPasswordRemotely -ComputerName sm0027d -User localadmin -NewPassword &quot;dkuf1234&quot; $x += Set-UserPasswordRemotely -ComputerName sm0027d -User localadmin -NewPassword &quot;1&quot; $x | Out-GridView </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T23:32:10.330", "Id": "518422", "Score": "2", "body": "[1] function parameter positions otta start with ZERO, not `1`. ///// [2] adding to an array with `+=` is generally a bad habit. either loop thru the list and assign the loop output to a $Var, OR use a collection type that has a working `.Add()` method ... like the `generic.list` type. ///// [3] have you looked at the LAPS stuff for this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T16:37:54.393", "Id": "518467", "Score": "1", "body": "@Lee_Dailey thanks for LAPS tip, official solution from Microsoft is always better. I need to check with my boss." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:08:57.027", "Id": "518477", "Score": "0", "body": "you are most welcome! glad to help a little bit ... [*grin*]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T07:30:25.430", "Id": "518748", "Score": "1", "body": "`$invokeResult = (Invoke-Command @param).Message` \n `$isSuccess = (Invoke-Command @param).isSuccess`\n \nShould become \n`$res = (Invoke-Command @param) \n$invokeResult = $res.Message \n$isSuccess = $res.isSuccess` \n\n \n`+=` destroys a static array and recreates a new one with the new element, it's a performance hit. \nThe .IsFixedSize(boolean) property of an array demonstrates the availability of the .Add() method, which is much more efficient." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T18:45:39.590", "Id": "262643", "Score": "0", "Tags": [ "powershell" ], "Title": "Changing password on remote machine. Try-catch, custom object building" }
262643
<p>A junior developer here.</p> <p>I wrote a simple javascript custom element code here: <a href="https://codepen.io/rndbox/pen/mdWxryw" rel="nofollow noreferrer">https://codepen.io/rndbox/pen/mdWxryw</a> as clean as I could with some advice from <a href="https://www.youtube.com/watch?v=g2nMKzhkvxw" rel="nofollow noreferrer">Junior Vs Senior Code - How To Write Better Code</a>.</p> <p>If possible, I would appreciate, if any willing Javascript <strong>Senior</strong> developer could improve / re-write my code in a more <strong>&quot;pro&quot;</strong> style so I can use his/her version as a reference/guideline on: better naming variables,better comment, use design pattern (if any), how to validate properly, check errors etc..</p> <p>Here is the JS code:</p> <pre><code>// Define a custom Element class Onixjs extends HTMLElement { // Set default options static defaultOptions = { speed: .65, pauseDuration: 2000, textsGap: '30%', // Margin between the leading and trailing text textTag: 'span', gradientsWidth: 15, // if &gt; 0 add gradient (width = gradientsWidth px) at the start and the and of the container }; /*== CONSTRUCTOR ==*/ constructor() { super(); this.defaultInnerHTML = this.innerHTML; this.options = { ...Onixjs.defaultOptions}; this.options.container = this.parentNode; this.onixjs = null; // Ref to the slider text outer html this.textsGapUnities = ['%','px']; // Possible unity for the textsGap width // Animation variables and states this.currentTranslation = this.options.gradientsWidth; this.rafID = null; this.timeoutID = null; this.isPaused = false; this.startTimeout = 0; } // Set options set opts(opts) { this.options = {...this.options, ...opts} this.update(); } /*== HELPERS ==*/ debounce = function(func, ms) { // author: javascript.info const _ = this; return function() { clearTimeout(_.timeout); _.timeout = setTimeout(() =&gt; func.apply(this, arguments), ms); }; } toHTML(string){ const outer = document.createElement('div'); outer.innerHTML = string; let html = string; if( outer.children.length == 1){ html = outer.children[0]; } else if( outer.children.length &gt; 1){ const el = document.createElement('div'); el.appendChild(outer); html = el; } return html; } /*==============*/ /*===== THE STYLE =======*/ setStyle(){ this.innerHTML = ` &lt;style&gt; .onixjs *{ box-sizing: border-box; } .onixjs{ width: 100%; overflow: hidden; position: relative; } .onix__inner{ display: flex; } /* text */ .onix__text{ margin: 0; display: inline-block; white-space: nowrap; } /* gradient */ .onix__gradients{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; } .onix__gradient{ display: block; height: 100%; position: absolute; top: 0; /* to edit */ /*border: 1px solid blue;*/ } .onix__gradient--is_left{ left: 0; background: linear-gradient(to left, rgba(255, 255, 255, 0), #fff 85%) } .onix__gradient--is_right{ right: 0; background: linear-gradient(to right, rgba(255, 255, 255, 0), #fff 85%) } &lt;/style&gt; ` } // Check if the text overflows its parent textIsOverflowing(){ if(!this.options.container){ return false }; // Create a &quot;ruler&quot; element const ruler = document.createElement('div') ruler.innerHTML = this.defaultInnerHTML; // Hide the element const styles = { &quot;visibility&quot;: &quot;hidden&quot;, &quot;position&quot;: &quot;absolute&quot; } Object.assign(ruler.style, styles); // Add to container... this.options.container.appendChild(ruler); // Check its width... const rulerWidth = ruler.offsetWidth; const containerWidth = this.options.container? this.options.container.offsetWidth : rulerWidth; // ...Then remove ruler.remove() return rulerWidth &gt; containerWidth; } // Convert textsGap to Number // '10px' -&gt; 10 // '10%' -&gt; 10 getTextsGapNb(unity){ const gap = this.options.textsGap; const nb = Number(gap.replace(unity,'')); return isNaN(nb)? 0 : nb; } // Convert textsGap value to absolute px value number // '10px' -&gt; 10 // ex : '10%' -&gt; 108.5 getTextsGapPx(containerWidth){ let unity = '%'; const gap = this.options.textsGap; let pxValue = 0; this.textsGapUnities.forEach((unit)=&gt;{ if(gap.includes(unit)){ unity = unit } }) if(unity == '%'){ pxValue = this.getTextsGapNb('%') / 100 * containerWidth; }else if(unity == 'px'){ pxValue = this.getTextsGapNb('px') } return pxValue; } buildLeadingText(){ /* creates leading/head text */ const leadingText = document.createElement(this.options.textTag); leadingText.classList = 'onix__text onix__text--is_heading'; leadingText.textContent = this.defaultInnerHTML; return leadingText; } buildTrailingText(){ const trailingText = document.createElement( this.options.textTag ); trailingText.className = 'onix__text onix__text--is_trailing'; trailingText.textContent = this.defaultInnerHTML; // Add gap between heading and trailing text // The gap width must be higher than the gradients width const gradsWidth = this.options.gradientsWidth; const _gap = this.getTextsGapPx(this.options.container.offsetWidth); const gap = _gap &gt; gradsWidth ? _gap : gradsWidth ; trailingText.style.marginLeft = `${ gap }px`; return trailingText; } buildGradients(){ if( this.options.gradientsWidth &lt; 0){ return } /* creates &amp; adds gradients */ const gradsWidth = this.options.gradientsWidth; const gradients = document.createElement('div'); gradients.className = 'onix__gradients'; const gradientLeft = document.createElement('span'); gradientLeft.className = 'onix__gradient onix__gradient--is_left'; const gradientRight = document.createElement('span'); gradientRight.className = 'onix__gradient onix__gradient--is_right'; gradientLeft.style.width = `${gradsWidth}px`; gradientRight.style.width = `${gradsWidth}px`; gradients.appendChild( gradientLeft ); gradients.appendChild( gradientRight ); return gradients; } buildConcreate(){ if(this.toHTML(this.defaultInnerHTML) instanceof HTMLElement){ throw new Error('onix-js takes a simple string, not an HTMLElement') } const docFrag = document.createDocumentFragment(); /* creates container and save reference*/ this.onixjs = document.createElement('div'); const onixjs = this.onixjs; onixjs.classList.add('onixjs'); /* creates inner container */ const onixInner = document.createElement('div'); onixInner.classList.add('onix__inner'); /* appending html */ onixInner.appendChild(this.buildLeadingText()); onixInner.appendChild(this.buildTrailingText()); // Outer doesnt exist append it to container onixjs.appendChild(onixInner); onixjs.appendChild(this.buildGradients()); /* append html to page */ docFrag.appendChild(onixjs); try { // Clean then append new content this.setStyle() this.appendChild(docFrag); } catch (error) { console.error(error); } } buildDefaultContent(){ this.innerHTML = this.defaultInnerHTML; } // Back to default text or init scroll text update(){ const scrollWasInitialized = this.querySelector('.onixjs') !== null; const scrollShouldInitialize = this.textIsOverflowing(); if(!scrollWasInitialized &amp;&amp; scrollShouldInitialize){ this.init(); }else if(scrollWasInitialized &amp;&amp; !scrollShouldInitialize){ this.stopAnimation(); this.onixjs.remove(); this.buildDefaultContent(); }else if(scrollWasInitialized &amp;&amp; scrollShouldInitialize){ this.stopAnimation(); this.onixjs.remove(); this.init(); }else { this.stopAnimation(); } } debouncedUpdate(){ this.debounce(this.update.bind(this), 1500)(); } /*== Animation ==*/ setPos(position=0){ const onixInner = this.onixjs.querySelector('.onix__inner'); onixInner.style.cssText = `transform: translateX(${position}px)`; } // Manage scroll and check pause translateX(){ const gapWidth = this.getTextsGapPx(this.options.container.offsetWidth); const gradientsWidth = this.options.gradientsWidth; const leading = this.onixjs.querySelector('.onix__text--is_heading'); const maxTranslation = leading.offsetWidth + gapWidth; const maxTranslationWithOffset = maxTranslation - gradientsWidth; const step = this.options.speed; let newTranslation = this.currentTranslation &gt; 0 ? (this.currentTranslation - step) : - Math.abs((this.currentTranslation - step)); // Should Pause the animation if(Math.abs(newTranslation) &gt; (maxTranslationWithOffset)){ this.isPaused = true this.currentTranslation = gradientsWidth this.setPos(gradientsWidth); // Continue after pause this.timeoutID = setTimeout(this.continue.bind(this), this.options.pauseDuration) return; } this.currentTranslation = newTranslation this.setPos(this.currentTranslation); } // Loop animation and pause animation loopTranslationAnimation(){ if(!this.isPaused){ this.translateX(); this.rafID = window.requestAnimationFrame(this.loopTranslationAnimation.bind(this)); }else{ this.pause(); } } initAnimation(){ clearTimeout(this.startTimeout); this.startTimeout = window.setTimeout(this.loopTranslationAnimation.bind(this), this.options.pauseDuration); } // Loop animation with start position and delay beginAnimation(){ this.isPaused = false; this.currentTranslation = this.options.gradientsWidth; this.setPos(this.currentTranslation); this.initAnimation(); } continue(){ this.isPaused = false; this.loopTranslationAnimation(); } pause(){ window.cancelAnimationFrame(this.rafID); } stopAnimation(){ this.isPaused = true; clearTimeout(this.timeoutID); this.pause(); } bindImmediateEvents(){ window.addEventListener('resize', this.debouncedUpdate.bind(this)); } unbindImmediateEvents(){ window.removeEventListener('resize', this.debouncedUpdate.bind(this)); } bindEvents(){ // Pause this.onixjs.addEventListener('mouseover',this.stopAnimation.bind(this)) // Continue this.onixjs.addEventListener('mouseleave',this.continue.bind(this)) } init(){ this.bindImmediateEvents(); if(!this.textIsOverflowing()){return} this.buildConcreate(); this.bindEvents(); this.beginAnimation(); } // Custom element cyclelife hooks connectedCallback(){ this.init(); } disconnectedCallback(){ this.stopAnimation(); } } customElements.define(&quot;onix-js&quot;, Onixjs); /*================= Add Options ==================*/ const onixjs = document.querySelector(&quot;onix-js&quot;); onixjs.opts = { speed: .8, textsGap: '40%', textTag: 'h3', } </code></pre> <p>The HTML :</p> <pre><code> &lt;div class=&quot;player__sound_title_container&quot;&gt; &lt;!-- Use custom element --&gt; &lt;onix-js&gt; If You Cant Ride Two Horses At Once...You Should Get Out Of The Circus &lt;/onix-js&gt; &lt;/div&gt; </code></pre> <p>Thanks very much!</p> <p>Ps: the code is in english although french is my native language.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:23:28.417", "Id": "518480", "Score": "0", "body": "The video shows what \"clean code\" may look like but doesn't show how to get there. I would highly advise that you check out [Wealcome](https://www.linkedin.com/company/wealcomecompany/) and [Michaël Azerhad](https://www.linkedin.com/in/micha%C3%ABl-azerhad-9058a044/) (the founder) on his talks on what real TDD is. He happens to be french as well. Doing proper TDD will force you to write your code better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:27:32.417", "Id": "518481", "Score": "0", "body": "That being said, the things that sticks out to me as a big no no is that you've essentially written one class that handles everything: the framework-like logic, helpers, the styles. You're essentially mixing a lot of different concepts together. You should probably separate the different parts, which will make things a lot easier to test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:31:04.200", "Id": "518482", "Score": "1", "body": "Regarding comments, they're not really needed as your tests should logically explain how your code works. Clean code should be understandable just from looking at the code. Comments are useful for documentation purposes on how to use your library (js-doc for example). If you had to implement something complex without having a simpler solution, then sure a comment or two would help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:32:49.327", "Id": "518483", "Score": "0", "body": "Validation and error checking will come naturally with TDD." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T19:01:56.287", "Id": "262645", "Score": "2", "Tags": [ "javascript", "ecmascript-6", "plugin" ], "Title": "Custom HTML Element with scrolling text" }
262645
<p>Sifting is used to create a Latin Square of distinct symbols. The sifting is implemented by swaps on an array. The symbols might be strings or integer, but they are required to be distinct. Notably, this requires deep copy so that the whole Latin Square is not sifted by the same 1.</p> <pre><code>import copy def make_latin_square(symbols): if symbols is None: raise ValueError(&quot;symbols is required to not be None&quot;) square = [] for row in range(len(symbols)): symbols[0], symbols[row] = symbols[row], symbols[0] square.append(copy.deepcopy(symbols)) return square def test_make_latin_square(): assert make_latin_square([0]) == [[0]] assert make_latin_square([0, 1, 2]) == [[0, 1, 2], [1, 0, 2], [2, 0, 1]] assert make_latin_square([-1, -2, -3]) == [[-1, -2, -3], [-2, -1, -3], [-3, -1, -2]] test_make_latin_square() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T19:55:45.747", "Id": "518400", "Score": "2", "body": "This is not a latin square. `[[0, 1, 2], [1, 0, 2], [2, 0, 1]]` has `2` in the 3rd column twice, and `0` in the second column twice. It looks like your test case was created with the output of your function, not a real test case. Which is the same issue as your original [post](https://codereview.stackexchange.com/q/262630/100620) had." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T20:06:37.120", "Id": "518401", "Score": "5", "body": "I recommend implementing a function `is_latin_square(square)`, that checks if a square meets all the criteria for a latin square. Once you have that working correctly you won't have to hardcode test case outcomes, which is *obviously* rather error-prone." } ]
[ { "body": "<p>The bug is that a swap between two elements will not result in a Latin square. Instead, (row + col) % (rows * cols) generates a unique number for each element of the Latin square.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:01:03.510", "Id": "262756", "ParentId": "262646", "Score": "0" } } ]
{ "AcceptedAnswerId": "262756", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T19:04:58.710", "Id": "262646", "Score": "-3", "Tags": [ "python", "python-3.x" ], "Title": "Generating a Latin Square (Modified Algorithm)" }
262646
<p>The code is written in TypeScript.</p> <pre><code>export function waitFor&lt;T, R&gt; ( reducer: (acc: R, value: T) =&gt; R, initial: R, condition: (accumulated: R) =&gt; boolean, ): OperatorFunction&lt;T, R&gt; { return (source$: Observable&lt;T&gt;) =&gt; { return new Observable&lt;R&gt;((subscriber) =&gt; { let accumulated: R = initial return source$.subscribe({ next (value) { accumulated = reducer(accumulated, value) if (condition(accumulated)) { subscriber.next(accumulated) subscriber.complete() } }, error (error) { subscriber.error(error) }, complete () { subscriber.complete() }, }) }) } } </code></pre> <p>Here's a passing marable test which should make it more obvious what the operator is supposed to do.</p> <pre><code>import { marbles } from 'rxjs-marbles/jest' import { waitFor } from './utils' describe(`waitFor`, () =&gt; { it(`waits for sum to be over 12`, marbles(m =&gt; { const source = m.cold(' ----a----b----c----d----e----f----g------|', { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7 }) const expected = m.cold('------------------------(x|)', { x: 15 }) const actual = source.pipe(waitFor((a, b) =&gt; a + b, 0, sum =&gt; sum &gt; 12)) m.expect(actual).toBeObservable(expected) })) }) </code></pre> <p>I'm mostly interested in the best practices of writing the operator. Did I miss unsubscribing from something and introduced a memory leak? <del>Did I reinvent the wheel, i.e. could I have achieved the same versatility of the operator by combining the existing standard ones?</del></p> <p>I realize now this is just a <code>scan</code> followed by a <code>skipUntil</code> and <code>first</code>. Ignoring this, I'd still like to know if my logic was sound and if I missed something important in my custom operator.</p>
[]
[ { "body": "<p>Yes, this implementation looks sound to me.</p>\n<p>Also you should first try to implement new operators like this by combining existing operators, since that leaves less room for mistakes, oversights, and let you piggyback on all the years of improvements the library wend trough.</p>\n<p>You already mentioned you re-implemented <code>scan</code> + something extra. Myself i would use <code>find</code>.</p>\n<p>The resulting operator below already has 2 minor improvements:</p>\n<pre><code>export function waitFor&lt;T, R&gt; (\n reducer: (acc: R | S, value: T, index: number) =&gt; R,\n seed: S,\n condition: (accumulated: R, index: number) =&gt; boolean,\n): OperatorFunction&lt;T, R&gt; {\n return (source$: Observable&lt;T&gt;) =&gt;\n source$.pipe(\n scan(reducer, initial),\n find(condition)\n )\n}\n</code></pre>\n<p>The reducer and the condition now have an index parameter.</p>\n<p>The <code>scan</code> operator gave me inspiration to separate the type of the seed and the accumulated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T06:46:15.953", "Id": "262669", "ParentId": "262649", "Score": "1" } } ]
{ "AcceptedAnswerId": "262669", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T20:06:22.137", "Id": "262649", "Score": "0", "Tags": [ "javascript", "typescript", "rxjs" ], "Title": "A custom RxJS operator which emits (and completes) once a condition has been satisfied for all previous values of the source" }
262649
<p>I recently picked up C, because I am getting tired of the hell that is Java Enterprise development. I decided that writing a Huffman compressor will be a great little exercise, and I have always wanted to write a compression algorithm. I want some pointers(get it) on how to make the code more idiomatic, modular and less verbose.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define MAX_SZ 128 #define MAX_CODE_LEN 64 int counts[MAX_SZ]; char codes[MAX_SZ][MAX_CODE_LEN]; typedef struct Node { char character; int count; struct Node *left; struct Node *right; } Node; void calculate_prob(char *str, int *counts) { int len = strlen(str); for (int i = 0; i &lt; len; i++) { counts[*str++]++; } } int comparator(const void *a, const void *b) { Node *n1 = (Node *)a; Node *n2 = (Node *)b; return (n1-&gt;count - n2-&gt;count); } Node *find_and_remove_min(Node *nodes, int sz) { int idx = 0; Node *minNode = &amp;nodes[0]; for (int i = 0; i &lt; sz; i++) { if (nodes[i].count &lt; minNode-&gt;count) { minNode = &amp;nodes[i]; idx = i; } } Node *node = (Node *)malloc(sizeof(Node)); memcpy(node, minNode, sizeof(Node)); nodes[idx] = nodes[sz - 1]; return node; } void dfs(Node *node, char *path, int sz) { if (node == NULL) { return; } if (node-&gt;left == NULL &amp;&amp; node-&gt;right == NULL) { strncpy(codes[node-&gt;character], path, sz); return; } path[sz] = '0'; dfs(node-&gt;left, path, sz + 1); path[sz] = '1'; dfs(node-&gt;right, path, sz + 1); } char *fileToString(char *file_name) { FILE *file = fopen(file_name, &quot;r&quot;); if (file == NULL) return NULL; fseek(file, 0, SEEK_END); long int size = ftell(file); fclose(file); file = fopen(file_name, &quot;r&quot;); char *str = (char *)malloc(size); int bytes_read = fread(str, sizeof(char), size, file); fclose(file); return str; } void writeCodeBook(FILE* file){ for (int i = 0; i &lt; MAX_SZ; i++) { if (codes[i][0] == '\0') { continue; } putc((char)i, file); putc(':', file); fwrite(codes[i], sizeof(char), strlen(codes[i]), file); putc('\n', file); } } void writeBitToFile(unsigned char bit, FILE *file, int flush) { static int count = 0; static char buffer = 0; if(flush){ buffer &lt;&lt;= (8 - count); fwrite(&amp;buffer, sizeof(buffer), 1, file); return; } buffer &lt;&lt;= 1; // Make room for next bit. if (bit) buffer |= 1; // Set if necessary. count++; if (count == 8) { fwrite(&amp;buffer, sizeof(buffer), 1, file); // Error handling elided. buffer = 0; count = 0; } } int main(int argc, char **argv) { char *str = NULL; if (argc &gt; 1) { str = fileToString(argv[1]); } else { return 1; } calculate_prob(str, counts); int node_count = 0; for (int i = 0; i &lt; MAX_SZ; i++) { if (counts[i] != 0) { node_count++; } } const int SZ = node_count; Node nodes[SZ]; for (int i = 0, idx = 0; i &lt; MAX_SZ; i++) { if (counts[i] != 0) { struct Node node = {(char)i, counts[i], NULL, NULL}; nodes[idx++] = node; } } qsort(nodes, SZ, sizeof(Node), comparator); int sz = SZ; Node *root = NULL; while (sz != 1) { struct Node *min = find_and_remove_min(nodes, sz); struct Node *min_2 = NULL; sz--; min_2 = find_and_remove_min(nodes, sz); Node new_node = {'\0', min-&gt;count + min_2-&gt;count, min, min_2}; nodes[sz - 1] = new_node; root = &amp;new_node; } char path[MAX_CODE_LEN]; memset(path, '\0', MAX_CODE_LEN); dfs(root, path, 0); FILE *file = NULL; if (argc &gt; 2) { file = fopen(argv[2], &quot;w+&quot;); } else { return 1; } writeCodeBook(file); for (char *s = str; *s; s++) { char *code = codes[*s]; int len = strlen(code); for (int i = 0; i &lt; len; i++) { unsigned char bit = code[i] - '0'; // printf(&quot;%d&quot;, bit); writeBitToFile(bit, file, 0); } } writeBitToFile(0, file, 1); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T22:39:27.267", "Id": "518419", "Score": "1", "body": "Why not C++? It would avoid some of the low-levelness that trips you up if you are used to Java (e.g. strings), is far less verbose, and potentially faster due to more extensive compile-time evaluation, and more modular since it can use templates and not require pointers to consecutive bytes, and makes it easy to have persistent state that you can feed input into via multiple separate calls (e.g. one buffer-full at a time)." } ]
[ { "body": "<p>Quite well-formatted, but does not quite escape your Java roots.<br />\nUnfortunately, they lead to unidiomatic code, inefficient code, and even bugs.</p>\n<ol>\n<li><p>A string in C is a data-structure, not a type. Specifically, it's a sequence of non-nul elements terminated and including the terminating nul.<br />\nYes, that means embedded zeros are not supported. Also, you must mind the terminator. If you need something more sophisticated, write it yourself or include third-party code.</p>\n<ol>\n<li><p><a href=\"//en.cppreference.com/w/c/string/byte/strlen\" rel=\"nofollow noreferrer\"><code>strlen()</code></a> just gives you the index of the terminator. Using it to determine how often your loop iterating over a string should iterate is a waste, just test for the terminator directly.</p>\n</li>\n<li><p><a href=\"//en.cppreference.com/w/c/string/byte/strncpy\" rel=\"nofollow noreferrer\"><code>strncpy()</code></a> does not do what you expect. Despite its name, it is not quite a string-function.<br />\nIt copies up to n characters from the source, stopping if encountering the string terminator. The rest of the target-buffer is nulled out.</p>\n<ul>\n<li><p>Yes, that means it always writes the whole buffer, even if you only want to copy an empty string.</p>\n</li>\n<li><p>Yes, the target might not begin with a string after the call.</p>\n</li>\n</ul>\n</li>\n<li><p>A file might contain nulls. Also, the random garbage beyond the copy of the file-contents might be null or not, but you shouldn't assume, even if you were allowed to access it at all.<br />\nShould you abandon reading it into a string, consider leaving standard C and memory-mapping instead.</p>\n</li>\n</ol>\n</li>\n<li><p>Java lacks unsigned types. If a value cannot ever be negative, consider whether one makes sense.</p>\n</li>\n<li><p><code>size_t</code> is the type designed for object sizes and thus also array-counts, being guaranteed to be big enough and supposed not to be too excessive.</p>\n</li>\n<li><p>Const-correctness is important for letting the compiler help find errors.</p>\n<p>Thus if a pointee is never modified by design, let the type reflect it. Doing so for function-arguments makes the function more broadly applicable.</p>\n</li>\n<li><p>Avoid casting. Casting is telling the compiler to blindly trust you to get it right.</p>\n<p>Especially, never cast a void-pointer to/from another data-pointer, as that allows you to break const-correctness, like in <code>comparator()</code>. Luckily, though the code invites UB, you don't <em>actually</em> modify the pointee.</p>\n</li>\n<li><p>Avoid <code>sizeof(TYPE)</code>. This duplicated type-info is impossible for the compiler to check, and often needs careful manual checking.<br />\n<code>sizeof *pointer</code> couples the size to the target, avoiding those problems. It is much more refactoring and general maintenance friendly.</p>\n<p>Also see <em><a href=\"//stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc\">Do I cast the result of malloc?\n</a></em> <strong>No.</strong></p>\n</li>\n<li><p>C knows struct-assignment. Use it instead of <code>memcpy()</code> for example in <code>find_and_remove_min()</code>.</p>\n</li>\n<li><p>Java numbers and pointers have no truth-value. C ones do, as truthy is defined as <code>value != 0</code>, and literal zero in pointer-context is a null pointer constant. A true boolean type was only added in C99. Don't be shy to take advantage.</p>\n</li>\n<li><p><code>calculate_prob()</code> doesn't calculate probabilities. It counts occurrences, creating a histogram.</p>\n</li>\n<li><p>There is a dedicated function for writing a string to a file: <a href=\"//en.cppreference.com/w/c/io/fputs\" rel=\"nofollow noreferrer\"><code>fputs()</code></a>.</p>\n</li>\n<li><p><a href=\"//en.cppreference.com/w/c/io/fputc\" rel=\"nofollow noreferrer\"><code>putc()</code></a> expects an <code>int</code>, which it internally casts to <code>unsigned char</code> before output. Casting the argument to <code>char</code> yourself does not help, but at least it does not hinder either.</p>\n</li>\n<li><p>Consider extracting most of <code>main()</code> into separate functions. Just validate the arguments, open files, and call out for the rest after.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T22:25:13.323", "Id": "262655", "ParentId": "262651", "Score": "4" } }, { "body": "<p><code>memcpy(node, minNode, sizeof(Node));</code></p>\n<p>Hmm, doesn't C let you assign structures? <code>*node = *minNode;</code></p>\n<hr />\n<p>Use <code>const</code> where you can.</p>\n<hr />\n<p>Don't compare against <code>NULL</code>. Just use <code>if(p)</code> or <code>if(!p)</code>;</p>\n<hr />\n<p><code>return</code> is not a function call. Don't put superfluous parenthesis around the value to be returned.</p>\n<hr />\n<p>I see you are already aware of some good things, like initializing variable when declared, not declaring them 'till you're ready, and using <code>const</code> with pointers for the input. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T17:27:15.420", "Id": "518472", "Score": "0", "body": "\"Don't compare against NULL. Just use .... if(!p);\" --> `p == NULL` is just fine. This borders on style issues and so the _best_ is to follow one's group style guide." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T22:45:35.723", "Id": "262657", "ParentId": "262651", "Score": "2" } } ]
{ "AcceptedAnswerId": "262655", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T20:48:36.973", "Id": "262651", "Score": "1", "Tags": [ "algorithm", "c", "compression" ], "Title": "Huffman compressor in plain C" }
262651
<p>Can someone give me any suggestions over my code that I made for this task? Also how much of 10 would rate it ?</p> <p>Suppose a simply linked list whose node is of type node and contains a student's name, registration number, and grade(vathmos), such as shown below:</p> <pre><code>struct node { char name [30]; int ΑΜ; float vathmos; struct node *next; }; </code></pre> <p>. Write a consonant</p> <pre><code>struct node *delete (struct node *head) </code></pre> <p>which runs through the list that starts at the head and deletes the penultimate one node of the list that starts at the head.</p> <p>. Write a function</p> <pre><code>display (struct node *head) </code></pre> <p>which runs through all the items in the list that starts at the head, from the beginning to the end, and for each node with a score from 0.0 up to 4.9 displays on the screen name, registration number and grade. It basically prints its data students who do not pass the course.</p> <p>ATTENTION: You do NOT need to write the main () function and create it list. We believe that our list has already been created, some have already been registered items and we have a pointer to the beginning of the list.</p> <pre><code> struct node{ char name [30]; int AM; float vathmos; struct node *next; }; struct node *delete (struct node *head){ struct node *temp = head; struct node *temp1; if(temp == NULL){ return head; }else if(temp-&gt;next == NULL){ return head; }else if(temp-&gt;next-&gt;next == NULL){ head = temp-&gt;next; free(temp); return head; }else{ while(temp-&gt;next-&gt;next-&gt;next != NULL){ temp = temp-&gt;next; } temp1 = temp-&gt;next; temp-&gt;next = temp-&gt;next-&gt;next; free(temp1); return head; } } void display (struct node * head){ struct node *temp = head; while(temp != NULL){ if(temp-&gt;vathmos &lt;= 4.9){ printf(&quot;NAME: %s\nAM: %d\nVathmos:%f\n&quot;, temp-&gt;name, temp-&gt;AM, temp-&gt;vathmos); } temp = temp-&gt;next; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T09:07:03.090", "Id": "518435", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T17:38:03.353", "Id": "518473", "Score": "1", "body": "Rikos Sina, \"how much of 10 would rate it ?\" --> Use an auto-formatter for the code. It saves time and makes your code more understandable and professional." } ]
[ { "body": "<ul>\n<li><p>I suspect that the code works. However, most people will frown at <code>-&gt;next-&gt;next-&gt;next</code>. If you'd need to delete the third from last (or 6th, or 42nd), what would you do?</p>\n<p>Consider writing a more generic function,</p>\n<pre><code> struct node * delete(struct node * head, size_t distance_from_end)\n</code></pre>\n<p>A small hint: having a helper function <code>struct node * advance(struct node *, size_t)</code> will be very beneficial.</p>\n</li>\n<li><p>Since we don't know <em>how</em> the list was constructed, we shouldn't blindly <code>free</code> the deleted node. Are we sure it was indeed dynamically allocated?</p>\n</li>\n<li><p>Technically testing for <code>temp-&gt;vathmos &lt;= 4.9</code> is wrong. The problem statement asks for nodes <em>with a score from 0.0 up to 4.9</em>, that is nodes with negative score should not be displayed. Ask your teacher for clarification on what to do with negative scores.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T17:24:00.427", "Id": "518470", "Score": "0", "body": "Thanks you for your opinion , it helps a lot @vnp" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T04:00:42.670", "Id": "262666", "ParentId": "262652", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T21:56:05.527", "Id": "262652", "Score": "1", "Tags": [ "algorithm", "c", "homework" ], "Title": "C code in Data structures" }
262652
<p>I'm 16 years old and no one to help me, no one to give any advice or constructive criticism, I'm aimless. I'll leave the link to my last code (github), a program that sends an email to everyone registered in the database. I would like some advice and project/content ideas for me to evolve. Evaluate my project sincerely.</p> <p><em><strong>UPDATE: According to the last suggestion (in the last post), the program was very dependent, not following the S.O.L.I.D concepts, one class was doing all the work, so I created 2 more classes to divide the functions (FactoryConnection and DAO).</strong></em></p> <p>Class DAO, this class is responsible for creating the SELECT statement (MySql) that connects to return users:</p> <pre><code>package project; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class DAO { static Connection conn; static ResultSet users; static PreparedStatement ps; protected static ResultSet retriveUsers() { FactoryConnection.closeConnections(conn, ps, users); // if there is any new connection, it will close the previous one try { conn = FactoryConnection.getConnectionToMySql(); ps = (PreparedStatement) conn.prepareStatement(&quot;select * from users&quot;); users = ps.executeQuery(); return users; } catch (Exception e) { e.printStackTrace(); } return null; } } </code></pre> <p>Class FactoryConnection, this class will create the connection to MySql (getConnectionToMySql)database and close the connections (closeConnections) when called:</p> <pre><code>package project; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.dbutils.DbUtils; public class FactoryConnection { protected static Connection getConnectionToMySql() throws SQLException { Connection conn = DriverManager.getConnection(&quot;jdbc:mysql://localhost:3306/emailproject?useTimezone=true&amp;serverTimezone=UTC&quot;, &quot;root&quot;, &quot;&quot;); return conn; } protected static void closeConnections(Connection conn, PreparedStatement ps, ResultSet users) { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(users); DbUtils.closeQuietly(ps); } } </code></pre> <p>Class JavaMailUtil, this class will send the email to the users (using the DAO class to get the users in database):</p> <pre><code>package project; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.swing.JOptionPane; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class JavaMailUtil { Connection conn; PreparedStatement ps; ResultSet rs; String sender = &quot;testemailforjava16@gmail.com&quot;; String senderPassword = &quot;******&quot;; public void sendEmail(String title, String text) { try { ResultSet users = DAO.retriveUsers(); while (users.next()) { Properties prop = new Properties(); prop.put(&quot;mail.smtp.auth&quot;, true); prop.put(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;); prop.put(&quot;mail.smtp.host&quot;, &quot;smtp.gmail.com&quot;); prop.put(&quot;mail.smtp.port&quot;, &quot;587&quot;); Session session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sender, senderPassword); } }); Message message = prepareMessage(session, sender, users.getString(2), text, title); Transport.send(message); } } catch (Exception e) { JOptionPane.showMessageDialog(null, &quot;Error!&quot;); e.printStackTrace(); return; } JOptionPane.showMessageDialog(null, &quot;Email successfully sent!&quot;); } private static Message prepareMessage(Session session, String sender, String recepient, String text, String title) { try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient)); message.setSubject(title); message.setText(text); return message; } catch (Exception e) { Logger.getLogger(JavaMailUtil.class.getName()).log(Level.SEVERE, null, e); } return null; } } </code></pre> <p>Swing Part, the main class that will call the codes:</p> <pre><code>package windows; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import project.JavaMailUtil; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; import javax.swing.JTextArea; import javax.swing.SwingConstants; public class MainWindow { private JFrame frame; private JTextField txtTitle; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainWindow window = new MainWindow(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow() { initialize(); } /** * Initialize the contents of the frame. */ public void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); JLabel lbl1 = new JLabel(&quot;Title:&quot;); lbl1.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 18)); lbl1.setBounds(10, 81, 43, 26); frame.getContentPane().add(lbl1); JLabel lbl2 = new JLabel(&quot;Text:&quot;); lbl2.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 18)); lbl2.setBounds(10, 133, 43, 26); frame.getContentPane().add(lbl2); txtTitle = new JTextField(); txtTitle.setHorizontalAlignment(SwingConstants.CENTER); txtTitle.setFont(new Font(&quot;Tahoma&quot;, Font.BOLD, 15)); txtTitle.setBounds(54, 77, 342, 37); frame.getContentPane().add(txtTitle); txtTitle.setColumns(10); JButton buttonSend = new JButton(&quot;Send Email&quot;); buttonSend.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 16)); buttonSend.setBounds(269, 227, 127, 23); frame.getContentPane().add(buttonSend); JTextArea txtText = new JTextArea(); txtText.setFont(new Font(&quot;Tahoma&quot;, Font.BOLD, 15)); txtText.setBounds(54, 136, 342, 80); frame.getContentPane().add(txtText); txtText.setLineWrap(true); txtText.setWrapStyleWord(true); JLabel lblNewLabel = new JLabel(&quot;Automatic Sender&quot;); lblNewLabel.setFont(new Font(&quot;Tahoma&quot;, Font.BOLD | Font.ITALIC, 23)); lblNewLabel.setBounds(95, 22, 243, 37); frame.getContentPane().add(lblNewLabel); JButton buttonUsers = new JButton(&quot;Users&quot;); buttonUsers.setFont(new Font(&quot;Tahoma&quot;, Font.PLAIN, 16)); buttonUsers.setBounds(54, 227, 83, 23); frame.getContentPane().add(buttonUsers); // TODO buttonSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JavaMailUtil javaMailUtil = new JavaMailUtil(); buttonSend.setText(&quot;Sending...&quot;); JOptionPane.showMessageDialog(null, &quot;Sending... Wait the alert!&quot;); javaMailUtil.sendEmail(txtTitle.getText(), txtText.getText()); buttonSend.setText(&quot;Send Email&quot;); } }); } } </code></pre> <p><em><strong>GitHub Link: <a href="https://github.com/DaviRibeiro-prog/JAVA/tree/main/EmailSenderProject/src" rel="nofollow noreferrer">https://github.com/DaviRibeiro-prog/JAVA/tree/main/EmailSenderProject/src</a></strong></em></p>
[]
[ { "body": "<p>That's already a nice improvement. However there is a lot of <code>static</code> in your code. <code>static</code> is the &quot;Uncle Ben&quot; keyword; it has &quot;great power but induce great responsibilities&quot;.</p>\n<p>Think back to the <em><strong>O</strong>pen Closed</em> principle of solid. How can I use a local file, or my favourite mail client address book instead of a MySQL database ?</p>\n<p>It would be great to add some abstractions. Why not one <code>AddressBook</code> interface:</p>\n<pre><code>interface AddressBook extends Iterable&lt;String&gt;\n</code></pre>\n<p>That interface will be used anywhere that you want to access retrieve your contacts. But because it is an interface you cannot statically access it (in fact you can but let's forgot about that). You should dynamically pass an instance of that <code>AddressBook</code> to your <code>JavaMailUtil</code>, and the constructor is the perfect candidate for that :</p>\n<pre><code>class JavaMailUtil {\n JavaMailUtil(AddressBook contacts) {\n this.contacts = contacts;\n }\n\n // When sending\n contacts.forEach(contact -&gt; {\n // Your sending logic.\n });\n}\n</code></pre>\n<p>You should try to remove all static keywords from your code and see how it will improve your program by allowing you to easily switch the implementations. Let's do it for the DAO so that you can reuse it for a MySql or MariaDb or any other compliant database.</p>\n<pre><code>class ContactsDao {\n public ContactsDao(ConnectionFactory conns) {\n this.conns = conns;\n } \n}\n</code></pre>\n<p>Do you remember the <em><strong>I</strong>nterface Seggregation</em> principle ?</p>\n<p>One thing with the DAO is that it returns a <code>ResultSet</code>. If I want to swap your DAO with a file, I have to convert my lines to a <code>ResultSet</code>. This will be annoying, error prone and useless because I should have to implement methods that are never used. So it is better to find a simpler model for iterating over all your contacts, and the <code>Iterator&lt;String&gt;</code> is a perfect one.</p>\n<p>You can easily convert your <code>DAO</code> to a <code>ContactsDao</code> or <code>PeristentAddressBook</code> that implement the <code>AddressBook</code> interface.</p>\n<p>With the same idea of creating an interface you can create one to send the messages, on that will use a Gmail account and another to use an Outlook account (or anything else). And, why not, a generic one to send a message, whatever the protocol will be.</p>\n<pre><code>interface Sender {\n void send(String title, String message, String recipient)\n}\n</code></pre>\n<p>Of course many lines of codes will be shared between the two email senders, you can have a look at the existing design patterns to share behaviors between classes. And will probably end with one abstract class that realize the template pattern :</p>\n<pre><code>abstract class SmtpSender implements Sender {\n abstract Session createSession();\n Message prepareMessage(Session session) {\n // ...\n }\n void send(String title, String message, String recipient) {\n Session session = createSession();\n Message message = prepareMessage();\n Transport.send(message);\n } \n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T08:11:36.830", "Id": "262746", "ParentId": "262653", "Score": "1" } } ]
{ "AcceptedAnswerId": "262746", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T22:06:56.870", "Id": "262653", "Score": "0", "Tags": [ "java", "sql", "swing", "email" ], "Title": "Evaluate my program with Java Mail + Sql + Swing" }
262653
<p>I've created a server file, that keeps waiting for clients. When someone connects to the server, he can send messages to the server, and from the server it is broadcasted to all clients.</p> <p>Can you criticize my simple chat? Any possible improvements and changes are welcome. I have 2 files:</p> <p><strong>Server:</strong></p> <pre class="lang-py prettyprint-override"><code> import threading import socket text_type = &quot;utf-8&quot; host = str(socket.gethostbyname(socket.gethostname())) port = 5050 server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind((host,port)) server.listen(4) clients = [] names = [] #This function sends message to all clients on room def broadcast(msg): for i in clients: message = msg.encode(text_type) i.send(message) #This function waits until someone send a message, and then pass it to broadcast() def get_message(client_reference): while True: try: message = client_reference.recv(1024).decode(text_type) broadcast(message) except: index = clients.index(client_reference) clients.remove(client_reference) client_reference.close() name = names[index] broadcast(f&quot;{name} left the chat.&quot;.encode(text_type)) names.remove(name) break #This function waits to new clients, and then store their name and other informations def new_client(): while True: client_reference,client_info = server.accept() name = client_reference.recv(1024).decode(text_type) print(f&quot;Connected with {name}, {client_info}&quot;) names.append(name) clients.append(client_reference) client_reference.send(str(f&quot;Welcome {name}.&quot;).encode(text_type)) broadcast(str(f&quot;{name} joined the chat.&quot;)) thread = threading.Thread(target=get_message, args=[client_reference]) thread.start() new_client() </code></pre> <p><strong>Client:</strong></p> <pre class="lang-py prettyprint-override"><code>import socket import threading text_type = &quot;utf-8&quot; server_ip = &quot;192.168.1.6&quot; port = 5050 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect((server_ip,port)) name = str(input(&quot;Type your name: &quot;)) client.send(name.encode('utf-8')) #This function gets other clients messages, so any client has access to all messages def messages(): while True: try: message = client.recv(1024).decode(text_type) print(message) except: print(&quot;ERROR&quot;) client.close() break #This function waits for the user input(message) def write(): while True: text = str(input(&quot;Digit a message: &quot;)) message = str(f&quot;{name}: {text}&quot;) client.send(message.encode(text_type)) receive_thread = threading.Thread(target=messages) receive_thread.start() write_thread = threading.Thread(target=write) write_thread.start() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T09:21:30.747", "Id": "518438", "Score": "1", "body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." } ]
[ { "body": "<ul>\n<li><code>text_type</code> is really an &quot;encoding&quot;, not a type, so there is a better variable name than this</li>\n<li><code>server</code> should not be a global</li>\n<li><code>server</code> should be wrapped in a <code>with</code> - see <a href=\"https://docs.python.org/3/library/socket.html#socket-objects\" rel=\"nofollow noreferrer\">here</a> about the docs calling out support for context management, and <a href=\"https://docs.python.org/3/reference/compound_stmts.html#the-with-statement\" rel=\"nofollow noreferrer\">here</a> for general information on context management</li>\n<li>Never <code>try/except</code>; you're going to want to catch a more specific exception</li>\n<li>For something that passes around messages whose sequence is not critical, UDP will be more efficient than TCP. Take this with a grain of salt: UDP will also lose a guarantee of packet delivery, so packets may be dropped. Both out-of-sequence and dropped packets are typically rare, so it's a judgement call. UDP is frequently used for streamed audio.</li>\n<li><code>recv(1024)</code> is not a reliable way to get a whole message. Messages may be fragmented between the client and the server, and <code>recv</code> offers no guarantee of returning a whole message. Since your messages are plain strings, about the worst that could happen is that one message gets fragmented within a multi-byte unicode sequence. Read <a href=\"http://docs.python.org/3/howto/sockets.html\" rel=\"nofollow noreferrer\">this</a>, in particular starting at <em>Now we come to the major stumbling block of sockets - <code>send</code> and <code>recv</code></em>.</li>\n<li><code>clients.remove(client_reference)</code> (and <code>index</code>) have O(n) worst-case performance. So a different data structure would help.</li>\n<li>Your current <code>broadcast</code>, in addition to broadcasting to all other clients, broadcasts to the sending client itself. Are you sure that's what you intended?</li>\n<li>Whenever you have two sequences, in this case <code>clients</code> and <code>names</code> whose elements logically align to represent &quot;one thing&quot; (a client), this is a clear case for a single sequence of class instances</li>\n<li>Currently, your design for the client protocol basically accepts any string at all and broadcasts it with no validation or constraints to every other client. One very funny security vulnerability among many is that someone with a trivially-modified client could send anything for their name, and have it change on each message. It's trivially easy to impersonate other users in this system.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:37:21.683", "Id": "518448", "Score": "0", "body": "What should I use instead of recv()?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:53:03.803", "Id": "518449", "Score": "0", "body": "What does \"server should be wrappen in a with\" mean? These are the only points that I don't understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T13:34:39.427", "Id": "518454", "Score": "0", "body": "I would disagree with using UDP over TCP: Switching the order of two messages that are sent at almost the same time is fine, if weird, but losing packets is something I would consider unacceptable, especially since messages may be fragmented, so you would miss part of a message." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T13:41:14.167", "Id": "518455", "Score": "0", "body": "*\"For something that passes around messages whose sequence is not critical, UDP will be more efficient than TCP\"* Yes, but I don't think that applies here. Language depends on context, so re-ordering a person's messages can affect the meaning and cause misunderstandings. And even if that wasn't an issue, you also appear to have control messages, and getting `alice2 is now called alice` and `alice disconnected` out of order is not ideal" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T14:02:01.820", "Id": "518456", "Score": "0", "body": "@SaraJ You're (both) right. I've added a little bit of nuance. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T14:09:31.067", "Id": "518458", "Score": "1", "body": "@irtexas19 re. `recv` - read https://docs.python.org/3/howto/sockets.html, in particular starting at _Now we come to the major stumbling block of sockets - `send` and `recv`_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T14:22:58.200", "Id": "518460", "Score": "0", "body": "@Reinderien I'm still working on program (5 hours now i think), but most of the updates are offline. I'll let you know when I finish it. Thanks for the support." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:24:50.597", "Id": "518612", "Score": "0", "body": "@Reinderien I improved my program, I think. Please check it: https://codereview.stackexchange.com/questions/262754/tcp-chat-room-in-python3" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T00:44:13.083", "Id": "262662", "ParentId": "262658", "Score": "4" } } ]
{ "AcceptedAnswerId": "262662", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T23:00:34.867", "Id": "262658", "Score": "4", "Tags": [ "python-3.x", "socket" ], "Title": "TCP chat room in Python 3" }
262658
<p>While reading <a href="https://people.eecs.berkeley.edu/%7Ebh/ss-toc2.html" rel="nofollow noreferrer"><strong>Simply Scheme</strong></a> by <em>Brian Harvey</em> and <em>Matthew Wright</em>:</p> <blockquote> <p><a href="https://people.eecs.berkeley.edu/%7Ebh/ssch2/functions.html" rel="nofollow noreferrer">Part I: Chapter 2 Functions</a></p> </blockquote> <blockquote> <p>In this chapter you are going to use the computer to explore functions, but you are <em>not</em> going to use the standard Scheme notation as in the rest of the book. That’s because, in this chapter, we want to separate the idea of functions from the complexities of programming language notation. For example, real Scheme notation lets you write expressions that involve more than one function, but in this chapter you can only use one at a time. To get into this chapter’s special computer interface, first start running Scheme as you did in the first chapter, then type <code>(load &quot;functions.scm&quot;)</code> to tell Scheme to read the program you’ll be using. (If you have trouble loading the program, look in Appendix A for further information about <code>load</code>.) Then, to start the program, type <code>(functions)</code></p> </blockquote> <p>I am using DrRacket with <code>#lang simply-scheme</code> <a href="https://github.com/jbclements/simply-scheme" rel="nofollow noreferrer">Github</a> <a href="https://docs.racket-lang.org/manual@simply-scheme/index.html" rel="nofollow noreferrer">Docs</a>.</p> <p>So I tried to <code>(load &quot;functions.scm&quot;)</code> but got this error back: <code>open-input-file: cannot open input file path: path/to/functions.scm system error: The system cannot find the file specified.; errid=2</code></p> <p>I also tried <code>(load &quot;functions.rkt&quot;)</code> and <code>(require &quot;functions.rkt&quot;)</code>, and got also the same error.</p> <p>So I read the documentation of <code>#lang simply-scheme</code> and found that:</p> <blockquote> <p>FIXME: the other helper libraries haven’t been mapped yet. (things like functions.scm would be nice to have as a library.)</p> </blockquote> <p>So I tried to tackle this problem and implement <code>(functions)</code> with my simple racket and scheme experience that I learned from past books.</p> <p>The notation is interactive and should act like the following:</p> <blockquote> <p>You’ll then be able to carry out interactions like the following.* In the text below we’ve printed what you type in <strong>boldface</strong> and what the <em>computer</em> types in lightface printing:</p> </blockquote> <blockquote> <p>Function: <strong>+</strong> <br /> Argument: <strong>3</strong> <br /> Argument: <strong>5</strong> <br /> The result is: 8</p> </blockquote> <blockquote> <p>Function: <strong>sqrt</strong> <br /> Argument: 144 <br /> The result is: 12</p> </blockquote> <p>So here is my code in 2 versions:</p> <p>First I have defined some helper functions for prompting the user for input:</p> <pre class="lang-lisp prettyprint-override"><code>(define (prompt format-string . args) (apply printf (cons format-string args)) (read)) (define (prompt-until pred? input (bad-input (const &quot;&quot;))) (let ([val (prompt input)]) (cond [(pred? val) val] [else (printf (bad-input val)) (prompt-until pred? input bad-input)]))) </code></pre> <p>I also added variadic functions handling, which I think the book version does not support.</p> <p><em>V1</em>:</p> <pre class="lang-lisp prettyprint-override"><code>(define (functions) (let ([func-symbol (prompt &quot;Function: &quot;)]) (with-handlers ([exn:fail:contract:variable? (lambda (_) (printf &quot;~a is not defined\n\n&quot; func-symbol) (functions))] [exn:fail:contract? (lambda (x) (printf &quot;\nContract violation ~a\n\n&quot; (regexp-replace #rx&quot;: contract violation&quot; (exn-message x) &quot;:&quot;)) (functions))]) (let* ([function (eval func-symbol)] [arity (procedure-arity function)]) (let loop ([func (lambda (x) x)] [current-argument 1] [arguments '()] [max-arity arity]) (cond [(equal? func-symbol 'exit) (printf &quot;exiting (functions)&quot;)] [(not (procedure? function)) (printf &quot;~a is not a procedure/function\n\n&quot; func-symbol) (functions)] [(and (integer? max-arity) (&gt; current-argument max-arity)) (printf &quot;the result is: ~v&quot; (apply function (reverse arguments))) (printf &quot;\n\n&quot;) (functions)] [(arity-at-least? max-arity) (printf &quot;The functions ~a is varadic and can accept arbitrary number of arguments!\nBut accepts minimum of ~a\n&quot; (symbol-&gt;string func-symbol) (arity-at-least-value max-arity)) (loop function current-argument arguments (eval (prompt-until exact-nonnegative-integer? &quot;How many argument do you want to supply (Non-negative Integer): &quot;)))] [else (loop function (add1 current-argument) (cons (eval (prompt (format &quot;Argument ~a: &quot; current-argument))) arguments) max-arity)])))))) </code></pre> <p><em>V2</em>: Here I removed some <code>let</code> bindings and tried to quit early when an abnormal case happens so the recursion doesn't have to expensive with all the checks happening each time.</p> <p>I also added more checks for variadic arity count.</p> <p>I also used a <code>for/list</code> comprehension instead of a hand-made tail recursive loop.</p> <pre class="lang-lisp prettyprint-override"><code>(define (functions) (let ([func-symbol (prompt &quot;Function: &quot;)]) (with-handlers ([exn:fail:contract:variable? (lambda (_) (printf &quot;~a is not defined.\n\n&quot; func-symbol) (functions))] [exn:fail:contract? (lambda (x) (printf &quot;Contract violation ~a\n\n&quot; (regexp-replace #rx&quot;: contract violation&quot; (exn-message x) &quot;:&quot;)) (functions))]) (cond [(member? func-symbol '(exit quit)) (displayln &quot;exiting (functions)&quot;)] [else (let ([function (eval func-symbol)]) (cond [(not (procedure? function)) (printf &quot;~a is not a procedure/function\n\n&quot; function) (functions)] [else (let* ([arity (procedure-arity function)] [integer-arity (cond [(arity-at-least? arity) (printf &quot;The function ~a is varadic and can accept arbitrary number of arguments!\nBut accepts minimum of ~a\n&quot; function (arity-at-least-value arity)) (prompt-until (conjoin exact-nonnegative-integer? (curry &lt;= (arity-at-least-value arity))) (format &quot;How many argument do you want to supply (Non-negative Integer &gt;= ~a): &quot; (arity-at-least-value arity)))] [(integer? arity) arity])] [arguments (for/list ([i (in-range 1 (add1 integer-arity))]) (eval (prompt &quot;Argument ~a: &quot; i)))]) (printf &quot;Result is: ~v\n\n&quot; (apply function arguments)) (functions))]))])))) </code></pre> <p>I have played with this function and it seems to work normally in all cases as it does handle abnormal cases correctly by printing the errors and not showing the errors directly to the end-user.</p> <p>I didn't handle all <code>procedure-arity</code> cases; because I thought it was sufficient handling normal functions and simple variadic functions only.</p> <p>My major concerns are:</p> <ul> <li>Using 3 <code>let</code>s.</li> <li>Using 3 <code>cond</code>s.</li> <li>The code contains many levels of deep nesting.</li> </ul> <p>I think my code is rather long, fairly unreadable, and for that I apologize.</p> <p>Also I would like to know if I'm violating any major conventions of the language in any obvious ways.</p> <p>I am sorry for the lengthy question, but I wanted to present all the background details, and I wanted to follow the <a href="https://codereview.stackexchange.com">StackExchange Code review</a> Guide as much as I can.</p> <p>Pardon me for any writing mistakes; English is not my mother tongue.</p> <p>Thanks in advance.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T23:14:21.027", "Id": "262659", "Score": "1", "Tags": [ "beginner", "reinventing-the-wheel", "lisp", "scheme", "racket" ], "Title": "Simply Scheme book: \"functions.scm\", How to use basic language constructs to create interactive prompt for function application" }
262659
<blockquote> <p>for some reason the function setlocale(LC_ALL, &quot;English&quot;) doesn't work when using an input function,(getchar, scanf, fgets,..), to get a special character, (Ç, ã, õ, é,...).</p> </blockquote> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;locale.h&gt; int cont = 0; int soma = 0; char resposta; int main (void){ int i = 0; char caractere; struct cadastro { char cpf[20]; int idade; char sexo; char nome[100]; }; setlocale(LC_ALL, &quot;Portuguese&quot;); void grauRisco (void); struct cadastro paciente; printf (&quot;Faça o cadastro \n&quot;); printf (&quot;Digite seu cpf: \n&quot;); scanf (&quot; %s&quot;, &amp;paciente.cpf); fflush(stdin); printf (&quot;Digite seu nome completo: \n&quot;); do { caractere = getchar(); paciente.nome[i] = caractere; ++i; } while (caractere != '\n'); paciente.nome[i - 1] = '\0'; fflush(stdin); printf (&quot;Digite sua idade: \n&quot;); scanf (&quot; %i&quot;, &amp;paciente.idade); fflush(stdin); printf (&quot;Digite seu sexo: m- masculino, f- feminino \n&quot;); scanf (&quot; %c&quot;, &amp;paciente.sexo); fflush(stdin); system(&quot;cls&quot;); printf(&quot;CPF: %s \n&quot;, paciente.cpf); printf (&quot;NOME: %s \n&quot;, paciente.nome); printf (&quot;IDADE: %i \n&quot;, paciente.idade); printf (&quot;SEXO: %c \n&quot;, paciente.sexo); printf (&quot;Responda as perguntas para saber qual ala deve-se dirigir \n&quot;); printf (&quot;Tem Febre? s-sim, n-nao \n&quot;); grauRisco(); printf (&quot;Tem dor de cabeça? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Tem secreção nasal ou espirros? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Tem dor/irritação na garganta? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Tem tosse seca? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Tem dificuldade respiratória? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Tem dores no corpo? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Tem diarréia? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Esteve em contato, nos ultimos 14 dias, com um caso diagnosticado com COVID-19? s-sim, n-não \n&quot;); grauRisco(); printf (&quot;Esteve em locais com grande aglomeração? s-sim, n-não \n&quot;); grauRisco(); system(&quot;cls&quot;); printf (&quot;Total de pontos %i \n&quot;, soma); if (soma &lt;= 9) { printf (&quot;Seu risco para Covid-19 é BAIXO. Dirija-se para à ala de risco baixo.&quot;); } else if (soma &gt; 9 &amp;&amp; soma &lt;= 19) { printf (&quot;Seu risco para Covid-19 é MEDIO. Dirija-se para à ala de risco médio&quot;); } else if (soma &gt;19) { printf (&quot;Seu risco para Covid-19 é ALTO. Dirija-se para à ala de risco alto&quot;); } FILE *arquivo; arquivo = fopen (&quot;pacientes.txt&quot;,&quot;a&quot;); fprintf (arquivo, &quot;---------------------------\n&quot;); fprintf (arquivo, &quot;CPF: %s \n&quot;, paciente.cpf); fprintf (arquivo, &quot;NOME: %s \n&quot;, paciente.nome); fprintf (arquivo, &quot;IDADE: %i \n&quot;, paciente.idade); fprintf (arquivo, &quot;SEXO: %c \n&quot;, paciente.sexo); fprintf (arquivo, &quot;Total de pontos %i \n&quot;, soma); fprintf (arquivo, &quot;---------------------------\n&quot;); fclose (arquivo); return 0; } void grauRisco (void) { scanf (&quot; %c&quot;, &amp;resposta); fflush(stdin); switch (resposta) { case 's': cont = cont +1; if (cont == 1) { soma = soma + 5; } else if (cont == 2) { soma = soma + 1; } else if (cont == 3) { soma = soma + 1; } else if (cont == 4) { soma = soma + 1; } else if (cont == 5) { soma = soma + 3; } else if (cont == 6) { soma = soma + 10; } else if (cont ==7) { soma = soma + 1; } else if (cont == 8) { soma = soma + 1; } else if (cont == 9) { soma = soma + 10; } else if (cont == 10) { soma = soma + 3; } break; case 'n': break; default: printf(&quot;A resposta não é valida. digite s-sim, n-não. \n&quot;); grauRisco(); break; } return ; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T03:15:31.110", "Id": "518427", "Score": "0", "body": "Welcome. You did not review the existing code ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T09:12:45.737", "Id": "518436", "Score": "0", "body": "When you say that `setlocale()` \"didn't work\", how do you know, given that you just ignored the return value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:12:02.347", "Id": "518446", "Score": "1", "body": "`fflush(stdin)` - since `stdin` is an input stream, the behaviour is __undefined__." } ]
[ { "body": "<h1><code>setlocale()</code> expects language tags</h1>\n<p>You call <code>setlocale(LC_ALL, &quot;Portuguese&quot;)</code>, but unfortunately the system does not expect the English name for a language, but rather a so-called <a href=\"https://en.wikipedia.org/wiki/Language_localisation#Language_tags_and_codes\" rel=\"nofollow noreferrer\">language tag</a>, a combination of ISO country and language codes. For example, if you wanted Portuguese spoken in Portugal, it would be <code>pt_PT</code>, but if you wanted Portuguese as spoken in Brazil, it would be <code>pt_BR</code>.</p>\n<h1><code>setlocale()</code> doesn't change how keyboard input works</h1>\n<p>The main thing <code>setlocale()</code> does is change how things like numbers and dates are printed, and it will choose the right translation file if you made your program <a href=\"https://en.wikipedia.org/wiki/Internationalization_and_localization\" rel=\"nofollow noreferrer\">internationalized</a> using <a href=\"https://en.wikipedia.org/wiki/Gettext\" rel=\"nofollow noreferrer\">gettext</a>. However, you are not using any of the functions that would change the output based on the locale, and more importantly, <code>setlocale()</code> doesn't change how text entered on the keyboard is transmitted to your program. The latter is done by the console or terminal emulator you are using, and it isn't affected by calls to <code>setlocale()</code>. Instead, you have to make sure you are prepared to handle what the console send to your program, which brings me to:</p>\n<h1>The character encoding matters</h1>\n<p>While you can expect most computer systems in the world to support ASCII out of the box, this only covers the letters used in English. When you want to support special characters such as Ç, ã and so on, there are multiple ways to <a href=\"https://en.wikipedia.org/wiki/Character_encoding\" rel=\"nofollow noreferrer\">encode those characters</a>. If your terminal is set for <a href=\"https://en.wikipedia.org/wiki/ISO/IEC_8859-1\" rel=\"nofollow noreferrer\">ISO 8859-1</a>, then all of the Portuguese characters fit inside a single <code>char</code>, however nowadays <a href=\"https://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">UTF-8</a> is the norm, and in that encoding the non-ASCII characters will take at least two bytes to encode, which means they no longer fit in a <code>char</code>.</p>\n<p>To support reading single characters from UTF-8 input, you will have to use <a href=\"https://en.cppreference.com/w/c/io/fgetwc\" rel=\"nofollow noreferrer\"><code>getwc()</code></a> or <a href=\"https://en.cppreference.com/w/c/io/fwscanf\" rel=\"nofollow noreferrer\"><code>wscanf(&quot;%c&quot;, ...)</code></a> to read the character into a <code>wchar_t</code>. However, if you want to read a whole line, like for example when asking for the full name of a patient, then you can use <a href=\"https://en.cppreference.com/w/c/io/fgetws\" rel=\"nofollow noreferrer\"><code>fgetws()</code></a>.</p>\n<p>But to make it more confusing, you can still use <code>fgets()</code> to read a line into a string of regular <code>char</code>s, and it will still be able to read UTF-8 input correctly, however there just might not be a one-to-one mapping from each <code>char</code> in the string to a single character anymore. It's fine for things like <code>paciente.nome</code>: you read it in and you print it, but you don't really care about the individual characters. The only time you care about one character is when you read in <code>paciente.sexo</code> and when asking sim/não questions. In both these cases, the only valid answers happen to be ASCII characters (<code>f</code>/<code>m</code> and <code>s</code>/<code>n</code>), so you can actually use regular <code>scanf(&quot;%c&quot;, ...)</code> or <code>getchar()</code> here.</p>\n<h1>Avoid long <code>if-else</code> chains</h1>\n<p>The long <code>if-else</code> chain inside <code>grauRisco()</code> should either be replaced with a <code>switch</code>-statement, like so:</p>\n<pre><code>case 's':\n cont++;\n\n switch(cont) {\n case 1:\n soma += 5;\n break;\n case 2:\n soma += 1;\n break;\n ...\n }\n break;\n</code></pre>\n<p>Or even better, use a data-driven approach, where the values to add to <code>soma</code> are stored in an array:</p>\n<pre><code>case 's':\n static const int incrementos_de_risco[10] = {5, 1, 1, 1, 3, 10, 1, 1, 10, 3};\n if (cont &lt; 10) {\n soma += incrementos_de_risco[cont++];\n }\n break;\n</code></pre>\n<h1>Avoid global variables</h1>\n<p>Global variables become problematic in larger programs; they pollute the global namespace, they make it harder to support multiple threads, and so on. It is best to avoid them where possible, and instead declare them as close to the scope where they are used instead, and pass (pointers to) those variables to other functions when necessary.</p>\n<p>In the case of <code>grauRisco()</code>, I would rename it to <code>pedirRisco()</code> (if that makes sense in Portuguese) and just have it return <code>true</code> or <code>false</code> depending on whether the user answered sim or não. You can also have it print the question, like so:</p>\n<pre><code>bool pedirRisco(const char *pergunta) {\n printf(&quot;%s s-sim, n-não\\n&quot;, pergunta);\n ...\n case 's':\n return true;\n case 'n':\n return false;\n ...\n}\n</code></pre>\n<p>Then just keep a count of how many risk factors a patient has, and only when you asked all questions, convert the number of risks to a risk factor:</p>\n<pre><code>int numeroRiscos = 0;\n\nnumeroRiscos += pedirRisco(&quot;Tem Febre?&quot;);\nnumeroRiscos += pedirRisco(&quot;Tem dor de cabeça?&quot;);\n...\n\nstatic const int graus[11] = {0, 5, 6, 7, 8, 11, 21, 22, 23, 33, 35};\nint soma = graus[numeroRiscos];\n</code></pre>\n<p>Note that this is just doing the same as your code, but I have a suspicion that you actually wanted to assign a risk value to each symptom. In that case, I would change it to:</p>\n<pre><code>int pedirRisco(const char *pergunta, int risco) {\n printf(&quot;%s s-sim, n-não\\n&quot;, pergunta);\n ...\n case 's':\n return risco;\n case 'n':\n return 0;\n ...\n}\n\n...\n\nint soma = 0;\nsoma += pedirRisco(&quot;Tem Febre?&quot;, 10);\nsoma += pedirRisco(&quot;Tem dor de cabeça?&quot;, 1);\n...\n</code></pre>\n<h1>Consider using a data-driven design</h1>\n<p>While the above already simplifies your code a lot, there is still a lot of repetition of code. This can be eliminated by using a more data-driven design, where you store the questions and the risk factors in an array, and then use a loop to ask all the questions and sum the risks:</p>\n<pre><code>static const struct {\n const char *pergunta,\n int risco,\n} riscos[] = {\n {&quot;Tem Febre?&quot;, 10},\n {&quot;Tem dor de cabeça?&quot;, 1},\n ...\n};\n\nsize_t nRiscos = sizeof riscos / sizeof *riscos; // number of elements in riscos[]\nint soma = 0;\nfor (size_t i = 0; i &lt; nRiscos; i++) {\n soma += pedirRisco(riscos[i].pergunta, riscos[i].risco);\n}\n</code></pre>\n<p>The main advantage is that it is now very easy to add more questions, and you could even have it read the list of questions and risk factors from a file.</p>\n<h1>Missing error checking</h1>\n<p>What happens if the output file cannot be opened, or if something goes wrong while trying to print the new patient record to it? You should check the return value of all I/O functions, and ideally print an error to <code>stderr</code> if something went wrong, <em>and</em> exit the program with <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_FAILURE</code></a>.</p>\n<h1>Avoid using <code>system()</code></h1>\n<p>The <code>system()</code> function is <em>very</em> expensive to use; it creates a new process which in turn parses the command you give it, and then it might even have to start another process to execute that command. Furthermore, it is not very portable, since <code>cls</code> is specific to Windows, but will not work on Linux or macOS for example.</p>\n<p>Instead, consider printing an <a href=\"https://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"nofollow noreferrer\">ANSI escape code</a> to <a href=\"https://stackoverflow.com/questions/37774983/clearing-the-screen-by-printing-a-character/37778152\">clear the screen using <code>printf()</code></a>. This works on most systems, including recent versions of Windows. You can also opt to not clear the screen at all, and just print a two or three blank lines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T10:44:55.030", "Id": "262670", "ParentId": "262660", "Score": "3" } } ]
{ "AcceptedAnswerId": "262670", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T00:12:58.553", "Id": "262660", "Score": "0", "Tags": [ "c", "io", "localization" ], "Title": "how to make inputs work well with special characters using the locale.h library?" }
262660
<p>I wrote the following Python library for getting a callable's argument names, testing whether a callable takes an argument with a given name, and filtering a <code>dict</code> down to just the keys that a callable accepts. You can see the entire code (tests etc.) <a href="https://github.com/jwodder/argset" rel="nofollow noreferrer">on GitHub</a>; only the actual module itself is shown below.</p> <p>Aside from the usual things (code quality, unanticipated cases, etc.), I'd like some feedback on the design of the API of the library itself. Are the attributes &amp; properties well-named, or are the names too unwieldy? Are the method names descriptive enough? Should the methods take <code>kwargs</code> as a <code>dict</code> or as <code>**kwargs</code>? Should <code>missing()</code> even take a <code>dict</code> or just a <code>set</code> of argument names? Should <code>ArgSet</code> store argument names in <code>set</code>s or <code>frozenset</code>s (and, if the latter, should <code>ArgSet</code> itself be frozen)? And so forth.</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; Simple callable argument inspection &amp; filtering ``argset`` provides a simple interface for determining whether a callable takes an argument with a given name, filtering a `dict` of potential arguments down to just those that a callable accepts, and determining any required arguments that are missing from a `dict` of potential arguments. Visit &lt;https://github.com/jwodder/argset&gt; for more information. &quot;&quot;&quot; __version__ = &quot;0.1.0&quot; __author__ = &quot;John Thorvald Wodder II&quot; __author_email__ = &quot;argset@varonathe.org&quot; __license__ = &quot;MIT&quot; __url__ = &quot;https://github.com/jwodder/argset&quot; from dataclasses import dataclass import inspect from typing import Any, Callable, Dict, FrozenSet __all__ = [&quot;ArgSet&quot;, &quot;argset&quot;] @dataclass class ArgSet: &quot;&quot;&quot;A representation of the arguments taken by a callable&quot;&quot;&quot; #: The number of arguments that are positional-only and do not have default #: values required_positional_only: int #: The number of arguments that are positional-only and have a default #: value optional_positional_only: int #: The names of all positional-or-keyword or keyword-only arguments that do #: not have default values required_args: FrozenSet[str] #: The names of all positional-or-keyword or keyword-only arguments that #: have default values optional_args: FrozenSet[str] #: Whether the callable has an argument of the form ``*args`` takes_args: bool #: Whether the callable has an argument of the form ``**kwargs`` takes_kwargs: bool @property def positional_only(self) -&gt; int: &quot;&quot;&quot;The total number of positional-only arguments&quot;&quot;&quot; return self.required_positional_only + self.optional_positional_only @property def argnames(self) -&gt; FrozenSet[str]: &quot;&quot;&quot;The names of all positional-or-keyword or keyword-only arguments&quot;&quot;&quot; return self.required_args | self.optional_args def __contains__(self, arg: str) -&gt; bool: return ( self.takes_kwargs or arg in self.required_args or arg in self.optional_args ) def select(self, kwargs: Dict[str, Any]) -&gt; Dict[str, Any]: &quot;&quot;&quot; Returns all items in ``kwargs`` where the key is the name of a positional-or-keyword or keyword-only argument accepted by the callable. If ``takes_kwargs`` is `True`, the return value is a copy of ``kwargs``. &quot;&quot;&quot; return {k: v for k, v in kwargs.items() if k in self} def missing(self, kwargs: Dict[str, Any]) -&gt; FrozenSet[str]: &quot;&quot;&quot; Returns all keys in ``required_args`` that do not appear in ``kwargs`` &quot;&quot;&quot; return frozenset(self.required_args - kwargs.keys()) def argset(func: Callable) -&gt; ArgSet: &quot;&quot;&quot; Inspects a callable and returns a summary of its arguments as an `ArgSet` &quot;&quot;&quot; sig = inspect.signature(func) required_pos = 0 optional_pos = 0 required_args = set() optional_args = set() takes_args = False takes_kwargs = False for param in sig.parameters.values(): if param.kind is param.POSITIONAL_ONLY: if param.default is param.empty: required_pos += 1 else: optional_pos += 1 elif param.kind in (param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY): if param.default is param.empty: required_args.add(param.name) else: optional_args.add(param.name) elif param.kind is param.VAR_POSITIONAL: takes_args = True elif param.kind is param.VAR_KEYWORD: takes_kwargs = True else: raise AssertionError( &quot;Unknown parameter type: {param.kind!r}&quot; ) # pragma: no cover return ArgSet( required_positional_only=required_pos, optional_positional_only=optional_pos, required_args=frozenset(required_args), optional_args=frozenset(optional_args), takes_args=takes_args, takes_kwargs=takes_kwargs, ) <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p><code>argset()</code> should be moved to a <code>@classmethod</code> pseudoconstructor in <code>ArgSet</code>. Otherwise, the most concerning thing about this code is that it exists at all. I find that metaprogramming is a sign that something, somewhere, has gone wrong in the design process. It can be useful in certain narrow cases such as a Doxygen-like code-diagramming tool, but you've not indicated what the intended use case actually is.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T01:32:58.110", "Id": "262664", "ParentId": "262661", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T00:44:04.277", "Id": "262661", "Score": "2", "Tags": [ "python", "python-3.x", "api" ], "Title": "API design of library for argument inspection & filtering" }
262661
<p>Happily picked up Haskell a couple days back and working on the following use case.</p> <p>Given a list of JSON objects with date fields and a start date, I want to create a list of weeks (here a tuple of dates, but improvements are welcome) from the start date to today plus a week, and count the number of days from the JSON that fall within each week.</p> <pre><code>{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} import Data.Aeson import GHC.Generics import Network.HTTP.Conduit (simpleHttp) import Data.Text (Text, intercalate) import Data.Time import Data.Time.Clock.POSIX import Data.Map (Map, fromList, toList, insert, lookup) import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Internal as BSI parseDate str = utctDay $ parseTimeOrError True defaultTimeLocale &quot;%d/%m/%Y&quot; str :: Day type DateRange = (Day, Day) type DateRangeCount = (DateRange, Int) _makeRanges :: Day -&gt; Day -&gt; [DateRange] -&gt; [DateRange] _makeRanges currDate endDate ranges | currDate &lt;= endDate = let endRangeDate = addDays 6 currDate newCurrDate = addDays 1 endRangeDate in (currDate, endRangeDate) : _makeRanges newCurrDate endDate ranges | otherwise = ranges createRanges :: String -&gt; UTCTime -&gt; [DateRange] createRanges startDateString endTime = let startDate = parseDate startDateString endDate = utctDay endTime in _makeRanges startDate endDate [] isDayInRange :: Day -&gt; DateRange -&gt; Bool isDayInRange day range = day &gt;= fst range &amp;&amp; day &lt;= snd range findRange :: Day -&gt; ([DateRange] -&gt; [DateRange]) findRange day = filter $ isDayInRange day incrementCount :: [DateRange] -&gt; Map DateRange Int -&gt; Person -&gt; Map DateRange Int incrementCount ranges countMap person = let range = head $ findRange (date person) ranges in case Data.Map.lookup range countMap of Just i -&gt; insert range (i+1) countMap Nothing -&gt; countMap countPersons :: [Person] -&gt; [DateRange] -&gt; Map DateRange Int countPersons persons ranges = let countMap = fromList $ map (, 0) ranges in foldl (incrementCount ranges) countMap persons newtype Person = Person {date :: Day} deriving (Show, Generic) instance FromJSON Person where parseJSON (Object o) = do dateString &lt;- o .: &quot;date&quot; return Person {date = parseDate dateString} getData :: Maybe String -&gt; IO (Either String [Person]) getData url = case url of Just url -&gt; eitherDecode &lt;$&gt; simpleHttp url Nothing -&gt; return (eitherDecode &lt;$&gt; BSL.pack $ map BSI.c2w &quot;[{\&quot;date\&quot;:\&quot;21/05/2021\&quot;},{\&quot;date\&quot;:\&quot;01/06/2021\&quot;}]&quot;) main :: IO () main = do -- r &lt;- getData $ Just &quot;gg&quot; r &lt;- getData Nothing case r of Left err -&gt; putStrLn err Right persons -&gt; do endTime &lt;- getCurrentTime let ranges = createRanges &quot;01/05/2021&quot; endTime counts = countPersons persons ranges mapM_ print $ toList counts print $ sum counts </code></pre> <p>Current input &quot;01/05/2021&quot;, the output is:</p> <pre><code>((2021-05-01,2021-05-07),0) ((2021-05-08,2021-05-14),0) ((2021-05-15,2021-05-21),1) ((2021-05-22,2021-05-28),0) ((2021-05-29,2021-06-04),1) ((2021-06-05,2021-06-11),0) 2 </code></pre> <p>Bonus question if it's allowed: I also want to type <code>Map DateRange Int</code> as DateRangeCountMap, but this messes with fromList's expected type which is the raw Map. Any ideas?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T00:57:13.327", "Id": "262663", "Score": "1", "Tags": [ "haskell", "functional-programming", "monads" ], "Title": "Count number of days within each date range in a list of date ranges" }
262663
<p>Note: this script requires <code>gmpy2</code>, if you are using Python 3.9.5 x64 on Windows 10 21H1 like me, then you need to download the pre-built <code>gmpy2</code> wheel from here: <a href="https://www.lfd.uci.edu/%7Egohlke/pythonlibs/" rel="nofollow noreferrer">https://www.lfd.uci.edu/~gohlke/pythonlibs/</a>.</p> <p>So this is a script that approaches pi using 9 algorithms (actually only 7, two of the algorithms are implemented in two different ways each).</p> <p>In this script I used <a href="https://en.wikipedia.org/wiki/Liu_Hui%27s_%CF%80_algorithm" rel="nofollow noreferrer">Liu Hui's π algorithm</a>, <a href="https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80" rel="nofollow noreferrer">Leibniz formula for π</a>, <a href="https://en.wikipedia.org/wiki/Approximations_of_%CF%80#Summing_a_circle%27s_area" rel="nofollow noreferrer">Summing the area of a disk</a>, <a href="https://en.wikipedia.org/wiki/Approximations_of_%CF%80#Middle_Ages" rel="nofollow noreferrer">Madhava's series</a>, <a href="https://en.wikipedia.org/wiki/Approximations_of_%CF%80#Polygon_approximation_to_a_circle" rel="nofollow noreferrer">Archimedes' method</a>, <a href="https://en.wikipedia.org/wiki/Approximations_of_%CF%80#Arctangent" rel="nofollow noreferrer">Arctangent series</a>, and <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwi_3aStnYDxAhWzhv0HHXq6Aa0QFjAAegQIBhAD&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FBailey%25E2%2580%2593Borwein%25E2%2580%2593Plouffe_formula&amp;usg=AOvVaw0qoaZ4Gn2ZVSfIdoM98Ts_" rel="nofollow noreferrer">Bailey–Borwein–Plouffe formula</a>.</p> <p>As these methods are all well-known and implemented countless times well before me, I will not explain the principles and details.</p> <p>This question is about making the implementations as efficient and accurate as possible.</p> <p>The code:</p> <pre class="lang-py prettyprint-override"><code>import gmpy2 import sys from gmpy2 import mpfr, sqrt, atan, ceil, factorial from itertools import product gmpy2.get_context().precision = 339 def cyclotomy(n): s = 6 M = 1 for _ in range(n): G = mpfr(sqrt(1 - M ** 2 / 4)) j = mpfr(1 - G) m = mpfr(sqrt((M / 2) ** 2 + j ** 2)) s *= 2 M = m return '{0:.100f}'.format(mpfr(s * m / 2)) def Leibniz(n): pi = mpfr(0.0) d = 1 for i in range(1, n): a = 2 * (i % 2) - 1 pi += mpfr(a * 4 / d) d += 2 return '{0:.100f}'.format(mpfr(pi)) def sumarea(r): r_sq = r**2 quardrant_sq = product((x**2 for x in range(r+1)), repeat=2) q = sum(a+b &lt;= r_sq for a, b in quardrant_sq) return '{0:.100f}'.format(mpfr((4*q - 4*r + 1) / r_sq)) def pixelpi(r): r_sq = r**2 s = sum(ceil(sqrt(r_sq - x**2)) for x in range(r+1)) return '{0:.100f}'.format(mpfr((4*s - 4*r + 1) / r_sq)) def Madhava(n): a = mpfr(0.0) for i in range(n): a += mpfr((-1.0/3.0)**i/(2.0*i+1.0)) return '{0:.100f}'.format(mpfr(sqrt(12)*a)) def Archimedes(n): pa = 6 pb = 4 * sqrt(3) for _ in range(n): pb = mpfr(2 * pa * pb / (pa + pb)) pa = mpfr(sqrt(pa * pb)) return '{0:.100f}'.format(mpfr((pa + pb) / 4)) def Arctangent(n): term = lambda x: mpfr((2 ** (x + 1) * factorial(x) ** 2) / factorial(2 * x + 1)) return '{0:.100f}'.format(mpfr(sum(term(i) for i in range(n)))) def ArctanPi(n): term = lambda x: mpfr(sqrt(2)) if x == 1 else mpfr(sqrt(2 + term(x - 1))) if n &gt;= 2: return '{0:.100f}'.format(mpfr(2 ** (n + 1) * atan(sqrt(2 - term(n - 1)) / term(n)))) def BBP(n): term = lambda x: mpfr((4 / (8 * x + 1) - 2 / (8 * x + 4) - 1 / (8 * x + 5) - 1 / (8 * x + 6)) * 16 ** -x) return '{0:.100f}'.format(mpfr(sum(term(i) for i in range(n)))) def main(a, b): switcher = { 0: cyclotomy, 1: Leibniz, 2: sumarea, 3: pixelpi, 4: Madhava, 5: Archimedes, 6: Arctangent, 7: ArctanPi, 8: BBP } return switcher.get(a)(b) if __name__ == '__main__': print(main(*map(int, sys.argv[1:]))) </code></pre> <p>So far I have found the algorithm based on Liu Hui's converges the fastest (except the recursive arctangent function which is prone to error), it yields the first 100 decimal places of pi at 166th iteration with 339 bit precision, though it will produce inaccurate result (the last two digits will change from &quot;79&quot; to &quot;80&quot;) if you input any higher number due to rounding.</p> <p>But at the 166th iteration we are calculating the perimeter of a regular polygon with 6 * 2 ^ 166 sides to get the result.</p> <p>The third and fourth methods use the same logic, but the third counts all the cells inside a circle which is always an integer, and this is somehow more accurate than the fourth.</p> <p>The fourth method sums the maximum y value at each x value, because it uses square roots y isn't always an integer, because issues of rounding this is less accurate than the third, but this is much faster than the third. And I have found rounding up y make the result most accurate.</p> <p>The seventh and eighth methods are using the same logic, but the eighth uses recursion, and it achieves the most accurate result at the fifth iteration (input is 6), then it gives very inaccurate results at inputs 164 to 169, and then it gives complete wrong results at input 170, and at input 172 it gives 4.0000, and at any number after that it yields -0.0000, and the maximum input is 997 in terminal and 998 in Python shell, otherwise it throws <code>RecursionError: maximum recursion depth exceeded in comparison</code>.</p> <p>These issues are caused by the way the computer works, the errors in precision and recursion limits, and I am unable to fix it.</p> <p>Beyond that there are no issues to report.</p> <p>I would like to know how can I improve the efficiency and accuracy of the algorithms, how can they be optimized. Any help will be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T18:32:49.350", "Id": "518475", "Score": "1", "body": "You may consider Machin's variety of formulas, starting with \\$\\dfrac{\\pi}{4} = 4\\arctan\\dfrac{1}{5} - \\arctan\\dfrac{1}{239}\\$, which converge in a blink of an eye." } ]
[ { "body": "<h1>Efficiency and accuracy</h1>\n<p>If the goal was to have the best function to calculate π, then you should just pick the algorithm which is known the converge the fastest, and optimize that as much as possible. There's not much point in wanting to optimize an algorithm you know isn't ever going to be the most efficient one to begin with. But I assume you want to do this anyway.</p>\n<p>Accuracy is the goal, and efficiency is how fast you reach the goal. The number of iterations to reach a certain accuracy is probably a bad measure of efficiency, because an algorithm that needs twice the number of iterations to reach the desired accuracy but is three times faster per iteration is going to win. So ideally, you want to benchmark your code and measure the time it takes to reach a given number of digits of accuracy.</p>\n<h1>Short != fast</h1>\n<p>Dense code is not necessarily fast, and making the code as compact as possible hurts readability and maintainability. I had to read this line a few times before I understood how it worked:</p>\n<pre><code>print(main(*map(int, sys.argv[1:])))\n</code></pre>\n<p>Just keep it plain and simple. I would have written this as:</p>\n<pre><code>algorithm = int(sys.argv[1])\nn_iterations = int(sys.argv[2])\nresult = main(algorithm, n_iterations)\nprint(result)\n</code></pre>\n<p>The temporary variables are not <em>necessary</em>, but just by giving a name to things this will automatically document the code: it's clear from this that we expect the first argument to be an integer that tells us which <code>algorithm</code> to use, and so on.</p>\n<p>Also, you can nest function definitions in Python instead of writing lambdas. This allows you to write more verbose code, for example:</p>\n<pre><code>def Arctangent(n):\n def term(x):\n numerator = 2 ** (x + 1) * factorial(x) ** 2\n denominator = factorial(2 * x + 1)\n return numerator / denominator\n\n return sum(term(mpfr(i)) for i in range(n))\n</code></pre>\n<h1>Use consistent and descriptive variable names</h1>\n<p>Related to the above, you use a lot of one and two letter variable names. It's hard to figure out what each of them means. If you are implementing a formula from a Wikipedia page or a scientific paper, then add a comment with a reference to the source material. Otherwise, just give the variables names that self-document them if possible, for example <code>d</code> in <code>Leibniz()</code> could be renamed <code>denominator</code>.</p>\n<p>Exceptions to this are commonly used short variable names, such as <code>i</code> for iterators, and <code>x</code> in lambdas.</p>\n<h1>Return raw results instead of formatting them</h1>\n<p>Functions are more useful if they <code>return</code> the raw results without post-processing them unnecessarily. This allows the caller to decide what to do with the data. It can always decide to format it to a string if necessary. In this case, it also removes code duplication. So instead of:</p>\n<pre><code>return '{0:.100f}'.format(mpfr(pi))\n</code></pre>\n<p>Just call:</p>\n<pre><code>return pi\n</code></pre>\n<p>And then the caller can do:</p>\n<pre><code>result = main(algorithm, n_iterations)\nprint(&quot;{:.100f}&quot;.format(result))\n</code></pre>\n<h1>Casting to <code>mpfr</code></h1>\n<p>Let's look at this line:</p>\n<pre><code>pi += mpfr(a * 4 / d)\n</code></pre>\n<p>Since <code>a</code> and <code>d</code> are just regular <code>float</code>s, this means that here we first calculate <code>a * 4 / d</code> using Python's <code>float</code> precision, and then cast the result of that to an <code>mpfr</code>. That's of course not so great. Make sure you do all operations with variables of type <code>mpfr</code> to fully benefit from gmpy2's multi-precision reals.</p>\n<p>Also, once a variable is an <code>mpfr</code>, there is no need to cast it again, like in this line:</p>\n<pre><code>return '{0:.100f}'.format(mpfr(pi))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T13:30:45.687", "Id": "262680", "ParentId": "262671", "Score": "4" } }, { "body": "<p>Hmm, I have tested many algorithms and found the <a href=\"https://en.wikipedia.org/wiki/Ramanujan%E2%80%93Sato_series\" rel=\"nofollow noreferrer\">Ramanujan algorithm</a> to be fastest, it only takes 13 iterations to arrive at pi to 100 decimal places (with 336 bits precision, though I always use 512 bits precision because it's binary solid).</p>\n<p>So this is the code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import gmpy2\nfrom gmpy2 import factorial, mpfr, sqrt\n\ngmpy2.get_context().precision = 512\n\ndef Ramanujan(n):\n term = lambda k: mpfr(factorial(4 * k) * (1103 + 26390 * k)) / (factorial(k) ** 4 * 396 ** (4 * k))\n s = sum(term(i) for i in range(n))\n return mpfr(1) / (2 * sqrt(2) * s / 9801)\n</code></pre>\n<p>At exactly n == 13 the result is correct to 100 decimal places:</p>\n<pre><code>str(Ramanujan(13))[0:102]\n'3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679'\n</code></pre>\n<p>Performance information:</p>\n<pre><code>%timeit Ramanujan(13)\n111 µs ± 1.74 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n<p>Also I have improved the BBP algorithm and reduced it to one line:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def BBP(n):\n return sum(1/mpfr(16)**k * (mpfr(4)/(8*k+1) - mpfr(2)/(8*k+4) - mpfr(1)/(8*k+5) - mpfr(1)/(8*k+6)) for k in range(n))\n</code></pre>\n<p>It takes 80 iterations to get the first 100 decimal places of pi.</p>\n<p>Performance:</p>\n<pre><code>%timeit BBP(80)\n377 µs ± 1.02 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n<p>The Archimedes method and cyclotomy method both take 166 iterations to get the first 100 decimal places.</p>\n<p>Performance:</p>\n<pre><code>%timeit Archimedes(166) \n466 µs ± 3.15 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n \n%timeit cyclotomy(166) \n1.32 ms ± 19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) \n</code></pre>\n<p>All the other methods take much longer time to compute and many more iterations to arrive at 100 decimal places.</p>\n<hr />\n<p>P.S.</p>\n<p>I know of the triangular function expressions of pi, for example:</p>\n<p>pi = arccos(-1) and pi = 4 * arctan(1)</p>\n<p>However they aren't iterative algorithms and do need a value of pi predefined to get the results.</p>\n<p>Though I do use them to check the validity of the results.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T06:55:58.390", "Id": "262711", "ParentId": "262671", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T10:56:13.743", "Id": "262671", "Score": "3", "Tags": [ "python", "performance", "beginner", "python-3.x", "programming-challenge" ], "Title": "Python 3 approximate pi using 9 algorithms" }
262671
<p>Could anyone help me with below logic implementation. I am new to Javascript and have been practicing advanced functions. The below code does the job but is there a better way to achieve the same? I want to make my code perfect.</p> <p>I am grouping by location and then getting the sentiments count.</p> <pre><code>// Feedback const sentiments = [ { location: &quot;France&quot;, sentiment: &quot;dissatisfied&quot; }, { location: &quot;France&quot;, sentiment: &quot;happy&quot; }, { location: &quot;France&quot;, sentiment: &quot;happy&quot; }, { location: &quot;Germany&quot;, sentiment: &quot;happy&quot; }, { location: &quot;France&quot;, sentiment: &quot;sad&quot; }, { location: &quot;Germany&quot;, sentiment: &quot;sad&quot; }, { location: &quot;Germany&quot;, sentiment: &quot;happy&quot; }, { location: &quot;Germany&quot;, sentiment: &quot;happy&quot; }, { location: &quot;Germany&quot;, sentiment: &quot;sad&quot; }, { location: &quot;Germany&quot;, sentiment: &quot;dissatisfied&quot; }, { location: &quot;Spain&quot;, sentiment: &quot;dissatisfied&quot; }, { location: &quot;Spain&quot;, sentiment: &quot;happy&quot; }, { location: &quot;Spain&quot;, sentiment: &quot;happy&quot; }, ]; // Group by Sentiments function GroupBySentiments(location, acc, cvalue) { let key = cvalue[&quot;sentiment&quot;]; // first time 0th index will be empty, so insert the sentiment if (acc[location][0] == undefined) { acc[location].push({ [key]: 1 }); } else if (acc[location].findIndex((l) =&gt; l.hasOwnProperty(key)) == -1) { acc[location].push({ [key]: 1 }); } else { let index = acc[location].findIndex((l) =&gt; l.hasOwnProperty(key)); acc[location][index][key] += 1; } return acc; } //Group by location result = sentiments.reduce((acc, sentiment) =&gt; { let key = sentiment[&quot;location&quot;]; if (!acc[key]) { acc[key] = []; } return GroupBySentiments(key, acc, sentiment); }, {}); </code></pre> <pre><code>//OUTPUT { France: [ { dissatisfied: 1 }, { happy: 2 }, { sad: 1 } ], Germany: [ { happy: 3 }, { sad: 2 }, { dissatisfied: 1 } ], Spain: [ { dissatisfied: 1 }, { happy: 2 } ] } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:13:12.660", "Id": "518447", "Score": "1", "body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[ { "body": "<h1>Output format</h1>\n<p>For each location, you have a list of objects with a single sentiment.</p>\n<p>i.e.: <code>{ France: [ { dissatisfied: 1 }, { happy: 2 }, ... ] }</code></p>\n<p>To access how many are &quot;happy&quot; from France you would need to do something like</p>\n<pre><code>const happySentiment = results.France.find((sentiment) =&gt; sentiment.hasOwnProperty(&quot;happy&quot;));\nconst happyCount = happySentiment ? happySentiment.happy : 0; \n</code></pre>\n<p>This is, imo, a lot of work just to find how many people are happy in France, at this point you might as well add +1 to dissatisfied for me.</p>\n<p>Joke aside, if there is not a specific reason to work with that output format, why not generate something that is easier to handle?</p>\n<p>i.e.: <code>{ France: { dissatisfied: 1, happy: 2 }}</code></p>\n<p>and thus to access the same result as before would be:</p>\n<pre><code>const happyCount = results.France.happy ?? 0;\n</code></pre>\n<h1>New Implementation</h1>\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 sentiments = [\n { location: \"France\", sentiment: \"dissatisfied\" },\n { location: \"France\", sentiment: \"happy\" },\n { location: \"France\", sentiment: \"happy\" },\n { location: \"Germany\", sentiment: \"happy\" },\n { location: \"France\", sentiment: \"sad\" },\n { location: \"Germany\", sentiment: \"sad\" },\n { location: \"Germany\", sentiment: \"happy\" },\n { location: \"Germany\", sentiment: \"happy\" },\n { location: \"Germany\", sentiment: \"sad\" },\n { location: \"Germany\", sentiment: \"dissatisfied\" },\n { location: \"Spain\", sentiment: \"dissatisfied\" },\n { location: \"Spain\", sentiment: \"happy\" },\n { location: \"Spain\", sentiment: \"happy\" },\n];\n\nconst result = sentiments.reduce((acc, {location, sentiment}) =&gt; {\n const sentimentCounts = acc[location] ?? {};\n sentimentCounts[sentiment] = (sentimentCounts[sentiment] ?? 0) + 1;\n acc[location] = sentimentCounts;\n return acc;\n}, {});\n\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T14:06:04.023", "Id": "518457", "Score": "0", "body": "I appreciate this, Very nice solution! many thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T14:24:36.613", "Id": "518461", "Score": "0", "body": "One option depending on your needs is just counting in the original array `(loc, sent) => sentiments.filter(s => s.location == loc && s.sentiment == sent).length`. Considered making this an answer, but it's more of a \"for completeness\" addition" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:36:35.097", "Id": "262673", "ParentId": "262672", "Score": "3" } } ]
{ "AcceptedAnswerId": "262673", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T10:56:41.617", "Id": "262672", "Score": "2", "Tags": [ "javascript", "beginner" ], "Title": "Is there a better approach to group the props and get the count of an object of arrays in javascript, less code but native approach" }
262672
<h2>Intro</h2> <p>So I am writing a larger script where a part of it is checking user input. Maybe I have a menu where the user can choose different options, or maybe I want them to write in some number/s. After some thinking I decided to write an all encompassing function to handle all the different user inputs. In short there was 4 different user cases I wanted to allow as seen below</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: center;">single input</th> <th style="text-align: center;">multiple inputs</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;"><strong>floats</strong></td> <td style="text-align: center;"></td> <td style="text-align: center;"></td> </tr> <tr> <td style="text-align: left;"><strong>Ints</strong></td> <td style="text-align: center;"></td> <td style="text-align: center;"></td> </tr> </tbody> </table> </div> <p>So my function should be able to handle multiple decimal number inputs, and check that they are all correct based on the restraints given. The main portion of the code is</p> <pre><code>get_valid_user_input( text=&quot;Choice&quot;, must_be_int=True, low=1, high=100, plural=False, ) </code></pre> <p>Where I can either give in <code>low</code> and <code>high</code> or a list <code>int_range=[-5,2.2,8]</code> to determine the number range the users inputs has to lie in. In addition we choose whether to accept whole numbers or any number in range, and finally whether to ask for a single or multiple values. Note that as this is a part of a bigger code, the user input is kept fairly minimal.</p> <h2>Questions</h2> <p>All in all I am mostly happy with the code i've written. I do have some questions though</p> <ol> <li><p>A SMELL I found was I found myself typing the parameters of certain functions over and over again. For instance:</p> <pre><code> if not is_input_in_range( user_input, must_be_int=must_be_int, low=low, high=high, input_range=int_range, ): </code></pre> </li> <li><p>Would the whole code be better as a class?</p> </li> </ol> <p>Other inputs or guidances for writing better code are more than welcome as well.</p> <h2>Code</h2> <pre><code>DELIMITERS = [&quot;,&quot;, &quot; &quot;, &quot;;&quot;] def user_input_2_list(user_input, delimiters=DELIMITERS): for delimiter in DELIMITERS: if delimiter in user_input: return user_input.split(delimiter) return [user_input] def is_integer(value): try: float(value) except ValueError: return False else: return float(value).is_integer() def is_float(value): try: float(value) return True except ValueError: return False def sanitize_user_input(user_input): &quot;&quot;&quot; Removes all characters from strings except digits. It leaves . as it is the decimal marker in Python &quot;&quot;&quot; if user_input.isdigit(): return user_input elif is_float(user_input): return user_input return &quot;&quot;.join(i for i in user_input if i.isdigit() or i in &quot;.&quot;) def is_input_in_range( user_input, must_be_int=True, low=float(&quot;-inf&quot;), high=float(&quot;inf&quot;), input_range=None ): if not input_range: input_range = range(low, high + 1) if not input_range: return False if must_be_int: return int(user_input) in input_range if is_integer(user_input) else False elif is_float(user_input): return input_range[0] &lt;= float(user_input) &lt;= input_range[-1] return False def error_msg_4_user_input( must_be_int=True, low=None, high=None, int_range=None, range_limit=3, is_plural=False ): if not int_range: int_range = list(range(low, high + 1)) if not int_range: return &quot;&quot; is_range_consecutive = True else: int_range = sorted(int_range) is_range_consecutive = int_range == list( range(min(int_range), max(int_range) + 1) ) plural = &quot;s&quot; if (is_plural and len(int_range) &gt; 1) else &quot;&quot; string_text = f&quot;Woops, your input{plural} must be&quot; if must_be_int: string_text += (&quot; a&quot; if not plural else &quot;&quot;) + &quot; whole number&quot; + plural if is_range_consecutive and len(int_range) &gt;= range_limit: range_text = f&quot;[{int_range[0]}, {int_range[1]}, ..., {int_range[-1]}]&quot; else: range_text = &quot;range &quot; + int_range else: range_text = f&quot;range [{int_range[0]}, {int_range[-1]}]&quot; return string_text + &quot; in &quot; + range_text def get_valid_user_input( text, must_be_int=True, low=None, high=None, int_range=None, plural=False, ): input_in_range = False while not input_in_range: input_in_range = True &quot;&quot;&quot; The following line: 1. transforms user input string into a list of string 2. removes every non-digit character from the list 3. removes empty values from the input &quot;&quot;&quot; if plural: user_inputs = list( filter( None, map( sanitize_user_input, user_input_2_list(input(f&quot;{text.capitalize()}: &quot;)), ), ) ) else: user_inputs = [ sanitize_user_input( input(f&quot;{text.capitalize()}: &quot;).replace(&quot; &quot;, &quot;&quot;).replace(&quot;,&quot;, &quot;.&quot;) ) ] for user_input in user_inputs: if not is_input_in_range( user_input, must_be_int=must_be_int, low=low, high=high, input_range=int_range, ): input_in_range = False print( error_msg_4_user_input( must_be_int=must_be_int, low=low, high=high, int_range=int_range, plural=plural, ) ) break numbr = int if must_be_int else float return numbr(user_inputs[0]) if not plural else sorted(map(numbr, set(user_inputs))) if __name__ == &quot;__main__&quot;: print(&quot;Write in a whole number from 1 to 100&quot;) get_valid_user_input( text=&quot;Choice&quot;, must_be_int=True, low=1, high=100, plural=False, ) print(&quot;Write in a whole numbers from 1 to 100&quot;) get_valid_user_input( text=&quot;Choice&quot;, must_be_int=False, low=1, high=100, plural=True, ) print(&quot;Write in any number between 1 to 100&quot;) get_valid_user_input( text=&quot;Choice&quot;, must_be_int=False, low=1, high=100, plural=False, ) print(&quot;Write in any numbers between 1 to 100&quot;) ans = get_valid_user_input( text=&quot;Choice&quot;, must_be_int=False, low=1, high=100, plural=True, ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T17:35:10.940", "Id": "518563", "Score": "0", "body": "Input for what particular purpose?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T17:40:50.593", "Id": "518564", "Score": "0", "body": "I am trying to design some general purpose code that could be useful in many area. Perhaps I should have included the tag `design_patterns`. One very concrete application could be writing in scores for an exam. Perhaps I want to allow myself to write in any type of score between 0 and 5 for a given question, or perhaps limit myself to whole numbers. I could also see the code above being useful when designing a simple menu, where the user picks one of the options:" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:45:00.343", "Id": "262674", "Score": "0", "Tags": [ "python-3.x", "parsing", "user-interface" ], "Title": "User input, floats, ints and ranges" }
262674
<p>I mainly write code for data analysis so don't think about or use OOP at all on the day job. I thought I'd have a go at a simple Monty Hall simulation in an object-oriented style to figure out how it works - specifically I based it on this: <a href="https://www.reddit.com/r/dailyprogrammer/comments/n94io8/20210510_challenge_389_easy_the_monty_hall_problem/" rel="nofollow noreferrer">https://www.reddit.com/r/dailyprogrammer/comments/n94io8/20210510_challenge_389_easy_the_monty_hall_problem/</a></p> <p>Appreciate this project has been done to death but I just want to get a bit of feedback on whether I 'get' OOP or not (this is my first OOP program). Having written a lot of code in a procedural style, I found it quite confusing. Note that the strategies in the <code>strategise</code> method are from the link above. If an unrecognised name is used, it just picks a second door randomly.</p> <p>What I specifically struggled with are things like:</p> <ul> <li>What should be an object? There were lots of things that could have been. Doors, maybe a game show host, maybe the prizes... in the end I kept it simple but that was only after a few iterations and getting stuck.</li> <li>Am I using the classes/methods correctly when running the simulation? Would you surface more of the methods rather than using a 'wrapper' method like I've done with <code>Contestant.play_the_game</code>?</li> <li>The <code>strategise</code> method is a bit of a mess. Is there a better way of implementing this that isn't just a load of <code>if...else</code>?</li> </ul> <p>Any other thoughts/criticisms on general style and anything else are welcome - I don't generally code in Python either so this was all very new.</p> <p>My class definitions are in a file called montyHall.py:</p> <pre><code>import random class MontyHall: def __init__(self): '''The Monty Hall game! Three doors, 2 goats, one car.''' self.doors = {1: &quot;goat&quot;, 2: &quot;goat&quot;, 3: &quot;goat&quot;} prize_door = random.randint(1, 3) self.doors[prize_door] = &quot;car&quot; def check_door(self, door_number): '''Checks what is behind a given door.''' return self.doors[door_number] def first_reveal(self, door_number): '''Takes a door number picked by the contestant and opens one of other doors with a goat.''' doors = [1, 2, 3] doors.remove(door_number) prizes = list(map(self.check_door, doors)) if &quot;car&quot; in prizes: del doors[prizes.index(&quot;car&quot;)] door = random.choice(doors) return door def second_reveal(self, door_number): '''Takes the contestant's second pick and reveals their prize.''' prize = self.check_door(door_number) return prize class Contestant: def __init__(self, name): '''A contestant to play the Monty Hall game.''' self.name = name self.wins = [] self.second_door = 0 if self.name in [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Frank&quot;, &quot;Gina&quot;]: self.first_door = 1 else: self.first_door = random.choice([1, 2, 3]) def strategise(self, doors): '''Picks a second door. If the contestant name is not recognised, it just picks randomly.''' if self.name in [&quot;Alice&quot;, &quot;Dave&quot;]: self.second_door = self.first_door elif self.name in [&quot;Bob&quot;, &quot;Erin&quot;]: self.switch_doors(doors) elif self.name == &quot;Frank&quot;: if 2 in doors: self.second_door = 2 else: self.second_door = self.first_door elif self.name == &quot;Gina&quot;: if not self.wins: self.second_door = self.first_door else: if self.wins[-1]: if self.second_door != self.first_door: self.switch_doors(doors) else: if self.second_door != self.first_door: self.second_door = self.first_door else: self.switch_doors(doors) else: self.second_door = random.choice(doors) def switch_doors(self, doors): '''Switches doors for the second contestant pick.''' doors.remove(self.first_door) self.second_door = doors[0] def first_pick(self, competition): '''Pass the first door choice to the competition to open one of the other doors, and then pick a strategy.''' open_door = competition.first_reveal(self.first_door) doors = [1, 2, 3] doors.remove(open_door) self.strategise(doors) def second_pick(self, competition): '''Pass the second door choice to the competition to reveal the prize!''' prize = competition.second_reveal(self.second_door) if (prize == &quot;car&quot;): self.wins.append(1) else: self.wins.append(0) def play_the_game(self, competition): '''Play the game.''' self.first_pick(competition) self.second_pick(competition) </code></pre> <p>And I run the simulation like this:</p> <pre><code>from montyHall import * def main(): alice = Contestant(&quot;Alice&quot;) bob = Contestant(&quot;Bob&quot;) carol = Contestant(&quot;Carol&quot;) dave = Contestant(&quot;Dave&quot;) erin = Contestant(&quot;Erin&quot;) frank = Contestant(&quot;Frank&quot;) gina = Contestant(&quot;Gina&quot;) for i in range(1000): for contestant in [alice, bob, carol, dave, erin, frank, gina]: competition = MontyHall() contestant.play_the_game(competition) for contestant in [alice, bob, carol, dave, erin, frank, gina]: print(contestant.name + &quot; win rate: &quot; + str(100 * sum(contestant.wins)/len(contestant.wins)) + &quot;%&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<p>I'm by no means an expert and recognizing that something can be improved doesn't necessarily mean you know how. But let's give it a try anyway.</p>\n<p>For the OO approach:\nI would say there are 3 key elements in the Monty Hall problem (4 if the looping over games is also included) that we want to abstract/encapsulate:</p>\n<ol>\n<li>The &quot;board&quot;; random selection of goats and a car which can be revealed by opening a door.</li>\n<li>The player (which is mainly the strategy for the first pick and switching on the second).</li>\n<li>The logic of the game (or indeed the host).</li>\n</ol>\n<p>For these elements we want to first think of the visible behaviors (without thinking of how to do it in code).</p>\n<p>For the doors; we should be able to reveal what is behind the door (in this case it doesn't matter if that is for a contestant or the host).</p>\n<p>For the player; we have to make a first guess, followed by a decision if we want to switch.</p>\n<p>For the game; we want to play the game (with a &quot;board&quot; and a player).</p>\n<p>This almost fully reveals how our classes should look and how we want to test them. See the <code>test_monty_hall.py</code> for how to use the classes without being concerned about implementation details.\nA TDD approach can also help in discovering what the classes and methods should be. Because to test something you fist need to figure out what it should do. On top of that, if things are difficult to test they are probably not at the right abstraction (the <code>Game</code> class might benefit from a different abstraction since we are testing &quot;private&quot; methods in this example, left as an exercise to the reader ...).</p>\n<p>With this OO approach you also have a nicer alternative to <code>strategise</code>.\nInstead of a single class with all strategies you can have just an abstract class with concrete implementations of the different strategies. This keeps everything related to the contestants strategy nicely encapsulated.</p>\n<p>In my attempt you would end up with the <code>MontyHall.py</code> (all code focuses on the OO approach, cutting corners in other places)</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\nfrom abc import ABC, abstractmethod\n\n\nclass Board:\n\n def __init__(self, inp=None):\n if not inp:\n inp = self._generate()\n self._doors = inp\n\n def reveal(self, door):\n &quot;&quot;&quot;Reveal door content.\n \n Converts door number from human format to indices.\n &quot;&quot;&quot;\n return self._doors[door - 1]\n\n def _generate(self):\n doors = ['car', 'goat', 'goat']\n random.shuffle(doors)\n return doors\n\n\nclass IPlayer(ABC):\n\n def __init__(self, name) -&gt; None:\n super().__init__()\n self.name = name\n\n @abstractmethod\n def pick(self):\n pass\n\n @abstractmethod\n def switch(self):\n pass\n\nclass Game:\n\n def __init__(self, board: Board, player: IPlayer) -&gt; None:\n self.board = board\n self.player = player\n self.won = False\n\n def play(self):\n player_pick = self.player.pick()\n other = self._reveal_other(player_pick)\n if self.player.switch():\n player_pick = self._switch_pick(player_pick, other)\n if self.board.reveal(player_pick) == 'car':\n self.won = True\n\n def _reveal_other(self, number):\n goats = {x+1 for x, item in enumerate(self.board._doors) if item == 'goat'}\n goats.discard(number)\n return random.choice(list(goats))\n\n def _switch_pick(self, player_pick, other):\n return {1,2,3}.difference((player_pick, other)).pop()\n\n\nclass FirstNoSwitch(IPlayer):\n\n def pick(self):\n return 1\n\n def switch(self):\n return False\n\nclass FirstSwitch(IPlayer):\n\n def pick(self):\n return 1\n\n def switch(self):\n return True\n</code></pre>\n<p><code>main.py</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>from MontyHall import Board, Game\nfrom MontyHall import FirstNoSwitch, FirstSwitch\n\n\nif __name__ == &quot;__main__&quot;:\n bob = FirstSwitch(&quot;Bob&quot;)\n alice = FirstNoSwitch(&quot;Alice&quot;)\n\n runs = 1000\n b = 0\n a = 0\n for run in range(runs):\n bobs_game = Game(Board(), bob)\n alices_game = Game(Board(), alice)\n\n bobs_game.play()\n if bobs_game.won:\n b += 1\n\n alices_game.play()\n if alices_game.won:\n a += 1\n\n print(&quot;{} won {} out of {}: {:0.2f}%&quot;.format(bob.name, b, runs, 100*b/runs))\n print(&quot;{} won {} out of {}: {:0.2f}%&quot;.format(alice.name, a, runs, 100*a/runs))\n</code></pre>\n<p><code>test_monty_hall.py</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>import unittest\n\nfrom MontyHall import Board, Game\nfrom MontyHall import FirstNoSwitch, FirstSwitch\n\nclass TestMontyHallBoard(unittest.TestCase):\n\n def test_revealing_a_door_shows_its_content(self):\n input = ['goat', 'goat', 'car']\n board = Board(input)\n self.assertEqual(board.reveal(1), 'goat')\n self.assertEqual(board.reveal(2), 'goat')\n self.assertEqual(board.reveal(3), 'car')\n\n def test_generating_a_random_board(self):\n board = Board()\n self.assertEqual(board._doors.count('goat'), 2)\n self.assertEqual(board._doors.count('car'), 1)\n\n\nclass TestStratagy(unittest.TestCase):\n\n def test_frist_no_switch(self):\n s = FirstNoSwitch(&quot;Alice&quot;)\n self.assertEqual(s.pick(), 1)\n self.assertFalse(s.switch())\n\n def test_frist_switch(self):\n s = FirstSwitch(&quot;Bob&quot;)\n self.assertEqual(s.pick(), 1)\n self.assertTrue(s.switch())\n \n\nclass TestMontyHallGame(unittest.TestCase):\n\n def test_new_game_is_not_won(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n self.assertFalse(game.won)\n\n def test_picking_goat_reveals_the_other_goat(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n self.assertEqual(game._reveal_other(1), 2)\n\n def test_picking_other_goat_reveals_the_goat_(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n self.assertEqual(game._reveal_other(2), 1)\n\n def test_picking_car_reveals_a_goat(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n self.assertTrue(game._reveal_other(3) in (1, 2))\n\n def test_switching_one_two_gives_three(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n self.assertEqual(game._switch_pick(1, 2), 3)\n\n def test_switching_three_two_gives_one(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n self.assertEqual(game._switch_pick(3, 2), 1)\n\n def test_alice_wins(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['car', 'goat', 'goat'])\n game = Game(b, p)\n game.play()\n self.assertTrue(game.won)\n\n def test_alice_loses(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'car', 'goat'])\n game = Game(b, p)\n game.play()\n self.assertFalse(game.won)\n\n def test_alice_loses_again(self):\n p = FirstNoSwitch(&quot;Alice&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n game.play()\n self.assertFalse(game.won)\n\n def test_bob_wins(self):\n p = FirstSwitch(&quot;Bob&quot;)\n b = Board(['goat', 'goat', 'car'])\n game = Game(b, p)\n game.play()\n self.assertTrue(game.won)\n def test_bob_wins_again(self):\n p = FirstSwitch(&quot;Bob&quot;)\n b = Board(['goat', 'car', 'goat'])\n game = Game(b, p)\n game.play()\n self.assertTrue(game.won)\n\n def test_bob_loses(self):\n p = FirstSwitch(&quot;Bob&quot;)\n b = Board(['car', 'goat', 'goat'])\n game = Game(b, p)\n game.play()\n self.assertFalse(game.won)\n</code></pre>\n<p>To run the unittests: <code>python -m unittest -v</code></p>\n<p>This should give you a nice way to implement the remaining strategies.</p>\n<p>The code duplication in my <code>main.py</code> also presents the opportunity for the fourth class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T18:05:08.123", "Id": "518474", "Score": "0", "body": "This is excellent, a very thorough answer. I like your suggestion of starting out by thinking about the visible behaviors before diving into code. Looking back at my initial implementation with that in mind (i.e. that a player does two things - pick a door and switch/stick), it looks to me like I was writing `Contestant` as a mini-procedural program rather than a class. I also didn't know about abstract classes and I really like how that works with defining each player, so I'll definitely look into that further. A lot to think about but all really helpful - thanks for your time!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T16:52:25.743", "Id": "262688", "ParentId": "262675", "Score": "4" } }, { "body": "<p>You've done a good job in writing code that is organized and clear. However, as\nyour comments imply, one can see things slipping out of the control in this\ncode. That's not unusual for first drafts of anything, especially when\nlearning.</p>\n<p>Discussion of OOP design can verge into unreality: it's tempting to focus so\nheavily on technique (<em>OK, we're doing OOP now ... time to get serious</em>) that\none loses sight of more practical considerations. In that context, it's easy to\ntake things too far, effectively over-engineering things that could be done\nmore simply.</p>\n<p>You have a sensible top-level design: you have a game (<code>MontyHall</code>) and players\n(<code>Contestant</code>). Where things go awry, I think, is that you've made the player\nclass responsible for running the game and for handling simulation-related\nconcerns: in software-land, decisions like that can make a certain amount of\nsense, but in the real world, Monty Hall never put the guests in charge of\nanything resembling <code>play_the_game()</code>. Let common-sense and reality overrule\nany abstract OOP-base line of reasoning. That's one piece of broad advice.</p>\n<p>A missing piece in your program is the idea of a simulation. Your intent seems\nto be playing the game many times to compare strategies. This goal mostly falls\noutside of the idea of playing a game (you play it, there's an outcome, it's\nover). Aggregating the results of many games does not, narrowly speaking, fall\nwithin the boundaries of playing a game. OK, maybe each player should track its\nown wins and losses? That's what you currently do and, intuitively, that makes\nsome sense: real humans do track their wins and losses. However, my first\ninstinct (learned mostly from painful experience) would be to restrict\nthe game and the players to their simplest implementations: deliberately narrow\ntheir focus to playing one game. Let some other part of the program concern\nitself with tallying results. That's another piece of broad advice: build\nprograms from simple parts.</p>\n<p>So if players don't have to orchestrate a game or tally results across many\ngames, what's left? Players might need a name or label; they need a first-door\nstrategy; and they need a switch-doors strategy. The strategies could be\nrepresented with a heavy OO-based implementation, as suggested in another\nreview, but that strikes me as over-engineering. What does a first-door\nstrategy require? It's just a function that needs to return 1, 2, or 3. What\nabout switch-door strategy? Just a function that returns True/False. In other\nwords, a player is just a data class, and strategies are just ordinary functions\nthan can be mixed and combined flexibly across players.</p>\n<pre><code>from dataclasses import dataclass\nfrom typing import Callable\nfrom random import randint, choice\n\nDOORS = range(1, 4)\n\n@dataclass(frozen = True)\nclass Contestant:\n name: str\n select: Callable[[], int]\n switch: Callable[[], bool]\n\ndef select_random() -&gt; int:\n return choice(DOORS)\n\n# Example usage.\nc1 = Contestant('Billy', select_random, lambda: False)\nc2 = Contestant('Larry', select_random, lambda: True)\n</code></pre>\n<p>If we start from those simple building blocks, what would a game class need to\ndo? Get a player, set up the doors, get first selection, get alternative\ndoor, get switch decision, return outcome. You could shove all of that into\na class ... but for what purpose? It sounds a lot more like a simple function\nto me. You could have the function return just a simple won/lost boolean\nor you could have it return a data object exposing all of its calculations.\nLet's go with the latter, just for more practice and maybe because\nwe don't know yet what we might want to check in the simulations:</p>\n<pre><code>def lets_make_a_deal(contestant):\n # The car, the first pick, and the other doors.\n car = choice(DOORS)\n pick = contestant.select()\n others = [d for d in DOORS if d != pick]\n\n # Revealed door and alternative door.\n if pick == car:\n shuffle(others)\n else:\n others.sort(key = lambda d: d == car)\n revealed, alternative = others\n\n # Final pick\n final = alternative if contestant.switch() else pick\n won = final == car\n return MontyHall(car, pick, revealed, alternative, final, won)\n\n@dataclass(frozen = True)\nclass MontyHall:\n car: int\n pick: int\n revealed: int\n alternative: int\n final: int\n won: bool\n</code></pre>\n<p>So far, this is a bit disappointing: even though you're solving the problem at\nhand, you are not getting much OOP practice. So rather than forcing OOP on a\nproblem where it might not be too beneficial, search for a different domain.\nRunning game simulations seems to have more promise. You have different\nplayers with different strategies; you want to collection information; and you\nwant to report that information in different ways. All of that suggests\n<strong>state</strong> (various attributes to store) and <strong>behavior</strong> (calculating, printing,\netc). Some type of <code>Simulation</code> class might be useful. Give it a shot, but\ndon't try to force full-blown OOP if it doesn't seem to help.\nIt's possible to build very powerful programs with plain-old functions\nand lots of well-conceived data classes (frozen when feasible).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T10:45:46.893", "Id": "518531", "Score": "0", "body": "Thanks for your thoughts (and also wanted to say this is really well-written). It's clear to me now that I had contestants handling everything in each game, which kind of makes an object-oriented approach redundant - at that stage I could just make the contestant methods a series of functions. And that last sentence is helpful - I've not been coding for long so often fall into the trap of thinking 'complex' implies 'good', when it clearly doesn't. Thanks again" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T21:45:51.867", "Id": "262700", "ParentId": "262675", "Score": "3" } }, { "body": "<p>I tried really hard to unpack your code. It's good that you've attempted some OOP, but you've misrepresented state. Only Gina, for instance, needs to know what her previous second door choice was and previous game outcome was. Your &quot;pick&quot; vs &quot;door&quot; terminology is confusing. It was honestly somewhat of a nightmare to reverse-engineer this thing, but I did, and the code I'm going to suggest is probabilistically equal. I have not evaluated whether the math is <em>correct</em>, but the results are the same as your original ones.</p>\n<p>A simple polymorphic representation that captures the door decisions in overrides will make your code more clear. Do not base such decisions on name strings.</p>\n<p>Don't store a list of all of the wins and losses; you only care about counts (and in one case, the most recent win/loss).</p>\n<p>Use zero-based door indices instead of one-based, and don't explicitly store the prize strings at all, only the winning door index.</p>\n<p>Do not call <code>strategise</code> from <code>first_pick</code>; this is a surprising mixup of responsibility.</p>\n<h2>Suggested</h2>\n<pre><code>import random\nfrom typing import Sequence, Set, Optional\n\n\nclass MontyHall:\n def __init__(self, n: int):\n &quot;&quot;&quot;The Monty Hall game! Three doors, n-1 goats, one car.&quot;&quot;&quot;\n self.n = n\n self.prize_door = random.randrange(n)\n\n @property\n def doors(self) -&gt; Sequence[int]:\n return range(self.n)\n\n def first_reveal(self, door_number: int) -&gt; int:\n &quot;&quot;&quot;\n Given a door picked by a contestant, returns a random choice from the\n remaining doors that is guaranteed to lose.\n &quot;&quot;&quot;\n doors = set(self.doors) - {door_number, self.prize_door}\n open_door = random.choice(tuple(doors))\n return open_door\n\n\nclass Contestant:\n &quot;&quot;&quot;A contestant to play the Monty Hall game.&quot;&quot;&quot;\n def __init__(self, name: str, random_first_door: bool):\n self.name = name\n self.random_first_door = random_first_door\n self.wins = 0\n self.losses = 0\n\n def first_door(self, game: MontyHall) -&gt; int:\n if self.random_first_door:\n return random.randrange(game.n)\n return 0\n\n def second_door(self, doors: Set[int], first_door: int) -&gt; int:\n raise NotImplementedError()\n\n def play(self, game: MontyHall):\n first_door = self.first_door(game)\n open_door = game.first_reveal(first_door)\n doors = set(game.doors) - {open_door}\n second_door = self.second_door(doors, first_door)\n self.save_win(second_door == game.prize_door)\n\n def save_win(self, won: bool) -&gt; None:\n if won:\n self.wins += 1\n else:\n self.losses += 1\n\n @property\n def win_rate(self) -&gt; float:\n return self.wins / (self.wins + self.losses)\n\n def __str__(self):\n return f'{self.name} win rate: {self.win_rate:.1%}'\n\n\nclass RepeatContestant(Contestant):\n def second_door(self, doors: Set[int], first_door: int) -&gt; int:\n return first_door\n\n\nclass SwitchContestant(Contestant):\n def second_door(self, doors: Set[int], first_door: int) -&gt; int:\n remaining = doors - {first_door}\n return next(iter(remaining))\n\n\nclass FavouriteContestant(Contestant):\n def second_door(self, doors: Set[int], first_door: int) -&gt; int:\n if 1 in doors:\n return 1\n return first_door\n\n\nclass LastWinContestant(Contestant):\n def __init__(self, name: str, random_first_door: bool):\n super().__init__(name, random_first_door)\n self.prev_second_door: Optional[int] = None\n self.prev_outcome: Optional[bool] = None\n\n def second_door(self, doors: Set[int], first_door: int) -&gt; int:\n if self.prev_outcome is None:\n second_door = first_door\n elif self.prev_outcome:\n if self.prev_second_door == first_door:\n second_door = self.prev_second_door\n else:\n remaining = doors - {first_door}\n second_door = next(iter(remaining))\n elif self.prev_second_door == first_door:\n remaining = doors - {first_door}\n second_door = next(iter(remaining))\n else:\n second_door = first_door\n\n self.prev_second_door = second_door\n return second_door\n\n def save_win(self, won: bool) -&gt; None:\n super().save_win(won)\n self.prev_outcome = won\n\n\nclass RandomContestant(Contestant):\n def second_door(self, doors: Set[int], first_door: int) -&gt; int:\n return random.choice(tuple(doors))\n\n\ndef main() -&gt; None:\n random.seed(0) # for repeatability\n\n contestants = (\n RepeatContestant('Alice', random_first_door=False),\n SwitchContestant('Bob', random_first_door=False),\n RandomContestant('Carol', random_first_door=True),\n RepeatContestant('Dave', random_first_door=True),\n SwitchContestant('Erin', random_first_door=True),\n FavouriteContestant('Frank', random_first_door=False),\n LastWinContestant('Gina', random_first_door=False),\n )\n\n for _ in range(10_000):\n for contestant in contestants:\n competition = MontyHall(n=3)\n contestant.play(competition)\n\n for contestant in contestants:\n print(contestant)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<h2>Output</h2>\n<pre><code>Alice win rate: 33.7%\nBob win rate: 67.1%\nCarol win rate: 50.3%\nDave win rate: 34.0%\nErin win rate: 66.8%\nFrank win rate: 50.4%\nGina win rate: 55.0%\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T10:54:12.883", "Id": "518532", "Score": "1", "body": "Thanks for your answer. This sentence - \"Do not call strategise from first_pick; this is a surprising mixup of responsibility\" - clarified a lot for me. Specific strategies for picking that second door are things that specific contestants (or types of contestant) do, not contestants in general. More generally, I think I need to get the conceptual bit of this straight - both why we even do OOP, and also what makes most sense in this specific problem. \nI think this is one of those rare cases when learning to code where a bit less doing and a bit more thinking is in order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T13:59:27.317", "Id": "518546", "Score": "0", "body": "@henryn Good observations. This will come more naturally to you with practice." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T06:04:41.093", "Id": "262709", "ParentId": "262675", "Score": "4" } }, { "body": "<h1>Introduction</h1>\n<p>I know I am beating a dead horse, but I attempted to just study one bit of your code. I had some problems with how you defined the <code>class MontyHall</code>. Do note I do not disagree with any of the answers above, I just wanted to give my take on this particular class.</p>\n<p>As others have stated it can be wise to take a step back and really think what each class should do, and what should be a class and not. I personally like to use classes for something that has a particular <em>state</em> and that gets updated.</p>\n<p>So we have a few objects (whether these objects should be functions, classes, metaclasses is not yet decided) which are: The Monty Hall, The contestants and The game. In my eyes we have some doors (The Monty Hall), we have some users (the contstants) and a host (The game). Now, both the the host and the users interact with the doors in some capacity and so it is logical that at least the doors should be a class. What I call the doors is your <code>MontyHall</code> Class.</p>\n<h1>Specifics</h1>\n<pre><code>self.doors = {1: &quot;goat&quot;, 2: &quot;goat&quot;, 3: &quot;goat&quot;}\n</code></pre>\n<p>Here you define doors to be a dictionary containing goats.</p>\n<ul>\n<li>Why not just use a list <code>self.doors = [&quot;goats&quot;, &quot;goats&quot;, &quot;goats&quot;]</code> ?</li>\n<li>On a broader level this implementation seems strange, we first place\na goat in every door, and then we swap out a goat for a car.</li>\n<li>You use 1, 2, 3 but in Python we usually use a zero based index.</li>\n<li>Everything is hardcoded, what if we wanted to win a trip to the moon instead, or had 4 doors instead of 3?</li>\n<li>The whole <code>check_door</code> seems inefficient, the class should be all knowing\nhaving to do a lookup every time is a bit odd.</li>\n<li>Also you seem to be mixing some information. Is it really the MontyHall (doors) that performs the reveal or should it really be some external source? In your code I get the impression that the doors are sentient and perform the reveal themselves ^^</li>\n</ul>\n<h1>Solutions</h1>\n<p>Here as stated in the introduction I am only focusing on improving the <code>MontyHall</code> class. Which in my eyes <em>only</em> should have responsibility for the doors. What is behind each door, which doors have been picked, hiding the prize(s), and opening doors.</p>\n<p>Let us start with getting rid of most of the hardcoded variables, allowing for the more natural zero based indexing and switching from <code>dict</code> to <code>list</code></p>\n<pre><code>ZERO_INDEX_DOORS = False\nOFFSET = 0 if ZERO_INDEX_DOORS else 1\n\nclass MontyHall:\n def __init__(self, doors=3, prizes=1, non_prize=&quot;goat&quot;, prize=&quot;car&quot;, offset=OFFSET):\n &quot;&quot;&quot;A number of doors either containing a prize, or not. Can you guess which?&quot;&quot;&quot;\n self.prize = prize\n self.non_prize = non_prize\n #\n self.len = doors\n self.doors = list(range(offset, self.len + offset))\n self.prizes = random.sample(self.doors, prizes)\n self.non_prizes = [door for door in self.doors if door not in self.prizes]\n</code></pre>\n<p>Note how we can choose to apply a 1 based index by setting <code>offset=1</code> (this is my one over-engineering) This code is quite fundamentally different than yours as it stores information in multiple lists. For instance</p>\n<pre><code> self.doors = [1,2,3]\n self.prizes = [1]\n self.non_prizes = [2,3]\n</code></pre>\n<p>If you notice we can do slightly better than this. <code>self.non_prizes</code>\nwill always be the compliment between <code>self.doors</code> and <code>self.non_prizes</code>. Meaning\nwe want every element in <code>self.doors</code> not in <code>self.non_prizes</code>. This lends itself to a useful helper function</p>\n<pre><code>def list_compliment(list1, list2):\n # Get every element in list1 not in list2\n if isinstance(list2, (int, float)):\n list2 = [list2]\n result = []\n for num in list1:\n if num not in list2:\n result.append(num)\n return result\n</code></pre>\n<p>The first part is to allow <code>list2</code> to be an <code>int</code> or <code>float</code>.\nAgain this code could be written more succinctly, but it is very easy to understand. As Reinderen mentions we could have implemented it using sets</p>\n<pre><code>def list_compliment(list1, list2):\n # Get every element in list1 not in list2\n if isinstance(list2, (int, float)):\n list2 = [list2]\n return list(set(list1) - set(list2))\n</code></pre>\n<p>However, converting between sets and lists are somewhat expensive operation. A better way would perhaps be to work with sets throughout the entire code. This, however, is left as an exercise for the reader.</p>\n<p>Using the function just defined <code>self.non_prizes</code> can now be defined as</p>\n<pre><code>self.non_prizes = list_compliment(self.doors, self.prizes)\n</code></pre>\n<p>Neat! Now we want our class <code>MontyHall</code> to be able to distinguish\nwhich doors the user and the host can choose from. The host can not reveal\na door with a prize behind it, and if the user want to switch doors, they can not pick the same door. These two conditions are easy to fulfill using the <code>list_compltiment</code></p>\n<pre><code>self.available_user = list_compliment(self.doors, self._picked)\nself.available_host = list_compliment(self.non_prizes, self.picked)\n</code></pre>\n<p>As we discussed previously we want a statespace, so we want to have some way of updating the state. Updating the state means to remove opened doors, and update which doors are available. An example can look like this</p>\n<pre><code>def update(self, door_2_remove=None):\n &quot;&quot;&quot;Removes a door from the state, and updates available doors to the various roles&quot;&quot;&quot;\n if door_2_remove:\n self.doors.remove(door_2_remove)\n if door_2_remove in self.prizes:\n self.prizes.remove(door_2_remove)\n else:\n self.non_prizes.remove(door_2_remove)\n #\n self.available_user = list_compliment(self.doors, self._picked)\n self.available_host = list_compliment(self.non_prizes, self.picked)\n</code></pre>\n<p>Now we have two more points to go. 1) We want some way for the user to pick a door, 2) we need a way to open a door. Now, to open a door we can do it as follows</p>\n<pre><code>def pick(self, door):\n self.picked = door\n return door\n\n@property\ndef picked(self):\n return self._picked\n\n@picked.setter\ndef picked(self, door):\n self._picked = door\n self.update()\n</code></pre>\n<p>Now this might be overkill but it allows us to call the function\nboth by doing <code>door = MontyHall()</code> and then either\n<code>door.pick(1)</code> or <code>door.picked=1</code>. Why we set it up as above is to make sure\nthe proper lists are updated each time a new door is chosen. Opening a door is easy</p>\n<pre><code>def open(self, door):\n &quot;&quot;&quot;Opens a given door and reveals its content. If no door, open users choice&quot;&quot;&quot;\n content = self.prize if door in self.prizes else self.non_prize\n self.update(door)\n return content\n</code></pre>\n<p>Opening the users chosen door can be done as follows</p>\n<pre><code>def open_picked(self):\n return self.open_door(self._picked)\n</code></pre>\n<p>Now a game can look like the following</p>\n<pre><code>doors = Doors(total=5, prizes=3)\n\nuser_doors = doors.available(&quot;user&quot;)\n# Contestant picks a door from the user_doors defined above\ndoors.pick(1)\nprint(doors.prizes)\n#\n# The host gets a list of non_prize_doors the user has not choosen\noptions = doors.available(&quot;host&quot;)\nchoice = random.choice(options) # Picks a door to open based on some logic\n#\n# Shows the user the non prize content of the opened door\ncontent = doors.open(choice)\nprint(content)\n#\n# The user now gets a list of available doors to switch to\ndoors_2_switch_2 = doors.available(&quot;user&quot;)\n#\n# Some logic here to choose the door based on the available info\nuser_door = 1\ndoors.pick(user_door)\n#\n# The host now reveals what is behind the door the user choose\n#\ncontent = doors.open_picked() #\nprint(content)\n#\nif content == doors.prize:\n print(&quot;You won&quot;)\nelse:\n print(&quot;You lost&quot;)\n</code></pre>\n<h1>Further work</h1>\n<p>Add checks for classes as Reinderien has done in his code. Implement some error checking for IndexErrors etc. Implement the remaining classes.</p>\n<h1>Full code</h1>\n<pre><code>import random\n\nZERO_INDEX_DOORS = False\nOFFSET = 0 if ZERO_INDEX_DOORS else 1\n\n\ndef list_compliment(list1, list2):\n # Get every element in list1 not in list2\n if isinstance(list2, (int, float)):\n list2 = [list2]\n result = []\n for num in list1:\n if num not in list2:\n result.append(num)\n return result\n\n\nclass Doors:\n def __init__(self, total=3, prizes=1, non_prize=&quot;goat&quot;, prize=&quot;car&quot;, offset=OFFSET):\n &quot;&quot;&quot;A number of doors either containing a prize, or not. Can you guess which?&quot;&quot;&quot;\n self.prize = prize\n self.non_prize = non_prize\n #\n self.len = total\n self.doors = list(range(offset, self.len + offset))\n self.prizes = random.sample(self.doors, prizes)\n self.non_prizes = list_compliment(self.doors, self.prizes)\n self._available = dict()\n self._picked = -1\n #\n self.update()\n\n def open(self, door):\n &quot;&quot;&quot;Opens a given door and reveals its content. If no door, open users choice&quot;&quot;&quot;\n content = self.prize if door in self.prizes else self.non_prize\n self.update(door)\n return content\n\n def open_picked(self):\n return self.open(self._picked)\n\n def pick(self, door):\n self.picked = door\n return door\n\n @property\n def picked(self):\n return self._picked\n\n @picked.setter\n def picked(self, door):\n self._picked = door\n self.update()\n\n def update(self, door_2_remove=None):\n &quot;&quot;&quot;Removes a door from the state, and updates available doors to the various roles&quot;&quot;&quot;\n if door_2_remove:\n self.doors.remove(door_2_remove)\n if door_2_remove in self.prizes:\n self.prizes.remove(door_2_remove)\n else:\n self.non_prizes.remove(door_2_remove)\n #\n self.available_user = list_compliment(self.doors, self._picked)\n self.available_host = list_compliment(self.non_prizes, self.picked)\n\n\nif __name__ == &quot;__main__&quot;:\n\n doors = Doors(total=5, prizes=3)\n\n available = doors.available_user\n # Contestant picks a door\n doors.pick(1)\n print(doors.prizes)\n #\n # The host gets a list of non_prize_doors the user has not choosen\n options = doors.available_host\n choice = random.choice(options) # Picks a door to open based on some logic\n #\n # Shows the user the non prize content of the opened door\n content = doors.open(choice)\n print(content)\n #\n # The user now gets a list of available doors to switch to\n doors_2_switch_2 = doors.available_user\n #\n # Some logic here to choose the door based on the available info\n user_door = 1\n doors.pick(user_door)\n #\n # The host now reveals what is behind the door the user choose\n #\n content = doors.open_picked() #\n print(content)\n #\n if content == doors.prize:\n print(&quot;You won&quot;)\n else:\n print(&quot;You lost&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T15:12:17.687", "Id": "518550", "Score": "0", "body": "_use classes for something that has a particular state and that gets updated_ - This is slightly too narrow; _immutable_ classes with state that does not get updated can still be a very useful encapsulated representation. For example see Python's own `str` or `pathlib.Path`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T15:14:27.027", "Id": "518551", "Score": "0", "body": "_Why do you differ between first_reveal and second_reveal?_ because the OP has explicitly implemented a strategy that will vary based on the door-picking sequence. The first choice has entirely different logic than the second choice, and for Monty Hall scenarios this is kind of unavoidable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T15:18:23.367", "Id": "518552", "Score": "0", "body": "_list_compliment_ really would be more naturally expressed using set subtraction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T16:05:18.597", "Id": "518557", "Score": "1", "body": "@Reinderien I agree that my definition is too narrow, however OP asked for advice on how to structure classes / when to use them. In that regard it can be useful to think of it in terms of states. Even if there are other cases where they are useful.\n\nI have removed my second bullet point about the reveals. My point was rather which class should be responsible for this logic. Perhaps better is to store number of doors opened.\n\nI like the set idea! however might go against the spirit of the game not knowing where the doors are. But it would certainly make the code easier <- exercise for OP." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T12:26:53.330", "Id": "262719", "ParentId": "262675", "Score": "1" } } ]
{ "AcceptedAnswerId": "262688", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T11:48:20.660", "Id": "262675", "Score": "6", "Tags": [ "python", "object-oriented", "simulation" ], "Title": "Monty Hall simulation - OOP" }
262675
<p><strong>Problem statement for better understanding</strong>: Let's say we assign a unique number to each alphabet,</p> <pre><code>a=1, b=2, c=3...z=26 </code></pre> <p>then find the frequency of the sum of each word for all possible three letter words (with or without meaning). E.g.</p> <blockquote> <p>abc has sum of 6, yzx has a sum of 75, zzz has the sum of 78, cat has a sum of 24</p> </blockquote> <p>and so on.</p> <p>Following is my code in Kotlin.</p> <pre><code> var h = mutableMapOf&lt;Int, Int&gt;() for(i in 1..26){ for(j in 1..26){ for(k in 1..26){ val t = i+j+k if(h.containsKey(t)){ val count = h.get(t) h[t] = count!!.plus(1) } else { h.put(t, 1) } } } } println(h) </code></pre> <p>The output is:</p> <blockquote> <p>{3=1, 4=3, 5=6, 6=10, 7=15, 8=21, 9=28, 10=36, 11=45, 12=55, 13=66, 14=78, 15=91, 16=105, 17=120, 18=136, 19=153, 20=171, 21=190, 22=210, 23=231, 24=253, 25=276, 26=300, 27=325, 28=351, 29=375, 30=397, 31=417, 32=435, 33=451, 34=465, 35=477, 36=487, 37=495, 38=501, 39=505, 40=507, 41=507, 42=505, 43=501, 44=495, 45=487, 46=477, 47=465, 48=451, 49=435, 50=417, 51=397, 52=375, 53=351, 54=325, 55=300, 56=276, 57=253, 58=231, 59=210, 60=190, 61=171, 62=153, 63=136, 64=120, 65=105, 66=91, 67=78, 68=66, 69=55, 70=45, 71=36, 72=28, 73=21, 74=15, 75=10, 76=6, 77=3, 78=1}</p> </blockquote> <p>Regardless of the efficiency of the algorithm, how can I use functional programming in Kotlin to unwrangle the ugly loops to make it more readable and pleasant to the eyes?</p> <ul> <li>EDIT: The solution need not be strictly in Kotlin</li> </ul>
[]
[ { "body": "<p>There are three things you are doing here:</p>\n<ul>\n<li>Three loops</li>\n<li>Sum</li>\n<li>Grouping and counting</li>\n</ul>\n<p>The way I would recommend to do these things in Kotlin are:</p>\n<p>One loop: <code>val loop = 1..26</code></p>\n<p>Three loops and sum: <code>loop.flatMap {x -&gt; loop.flatMap { y -&gt; loop.map { z -&gt; x + y + z } } }</code></p>\n<p>Grouping by and counting: <code>.groupingBy { it }.eachCount()</code></p>\n<p>Resulting code:</p>\n<pre><code>val loop = 1..26\nval result = loop.flatMap { x -&gt; \n loop.flatMap { y -&gt; \n loop.map { z -&gt; x + y + z }\n }\n}.groupingBy { it }.eachCount()\n</code></pre>\n<p>Still though, I have to tell you that this is not an effective way and you might want to learn more about combinatorics in order to make a more efficient solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T10:39:41.867", "Id": "518530", "Score": "0", "body": "Thanks for your response. I will try this out and revert." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T21:30:21.520", "Id": "262699", "ParentId": "262678", "Score": "3" } } ]
{ "AcceptedAnswerId": "262699", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T12:44:36.243", "Id": "262678", "Score": "2", "Tags": [ "functional-programming", "kotlin" ], "Title": "Using Functional programming to untangle deeply nested loops (Kotlin)" }
262678
<p>I am wondering if this is correct:</p> <pre><code>VAR &lt;- c(&quot;City&quot;) data %&gt;% select(salary, age, VAR) melt(id.vars = c(&quot;Salary2&quot;, &quot;Age2&quot;,&quot;City&quot;)) -&gt; finalData </code></pre> <p>I get the message:</p> <pre><code>Note: Using an external vector in selections is ambiguous. ℹ Use `all_of(VAR)` instead of `VAR` to silence this message. ℹ See &lt;https://tidyselect.r-lib.org/reference/faq-external-vector.html&gt;. </code></pre> <p>The resulting finalData seems correct, but I wonder if this is the way to go. Thanks!</p>
[]
[ { "body": "<p>Here the VAR created another instance that is not part of data. Remember in R, everything is a vector.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T15:33:50.233", "Id": "518463", "Score": "0", "body": "Thanks. How to create a variable that can replace tens of others one so I don't have to replace manually?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T06:22:48.937", "Id": "518516", "Score": "0", "body": "This answer is not correct; running `select(VAR)` doesn't create anything. It just happens to evaluate `VAR` (since the column `\"VAR\"` is not present) to then run `select(City)`, which is a column in the original dataset. If it had not been a column, it would give an error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T14:57:46.267", "Id": "518548", "Score": "0", "body": "Thanks! now I too have got it cleared." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T12:08:40.517", "Id": "518926", "Score": "1", "body": "Not everything in R is a vector. For example, functions aren't." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T15:09:56.727", "Id": "262683", "ParentId": "262682", "Score": "0" } }, { "body": "<p><strong>Answer</strong></p>\n<p>Like the error says, use <code>all_of</code> (imported by <code>tidyverse</code> from <code>tidyselect</code>):</p>\n<pre class=\"lang-r prettyprint-override\"><code>var &lt;- &quot;Sepal.Length&quot;\niris %&gt;% \n select(tidyselect::all_of(var)) %&gt;% \n str\n\n# 'data.frame': 150 obs. of 1 variable:\n# $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n</code></pre>\n<p><strong>Rationale</strong></p>\n<p>Let's say we want to select a column:</p>\n<pre class=\"lang-r prettyprint-override\"><code>iris[, &quot;Sepal.Length&quot;]\n</code></pre>\n<p>In base R, we can easily select columns with variables:</p>\n<pre class=\"lang-r prettyprint-override\"><code>var &lt;- &quot;Sepal.Length&quot;\niris[, var]\n</code></pre>\n<hr />\n<p>However, you are using <code>tidyverse</code> functions. For example, <code>select</code> is from the <code>dplyr</code> package. The <code>tidyverse</code> packages rely on a special type of <a href=\"http://adv-r.had.co.nz/Computing-on-the-language.html\" rel=\"nofollow noreferrer\">non-standard evaluation</a>. As such, the correct way of selecting the <code>&quot;Sepal.Length&quot;</code> column is:</p>\n<pre class=\"lang-r prettyprint-override\"><code>select(iris, Sepal.Length) \n\n# more typically written as:\niris %&gt;% select(Sepal.Length)\n</code></pre>\n<p>As you can see, we are no longer using quotation marks. This is similar to <code>iris$Sepal.Length</code> in base R. A more extensive explanation of design choices in <code>dplyr</code> can be found <a href=\"https://dplyr.tidyverse.org/articles/programming.html\" rel=\"nofollow noreferrer\">here</a>. The core reasons for designing <code>tidyverse</code> this way are that it is more intuitive to use, and that is often faster to write.</p>\n<hr />\n<p>Let's consider your case:</p>\n<pre class=\"lang-r prettyprint-override\"><code>VAR &lt;- c(&quot;City&quot;)\niris %&gt;% select(VAR)\n</code></pre>\n<p>What it is doing, is looking for <code>&quot;VAR&quot;</code> inside <code>iris</code>. Since it cannot find it, it will then evaluate <code>VAR</code>, which yield <code>&quot;City&quot;</code>. It will then look for <code>&quot;City&quot;</code>, which in this case it won't find. It does work if we specify a column that is present (like in your example):</p>\n<pre class=\"lang-r prettyprint-override\"><code>VAR &lt;- c(&quot;Sepal.Length&quot;)\niris %&gt;% select(VAR)\n</code></pre>\n<hr />\n<p><strong>Where it goes wrong</strong></p>\n<p>So, what happens if we have a column called <code>VAR</code>, and supply a variable called <code>VAR</code>?</p>\n<pre class=\"lang-r prettyprint-override\"><code>iris$VAR &lt;- 1\nVAR &lt;- c(&quot;Sepal.Length&quot;)\niris %&gt;% select(VAR) %&gt;% str\n\n#'data.frame': 150 obs. of 1 variable:\n# $ VAR: num 1 1 1 1 1 1 1 1 1 1 ...\n</code></pre>\n<p>Here, it will return the column with ones, NOT what we intended. Using <code>all_of</code>, we can explicitly indicate that <code>select</code> should consider an EXTERNAL variable. This is to ensure that you get the results that you expect:</p>\n<pre class=\"lang-r prettyprint-override\"><code>iris$VAR &lt;- 1\nVAR &lt;- c(&quot;Sepal.Length&quot;)\niris %&gt;% select(all_of(VAR)) %&gt;% str\n\n#'data.frame': 150 obs. of 1 variable:\n# $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T07:13:03.807", "Id": "518523", "Score": "0", "body": "Thanks, however, I got confused as to which package I am using. I use the select function, from dplyr, not tidyverse. So It should work in my case. Also, in my case VAR is not the name of any column, its value is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T07:14:32.060", "Id": "518524", "Score": "0", "body": "`dplyr` is part of `tidyverse`. If you type `?select`, you'll find that `dplyr` actually imports `select` from `tidyselect` :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T07:16:18.753", "Id": "518525", "Score": "0", "body": "And I realise that `VAR` is not one of your columns. The point I was making is that it is dangerous not to use `all_of( )` because one of your columns may have the same name. Using `all_of( )` ensures that your code behaves as you expect it to. It is safer to include it, although in your specific example it is not needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T07:27:27.230", "Id": "518527", "Score": "0", "body": "Thanks, all clear now :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T06:18:25.970", "Id": "262710", "ParentId": "262682", "Score": "1" } } ]
{ "AcceptedAnswerId": "262710", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T14:51:32.233", "Id": "262682", "Score": "1", "Tags": [ "r" ], "Title": "R coding: creating a name variable to use with select" }
262682
<p>I have a list of <code>n</code> cities and hourly weather prediction for each one of them for <code>h</code> hours. I'm writing a script to find a pair of cities which has the most similar weather. And to represent the similarity in terms of a percentage scale.</p> <p>An example dataset with 5 hour forecast for 3 cities are as follows:</p> <pre><code>city temp feels_like pressure humidity wind_speed wind_deg ------------------------ ------ ------------ ---------- ---------- ------------ ---------- Hoboken 302.59 302.64 1013 44 4.45 266 Hoboken 304.41 303.97 1013 37 4.57 252 Hoboken 305.44 304.84 1012 34 5.26 254 Hoboken 305.8 305.15 1012 33 6.22 251 Hoboken 305.69 305.16 1012 34 6.7 253 Port Hueneme 289.65 289.39 1015 78 1.51 172 Port Hueneme 290.16 289.9 1015 76 2.17 191 Port Hueneme 290.3 290.08 1015 77 2.81 202 Port Hueneme 290.49 290.26 1014 76 3.64 208 Port Hueneme 290.41 290.18 1015 76 4.06 212 Auburn 299.29 299.29 1011 66 7.12 265 Auburn 299.92 301.21 1012 64 7.63 266 Auburn 300.19 301.51 1011 63 7.52 265 Auburn 299.89 301.1 1012 63 7.52 267 Auburn 299.27 299.27 1012 64 7.17 266 </code></pre> <p>And here is my script to find most similar cities in terms of weather assuming all datapoint have same weightage.</p> <pre><code>import pandas as pd import numpy as np def nearest(df): &quot;&quot;&quot; Process Dataframe with weather data and returns closest match for each city &quot;&quot;&quot; ret = [] for i, row in df.iterrows(): diff = np.abs(df.drop(i)['sum'] - df['sum'][i]) idx = diff.argmin() min_diff = diff.min() ret.append((df.drop(i).iloc[idx]['city'], min_diff)) return ret def main(): # Prepare dataframe df = pd.read_csv('hourly_weather_data.csv') # find average of each weather data points (temp, feels_like, etc) for each city df = df.groupby('city', as_index=False).mean() # Adds all mean values to a single value for comparison df['sum'] = df.sum(axis=1) df = df[['city', 'sum']] # Find closest city to each city in weather data mean df[['closest_city', 'diff']] = nearest(df) # Calculate similarity % df['%match'] = (df['sum'] - df['diff']) / df['sum'] * 100 # Find closest match by taking highest match% closest = df.iloc[df['%match'].argmax()] </code></pre>
[]
[ { "body": "<p>You probably want to replace</p>\n<pre><code>def main(): \n</code></pre>\n<p>with</p>\n<pre><code>if __name__ == &quot;__main__&quot;:\n</code></pre>\n<p>This second form means only run the indented code if this module specifically is called, not if it is imported. I'm assuming after the provided code, you just call <code>main()</code>, which is fine, but if you have no intentions of using <code>main</code> outside of this module, you should use the second form.</p>\n<p>Also, avoid <code>df.iterrows()</code> at all costs. It <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html\" rel=\"nofollow noreferrer\">returns a pandas <code>Series</code></a> for <em>every</em> row, which adds a huge amount of unnecessary overhead. You always want to create a vectorized solution if you can, so it would be good practice to investigate your <code>nearest</code> function to determine how you can replace the <code>df.iterrows()</code> with a form which uses the entire series at once, rather than row by row.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T06:54:40.753", "Id": "518520", "Score": "2", "body": "Thanks for the input. If you have any suggestions on the best approach to do the nearest function, adding them to the answer will be very helpful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T05:14:19.673", "Id": "262708", "ParentId": "262684", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T15:57:18.567", "Id": "262684", "Score": "2", "Tags": [ "python", "performance", "pandas" ], "Title": "Find the most similar pair of rows from a table" }
262684
<p>There are some Kiosk machines for people to take a survey. The survey is running by a 3rd party, so no way to get the data from them. To measure how much machines are in use I wrote a script to pull Edge-Chromium browsing history from a remote machine</p> <pre><code>function Copy-FileRemotely { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [string]$ComputerName ) try { $isSuccess = $true $Message = Copy-Item -Path &quot;\\$ComputerName\c$\Users\SMZSurvey2\AppData\Local\Microsoft\Edge\User Data\Default\History&quot; -Destination $PSScriptRoot\$ComputerName -Force -ErrorAction Stop -PassThru } catch { $isSuccess = $false $Message = ($_.Exception).Message } return [pscustomobject]@{ 'ComputerName' = $ComputerName 'isSuccess' = $isSuccess 'Message' = $Message } } $comps = &quot;smz-F9246-DB&quot;, &quot;xxx&quot; $result = @() foreach ($comp in $comps) { $result += Copy-FileRemotely $comp } $result | Out-GridView sleep 10 <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:38:05.970", "Id": "518492", "Score": "0", "body": "just for my curiosity ... how does the cache give you \"how much machines are in use\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:55:30.740", "Id": "518498", "Score": "0", "body": "@Lee_Dailey The history file contains titles of pages a user visited, the datestamps, etc. When a person finishes a survey, Edge displays him the \"Thank you!\" page. I guess I count those pages per day. It gives me the number of people that took a survey test on a particular machine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:52:24.247", "Id": "518508", "Score": "0", "body": "ah! thank you for the \"why\" of it. [*grin*] ///// i would likely use `Invoke-Command` to run your code on each system in parallel and let the count be sent back to you instead of the whole list of pages. i suspect that could get QUITE large ... and make things rather slow when sent across the network." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T11:41:15.887", "Id": "518536", "Score": "0", "body": "@Lee_Dailey Edge-Chromium keeps its browsing history data in SQLite database which stored in a file called History. I don't know how to decipher the file with Invoke-Command." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T20:26:06.653", "Id": "518574", "Score": "0", "body": "ah! i presumed you had code that you were running to decipher that info. if you DO have something that you can run on the _target_ systems, then i would do that. less to shove across your network AND running the code in parallel makes it seem worth your while." } ]
[ { "body": "<p>To make what you have more readable, I would not create a helper function to replace <code>Copy-Item</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$comps = &quot;smz-F9246-DB&quot;, &quot;xxx&quot;\n\n$result = foreach ($comp in $comps) {\n Try { Copy-Item `\n -Path &quot;\\\\$comp\\c$\\Users\\SMZSurvey2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\History&quot; `\n -Destination &quot;$PSScriptRoot\\$ComputerName&quot; -Force -PassThru\n }\n Catch [Common.Exceptions.You.See] { Write-Output &quot;$comp could not be contacted, skipping...&quot; }\n}\n\n# output list of files/failures\n$result\n</code></pre>\n<p>Based on your comments, you just want the count of visits to a specific site, which is pretty straightforward if you have powershell remoting available. I adapted <a href=\"https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Get-BrowserData.ps1\" rel=\"nofollow noreferrer\">this code</a> by user rvrsh3ll, which pulls website names from the chromium <code>History</code> file.</p>\n<pre><code># Connect to each machine and get the browsing history\n$result = Foreach ($comp in $comps) {\n\n Try { \n Invoke-Command -ComputerName $comp -EA Stop -ScriptBlock {\n\n # Regex returns trimmed URL\n $Regex = '(http(|s))://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&amp;=]*)*?'\n $Site = 'https://stackoverflow.com' # Set this\n\n # Seach chrome history for site visits\n $Count = (\n Get-Content -Path &quot;C:\\Users\\SMZSurvey2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\History&quot; -EA Stop|\n Select-String -AllMatches $regex |\n % {($_.Matches).Value} | \n Where {$_ -like $Site}\n ).Count\n\n # output as object\n [PSCustomObject]@{\n ComputerName = $using:comp\n SiteVisits = $Count\n Success = ($Count -gt -1) -and ($null -ne $Count)\n }\n } \n } Catch {[PSCustomObject]@{ComputerName=$comp;SiteVisits='N/A';Success=$false}}\n}\n\n# Output results:\n$result | FT ComputerName,SiteVisits,Success\n</code></pre>\n<p>And the results look like so:</p>\n<pre><code>ComputerName SiteVisits Success\n------------ ---------- -------\noffline-PC N/A False\nin-use-PC 2 True\nunused-PC 0 True\n</code></pre>\n<p>Hopefully this helps you skip the step of processing the file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T21:42:32.117", "Id": "263345", "ParentId": "262687", "Score": "2" } } ]
{ "AcceptedAnswerId": "263345", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T16:36:11.237", "Id": "262687", "Score": "1", "Tags": [ "powershell" ], "Title": "Script to copy Egde-Chromium browsing history from a remote machine. Try-catch, custom object building" }
262687
<p>I am attempting to perform <a href="https://en.wikipedia.org/wiki/Median_filter" rel="nofollow noreferrer">Median Filter</a> with size 3 x 3 in C language. The function <code>MedianFilter33</code> has been implemented as follows.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p>The basic structures:</p> <pre><code>typedef struct RGB { unsigned char R, G, B; } RGB; typedef struct BMPIMAGE { char FILENAME[MAX_PATH]; unsigned int XSIZE; unsigned int YSIZE; unsigned char FILLINGBYTE; unsigned char *IMAGE_DATA; } BMPIMAGE; typedef struct RGBIMAGE { unsigned int XSIZE; unsigned int YSIZE; RGB *IMAGE_DATA; } RGBIMAGE; </code></pre> </li> <li><p><code>MedianFilter33</code> function implementation:</p> <pre><code>RGB *MedianFilter33(const RGB *image,const int xsize,const int ysize) { RGB *output; output = (RGB*)malloc(xsize * ysize * sizeof(RGB)); if (output == NULL) { printf(&quot;Memory allocation error!&quot;); return NULL; } for(long long int i = 0; i &lt;(xsize * ysize); i++) { if( (i &lt; xsize) || ( (i % xsize) == 0) || ( ((i + 1) % xsize) == 0) || (i &gt;= (xsize*(ysize-1)))) { output[i].R = image[i].R; output[i].G = image[i].G; output[i].B = image[i].B; } else { unsigned char *sort_array; sort_array = (unsigned char*)malloc(9 * sizeof(unsigned char)); // R channel sorting sort_array[0] = image[i-xsize-1].R; sort_array[1] = image[i-xsize].R; sort_array[2] = image[i-xsize+1].R; sort_array[3] = image[i-1].R; sort_array[4] = image[i].R; sort_array[5] = image[i+1].R; sort_array[6] = image[i+xsize-1].R; sort_array[7] = image[i+xsize].R; sort_array[8] = image[i+xsize+1].R; sort_array = bubble_sort_uchar(sort_array,9,0); output[i].R = sort_array[4]; // G channel sorting sort_array[0] = image[i-xsize-1].G; sort_array[1] = image[i-xsize].G; sort_array[2] = image[i-xsize+1].G; sort_array[3] = image[i-1].G; sort_array[4] = image[i].G; sort_array[5] = image[i+1].G; sort_array[6] = image[i+xsize-1].G; sort_array[7] = image[i+xsize].G; sort_array[8] = image[i+xsize+1].G; bubble_sort_uchar(sort_array,9,0); output[i].G = sort_array[4]; // B channel sorting sort_array[0] = image[i-xsize-1].B; sort_array[1] = image[i-xsize].B; sort_array[2] = image[i-xsize+1].B; sort_array[3] = image[i-1].B; sort_array[4] = image[i].B; sort_array[5] = image[i+1].B; sort_array[6] = image[i+xsize-1].B; sort_array[7] = image[i+xsize].B; sort_array[8] = image[i+xsize+1].B; bubble_sort_uchar(sort_array,9,0); output[i].B = sort_array[4]; } } return output; } </code></pre> </li> </ul> <p><strong>Full Testing Code</strong></p> <p>In order to test <code>MedianFilter33</code> function implementation above, a tiny <code>bmp</code> image read / write framework has been performed.</p> <pre><code>/* Develop by Jimmy Hu */ #include &lt;math.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #define MAX_PATH 256 #define FILE_ROOT_PATH &quot;./&quot; #define True true #define False false typedef struct RGB { unsigned char R, G, B; } RGB; typedef struct BMPIMAGE { char FILENAME[MAX_PATH]; unsigned int XSIZE; unsigned int YSIZE; unsigned char FILLINGBYTE; unsigned char *IMAGE_DATA; } BMPIMAGE; typedef struct RGBIMAGE { unsigned int XSIZE; unsigned int YSIZE; RGB *IMAGE_DATA; } RGBIMAGE; RGB *MedianFilter33(const RGB*, const int x, const int y); RGB *raw_image_to_array(const unsigned char *image, const int xsize, const int ysize); unsigned long bmp_read_x_size(const char *filename, const bool extension); unsigned long bmp_read_y_size(const char *filename, const bool extension); char bmp_read(unsigned char *image, const int xsize, const int ysize, const char *filename, const bool extension); BMPIMAGE bmp_file_read(const char *filename, const bool extension); int bmp_write(const unsigned char *image, const int xsize, const int ysize, const char *filename); unsigned char *array_to_raw_image(const RGB* InputData, const int xsize, const int ysize); unsigned char bmp_filling_byte_calc(const unsigned int xsize); unsigned char *bubble_sort_uchar( const unsigned char *data_input, const unsigned long long int data_input_count, const bool mode); int main(int argc, char** argv) { printf(&quot;BMP image file name:(ex:test): &quot;); char *FilenameString; FilenameString = (char*)malloc( MAX_PATH * sizeof(char) ); scanf(&quot;%s&quot;,FilenameString); BMPIMAGE BMPImage1; BMPImage1 = bmp_file_read(FilenameString,false); free(FilenameString); printf(&quot;%s\n&quot;,BMPImage1.FILENAME); if(BMPImage1.IMAGE_DATA == NULL) { printf(&quot;Image contents error!&quot;); return -1; } RGBIMAGE RGBImage1; RGBImage1.XSIZE = BMPImage1.XSIZE; RGBImage1.YSIZE = BMPImage1.YSIZE; RGBImage1.IMAGE_DATA = (RGB*)malloc(RGBImage1.XSIZE * RGBImage1.YSIZE * sizeof(RGB)); if (RGBImage1.IMAGE_DATA == NULL) { printf(&quot;Memory allocation error!&quot;); return -1; } RGBImage1.IMAGE_DATA = raw_image_to_array(BMPImage1.IMAGE_DATA, BMPImage1.XSIZE, BMPImage1.YSIZE); bmp_write(array_to_raw_image(MedianFilter33(RGBImage1.IMAGE_DATA,RGBImage1.XSIZE, RGBImage1.YSIZE), RGBImage1.XSIZE, RGBImage1.YSIZE), BMPImage1.XSIZE, BMPImage1.YSIZE, &quot;MedianFilterOutput&quot;); return 0; } RGB *MedianFilter33(const RGB *image,const int xsize,const int ysize) { RGB *output; output = (RGB*)malloc(xsize * ysize * sizeof(RGB)); if (output == NULL) { printf(&quot;Memory allocation error!&quot;); return NULL; } for(long long int i = 0; i &lt;(xsize * ysize); i++) { if( (i &lt; xsize) || ( (i % xsize) == 0) || ( ((i + 1) % xsize) == 0) || (i &gt;= (xsize*(ysize-1)))) { output[i].R = image[i].R; output[i].G = image[i].G; output[i].B = image[i].B; } else { unsigned char *sort_array; sort_array = (unsigned char*)malloc(9 * sizeof(unsigned char)); // R channel sorting sort_array[0] = image[i-xsize-1].R; sort_array[1] = image[i-xsize].R; sort_array[2] = image[i-xsize+1].R; sort_array[3] = image[i-1].R; sort_array[4] = image[i].R; sort_array[5] = image[i+1].R; sort_array[6] = image[i+xsize-1].R; sort_array[7] = image[i+xsize].R; sort_array[8] = image[i+xsize+1].R; sort_array = bubble_sort_uchar(sort_array,9,0); output[i].R = sort_array[4]; // G channel sorting sort_array[0] = image[i-xsize-1].G; sort_array[1] = image[i-xsize].G; sort_array[2] = image[i-xsize+1].G; sort_array[3] = image[i-1].G; sort_array[4] = image[i].G; sort_array[5] = image[i+1].G; sort_array[6] = image[i+xsize-1].G; sort_array[7] = image[i+xsize].G; sort_array[8] = image[i+xsize+1].G; bubble_sort_uchar(sort_array,9,0); output[i].G = sort_array[4]; // B channel sorting sort_array[0] = image[i-xsize-1].B; sort_array[1] = image[i-xsize].B; sort_array[2] = image[i-xsize+1].B; sort_array[3] = image[i-1].B; sort_array[4] = image[i].B; sort_array[5] = image[i+1].B; sort_array[6] = image[i+xsize-1].B; sort_array[7] = image[i+xsize].B; sort_array[8] = image[i+xsize+1].B; bubble_sort_uchar(sort_array,9,0); output[i].B = sort_array[4]; } } return output; } RGB *raw_image_to_array(const unsigned char *image, const int xsize, const int ysize) { RGB *output; output = (RGB*)malloc(xsize * ysize * sizeof(RGB)); if(output == NULL) { printf(&quot;Memory allocation error!&quot;); return NULL; } unsigned char FillingByte; FillingByte = bmp_filling_byte_calc(xsize); for(int y = 0;y&lt;ysize;y++) { for(int x = 0;x&lt;xsize;x++) { output[y*xsize + x].R = image[3*(y * xsize + x) + y * FillingByte + 2]; output[y*xsize + x].G = image[3*(y * xsize + x) + y * FillingByte + 1]; output[y*xsize + x].B = image[3*(y * xsize + x) + y * FillingByte + 0]; } } return output; } //----bmp_read_x_size function---- unsigned long bmp_read_x_size(const char *filename, const bool extension) { char fname_bmp[MAX_PATH]; if(extension == false) { sprintf(fname_bmp, &quot;%s.bmp&quot;, filename); } else { strcpy(fname_bmp,filename); } FILE *fp; fp = fopen(fname_bmp, &quot;rb&quot;); if (fp == NULL) { printf(&quot;Fail to read file!\n&quot;); return -1; } unsigned char header[54]; fread(header, sizeof(unsigned char), 54, fp); unsigned long output; output = header[18] + (header[19] &lt;&lt; 8) + ( header[20] &lt;&lt; 16) + ( header[21] &lt;&lt; 24); fclose(fp); return output; } //---- bmp_read_y_size function ---- unsigned long bmp_read_y_size(const char *filename, const bool extension) { char fname_bmp[MAX_PATH]; if(extension == false) { sprintf(fname_bmp, &quot;%s.bmp&quot;, filename); } else { strcpy(fname_bmp,filename); } FILE *fp; fp = fopen(fname_bmp, &quot;rb&quot;); if (fp == NULL) { printf(&quot;Fail to read file!\n&quot;); return -1; } unsigned char header[54]; fread(header, sizeof(unsigned char), 54, fp); unsigned long output; output= header[22] + (header[23] &lt;&lt; 8) + ( header[24] &lt;&lt; 16) + ( header[25] &lt;&lt; 24); fclose(fp); return output; } //---- bmp_file_read function ---- char bmp_read(unsigned char *image, const int xsize, const int ysize, const char *filename, const bool extension) { char fname_bmp[MAX_PATH]; if(extension == false) { sprintf(fname_bmp, &quot;%s.bmp&quot;, filename); } else { strcpy(fname_bmp,filename); } unsigned char filling_bytes; filling_bytes = bmp_filling_byte_calc(xsize); FILE *fp; fp = fopen(fname_bmp, &quot;rb&quot;); if (fp==NULL) { printf(&quot;Fail to read file!\n&quot;); return -1; } unsigned char header[54]; fread(header, sizeof(unsigned char), 54, fp); fread(image, sizeof(unsigned char), (size_t)(long)(xsize * 3 + filling_bytes)*ysize, fp); fclose(fp); return 0; } BMPIMAGE bmp_file_read(const char *filename, const bool extension) { BMPIMAGE output; stpcpy(output.FILENAME, &quot;&quot;); output.XSIZE = 0; output.YSIZE = 0; output.IMAGE_DATA = NULL; if(filename == NULL) { printf(&quot;Path is null\n&quot;); return output; } char fname_bmp[MAX_PATH]; if(extension == false) { sprintf(fname_bmp, &quot;%s.bmp&quot;, filename); } else { strcpy(fname_bmp,filename); } FILE *fp; fp = fopen(fname_bmp, &quot;rb&quot;); if (fp == NULL) { printf(&quot;Fail to read file!\n&quot;); return output; } stpcpy(output.FILENAME, fname_bmp); output.XSIZE = (unsigned int)bmp_read_x_size(output.FILENAME,true); output.YSIZE = (unsigned int)bmp_read_y_size(output.FILENAME,true); if( (output.XSIZE == -1) || (output.YSIZE == -1) ) { printf(&quot;Fail to fetch information of image!&quot;); return output; } else { printf(&quot;Width of the input image: %d\n&quot;,output.XSIZE); printf(&quot;Height of the input image: %d\n&quot;,output.YSIZE); printf(&quot;Size of the input image(Byte): %d\n&quot;,(size_t)output.XSIZE * output.YSIZE * 3); output.FILLINGBYTE = bmp_filling_byte_calc(output.XSIZE); output.IMAGE_DATA = (unsigned char*)malloc((output.XSIZE * 3 + output.FILLINGBYTE) * output.YSIZE * sizeof(unsigned char)); if (output.IMAGE_DATA == NULL) { printf(&quot;Memory allocation error!&quot;); return output; } else { for(int i = 0; i &lt; ((output.XSIZE * 3 + output.FILLINGBYTE) * output.YSIZE);i++) { output.IMAGE_DATA[i] = 255; } bmp_read(output.IMAGE_DATA, output.XSIZE, output.YSIZE, output.FILENAME, true); } } return output; } //----bmp_write function---- int bmp_write(const unsigned char *image, const int xsize, const int ysize, const char *filename) { unsigned char FillingByte; FillingByte = bmp_filling_byte_calc(xsize); unsigned char header[54] = { 0x42, 0x4d, 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; unsigned long file_size = (long)xsize * (long)ysize * 3 + 54; unsigned long width, height; char fname_bmp[MAX_PATH]; header[2] = (unsigned char)(file_size &amp;0x000000ff); header[3] = (file_size &gt;&gt; 8) &amp; 0x000000ff; header[4] = (file_size &gt;&gt; 16) &amp; 0x000000ff; header[5] = (file_size &gt;&gt; 24) &amp; 0x000000ff; width = xsize; header[18] = width &amp; 0x000000ff; header[19] = (width &gt;&gt; 8) &amp;0x000000ff; header[20] = (width &gt;&gt; 16) &amp;0x000000ff; header[21] = (width &gt;&gt; 24) &amp;0x000000ff; height = ysize; header[22] = height &amp;0x000000ff; header[23] = (height &gt;&gt; 8) &amp;0x000000ff; header[24] = (height &gt;&gt; 16) &amp;0x000000ff; header[25] = (height &gt;&gt; 24) &amp;0x000000ff; sprintf(fname_bmp, &quot;%s.bmp&quot;, filename); FILE *fp; if (!(fp = fopen(fname_bmp, &quot;wb&quot;))) { return -1; } fwrite(header, sizeof(unsigned char), 54, fp); fwrite(image, sizeof(unsigned char), (size_t)(long)(xsize * 3 + FillingByte)*ysize, fp); fclose(fp); return 0; } unsigned char *array_to_raw_image(const RGB* InputData, const int xsize, const int ysize) { unsigned char FillingByte; FillingByte = bmp_filling_byte_calc(xsize); unsigned char *output; output = (unsigned char*)malloc((xsize * 3 + FillingByte) * ysize * sizeof(unsigned char)); if(output == NULL) { printf(&quot;Memory allocation error!&quot;); return NULL; } for(int y = 0;y &lt; ysize;y++) { for(int x = 0;x &lt; (xsize * 3 + FillingByte);x++) { output[y * (xsize * 3 + FillingByte) + x] = 0; } } for(int y = 0;y&lt;ysize;y++) { for(int x = 0;x&lt;xsize;x++) { output[3*(y * xsize + x) + y * FillingByte + 2] = InputData[y*xsize + x].R; output[3*(y * xsize + x) + y * FillingByte + 1] = InputData[y*xsize + x].G; output[3*(y * xsize + x) + y * FillingByte + 0] = InputData[y*xsize + x].B; } } return output; } unsigned char bmp_filling_byte_calc(const unsigned int xsize) { unsigned char filling_bytes; filling_bytes = ( xsize % 4); return filling_bytes; } unsigned char *bubble_sort_uchar( const unsigned char *data_input, const unsigned long long int data_input_count, const bool mode) { unsigned char *output; output = (unsigned char*)malloc( data_input_count * sizeof(unsigned char) ); for(unsigned long long int y=0;y &lt; data_input_count;y++) { output[y] = data_input[y]; } for(unsigned long long int x = 1; x &lt; data_input_count; x++) { for(unsigned long long int y = 0; y &lt; data_input_count - x; y++) { if( mode == 0 ) { if(output[y] &gt; output[y + 1]) { unsigned char temp; temp = output[y]; output[y] = output[y + 1]; output[y + 1] = temp; } } else if( mode == 1 ) { if(output[y] &lt; output[y + 1]) { unsigned char temp; temp = output[y]; output[y] = output[y + 1]; output[y + 1] = temp; } } } } return output; } </code></pre> <p>If there is any possible improvement, please let me know.</p>
[]
[ { "body": "<ul>\n<li><p>Thou shalt not cast <code>malloc</code>. It is redundant (if you <code>#include &lt;stdlib.h&gt;</code>), and may lead to hard-to-find bugs (if you don't).</p>\n</li>\n<li><p><code>sort_array</code> is allocated at each iteration, yet never <code>free</code>d.</p>\n<p>That said, I don't see why it needs <code>malloc</code> at all. Declare it statically</p>\n<pre><code> unsigned char sort_array[9];\n</code></pre>\n</li>\n<li><p>DRY. The code for R, G, and B channels, thrice repeated, cries to become a function. Consider defining <code>RGB</code> as</p>\n<pre><code> typedef struct {\n unsigned char channel[3];\n } RGB;\n</code></pre>\n<p>and writing the <code>else</code> clause as</p>\n<pre><code> for (int color = 0; color &lt; 3; i++) {\n output[i].channel[color] = median_filter_channel(image, i, xsize, color);\n }\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T18:51:12.340", "Id": "262691", "ParentId": "262690", "Score": "5" } }, { "body": "<p><strong><code>int</code> vs. <code>size_t</code> math</strong></p>\n<pre><code>...,const int xsize,const int ysize) ...\noutput = (RGB*)malloc(xsize * ysize * sizeof(RGB));\n// int * int \n</code></pre>\n<p><code>size_t</code> math typically exceeds <code>int</code> (and maybe <code>unsigned</code>) math and may handle <code>int</code> overflow of <code>xsize * ysize</code>.</p>\n<p>Consider dropping the unneeded cast, re-order and size to the referenced data, rather than type.</p>\n<pre><code>output = malloc(sizeof *output * xsize * ysize); // Uses size_t multiplication\n\n// RGBImage1.IMAGE_DATA = (RGB*)malloc(RGBImage1.XSIZE * RGBImage1.YSIZE * sizeof(RGB));\nRGBImage1.IMAGE_DATA = malloc(sizeof *RGBImage1.IMAGE_DATA * RGBImage1.XSIZE * RGBImage1.YSIZE);\n// size_t * int(converted to size_t) \n</code></pre>\n<p><strong><code>const</code> parameters</strong></p>\n<p>This is <strong>not</strong> about the <code>const</code> in <code>const RGB *</code>.</p>\n<p>Curious code uses <code>const int xsize</code>, but not <code>const RGB * const image</code> as neither <code>xsize</code> nor <code>RGB</code> changes.</p>\n<p>If one is using <code>const</code> to help prevent changes to unchanging parameters, be consistent.</p>\n<pre><code>// RGB *MedianFilter33(const RGB *image,const int xsize,const int ysize)\nRGB *MedianFilter33(const RGB * const image, const int xsize, const int ysize)\n</code></pre>\n<p>IMO: these <code>const</code> tend to be more error prone/obfuscation than worth it as they are noise in a <code>.h</code> function declaration.</p>\n<pre><code>// Suggested:\nRGB *MedianFilter33(const RGB *image, int xsize, int ysize)\n</code></pre>\n<p><strong><code>int</code> vs. <code>long long</code></strong></p>\n<p>Code curiously uses <code>long long i</code> below versus <code>int i</code>.</p>\n<pre><code>... const int xsize,const int ysize ...\nfor(long long int i = 0; i &lt;(xsize * ysize); i++) // Why long long int?\n</code></pre>\n<p>Should <code>xsize * ysize</code> exceed <code>INT_MAX</code>, result is <em>undefined behavior</em> and so nothing is gained by making <code>i</code> an <code>long long</code>. Code could compute the product using <code>long long</code> math`:</p>\n<pre><code>// A little better\nfor(long long int i = 0; i &lt;(1LL * xsize * ysize); i++)\n</code></pre>\n<p>For array sizing consider <code>size_t</code> and a C2x principle: put <a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\">dimensions first</a>.</p>\n<pre><code>// RGB *MedianFilter33(const RGB *image,const int xsize,const int ysize)\nRGB *MedianFilter33(size_t xsize, size_t ysize, const RGB *image)\n</code></pre>\n<p>Likewise problem with</p>\n<pre><code>unsigned char header[54];\n...\nunsigned long output;\noutput = header[18] + (header[19] &lt;&lt; 8) + ( header[20] &lt;&lt; 16) + ( header[21] &lt;&lt; 24);\n</code></pre>\n<p><code>header[18] + (header[19] &lt;&lt; 8) + ( header[20] &lt;&lt; 16) + ( header[21] &lt;&lt; 24)</code> is computed using <code>int</code> math.</p>\n<p>Alternative:</p>\n<pre><code>unsigned long output = header[18] + \n ((unsigned long)header[19] &lt;&lt; 8) + \n ((unsigned long)header[20] &lt;&lt; 16) + \n ((unsigned long)header[21] &lt;&lt; 24);\n</code></pre>\n<p>Here also, I'd consider <code>size_t</code> rather than <code>unsigned long</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:30:35.457", "Id": "518615", "Score": "0", "body": "A common, and useful, practice is to use `const` where possible and useful in the *definition*, but only the type (without top-level `const`) in other declarations (e.g. in a header file)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:52:46.290", "Id": "518631", "Score": "0", "body": "@TobySpeight I respectively disagree that \"use const where possible\". IMO not worthy the noise/clarity ratio. Perhaps there is a better forum than comments here to hash that out?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:02:47.580", "Id": "518638", "Score": "0", "body": "\"where possible\" is too strong. \"Where you would declare a similar local variable `const`\" is probably more apt. Main point was don't write it in non-defining declarations. (BTW, ITYM \"respectfully\"?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:09:38.900", "Id": "518641", "Score": "0", "body": "@TobySpeight Yes, respectfully." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T17:19:23.227", "Id": "519098", "Score": "0", "body": "@chux-ReinstateMonica Thank you for the answer. After I tried to remove the unneeded cast you mentioned. It can be compiled successfully in gcc, but clang says \"error: assigning to 'RGB *' from incompatible type 'void *'\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T17:26:15.583", "Id": "519100", "Score": "1", "body": "@JimmyHu `\"error: assigning to 'RGB *' from incompatible type 'void *'\"` --> You are likely compiling in another language like C++. Try compiling in C instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T17:33:11.327", "Id": "519101", "Score": "1", "body": "@chux-ReinstateMonica Thank you for letting me know the difference. It can be compiled successfully in clang, not clang++." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T03:22:03.810", "Id": "262706", "ParentId": "262690", "Score": "3" } }, { "body": "<p><code>buble_sort_uchar</code> allocates memory, and returns a pointer to it, but the pointer is never freed. And in two cases (G and B channels), the returned pointer isn't saved so the sort effectively does nothing except leak memory.</p>\n<p>Similarly, the memory allocated in <code>MedianFilter33</code> for <code>sort_array</code> is never freed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:27:29.107", "Id": "518614", "Score": "0", "body": "And neither of those actually require allocation - local variables should be fine in both cases." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T17:40:55.050", "Id": "262727", "ParentId": "262690", "Score": "1" } }, { "body": "<p>You’ve got some excellent answers commenting on the code itself. I am here to comment on the <em>algorithm</em>.</p>\n<p>It is really hard to implement a color median filter. The median is defined for a set of scalar values (and thus it is straight-forward to define a median filter that works on a gray-scale image). But the median of a set of 3-vectors (such as RGB pixel values) is not well defined. You cannot meaningfully sort vectors.</p>\n<p>You have implemented a marginal median—you compute the median for each of the components of the vector separately. The resulting value is typically not one of the input vectors. This means that your median filter is creating new colors that do not appear in the input image. For example, the marginal median of a equal combination of pure green, red and blue pixels is black! And the marginal median of an equal combination of pure magenta, cyan and yellow pixels is white!</p>\n<p>There exists a vector median. It selects the input vector that has the minimal distance to all other inputs (using either the sum of distances or sum of square distances). This is a lot more expensive to compute than the marginal median, and there is no guarantee that the vector median is actually “in the middle” of the set. But at least you don’t introduce new colors.</p>\n<p>You can define a consistent ordering of RGB colors, for example using dictionary sort, or sorting on brightness only and ignoring color, or some other system. No matter how you define the ordering, there is no guarantee that the result of your median computation is meaningful.</p>\n<p>Finally, you can convert from RGB to another color space, and there use a dictionary sort. The same issues as above apply.</p>\n<p>So, I have no good solution for you. It depends very much on the application which solution is most suitable. For “salt and pepper noise”, the marginal median and the sorting on brightness alone are reasonable solutions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T00:47:26.873", "Id": "262828", "ParentId": "262690", "Score": "4" } } ]
{ "AcceptedAnswerId": "262691", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T17:37:20.973", "Id": "262690", "Score": "4", "Tags": [ "c", "reinventing-the-wheel", "file", "image", "memory-management" ], "Title": "Image Processing Median Filter in C" }
262690
<p>A follow-up for <a href="https://codereview.stackexchange.com/q/262626/183642">this</a> previous question.</p> <p>I took into account previous reviews, and tried to make a simple API. I had never done anything non-trivial with C++20 concepts and ranges until now, so I am sure I have a lot of things to fix. I added many helper concepts. Interestingly, while there are various iterator and range concepts in the standard library, there is no way to specify &quot;iterator for int&quot; or &quot;range of int&quot;. So, many of my concepts try to implement that.</p> <p>The general design is that you can view a UTF-8 range as a range of code-points using the <code>from_utf8_range</code> class. And, you can write code points to a UTF-16 range using the <code>to_utf16_iter</code> class. To convert between ranges, you can use <code>std::ranges::copy</code> from standard library. <code>to_utf16</code> is a convenience function to do that.</p> <h1>Code</h1> <pre><code>#include &lt;stddef.h&gt; #include &lt;iterator&gt; #include &lt;ranges&gt; #include &lt;stdexcept&gt; #include &lt;type_traits&gt; namespace unic { /// Some helper concept-combinations /// ..._for&lt;T1, T2&gt; -&gt; T1 contains the T2 template &lt;class Iter, class Type&gt; concept iterator_for = ::std::same_as&lt;::std::decay_t&lt;::std::iter_value_t&lt;Iter&gt;&gt;, Type&gt;; template &lt;class Iter, class Type&gt; concept forward_iterator_for = ::std::forward_iterator&lt;Iter&gt; &amp;&amp; iterator_for&lt;Iter, Type&gt;; template &lt;class Iter, class Type&gt; concept input_iterator_for = ::std::input_iterator&lt;Iter&gt; &amp;&amp; iterator_for&lt;Iter, Type&gt;; template &lt;class Range, class Type&gt; concept range_for = ::std::ranges::range&lt;Range&gt; &amp;&amp; ::std::same_as&lt;::std::decay_t&lt;::std::ranges::range_value_t&lt;Range&gt;&gt;, Type&gt;; template &lt;class Range, class Type&gt; concept sized_range_for = ::std::ranges::sized_range&lt;Range&gt; &amp;&amp; range_for&lt;Range, Type&gt;; template &lt;class SizedInputRange, class Type&gt; concept sized_input_range_for = sized_range_for&lt;SizedInputRange, Type&gt; &amp;&amp; ::std::ranges::input_range&lt;SizedInputRange&gt;; template &lt;class SizedInputRange, class Type&gt; concept sized_forward_range_for = sized_range_for&lt;SizedInputRange, Type&gt; &amp;&amp; ::std::ranges::forward_range&lt;SizedInputRange&gt;; template &lt;class InputRange, class Type&gt; concept input_range_for = ::std::ranges::input_range&lt;InputRange&gt; &amp;&amp; range_for&lt;InputRange, Type&gt;; // Exception classes struct utf_error : ::std::runtime_error { utf_error(::std::string const&amp; msg) : ::std::runtime_error(msg) {} }; // This exception contains the point where error happened template &lt;class src_iter&gt; struct utf_positioned_error : utf_error { [[no_unique_address]] src_iter error_position{}; utf_positioned_error(src_iter err_pos, ::std::string const&amp; msg) : error_position(::std::move(err_pos)), utf_error(::std::move(msg)) {} }; // utf8 to code points template &lt;forward_iterator_for&lt;char8_t&gt; src_iter, ::std::sized_sentinel_for&lt;src_iter&gt; src_end_iter&gt; class from_utf8_range final { private: [[no_unique_address]] src_iter m_begin{}; [[no_unique_address]] src_end_iter m_end{}; public: struct iterator final // forward_iterator { private: friend class from_utf8_range; [[no_unique_address]] src_iter m_begin{}; [[no_unique_address]] src_end_iter m_end{}; constexpr iterator(src_iter begin, src_end_iter end) noexcept : m_begin(::std::move(begin)), m_end(::std::move(end)) {} // returns -1 on fail [[nodiscard]] static constexpr int compute_byte_count( char8_t const header) noexcept { auto const cnt = ::std::countl_one(static_cast&lt;unsigned char&gt;(header)); if (cnt == 0) return 1; if (cnt &lt; 2 || cnt &gt; 6) return -1; return cnt; } public: iterator() = default; // required for the iterator concept apparently using iterator_category = ::std::forward_iterator_tag; using difference_type = ::std::ptrdiff_t; using value_type = char32_t; [[maybe_unused]] constexpr auto operator++() -&gt; iterator&amp; { auto const cnt = compute_byte_count(*m_begin); if (cnt == -1 || cnt &gt; m_end - m_begin) throw utf_positioned_error(m_begin, &quot;Length in header byte is wrong&quot;); ::std::advance(m_begin, cnt); return *this; } [[nodiscard]] constexpr auto operator++(int) -&gt; iterator { auto copy = *this; ++*this; return copy; } [[nodiscard]] constexpr auto operator*() const -&gt; char32_t { auto const cnt = compute_byte_count(*m_begin); if (cnt == -1 || cnt &gt; m_end - m_begin) throw utf_positioned_error(m_begin, &quot;Length in header byte is wrong&quot;); char32_t code_point = 0; if (cnt == 1) // ascii code_point = *m_begin; else { // extract trailing bits auto begin = m_begin; code_point = static_cast&lt;char32_t&gt;( *begin++ &amp; (static_cast&lt;char8_t&gt;(~0u) &gt;&gt; (cnt + 1))); // extract rest of the bytes for (int i = 1; i &lt; cnt; ++i) { if (*begin &lt; 0x80 || 0xBF &lt; *begin) throw utf_positioned_error(begin, &quot;Illegal trail byte&quot;); code_point = (code_point &lt;&lt; 6) | (*begin &amp; 0x3F); ++begin; } } return code_point; } [[nodiscard]] constexpr auto operator==( iterator const&amp; other) const noexcept -&gt; bool { return m_begin == other.m_begin; } [[nodiscard]] constexpr auto operator!=( iterator const&amp; other) const noexcept -&gt; bool { return !(*this == other); } }; public: constexpr from_utf8_range(src_iter begin, src_end_iter end) noexcept : m_begin(::std::move(begin)), m_end(::std::move(end)) {} template &lt;sized_range_for&lt;char8_t&gt; u8range&gt; constexpr from_utf8_range(u8range const&amp; range) noexcept : from_utf8_range(::std::begin(range), ::std::end(range)) {} // all iterators are const [[nodiscard]] constexpr auto begin() const noexcept { return iterator(m_begin, m_end); } [[nodiscard]] constexpr auto end() const noexcept { return iterator{m_end, m_end}; } [[nodiscard]] constexpr auto cbegin() const noexcept { return begin(); } [[nodiscard]] constexpr auto cend() const noexcept { return end(); } }; template &lt;sized_range_for&lt;char8_t&gt; u8range&gt; from_utf8_range(u8range const&amp; range) noexcept -&gt;from_utf8_range&lt;::std::decay_t&lt;decltype(::std::ranges::begin(range))&gt;, ::std::decay_t&lt;decltype(::std::ranges::end(range))&gt;&gt;; namespace detail { // Outputs a code-point to a UTF-16 output iterator template &lt;::std::output_iterator&lt;char16_t&gt; out_iter&gt; [[maybe_unused]] constexpr int append(out_iter out, char32_t code_point) { if (code_point &lt;= 0xFFFF) { *out++ = static_cast&lt;char16_t&gt;(code_point); return 1; } else if (code_point &lt;= 0x10FFFF) { code_point -= 0x10000; *out++ = static_cast&lt;char16_t&gt;((code_point &gt;&gt; 10) + 0xD800); *out++ = static_cast&lt;char16_t&gt;((code_point &amp; 0x3FF) + 0xDC00); return 2; } else { throw utf_positioned_error(out, &quot;Out of UTF-16 range&quot;); } } } // namespace detail // Code points to utf16 template &lt;::std::output_iterator&lt;char16_t&gt; out_iter&gt; class to_utf16_iter final { private: [[no_unique_address]] out_iter m_iter{}; struct proxy_assigner { private: friend class to_utf16_iter; [[no_unique_address]] to_utf16_iter* m_parent; proxy_assigner(to_utf16_iter* parent) noexcept : m_parent{parent} {} proxy_assigner(::std::nullptr_t) = delete; public: [[maybe_unused]] constexpr auto operator=(char32_t const code_point) const -&gt; proxy_assigner const&amp; { auto const unit_cnt = detail::append(m_parent-&gt;m_iter, code_point); ::std::advance(m_parent-&gt;m_iter, unit_cnt); return *this; } template &lt;class T&gt; proxy_assigner&amp; operator=(T) const = delete; }; public: to_utf16_iter(out_iter iter) noexcept : m_iter(::std::move(iter)) {} to_utf16_iter() = default; using iterator_category = ::std::output_iterator_tag; using difference_type = ptrdiff_t; // Incrementing is no-op for output iterators. Actual incrementing is done on // write [[maybe_unused]] constexpr auto operator++() noexcept -&gt; to_utf16_iter&amp; { return *this; } [[nodiscard]] constexpr auto operator++(int) noexcept -&gt; to_utf16_iter { return *this; } [[nodiscard]] constexpr auto operator*() noexcept -&gt; proxy_assigner { return {this}; } }; template &lt;input_iterator_for&lt;char32_t&gt; input_beg, ::std::sentinel_for&lt;input_beg&gt; input_end&gt; constexpr ptrdiff_t to_utf16_size(input_beg beg, input_end const end) { ptrdiff_t size = 0; for (; beg != end; ++beg) { auto const code_point = *beg; if (code_point &lt;= 0xFFFF) size += 1; else if (code_point &lt;= 0x10FFFF) size += 2; else throw utf_positioned_error(beg, &quot;Out of UTF-16 range&quot;); } return size; } template &lt;input_range_for&lt;char32_t&gt; u32range&gt; constexpr ptrdiff_t to_utf16_size(u32range const&amp; range) { return to_utf16_size(::std::ranges::begin(range), ::std::ranges::end(range)); } template &lt;forward_iterator_for&lt;char8_t&gt; input_beg, ::std::sized_sentinel_for&lt;input_beg&gt; input_end&gt; constexpr ptrdiff_t to_utf16_size(input_beg beg, input_end const end) { return to_utf16_size(from_utf8_range{beg, end}); } template &lt;sized_forward_range_for&lt;char8_t&gt; u8range&gt; constexpr ptrdiff_t to_utf16_size(u8range const&amp; range) { return to_utf16_size(from_utf8_range{range}); } template &lt;forward_iterator_for&lt;char8_t&gt; u8beg, ::std::sized_sentinel_for&lt;u8beg&gt; u8end, ::std::output_iterator&lt;char32_t&gt; code_point_out&gt; constexpr void to_utf32(u8beg beg, u8end end, code_point_out out) { ::std::ranges::copy(from_utf8_range{beg, end}, out); } template &lt;forward_iterator_for&lt;char8_t&gt; u8beg, ::std::sized_sentinel_for&lt;u8beg&gt; u8end, ::std::output_iterator&lt;char16_t&gt; code_point_out&gt; constexpr void to_utf16(u8beg beg, u8end end, code_point_out out) { to_utf32(beg, end, to_utf16_iter{out}); } template &lt;sized_input_range_for&lt;char8_t&gt; u8range, ::std::output_iterator&lt;char32_t&gt; code_point_out_iter&gt; constexpr void to_utf32(u8range const&amp; range, code_point_out_iter out) { from_utf8_range rng{range}; to_utf32(::std::ranges::begin(rng), ::std::ranges::end(rng), out); } template &lt;sized_input_range_for&lt;char8_t&gt; u8range, ::std::output_iterator&lt;char16_t&gt; code_point_out&gt; constexpr void to_utf16(u8range const&amp; range, code_point_out out) { to_utf16(::std::ranges::begin(range), ::std::ranges::end(range), out); } } // namespace unic </code></pre> <h1>Basic usage</h1> <pre><code>int main() { char8_t constexpr u8[] = u8&quot;\U0001F449 \U00002728\u7EDD\u4E0D\u4F1A\u653E\u5F03\u4F60\U00002728 &quot; u8&quot;\U0001F448&quot;; try { auto constexpr u16_size = unic::to_utf16_size(u8); char16_t output[u16_size]; // constexpr size unic::to_utf16(u8, output); } catch (::std::exception const&amp; ex) { puts(ex.what()); return -1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:34:28.653", "Id": "518626", "Score": "0", "body": "_there is no way to specify \"iterator for int\" or \"range of int\"_ Probably because the standard algorithms and most code people write won't be specific for collections of `int`, but will be collections of `T` (another template argument) or some concept describing the requirements of that type; or to specify that iterators are to the _same_ type that is not itself present as an argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:43:45.870", "Id": "518629", "Score": "0", "body": "@JDługosz Hmm. We do have `std::span` for a continuous range of a specific type. It would nice if we could have a similar concept. You're probably right that there isn't enough \"demand\" though. Defining those for your project is simple enough that I don't think we should complicate the standard library by adding more \"stuff\" either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:51:57.840", "Id": "518630", "Score": "0", "body": "@Ayxan_Haqverdili Take a look at the headers for the latest version of standard algorithms... how do they declare that the `begin` and `end` are iterators to the same thing (or iterator and sentinel) and apply any concept to the `value_type`? There's certainly some common constraints that apply to many algorithms, so are they effectively packaged?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:59:31.013", "Id": "518634", "Score": "0", "body": "@JDługosz they use [`sentinel_for`](https://en.cppreference.com/w/cpp/iterator/sentinel_for) everywhere. That's also where I borrowed the naming convention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:08:40.980", "Id": "518640", "Score": "0", "body": "There are some other useful concepts like `indirectly_copyable`. But none provide the hard constraint I want: \"A range of char8_t elements\". I don't want people to pass vaguely related ranges. Like, someone could pass in a range of `int`s since `int` is convertible to `char8_t`." } ]
[ { "body": "<p>It's better to include <code>&lt;cstddef&gt;</code> than the deprecated <code>&lt;stddef.h&gt;</code> in C++ code (that ensures the definitions are in the <code>std</code> namespace). Ironically, the code proceeds to use <code>std::nullptr_t</code> despite the fact that the C header makes no guarantee of also defining such identifiers. The use of <code>ptrdiff_t</code> will need updating, though.</p>\n<p>I think it's overkill to write <code>::std::</code> rather than just <code>std::</code>, where we know we won't define an inner namespace with that name.</p>\n<blockquote>\n<pre><code>auto const cnt\n</code></pre>\n</blockquote>\n<p>We're allowed to use vowels in our identifiers! And doing so avoids ambiguity...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:51:29.980", "Id": "518494", "Score": "0", "body": "Thank you for the review! I recently saw a new proposal to un-depricate `.h` headers. I should have gone with `<cstddef>` anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:52:34.467", "Id": "518496", "Score": "0", "body": "I have been using `cnt` to mean count for as long as I remember. I should probably start getting used to `count` for clarity's sake." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T06:59:41.203", "Id": "518521", "Score": "0", "body": "The abbreviation jarred, particularly as it was out of step with the rest of the code. Sorry I didn't have time for a more in-depth review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:36:45.213", "Id": "518628", "Score": "0", "body": "Yea, the _great vowel shortage_ ended many years ago." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:49:50.193", "Id": "518650", "Score": "1", "body": "Well, some of the `cnt` you could have meant might be better off as `r` for `result` (if I declare a local for the result, that's my preference) or `n` (if the scope is small enough and there is no similar variable resp. no equally good use for `n`). Conciseness is good as long as it supports or at least doesn't hinder readability." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:48:51.793", "Id": "262697", "ParentId": "262692", "Score": "1" } }, { "body": "<p>Looks like you really embraced it! Good show! I just have a few simple notes:</p>\n<p>Being C++20, you don't need to define <code>operator!=</code> as well if <code>operator==</code> is defined.</p>\n<p><code>::std::begin(range), ::std::end(range)</code><br />\nRemember the &quot;std 2-step&quot;. Just use <code>std::range::begin</code> etc. to use the new ones that don't have these issues. I see you used those elsewhere, so you might have just missed some occurrences.</p>\n<p><code>// all iterators are const</code><br />\nNo, you call <code>operator++</code> on the iterator, can assign to one, etc.</p>\n<p>The various concepts you define ought to go into a nested <code>detail</code> namespace, as they pollute your official API. Or maybe you want those in your own different namespace for general reuse separate from this project.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:06:41.190", "Id": "518653", "Score": "0", "body": "I meant to say that they are all const-iterators, as in you can't modify the element they \"point\" to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:22:56.647", "Id": "518664", "Score": "1", "body": "You could call the nested class `const_iterator`, matching the names as used in collection class templates." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:51:42.333", "Id": "262765", "ParentId": "262692", "Score": "1" } } ]
{ "AcceptedAnswerId": "262765", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T19:42:04.743", "Id": "262692", "Score": "4", "Tags": [ "c++", "c++20", "unicode" ], "Title": "UTF-8 to UTF-16 using C++20 concepts and ranges" }
262692
<p>I've tried to implement multithreaded pathfinding in an attempt to increase performance, but if anything, performance seems to actually decrease when I enable multithreading.</p> <p>Is there anything I should do differently in order to see a performance gain from multithreading?</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using UnityEngine; public class PathRequest { public Vector3 Start; public Vector3 Destination; public float MaxRayDistance; public List&lt;Vector3&gt; OutPoints; public List&lt;Vector3&gt; OutDebugSearchList; public bool OutResult; public Action Callback; } public class PathFinder : MonoBehaviour { static public PathFinder Get { get; private set; } [SerializeField] private NavmeshView _navmesh; public int MaxThreads = 8; public int BufferCountWarning = 200; private AStarPool _aStarPool = new AStarPool(); private Queue&lt;PathRequest&gt; _finishedRequests = new Queue&lt;PathRequest&gt;(100); private List&lt;PathRequest&gt; _finishedRequestsBuffer = new List&lt;PathRequest&gt;(100); private List&lt;Thread&gt; _threads = new List&lt;Thread&gt;(20); private Queue&lt;PathRequest&gt; _newRequests = new Queue&lt;PathRequest&gt;(100); private void Awake() { //SINGLETON if (Get == null) { Get = this; } else { DestroyImmediate(gameObject); return; } DontDestroyOnLoad(gameObject); //ASTAR for (int i = 0; i &lt; MaxThreads; ++i) { _aStarPool.AddItem(new AStar(NeighborStrategy, NeighbourDistanceStrategy, HeuristicStrategy, _navmesh.NavmeshSO.Navmesh.CenterPoints.Length)); } } private void Update() { ExecuteCallbacksOnPathFound(); UpdateThreads(); } public void RequestPath(PathRequest pr) { _newRequests.Enqueue(pr); //WaitCallback threadwork = (s) =&gt; ThreadWork(pr); //ThreadPool.QueueUserWorkItem(threadwork); } public int GetNumNodes() { return _navmesh.NavmeshSO.Navmesh.CenterPoints.Length; } private void StartThread(PathRequest pr) { ThreadStart threadStart = () =&gt; ThreadWork(pr); //threadStart.Invoke(); Thread t = new Thread(threadStart); t.Start(); _threads.Add(t); } private void ThreadWork(PathRequest pr) { AStar instance = null; lock (_aStarPool) { instance = _aStarPool.GetItem(); } Stopwatch sw = new Stopwatch(); sw.Start(); FindPath(pr, instance); sw.Stop(); lock (_aStarPool) { _aStarPool.AddItem(instance); } float distance = 0f; if (pr.OutResult) { for (int i = 1; i &lt; pr.OutPoints.Count; ++i) distance += (pr.OutPoints[i] - pr.OutPoints[i - 1]).magnitude; } UnityEngine.Debug.Log($&quot;Path found: {pr.OutResult}, distance: {distance}, with elapsed ms {sw.Elapsed.TotalMilliseconds}&quot;); lock (_finishedRequests) { _finishedRequests.Enqueue(pr); } } private void UpdateThreads() { for(int i = _threads.Count -1; i &gt;= 0; --i) { if(!_threads[i].IsAlive) { _threads.RemoveAt(i); } } while(_threads.Count &lt; MaxThreads) { if(_newRequests.Count &gt; 0) { StartThread(_newRequests.Dequeue()); } else { break; } } if(_newRequests.Count &gt; BufferCountWarning) { UnityEngine.Debug.Log($&quot;Warning: over {BufferCountWarning} path requests in queue&quot;); } } private void ExecuteCallbacksOnPathFound() { if (_finishedRequests.Count &gt; 0) { _finishedRequestsBuffer.Clear(); lock (_finishedRequests) { for (int i = 0; i &lt; _finishedRequests.Count; ++i) { _finishedRequestsBuffer.Add(_finishedRequests.Dequeue()); } } foreach (var request in _finishedRequestsBuffer) { request.Callback(); } } } private void NeighborStrategy(int nodeIn, int[] nArr) { nArr[0] = _navmesh.NavmeshSO.Navmesh.TriangleConnections[nodeIn * 3]; nArr[1] = _navmesh.NavmeshSO.Navmesh.TriangleConnections[nodeIn * 3 + 1]; nArr[2] = _navmesh.NavmeshSO.Navmesh.TriangleConnections[nodeIn * 3 + 2]; } private float NeighbourDistanceStrategy(int nodeFrom, int toNeighbour) { return _navmesh.NavmeshSO.Navmesh.TriangleConnectionsDistances[nodeFrom * 3 + toNeighbour]; } private float HeuristicStrategy(int nodeFrom, int nodeTo) { Vector3 posFrom = _navmesh.NavmeshSO.Navmesh.CenterPoints[nodeFrom]; Vector3 posTo = _navmesh.NavmeshSO.Navmesh.CenterPoints[nodeTo]; return (posTo - posFrom).magnitude; } private void FindPath(PathRequest pr, AStar aStar) { Vector3 navmeshStartPos = default(Vector3); Vector3 navmeshEndPos = default(Vector3); pr.OutResult = false; int startNode = _navmesh.GetClosestPointOnNavmesh_Partitioning(new Ray(pr.Start, Vector3.down), pr.MaxRayDistance, ref navmeshStartPos); if (startNode == -1) return; int endNode = _navmesh.GetClosestPointOnNavmesh_Partitioning(new Ray(pr.Destination, Vector3.down), pr.MaxRayDistance, ref navmeshEndPos); if (endNode == -1) return; List&lt;int&gt; nodes = null; bool success = false; Stopwatch sw = null; //sw = new Stopwatch(); //sw.Start(); //success = _aStar.OldFindPathNodes(startNode, endNode, ref nodes); //sw.Stop(); //UnityEngine.Debug.Log($&quot;Old AStar ran with {sw.Elapsed.TotalMilliseconds} ms&quot;); sw = new Stopwatch(); sw.Start(); success = aStar.FindPathNodes(startNode, endNode, ref nodes); sw.Stop(); UnityEngine.Debug.Log($&quot;AStar ran with {sw.Elapsed.TotalMilliseconds} ms&quot;); if (!success) return; if (pr.OutDebugSearchList != null) { pr.OutDebugSearchList.Clear(); foreach(int node in nodes) { pr.OutDebugSearchList.Add(_navmesh.NavmeshSO.Navmesh.CenterPoints[node]); } } pr.OutPoints.Clear(); foreach(int node in nodes) { pr.OutPoints.Add(_navmesh.NavmeshSO.Navmesh.CenterPoints[node]); } pr.OutPoints.Add(pr.Destination); pr.OutResult = true; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T18:29:03.047", "Id": "518784", "Score": "0", "body": "One tip: `_threads` collection isn't thread-safe, be sure not to damage while using it concurrently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T23:26:24.370", "Id": "519054", "Score": "0", "body": "@aepot why is it not threadsafe?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T06:49:10.690", "Id": "519070", "Score": "0", "body": "Because `List<T>` isn't thread-safe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T20:09:28.747", "Id": "519697", "Score": "1", "body": "I would try using Unity's JOBs system for multi-threading, they'll take care of a lot of the scheduling headaches and it'll try to only create as many threads as you need, limiting overhead. If you can write codes within the constraints of \"HPC#\" (high-performance C#), then you'll get super aggressive compiler optimizations thanks to Unity's BURST compiler that will produce faster code than anything you could write with plain old C# multi-threading land. For any more detailed feedback, we'll probably need more context." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:02:02.277", "Id": "262693", "Score": "5", "Tags": [ "c#", "performance", "multithreading", "unity3d" ], "Title": "Multithreaded pathfinding in Unity C#" }
262693
<p>I have a 200 line fully functional flappy bird code but I was told it's suppose to be 250 lines. I don't know what more I can add to the js of the game to improve it and make it longer. I was told I can maybe add a pause button but I only know how to do it through css and not through JS. any suggestions? I also thought about lowering the restart button under the line of the score and speed and centering it but it didn't work for me.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var bird; var pole1; var pole2; var scoreSpan; var speedSpan; var highSpan; var speed; var score; var high; var flapping; var playing; var scoreUpdated; var gameArea; var restartBtn; var containerWidth; var containerHeight; function load() { high = 0; bird = document.getElementById("bird") poles = document.querySelectorAll(".pole") pole1 = document.getElementById("pole-1") pole2 = document.getElementById("pole-2") scoreSpan = document.getElementById("score") speedSpan = document.getElementById("speed") highSpan = document.getElementById("high") gameArea = document.getElementById("game-area"); restartBtn = document.getElementById("restart-btn"); containerWidth = gameArea.clientWidth; containerHeight = gameArea.clientHeight; gameArea.addEventListener("mousedown", function (e) { if (playing) { flapping = true; } }); gameArea.addEventListener("mouseup", function (e) { if (playing) { flapping = false; } }); } function restart() { restartBtn.removeEventListener('click', restart); if (score &gt;= high) { high = score; } speed = 2; score = 0; scoreUpdated = false; flapping = false; playing = true; speedSpan.textContent = speed; scoreSpan.textContent = score; highSpan.textContent = high; poles.forEach((pole) =&gt; { pole.style.right = 0; }); bird.style.top = 20 + "%"; gameLoop(); } function update() { var polesCurrentPos = parseFloat(window.getComputedStyle(poles[0]).getPropertyValue("right")); if (polesCurrentPos &gt; containerWidth * 0.85) { if (!scoreUpdated) { score += 1; scoreUpdated = true; } scoreSpan.textContent = score; if (score &gt;= high) { high = score; highSpan.textContent = high; } } if (polesCurrentPos &gt; containerWidth) { var newHeight = parseInt(Math.random() * 100); pole1.style.height = 100 + newHeight + "px"; pole2.style.height = 100 - newHeight + "px"; polesCurrentPos = 0; speed += 0.25; speedSpan.textContent = parseInt(speed); scoreUpdated = false; } poles.forEach((pole) =&gt; { pole.style.right = polesCurrentPos + speed + "px"; }); let birdTop = parseFloat(window.getComputedStyle(bird).getPropertyValue("top")); if (flapping) { bird.style.top = birdTop + -2 + "px"; } else if (birdTop &lt; containerHeight - bird.clientHeight) { bird.style.top = birdTop + 2 + "px"; } if (collision(bird, pole1) || collision(bird, pole2) || birdTop &lt;= 0 || birdTop &gt; containerHeight - bird.clientHeight) { gameOver(); } } function gameOver() { window.console.log("Game Over!:("); playing = false; restartBtn.addEventListener('click', restart); } function gameLoop() { update(); if (playing) { requestAnimationFrame(gameLoop); } } function collision(gameDiv1, gameDiv2) { let left1 = gameDiv1.getBoundingClientRect().left; let top1 = gameDiv1.getBoundingClientRect().top; let height1 = gameDiv1.clientHeight; let width1 = gameDiv1.clientWidth; let bottom1 = top1 + height1; let right1 = left1 + width1; let left2 = gameDiv2.getBoundingClientRect().left; let top2 = gameDiv2.getBoundingClientRect().top; let height2 = gameDiv2.clientHeight; let width2 = gameDiv2.clientWidth; let bottom2 = top2 + height2; let right2 = left2 + width2; if (bottom1 &lt; top2 || top1 &gt; bottom2 || right1 &lt; left2 || left1 &gt; right2) return false; return true; } document.addEventListener("keydown", function (e) { var key = e.key; if (key === " " &amp;&amp; playing) { flapping = true; } }); document.addEventListener("keyup", function (e) { e.preventDefault(); var key = e.key; if (key === " " &amp;&amp; playing) { flapping = false; } }); var myGameArea = { canvas: document.createElement("div"), game: document.getElementById("game"), gamearea: document.createElement("div"), gameinfo: document.createElement("div"), bird: document.createElement("div"), pole1: document.createElement("div"), pole2: document.createElement("div"), score: document.createElement("p"), scores: document.createElement("span"), speed: document.createElement("p"), speeds: document.createElement("span"), high: document.createElement("p"), highs: document.createElement("span"), restart: document.createElement("button"), start: function () { this.canvas.style = "font-family: David, cursive, sans-serif;text-align: center;"; this.canvas.width = 504; this.canvas.height = 341; this.game.appendChild(this.canvas); this.gamearea.style = "margin: auto;position: relative;width: 400px;height: 300px;border: 2px solid green;background-color: deepskyblue;overflow: hidden;"; this.gamearea.id = "game-area"; this.canvas.appendChild(this.gamearea); this.gameinfo.style = "margin: 5px;font-size: 18px;"; this.gameinfo.id = "game-info"; this.canvas.appendChild(this.gameinfo); this.bird.style = "position: absolute;background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJUAAABkCAYAAACPbHLzAAAABmJLR0QArgB4ACK51uKEAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4AobCCQTbH2I3QAAAfZJREFUeNrt3dFto0AUQFGIUgkd0Y1TgVON3ZFbmfz4IwlIJPAeA55zJP+stNoV3H0zDNam6wCOrt/zDytdV1zy6jc8/Z6/ucyIClEhKhAVokJUICpEhahAVIiKl+CFcmued6Dv8+69SdVqWyXvH7iohGX5I2b5m4QQuByaVIRPLVERHpblz/IXvhyKqpL7ZZj82vj5OExUW8J6d3vrxDRepwHdu2G/uP64HGaeZ4VNqpY/t8tQSukWP7fLkPf3KOs+ojpxUOlhlfywPP0R/nQoqkqb8iXj9bHq9+0R1lJcotrJ3Mb8VaeWqAgPS1SEL4eiYtdNvCMFRwqrjhycqLNZ1VN3J+rnPVH/z0GoF8qVzqxm3/197PDur+RPJVFVjuvHWdbBvqWwdokTVXOPafl7JRt1wjfeoiL8CU5UYgrfAolKSOG8phGUqDi+2agO/71kzhfV97hcIjZH9TskU4u0PZWwSNmom1qkPf2Ji/CoLImkRWVqkRKVqUVaVKYWKVGZWqRFZWqJKpW4RJUal8stKhAVoqKFqOx7MKkQFaICUSEqRAWiQlSICkSFqBAViIo0i/8BVug3F3oX/AA3vK8eVWhoohJVeGiiElV4aKISVXhkfuJDE1F5+kNUiApRgagQFaICUSEqRAWiQlSICkQFAAAARPkCSGysXZ/O3oIAAAAASUVORK5CYII=');height: 27px;width: 42px;background-size: contain;background-repeat: no-repeat;top: 20%;left: 15%;"; this.bird.id = "bird"; this.gamearea.appendChild(this.bird); this.pole1.style = "position: absolute;height: 100px;width: 30px;background-color: green;right: 0px;top: 0;"; this.pole1.id = "pole-1"; this.pole1.className = "pole"; this.gamearea.appendChild(this.pole1); this.pole2.style = "position: absolute;height: 100px;width: 30px;background-color: green;right: 0px; bottom: 0;"; this.pole2.id = "pole-2"; this.pole2.className = "pole"; this.gamearea.appendChild(this.pole2); this.restart.id = "restart-btn"; this.restart.style = "padding: 5px 10px;background-color: green;color: white;font-size: 18px;border: none;cursor: pointer;outline: none;"; var restartbtn = document.createTextNode("Restart"); this.restart.appendChild(restartbtn); this.gameinfo.appendChild(this.restart); this.score.style = "display: inline;padding: 20px;"; var s1 = document.createTextNode("Score: "); this.score.appendChild(s1); this.gameinfo.appendChild(this.score); this.speed.style = "display: inline;padding: 20px;"; var s2 = document.createTextNode("Speed: "); this.speed.appendChild(s2); this.gameinfo.appendChild(this.speed); this.high.style = "display: inline;padding: 20px;"; var s3 = document.createTextNode("High Score: "); this.high.appendChild(s3); this.gameinfo.appendChild(this.high); this.scores.id = "score"; var s1s = document.createTextNode("0"); this.scores.appendChild(s1s); this.score.appendChild(this.scores); this.speeds.id = "speed"; var s2s = document.createTextNode("2"); this.speeds.appendChild(s2s); this.speed.appendChild(this.speeds); this.highs.id = "high"; var s3s = document.createTextNode("0"); this.highs.appendChild(s3s); this.high.appendChild(this.highs); } } myGameArea.start(); load(); restart();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;Flappy Bird&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="stylesheet1.css" media="screen" /&gt; &lt;script src="game.js" defer&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="game"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:18:37.780", "Id": "518485", "Score": "5", "body": "\"I have a 200 line fully functional flappy bird code but I was told it's suppose to be 250 lines.\", why are the number of lines important?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:21:58.003", "Id": "518486", "Score": "0", "body": "it's for an assignment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:25:32.600", "Id": "518487", "Score": "4", "body": "Then the assignment is clearly flawed, it should be more about which features you as a developer should implement in the game. Could you provide a working version of your project in your question as a snippet please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:29:59.503", "Id": "518489", "Score": "4", "body": "\"I have a 200 line fully functional flappy bird code but I was told it's suppose to be 250 lines\" What does the specification ask for, specifically? This question reads like you have information you're not telling us." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:33:10.263", "Id": "518490", "Score": "0", "body": "The problem is that there isn't anything specific, I wasn't told to add X so I don't have ideas on what to add in order to make my js 250 lines" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T00:08:08.313", "Id": "518510", "Score": "1", "body": "\"I have a 200 line fully functional flappy bird code but I was told it's suppose to be 250 lines.\" - Writing code is not like writing an essay. Having a \"minimum\" code length is a very strange requirement. Are you sure that's not a \"maximum\"? \"...a pause button but I only know how to do it through css and not through JS\" - How would add a _working_ pause button with CSS? What is the complication in adding a pause button (you seem to have already done the \"hard\" stuff)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T05:12:51.363", "Id": "518515", "Score": "0", "body": "Some small ideas that can add complexity (and more lines): You could update the bird's physics to accelerate downwards. You could make the \"flap\" button do a quick spurt of upward accelaration, you could make spacebar and up also move the bird up, you could add audio, or animate a moving background in Javascript, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T16:11:23.510", "Id": "518561", "Score": "0", "body": "Adding more lines is easy. Turn your `.style = \"super long line of CSS\"` into template literals with one property per line, move long `||`s into their own functions. That's something beneficial to do anyway. \"Minimum lines\" is a [very absurd requirement](https://stackoverflow.com/questions/184071/when-if-ever-is-number-of-lines-of-code-a-useful-metric) as others have pointed out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T11:29:39.927", "Id": "518609", "Score": "0", "body": "Just use a more open style. VS will expand your code to 244 lines with the correct code format settings. Move all `var` to the top of their scope and you have 256 lines of code (no empty lines)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:17:03.977", "Id": "262694", "Score": "2", "Tags": [ "javascript" ], "Title": "What to add to a Flappy Bird JavaScript code" }
262694
<p>I tested this algorithm on 9x9 boards and on average, if the board passed to the function is a (valid) solution, it takes 0.13-0.14 seconds for 1 million executions on my machine. I ran my code in Release mode in Visual Studio and timed it using <code>Stopwatch</code>. I found the idea to use summing of all digits in rows, columns and square cells from another StackOverflow post on suggestions for making a sudoku validator. Note that I gave my code capabilities to work with perfect squares (perfect square is assumed in code) for the board size, where the size is assumed to be the same in all dimensions. I am also planning to build a sudoku solver in the near future.</p> <p>The sudoku board validating function:</p> <pre class="lang-cs prettyprint-override"><code>public static bool IsValidSudokuBoard(int[][] board) { int size = board.Length, cellSize = (int)Math.Sqrt(size), sumOfAllNums = (int)SumAllUpTo(size); for (int row = 0; row &lt; size; row++) if (Sum(board[row]) != sumOfAllNums) return false; for (int column = 0; column &lt; size; column++) { int columnSum = 0; for (int row = 0; row &lt; size; row++) columnSum += board[row][column]; if (columnSum != sumOfAllNums) return false; } for (int row = 0; row &lt; size; row += cellSize) for (int column = 0; column &lt; size; column += cellSize) { int cellSum = 0; for (int rowOffset = 0; rowOffset &lt; cellSize; rowOffset++) for (int columnOffset = 0; columnOffset &lt; cellSize; columnOffset++) cellSum += board[row + rowOffset][column + columnOffset]; if (cellSum != sumOfAllNums) return false; } return true; } </code></pre> <p>Where <code>SumAllUpTo</code> is defined as follows:</p> <pre class="lang-cs prettyprint-override"><code>public static double SumAllUpTo(double end, double start = 0d) =&gt; end * Math.Floor((end + 1d) / 2d) - ((start == 0d) ? 0d : SumAllUpTo(start)); </code></pre> <p>And <code>Sum</code> is defined as follows:</p> <pre class="lang-cs prettyprint-override"><code>public static int Sum(this int[] array) { int result = 0; for (int x = 0; x &lt; array.Length; x++) result += array[x]; return result; } </code></pre> <p>Today (06.06.2021) I tested whether the function would run faster if it always assumed the board passed to it was of size 9x9, and it turns out that it is about twice as fast, with the same input. It is only 1.5x slower than looking up each element of a 9x9 board 1 million times. The resulting slowest time for the 9x9 only function is 0.063 seconds for 1 million executions.</p> <pre class="lang-cs prettyprint-override"><code>public static bool IsValidSudokuBoard9x9(int[][] board) { for (int y = 0; y &lt; 9; y++) if (board[y][0] + board[y][1] + board[y][2] + board[y][3] + board[y][4] + board[y][5] + board[y][6] + board[y][7] + board[y][8] != 45) return false; for (int x = 0; x &lt; 9; x++) if (board[0][x] + board[1][x] + board[2][x] + board[3][x] + board[4][x] + board[5][x] + board[6][x] + board[7][x] + board[8][x] != 45) return false; for (int y = 0; y &lt; 9; y += 3) for (int x = 0; x &lt; 9; x += 3) if (board[y][x] + board[y][x + 1] + board[y][x + 2] + board[y + 1][x] + board[y + 1][x + 1] + board[y + 1][x + 2] + board[y + 2][x] + board[y + 2][x + 1] + board[y + 2][x + 2] != 45) return false; return true; } </code></pre> <p>At this point, I could write each of the loops down by hand and remove them, but the code would be extremely messy and it wouldn't get faster than 0.04 seconds (time for 1 million full 9x9 board look-ups, for each element). I can now confidently say that I have one of the fastest 9x9 sudoku board validation algorithms out there in C#.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:24:05.140", "Id": "518505", "Score": "0", "body": "Why do you want to make this faster? Why run it a million times? It should be good to run one time on a given puzzle and \"validate\" -> answer if it's a correct solution or not? If you're practicing/learning programming, I think you'd gain more from moving on to solving another problem rather than optimize something that has no use being optimized." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:27:27.147", "Id": "518506", "Score": "0", "body": "A sudoku validator may become the core of a sudoku solver, which uses random moves with backtracking and calls the validator millions of times. Optimizing the validator for speed is useful. (@user985366)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:28:28.107", "Id": "518507", "Score": "0", "body": "@RainerP. Good point, thanks for filling that in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T12:43:08.797", "Id": "518541", "Score": "0", "body": "A Sudoku solver should not be based on full-board validation though: it should backtrack *as early as possible* (that's not a small trick: it saves an exponential amount of work to prune a whole sub-tree of the recursion). This trick with the sums actually doesn't work for partially-filled boards. Of course we can still review this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T13:07:18.113", "Id": "518542", "Score": "2", "body": "Actually on second thought it doesn't really work for a full board either: it could be full of fives and pass the test" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T06:14:57.053", "Id": "518587", "Score": "2", "body": "you focused on the total sum, but you've forgot to check the uniqueness of numbers. You probably need to see Sudoku rules before you go further. https://masteringsudoku.com/sudoku-rules-beginners/" } ]
[ { "body": "<p>As it was stated by @harold and @iSR5 your current implementation is not bullet-proof. I will not repeat their suggestions.</p>\n<p>Rather I want to show you how to reduce repetition.<br />\nSo, let me share with you my revised version for <code>IsValidSudokuBoard9x9</code> then I will explain it:</p>\n<pre><code>public static bool IsValidSudokuBoard9x9New(int[][] board)\n{\n const byte numberOfRows = 9, numberOfColumns = numberOfRows, fullFilledRowOrColumn = 45;\n\n byte rowMaxIdx = numberOfRows - 1;\n for (byte row = 0; row &lt; numberOfRows; row++)\n if (board[row][0..rowMaxIdx].Sum() != fullFilledRowOrColumn)\n return false;\n\n byte columnMaxIdx = numberOfColumns - 1;\n for (byte column = 0; column &lt; numberOfColumns; column++)\n if (board[0..columnMaxIdx][column].Sum() != fullFilledRowOrColumn)\n return false;\n\n for (byte row = 0; row &lt; numberOfRows; row += 3)\n for (byte column = 0; column &lt; numberOfColumns; column += 3)\n {\n columnMaxIdx = (byte)(column + 2);\n rowMaxIdx = (byte)(row + 2);\n\n if (board[row..rowMaxIdx][column..columnMaxIdx].SelectMany(item =&gt; item).Sum() != fullFilledRowOrColumn)\n return false;\n }\n\n return true;\n}\n</code></pre>\n<ul>\n<li>Rather than repeating <code>9</code> over and over again\n<ul>\n<li>I would suggest to introduce constants with meaningful names like <code>numberOfRows, numberOfColumns</code></li>\n</ul>\n</li>\n<li>I would suggest to use <code>row</code> and <code>column</code> variable names instead of <code>x</code> and <code>y</code> in your loops</li>\n<li>I would encourage you to use C# 8's <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges\" rel=\"nofollow noreferrer\">Range and Index</a> feature rather than accessing each element one by one\n<ul>\n<li><code>board[row][0..rowMaxIdx]</code>: this will return an <code>IEnumerable&lt;int&gt;</code> on which you can simply call the <code>Sum</code> LINQ operator</li>\n<li><code>board[0..columnMaxIdx][column]</code>: it works in the same way as the previous one</li>\n<li><code>board[row..rowMaxIdx][column..columnMaxIdx]</code>: this will return an <code>int[][]</code> so first we need to flatten it (reduces its dimensions from 2 to 1) with <code>SelectMany</code> then we can issue the same <code>Sum</code> operator just like before</li>\n</ul>\n</li>\n<li>Finally a minor thing I've used <code>byte</code> for indexing rather than <code>int</code> because we know that the max index fits into that range</li>\n</ul>\n<hr />\n<p>Other suggestions:</p>\n<ul>\n<li>I would suggest to consider the usage of <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.getlength?view=net-5.0\" rel=\"nofollow noreferrer\">GetLength</a> to retrieve the length of each dimension of the <code>board</code> dynamically\n<ul>\n<li>It gives you the ability to write generic code that can handle other boards than 9x9, for example 5x5 without any code change</li>\n</ul>\n</li>\n<li>I would also suggest to consider the usage of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays\" rel=\"nofollow noreferrer\">multidimensional array</a> <code>int[,]</code> instead of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays\" rel=\"nofollow noreferrer\">jagged array</a> <code>int[][]</code>\n<ul>\n<li>With the latter one each row can have different number of columns, but we do know that each row should have exactly the same number of columns</li>\n</ul>\n</li>\n<li>Last but not least, I would suggest to extract each kind of validation into a separate method\n<ul>\n<li>This will drastically reduce the complexity of each method</li>\n</ul>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T07:36:24.433", "Id": "262745", "ParentId": "262698", "Score": "1" } }, { "body": "<p>Nice work building a very fast Sudoko validator. As others have mentioned, getting beyond the hard-coded size will take some tweaking.</p>\n<p>If I were writing a Sudoko solver (and the requisite validator), I'd probably start with the object model before the algorithms.</p>\n<p>So, I started thinking about the classes I might implement and sketched out some high-level ideas. In case you decide to flesh out the object model and want to compare notes, here they are. Please note this is pseudo-code.</p>\n<pre><code>public class Cell \n{\n public int Value { get; private set; } \n public int X { get; private set; }\n public int Y { get; private set; } \n\n public Set Row { get; private set; }\n public Set Column { get; private set; }\n public Set Box { get; private set; }\n}\n\npublic class Set //A row, column, or box\n{\n public List&lt;Cell&gt; Cells { get; private set; } \n public bool IsValid() =&gt; //check validity - i.e. contains each number only once\n}\n\npublic class Collection //All rows or all columns or all boxes\n{\n public List&lt;Set&gt; Items {get; private set;}\n public bool AreValid() =&gt; Items.All(i =&gt; i.IsValid());\n}\n\npublic class Board \n{\n public int Size {get; private set;}\n \n public Collection Rows { get; private set; }\n public Collection Columns { get; private set; }\n public Collection Boxes {get; private set;}\n \n public Board(int size) =&gt; Size = size;\n \n public void Generate()\n {\n Rows = new Collection();\n Columns = new Collection();\n Boxes = new Collection();\n Enumerable.Range(1, size).ToList().ForEach(x =&gt;\n { \n Enumerable.Range(1, size).ToList().ForEach(y =&gt; \n {\n ///generate cells, rows, columns, boxes, \n //add to collections\n });\n });\n } \n \n public bool IsValid() =&gt; \n Rows.AreValid() &amp;&amp; Columns.AreValid() &amp;&amp; Boxes.AreValid();\n}\n\nstatic void Main()\n{\n var board = new Board(9);\n board.Generate();\n var isValid = board.IsValid();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T14:06:56.693", "Id": "262936", "ParentId": "262698", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:58:25.000", "Id": "262698", "Score": "1", "Tags": [ "c#", "algorithm", ".net", "validation", "sudoku" ], "Title": "Possible speed improvements for a Sudoku board validation algorithm?" }
262698
<p>As a hobby project (and to learn the language), I'm working on a crypto library in Rust. The following is a component thereof, which implements encryption with and the cracking of the Caesar cipher.</p> <p>My primary interest is whether the code follows best practices, with a secondary concern regarding its efficiency. I'm not very used to Rust idioms, and there are a few places where I feel that the code is clunky, but can't see a better solution.</p> <p>Note that:</p> <ul> <li>this being a hobby project, I aim to write most everything myself and avoid external libraries;</li> <li>as this is part of a larger (as yet unwritten) framework, I have generalised more than necessary for this component alone. If it seems over-engineered, that would be because it has been designed for easy implementation of other [poly]alphabetic ciphers, like a more general substitution cipher or the Vigenère cipher.</li> </ul> <h1><code>lib.rs</code></h1> <pre class="lang-rust prettyprint-override"><code>#![feature(const_option)] pub mod alphabetic; pub mod caesar; pub mod frequency; </code></pre> <h1><code>alphabetic.rs</code></h1> <pre class="lang-rust prettyprint-override"><code>///Provides various types for dealing with alphabetic ciphers, like ///the Caesar and Vigenère ciphers. use std::{ cmp::{self, Ordering}, fmt::{self, Display}, ops::{Add, Sub}, }; pub const ALPHABET_SIZE: usize = 26; #[derive(Copy, Clone, Debug)] pub enum Case { Upper, Lower, } #[derive(Copy, Clone, Debug)] ///Contains a `value` (zero-indexed and guaranteed to be in the range 0-25) and /// a `Case` specifying the case. The case is only used for display purposes, /// and when cases are mixed in arithmetic operations, the output favours ///`Case::Upper` (so if one letter is uppercase, the result will also be /// uppercase); this ensures that addition is at least commutative. pub struct Letter { pub value: u8, pub case: Case, } impl Letter { ///Constructs a new `Letter` from its `u8` and `Case` components. pub const fn new(value: u8, case: Case) -&gt; Letter { Letter { value: (value) % ALPHABET_SIZE as u8, case, } } ///Constructs a new `Letter`, accepting a negative alphabetical index ///(which will wrap around). pub fn from_signed(value: i8, case: Case) -&gt; Letter { Letter { //rem_euclid returns nonnegative integers so this cast is safe value: value.rem_euclid(ALPHABET_SIZE as i8) as u8, case, } } ///Returns the `Letter` corresponding to a given `char`, or `None` if ///the `char` is out of the alphabetical ASCII range. pub const fn try_from_char(char_value: char) -&gt; Option&lt;Letter&gt; { let (start, case) = match char_value { 'A'..='Z' =&gt; ('A' as u32, Case::Upper), 'a'..='z' =&gt; ('a' as u32, Case::Lower), _ =&gt; return None, }; Some(Letter::new((char_value as u32 - start) as u8, case)) } ///Returns the `Letter` corresponding to a given byte, or `None` if the ///byte is out of the alphabetical ASCII range. pub fn try_from_utf8(byte_value: u8) -&gt; Option&lt;Letter&gt; { let (start, case) = match byte_value { 0x41..=0x5A =&gt; (0x41, Case::Upper), 0x61..=0x7A =&gt; (0x61, Case::Lower), _ =&gt; return None, }; Some(Letter::new(byte_value - start, case)) } ///Returns the `char` corresponding to the alphabetical character specified ///by `self.value` and `self.case`. Returns `None` if this fails, but that ///could only happen if `self.value` where out of its correct range (0-25). ///Typically we can be sure that is not the case, so we can `unwrap` the /// result, or use the `unsafe` `to_char_unchecked` if speed is /// required. pub fn try_to_char(&amp;self) -&gt; Option&lt;char&gt; { char::from_u32(match self.case { Case::Upper =&gt; self.value as u32 + 'A' as u32, Case::Lower =&gt; self.value as u32 + 'a' as u32, }) } ///# Safety ///This should be safe in all circumstances, since `from_u32_unchecked` ///could only fail if the value is out of ASCII range. So long as our ///range guarantee on `self.value` (0-25) is met, the corresponding `u32` ///will be in range. pub unsafe fn to_char_unchecked(&amp;self) -&gt; char { char::from_u32_unchecked(match self.case { Case::Upper =&gt; self.value as u32 + 'A' as u32, Case::Lower =&gt; self.value as u32 + 'a' as u32, }) } ///Returns the (ASCII) byte corresponding to the character specified by ///`self.value` and `self.case`. pub fn to_utf8(&amp;self) -&gt; u8 { match self.case { Case::Upper =&gt; self.value + 0x41, Case::Lower =&gt; self.value + 0x61, } } ///Returns `Case::Lower` iff both inputs are lowercase, and `Case::Upper` ///otherwise. Used internally to decide which case to give the result of an /// arithmetic operation on two `Letter`s. fn combined_case(case1: Case, case2: Case) -&gt; Case { match (case1, case2) { (Case::Lower, Case::Lower) =&gt; Case::Lower, _ =&gt; Case::Upper, } } } ///`Letters` add their values, wrapping around the alphabet if necessary. impl Add&lt;Letter&gt; for Letter { type Output = Self; fn add(self, rhs: Self) -&gt; Self { Self::new( self.value + rhs.value, Letter::combined_case(self.case, rhs.case), ) } } impl Add&lt;i8&gt; for Letter { type Output = Self; fn add(self, rhs: i8) -&gt; Self { Self::from_signed(self.value as i8 + rhs, self.case) } } impl Sub&lt;Letter&gt; for Letter { type Output = Self; fn sub(self, rhs: Self) -&gt; Self { Self::from_signed( self.value as i8 - rhs.value as i8, Letter::combined_case(self.case, rhs.case), ) } } impl Sub&lt;i8&gt; for Letter { type Output = Self; fn sub(self, rhs: i8) -&gt; Self { Self::from_signed(self.value as i8 - rhs, self.case) } } impl PartialEq for Letter { fn eq(&amp;self, other: &amp;Self) -&gt; bool { self.value == other.value } } impl Eq for Letter {} impl Ord for Letter { fn cmp(&amp;self, other: &amp;Self) -&gt; Ordering { self.value.cmp(&amp;other.value) } } impl PartialOrd for Letter { fn partial_cmp(&amp;self, other: &amp;Self) -&gt; Option&lt;Ordering&gt; { Some(self.cmp(other)) } } impl Display for Letter { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { write!(f, &quot;{}&quot;, self.try_to_char().ok_or(fmt::Error)?) } } #[derive(Clone, Debug, PartialEq)] ///Newtype over a `Vec&lt;Letter&gt;`. Allows conversion to and from a UTF-8 string, ///and allows elementwise addition and other operations. pub struct Alphabetic(Vec&lt;Letter&gt;); impl Alphabetic { pub fn new(vec: Vec&lt;Letter&gt;) -&gt; Alphabetic { Alphabetic(vec) } ///Returns an `Alphabetic` from the given string, but returns `None` if the /// string contains any non-alphabetic characters. pub fn try_from_str(string: &amp;str) -&gt; Option&lt;Alphabetic&gt; { let letters: Option&lt;Vec&lt;Letter&gt;&gt; = string.bytes().map(Letter::try_from_utf8).collect(); Some(Alphabetic::new(letters?)) } ///Returns an `Alphabetic` from the given string. Unlike `try_from_str`, /// this function will simply ignore any characters which it cannot /// convert, rather than returning `None`. pub fn from_str_filtered(string: &amp;str) -&gt; Alphabetic { Alphabetic::new( string .bytes() .filter(|x| x.is_ascii_alphabetic()) .map(|x| Letter::try_from_utf8(x).unwrap()) .collect(), ) } ///Applies `func` to each pair of values from `self` and `other`, /// collecting the results into a new `Alphabetic`. If it reaches the /// end of one of the strings, it will simply dump the remainder of the /// longer string into the output; therefore, the output is always the /// same length as the longer of the two strings. pub fn pairwise_map( &amp;self, other: &amp;Self, func: Box&lt;dyn Fn(Letter, Letter) -&gt; Letter&gt;, ) -&gt; Alphabetic { let mut buf: Vec&lt;Letter&gt; = Vec::with_capacity(cmp::max(self.len(), other.len())); let mut self_iter = self.iter(); let mut other_iter = other.iter(); loop { match (self_iter.next(), other_iter.next()) { (Some(sval), Some(oval)) =&gt; buf.push(func(*sval, *oval)), (Some(sval), None) =&gt; { buf.push(*sval); buf.extend(self_iter); break; } (None, Some(oval)) =&gt; { buf.push(*oval); buf.extend(other_iter); break; } (None, None) =&gt; break, } } Alphabetic::new(buf) } //exposed functions from the inner vec pub fn len(&amp;self) -&gt; usize { self.0.len() } pub fn is_empty(&amp;self) -&gt; bool { self.0.is_empty() } pub fn iter(&amp;self) -&gt; std::slice::Iter&lt;Letter&gt; { self.0.iter() } } impl Display for Alphabetic { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { write!(f, &quot;{}&quot;, { let chars = String::from_utf8(self.iter().map(Letter::to_utf8).collect()); chars.map_err(|_e| fmt::Error)? }) } } //copy-paste boilerplate land ///Addition and subtraction on `Alphabetic`s works by adding/subtracting each /// pair of `Letter`s, until we reach the end of either string, at which point /// the remainder of the longer string will be appended. impl Add&lt;Alphabetic&gt; for Alphabetic { type Output = Self; fn add(self, other: Self) -&gt; Self { self.pairwise_map(&amp;other, Box::new(|x, y| x + y)) } } impl Add&lt;Letter&gt; for Alphabetic { type Output = Self; fn add(self, other: Letter) -&gt; Self { Alphabetic::new(self.iter().map(|x| *x + other).collect()) } } impl Add&lt;i8&gt; for Alphabetic { type Output = Self; fn add(self, other: i8) -&gt; Self { Alphabetic::new(self.iter().map(|x| *x + other).collect()) } } impl Sub&lt;Alphabetic&gt; for Alphabetic { type Output = Self; fn sub(self, other: Self) -&gt; Self { self.pairwise_map(&amp;other, Box::new(|x, y| x - y)) } } impl Sub&lt;Letter&gt; for Alphabetic { type Output = Self; fn sub(self, other: Letter) -&gt; Self { Alphabetic::new(self.iter().map(|x| *x - other).collect()) } } impl Sub&lt;i8&gt; for Alphabetic { type Output = Self; fn sub(self, other: i8) -&gt; Self { Alphabetic::new(self.iter().map(|x| *x - other).collect()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_char_display() { let mut letter = Letter::try_from_char('U').unwrap(); //display property works properly assert_eq!(format!(&quot;{}&quot;, letter), &quot;U&quot;); letter = Letter::new(6, Case::Lower); //initialising letters from their values works properly assert_eq!(format!(&quot;{}&quot;, letter), &quot;g&quot;); } #[test] fn test_char_operators() { let letter1 = Letter::new(8, Case::Lower); let letter2 = Letter::from_signed(-16, Case::Lower); assert_eq!(format!(&quot;{}&quot;, letter1 + letter2), &quot;s&quot;); assert_eq!(format!(&quot;{}&quot;, letter1 - letter2), &quot;y&quot;); assert!(letter2 &gt; letter1); assert!(letter2 != letter1); } #[test] fn test_alphabetic_display() { let alpha = Alphabetic::try_from_str(&quot;hello&quot;).unwrap(); //display property works properly assert_eq!(format!(&quot;{}&quot;, alpha), &quot;hello&quot;); let beta = Alphabetic::try_from_str(&quot;helloり&quot;); //try_from_str correctly does not accept non-alphabetic chars assert_eq!(beta, None); } #[test] fn test_alphabetic_addition() { let alpha = Alphabetic::try_from_str(&quot;hello&quot;).unwrap(); let beta = Alphabetic::try_from_str(&quot;bbbbb&quot;).unwrap(); assert_eq!((alpha + beta).to_string(), &quot;ifmmp&quot;); let long = Alphabetic::try_from_str(&quot;longabcdefgh&quot;).unwrap(); let short = Alphabetic::try_from_str(&quot;short&quot;).unwrap(); //strings of different lengths can be added, commutatively assert_eq!((long.clone() + short.clone()).to_string(), &quot;dvbxtbcdefgh&quot;); assert_eq!((short.clone() + long.clone()).to_string(), &quot;dvbxtbcdefgh&quot;); //letter can be added to alphabetic assert_eq!( (Alphabetic::try_from_str(&quot;bbbbbb&quot;).unwrap() + Letter::try_from_char('b').unwrap()) .to_string(), &quot;cccccc&quot; ); } #[test] fn test_empty_values() { let a = Alphabetic::try_from_str(&quot;&quot;).unwrap(); let b = Alphabetic::from_str_filtered(&quot;&quot;); let c = Alphabetic::new(vec![]); assert_eq!(a.to_string(), &quot;&quot;); assert_eq!(b.to_string(), &quot;&quot;); assert_eq!(c.to_string(), &quot;&quot;); } } </code></pre> <h1><code>frequency.rs</code></h1> <pre class="lang-rust prettyprint-override"><code>///Provides utilities relating to frequency analysis, to be used by cipher /// modules. use crate::alphabetic::{self, Alphabetic, Case, Letter}; //https://en.wikipedia.org/wiki/Letter_frequency //relative frequencies of letters in the english language, in alphabet order pub const ENGLISH_FREQUENCIES: [f64; alphabetic::ALPHABET_SIZE] = [ 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074, ]; ///Returns a `Vec` of relative frequencies of each `Letter` in the string. pub fn frequencies(string: &amp;Alphabetic) -&gt; Vec&lt;f64&gt; { let mut counts = vec![0usize; alphabetic::ALPHABET_SIZE]; string.iter().for_each(|x| { counts[x.value as usize] += 1; }); let sum = counts.iter().sum::&lt;usize&gt;(); if sum == 0 { return vec![0f64; alphabetic::ALPHABET_SIZE]; } counts.into_iter().map(|x| x as f64 / sum as f64).collect() } ///Returns the `Letter` which occurs most frequently in the given string. ///# Panics ///There are 2 `unwrap`s in this function. One of them /// unwraps the result of a `std::slice::Iter::max_by()`, /// which yields `None` only when the iter is empty Since we /// use the constant iter `(0..26)`, this is not a concern. /// The other unwrap is on the result of an /// `f64::partial_cmp()`, which would fail if one of the /// `f64`s is an unusual value, like `NaN`. We obtain these /// values from division and check for division by zero, so /// there *should* be no way for this panic to occur. pub fn most_frequent_letter(string: &amp;Alphabetic) -&gt; Letter { let freqs = frequencies(string); Letter::new( (0..26) .max_by(|x, y| freqs[*x].partial_cmp(&amp;freqs[*y]).unwrap()) .unwrap() as u8, Case::Lower, ) } ///Returns a `Vec` containing the `Letters` representing `a` through `z`, in /// order from most frequent to least frequent in the given string. pub fn letters_by_frequency(string: &amp;Alphabetic) -&gt; Vec&lt;Letter&gt; { let freqs = frequencies(string); let mut indices: Vec&lt;usize&gt; = (0..26).collect(); indices.sort_by(|x, y| freqs[*y].partial_cmp(&amp;freqs[*x]).unwrap()); indices .into_iter() .map(|x| Letter::new(x as u8, Case::Lower)) .collect() } ///Returns the mean squared difference between two `f64` slices. The mean /// squared difference is only defined on two slices of the same length (if the /// slices are not the same length, this function returns `None`). It is defined /// as the sum of the squares of the differences between each pair of items (one /// from each slice), divided by the length of the slices. pub fn mean_squared_difference(freqs1: &amp;[f64], freqs2: &amp;[f64]) -&gt; Option&lt;f64&gt; { let length = match (freqs1.len(), freqs2.len()) { (0, _) | (_, 0) =&gt; { return None; } (x, y) if x == y =&gt; x, _ =&gt; return None, }; let mut sum = 0f64; for i in 0..length { sum += (freqs1[i] - freqs2[i]).powi(2) } Some(sum) } #[cfg(test)] mod tests { use super::*; #[test] fn test_frequency() { let string = Alphabetic::try_from_str(&quot;hello&quot;).unwrap(); assert_eq!( most_frequent_letter(&amp;string), Letter::try_from_char('l').unwrap() ); let freqs: Vec&lt;f64&gt; = vec![ 0.0, 0.0, 0.0, 0.0, 0.2, 0.0, 0.0, 0.2, 0.0, 0.0, 0.0, 0.4, 0.0, 0.0, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ]; assert_eq!(frequencies(&amp;string), freqs); let letters = letters_by_frequency(&amp;string); assert_eq!(letters[0], Letter::try_from_char('l').unwrap()); assert_eq!(letters[1], Letter::try_from_char('e').unwrap()); assert_eq!(letters[2], Letter::try_from_char('h').unwrap()); assert_eq!(letters[3], Letter::try_from_char('o').unwrap()); } } </code></pre> <h1><code>caesar.rs</code></h1> <pre class="lang-rust prettyprint-override"><code>///Provides functions for encrypting and cracking Caesar ciphers. use crate::{ alphabetic::{self, Alphabetic, Letter}, frequency::{frequencies, mean_squared_difference, most_frequent_letter, ENGLISH_FREQUENCIES}, }; ///Shift the given string by the given number of places. pub fn shift(string: &amp;Alphabetic, num_places: i8) -&gt; Alphabetic { string.clone() + num_places } ///Iterator over all of the possible shifts of a given string. pub struct GenShifts(Alphabetic, i8); impl GenShifts { fn new(string: Alphabetic) -&gt; GenShifts { GenShifts(string, 0) } } impl Iterator for GenShifts { type Item = Alphabetic; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { if self.1 == alphabetic::ALPHABET_SIZE as i8 { return None; } self.1 += 1; Some(shift(&amp;self.0, self.1 - 1)) } } pub fn gen_shifts(string: Alphabetic) -&gt; GenShifts { GenShifts::new(string) } ///Crack an encrypted string by shifting the string such /// that the most common character therein is mapped to 'e' /// (the most common letter in English) pub fn crack_match_maxima(string: &amp;Alphabetic) -&gt; Alphabetic { const MOST_FREQUENT_ENGLISH: Letter = Letter::try_from_char('e').unwrap(); string.clone() - most_frequent_letter(&amp;string) + MOST_FREQUENT_ENGLISH } ///Crack an encrypted string by choosing the shift which /// minimises the MSE (mean squared error) between the /// observed letter frequencies and the expected letter /// frequencies (based on a large sample of English text) pub fn crack_minimise_mse(string: &amp;Alphabetic) -&gt; Alphabetic { gen_shifts(string.clone()) .min_by(|x, y| { let mse = |x| mean_squared_difference(&amp;frequencies(x), &amp;ENGLISH_FREQUENCIES).unwrap(); mse(x).partial_cmp(&amp;mse(y)).unwrap() }) .unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn test_shift() { assert_eq!( shift(&amp;Alphabetic::try_from_str(&quot;abcdef&quot;).unwrap(), 1).to_string(), &quot;bcdefg&quot; ); let mut shifts = gen_shifts(Alphabetic::try_from_str(&quot;abcdef&quot;).unwrap()); assert_eq!(shifts.next().unwrap().to_string(), &quot;abcdef&quot;); assert_eq!(shifts.next().unwrap().to_string(), &quot;bcdefg&quot;); assert_eq!(shifts.next().unwrap().to_string(), &quot;cdefgh&quot;); assert_eq!(shifts.next().unwrap().to_string(), &quot;defghi&quot;); } #[test] fn test_crack() { let original = Alphabetic::from_str_filtered( &quot;If it were done when 'tis done, then 'twere well It were done quickly: if the assassination Could trammel up the consequence, and catch With his surcease success; that but this blow Might be the be-all and the end-all here, But here, upon this bank and shoal of time, We'ld jump the life to come. But in these cases We still have judgment here; that we but teach Bloody instructions, which, being taught, return To plague the inventor: this even-handed justice Commends the ingredients of our poison'd chalice To our own lips. He's here in double trust; First, as I am his kinsman and his subject, Strong both against the deed; then, as his host, Who should against his murderer shut the door, Not bear the knife myself. Besides, this Duncan Hath borne his faculties so meek, hath been So clear in his great office, that his virtues Will plead like angels, trumpet-tongued, against The deep damnation of his taking-off; And pity, like a naked new-born babe, Striding the blast, or heaven's cherubim, horsed Upon the sightless couriers of the air, Shall blow the horrid deed in every eye, That tears shall drown the wind. I have no spur To prick the sides of my intent, but only Vaulting ambition, which o'erleaps itself And falls on the other.&quot;, ); let shifted = shift(&amp;original, 6); assert_eq!(crack_match_maxima(&amp;shifted), original); assert_eq!(crack_minimise_mse(&amp;shifted), original); } } </code></pre>
[]
[ { "body": "<p>Overall, your implementation looks good! Your code is well documented, it has unit tests and the use of the standard traits is also great.</p>\n<p><strong>Here are some of my suggestions:</strong></p>\n<p>The <code>value</code> field of <code>Letter</code> must be in the range 0-25, I would either add an assertion\nin the <code>new</code> method of <code>Letter</code> that panics if the range is violated, or make it return a <code>Result</code> and handle the error.</p>\n<hr />\n<p>Implementing the above will allow you to move the unsafe from <code>pub unsafe fn to_char_unchecked(&amp;self) -&gt; char</code> into the method body as it will always be safe to convert. It's a good practice to avoid <code>unsafe</code> in public APIs whenever it's possible by creating a safe abstraction over the unsafe code.</p>\n<hr />\n<p><code>value</code> and <code>case</code> should not be public. You can change them to <code>pub(crate)</code>.</p>\n<hr />\n<p>Remove the need for unstable features.</p>\n<p><code>const MOST_FREQUENT_ENGLISH: Letter = Letter::try_from_char('e').unwrap();</code></p>\n<p>can be replaced with</p>\n<pre><code>const MOST_FREQUENT_ENGLISH: Letter = Letter {\n value: 4,\n case: Case::Lower,\n };\n</code></pre>\n<p>and <code>#![feature(const_option)]</code> can be removed. The const variable can also be taken out of the method.</p>\n<hr />\n<p><code>fn combined_case(case1: Case, case2: Case) -&gt; Case</code> can be implemented using the <code>Add</code> trait as you have done for Letter.</p>\n<hr />\n<p>Use <code>filter_map()</code> instead of <code>filter()</code> and <code>map()</code>.</p>\n<pre><code>Alphabetic::new(\n string\n .bytes()\n .filter(|x| x.is_ascii_alphabetic())\n .map(|x| Letter::try_from_utf8(x).unwrap())\n .collect(),\n )\n</code></pre>\n<p>can be replaced with</p>\n<pre><code>Alphabetic::new(\n string\n .bytes()\n .filter_map(Letter::try_from_utf8)\n .collect(),\n )\n</code></pre>\n<hr />\n<p><code>assert!(letter2 != letter1);</code> can be changed to <code>assert_ne!(letter2, letter1);</code></p>\n<hr />\n<p>Avoid dynamic dispatch.\nThere is no need to use dynamic dispatch in this method</p>\n<pre><code> pub fn pairwise_map(\n &amp;self,\n other: &amp;Self,\n func: Box&lt;dyn Fn(Letter, Letter) -&gt; Letter&gt;,\n ) -&gt; Alphabetic \n</code></pre>\n<p>It can be changed using generic type:</p>\n<pre><code>pub fn pairwise_map&lt;Func&gt;(&amp;self, other: &amp;Self, func: Func) -&gt; Alphabetic\n where\n Func: Fn(Letter, Letter) -&gt; Letter,\n</code></pre>\n<p>Or an <code>fn</code> pointer:</p>\n<pre><code> pub fn pairwise_map(\n &amp;self,\n other: &amp;Self,\n func: fn(Letter, Letter) -&gt; Letter,\n ) -&gt; Alphabetic {\n</code></pre>\n<hr />\n<p>This:</p>\n<pre><code>let length = match (freqs1.len(), freqs2.len()) {\n (0, _) | (_, 0) =&gt; {\n return None;\n }\n (x, y) if x == y =&gt; x,\n _ =&gt; return None,\n };\n</code></pre>\n<p>can be simplified</p>\n<pre><code>let length = match (freqs1.len(), freqs2.len()) {\n (x, y) if x == y &amp;&amp; x != 0 =&gt; x,\n _ =&gt; return None,\n };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T18:37:07.167", "Id": "518785", "Score": "2", "body": "Thank you for the useful pointers (pun not intended)! I honestly didn't even know about `pub(crate)` or `filter_map`, and I'm not sure why I went for a box for the function. My only question is about the last part with the `match` statement - you seem to have written the same thing twice rather than changing it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T09:46:45.577", "Id": "518826", "Score": "1", "body": "Sorry, I've changed it now :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T16:34:43.510", "Id": "262808", "ParentId": "262701", "Score": "4" } } ]
{ "AcceptedAnswerId": "262808", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T22:00:21.940", "Id": "262701", "Score": "5", "Tags": [ "beginner", "rust", "caesar-cipher" ], "Title": "Caesar cipher/beginnings of a crypto library in Rust" }
262701
<p>In learning haskell, I'm writing a fuzzy menu. At the moment, my executable reads in a 'dictionary' from stdin, and ranks each word according to how well it fuzzily matches a search pattern given in the first CLI arg. The idea of the fuzzy matching algorithm is to split a pattern by its delimiters, and then match each character with a prefix of a token, accumulating a score to represent the quality of the match.</p> <p>My main module looks like this:</p> <pre><code>module Main where import Data.List import Fuzzy import System.Environment main :: IO () main = do contents &lt;- getContents let dict = lines contents args &lt;- getArgs let pattern = splitWord (head args) let scored = map (\x -&gt; (score (x, pattern), x)) dict print (sort scored) </code></pre> <p>I'm not sure whether or not I'm misusing the do block and/or some I/O primitives here: overall, I think it could be better but I don't know how to change it.</p> <p>The Util module looks like this:</p> <pre><code>module Util ( splitWord , boolToFloat , nextChar ) where splitWord :: String -&gt; [String] splitWord (l : '_' : r ) = splitWord ([l, '-'] ++ r) splitWord (l : '.' : r ) = splitWord ([l, '-'] ++ r) splitWord (l : ':' : r ) = splitWord ([l, '-'] ++ r) splitWord (l : '-' : r ) = [[l]] ++ splitWord r splitWord (c : []) = [[c]] splitWord [] = [] splitWord s = do let rest = splitWord (tail s) let first = (head s) : (head rest) return first ++ tail rest boolToFloat :: Bool -&gt; Float boolToFloat True = 1.0 boolToFloat False = 0.0 nextChar :: [String] -&gt; [String] nextChar s = case tail (head s) of [] -&gt; tail s n -&gt; [n] ++ tail s </code></pre> <p>Especially in <code>splitWord</code>, I think the code here is somewhat repetitive, and again I don't really know how to make it simpler.</p> <p>And finally, the Fuzzy module is as follows:</p> <pre><code>module Fuzzy ( score ) where import Util score :: (String, [String]) -&gt; Float score ([], _ ) = 0 score (_ , []) = 0 score (s , t ) = boolToFloat (head s == head (head t)) + max (score (tail s, t) * 0.8) (score (tail s, nextChar t)) </code></pre> <p>This module (and function) is the one I have the least concerns about - most of the problems in my code (as I perceive them) are about IO and redundancy in splitWord's pattern matching. Thanks for any advice!</p>
[]
[ { "body": "<ol>\n<li>I think your use of do notation in the splitWord function is bad and I think your code is even correct by accident. Let me add parentheses to highlight it:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWord s = do\n let rest = splitWord (tail s)\n let first = (head s) : (head rest)\n (return first) ++ tail rest\n</code></pre>\n<p>Most people, including me, will assume the last return statement in a do block to be applied last, like this:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWord s = do\n let rest = splitWord (tail s)\n let first = (head s) : (head rest)\n return (first ++ tail rest)\n</code></pre>\n<p>Which is incorrect in this case! I would advise to just not use do notation here:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWord s =\n let rest = splitWord (tail s)\n first = (head s) : (head rest)\n in [first] ++ tail rest\n</code></pre>\n<ol start=\"2\">\n<li>Use pattern matching instead of <code>head</code> and <code>tail</code>:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code> (arg:_) &lt;- getArgs\n let pattern = splitWord arg\n</code></pre>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWord (l:r) =\n let (l':r') = splitWord r\n first = l : l'\n in [first] ++ r'\n</code></pre>\n<pre class=\"lang-hs prettyprint-override\"><code>nextChar :: [String] -&gt; [String]\nnextChar ((_:[]):s) = s\nnextChar ((_:n):s) = [n] ++ s\n</code></pre>\n<pre class=\"lang-hs prettyprint-override\"><code>score ((hs:s, t@((hht:_):_)) = boolToFloat (hs == hht)\n + max (score (s, t) * 0.8) (score (s, nextChar t))\n</code></pre>\n<p>This also makes it more clear to me that your <code>score</code> function is partial: what should the result of <code>score (&quot;x&quot;, [&quot;&quot;])</code> be?</p>\n<ol start=\"3\">\n<li>It is also in general more common to use curried functions instead of tuples as arguments:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>score :: String -&gt; [String] -&gt; Float\nscore [] _ = 0\nscore _ [] = 0\n\nscore (hs:s) t@((hht:_):_) = boolToFloat (hs == hht)\n + max (score s t * 0.8) (score s (nextChar t))\n</code></pre>\n<ol start=\"4\">\n<li>You can make the <code>main</code> function a bit nicer with <code>fmap</code>:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>main :: IO ()\nmain = do\n dict &lt;- fmap lines getContents\n\n args &lt;- fmap (splitWord . head) getArgs\n\n let scored = map (\\x -&gt; (score (x, pattern), x)) dict\n print (sort scored)\n</code></pre>\n<p>But it looks decent without that too, so don't worry to much about that.</p>\n<ol start=\"5\">\n<li>You can deal with the repetitiveness in <code>splitWord</code> by using guards and the <code>elem</code> function, change:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWord (l : '_' : r ) = splitWord ([l, '-'] ++ r)\nsplitWord (l : '.' : r ) = splitWord ([l, '-'] ++ r)\nsplitWord (l : ':' : r ) = splitWord ([l, '-'] ++ r)\nsplitWord (l : '-' : r ) = [[l]] ++ splitWord r\n</code></pre>\n<p>to:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWord (l : x : r )\n | x `elem` &quot;_.:-&quot; = [l] : splitWord r\n</code></pre>\n<p>Note that the <code>elem</code> function can be slower than pattern matching, so alternatively you can split out the pattern matching in its own function:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>isSep :: Char -&gt; Bool\nisSep '_' = True\nisSep '.' = True\nisSep ':' = True\nisSep '-' = True\nisSep _ = False\n\n...\n\nsplitWord (l : x : r )\n | isSep x = [l] : r\n</code></pre>\n<ol start=\"6\">\n<li>Use library functions like <code>break</code> in <code>splitWord</code>:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWord :: String -&gt; [String]\nsplitWord s = case break isSep word of\n ([], x:r) -&gt; x : splitWord r -- *\n (l, []) -&gt; l\n (l, _:r) -&gt; l : splitWord r\n</code></pre>\n<p>* This first case is a bit strange and maybe you don't need it, but I think it is needed to make this function match your splitWord function exactly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T10:04:25.570", "Id": "262715", "ParentId": "262704", "Score": "2" } } ]
{ "AcceptedAnswerId": "262715", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T01:19:19.463", "Id": "262704", "Score": "1", "Tags": [ "haskell" ], "Title": "Fuzzy Finding in Haskell" }
262704
<p>Is it good practice to create many subtypes which are all exactly the same just for more descriptive class names? I did this but then I realised all my subtypes were redundant, and it seemed kind of like duplication. I deleted them all. Now I just use one type, and I tend to be able to write more reusable code and end up with far less code for the same functionality. The deleted subtypes have their own database table each, for data querying purposes and also categorisation. Then If some subtypes do differ in the future, I can extend the type I currently use for all my subtypes. What is the best strategy, lots of redundant classes which are all the same, just for more descriptive class names, or one type, then extend it only if needed?</p> <p>Example - Reuse this:</p> <pre><code>class VeganItemDomainEntity extends DomainEntity&lt;VeganItemDomainEntity, int?&gt; { const factory VeganItemDomainEntity( {int? id, String? name, String? companyName, String? description}) = _VeganItemDomainEntity; } </code></pre> <p>Or make many classes the same as this with descriptive names:</p> <pre><code>class VeganGroceryItemDomainEntity extends DomainEntity&lt;VeganGroceryItemDomainEntity, int?&gt; { const factory VeganGroceryItemDomainEntity( {int? id, String? name, String? companyName, String? description}) = _VeganGroceryItemDomainEntity; } class VeganRestaurantMenuItemDomainEntity extends DomainEntity&lt;VeganRestaurantMenuItemDomainEntity, int?&gt; { const factory VeganRestaurantMenuItemDomainEntity( {int? id, String? name, String? companyName, String? description}) = _VeganRestaurantMenuItemDomainEntity; }... </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T06:35:21.383", "Id": "518518", "Score": "1", "body": "*create many subtypes which are all exactly the same just for more descriptive class names?* NO. You and I are the same type but have different **variable names**. We have different property values, not different properties per se." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T03:05:26.040", "Id": "262705", "Score": "0", "Tags": [ "object-oriented", "design-patterns", "classes" ], "Title": "Create Many Subtypes which are all exactly the same VS use just one type" }
262705
<p>Dear coding black belts,</p> <p>My code is working but seems clunky.</p> <ul> <li>Take a random number from 1 to 99,999</li> <li>Display it in 3D in a modified version of the <a href="https://en.wikipedia.org/wiki/The_Ciphers_of_the_Monks" rel="nofollow noreferrer">Cistercian numerals</a> from 13th century monks (adding one sagittal dimension)</li> <li>Ask for user input and check if the answer is correct.</li> </ul> <p>I breakdown the random number to its digits components in a list:</p> <pre><code>Cistercian = randrange(1, 99999) List_digits = [0, 0, 0] + [int(x) for x in str(Cistercian)] units = List_digits[-1] tens = List_digits[-2] hundreds = List_digits[-3] thousands = List_digits[-4] man = List_digits[-5] </code></pre> <p>(&quot;man&quot; means &quot;10,000&quot; in Japanese)</p> <p>I predefined 14 points in the 3d space:</p> <pre><code>P1 = (-40, 0, 120) P2 = (0, 0, 120) P3 = (40, 0, 120) P4 = (-40, 0, 80) P5 = (0, 0, 80) P6 = (40, 0, 80) P7 = (-40, 0, 40) P8 = (0, 0, 40) P9 = (40, 0, 40) P10 = (-40, 0, 0) P11 = (0, 0, 0) P12 = (40, 0, 0) P13 = (0, -40, 80) P14 = (0, -40, 40) </code></pre> <p>Then I map each digit as connections between the points above:</p> <pre><code>if thousands == 1: x_values1k = [P11[0], P10[0]] y_values1k = [P11[1], P10[1]] z_values1k = [P11[2], P10[2]] plt.plot(x_values1k, y_values1k, z_values1k, color='k', lw=3) elif thousands == 2: x_values2k = [P8[0], P7[0]] y_values2k = [P8[1], P7[1]] z_values2k = [P8[2], P7[2]] plt.plot(x_values2k, y_values2k, z_values2k, color='k', lw=3) </code></pre> <p>It's used 50 times. I'd like to define a function that would only require the input of the coordinates once instead of re-writing the same 4 lines for each step. I'm struggling with how to manage that. I tried defining a function, but I was running into errors with the <code>plt.plot</code> aspect, where the x_values, z_values, y_values are different each of the 50 times.</p> <p>for reference, lines 168 to 506, full code below <a href="https://github.com/jelaludo/Cistercian3D/blob/main/main.py" rel="nofollow noreferrer">https://github.com/jelaludo/Cistercian3D/blob/main/main.py</a></p> <p>Example of output:<br /> <a href="https://i.stack.imgur.com/PywhU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PywhU.png" alt="3d Cistercian numbers with Matplotlib" /></a></p> <p>Here's the full code:</p> <pre><code># Adding a sagittal dimension to the 13th Century Cistercian monks numerals # to bring the upper limit from 9,999 to 99,999. import numpy as np # import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from random import randrange # Cistercian = int(input(&quot;Please Input number from 1 to 99,999: &quot;)) Cistercian = randrange(1, 99999) # print(f&quot;{Cistercian:,}&quot;) List_digits = [0, 0, 0] + [int(x) for x in str(Cistercian)] # Concatenating [0,0,0] for &quot;padding&quot; units = List_digits[-1] tens = List_digits[-2] hundreds = List_digits[-3] thousands = List_digits[-4] man = List_digits[-5] #&quot;man&quot; is 10,000 in Japanese # print(man, &quot; = Ten Thousands&quot;) # print(thousands, &quot; = Thousands&quot;) # print(hundreds, &quot; = Hundreds&quot;) # print(tens, &quot; = Tens&quot;) # print(units, &quot; = Units&quot;) # Define the planes and that it is 3D fig = plt.figure() ax = Axes3D(fig) # set initial Elevation and Azimuth view for the 3d graph ax.view_init(15, -60) # Set size for xyz space ax.set_xlim3d(-150, 150) ax.set_ylim3d(-150, 150) ax.set_zlim3d(-150, 150) # ax = fig.add_subplot(111, projection='3d') # Structure of the matrix to represent Cistercian numbers, e.g. 11 to 2 is a straight line. # 1 2 3 # 4 5 6 # 7 8 9 # 10 11 12 # + sagittal plane #13 at height #5 and #14 at height #8 P1 = (-40, 0, 120) P2 = (0, 0, 120) P3 = (40, 0, 120) P4 = (-40, 0, 80) P5 = (0, 0, 80) P6 = (40, 0, 80) P7 = (-40, 0, 40) P8 = (0, 0, 40) P9 = (40, 0, 40) P10 = (-40, 0, 0) P11 = (0, 0, 0) P12 = (40, 0, 0) P13 = (0, -40, 80) P14 = (0, -40, 40) # Center Points def p11(): ax.scatter(0, 0, 0, color='k', lw=1) def p8(): ax.scatter(0, 0, 40, color='k', lw=1) def p5(): ax.scatter(0, 0, 80, color='k', lw=1) def p2(): ax.scatter(0, 0, 120, color='k', lw=1) p11() p8() p5() p2() # Sagittal Plane Points def p13(): ax.scatter(0, -40, 80, color='steelblue') def p14(): ax.scatter(0, -40, 40, color='steelblue') p13() p14() # Thousands Points def p7(): ax.scatter(-40, 0, 40, color='slategrey', lw=1) def p10(): ax.scatter(-40, 0, 0, color='slategrey', lw=1) p7() p10() # Hundreds Points def p9(): ax.scatter(40, 0, 40, color='seagreen', lw=1) def p12(): ax.scatter(40, 0, 0, color='seagreen', lw=1) p9() p12() # Tens Points def p1(): ax.scatter(-40, 0, 120, color='darkgoldenrod', lw=1) def p4(): ax.scatter(-40, 0, 80, color='darkgoldenrod', lw=1) p1() p4() # Units Points def p3(): ax.scatter(40, 0, 120, color='darkcyan', lw=1) def p6(): ax.scatter(40, 0, 80, color='darkcyan', lw=1) p3() p6() p11() p10() # Draw center column x_valuesCenter = [P11[0], P2[0]] y_valuesCenter = [P11[1], P2[1]] z_valuesCenter = [P11[2], P2[2]] plt.plot(x_valuesCenter, y_valuesCenter, z_valuesCenter, color='k', lw=3) userguess = Cistercian # def ContinueTillFailure(): # while userguess==Cistercian: if man == 1: x_values1m = [P8[0], P14[0]] y_values1m = [P8[1], P14[1]] z_values1m = [P8[2], P14[2]] plt.plot(x_values1m, y_values1m, z_values1m, color='k', lw=3) elif man == 2: x_values2m = [P5[0], P13[0]] y_values2m = [P5[1], P13[1]] z_values2m = [P5[2], P13[2]] plt.plot(x_values2m, y_values2m, z_values2m, color='k', lw=3) elif man == 3: x_values3m = [P13[0], P8[0]] y_values3m = [P13[1], P8[1]] z_values3m = [P13[2], P8[2]] plt.plot(x_values3m, y_values3m, z_values3m, color='k', lw=3) elif man == 4: x_values4m = [P5[0], P14[0]] y_values4m = [P5[1], P14[1]] z_values4m = [P5[2], P14[2]] plt.plot(x_values4m, y_values4m, z_values4m, color='k', lw=3) elif man == 5: x_values5m = [P5[0], P14[0]] y_values5m = [P5[1], P14[1]] z_values5m = [P5[2], P14[2]] plt.plot(x_values5m, y_values5m, z_values5m, color='k', lw=3) x_values5mb = [P14[0], P8[0]] y_values5mb = [P14[1], P8[1]] z_values5mb = [P14[2], P8[2]] plt.plot(x_values5mb, y_values5mb, z_values5mb, color='k', lw=3) elif man == 6: x_values6m = [P13[0], P14[0]] y_values6m = [P13[1], P14[1]] z_values6m = [P13[2], P14[2]] plt.plot(x_values6m, y_values6m, z_values6m, color='k', lw=3) elif man == 7: x_values7m = [P13[0], P14[0]] y_values7m = [P13[1], P14[1]] z_values7m = [P13[2], P14[2]] plt.plot(x_values7m, y_values7m, z_values7m, color='k', lw=3) x_values7mb = [P14[0], P8[0]] y_values7mb = [P14[1], P8[1]] z_values7mb = [P14[2], P8[2]] plt.plot(x_values7mb, y_values7mb, z_values7mb, color='k', lw=3) elif man == 8: x_values8m = [P13[0], P14[0]] y_values8m = [P13[1], P14[1]] z_values8m = [P13[2], P14[2]] plt.plot(x_values8m, y_values8m, z_values8m, color='k', lw=3) x_values8mb = [P5[0], P13[0]] y_values8mb = [P5[1], P13[1]] z_values8mb = [P5[2], P13[2]] plt.plot(x_values8mb, y_values8mb, z_values8mb, color='k', lw=3) elif man == 9: x_values9m = [P13[0], P14[0]] y_values9m = [P13[1], P14[1]] z_values9m = [P13[2], P14[2]] plt.plot(x_values9m, y_values9m, z_values9m, color='k', lw=3) x_values9mb = [P5[0], P13[0]] y_values9mb = [P5[1], P13[1]] z_values9mb = [P5[2], P13[2]] plt.plot(x_values9mb, y_values9mb, z_values9mb, color='k', lw=3) x_values9mc = [P14[0], P8[0]] y_values9mc = [P14[1], P8[1]] z_values9mc = [P14[2], P8[2]] plt.plot(x_values9mc, y_values9mc, z_values9mc, color='k', lw=3) else: p13() # ## Draw corresponding Cistercian coordinates for thousands if thousands == 1: x_values1k = [P11[0], P10[0]] y_values1k = [P11[1], P10[1]] z_values1k = [P11[2], P10[2]] plt.plot(x_values1k, y_values1k, z_values1k, color='k', lw=3) elif thousands == 2: x_values2k = [P8[0], P7[0]] y_values2k = [P8[1], P7[1]] z_values2k = [P8[2], P7[2]] plt.plot(x_values2k, y_values2k, z_values2k, color='k', lw=3) elif thousands == 3: x_values3k = [P11[0], P7[0]] y_values3k = [P11[1], P7[1]] z_values3k = [P11[2], P7[2]] plt.plot(x_values3k, y_values3k, z_values3k, color='k', lw=3) elif thousands == 4: x_values4k = [P8[0], P10[0]] y_values4k = [P8[1], P10[1]] z_values4k = [P8[2], P10[2]] plt.plot(x_values4k, y_values4k, z_values4k, color='k', lw=3) elif thousands == 5: x_values5k = [P8[0], P10[0]] y_values5k = [P8[1], P10[1]] z_values5k = [P8[2], P10[2]] plt.plot(x_values5k, y_values5k, z_values5k, color='k', lw=3) x_values5kb = [P11[0], P10[0]] y_values5kb = [P11[1], P10[1]] z_values5kb = [P11[2], P10[2]] plt.plot(x_values5kb, y_values5kb, z_values5kb, color='k', lw=3) elif thousands == 6: x_values6k = [P7[0], P10[0]] y_values6k = [P7[1], P10[1]] z_values6k = [P7[2], P10[2]] plt.plot(x_values6k, y_values6k, z_values6k, color='k', lw=3) elif thousands == 7: x_values7k = [P7[0], P10[0]] y_values7k = [P7[1], P10[1]] z_values7k = [P7[2], P10[2]] plt.plot(x_values7k, y_values7k, z_values7k, color='k', lw=3) x_values7kb = [P11[0], P10[0]] y_values7kb = [P11[1], P10[1]] z_values7kb = [P11[2], P10[2]] plt.plot(x_values7kb, y_values7kb, z_values7kb, color='k', lw=3) elif thousands == 8: x_values8k = [P7[0], P10[0]] y_values8k = [P7[1], P10[1]] z_values8k = [P7[2], P10[2]] plt.plot(x_values8k, y_values8k, z_values8k, color='k', lw=3) x_values8kb = [P7[0], P8[0]] y_values8kb = [P7[1], P8[1]] z_values8kb = [P7[2], P8[2]] plt.plot(x_values8kb, y_values8kb, z_values8kb, color='k', lw=3) elif thousands == 9: x_values9k = [P7[0], P10[0]] y_values9k = [P7[1], P10[1]] z_values9k = [P7[2], P10[2]] plt.plot(x_values9k, y_values9k, z_values9k, color='k', lw=3) x_values9kb = [P7[0], P8[0]] y_values9kb = [P7[1], P8[1]] z_values9kb = [P7[2], P8[2]] plt.plot(x_values9kb, y_values9kb, z_values9kb, color='k', lw=3) x_values9kc = [P10[0], P11[0]] y_values9kc = [P10[1], P11[1]] z_values9kc = [P10[2], P11[2]] plt.plot(x_values9kc, y_values9kc, z_values9kc, color='k', lw=3) else: p10() if hundreds == 1: x_values1c = [P11[0], P12[0]] y_values1c = [P11[1], P12[1]] z_values1c = [P11[2], P12[2]] plt.plot(x_values1c, y_values1c, z_values1c, color='k', lw=3) elif hundreds == 2: x_values2c = [P8[0], P9[0]] y_values2c = [P8[1], P9[1]] z_values2c = [P8[2], P9[2]] plt.plot(x_values2c, y_values2c, z_values2c, color='k', lw=3) elif hundreds == 3: x_values3c = [P11[0], P9[0]] y_values3c = [P11[1], P9[1]] z_values3c = [P11[2], P9[2]] plt.plot(x_values3c, y_values3c, z_values3c, color='k', lw=3) elif hundreds == 4: x_values4c = [P8[0], P12[0]] y_values4c = [P8[1], P12[1]] z_values4c = [P8[2], P12[2]] plt.plot(x_values4c, y_values4c, z_values4c, color='k', lw=3) elif hundreds == 5: x_values5c = [P8[0], P12[0]] y_values5c = [P8[1], P12[1]] z_values5c = [P8[2], P12[2]] plt.plot(x_values5c, y_values5c, z_values5c, color='k', lw=3) x_values5cb = [P11[0], P12[0]] y_values5cb = [P11[1], P12[1]] z_values5cb = [P11[2], P12[2]] plt.plot(x_values5cb, y_values5cb, z_values5cb, color='k', lw=3) elif hundreds == 6: x_values6c = [P9[0], P12[0]] y_values6c = [P9[1], P12[1]] z_values6c = [P9[2], P12[2]] plt.plot(x_values6c, y_values6c, z_values6c, color='k', lw=3) elif hundreds == 7: x_values7c = [P11[0], P12[0]] y_values7c = [P11[1], P12[1]] z_values7c = [P11[2], P12[2]] plt.plot(x_values7c, y_values7c, z_values7c, color='k', lw=3) x_values7cb = [P12[0], P9[0]] y_values7cb = [P12[1], P9[1]] z_values7cb = [P12[2], P9[2]] plt.plot(x_values7cb, y_values7cb, z_values7cb, color='k', lw=3) elif hundreds == 8: x_values8c = [P12[0], P9[0]] y_values8c = [P12[1], P9[1]] z_values8c = [P12[2], P9[2]] plt.plot(x_values8c, y_values8c, z_values8c, color='k', lw=3) x_values8cb = [P8[0], P9[0]] y_values8cb = [P8[1], P9[1]] z_values8cb = [P8[2], P9[2]] plt.plot(x_values8cb, y_values8cb, z_values8cb, color='k', lw=3) elif hundreds == 9: x_values9c = [P12[0], P9[0]] y_values9c = [P12[1], P9[1]] z_values9c = [P12[2], P9[2]] plt.plot(x_values9c, y_values9c, z_values9c, color='k', lw=3) x_values9cb = [P12[0], P11[0]] y_values9cb = [P12[1], P11[1]] z_values9cb = [P12[2], P11[2]] plt.plot(x_values9cb, y_values9cb, z_values9cb, color='k', lw=3) x_values9cc = [P9[0], P8[0]] y_values9cc = [P9[1], P8[1]] z_values9cc = [P9[2], P8[2]] plt.plot(x_values9cc, y_values9cc, z_values9cc, color='k', lw=3) else: p12() if tens == 1: x_values1t = [P1[0], P2[0]] y_values1t = [P1[1], P2[1]] z_values1t = [P1[2], P2[2]] plt.plot(x_values1t, y_values1t, z_values1t, color='k', lw=3) elif tens == 2: x_values2t = [P5[0], P4[0]] y_values2t = [P5[1], P4[1]] z_values2t = [P5[2], P4[2]] plt.plot(x_values2t, y_values2t, z_values2t, color='k', lw=3) elif tens == 3: x_values3t = [P2[0], P4[0]] y_values3t = [P2[1], P4[1]] z_values3t = [P2[2], P4[2]] plt.plot(x_values3t, y_values3t, z_values3t, color='k', lw=3) elif tens == 4: x_values4t = [P1[0], P5[0]] y_values4t = [P1[1], P5[1]] z_values4t = [P1[2], P5[2]] plt.plot(x_values4t, y_values4t, z_values4t, color='k', lw=3) elif tens == 5: x_values5t = [P1[0], P2[0]] y_values5t = [P1[1], P2[1]] z_values5t = [P1[2], P2[2]] plt.plot(x_values5t, y_values5t, z_values5t, color='k', lw=3) x_values5tb = [P1[0], P5[0]] y_values5tb = [P1[1], P5[1]] z_values5tb = [P1[2], P5[2]] plt.plot(x_values5tb, y_values5tb, z_values5tb, color='k', lw=3) elif tens == 6: x_values6t = [P1[0], P4[0]] y_values6t = [P1[1], P4[1]] z_values6t = [P1[2], P4[2]] plt.plot(x_values6t, y_values6t, z_values6t, color='k', lw=3) elif tens == 7: x_values7t = [P1[0], P2[0]] y_values7t = [P1[1], P2[1]] z_values7t = [P1[2], P2[2]] plt.plot(x_values7t, y_values7t, z_values7t, color='k', lw=3) x_values7tb = [P1[0], P4[0]] y_values7tb = [P1[1], P4[1]] z_values7tb = [P1[2], P4[2]] plt.plot(x_values7tb, y_values7tb, z_values7tb, color='k', lw=3) elif tens == 8: x_values8t = [P4[0], P1[0]] y_values8t = [P4[1], P1[1]] z_values8t = [P4[2], P1[2]] plt.plot(x_values8t, y_values8t, z_values8t, color='k', lw=3) x_values8tb = [P5[0], P4[0]] y_values8tb = [P5[1], P4[1]] z_values8tb = [P5[2], P4[2]] plt.plot(x_values8tb, y_values8tb, z_values8tb, color='k', lw=3) elif tens == 9: x_values9t = [P4[0], P1[0]] y_values9t = [P4[1], P1[1]] z_values9t = [P4[2], P1[2]] plt.plot(x_values9t, y_values9t, z_values9t, color='k', lw=3) x_values9tb = [P5[0], P4[0]] y_values9tb = [P5[1], P4[1]] z_values9tb = [P5[2], P4[2]] plt.plot(x_values9tb, y_values9tb, z_values9tb, color='k', lw=3) x_values9tc = [P1[0], P2[0]] y_values9tc = [P1[1], P2[1]] z_values9tc = [P1[2], P2[2]] plt.plot(x_values9tc, y_values9tc, z_values9tc, color='k', lw=3) else: p1() if units == 1: x_values1u = [P3[0], P2[0]] y_values1u = [P3[1], P2[1]] z_values1u = [P3[2], P2[2]] plt.plot(x_values1u, y_values1u, z_values1u, color='k', lw=3) elif units == 2: x_values2u = [P5[0], P6[0]] y_values2u = [P5[1], P6[1]] z_values2u = [P5[2], P6[2]] plt.plot(x_values2u, y_values2u, z_values2u, color='k', lw=3) elif units == 3: x_values3u = [P2[0], P6[0]] y_values3u = [P2[1], P6[1]] z_values3u = [P2[2], P6[2]] plt.plot(x_values3u, y_values3u, z_values3u, color='k', lw=3) elif units == 4: x_values4u = [P3[0], P5[0]] y_values4u = [P3[1], P5[1]] z_values4u = [P3[2], P5[2]] plt.plot(x_values4u, y_values4u, z_values4u, color='k', lw=3) elif units == 5: x_values5u = [P3[0], P2[0]] y_values5u = [P3[1], P2[1]] z_values5u = [P3[2], P2[2]] plt.plot(x_values5u, y_values5u, z_values5u, color='k', lw=3) x_values5ub = [P3[0], P5[0]] y_values5ub = [P3[1], P5[1]] z_values5ub = [P3[2], P5[2]] plt.plot(x_values5ub, y_values5ub, z_values5ub, color='k', lw=3) elif units == 6: x_values6u = [P3[0], P6[0]] y_values6u = [P3[1], P6[1]] z_values6u = [P3[2], P6[2]] plt.plot(x_values6u, y_values6u, z_values6u, color='k', lw=3) elif units == 7: x_values7u = [P2[0], P3[0]] y_values7u = [P2[1], P3[1]] z_values7u = [P2[2], P3[2]] plt.plot(x_values7u, y_values7u, z_values7u, color='k', lw=3) x_values7ub = [P3[0], P6[0]] y_values7ub = [P3[1], P6[1]] z_values7ub = [P3[2], P6[2]] plt.plot(x_values7ub, y_values7ub, z_values7ub, color='k', lw=3) elif units == 8: x_values8u = [P3[0], P6[0]] y_values8u = [P3[1], P6[1]] z_values8u = [P3[2], P6[2]] plt.plot(x_values8u, y_values8u, z_values8u, color='k', lw=3) x_values8ub = [P5[0], P6[0]] y_values8ub = [P5[1], P6[1]] z_values8ub = [P5[2], P6[2]] plt.plot(x_values8ub, y_values8ub, z_values8ub, color='k', lw=3) elif units == 9: x_values9u = [P3[0], P6[0]] y_values9u = [P3[1], P6[1]] z_values9u = [P3[2], P6[2]] plt.plot(x_values9u, y_values9u, z_values9u, color='k', lw=3) x_values9ub = [P5[0], P6[0]] y_values9ub = [P5[1], P6[1]] z_values9ub = [P5[2], P6[2]] plt.plot(x_values9ub, y_values9ub, z_values9ub, color='k', lw=3) x_values9uc = [P3[0], P2[0]] y_values9uc = [P3[1], P2[1]] z_values9uc = [P3[2], P2[2]] plt.plot(x_values9uc, y_values9uc, z_values9uc, color='k', lw=3) else: plt.show() # Center Points def p11(): ax.scatter(0, 0, 0, color='k', lw=1) def p8(): ax.scatter(0, 0, 40, color='k', lw=1) def p5(): ax.scatter(0, 0, 80, color='k', lw=1) def p2(): ax.scatter(0, 0, 120, color='k', lw=1) p11() p8() p5() p2() # Sagittal Plane Points def p13(): ax.scatter(0, -40, 80, color='steelblue') def p14(): ax.scatter(0, -40, 40, color='steelblue') p13() p14() # Thousands Points def p7(): ax.scatter(-40, 0, 40, color='slategrey', lw=1) def p10(): ax.scatter(-40, 0, 0, color='slategrey', lw=1) p7() p10() # Hundreds Points def p9(): ax.scatter(40, 0, 40, color='seagreen', lw=1) def p12(): ax.scatter(40, 0, 0, color='seagreen', lw=1) p9() p12() # Tens Points def p1(): ax.scatter(-40, 0, 120, color='darkgoldenrod', lw=1) def p4(): ax.scatter(-40, 0, 80, color='darkgoldenrod', lw=1) p1() p4() # Units Points def p3(): ax.scatter(40, 0, 120, color='darkcyan', lw=1) def p6(): ax.scatter(40, 0, 80, color='darkcyan', lw=1) p3() p6() # define two points, create lists of xyz values, and plot a line between them # ax.set_xlabel(&quot;X-Axis&quot;) # ax.set_ylabel(&quot;Y-Axis&quot;) # ax.set_zlabel(&quot;Z-Axis&quot;) # from pylab import rcParams # rcParams['figure.figsize'] = 20, 20 #hide axis values by setting them to blank [] ax.axes.xaxis.set_ticklabels([]) ax.axes.yaxis.set_ticklabels([]) ax.axes.zaxis.set_ticklabels([]) ax.set_title(&quot;3D Cistercian Numerals (Sagittal for 10k)&quot;) plt.show() plt.savefig('/Users/gfabr/Pictures/HalfFailedIfBlank%s.png') import tkinter as tk from tkinter import simpledialog ROOT = tk.Tk() ROOT.withdraw() # the input dialog prompt = simpledialog.askstring(title=&quot;Test&quot;, prompt=&quot;What's your best guess?:&quot;) # https://matplotlib.org/stable/gallery/color/named_colors.html # userguess = int(input(&quot;Best guess ? :&quot;)) userguess = int(prompt) print(f&quot;{userguess:,}&quot;) print(f&quot;{Cistercian:,}&quot;) from termcolor import colored if userguess==Cistercian: print(colored(&quot;correct&quot;, 'green')) else: print(colored(&quot;not quite&quot;, 'red')) # to do # simplify recurring code # option to re-show previous number # save graph to a png file # dynamically name the save file .png to include the number created (with %s ?) # increment, track how many you got right in a row </code></pre>
[]
[ { "body": "<h1>Avoid repeating yourself</h1>\n<p>There is <em>a lot</em> of code duplication in your program. This means you had to type in more than necessary, and the chance of bugs getting in your code has increased as well. Whenever you find you have lots of similar sections of code, find a way to reduce that.</p>\n<p>For example, when you define <code>P1</code>, <code>P2</code> and so on, it would be easy to make a typo and define the same variable twice for example. In any case, this looks like a job for a list:</p>\n<pre><code>P = [(-40, 0, 120),\n (0, 0, 120),\n ...\n (0, -40, 40)]\n</code></pre>\n<p>But even then it's easy to make mistakes when entering all those coordinates themselves. And how were they created in the first place? You could just write code to <em>generate</em> those numbers:</p>\n<pre><code>P = []\n\n# Add Cistercian numbers\nfor z in 120, 80, 40, 0:\n for x in -40, 0, 40:\n P.append((x, 0, z))\n\n# Add sagittal planes\nP.append((0, -40, 80))\nP.append((0, -40, 40))\n</code></pre>\n<p>Note, the array <code>P</code> above starts counting at zero, so <code>P[0]</code> is equivalent to your <code>P1</code>.</p>\n<p>Then there are the functions <code>p1()</code> to <code>p14()</code>. You define them and use them only once, which is a bit silly. But worse, they repeat the coordinates defined in <code>P</code>. Consider writing a function that draws a series of points or lines:</p>\n<pre><code>def draw(points, indices, color, lw=0):\n for i in indices:\n p = points[i]\n ax.scatter(p[0], p[1], p[2], color=color, lw=lw)\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>draw(P, [10, 7, 4, 1], 'k', 1) # Center points\ndraw(P, [12, 13], 'steelblue') # Sagittal plane points\n...\n</code></pre>\n<p>Now try to apply these techniques to the huge <code>if</code>-<code>else</code> chains you have.</p>\n<h1>Avoid hardcoded numbers</h1>\n<p><a href=\"https://en.wikipedia.org/wiki/Hard_coding\" rel=\"nofollow noreferrer\">Hardcoding</a> numbers can be a problem. Consider for example that all your coordinates are multiples of 40. I guess that's because it turns out to be a nice scale when you create the plot on your screen. But what if you want to change the scale later? Now you have to replace all instances of <code>-40</code>, <code>40</code>, <code>80</code> and so on, and hope you don't accidentily replace a <code>40</code> that had a completely different meaning. Avoid hardcoding numbers, instead create variables as soon as possible for things and use those from then on. For example:</p>\n<pre><code># Set size for xyz space\nsize = 150\nax.set_xlim3d(-size, size)\nax.set_ylim3d(-size, size)\nax.set_zlim3d(-size, size)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T09:38:53.800", "Id": "262749", "ParentId": "262707", "Score": "2" } } ]
{ "AcceptedAnswerId": "262749", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T04:48:39.987", "Id": "262707", "Score": "3", "Tags": [ "python", "matplotlib" ], "Title": "3d Cistercian numbers mini game (MatPlotLib), inputting similar xyz coordinates 50 times, how to streamline?" }
262707
<p>I have written the following code. It checks to see if the object contains the key where the key is present in the map.</p> <pre><code>const myMap = new Map(); myMap.set(2, 'test1'); myMap.set(3, 'test1'); let cellToHighLight = []; let contanins = false; for (let a = 2; a &lt;= 5; a++) cellToHighLight.push({ 'rowId': a, 'column': a++ }); for (const key in cellToHighLight) { if (myMap.has(cellToHighLight[key].rowId)) { contanins = true break; } } console.log(contanins) </code></pre> <p>My code is working, but I am striving to write cleaner, more optimal code. Can anyone suggest a cleaner way to write this code and/or a more optimized form?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T19:08:49.493", "Id": "518529", "Score": "0", "body": "Use `Set`. Make a set of all the keys of `myMap`, make a set of the `rowId` values in `cellToHighLight`. Then test the intersection of the two sets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T13:43:37.523", "Id": "518545", "Score": "0", "body": "Too bad Javascript doesn't have a native function to test intersection between two sets, so it still has to be hand-done." } ]
[ { "body": "<p>The Map() constructor can take an array of pairs, so you can set its starting values in one go.</p>\n<p>A little whitespace can go a long way to visually separate different parts of your code.</p>\n<p>I won't focus too much on your first for loop, as it looks like it was mainly meant to set up dummy values, but I will mention this: Avoid modifying your looping variable outside the actual for loop. If you want it to step by 2, just change <code>a++</code> to <code>a+=2</code> inside your for loop. (Also, I would rename &quot;a&quot; to &quot;i&quot; - i's a more standard looping variable name).</p>\n<p>I would recommend staying away from <code>for in</code>, especially with arrays, it has some unexpected issues (like iterating out of order), and there's always another way to do it. In this case, <code>for (const value of cellToHighLight)</code></p>\n<p>What you're basically doing with that last for loop is &quot;looking for something'. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\">yourArray.find()</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\" rel=\"nofollow noreferrer\">yourArray.findIndex()</a> will do this for you. Go to that link and familiarize yourself with some of the other array methods available, they come in handy.</p>\n<p>Here's a rewrite that applies the above suggestions.</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>// setup variables\n\nconst myMap = new Map([\n [2, 'test1'],\n [3, 'test1']\n]);\n\nlet cellToHighLight = [];\nfor (let i = 2; i &lt;= 5; i+=2)\n cellToHighLight.push({\n rowId: i,\n column: i\n });\n\n// search\n\nlet contanins = !!cellToHighLight.find(({ rowId }) =&gt; myMap.has(rowId));\nconsole.log(contanins);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T13:45:56.800", "Id": "262721", "ParentId": "262716", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T19:03:36.263", "Id": "262716", "Score": "1", "Tags": [ "javascript" ], "Title": "Cleaning up and optimizing JavaScript code to check if an object contains a key that is present in a map" }
262716
<p>Just wrote this small ring buffer system for an embedded device using C++98. Looking for cc, advice and bugs.</p> <p>Please check it out!</p> <p><a href="https://github.com/Bambofy/EmbeddedRingBuffer" rel="nofollow noreferrer">https://github.com/Bambofy/EmbeddedRingBuffer</a></p> <pre><code>/* Changelog ------------------------------------------------------------------ * 06/06/2021 Initial version * ---------------------------------------------------------------------------*/ #ifndef RINGBUFFER_RINGBUFFER_H #define RINGBUFFER_RINGBUFFER_H #include &quot;Block.h&quot; /** * @brief A ring buffer is a FIFO structure that can be used to * spool data between devices. * * There is a Skip() function that allows the client to * control when the read cursor is changed. This is so the * client can perform an action after Read() without the * write cursor overwriting data while the read block is used. * * For e.g with the sequence of events: * 1. Read(1000, false) * 2. Busy writing to sd card for 5 seconds * 3. Skip() * * Because the skip isn't called until the writing * has finished, another thread can .Append() without * corrupting the data being written. * * * @attention The ring buffer can only contain Length-1 number of entries, * because the last index is reserved for overrun checks. * * @tparam Length The length of the backing store array. * @tparam T The type of data stored. */ template&lt;unsigned int LENGTH, class T&gt; class RingBuffer { public: RingBuffer() : read_position(0), write_position(0) { } ~RingBuffer() { memset(data, 0, LENGTH); } /** * @brief Appends a value the end of the * buffer. */ void Append(T value) { /* * If the next position is where the read cursor * is then we have a full buffer. */ bool buffer_full; buffer_full = ((write_position + 1U) % LENGTH) == read_position; if (buffer_full) { /* * Tried to append a value while the buffer is full. */ overrun_flag = true; } else { /* * Buffer isn't full yet, write to the curr write position * and increment it by 1. */ overrun_flag = false; data[write_position] = value; write_position = (write_position + 1U) % LENGTH; } } /** * @brief Retrieve a continuous block of * valid buffered data. * @param num_reads_requested How many reads are required. * @param skip Whether to increment the read position * automatically, (false for manual skip * control) * @return A block of items containing the maximum * number the buffer can provide at this time. */ Block&lt;T&gt; Read(unsigned int num_reads_requested, bool skip = true) { bool bridges_zero; Block&lt;T&gt; block; /* * Make sure the number of reads does not bridge the 0 index. * This is because we can only provide 1 contiguous block at * a time. */ bridges_zero = (read_position &gt; write_position); if (bridges_zero) { unsigned int reads_to_end; bool req_surpasses_buffer_end; reads_to_end = LENGTH - read_position; req_surpasses_buffer_end = num_reads_requested &gt; reads_to_end; if (req_surpasses_buffer_end) { /* * If the block requested exceeds the buffer end. Then * return a block that reaches the end and no more. */ block.SetStart(&amp;(data[read_position])); block.SetLength(reads_to_end); if (skip) { read_position = (read_position + reads_to_end) % LENGTH; } } else { /* * If the block requested does not exceed 0 * then return a block that reaches the number of reads required. */ block.SetStart(&amp;(data[read_position])); block.SetLength(num_reads_requested); if (skip) { read_position = (read_position + num_reads_requested) % LENGTH; } } } else { /* * If the block doesn't bridge the zero then * return the maximum number of reads to the write * cursor. */ unsigned int max_num_reads; unsigned int num_reads_to_write_position; num_reads_to_write_position = (write_position - read_position); if (num_reads_requested &gt; num_reads_to_write_position) { /* * If the block length requested exceeds the * number of items available, then restrict * the block length to the distance to the write position. */ max_num_reads = num_reads_to_write_position; } else { /* * If the block length requested does not exceed the * number of items available then the entire * block is valid. */ max_num_reads = num_reads_requested; } block.SetStart(&amp;(data[read_position])); block.SetLength(max_num_reads); if (skip) { read_position = (read_position + max_num_reads) % LENGTH; } } return block; } /** * @brief Advances the read position. * */ void Skip(unsigned int num_reads) { read_position = (read_position + num_reads) % LENGTH; } bool Overrun() { return overrun_flag; } unsigned int Length() { return LENGTH; } private: unsigned int read_position; unsigned int write_position; T data[LENGTH]; bool overrun_flag; }; #endif </code></pre> <hr> <pre><code>/* Changelog ------------------------------------------------------------------ * 06/06/2021 Initial version * ---------------------------------------------------------------------------*/ #ifndef RINGBUFFER_BLOCK_H #define RINGBUFFER_BLOCK_H #include &lt;cstddef&gt; /** * @brief A block represents a continuous section * of the ring buffer. * @tparam T The type of data stored in the ring buffer. */ template&lt;class T&gt; class Block { public: Block() : start(nullptr), length(0) { } ~Block() { } /** * @brief Sets the block's starting * position to a point in memory. */ void SetStart(T* start) { this-&gt;start = start; } /** * @brief Sets the number of items in the * block. */ void SetLength(unsigned int length) { this-&gt;length = length; } /** * @return The block's starting * point in memory. */ T* Start() { return this-&gt;start; } /** * @return The number of items in the block. */ unsigned int Length() { return this-&gt;length; } /** * @param index The index of the item in the block. * @return The item in the block at the index. */ T At(unsigned int index) { return this-&gt;start[index]; } private: T* start; unsigned int length; }; #endif </code></pre> <hr> <p>Here is a test:</p> <pre><code>#include &lt;iostream&gt; #include &quot;RingBuffer.h&quot; int main() { RingBuffer&lt;100, int&gt; buffer; Block&lt;int&gt; block; /* Write 100 ints */ for (int i = 0; i &lt; buffer.Length(); i++) { buffer.Append(i); } /* Read a block */ block = buffer.Read(100); /* Print out the block */ for (int i = 0; i &lt; block.Length(); i++) { std::cout &lt;&lt; block.At(i) &lt;&lt; std::endl; } /* Read another block */ block = buffer.Read(1000); /* Print out the block */ for (int i = 0; i &lt; block.Length(); i++) { std::cout &lt;&lt; block.At(i) &lt;&lt; std::endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T11:26:36.027", "Id": "518535", "Score": "0", "body": "There was a bit of a formatting problem with your code apparently, the current version should be better. Is there a reason your `ifndef` talks about a `RINGBUFFER_RINGBUFFER_H` (double ringbuffer) or is this a typo?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T11:52:04.197", "Id": "518537", "Score": "0", "body": "Yes the double ringbuffer include guard is a typo, I had to change everything froms tabs to spaces" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T12:16:00.773", "Id": "518538", "Score": "1", "body": "This code is tagged C++98, but uses `nullptr`. I think you may not be using the version of C++ you think you’re using. (Nobody is still using C++98 anymore these days.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T12:35:32.677", "Id": "518540", "Score": "0", "body": "@indi thanks for the heads up i'll change this to 0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T16:10:17.443", "Id": "518560", "Score": "2", "body": "The point about your code not being C++98 wasn’t to make your code *worse* in order to make it 98-compatible, it was to give up on being 98-compatible and upgrade your target version. You mentioned multi-threading: that is literally impossible to do properly in C++98; if you want to properly support multiple threads, you need at least C++11 for its multi-thread-aware memory model (not to mention stuff like `std::atomic`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T18:09:22.913", "Id": "518567", "Score": "0", "body": "@indi it isn't multi-thread compatible, its compatible with interrupt based concurrency like this https://www.digikey.com/en/maker/projects/getting-started-with-stm32-timers-and-timer-interrupts/d08e6493cefa486fb1e79c43c0b08cc6 . I don't want to add the overhead of including the C++11 features like std::atomic because its meant to be used on embedded devices like arduinos. But if it is required i will add it. I have changed the 0 to NULL defined in stddef.h" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T21:36:08.730", "Id": "518579", "Score": "0", "body": "Hi @RichardBamford - `Append` as written is really bad - the caller assume the data they've provide has ended up in the buffer, but maybe it didn't. The answer below nearly realises this .. Imagine if half your message got sent because the intermediate buffers threw part of it away !!" } ]
[ { "body": "<p>This looks quite good, some minor changes could be made though:</p>\n<h1>Return <code>overrun_flag</code> instead of storing it</h1>\n<p>Especially on an embedded system, you don't want to store data unnecessarily. Instead of having a member variable <code>overrun_flag</code> and having <code>Append()</code> set it, why not have <code>Append()</code> return a <code>bool</code> indicating whether the attempt to append succeeded or not?</p>\n<p>This also forces the caller to immediately check the value, and there is no possibility that another call to <code>Append()</code> might reset <code>overrun_flag</code> to <code>false</code> before it tries to check whether an earlier call to <code>Append()</code> failed.</p>\n<h1>Pass values as <code>const</code> references where appropriate</h1>\n<p>If <code>T</code> is an <code>int</code>, passing it by value to a function is fine. But if it becomes a larger struct, maybe one with constructors, this might become inefficient. Consider passing them by <code>const</code> reference instead:</p>\n<pre><code>bool Append(const T &amp;value) {\n if ((write_position + 1U) % LENGTH == read_position)\n return false;\n\n data[write_position] = value;\n write_position = (write_position + 1U) % LENGTH;\n return true;\n}\n</code></pre>\n<h1>About <code>Block</code></h1>\n<p>Your <code>Block</code> class is a nice way of providing a view of consecutive items in the ringbuffer. However, there are two issues with it.</p>\n<p>The most important one is why have a <code>skip</code> parameter? Surely if you immediately update the <code>read_position</code>, another thread might start overwriting the data, before the thread calling <code>Read()</code> had a chance to read the data. I would therefore remove this parameter, and always force the reader to call <code>Skip()</code> manually. Even better, you could make a <code>Block</code> a <a href=\"https://en.cppreference.com/w/cpp/language/raii\" rel=\"nofollow noreferrer\">RAII</a> type, and have it automatically call <code>Skip()</code> when its destructor is called.</p>\n<p>But the second problem is that while it looks efficient, it will actually prevent writers from writing to the ring buffer for longer than necessary, because they have to wait for the reader to process the whole block. And if you are going to loop over the block sequentially anyway, then it would actually make more sense to just provide access to the first unread element, like <a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow noreferrer\"><code>std::queue</code></a> does. That brings me to:</p>\n<h1>Consider copying <code>std::queue</code>'s API</h1>\n<p>It's always easier for C++ programmers if the classes they use have a similar interface as those from similar classes in the standard library. It's even better if your own classes are drop-in replacements for STL classes. So in this case, I'd recommend you provide the same member functions as <a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow noreferrer\"><code>std::queue</code></a>.</p>\n<h1>Thread safety</h1>\n<p>Since you mentioned multiple threads accessing the ringbuffer at the same time, you should definitely think about thread safety. Do you want to allow multiple readers and multiple writers, or just a single reader and/or a single writer? At the moment it is at best only safe for a single reader and a single writer. If that's what is intended, make sure you document that.</p>\n<p>However, the question is if this is even safe for a single reader and a single writer accessing the data simultaneously. On 8-bit Atmel MCUs, <a href=\"https://forum.arduino.cc/t/atomic-reading-of-uint16_t/202786/3\" rel=\"nofollow noreferrer\">16-bit reads and writes are <em>not</em> atomic</a>. You should therefore use some way to synchronize access to the read and write pointers. If you don't, then your code might seem to work as most of the time, the reads and writes won't be done at exactly the same time, but once in a while it might go wrong, and depending on what your embedded device is controlling, the consequences might be grave.</p>\n<p>Check if your embedded device has support for atomic reads and writes to <code>unsigned int</code>s, and if not, use a <a href=\"https://en.wikipedia.org/wiki/Semaphore_(programming)\" rel=\"nofollow noreferrer\">semaphore</a> or <a href=\"https://en.wikipedia.org/wiki/Lock_(computer_science)\" rel=\"nofollow noreferrer\">mutex</a> primitive to ensure only one thread gets to update the read/write pointers at a time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T12:34:06.203", "Id": "518539", "Score": "0", "body": "Thank you very much for your input! There's a skip parameter on the Read() function because if you dont want to use it in an ISR setting, you dont have to manually skip it. And the block is not ment to be iterated (this is the worst thing that can be done in terms of taking up cpu time), it is meant to be directly transferred using a DMA. The iteration problem is what made me create the skipping feature in the first place, iterating to pull data from the buffer one after another (say 30,000 times) takes too much time thats why you read from it in blocks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T15:35:39.927", "Id": "518555", "Score": "0", "body": "Ah OK, I only saw the `Block`s being iterated over in your example, but indeed if you want to do DMA this is a good solution. I would still remove the `skip` parameter though, and make it more explicit. This will make the code more robust against future changes where you might introduce an ISR that writes to the ringbuffer for example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T17:58:15.343", "Id": "518566", "Score": "0", "body": "Ok i'll remove the skip parameter, i agree, it is too hidden. thank you" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T12:24:05.150", "Id": "262718", "ParentId": "262717", "Score": "3" } }, { "body": "<ul>\n<li><p>A <code>LENGTH</code> confusion.</p>\n<p>In the destructor the <code>memset(data, 0, LENGTH);</code> clears <code>LENGTH</code> <em>bytes</em>, whereas a definition of</p>\n<pre><code>T data[LENGTH]\n</code></pre>\n<p>says there are <code>LENGTH</code> items of <code>sizeof T</code>. A bit more than <code>LENGTH</code> bytes.</p>\n<p>As a side note, the destructor (after fixing the <code>LENGTH</code> issue) works correctly <em>only</em> if <code>T</code> is trivially constructible. BTW, if it is so, do you need it at all?</p>\n</li>\n<li><p>Unrestricted getters and setters defeat the purpose of having <code>start</code> and <code>length</code> private to <code>Block</code>. It is cleaner to define</p>\n<pre><code> Block::Block(T * start, size_t size)\n</code></pre>\n<p>and get rid of setters whatsoever.</p>\n</li>\n<li><p>Every branch of <code>Read</code> does <code>block.SetStart(&amp;(data[read_position]));</code>. Make it clear and lift it out of the <code>if/else</code> cascade. See the next bullet for more.</p>\n</li>\n<li><p><code>brigdes_zero = (read_position &gt; write_position);</code> does not care of <code>num_reads_requested</code>, and therefore looks suspicious. I understand the underlying motivation, but there is a cleaner way to express it. Consider</p>\n<pre><code> read_hard_end = (read_position &gt; write_position)? LENGTH: write_position;\n max_reads_available = read_hard_end - write_position;\n read_size = std::min(num_read_requested, max_reads_available);\n\n Block&lt;T&gt; block(&amp;data[read_position], read_size);\n return block;\n</code></pre>\n<p>(I intentionally skip the <code>Skip</code> handling).</p>\n</li>\n<li><p><a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged &#39;c++&#39;\" rel=\"tag\">c++</a> is not <a href=\"/questions/tagged/java\" class=\"post-tag\" title=\"show questions tagged &#39;java&#39;\" rel=\"tag\">java</a>. All those <code>this-&gt;</code> only add noise.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T08:36:06.720", "Id": "518599", "Score": "0", "body": "Thank you for the cc, i have removed the memset() and researching into your suggestions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T01:13:27.013", "Id": "262738", "ParentId": "262717", "Score": "4" } }, { "body": "<p>You don't need version history stored in the file -- that's what version control systems do for you.</p>\n<pre><code>~RingBuffer()\n {\n memset(data, 0, LENGTH);\n }\n</code></pre>\n<p>Why zero the memory that you're not going to use again? Is that for debugging? If you do need it, consider <code>std::fill_n</code> instead. But wait a minute... <code>LENGTH</code> is in bytes, but <code>data</code> is an array of <code>T</code> not a byte-buffer. So this is actually wrong, which is one good reason for preferring the C++ algorithms . But does setting objects of type <code>T</code> to 0 even make sense? This is run <em>before</em> the destructors for the individual <code>T</code>s so overwriting it like this can cause a lot of grief.</p>\n<hr />\n<p><code>LENGTH</code> should be <code>size_t</code>, not <code>unsigned int</code>.</p>\n<hr />\n<p>Don't use <code>std::endl</code> (standard <em>Code Review</em> issue!)</p>\n<hr />\n<p><code>write_position = (write_position + 1U) % LENGTH;</code><br />\nThat is a <strong>very slow</strong> way to handle wrap-around. Even on CPUs that support division with a built-in instruction, it is remarkably slow. Worse yet, you're repeating it! Break out a variable, say, <code>next_write_position</code>, to use in all the places that need it.</p>\n<hr />\n<pre><code>bool buffer_full;\n\nbuffer_full = ((write_position + 1U) % LENGTH) == read_position;\n</code></pre>\n<p>So close... Define variables where you need them, <em>and initialize</em> in the declaration. And use <code>const</code> where you can. So:<br />\n<code>const bool buffer_full = ... ;</code></p>\n<hr />\n<p>Use standard names for members that do well-understood things. Using this, it would be a pain to learn that I have to use <code>Length</code> instead of <code>size</code>, <code>Append</code> instead of <code>push_back</code>, etc. Make it fit with what people already know. This is a sequential container that works like a <code>deque</code>, so it should have the same API to the extent possible.</p>\n<hr />\n<pre><code>bool Overrun()\n {\n return overrun_flag;\n }\n</code></pre>\n<p>(and others) Access-only member functions should be <code>const</code>.</p>\n<hr />\n<p><code>start(nullptr)</code><br />\nYou don't have <code>nullptr</code> in C++98; that was added in C++11. Use the <strong>literal constant <code>0</code></strong>.</p>\n<hr />\n<p><code>Block::Setstart</code> and <code>Setlength</code>:<br />\nNo... just make those constructor arguments. They are <em>only</em> used to set up the block object to be returned, and always called together. Just record the start/length as local variables in the function and then <code>Block&lt;T&gt;(startpos,length);</code> at the end. Don't define <code>block</code> at the top of the function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T20:52:23.840", "Id": "518719", "Score": "0", "body": "Thanks for the CC! the memset error was fixed a couple of commits ago, https://github.com/Bambofy/EmbeddedRingBuffer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T20:09:09.070", "Id": "262778", "ParentId": "262717", "Score": "2" } }, { "body": "<p>Review addressing the embedded system aspects, assuming the target is Arduino/AVR 328P:</p>\n<ul>\n<li><p>Implementing destructors for a class to be used in a bare metal embedded system is very fishy. If you find yourself in a situation where you need to push/pop ring buffers on the stack, you are doing something very wrong. Objects of such classes should always be allocated with static storage duration.</p>\n</li>\n<li><p><code>RingBuffer&lt;100, int&gt; buffer;</code> is wrong in several ways - it should preferably have static storage duration as mentioned, but more importantly you shouldn't slaughter some 200+ bytes of your stack just like that. Assuming this is for AVR 328P then that's 10% out of your total RAM blown. And maybe some 50% of the stack?</p>\n<p>In addition, there's an old cynical rule saying that we should never allocate any buffers at all on the stack in embedded systems, because buffer overruns and stack overflows are such common bugs.</p>\n</li>\n<li><p>Embedded systems should always use the <code>stdint.h</code> types. This is an 8-bitter so all arithmetic should preferably be done on <code>uint8_t</code> integers whenever possible. You shouldn't use <code>int</code> which is 16 bit and also needlessly signed - signed types are dangerous to use in case they end up in bitwise arithmetic, as is common in embedded systems. Getting rid of <code>int</code> and limiting the max size of the ring buffer to at most 255 will speed up this code considerably.</p>\n</li>\n<li><p>As mentioned in other reviews, any decent ring buffer comes with a &quot;thread-safety&quot; option. In this case interrupt safety, since ring buffers are most commonly used when communicating between for example an UART rx ISR and the UART driver.</p>\n<p>There's a common misconception that the size of variables vs data size of the CPU somehow matters for atomicity. That's plain wrong, C++ code can end up non-atomic even if doing 8 bit access on a 8 bit CPU. You need to use the actual atomic feature (C++11 only?) or inline assembler, or the variables cannot be assumed to be atomic. More info here: <a href=\"https://electronics.stackexchange.com/a/409570/6102\">https://electronics.stackexchange.com/a/409570/6102</a>.</p>\n<p>The most common way to prevent race conditions in ring buffers is simply to accept a pointer to an interrupt enable register and a mask. So if the UART driver is to utilize the ring buffer, it would pass along a <code>volatile</code> pointer to the UART rx enable/disable register and the ring buffer can simply shut off the interrupt. In the specific case of UART, the data is very slow compared to the program execution, so disabling the interrupt for a few microseconds won't even lead to data loss. Or in case you need tougher real-time than that, you shouldn't be using classes in the first place.</p>\n</li>\n<li><p>Bare metal systems don't return from main(). Who would they return to? You need to have an eternal loop in main(), otherwise you'll just generate pointless bloat return code that chews up stack and flash needlessly. Ideally embedded systems use the implementation-defined form <code>void main (void)</code> but unfortunately there's a misguided PC programmer rule in the C++ standard saying that if a program defines a function <code>main()</code> it must return <code>int</code>. Freestanding systems are not exempt from this rule for reasons unknown. You can avoid this C++ language design flaw by using gcc for AVR and compile for embedded systems with <code>-ffreestanding</code>. (The same option works in C too.)</p>\n<p>To illustrate, here's the code with extra bloat generated by incorrect form <code>int main()</code> with return:</p>\n<pre><code> main:\n push r28\n push r29\n in r28,__SP_L__\n in r29,__SP_H__\n ldi r24,0\n ldi r25,0\n pop r29\n pop r28\n ret\n</code></pre>\n<p>And here's the code generated by correct form <code>void main (void)</code> enabled with <code>-ffreestanding</code> and then an eternal loop:</p>\n<pre><code> main:\n push r28\n push r29\n in r28,__SP_L__\n in r29,__SP_H__\n .L2:\n rjmp .L2\n</code></pre>\n<p>(It's weird that they set the SP from main() but that's another story...)</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T14:59:57.400", "Id": "263148", "ParentId": "262717", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T10:36:49.787", "Id": "262717", "Score": "2", "Tags": [ "c++", "circular-list", "embedded", "c++98" ], "Title": "Ring buffer for Arduino" }
262717
<p>I have the following working code for a generic WebSocket component:</p> <pre><code>import json import aiohttp import asyncio import gzip import asyncio from threading import Thread class WebSocket: KEEPALIVE_INTERVAL_S = 10 def __init__(self, url, on_connect, on_msg): self.url = url self.on_connect = on_connect self.on_msg = on_msg self.streams = {} self.worker_thread = Thread(name='WebSocket', target=self.thread_func, daemon=True).start() def thread_func(self): asyncio.run(self.aio_run()) async def aio_run(self): async with aiohttp.ClientSession() as session: self.ws = await session.ws_connect(self.url) await self.on_connect(self) async def ping(): while True: print('KEEPALIVE') await self.ws.ping() await asyncio.sleep(WebSocket.KEEPALIVE_INTERVAL_S) async def main_loop(): async for msg in self.ws: def extract_data(msg): if msg.type == aiohttp.WSMsgType.BINARY: as_bytes = gzip.decompress(msg.data) as_string = as_bytes.decode('utf8') as_json = json.loads(as_string) return as_json elif msg.type == aiohttp.WSMsgType.TEXT: return json.loads(msg.data) elif msg.type == aiohttp.WSMsgType.ERROR: print('⛔️ aiohttp.WSMsgType.ERROR') return msg.data data = extract_data(msg) self.on_msg(data) # May want this approach if we want to handle graceful shutdown # W.task_ping = asyncio.create_task(ping()) # W.task_main_loop = asyncio.create_task(main_loop()) await asyncio.gather( ping(), main_loop() ) async def send_json(self, J): await self.ws.send_json(J) </code></pre> <p>I'm creating a daemon thread, from which I invoke <code>asyncio.run(...)</code>, which allows me to leverage asyncio functionality while allowing the component to be executed from non-asyncio code.</p> <p>Here's an example consumer of the component:</p> <pre><code>class WS_HotBit: URL = 'wss://ws.hotbit.io' KEY = None def __init__(self, on_trades): def on_msg(data): print(data) if set(data.keys()) == set(['error', 'result', 'id']): print(data) elif set(data.keys()) == set(['method', 'id', 'ts', 'params']): stream = data['method'] id_ = data['id'] timestamp = data['ts'] payload = data['params'] # payload: ['ETHUSDT', [{'id': 2304578176, 'time': 1622984716.977204, 'price': '2680', 'amount': '0.00984', 'type': 'sell'},...], ...] if len(payload) != 2: print('⚠️ Unknown WebSocket packet format') print(payload) else: symbol, trades = payload print(f'id: {id_}', stream, timestamp, symbol, f'got {len(trades)} trades') on_trades(symbol, trades) else: print('⚠️ Unknown packet from WebSocket') print(data) async def on_connect(ws): await ws.send_json({'method': 'deals.subscribe', 'params': ['ETHUSDT', 'BTCUSDT'], 'id': 1}) self.websocket = WebSocket(WS_HotBit.URL, on_connect, on_msg) </code></pre> <p>And this code tests the consumer:</p> <pre><code>from time import sleep if __name__ == '__main__': def on_trades(symbol, trades): print(symbol, [tr['amount'] for tr in trades]) ws_hotbit = WS_HotBit(on_trades) while True: sleep(3) print('Main TICK') </code></pre> <p>The consumer is able to send packets into the websocket, and thus subscribe to streams, albeit with the limitation that this is done all in one place, as I'm using a 'did-connect' callback. I can't see a clean way of bypassing this limitation (and allowing sending packets from non-asyncio code at any time.</p> <p>I'm also aware that there is no correct destruction sequence.</p> <p>This is my first foray into asycnio, and my feeling is that it could be cleaner.</p> <p>Forever grateful if an engineer with more experience/expertise would care to point out the biggest flashing red lights.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T15:05:58.627", "Id": "262722", "Score": "1", "Tags": [ "python", "multithreading", "websocket", "asyncio" ], "Title": "Building a generic WebSocket component in Python" }
262722
<p>I'm using PHP/Laravel and I have two controllers.</p> <ul> <li>Controllers/PaymentController</li> <li>Controllers/PaymentExpressControler</li> </ul> <p>They both create an request which is exactly the same, but it has some differences.</p> <p>Let's say, they both use <code>createRequest(Request $Request)</code> which is a POST request to a third-party api.</p> <p>I'm wondering how can I reduce the code, because it's clearly duplicated.</p> <p>I was thinking of two options, a trait or a class.</p> <ul> <li>Controllers/Payment/(NameOfThirdParty).php which is a class with createRequest</li> </ul> <p>How would this sound like?</p> <p>My current <code>createRequest</code></p> <pre><code>protected function createRequest(Request $request) { $this-&gt;cartCollection(); $availableMethods = ['mb', 'mbw', 'cc', 'dd']; $tkey = uniqid(Auth::id(), true); if (in_array($request-&gt;type, $availableMethods)) { $payment_body = [ &quot;method&quot; =&gt; $request-&gt;type, &quot;value&quot; =&gt; (float)\Cart::getTotal(), &quot;currency&quot; =&gt; &quot;EUR&quot;, &quot;key&quot; =&gt; $tkey, &quot;type&quot; =&gt; &quot;sale&quot;, &quot;customer&quot; =&gt; [ &quot;name&quot; =&gt; Auth::user()-&gt;name, &quot;email&quot; =&gt; Auth::user()-&gt;email, &quot;phone&quot; =&gt; isset($request-&gt;telm) ? $request-&gt;telm : &quot;&quot;, ], &quot;capture&quot; =&gt; [ &quot;descriptive&quot; =&gt; &quot;Order&quot;, &quot;transaction_key&quot; =&gt; $tkey, ], ]; if ($request-&gt;type == 'dd') { $sdd_mandate = ['sdd_mandate' =&gt; [ &quot;iban&quot; =&gt; $request-&gt;iban, &quot;account_holder&quot; =&gt; Auth::user()-&gt;name, &quot;name&quot; =&gt; Auth::user()-&gt;name, &quot;email&quot; =&gt; Auth::user()-&gt;email, &quot;phone&quot; =&gt; isset($request-&gt;telm) ? $request-&gt;telm : &quot;0000000&quot;, &quot;country_code&quot; =&gt; &quot;EU&quot;, ]]; $payment_body = array_merge($payment_body, $sdd_mandate); } $response = Http::withHeaders([ 'AccountId' =&gt; config('payment.accountId'), 'ApiKey' =&gt; config('payment.apiKey'), 'Content-Type' =&gt; 'application/json', ])-&gt;post('REMOVED API LINK', $payment_body); $this-&gt;addToPreOrdersTable($tkey); return $response-&gt;collect(); } } } </code></pre> <pre><code>protected function addToPreOrdersTable(string $hash) { $this-&gt;cartCollection(); OrderService::createPreOrder($this-&gt;contents, $hash, 'buy'); } </code></pre> <p>addToPreOrdersTable Is also in both controllers.</p> <pre><code> protected function index(Request $request) { if (isset($request-&gt;type)) { $result = $this-&gt;createRequest($request); $status = $result['status']; if ($status == 'ok') { $type = $result['method']['type']; switch ($type) { case 'cc': return redirect($result['method']['url']); case 'mb': return view('payment', ['type' =&gt; 'mb', 'data' =&gt; $result['method']]); case 'mbw': return view('payment', ['type' =&gt; 'mbw']); case 'dd': return view('payment', ['type' =&gt; 'dd', 'data' =&gt; $result['method']]); } } return back()-&gt;withInput()-&gt;withErrors(['Error' =&gt; 'An error has occured.']); } return view('payment'); } </code></pre>
[]
[ { "body": "<p>I would create another service layer that would handle the creation of the request and maybe the call to the third party api. Your controllers are there to create the best response to the http request not really to create the best response, create external requests, handle them, etc..</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T11:07:16.157", "Id": "262751", "ParentId": "262724", "Score": "1" } }, { "body": "<p>Let's implements following: separate logic, refactoring of methods</p>\n<p><strong>Separate logic</strong></p>\n<p>Validate Requests/PaymentRequest.php add rule for <a href=\"https://laravel.com/docs/8.x/validation#creating-form-requests\" rel=\"nofollow noreferrer\">validation</a></p>\n<pre><code>use Illuminate\\Foundation\\Http\\FormRequest;\n\nclass PaymentRequest extends FormRequest\n{\n public function rules(): array\n {\n return [\n 'name' =&gt; ['required', 'string', 'in:cc,mb,mbw,dd'],\n 'telm' =&gt; ['string'],\n 'iban' =&gt; ['required', 'string']\n ];\n }\n}\n</code></pre>\n<p>take out the logic and leave the thin controller:</p>\n<p><em>Controllers/PaymentController</em></p>\n<pre><code>public function index(PaymentRequest $request, PaymentService $service) {\n\n return $service-&gt;run($request);\n \n}\n</code></pre>\n<p>Now we are separating to service and external service. ExternalService - external request, service -our logic;</p>\n<p>add <em>Services/PaymentService.php</em> and change method <code>createRequest</code> to <code>send</code></p>\n<pre><code> class PaymentService implements PaymentServiceInterface {\n\n private $externalPaymentService;\n public function __construct(ExternalPaymentService $externalPaymentService)\n {\n $this-&gt;externalPaymentService = $externalPaymentService;\n }\n\n public function run(PaymentRequest $request) {\n \n // Validate rule in PaymentRequest will not let you go further\n // if (isset($request-&gt;type)) { \n $tkey = uniqid(Auth::id(), true);\n $result = $this-&gt;externalPaymentService-&gt;send($request, $tkey);\n $this-&gt;addToPreOrdersTable($tkey);\n $status = $result['status'];\n if ($status == 'ok') {\n $type = $result['method']['type'];\n switch ($type) {\n case 'cc':\n return redirect($result['method']['url']);\n case 'mb':\n return view('payment', ['type' =&gt; 'mb', 'data' =&gt; $result['method']]);\n case 'mbw':\n return view('payment', ['type' =&gt; 'mbw']);\n case 'dd':\n return view('payment', ['type' =&gt; 'dd', 'data' =&gt; $result['method']]);\n }\n }\n return back()-&gt;withInput()-&gt;withErrors(['Error' =&gt; 'An error has occured.']);\n //}\n // return view('payment');\n }\n\n protected function addToPreOrdersTable(string $hash)\n {\n $this-&gt;cartCollection();\n OrderService::createPreOrder($this-&gt;contents, $hash, 'buy');\n }\n\n}\n</code></pre>\n<p><em>Services/PaymentServiceInterface.php</em></p>\n<pre><code>interface PaymentServiceInterface {\n run(Request $request); \n}\n</code></pre>\n<p><em>ExternalService/ExternalPaymentService.php</em></p>\n<pre><code>class ExternalPaymentService {\n public function send(Request $request, $tkey)\n {\n $this-&gt;cartCollection();\n\n $availableMethods = ['mb', 'mbw', 'cc', 'dd'];\n\n\n if (in_array($request-&gt;type, $availableMethods)) {\n $payment_body = [\n &quot;method&quot; =&gt; $request-&gt;type,\n &quot;value&quot; =&gt; (float)\\Cart::getTotal(),\n &quot;currency&quot; =&gt; &quot;EUR&quot;,\n &quot;key&quot; =&gt; $tkey,\n &quot;type&quot; =&gt; &quot;sale&quot;,\n &quot;customer&quot; =&gt;\n [\n &quot;name&quot; =&gt; Auth::user()-&gt;name,\n &quot;email&quot; =&gt; Auth::user()-&gt;email,\n &quot;phone&quot; =&gt; isset($request-&gt;telm) ? $request-&gt;telm : &quot;&quot;,\n ],\n &quot;capture&quot; =&gt;\n [\n &quot;descriptive&quot; =&gt; &quot;Order&quot;,\n &quot;transaction_key&quot; =&gt; $tkey,\n ],\n ];\n if ($request-&gt;type == 'dd') {\n $sdd_mandate = ['sdd_mandate' =&gt; [\n &quot;iban&quot; =&gt; $request-&gt;iban,\n &quot;account_holder&quot; =&gt; Auth::user()-&gt;name,\n &quot;name&quot; =&gt; Auth::user()-&gt;name,\n &quot;email&quot; =&gt; Auth::user()-&gt;email,\n &quot;phone&quot; =&gt; isset($request-&gt;telm) ? $request-&gt;telm : &quot;0000000&quot;,\n &quot;country_code&quot; =&gt; &quot;EU&quot;,\n ]];\n $payment_body = array_merge($payment_body, $sdd_mandate);\n }\n $response = Http::withHeaders([\n 'AccountId' =&gt; config('payment.accountId'),\n 'ApiKey' =&gt; config('payment.apiKey'),\n 'Content-Type' =&gt; 'application/json',\n ])-&gt;post('REMOVED API LINK', $payment_body);\n\n\n return $response-&gt;collect();\n }\n }\n }\n</code></pre>\n<p>Okay, we made first level, separated logic!</p>\n<p><strong>Refactoring of methods</strong></p>\n<p>Let's create <em>Services/PaymentsRenderStrategy.php</em> and will changing <code>run</code> in <code>PaymentService</code></p>\n<p><em>Services/PaymentsRenderStrategy.php</em></p>\n<pre><code>class PaymentsRenderStrategy {\n private function cc($method) {\n return redirect($method['url']);\n }\n\n private function mb($method) {\n return view('payment', ['type' =&gt; 'mb', 'data' =&gt; $method]);\n }\n\n private function mbw($method) {\n return view('payment', ['type' =&gt; 'mbw']);\n }\n\n private function dd($method) {\n return view('payment', ['type' =&gt; 'dd', 'data' =&gt; $method]);\n }\n\n public function render($type, $data) {\n try {\n return $this-&gt;$type($data);\n } catch (Exception $e) {\n throw new Exception('some error in methods');\n }\n }\n\n }\n</code></pre>\n<p>rewrite <em>Services/PaymentService.php</em></p>\n<pre><code> class PaymentService implements PaymentServiceInterface {\n\n private $externalPaymentService;\n\n public function __construct(ExternalPaymentService $externalPaymentService)\n {\n $this-&gt;externalPaymentService = $externalPaymentService;\n }\n\n public function run(PaymentRequest $request) {\n\n try {\n $tkey = uniqid(Auth::id(), true);\n $this-&gt;cartCollection();\n $result = $this-&gt;externalPaymentService-&gt;collect($request, $tkey)-&gt;send($request, $tkey);\n $this-&gt;addToPreOrdersTable($tkey);\n $status = $result['status'];\n\n if ($status != 'ok') {\n throw new Exception('Bad request');\n }\n return (new PaymentsRenderStrategy())-&gt;render($request-&gt;type, ($result['method']);\n\n } catch (Exception $e) {\n return back()-&gt;withInput()-&gt;withErrors(['Error' =&gt; 'An error has occured.']);\n }\n }\n\n protected function addToPreOrdersTable(string $hash)\n {\n $this-&gt;cartCollection();\n OrderService::createPreOrder($this-&gt;contents, $hash, 'buy');\n }\n\n}\n</code></pre>\n<p>Validateon we moved in PaymentRequest and we don't need extra checks like if <code>(in_array($request-&gt;type, $availableMethods))</code>.</p>\n<p><code>$this-&gt;$type($data);</code> - call need method by type (note: use <strong>$this-&gt;$type</strong>)</p>\n<p>also we took the logic out of <code>ExternalPaymentService</code> and serparate method send by <code>collect</code> and <code>send</code></p>\n<p>ExternalServices/PaymentExternalService.php</p>\n<pre><code>class ExternalPaymentService {\n\n private $paymentBody;\n\n public function collect(PaymentRequest $request, $tkey) {\n $this-&gt;paymentBody = [\n &quot;method&quot; =&gt; $request-&gt;type,\n &quot;value&quot; =&gt; (float)\\Cart::getTotal(),\n &quot;currency&quot; =&gt; &quot;EUR&quot;,\n &quot;key&quot; =&gt; $tkey,\n &quot;type&quot; =&gt; &quot;sale&quot;,\n &quot;customer&quot; =&gt;\n [\n &quot;name&quot; =&gt; Auth::user()-&gt;name,\n &quot;email&quot; =&gt; Auth::user()-&gt;email,\n &quot;phone&quot; =&gt; isset($request-&gt;telm) ? $request-&gt;telm : &quot;&quot;,\n ],\n &quot;capture&quot; =&gt;\n [\n &quot;descriptive&quot; =&gt; &quot;Order&quot;,\n &quot;transaction_key&quot; =&gt; $tkey,\n ],\n ];\n if ($request-&gt;type == 'dd') {\n $sdd_mandate = ['sdd_mandate' =&gt; [\n &quot;iban&quot; =&gt; $request-&gt;iban,\n &quot;account_holder&quot; =&gt; Auth::user()-&gt;name,\n &quot;name&quot; =&gt; Auth::user()-&gt;name,\n &quot;email&quot; =&gt; Auth::user()-&gt;email,\n &quot;phone&quot; =&gt; isset($request-&gt;telm) ? $request-&gt;telm : &quot;0000000&quot;,\n &quot;country_code&quot; =&gt; &quot;EU&quot;,\n ]];\n $this-&gt;paymentBody = array_merge($this-&gt;paymentBody, $sdd_mandate);\n }\n\n return $this;\n }\n\n public function send()\n {\n\n $response = Http::withHeaders([\n 'AccountId' =&gt; config('payment.accountId'),\n 'ApiKey' =&gt; config('payment.apiKey'),\n 'Content-Type' =&gt; 'application/json',\n ])-&gt;post('REMOVED API LINK', $this-&gt;paymentBody);\n\n\n return $response-&gt;collect();\n }\n }\n</code></pre>\n<p>Here we refactor I hope helped you. Next stage: take out magic constants (cc,mb,mbw,dd), to short methods ...etc. See <a href=\"https://refactoring.guru/\" rel=\"nofollow noreferrer\">more</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T12:48:00.600", "Id": "262792", "ParentId": "262724", "Score": "3" } } ]
{ "AcceptedAnswerId": "262792", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T15:56:23.690", "Id": "262724", "Score": "2", "Tags": [ "php", "laravel" ], "Title": "How to reduce a POST request duplicate in Laravel/PHP for payment system?" }
262724
<p>This is the simplest implementation of the 'DataGridBehavior' Class for column Filtering I could come up with:</p> <pre><code> public static List&lt;ColumnItem&gt; GetColumnsFilter(DependencyObject obj) { ...} public static void SetColumnsFilter(DependencyObject obj, List&lt;ColumnItem&gt; value) { ...} public static readonly DependencyProperty ColumnsFilterProperty = DependencyProperty.RegisterAttached(&quot;ColumnsFilter&quot;, typeof(List&lt;ColumnItem&gt;), typeof(DataGridBehavior), new PropertyMetadata(null, OnColumnsFilterChange)); private static void OnColumnsFilterChange(DependencyObject d, DependencyPropertyChangedEventArgs e) { var dg = d as DataGrid; if (dg == null) return; // Columns is a list and will never change if(e.NewValue == null &amp;&amp; e.OldValue != null) dg.Loaded -= Handle_DataGridLoadedEvent; if (e.NewValue == null || ((List&lt;ColumnItem&gt;)e.NewValue).Count == 0) return; var Columns = ((List&lt;ColumnItem&gt;)e.NewValue); // Columns is a list and will never change. if (e.OldValue == null) { dg.Loaded += Handle_DataGridLoadedEvent; } else // e.NeValue != null &amp;&amp; e.OldValue != null (For some reason) { dg.Loaded -= Handle_DataGridLoadedEvent; } } private static void Handle_DataGridLoadedEvent(object sender, RoutedEventArgs e) { var dg = sender as DataGrid; var Columns = GetColumnsFilter(dg); foreach (var column in dg.Columns) { var col = Columns.FirstOrDefault(c =&gt; c.PropertyName == column.Header.ToString()); if (col == null) continue; var binding = new Binding(nameof(col.IsShown)); binding.Source = col; binding.Converter = new BooleanToVisibilityConverter(); BindingOperations.SetBinding(column, DataGridColumn.VisibilityProperty, binding); } } </code></pre> <p>As for now, its use is straight forward. In my ViewModel, I have a:</p> <blockquote> <p>List&lt; ColumnItem&gt; Columns {get; set;}</p> </blockquote> <pre><code>public class ColumnItem : IDeepClone&lt;ColumnItem&gt; { public string PropertyName { get; set; } public Type PropertyType { get; set; } public bool IsShown { get; set; } = true; public List&lt;ColumnItem&gt; InnerProperties { get; set; } public TypeComplexity Complexity { get; set; } = TypeComplexity.SIMPLE; } </code></pre> <p>In my Xaml, I just add the behavior while binding it to the columns:</p> <pre><code>&lt;DataGrid ItemSource={..} behaviors:DataGridBehavior.Columns={Binding Columns}/&gt; </code></pre> <p>On Top of that, I usually have a listbox with a custom template that shows my columns in the format of: (Only for testing, better format to be used in the end product)</p> <pre><code>&lt;StackPanel Orientation=&quot;Horizontal&quot;&gt; &lt;TextBlock Text={Binding PropertyName}/&gt; &lt;CheckBox IsChecked={Binding IsShown}/&gt; &lt;/StackPanel&gt; </code></pre> <p>Since I'm going to be using it extensively through out my program. I wanted to know if this implementation has any flaws. Should I use WeakEventManager or handle my e.OldValue &amp;&amp; e.NewValue checks differently. There are too many different answers on how to use it on the net, usually using xaml code behind (not that this implementation is further from that). Any insight would be much appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T21:17:32.770", "Id": "518578", "Score": "0", "body": "Just a tip: for filtering I prefer `ICollectionView.Filter`. Something like [this](https://docs.microsoft.com/en-us/dotnet/desktop/wpf/controls/how-to-group-sort-and-filter-data-in-the-datagrid-control?view=netframeworkdesktop-4.8)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T11:09:28.433", "Id": "518607", "Score": "0", "body": "I do use them in a sort in my data filtering, although the solution above is only to show or hide columns in a datagrid. No data filtering there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T11:16:40.647", "Id": "518608", "Score": "0", "body": "Ah, ok. To show/hide a column you may just set Width=0 to the column, either through Converter. Just an option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:56:31.520", "Id": "518619", "Score": "0", "body": "That's one way, but you still need a whole mechanism to do it. Probably a type to hold the Column Name and a show/hide boolean and a converter. Problem with that is that it means you can't use it while AutoGeneratedColumns=True, so you must set each column binding yourself and add the binding to visibility manually for every datagrid in your app. Also, setting the width to 0, makes it hard to show the column back again with unknown width." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:11:36.850", "Id": "518623", "Score": "0", "body": "_hard to show the column back again with unknown width._ Why? `DataTrigger` would do it for you. `<DataTrigger Binding=\"{Binding MyProperty,RelativeSource=...}\" Value=\"True\"><Setter Property=\"Width\" Value=\"0\"/></DataTrigger>`, but I agree that it doesn't completely solve the issue but makes possible to simplify the solution...probably, i didn't try it with autogenerated columns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:55:38.203", "Id": "518633", "Score": "1", "body": "Alright, I see what you meant now. I still believe it would be hard to implement for auto generated columns without behaviors. But thanks, I'll keep it in mind.\nI just expanded the solution above, to use the list of columns to populate the columns on the datagrid in case of autogeneratedcolumns is false and no columns were custom created in xaml." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T16:09:13.960", "Id": "262725", "Score": "2", "Tags": [ "c#", "wpf", "xaml" ], "Title": "WPF DataGrid Column FIltering using Behaviors" }
262725
<p>I have several Dao classes, including a UserDao, below. The DAOs have many methods, but I'm focussing on <code>deleteUser</code>:</p> <pre><code>@Override public boolean deleteUser(Connection connection,String login) throws MySQLEXContainer.MySQLDBExecutionException, SQLException { int rowNum = 0; Connection con; PreparedStatement statement = null; try { String query = QueriesUtil.getQuery(&quot;deleteUser&quot;); con = connection; statement = con.prepareStatement(query); statement.setString(1, login); rowNum = statement.executeUpdate(); } catch (SQLException e) { LOGGER.error(e); throw new MySQLEXContainer.MySQLDBExecutionException(&quot;Bad execution&quot;,e); }finally { ConnectionUtil.oneMethodToCloseThemAll(null ,statement,null); } return rowNum &gt; 0; } </code></pre> <p>Test class for that Dao:</p> <pre><code>class MySQLUserDaoTest { private Connection connection; private PreparedStatement preparedStatement; private UserDao userDao; private ResultSet resultSet; @BeforeEach void init() throws SQLException { userDao = new MySQLUserDao(); preparedStatement = mock(PreparedStatement.class); connection = mock(Connection.class); resultSet = mock(ResultSet.class); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); } @Test void deleteUser() throws SQLException, MySQLEXContainer.MySQLDBExecutionException { String login = &quot;Login&quot;; when(connection.prepareStatement(anyString()).executeUpdate()).thenReturn(1); boolean result = userDao.deleteUser(connection,login); assertTrue(result); } } </code></pre> <p>Am I using Mockito effectively or could my tests be improved?</p>
[]
[ { "body": "<h3>What are you testing?</h3>\n<p>Consider whether or not mocking is really the way you want to go with testing your DAO. Often an integration test / in-memory database test can be simpler / more aligned with the way the DAO changes.</p>\n<p>If you do want to go down the mocking approach, then you need to be clear about what it is you're trying to achieve with the mocks. As it stands, your test is essentially, &quot;When I call <code>deleteUser</code>, deleteUser<code>should return</code>true<code>&quot;. There's some </code>when` mocking setup, to help that happen.</p>\n<p>Things <strong>you aren't testing</strong> (which you may or may not care about):</p>\n<ul>\n<li>That a statement is actually prepared</li>\n<li>The statement that is prepared (it could be &quot;drop table users&quot;)</li>\n<li>The parameters that are passed to the statement</li>\n<li>That a prepared statement is actually executed</li>\n<li>What happens if the execution returns values other than 1 (2 and 0 spring to mind)</li>\n<li>The interactions with QueriesUtil / ConnectionsUtil</li>\n<li>What happens if the statement throws an exception</li>\n</ul>\n<h3>Other general feedback</h3>\n<ul>\n<li><p><code>deleteUser</code> is a poor name for a test, it gives me no hint as to what I should expect the test to do, other than it has something to do with deleting users.</p>\n</li>\n<li><p>You create a <code>mock(ResultSet.class)</code>, however it's never used.</p>\n</li>\n<li><p>Your <code>when</code> statement in the test is cluttered which makes it more difficult to read, you could just use the field directly:</p>\n<pre><code>when(preparedStatement.executeUpdate()).thenReturn(1);\n</code></pre>\n</li>\n<li><p>You don't need to declare function level variables that are just copies of function parameters. This just aliases the variable <code>connection</code> to something less specific, and adds noise to the function:</p>\n<pre><code>con = connection;\n</code></pre>\n</li>\n<li><p><code>deleteUser</code> takes a <code>login</code> parameter, is this the userId?</p>\n</li>\n<li><p>You've declared <code>deleteUser</code> as throwing <code>SQLException</code>. It can't unless <code>oneMethodToCloseThemAll</code> throws it (because otherwise you catch and translate it). If <code>oneMethodToCloseThemAll</code> does throw it, do you want to catch and translate that as well?</p>\n</li>\n<li><p>Consider if you want to <code>verify</code> any of your mock calls.</p>\n</li>\n<li><p><code>oneMethodToCloseThemAll</code> looks like it's designed to close multiple things, if they're not null. Consider using <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources</a> instead.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:37:06.693", "Id": "518647", "Score": "0", "body": "I have service class for that Dao so oneMethodToCloseThemAll method will be catched at that layer. Thank for so detailed answer It helped me a lot" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T07:56:40.023", "Id": "518751", "Score": "1", "body": "@DozezQuest `oneMethodToCloseThemAll` is a bad name. It's just a bad pun instead of explaining what it does." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:01:33.940", "Id": "262757", "ParentId": "262726", "Score": "1" } } ]
{ "AcceptedAnswerId": "262757", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T16:14:05.253", "Id": "262726", "Score": "3", "Tags": [ "java", "unit-testing", "database", "jdbc", "junit" ], "Title": "Testing DAO Delete User" }
262726
<h2>Background</h2> <p>I am teaching a course at university level, and have lately been working on creating a home exam for my students. However, the institute has given clear instructions that collaboration is not allowed. In order to comply with this, I saw no other way than to give each student their own variant of the exam (minor changes to numbers, variables etc).</p> <h3>Brief overview</h3> <p>I did it as follows:</p> <ul> <li><p>The exams are generated from a LaTeX document that looks something like the following</p> <pre><code>\documentclass[12p,A4paper]{article} includeSolution = {true} % This locks the seed \ExplSyntaxOn \sys_gset_rand_seed:n {5} \ExplSyntaxOff \begin{document} Lorem Lipsum \end{document} </code></pre> <p>(Do note that the document above is just a sketch of my real document, if you want to compile it you need to comment out the line <code>includeSolution = {true}</code> and add the package <code>xparse</code>)</p> </li> <li><p>Python is then used to access the lines <code>includeSolution = {true}</code> and <code>\sys_gset_rand_seed:n {5}</code> and change them.</p> </li> <li><p>Changing the lines and compiling the LaTeX document generates the new variants of the questions.</p> </li> <li><p>This process is repeated for every student in the course and the resulting pdf's are neatly placed in a seperate subfolder.</p> </li> </ul> <p>The interface for the code is something along the lines of</p> <pre><code>python generate_variants.py -f &quot;test.tex&quot; -n 5 -lf &quot;true&quot; -m 2021 </code></pre> <p>I've tried to add an <code>argparse</code> to explain all the options and how to use them.</p> <h2>Questions</h2> <p>I am really just asking for feedback on my implementation as a whole.</p> <ul> <li>Is the code well written and understandable</li> <li>Does my usage of a class make sense or is there a cleaner implementation?</li> <li>Could be parser for command line arguments have been implemented better?</li> <li>I decided to go for absolute paths using <code>pathlib</code>, but I am not sure if I covered all the corner cases. E.g running the python file from another directory etc</li> <li>would my implementation run on Windows vs Linux vs Mac?</li> </ul> <p><em>If this question is too broad I could try to split it into smaller questions. E.g only asking about the parser</em></p> <h2>Full code</h2> <p><strong>This question is only about the Python portion of the code</strong></p> <pre><code>import re import os import time from pathlib import Path import shutil import sys import argparse LATEXMK = &quot;latexmk -xelatex -shell-escape -pdf -interaction=batchmode&quot; MAX_CHARACTER_WiDTH = 79 SYMBOL = &quot;-=&quot; DELIMITER = &quot;-&quot; INDENT = 2 INDENT_WIDTH = &quot; &quot; INDENT_STR = INDENT_WIDTH * INDENT def regex_2_find(text, regex): return text.strip() + &quot; {&quot; + regex.strip() + &quot;}&quot; DIGITS = r&quot;[0-9]+&quot; BOOLEAN = r&quot;(\btrue|false\b)&quot; SEED_TXT = &quot;sys_gset_rand_seed:n&quot;.strip() SEED_REGEX = re.compile(regex_2_find(SEED_TXT, DIGITS)) SOLUTION_TXT = &quot;includeSolution =&quot; SOLUTION_REGEX = re.compile(regex_2_find(SOLUTION_TXT, BOOLEAN)) def get_terminal_width() -&gt; int: return shutil.get_terminal_size()[0] def get_max_terminal_width(max_width: int = MAX_CHARACTER_WiDTH) -&gt; int: return min(get_terminal_width(), max_width) def line_break( width: int = None, max_width: int = MAX_CHARACTER_WiDTH, symbol: str = SYMBOL ) -&gt; str: if not len(symbol): return &quot;&quot; max_terminal_width = get_max_terminal_width(max_width) width = min(max_terminal_width, width) if width else max_terminal_width repeats, remainder = divmod(width, len(symbol)) linebreak = repeats * symbol + symbol[:remainder] return linebreak def word_wrap( text, width: int = None, indent: int = INDENT, max_width: int = MAX_CHARACTER_WiDTH ) -&gt; str: max_terminal_width = get_max_terminal_width(max_width) width = min(max_terminal_width, width) if width else max_terminal_width indent_width = INDENT_WIDTH * indent lines = [] current_line = &quot;&quot; for word in text.replace(&quot;\n&quot;, &quot;&quot;).split(&quot; &quot;): if len(current_line) + len(word) &gt; width: lines.append(indent_width + current_line.strip()) current_line = word else: current_line += &quot; &quot; + word lines.append(indent_width + current_line.strip()) return &quot;\n&quot;.join(lines) def replace_text_w_regex( file_path: str, compiled_text, regex ) -&gt; None: with open(file_path, &quot;r+&quot;) as f: file_contents = f.read() file_contents = compiled_text.sub(regex, file_contents) f.seek(0) f.truncate() f.write(file_contents) def compile_latex(filename: str, latexmk: str): &quot;&quot;&quot; Runs the compilation for the latex file, example: latexmk -xelatex -shell-escape pdflatex etc &quot;&quot;&quot; compile_command = f&quot;{latexmk} {filename}&quot; os.system(compile_command) def ask_user_2_confirm() -&gt; bool: return input(INDENT_STR + &quot;[yes/no]: &quot;).lower().strip() in [&quot;yes&quot;, &quot;ja&quot;, &quot;ok&quot;, &quot;y&quot;] def replace_suffix(filepath: Path, suffix: str = None) -&gt; Path: return filepath.with_suffix(&quot;&quot;).with_suffix(suffix) class Exam: def __init__( self, filename: str, # Input path for exam directory: str, # Output path for exam students: int, solution: bool = False, latexmk: str = LATEXMK, suffix: str = &quot;.pdf&quot;, multiplier: int = 1, ): self.filename = filename self.path_in = self.get_filepath(filename) self.directory = directory self.students = int(students) self.compiler = latexmk self.suffix = suffix if suffix else self.path_in.suffix self.multiplier = int(multiplier) self.path_out = self.get_dir(self.directory) self.include_solution = solution def get_filepath(self, filename: str = None) -&gt; Path: &quot;&quot;&quot;Checks if filepath exists and creates an absolute path&quot;&quot;&quot; filename = filename if filename else self.filename filepath = Path(filename) if not filepath.is_file(): raise NameError(f&quot;The path '{filepath}' does not exist&quot;) if not filepath.is_absolute(): filepath = Path(Path.cwd(), filepath) return filepath def get_dir(self, filepath=None, directory=None) -&gt; Path: &quot;&quot;&quot;Checks if directory exists, if not it asks to create it&quot;&quot;&quot; filepath = filepath if filepath else self.path_in if isinstance(filepath, str): filepath = Path(filepath) directory = directory if directory else self.directory if not directory: directory = Path(filepath.parent, filepath.stem) elif isinstance(directory, str): directory = Path(directory) elif isinstance(directory, Path): pass else: raise TypeError(f&quot;Expected directory to be of type 'str' or 'Path' got {type(directory)}&quot;) if not directory.is_absolute(): directory = directory.absolute() if not directory.is_dir(): print(f&quot;Looks like: '{output_dir}' is not a directory&quot;) print(&quot;Would you like to create it?&quot;) if ask_user_2_confirm(): os.mkdir(directory) if not output_dir.is_dir(): raise NameError(f&quot;The path '{directory}' does not exist&quot;) return directory def last_modified_pdf(self) -&gt; float: return os.stat(self.path_out).st_mtime def last_modified_tex(self) -&gt; float: return os.stat(self.path_in).st_mtime def last_modified_str(self) -&gt; str: parts = self.path_out.parts root = &quot;&quot;.join(self.path_out.parts[0:2]) path_in_str = f&quot;{self.path_in.name}&quot; if len(parts) &gt; 3: path_out_str = f&quot;{root}/../{self.path_out.name}/&quot; else: path_out_str = f&quot;{self.path_out.name}/&quot; max_path = max(len(path_out_str), len(path_in_str)) modi_path_in = time.ctime(self.last_modified_tex()) modi_path_out = time.ctime(self.last_modified_pdf()) filepath_modified_str = f&quot;Filepath: {path_in_str: &gt;{max_path}} last modified {modi_path_in}&quot; folder_modified_str = f&quot;Folder: {path_out_str: &gt;{max_path}} last modified {modi_path_out}&quot; return INDENT_STR + filepath_modified_str + &quot;\n&quot; + INDENT_STR + folder_modified_str def pdf( self, student_id: int = 1, path_in: Path = None, include_solution: bool = None, suffix: str = None, ) -&gt; str: &quot;&quot;&quot;Generates the output pdf name&quot;&quot;&quot; path_in = path_in if path_in else self.path_in suffix = suffix if suffix else self.suffix suffix = f&quot;.{suffix}&quot; if suffix[0] != &quot;.&quot; else suffix include_solution = include_solution if include_solution else self.include_solution solution_str = DELIMITER + &quot;LF&quot; if include_solution else &quot;&quot; # student_id = student_id if student_id else self.students return f&quot;{path_in.stem}{DELIMITER}{student_id:04d}{solution_str}{suffix}&quot; def create_pdf( self, student_id: int, path_in: Path = None, path_out: Path = None, include_solution: bool = None, compiler: str = None, suffix: str = None, multiplier: int = None, ) -&gt; None: # This is where the student pdfs are generated path_in = path_in if path_in else self.path_in path_out = path_out if path_out else self.path_out include_solution = include_solution if include_solution else self.include_solution suffix = suffix if suffix else self.suffix compiler = compiler if compiler else self.compiler multiplier = multiplier if multiplier else self.multiplier # Updates the seed in the pdf subs = regex_2_find(SEED_TXT, str(multiplier * student_id)) replace_text_w_regex(str(path_in), SEED_REGEX, subs) # Makes sure the pdf includes/excludes the solutions subs = regex_2_find(SOLUTION_TXT, str(include_solution).lower()) replace_text_w_regex(str(path_in), SOLUTION_REGEX, subs) # compiles the LaTeX compile_latex(str(path_in), compiler) # Copies the compiled pdf to another dir input_pdf = replace_suffix(path_in, suffix) output_pdf = Path(path_out, self.pdf(student_id, path_out, include_solution, suffix)) shutil.copy2(input_pdf, output_pdf) def generate_variants( self, students: int = None, filename: str = None, directory: str = None, solution: str = None, latexmk: str = LATEXMK, suffix: str = None, multiplier: int = None, ) -&gt; None: students = students if students else self.students if not filename: filename = self.filename path_in = self.path_in else: path_in = get_filepath(filename) if not directory: path_out = self.path_out else: path_out = self.get_output_dir(directory, filename) suffix = suffix if suffix else self.suffix compiler = latexmk if latexmk else self.compiler multiplier = multiplier if multiplier else self.multiplier linebreak = line_break() if self.last_modified_tex() &gt; self.last_modified_pdf(): generate_pdfs = True else: print(linebreak) print(self.last_modified_str()) print(linebreak) print( word_wrap( &quot;It looks like the solutions / exams have been modified after the last time the tex file was &quot; + &quot;modified. Are you sure you want to regenerate the PDF files?&quot; ) ) generate_pdfs = ask_user_2_confirm() if not generate_pdfs: return for student in range(1, students + 1): print(linebreak) print(INDENT_STR + str(student)) print(linebreak) self.create_pdf( student, path_in, path_out, solution, compiler, suffix, multiplier, ) Path(self.path_out).touch() # makes sure pdfs are updated after tex file def __str__(self): linebreak = line_break() return_str = &quot;\n&quot; + linebreak output_dict = { &quot;Students&quot;: self.students, &quot;Include solution&quot;: self.include_solution, &quot;TEX compiler&quot;: self.compiler, &quot;Output suffix&quot;: self.suffix, &quot;RNG seed multiplier&quot;: self.multiplier, } key_len = max(map(len, output_dict)) for key, val in output_dict.items(): return_str += f&quot;\n{INDENT_STR}{key: &gt;{key_len}}: {val}&quot; return_str += f&quot;\n{linebreak}\n{self.last_modified_str()}\n{linebreak}&quot; return return_str def get_commandline_args(): # Create the parser parser = argparse.ArgumentParser( description=&quot;Generates pdf-variants and places them in a sub directory, -h for help&quot; ) req_grp = parser.add_argument_group(title=&quot;Required&quot;) req_grp.add_argument( &quot;-f&quot;, &quot;--file_name&quot;, required=True, type=str, help=&quot;the path to the tex file&quot; ) parser.add_argument( &quot;-d&quot;, &quot;--directory&quot;, nargs=&quot;?&quot;, default=&quot;&quot;, help=&quot;enter desired output dir. default = dir of tex file&quot;, ) parser.add_argument( &quot;-c&quot;, &quot;--compiler&quot;, type=str, nargs=&quot;?&quot;, default=LATEXMK, help=&quot;which command to run on the tex file. default = &quot; + LATEXMK, ) parser.add_argument( &quot;--suffix&quot;, type=str, nargs=&quot;?&quot;, default=&quot;.pdf&quot;, help=&quot;File ending for the output. default = .pdf&quot;, ) parser.add_argument( &quot;-sol&quot;, &quot;--include_solution&quot;, type=lambda x: (str(x).lower() == &quot;true&quot;), default=False, help=&quot;Boolean value: whether to include solutions or not. default = false&quot; ) parser.add_argument( &quot;-n&quot;, &quot;--students&quot;, type=int, nargs=&quot;?&quot;, default=1, help=&quot;Number of pdfs to generate. default = 1&quot;, ) parser.add_argument( &quot;-m&quot;, &quot;--multiplier&quot;, type=int, nargs=&quot;?&quot;, default=1, help=&quot;Number to multiply the seed generation with, common to use exam year. default = 1&quot;, ) return parser # Temporary fix YOU SHOULD RUN THE FILE FROM COMMANDLINE ARGUMENTS = [ &quot;file_name&quot;, &quot;directory&quot;, &quot;students&quot;, &quot;compiler&quot;, &quot;include_solution&quot;, &quot;suffix&quot;, &quot;multiplier&quot; ] DEFAULTS = [&quot;&quot;, &quot;&quot;, LATEXMK, &quot;false&quot;, 1, &quot;.pdf&quot;, 1] def main(): command_args = get_commandline_args() # if len(sys.argv) &gt; 1: args = command_args.parse_args() # print(args) tek2021 = Exam( args.file_name, args.directory, args.students, args.include_solution, args.compiler, args.suffix, args.multiplier, ) # else: # Temporary fix removed, might add option to run from file alter # print(&quot;&quot;) # args = [] # for index, option in enumerate(ARGUMENTS): # user_input = input(f&quot;{option}: &quot;) # if option in [&quot;students&quot;, &quot;multiplier&quot;]: # user_input = int(user_input) # args.append(user_input if user_input else DEFAULTS[index]) # Tek2021 = Exam(*args) print(tek2021) tek2021.generate_variants() if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T00:36:31.997", "Id": "518583", "Score": "2", "body": "You're brave using tex. I would have used html." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T00:39:51.230", "Id": "518584", "Score": "0", "body": "Lines 250-252 will not interpret. You've missed two `self.` references for those methods, and `directory` and `filepath` are not defined - perhaps `directory` also missing a `self.`, and for `filepath` I have no idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:05:03.173", "Id": "518620", "Score": "4", "body": "It's allowed (and encouraged) to edit a question for correctness - so long as that's done before any answers are submitted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T20:59:06.430", "Id": "518720", "Score": "0", "body": "@Reinderien I've updated the code to be able to be run without any command line interface, but I really do not think this is desirable as this throws the entire help portion of the code out the window =) I've also fixed the missing `self` arguments. I will remove my previous comments to clean up the comment section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T22:27:09.493", "Id": "518721", "Score": "0", "body": "I haven't used Tex since the dark ages, but I think you could pass in a seed as a command line argument and then use `\\rand` to generate random but reproducible exam variants. Put the seed on the exam variant, just in case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T04:03:48.923", "Id": "518737", "Score": "0", "body": "There is no way to pipe anything into LaTeX unfortunately. I could have split the file upon finding the desired lines, instead of regexing the same lines over and over again sure. However, this is blazingly fast compared to compiling the LaTeX files. And again this is not a question about the LaTeX portion of the code ^^ If you wanted to see how my (old) exam files in LaTeX actually looks see https://pastebin.com/BiQ10Qe5 and for a particular problem https://pastebin.com/wDYcPXFv (not compilable due to heaps of custom packages unfortunately)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T14:31:18.180", "Id": "518857", "Score": "0", "body": "This still doesn't run. You have a handful of undefined symbols, including `args`, `directory`, `filepath`, and `output_dir`. These are made obvious by any self-respecting IDE; are you using one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T16:15:47.750", "Id": "518871", "Score": "0", "body": "@Reinderien I ran the file through pycharm until it stopped giving me errors, seems something still got messed up when adding the add hoc method of running the file without the cmd. I've rolled back this file, and scrutinized the file for missing symbols. I've truly done my best to make sure the file runs smoothly (it runs fine here, so it is hard to pinpoint where the error or). Nevertheless, if it still fails to runI will look into it again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T16:31:13.503", "Id": "518873", "Score": "0", "body": "Would it not be simpler to abstractly define variable parametrized tasks and in the first step generate texts of all/many variations and then in a second step LaTeX docs. Also with respect to generating solutions. _(Love TeX.)_" } ]
[ { "body": "<p>OK. You still have undefined symbols but I'm going to push on.</p>\n<ul>\n<li>For your function signatures, consider PEP484 type hints. You've done this on, for example, <code>get_max_terminal_width</code> but not <code>regex_2_find</code></li>\n<li><code>get_terminal_size</code> returns a 2-tuple. Rather than <code>[0]</code>, unpacking to <code>columns, lines = get_terminal_size()</code> is I think clearer.</li>\n<li>You've written <code>word_wrap</code> yourself; but have you read about <a href=\"https://docs.python.org/3/library/textwrap.html\" rel=\"nofollow noreferrer\">textwrap</a>?</li>\n<li><code>f.seek(0) / f.truncate()</code> should be equivalent to <code>f.truncate(0)</code>.</li>\n<li>For <code>[&quot;yes&quot;, &quot;ja&quot;, &quot;ok&quot;, &quot;y&quot;]</code> consider using a set instead. If I were you I'd simplify this to <code>.lower().startswith('y')</code>.</li>\n<li>The first <code>with_suffix</code> in <code>.with_suffix(&quot;&quot;).with_suffix(suffix)</code> is redundant; it's a replacement and not an append operation</li>\n<li>For your <code>raise NameError(f&quot;The path '{filepath}' does not exist&quot;)</code>, <code>FileNotFoundError</code> would be more appropriate. Similarly, <code>raise TypeError(f&quot;Expected directory...</code> is not what <code>TypeError</code> is for.</li>\n<li><code>output_dir</code> in <code>print(f&quot;Looks like: '{output_dir}' is not a directory&quot;)</code> is (still) undefined. I'm not joking :) <code>get_filepath</code> is (still) similarly undefined.</li>\n<li><em>enter desired output dir. default = dir of tex file</em> is a lie. It does not default to the directory of the tex file: it defaults to a <em>new</em> directory whose name is based on the stem of the tex file.</li>\n<li>For so many reasons, don't use <code>os.system()</code>; prefer <code>subprocess</code>. When I ran this, <code>latexmk</code> failed because <code>perl</code> was not found, but this failure was glossed over and execution continued when it should not have. You may be tempted to use <code>subprocess</code> with <code>shell=True</code> but don't do this either, due to security reasons. Ask for an absolute directory to <code>latexmk</code>, or maybe look into <code>getenv('PATH')</code> and do a heuristic search for the usual suspects.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T16:58:41.783", "Id": "518875", "Score": "0", "body": "I used `with_suffix(\"\")` because `with_suffix` is actually not a replacement but an addition despite what the name suggests so `Path(\"temp.txt\").with_suffix(\".pdf\")` will return `Path(temp.txt.pdf)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T16:59:37.743", "Id": "518876", "Score": "0", "body": "Are you absolutely sure? `Path('foo.txt').with_suffix('.bar') > WindowsPath('foo.bar')`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T17:16:59.703", "Id": "518881", "Score": "0", "body": "I am absolute sure I am wrong ;-) However there is something worse with my implementation. `with_suffix` only replaces the _last suffix_. In addition all suffixes are not possible only `pdf` or `dvi`, similarly the input file must be a `tex` file so some additional checks are needed, woops.. I forgot to comment away the actual compilation using `latexmk` as I can't expect a review having TeX installed on their system, but i'll switch it to `pdflatex` just in case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T17:22:19.900", "Id": "518883", "Score": "1", "body": "No worries :) Feel free to take a stab at these issues and seek another round of review in a subsequent question. I'm actually curious to see some realistic output, even if it means installing a small tex instance locally." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T16:51:21.133", "Id": "262858", "ParentId": "262728", "Score": "1" } } ]
{ "AcceptedAnswerId": "262858", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T17:44:51.780", "Id": "262728", "Score": "7", "Tags": [ "python-3.x", "object-oriented", "regex", "console" ], "Title": "Stop cheating on home exams using python" }
262728
<p>I am running an IoT fleet, and the need for checking the empty disk usage space has increased.</p> <p>So I am using the following python code.</p> <p>In addition to best practices, efficiency, readability, pythonic, etc. I would love you to share your thoughts about: Is it compliance with: &quot;Robert Martin Single Responsibility Principle&quot; I tried to be consistent and divide my script functions in a logical matter.</p> <pre><code>import os from psutil import disk_usage import sys import logging import subprocess THRESHOLD_PERCENTAGE = 50 # Defining logger def make_logger(): log = logging.getLogger(__name__) log.setLevel(logging.INFO) formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s') handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) log.addHandler(handler) return log def display_disk_usage(): disk = disk_usage(os.path.realpath('/')) logger.info(&quot;Total disk space: %d GiB&quot; % (disk.total // (2 ** 30))) logger.info(&quot;Used disk space: %d GiB&quot; % (disk.used // (2 ** 30))) logger.info(&quot;Free disk space: %d GiB&quot; % (disk.free // (2 ** 30))) logger.info(&quot;Used disk percentage: %d&quot; % disk.percent + '%') return disk.percent def disk_usage_threshold(in_use_disk_percentage): if in_use_disk_percentage &lt; THRESHOLD_PERCENTAGE: return 'Disk usage is under the threshold level' logger.warning(f'\nWarning your disk usage above the threshold it is {in_use_disk_percentage}% full') ask_user_for_action = input('If you wish to delete logs and local postgres data print &quot;yes&quot;\n') if ask_user_for_action == 'yes': clean_disk_usage() logger.info('clean disk usage') else: logger.info(f'Be careful your disk usage is {in_use_disk_percentage}%') def clean_disk_usage(): # Stop docker and PM2 logger.info('\nStopping Dockers and PM2 processes\n') subprocess.run('sudo sh /home/pi/Desktop/speedboatBox/scripts/stop_speedboatbox.sh', shell=True, capture_output=True, check=True) logger.info('\nDeleting log.out directory\'s content ...\n') subprocess.run('sudo truncate -s 0 /home/pi/Desktop/log.out', shell=True, capture_output=True, check=True) logger.info('\nDeleting local postgres data-base ...\n') try: subprocess.run('sudo sh /home/pi/Desktop/speedboatBox/postgresql_service/delete_db.sh', shell=True, capture_output=True) except subprocess.CalledProcessError as e: logger.info(e) display_disk_usage() # Start dockers and PM2 processes logger.info('\nStarting dockers and PM2 processes ...\n') subprocess.run('sudo sh /home/pi/Desktop/speedboat/scripts/start_speedboatbox.sh', shell=True, capture_output=True, check=True) if __name__ == '__main__': logger = make_logger() in_use_disk_percentage = display_disk_usage() disk_usage_threshold(in_use_disk_percentage) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T18:38:55.743", "Id": "518569", "Score": "2", "body": "FYI, [tag:python-2.x] says: \"Do not mix this tag with the python-3.x tag\" and [tag:python-3.x] says: \"Do not mix this tag with the python-2.x tag.\" Please pick a version, or if the program is intended to work in both environments, remove both and maybe mention that intent in the post text. Thanks." } ]
[ { "body": "<p>Overall not bad! You've managed to avoid many of the &quot;usual suspects&quot; when it comes to Python scripting practices.</p>\n<ul>\n<li><code>make_logger</code> could use a return typehint</li>\n<li><code>display_disk_usage</code>, trivially modified to accept a mountpoint path, would be a more flexible implementation</li>\n<li><code>display_disk_usage</code> is doing two things: displaying (what it says on the tin), and calculating and returning (not what it says on the tin). Separate out the <code>disk_usage</code> call, and instead accept a disk instance.</li>\n<li><code>disk_usage_threshold</code> either returns what looks to be a warning string, or <code>None</code>. This function has a number of problems:\n<ul>\n<li>The return value, as a string, is not useful - replace it with a boolean and let the caller decide whether to print a warning. Or better yet return nothing at all, since you don't actually use the return value.</li>\n<li><em>Be careful your disk usage is</em> sounds like a <code>logger.warning</code>, not <code>logger.info</code></li>\n<li>The function would be better-called <code>check_disk_usage_threshold</code> - there needs to be a verb somewhere</li>\n</ul>\n</li>\n</ul>\n<p>This:</p>\n<pre><code>logger.info('\\nDeleting log.out directory\\'s content ...\\n')\n</code></pre>\n<p>should use a double-quoted string so that you don't have to escape the inner single quotes.</p>\n<p>This:</p>\n<pre><code>except subprocess.CalledProcessError as e:\n logger.info(e)\n</code></pre>\n<p>should likely be logged at level <code>error</code>.</p>\n<p>This:</p>\n<pre><code>subprocess.run('sudo sh /home/pi/Desktop/speedboatBox/scripts/stop_speedboatbox.sh', shell=True, capture_output=True,\n</code></pre>\n<p>is troublesome for a number of reasons:</p>\n<ul>\n<li>You're asking to capture output, but then discarding it. Consider at least logging it. If it's too noisy, demote it to logging level <code>debug</code></li>\n<li>Don't hard-code absolute paths. This path should be parametric or at least extracted to a constant.</li>\n<li>System-level scripts should NOT exist in the <code>/home</code> directory.</li>\n<li><code>shell=True</code> has vulnerabilities. Best to use <code>shell=False</code> and call into a specific executable instead.</li>\n</ul>\n<p>This:</p>\n<pre><code>/home/pi/Desktop/log.out\n</code></pre>\n<p>similarly should not be hard-coded and should not live in <code>/home</code>, instead going in <code>/var/log</code>.</p>\n<p>This:</p>\n<pre><code>/home/pi/Desktop/speedboatBox/postgresql_service\n</code></pre>\n<p>is a thoroughly ruinous place to install PostgreSQL, if that's what this is.</p>\n<p>Broadly: think of <code>/home</code> as a human person's desktop. If all of the files in it were to be deleted, the computer - with no human files - should still be able to run your software. Unix has a standard directory layout - <code>/var</code> for logs and runtime files, <code>/etc</code> for config, etc. Part of making this script robust and secure will be following this layout.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:29:10.907", "Id": "518704", "Score": "0", "body": "Truly beneficial !!!!\nI would be happy if you could elaborate for me on those issues:\n1. what is the proper type hint return value for ```make_looger``` function.\nshould it looks like that:\n```# Defining logger\ndef make_logger(): -> str```\n```Don't hard-code absolute paths. This path should be parametric or at least extracted to a constant.```\nI have to know why it is a bad thing. Is it for keeping the code DRY? or for some other reason ??\n```shell=True has vulnerabilities.``` Isn't just another way to use subprocess and not to pass the arguments has a list, what is the core diff" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T21:59:47.077", "Id": "262736", "ParentId": "262729", "Score": "5" } }, { "body": "<p>First, some minor issues:</p>\n<ul>\n<li><code>logger</code> is a global variable, and all your functions are completely dependent on it being present -- and if you <code>import</code> this file it won't be. You may want to create the logger outside the <code>if __name__ == '__main__':</code> block, or pass the logger around as a parameter, or have your functions call <code>logging.getLogger(__name__)</code> themselves</li>\n<li>When logging disk usage percentage, you're using the <code>%</code> operator to format the message but then concatenating another string onto it. Including the percent sign in the format string like <code>&quot;Used disk percentage: %d%%&quot;</code> feels more natural</li>\n<li>How does the stop script act if the processes it's supposed to stop aren't running? Is it correct to restart them even if they weren't running before you did the cleanup?</li>\n<li>In case truncating the log file fails, the restart script doesn't run. Maybe you should use <code>try</code>/<code>finally</code> to make sure the restart script runs even if one of the cleanup actions throws an exception?</li>\n<li>Why <code>sudo sh {script}</code> instead of just <code>sudo {script}</code>? Are you <em>sure</em> the scripts will always be sh scripts?</li>\n<li>I don't think you need to have &quot;Warning&quot; at the start of the warning message -- you seem to have configured the logger to print the message level before each message anyway, so you'd end up with &quot;WARNING - Warning your disk usage...&quot;</li>\n</ul>\n<p>When <code>disk_usage_threshold</code> returns early, it returns a string, which is then discarded. When it doesn't, it returns <code>None</code>. This feels weird -- returning nothing is fine, returning some useful information is good. But pick an approach and commit to it so the caller has some idea what to do</p>\n<p>Your <code>display_disk_usage</code> function is a bit odd. It fetches all kinds of disk usage information, but discards almost all of it -- what if the caller wants more of it? It also kind of has two responsibilities -- to get disk usage information, and to log it. Those feel like two separate steps, and should be handled accordingly -- in one place you call that function to get the data, and the logging is a nice side benefit, in another you call it only for the logging and discard the data entirely, and that makes its usage feel inconsistent</p>\n<p><code>clean_disk_usage</code> is very tightly coupled to your system, with hard-coded absolute paths into a user's home folder. If that's where those scripts live you might need to have those paths in the code <em>somewhere</em>, sure, but if you turn those paths into parameters of the <code>clean_disk_usage</code> function (and maybe even command-line parameters of the program itself), you get a lot more flexibility</p>\n<p>On a related note, your start script isn't in the same location as the stop script. Maybe there's a reason for that, but it looks like it might be a typo, so I'm pointing it out just in case</p>\n<p>Finally, your subprocesses raise some questions about your file structure in general</p>\n<ul>\n<li>Who is meant to run this program anyway? If it's <code>pi</code>, why do they need <code>sudo</code> to access files in their own home directory? And why is some other user's processes modifying those files -- or if <code>pi</code> owns those processes, why do they use <code>sudo</code> to stop and restart them? If this program isn't meant to be run by <code>pi</code> at all, well that raises different questions</li>\n<li>Is this data even user-specific? If so, why are we only concerned with <code>pi</code>'s copy? If not, why is it in a user's home directory?</li>\n<li>Even if this data really is user-specific, who's putting it on the <em>desktop</em>? They seem to be generated by other programs, and I'd usually expect those to put things somewhere like <code>$XDG_CACHE_DIR</code> or <code>$XDG_DATA_HOME</code>, and those typically don't point to locations under <code>~/Desktop</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:45:12.010", "Id": "518683", "Score": "4", "body": "`logger` being a global upon which all of a module's functions depend is pretty typical. So yes: I think the one option you proposed, initializing it outside of the main guard, is the right way to go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T20:01:34.760", "Id": "518714", "Score": "0", "body": "would be happy to know if I got the point of ```Your display_disk_usage function is a bit odd.```\nwould that be a better way to approach it?\n\n\n\n`def get_disk_usage_info(mount_point_path='/'):\n return disk_usage(os.path.realpath(mount_point_path))\n\n\n\ndef log_disk_usage_info():\n logger.info(\"Total disk space: %d GiB\" % (disk_info.total // (2 ** 30)))\n logger.info(\"Used disk space: %d GiB\" % (disk_info.used // (2 ** 30)))\n logger.info(\"Free disk space: %d GiB\" % (disk_info.free // (2 ** 30)))\n logger.info(\"Used disk percentage: %d%%\" % disk_info.percent)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:12:43.213", "Id": "262771", "ParentId": "262729", "Score": "3" } } ]
{ "AcceptedAnswerId": "262771", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T17:50:13.217", "Id": "262729", "Score": "7", "Tags": [ "python", "python-3.x", "status-monitoring" ], "Title": "Python script for alerting disk usage and take action if needed" }
262729
<p>A while back, I answered <a href="https://stackoverflow.com/questions/62111137/deserialize-a-binary-tree-breadth-first-in-functional-programming">this question</a> on Stack Overflow that involved deserializing a binary tree breadth-first using functional programming (the question itself isn't relevant). I'd like to make sure that I'm following functional programming principles and whether or not this is stack-safe. I'd also like to know if I can make my code more performant, less bloated, clearer, etc. If it helps, the question provides <a href="https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-" rel="nofollow noreferrer">this link</a> to explain the algorithm.</p> <p>I first defined this rather simple tree type. Every child is an instance of <code>Node</code>, and the absence of a left or right child is denoted with <code>Empty</code>.</p> <pre class="lang-scala prettyprint-override"><code>sealed trait Tree[+T] case class Node[+T](data: T, left: Tree[T], right: Tree[T]) extends Tree[T] case object Empty extends Tree[Nothing] </code></pre> <p>And this trait that represents a function that takes the current list of serialized items (every item is an <code>Option</code>, with <code>None</code> meaning there is no child). It consumes one or more of these items and returns the rest, along with an <code>Either</code>, where a <code>Right</code> contains a fully built tree, and a <code>Left</code> contains another <code>RecFun</code> that will later consume more items to finish building the current tree.</p> <pre class="lang-scala prettyprint-override"><code>trait RecFun[T] extends (List[Option[T]] =&gt; (List[Option[T]], Either[RecFun[T], Tree[T]])) </code></pre> <p>The entry point is <code>makeTree</code>. First, a <code>RecFun</code> is made using <code>createRec</code> below, and the recursive helper inside <code>makeTree</code> starts processing the tree from there.</p> <pre class="lang-scala prettyprint-override"><code>def makeTree[T](list: List[Option[T]]): Tree[T] = { def helper(f: RecFun[T], l: List[Option[T]]): Tree[T] = f(l) match { case (_, Right(tree)) =&gt; tree case (next, Left(f)) =&gt; helper(f, next) } list match { case Some(x) :: tail =&gt; helper(createRec(x), tail) case _ =&gt; Empty } } </code></pre> <p><code>createRec</code> takes the value of the root node of a subtree, and makes a <code>RecFun</code> to continue building it.</p> <pre class="lang-scala prettyprint-override"><code>def createRec[T](data: T): RecFun[T] = { //No more children, so return a Right with a node whose children are Emptys case None :: Nil | Nil =&gt; (Nil, Right(Node(data, Empty, Empty))) //There's a left child, but no right child to be had, so return here too case Some(l) :: Nil =&gt; (Nil, Right(Node(data, Node(l, Empty, Empty), Empty))) case lo :: ro :: rest =&gt; //Possible left child :: possible right child :: rest of the items //Return the rest, and an Either depending on what lo and ro are (rest, (lo, ro) match { case (Some(l), Some(r)) =&gt; //Both children exist, so wait for both of them before building the tree Left(waitForChildren(data, createRec(l), createRec(r))) case (Some(l), None) =&gt; //Need to wait only for left child Left(waitForChild(Node(data, _, Empty), createRec(l))) case (None, Some(r)) =&gt; //Need to wait only for right child Left(waitForChild(Node(data, Empty, _), createRec(r))) //Both children don't exist, so build tree and return right now case (None, None) =&gt; Right(Node(data, Empty, Empty)) }) } </code></pre> <p>This helper simply combines functions that build a tree where the root's value is known, but the children are not.</p> <pre class="lang-scala prettyprint-override"><code>//Here, both the children need to be deserialized and have their own RecFuns def waitForChildren[T](data: T, leftF: RecFun[T], rightF: RecFun[T]): RecFun[T] = input =&gt; { //Attempt to deserialize the left child first val (next, res) = leftF(input) res match { //If it succeeded, use waitForChild to wait for the right child case Right(tree) =&gt; (next, Left(waitForChild(Node(data, tree, _), rightF))) //Otherwise, try to deserialize the right child, then run the new left RecFun leftF2 again case Left(leftF2) =&gt; { val (next2, res2) = rightF(next) //Return the rest of the list, along with the new RecFun (next2, Left(res2 match { //If the right child is constructed, wait for the left child to be constructed case Right(tree) =&gt; waitForChild(Node(data, _, tree), leftF2) //Otherwise, run leftF2 first, then the new right RecFun rightF2 case Left(rightF2) =&gt; waitForChildren(data, leftF2, rightF2) })) } } } </code></pre> <p>Here, one child is known, and we're just waiting for another.</p> <pre class="lang-scala prettyprint-override"><code>/** * @param ctor Function that takes a child and finishes building parent tree * @param f Function to construct child */ def waitForChild[T](ctor: Tree[T] =&gt; Node[T], f: RecFun[T]): RecFun[T] = input =&gt; { //Try deserializing the child based on the function f val (next, res) = f(input) (next, res match { //If it's fully built, build the parent tree by applying ctor to it case Right(tree) =&gt; Right(ctor(tree)) //Otherwise, wait for the new RecFun case Left(recFun) =&gt; Left(waitForChild(ctor, recFun)) }) } </code></pre> <p>Here is the code I used for testing:</p> <pre class="lang-scala prettyprint-override"><code>val tree = Node( 1, Node(2, Node(3, Node(5, Empty, Empty), Empty), Node(4, Empty, Empty)), Empty ) val tree2 = makeTree(List(Some(1), Some(2), None, Some(3), Some(4), Some(5), None)) println(tree2) assert(tree == tree2) </code></pre> <p><a href="https://scastie.scala-lang.org/sNxnUMZUS6Cout7KZCYHIA" rel="nofollow noreferrer">Here</a> is a Scastie.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T18:56:46.333", "Id": "262730", "Score": "2", "Tags": [ "functional-programming", "scala", "binary-tree" ], "Title": "Deserialize a binary breadth-first in functional programming" }
262730
<p>I want to sort object list named schedules according to arrivalT. if arrivalT is equal, I want to sort according to burst, if arrivalT and bursT both equal I want to sort according to id. Is my custom comparitor implementaion correct?</p> <pre><code>from functools import cmp_to_key class Pair: def __init__(self, id, arrivalT, burstT): self.id = id self.arrivalT = arrivalT self.burstT = burstT def compare(p1, p2): if p1.arrivalT &lt; p2.arrivalT: return -1 elif p1.arrivalT &lt; p2.arrivalT: return 1 else: if p1.burstT &lt; p1.burstT: return -1 elif p1.burstT &gt; p2.burstT: return 1 else: if p1.id &lt; p2.id: return -1 elif p1.id &gt; p2.id: return 1 n = len(id) schedules = [] for i in range(n): schedules.append(Pair(id[i], arrival[i], burst[i])) schedules = sorted(schedules, key = cmp_to_key(compare)) for i in schedules: print(i.id, i.arrivalT, i.burstT) id =[1, 2, 3, 4] arrival = [2, 0, 4, 5] burst = [3, 4, 2, 4 ] shortestJobFirst(id, arrival, burst) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T20:04:41.593", "Id": "518572", "Score": "2", "body": "In terms of correctness insofar as correct results, you need to be at least somewhat confident that your implementation is correct before this is eligible for review. The purpose of review isn't to validate correctness, it's to talk about how well-structured the implementation is, standards adherence, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T07:16:59.363", "Id": "518593", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<h1>Tips and changes</h1>\n<ol>\n<li><p>Python has a style guide <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> which explains in excruciating detail how to structure your code. I whole heartily recommend skimming through it and follow it.</p>\n<p>For instance <code>shortesJobFirst(id, arrival, burst)</code> <em>appears</em> (it is hard to know) to be a function, but functions in python are - according to PEP 8 - written in lowercase seperated by underscores. E.g <code>shortesJobFirst -&gt; shortest_job_first</code>. However if <code>shortesJobFirst</code> is a class, you are good =)</p>\n</li>\n<li><p>You should use the <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == &quot;__main__&quot;:</code></a> module in your answer.</p>\n</li>\n<li><p>Your naming practices are somewhat lacking, what does <code>Pair</code> mean? A better name would perhaps have been <code>Job</code>.</p>\n</li>\n<li><p>It is tough suggesting better names, as you lack a short explanation of what your code does. This is done by using <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a></p>\n</li>\n<li><p>The printing could be improved by using <a href=\"https://pyformat.info/\" rel=\"nofollow noreferrer\">pythons awesome formating options</a></p>\n</li>\n<li><p>Why use a class at all when a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple()</code></a> can do the same job?</p>\n</li>\n<li><p>Why implement a sorting function when you can use <code>attrgetter</code> from <a href=\"https://docs.python.org/3/library/operator.html\" rel=\"nofollow noreferrer\"><code>operators</code></a>?</p>\n</li>\n<li><p>Use a basic linter for your code, this ensures you have correct spacings and indents. As mentioned it is common to have two spaces between classes and functions.</p>\n</li>\n</ol>\n<h1>Improvements</h1>\n<pre><code>from collections import namedtuple\nfrom operator import attrgetter\n\n\ndef sort_jobs_by_attributes(jobs, attributes):\n &quot;&quot;&quot;\n This functions sorts the jobs (namedtuples) according to the attribute_lst. If\n\n attribute_lst = [&quot;arrival_time&quot;, &quot;burst_time&quot;, &quot;id&quot;]\n\n We then first sort by arrival_time, on tie we\n sort by burst_time, on tie we\n sort by id\n &quot;&quot;&quot;\n for attribute in reversed(attributes):\n jobs.sort(key=attrgetter(attribute))\n return jobs\n\n\nJOB_ATTRIBUTES = [&quot;arrival_time&quot;, &quot;burst_time&quot;, &quot;id&quot;]\nJob = namedtuple(&quot;Job&quot;, JOB_ATTRIBUTES)\n\n\nif __name__ == &quot;__main__&quot;:\n\n job_ids = [1, 2, 3, 4]\n arrival_times = [4, 1, 4, 1]\n burst_times = [3, 4, 2, 4]\n\n jobs = [\n Job(*job_details) for job_details in zip(arrival_times, burst_times, job_ids)\n ]\n\n sort_jobs_by_attributes(jobs, JOB_ATTRIBUTES)\n\n for job in jobs:\n print(job)\n</code></pre>\n<p><strong>Side note:</strong> you don't need to provide any key function. The default behavior of tuples (and by extension, namedtuples, since they are a subclass) is to sort element-wise. That means that the first elements of the two tuples are compared, and if there's a tie then the second elements are compared, and so on. Since the name is the first element, all you need is <code>sorted(jobs)</code>.</p>\n<pre><code>from collections import namedtuple\n\nJOB_ATTRIBUTES = [&quot;arrival_time&quot;, &quot;burst_time&quot;, &quot;id&quot;]\nJob = namedtuple(&quot;Job&quot;, JOB_ATTRIBUTES)\n\n\nif __name__ == &quot;__main__&quot;:\n\n job_ids = [1, 2, 3, 4]\n arrival_times = [4, 1, 4, 1]\n burst_times = [3, 4, 2, 4]\n job_details = [arrival_times, burst_times, job_ids]\n\n jobs = sorted(\n Job(*details) for details in zip(*job_details)\n )\n\n for job in jobs:\n print(job)\n</code></pre>\n<p>Note that implicitly sorting the tuple can be a bit spooky if you later decide the change around the order. In addition to make it harder to see <em>exactly</em> what is being sorted. I will leave it up to you to make the final call on which version is the best.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T21:57:42.517", "Id": "518580", "Score": "0", "body": "This is a good review. Can be done in one sort call, if so inclined: `sort(key = lambda j: tuple(getattr(j, a) for a in attributes))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T22:09:40.820", "Id": "518581", "Score": "0", "body": "@FMc good comment. In fact you do not need any keys ;-) See the edit above." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T21:26:17.683", "Id": "262734", "ParentId": "262732", "Score": "3" } }, { "body": "<p>As suggested in another review, you could write a specific function to sort the\nobjects as you like in this one use case. Or you could package these objects up\nas <code>namedtuple</code> instances, and just sort them directly. But you might not want\nto convert to <code>nametuple</code> (maybe your class needs some other behaviors). In\nthat case, you have a few options.</p>\n<p>One is to use a <code>dataclass</code> and arrange the attributes in the order than you\nwant sorting to occur. This approach is similar to the <code>nametuple</code> strategy in\nthe sense that you must declare the attributes in the desired sorting-order.</p>\n<pre><code>from dataclasses import dataclass\n\n@dataclass(frozen = True, order = True)\nclass Job:\n arrivalT: int\n burstT: int\n id: int\n</code></pre>\n<p>Another option is to define the <code>__lt__()</code> method in the class, so that\nPython's built-in sorting functions can compare the objects directly.</p>\n<pre><code>@dataclass(frozen = True)\nclass Job:\n id: int\n arrivalT: int\n burstT: int\n\n def __lt__(self, other):\n return (\n (self.arrivalT, self.burstT, self.id) &lt;\n (other.arrivalT, other.burstT, other.id)\n )\n</code></pre>\n<p>Or if you need more flexibility at runtime, you could write a general purpose\nfunction to allow you to sort any objects based on any combination of\nattributes. This approach would make more sense in situations where you don't\nknow in advance how things should be sorted.</p>\n<pre><code>@dataclass(frozen = True)\nclass Job:\n id: int\n arrivalT: int\n burstT: int\n\ndef attrs_getter(*attributes):\n return lambda x: tuple(getattr(x, a) for a in attributes)\n\n# Usage example.\njobs = [Job(1, 4, 3), Job(2, 1, 4), Job(3, 4, 2), Job(4, 1, 4)]\njobs.sort(key = attrs_getter('arrivalT', 'burstT', 'id'))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T07:35:36.153", "Id": "518595", "Score": "0", "body": "Great answer! I particularly liked hooking into `__lt__`. I just want to mention that my first snippet works perfectly fine using a class as well. I just found it convinient in this case to switch to a named tuple =)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T23:52:18.783", "Id": "262737", "ParentId": "262732", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T20:01:31.923", "Id": "262732", "Score": "0", "Tags": [ "python" ], "Title": "Is my custom operator for sorting in python correct?" }
262732
<p>I have turned a &quot;classic&quot; Bootstrap form into a &quot;floating labels&quot; form.</p> <p>For this purpose, I had to <strong>move the labels below the form controls</strong>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.form-control:focus { box-shadow: none !important; border-color: #c4c4c4 !important; } .with-floating-label { position: relative; } .with-floating-label label { position: absolute; top: 10px; padding: 0 3px; background: #fff; left: 0.75rem; margin: 0 0 0 -2px; font-size: inherit; line-height: 1; opacity: 0; transition: opacity 0.2s ease-in-out, top 0.3s ease-in-out; } .with-floating-label input:not(:-moz-placeholder-shown)+label, .with-floating-label textarea:not(:-moz-placeholder-shown)+label { top: -6px; font-size: 12px; opacity: 1; } .with-floating-label input:not(:-ms-input-placeholder)+label, .with-floating-label textarea:not(:-ms-input-placeholder)+label { top: -6px; font-size: 12px; opacity: 1; } .with-floating-label input:not(:placeholder-shown)+label, .with-floating-label textarea:not(:placeholder-shown)+label { top: -6px; font-size: 12px; opacity: 1; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="container"&gt; &lt;div class="card my-2"&gt; &lt;div class="card-header"&gt;Register&lt;/div&gt; &lt;div class="card-body"&gt; &lt;form method="POST" action="http://mysite.com/register" novalidate autocomplete="off"&gt; &lt;input type="hidden" name="token" value="O4SZD63ujSDWUQNj6u2Q8LsC6HDQdhMZwjAW128x"&gt; &lt;div class="form-group with-floating-label"&gt; &lt;input id="username" type="text" placeholder="Username" class="form-control" name="username" value=""&gt; &lt;label for="username" class="text-muted"&gt;Username&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group with-floating-label"&gt; &lt;input id="first_name" type="text" placeholder="First name" class="form-control" name="first_name" value=""&gt; &lt;label for="first_name" class="text-muted"&gt;First name&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group with-floating-label"&gt; &lt;input id="last_name" type="text" placeholder="Last name" class="form-control" name="last_name" value=""&gt; &lt;label for="last_name" class="text-muted"&gt;Last name&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group with-floating-label"&gt; &lt;input id="email" type="email" placeholder="Email address" class="form-control" name="email" value=""&gt; &lt;label for="email" class="text-muted"&gt;Email address&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group with-floating-label"&gt; &lt;input id="password" placeholder="Password" type="password" class="form-control" name="password"&gt; &lt;label for="password" class="text-muted"&gt;Password&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group with-floating-label"&gt; &lt;input id="password-confirm" placeholder="Confirm Password" type="password" class="form-control" name="password_confirmation"&gt; &lt;label for="password-confirm" class="text-muted"&gt;Confirm Password&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group mb-0"&gt; &lt;button type="submit" class="btn btn-block btn-primary"&gt;Register&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h4>Questions/concerns:</h4> <ol> <li>Does this change affect security?</li> <li>Are there any usability issues?</li> <li>Are there any other ways it can be improved?</li> </ol>
[]
[ { "body": "<ol>\n<li>I don't see anything worrying about security;</li>\n<li>Regarding usability it looks pretty good too;</li>\n<li>Since you are using <code>placeholders</code> instead of <code>labels</code> I would remove all <code>labels</code> and work only with <code>inputs</code>. Like this:</li>\n</ol>\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-css lang-css prettyprint-override\"><code>.form-control {\n margin-bottom: 1rem;\n}\n\n.form-control:focus {\n box-shadow: none !important;\n border-color: #c4c4c4 !important;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" /&gt;\n\n&lt;div class=\"container\"&gt;\n &lt;div class=\"card my-2\"&gt;\n &lt;div class=\"card-header\"&gt;Register&lt;/div&gt;\n &lt;div class=\"card-body\"&gt;\n &lt;form method=\"POST\" action=\"http://mysite.com/register\" novalidate autocomplete=\"off\"&gt;\n &lt;input type=\"hidden\" name=\"token\" value=\"O4SZD63ujSDWUQNj6u2Q8LsC6HDQdhMZwjAW128x\"&gt;\n &lt;div class=\"form-group\"&gt;\n &lt;input id=\"username\" type=\"text\" placeholder=\"Username\" class=\"form-control\" name=\"username\" value=\"\"&gt;\n &lt;input id=\"first_name\" type=\"text\" placeholder=\"First name\" class=\"form-control\" name=\"first_name\" value=\"\"&gt;\n &lt;input id=\"last_name\" type=\"text\" placeholder=\"Last name\" class=\"form-control\" name=\"last_name\" value=\"\"&gt;\n &lt;input id=\"email\" type=\"email\" placeholder=\"Email address\" class=\"form-control\" name=\"email\" value=\"\"&gt;\n &lt;input id=\"password\" placeholder=\"Password\" type=\"password\" class=\"form-control\" name=\"password\"&gt;\n &lt;input id=\"password-confirm\" placeholder=\"Confirm Password\" type=\"password\" class=\"form-control\" name=\"password_confirmation\"&gt;\n &lt;button type=\"submit\" class=\"btn btn-block btn-primary\"&gt;Register&lt;/button&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T13:39:29.977", "Id": "263144", "ParentId": "262733", "Score": "1" } } ]
{ "AcceptedAnswerId": "263144", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T20:13:28.277", "Id": "262733", "Score": "2", "Tags": [ "css", "form", "twitter-bootstrap" ], "Title": "Bootstrap form with floating labels" }
262733
<p>first post here. I'm looking for some general input as to the correctness of what I'm trying to do here. Is this a good idea, bad idea, what could be plus points or negative aspects to this design?</p> <p>If this is not the right forum for this question please advise where is best, thanks :)</p> <p>What I'm envisioning is using the Parse Back4App database as a &quot;master database event log&quot; which would act as a master database change log for any user accounts connected to one database. Full databases are stored with Hive on client devices. Any changes made are pushed to the server as log events. These will be read by client devices as instructions for any local database changes that need to be made so all databases stay in sync. This will be a last to write wins design. This database would be auto-deleting for data older than say every 3 months to ensure all users are updated and so that the data transfer doesn't get too large.</p> <p>My code is a bit messy as I haven't refactored too much so please bear with that. I'm simply looking for advice as to if this is a good idea or not, and any other advice as per first paragraph.</p> <p>Secondly (possibly this part belongs in SO) but if anyone wants to make general suggestions for my encryption issue please see the readMe file under MAJOR ISSUE on GitHub.</p> <p>Example database log with create &amp; delete actions logged. <a href="https://i.stack.imgur.com/EH0k5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EH0k5.png" alt="Example database log" /></a></p> <p><a href="https://github.com/SexyBeast007/service_database_sync" rel="nofollow noreferrer">FULL PROJECT</a></p> <p><em><strong>Book model</strong></em></p> <pre><code>import 'package:hive/hive.dart'; part 'book_model.g.dart'; @HiveType(typeId: 0) class Book { @HiveField(0) String title; @HiveField(1) String author; @HiveField(2) DateTime publishingDate; @HiveField(3) DateTime dateAdded; @HiveField(4) DateTime lastModified; Book({ this.title, this.author, this.publishingDate, this.dateAdded, this.lastModified, }); @override String toString() { return ''' title: $title author: $author publishingDate: $publishingDate dateAdded: $dateAdded lastModified $lastModified '''; } Book.fromJson(Map&lt;String, dynamic&gt; json) : title = json['title'], author = json['author'], publishingDate = json['publishingDate'], dateAdded = json['dateAdded'], lastModified = json['lastModified']; Map&lt;String, dynamic&gt; toJson() =&gt; { 'title': title, 'author': author, 'publishingDate': publishingDate, 'dateAdded': dateAdded, 'lastModified': lastModified }; } </code></pre> <p><em><strong>Database sync item model</strong></em></p> <pre><code>import 'book_model.dart'; import 'package:hive/hive.dart'; part 'database_sync_model.g.dart'; @HiveType(typeId: 1) class DatabaseSyncItem { @HiveField(0) Book previousBookValue; @HiveField(1) Book updatedBookValue; @HiveField(2) DateTime dateAdded; @HiveField(3) DateTime lastModified; @HiveField(4) DatabaseAction entryAction; DatabaseSyncItem({ this.previousBookValue, this.updatedBookValue, this.dateAdded, this.lastModified, this.entryAction, }); @override String toString() { return ''' previousValue: $previousBookValue updatedValue: $updatedBookValue dateAdded: $dateAdded lastModified: $lastModified entryAction: $entryAction '''; } // Turn json back into data model DatabaseSyncItem.fromJson(Map&lt;String, dynamic&gt; json) : previousBookValue = json['previousBookValue'], updatedBookValue = json['updatedBookValue'], dateAdded = json['dateAdded'], lastModified = json['lastModified'], entryAction = json['entryAction']; // Turn data model into json Map&lt;String, dynamic&gt; toJson() =&gt; { 'previousBookValue': previousBookValue, 'updatedBookValue': updatedBookValue, 'dateAdded': dateAdded, 'lastModified': lastModified, 'entryAction': entryAction, }; } enum DatabaseAction { create, update, delete, } </code></pre> <p><em><strong>Local database services</strong></em></p> <pre><code>import 'package:hive/hive.dart'; import 'package:service_database_sync/models/book_model.dart'; import 'package:service_database_sync/services/server_database_services.dart'; class ClientDatabaseServices { final String hiveBox = 'book_box'; List&lt;Book&gt; _bookList = []; Book _activeBook; ServerDatabaseServices parseAction = ServerDatabaseServices(); /// /// CREATE EVENT /// // Add book to database &amp; update list Future&lt;void&gt; addBook(Book newBook) async { var box = await Hive.openBox&lt;Book&gt;(hiveBox); await box.add(newBook); _bookList = box.values.toList(); await parseAction.logCreateEvent(newBook); } /// /// READ EVENTS /// // Send database items to list Future&lt;void&gt; _databaseToRepository() async { var box = await Hive.openBox&lt;Book&gt;(hiveBox); _bookList = box.values.toList(); } // Return list for use Future&lt;List&lt;Book&gt;&gt; getBookList() async { await _databaseToRepository(); return _bookList; } // Getter for list List&lt;Book&gt; get bookList =&gt; _bookList; // Return specific book Book getBook(index) { return _bookList[index]; } // Return list length int get bookCount { return _bookList.length; } // Get active book Book getActiveBook() { return _activeBook; } // Set active book void setActiveBook(key) async { var box = await Hive.openBox&lt;Book&gt;(hiveBox); _activeBook = box.get(key); } /// /// UPDATE EVENT /// // Updates specific book with new data void editBook({Book book, int bookKey}) async { var box = await Hive.openBox&lt;Book&gt;(hiveBox); await box.put(bookKey, book); _bookList = box.values.toList(); _activeBook = box.get(bookKey); } /// /// DELETE EVENTS /// // Deletes specific book and updates list Future&lt;void&gt; deleteBook(key) async { var box = await Hive.openBox&lt;Book&gt;(hiveBox); await parseAction.logDeleteEvent(box.getAt(key)); await box.deleteAt(key); _bookList = box.values.toList(); } // Empties hive box for database reset Future&lt;void&gt; deleteAll() async { var box = await Hive.openBox&lt;Book&gt;(hiveBox); await box.clear(); } } </code></pre> <p><em><strong>Server database services</strong></em></p> <pre><code>import 'package:parse_server_sdk/parse_server_sdk.dart'; import 'package:service_database_sync/models/book_model.dart'; import 'package:service_database_sync/models/database_sync_model.dart'; class ServerDatabaseServices { // Server app keys &amp; data final keyApplicationId = 'jVrkUb6tvSheT4NHqGuF9FtFDtQkmqS3pJbKRyLN'; final keyClientKey = 'MFYPnwLM1d38TtG2523YXxMQ4lCZdX9maovSjrdu'; final keyParseServerUrl = 'https://parseapi.back4app.com'; // String values String previousBookValue = 'previousBookValue'; String updatedBookValue = 'updatedBookValue'; String dateAdded = 'dateAdded'; String entryAction = 'entryAction'; String lastModified = 'lastModified'; /// /// /// CREATION LOG EVENT Future&lt;void&gt; logCreateEvent(Book book) async { final createEvent = DatabaseSyncItem( previousBookValue: null, updatedBookValue: book, dateAdded: book.dateAdded, entryAction: DatabaseAction.create, lastModified: DateTime.now(), ); final toServer = ParseObject('Event') ..set(previousBookValue, createEvent.previousBookValue) ..set(updatedBookValue, createEvent.updatedBookValue.toJson()) ..set(dateAdded, createEvent.dateAdded) ..set(entryAction, createEvent.entryAction.toString()) ..set(lastModified, createEvent.lastModified); await toServer.save(); } /// /// /// UPDATE LOG EVENT Future&lt;void&gt; logEditEvent(Book previousValue, Book updatedValue) async { updatedValue.lastModified = DateTime.now(); final editEvent = DatabaseSyncItem( previousBookValue: previousValue, updatedBookValue: updatedValue, dateAdded: previousValue.dateAdded, entryAction: DatabaseAction.update, lastModified: DateTime.now(), ); final toServer = ParseObject('Event') ..set(previousBookValue, editEvent.previousBookValue.toJson()) ..set(updatedBookValue, editEvent.updatedBookValue.toJson()) ..set(dateAdded, editEvent.dateAdded) ..set(entryAction, editEvent.entryAction.toString()) ..set(lastModified, editEvent.lastModified); await toServer.save(); } /// /// /// DELETE LOG EVENT Future&lt;void&gt; logDeleteEvent(Book book) async { book.lastModified = DateTime.now(); final deleteEvent = DatabaseSyncItem( previousBookValue: book, updatedBookValue: null, dateAdded: book.dateAdded, entryAction: DatabaseAction.delete, lastModified: DateTime.now(), ); final toServer = ParseObject('Event') ..set(previousBookValue, deleteEvent.previousBookValue.toJson()) ..set(updatedBookValue, deleteEvent.updatedBookValue) ..set(dateAdded, deleteEvent.dateAdded) ..set(entryAction, deleteEvent.entryAction.toString()) ..set(lastModified, deleteEvent.lastModified); await toServer.save(); } } </code></pre> <p><em><strong>Main</strong></em></p> <pre><code>import 'dart:io'; import 'package:hive/hive.dart'; import 'package:parse_server_sdk/parse_server_sdk.dart'; import 'package:service_database_sync/data/books_hardcoded.dart'; import 'package:service_database_sync/models/book_model.dart'; import 'package:service_database_sync/services/client_database_services.dart'; import 'package:service_database_sync/services/server_database_services.dart'; Future&lt;void&gt; main(List&lt;String&gt; arguments) async { Hive.init('hive_database'); Hive.registerAdapter(BookAdapter()); await Parse().initialize( ServerDatabaseServices().keyApplicationId, ServerDatabaseServices().keyParseServerUrl, clientKey: ServerDatabaseServices().keyClientKey, debug: true, ); await addBooksToLibrary(); sleep(Duration(seconds: 5)); await deleteSpicificBook(2); } Future&lt;void&gt; addBooksToLibrary() async { final bookDatabaseActions = ClientDatabaseServices(); await bookDatabaseActions.addBook(bookOne); await bookDatabaseActions.addBook(bookTwo); await bookDatabaseActions.addBook(bookThree); await bookDatabaseActions.addBook(bookFour); } Future&lt;void&gt; deleteSpicificBook(int index) async { final bookDatabaseActions = ClientDatabaseServices(); await bookDatabaseActions.deleteBook(index); } Future&lt;void&gt; deleteAllBooks() async { final bookDatabaseActions = ClientDatabaseServices(); await bookDatabaseActions.deleteAll(); } void printBookLibrary() async { final bookDatabaseActions = ClientDatabaseServices(); final box = await Hive.openBox&lt;Book&gt;(bookDatabaseActions.hiveBox); final books = box.values; print(books); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T21:48:08.640", "Id": "262735", "Score": "1", "Tags": [ "database", "server", "dart", "parse-platform" ], "Title": "Parse Back4App database as a master database change log rather than actual database- thoughts on this design principle?" }
262735
<p>I've just written this to facilitate my Wget downloads and I was wondering if anyone can review it for me.</p> <pre><code>@ECHO off CLS IF [%1] == [] GOTO missing_arg IF [%2] == [] GOTO missing_arg IF NOT EXIST %2% GOTO bad_dir ECHO About to download %1 to %2 ECHO. PAUSE CLS CD /d &quot;%2&quot; wget64 --execute robots=off --mirror --reject-regex '.*forum.*' --convert-links --adjust-extension --page-requisites --no-parent --progress=bar --no-check-certificate --show-progress --refer=http://google.com --user-agent=&quot;Mozilla/5.0 Firefox/4.0.1&quot; %1 rundll32.exe cmdext.dll,MessageBeepStub ECHO Download complete GOTO end :missing_arg rundll32.exe cmdext.dll,MessageBeepStub ECHO Correct syntax is &quot;WGET &lt;URL&gt; &lt;&quot;Local Dir&quot;&gt;&quot; GOTO end :bad_dir rundll32.exe cmdext.dll,MessageBeepStub ECHO Unable to find local directory for download - please check your input. :end </code></pre> <p>Note: &quot;Wget.bat&quot; is the name of the above batch file in order to differentiate it from the actual program &quot;Wget64.exe&quot; which is called by the batch.</p> <p>Please let me know what you think.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T06:35:52.237", "Id": "518744", "Score": "1", "body": "Looks good in overall. I'd only remove `pause`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T22:23:13.577", "Id": "518907", "Score": "0", "body": "`rundll32.exe cmdext.dll,MessageBeepStub` - how many motherboards have speakers these days?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T03:46:31.527", "Id": "518972", "Score": "0", "body": "@Michael Harvey Try it - on a modern system it redirects through the Windows audio system to produce a standard audio alert." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T03:49:27.977", "Id": "518973", "Score": "0", "body": "@ipx Thanks for that - much appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T06:59:26.553", "Id": "518984", "Score": "0", "body": "@PiHard - doesn't on mine (Windows 10 21H1) using Windows Default sound scheme." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-13T04:37:26.927", "Id": "519113", "Score": "1", "body": "@MichaelHarvey Interesting - of course I can't speak for your system, but it does on mine, which has the same version." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T06:06:34.330", "Id": "262743", "Score": "3", "Tags": [ "windows", "batch" ], "Title": "Batch file for Wget downloads" }
262743
<p>(<a href="https://codereview.stackexchange.com/questions/262658/tcp-chat-room-in-python-3">Previous question</a>)</p> <p>I've created a server file, that keeps waiting for clients. When someone connects to the server, he can send messages to the server, and from the server it is broadcasted to all clients.</p> <p>Can you criticize my simple chat? Any possible improvements and changes are welcome. I have 2 classes and 2 objects files:</p> <p><strong>Server class:</strong></p> <pre class="lang-py prettyprint-override"><code> import threading import socket class Server: def __init__(self): self.host = str(socket.gethostbyname(socket.gethostname())) self.port = 5050 self.server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.server.bind((self.host,self.port)) self.server.listen(6) self.text_coding = &quot;utf-8&quot; #encoding and decoding format self.text_length = 30 #max bytes of the messages self.clients = [] #stores each client reference self.names = [] #stores clients names? self.disconnect = str(&quot;$hutdown&quot;) #safe word to close the connection and leave the chat #This function sends everyone message to everyone (including the one who send) def broadcast(self,msg): for i in self.clients: i.send(msg.encode(self.text_coding)) #This function removes current client name and reference from the lists above #And warns the server and all clients that the current client left def closing_client(self,client,name): self.clients.remove(client) self.names.remove(name) self.broadcast(f&quot;{name} left the chat.&quot;) print(f&quot;{name} left the chat.&quot;) #Each client has his own thread of this function #This function takes each client message, to send to broadcast(). def handle_client(self,client_reference,client_info,name): print(f&quot;Connected with {name}, {client_info}&quot;) while True: try: message0 = client_reference.recv(self.text_length).decode(self.text_coding) message = str(message0) #when someone uses the key word to leave the chat if message == str(f&quot;{name}: {self.disconnect}&quot;): self.closing_client(client_reference,name) break else: self.broadcast(message) except Exception as error: print(&quot;=================&quot;) print(error.__cause__) print(&quot;=================&quot;) self.closing_client(client_reference,name) break client_reference.close() #This functions waits for new client #And creates threads(of handle_client function) for each client def wait_new_client(self): while True: client_reference,client_info = self.server.accept() name = client_reference.recv(self.text_length).decode(self.text_coding) self.names.append(name) self.clients.append(client_reference) client_reference.send(str(f&quot;Welcome {name}.&quot;).encode(self.text_coding)) self.broadcast(str(f&quot;{name} joined the chat.&quot;)) thread = threading.Thread(target=self.handle_client, args=[client_reference,client_info,name]) thread.start() </code></pre> <p><strong>Server file:</strong></p> <pre class="lang-py prettyprint-override"><code>from Server import Server print(&quot;Starting server...&quot;) server0 = Server() print(&quot;=====================&quot;) print(f&quot;Server is listening at {server0.host}&quot;) server0.wait_new_client() </code></pre> <p><strong>Client class:</strong></p> <pre class="lang-py prettyprint-override"><code>import socket import threading class Client: def __init__(self,name): self.name = name self.server_ip = &quot;192.168.1.6&quot; self.server_port = 5050 self.text_lenght = 30 self.disconnect = str(&quot;$hutdown&quot;) self.text_coding = &quot;utf-8&quot; self.state = True self.client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.client.connect((self.server_ip,self.server_port)) self.client.send(self.name.encode(self.text_coding)) #This function waits for chat messages def chat_messages(self): while self.state: try: message = self.client.recv(self.text_lenght).decode(self.text_coding) print(message) except Exception as error: print(&quot;=================&quot;) print(error.__cause__) print(&quot;=================&quot;) self.client.close self.state = False #This function waits for user input, new message def write(self): while self.state: try: text = str(input(&quot;Digit a message: &quot;)) message = str(f&quot;{self.name}: {text}&quot;) self.client.send(message.encode(self.text_coding)) if text == self.disconnect: self.state = False except Exception as error: print(&quot;=================&quot;) print(error.__cause__) print(&quot;=================&quot;) self.client.close self.state = False #This function put the above functions on threads. def start(self): try: chat_messages_thread = threading.Thread(target=self.chat_messages) write_thread = threading.Thread(target=self.write) chat_messages_thread.start() write_thread.start() except Exception as error: print(&quot;=================&quot;) print(error.__cause__) print(&quot;=================&quot;) self.client.close self.state = False </code></pre> <p><strong>Client file:</strong></p> <pre class="lang-py prettyprint-override"><code>from Client import Client name = str(input(&quot;Type your name: &quot;)) client0 = Client(name) client0.start() </code></pre>
[]
[ { "body": "<p>There are a few things I'd like to point out</p>\n<h2>The Server class</h2>\n<ul>\n<li>It would be nice to be able to tell the server to listen on a different port, presumably by making the <code>Server</code> class' constructor take the port number as a parameter</li>\n<li>When you have a pair of lists that need to be kept in sync, it's often better to have a list of pairs instead. But in this case, clients presumably have unique names, so it might be nice to enforce that by having <code>self.clients</code> be a <code>dict</code> mapping names to client references</li>\n<li>In <code>handle_client</code>, you seem to be overusing the <code>str</code> function. It doesn't do any harm, but <code>message0</code> should already be a string after decoding so <code>message = str(message0)</code> is unnecessary, and in the <code>if</code> statement the string literal is <em>definitely</em> a string so you can just do <code>f&quot;...&quot;</code> instead of <code>str(f&quot;...&quot;)</code></li>\n<li><code>except Exception</code> is a bit smelly. Like, true, you <em>do</em> want to make sure that everything gets cleaned up properly if something unexpected happens, but usually you have some idea of what might go wrong, and maybe some way to recover from some of those</li>\n<li><code>closing_client</code> is a bit weird -- it removes the client from the list of known client sockets, but it doesn't take any steps to make sure it's closed. That seems like it could easily lead to a resource leak -- is there a reason that method doesn't also close the socket?</li>\n</ul>\n<h2>The client class</h2>\n<ul>\n<li>I feel like the constructor should definitely take the server IP and server port as parameters. Someone might want to connect to a different server</li>\n<li><code>self.state</code> is a bit of a weird name -- it seems to be <code>True</code> when connected to a server and <code>False</code> otherwise, so maybe it could be called <code>connected</code> instead?</li>\n<li>None of the <code>catch</code> blocks actually close the socket -- they just mention the close function, but they don't call it</li>\n<li><code>text_length</code> is misspelled as <code>text_lenght</code></li>\n</ul>\n<h2>The protocol in general</h2>\n<ul>\n<li>There's a bit of an awkward problem where a message containing the text <code>&quot;$hutdown&quot;</code> it literally the same as a <code>$hutdown</code> command. This isn't that big a problem when <code>$hutdown</code> is the only thing that isn't a literal message, but maybe you want to add more commands, maybe even some that are more complex. It could be useful to explicitly distinguish messages so you know that you know what everything's supposed to be</li>\n<li>It feels a bit weird that clients send their own name with each message -- a confused client might find itself unable to properly <code>$hutdown</code>, and a malicious client might try to send a rude message with someone else's name on it (and I don't think this server would notice if someone did -- it only checks names when processing <code>$hutdown</code> commands, right?). The server already knows who's sending the message, so this doesn't seem necessary -- it knows what socket belongs to whom, so if &quot;Taylor&quot;'s socket sends &quot;Hello&quot; the server can figure out that it should broadcast &quot;Taylor: Hello&quot;</li>\n<li>It doesn't seem like anyone actually checks that messages are within the acceptable length. Now, most of the time any data received just gets passed straight through to a different socket or stdout, so it <em>usually</em> isn't a problem. But what if someone's name is <code>MyVeryVeryVeryLongNameIsCool</code>? That's short enough to be accepted as a name, but long enough that <code>MyVeryVeryVeryLongNameIsCool: $hutdown</code> can't fit in a single message, so they can't disconnect properly. Or what if someone sends a message like <code>Sam: It's pronounced with a /ŋ/</code>? The whole message is valid as UTF-8 text, but if you try to decode that in 30-byte chunks you break the <code>ŋ</code> in half and get a <code>UnicodeDecodeError</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T15:23:52.900", "Id": "519094", "Score": "0", "body": "I've been trying to understand your answer. In most part is very clear, but : \n\n\"Or what if someone sends a message like Sam: It's pronounced\nwith a /ŋ/ ? The whole message is valid as UTF-8 text, but if you try to decode that in 30-byte\nchunks you break the ŋ in half and get a UnicodeDecodeError\"\nWhat does it mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T17:00:35.453", "Id": "519097", "Score": "0", "body": "@irtexas19 A byte can only have 256 different values, and there are far more than 256 different characters, so most characters are made up of multiple bytes. For example, when you do `\"\".encode(\"utf8\")` you get four bytes, not just one. If I send you 60 bytes of text and you try to handle them 30 bytes at a time, it's possible that the 30th byte is in the middle of a multi-byte character, and you can't decode just part of a character, so even if my message was valid UTF-8 text when read as a whole, the first 30 bytes on their own might not be" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T19:51:11.163", "Id": "519104", "Score": "0", "body": "So should I make sure that everyone sends exactly 30bytes of message, before encoding it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T11:55:44.083", "Id": "519161", "Score": "0", "body": "@irtexas19 That's an option - if the client expects 30-byte messages, then that's what the client should send. Though another option could be to have messages that include their own lengths, or have some sort of markers that show how long messages are, or where they begin and end, or something like that, so clients and servers can be sure to process complete messages" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:11:46.170", "Id": "262774", "ParentId": "262754", "Score": "2" } } ]
{ "AcceptedAnswerId": "262774", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:22:37.037", "Id": "262754", "Score": "3", "Tags": [ "python-3.x", "socket" ], "Title": "TCP chat room in Python3" }
262754
<p>This is meant to go in a <code>vulkan.hpp</code>-like strongly-typed wrapper for a pure C library.</p> <p>A wrapped enum provides back and forth implicit conversion between itself and the enum, while otherwise behaving as an <code>enum class</code> would.</p> <p>Wrapper utility:</p> <pre><code>#include &lt;type_traits&gt; template &lt;typename EnumT&gt; struct enum_wrapper { using enum_type = EnumT; using wrapped_type = enum_wrapper&lt;EnumT&gt;; enum_wrapper() noexcept = default; ~enum_wrapper() = default; // Implicitly castable from enum_type constexpr enum_wrapper(enum_type val) noexcept : _value(val) {} // Implicitly castable to enum_type constexpr operator enum_type() const noexcept { return _value; } // Because of the implicit conversion, we need to intercept all comparisons // in order to prevent comparing against an unrelated enum. template &lt;typename T&gt; constexpr bool operator&lt;(T rhs) const noexcept { static_assert(is_comparable&lt;T&gt;()); return _value &lt; rhs; } template &lt;typename T&gt; constexpr bool operator&lt;=(T rhs) const noexcept { static_assert(is_comparable&lt;T&gt;()); return _value &lt;= rhs; } template &lt;typename T&gt; constexpr bool operator==(T rhs) const noexcept { static_assert(is_comparable&lt;T&gt;()); return _value == rhs; } template &lt;typename T, std::enable_if_t&lt;std::is_enum_v&lt;T&gt;, int&gt; = 0&gt; constexpr bool operator!=(T rhs) const noexcept { static_assert(is_comparable&lt;T&gt;()); return _value != rhs; } template &lt;typename T&gt; constexpr bool operator&gt;(T rhs) const noexcept { static_assert(is_comparable&lt;T&gt;()); return _value &lt; rhs; } template &lt;typename T&gt; constexpr bool operator&gt;=(T rhs) const noexcept { static_assert(is_comparable&lt;T&gt;()); return _value &lt;= rhs; } private: enum_type _value; template &lt;typename T&gt; static constexpr bool is_comparable() { return std::is_same_v&lt;std::decay_t&lt;T&gt;, enum_type&gt; || std::is_same_v&lt;std::decay_t&lt;T&gt;, enum_wrapper&gt;; } }; template &lt;typename LhsT, typename EnumT&gt; constexpr bool operator&lt;(LhsT lhs, enum_wrapper&lt;EnumT&gt; rhs) noexcept { return rhs &gt; lhs; } template &lt;typename LhsT, typename EnumT&gt; constexpr bool operator&lt;=(LhsT lhs, enum_wrapper&lt;EnumT&gt; rhs) noexcept { return rhs &gt;= lhs; } template &lt;typename LhsT, typename EnumT&gt; constexpr bool operator==(LhsT lhs, enum_wrapper&lt;EnumT&gt; rhs) noexcept { return rhs == lhs; } template &lt;typename LhsT, typename EnumT&gt; constexpr bool operator!=(LhsT lhs, enum_wrapper&lt;EnumT&gt; rhs) noexcept { return rhs != lhs; } template &lt;typename LhsT, typename EnumT&gt; constexpr bool operator&gt;(LhsT lhs, enum_wrapper&lt;EnumT&gt; rhs) noexcept { return rhs &lt; lhs; } template &lt;typename LhsT, typename EnumT&gt; constexpr bool operator&gt;=(LhsT lhs, enum_wrapper&lt;EnumT&gt; rhs) noexcept { return rhs &lt;= lhs; } } </code></pre> <p>Wrapping:</p> <pre><code>extern &quot;C&quot; { enum lib_status { LIB_STATUS_OK = 0, LIB_STATUS_BAD_ARGUMENT = 1, }; typedef enum lib_status lib_status; enum lib_color { LIB_COLOR_RED = 0, LIB_COLOR_GREEN = 1, LIB_COLOR_BLUE = 2, }; typedef enum lib_color lib_color; lib_status lib_foo(lib_color color); } namespace lib { // &lt;insert copy of lib_color documentation&gt; struct color : detail::enum_wrapper&lt;lib_color&gt; { using enum_wrapper::enum_wrapper; color(enum_wrapper rhs) : enum_wrapper(rhs) {} static constexpr wrapped_type red{LIB_COLOR_RED}; static constexpr wrapped_type green{LIB_COLOR_GREEN}; static constexpr wrapped_type blue{LIB_COLOR_BLUE}; }; // &lt;insert copy of lib_status documentation&gt; struct status : detail::enum_wrapper&lt;lib_status&gt; { using enum_wrapper::enum_wrapper; status(enum_wrapper rhs) : enum_wrapper(rhs) {} static constexpr wrapped_type ok{LIB_STATUS_OK}; static constexpr wrapped_type {LIB_STATUS_BAD_ARGUMENT}; }; inline status foo(color in_col) { return lib_foo(in_col); } } </code></pre> <p>Using a wrapped enum:</p> <pre><code>static_assert(std::is_trivial_v&lt;lib::status&gt;); int main() { lib::status success = lib::status::ok; success = LIB_STATUS_OK; success = lib::foo(lib::color::red); success = lib_foo(LIB_COLOR_RED); // if(success == LIB_COLOR_RED) {} // DOES NOT COMPILE // can switch switch(success) { case lib::status::ok: break; case lib::status::bad_argument: break; } // Missing cases are caught: DOES NOT COMPILE // switch(success) { // case lib::status::ok: break; // } // These might look undesirably loose at a glance. // However, this allows using the c++ wrapper with 3rd-party // libraries that only implements a C api. e.g. using glfw() // alongside vulkan.hpp lib_foo(lib::color::green); // Can call C api with wrapper lib::foo(LIB_COLOR_RED); // Can still use the C enum in the C++ api // lib::foo(LIB_STATUS_OK); // DOES NOT COMPILE } </code></pre> <p>See it all on godbolt: <a href="https://gcc.godbolt.org/z/5d6cTPPnb" rel="nofollow noreferrer">https://gcc.godbolt.org/z/5d6cTPPnb</a></p> <p>I'm looking for general feedback and/or potential pitfalls users of the wrapped library could run into.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:30:38.583", "Id": "518669", "Score": "4", "body": "were you aware of the site policy that you are absolutely not, for any reason, supposed to edit the code in a post after it has been answered? Changes made after an answer may cause the answers to appear invalid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:32:23.103", "Id": "518670", "Score": "0", "body": "@Donald.McLean I was not, and I apologize. The only edits I have applied are bringing it in line with the policy that it has to compile, and clarifying intent. But I won't even do that in the future. Thank you very much for the callout. I'm not super familiar with this stackexchange yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:33:55.260", "Id": "518671", "Score": "0", "body": "@Donald I have also rollbacked the changes. Thank you again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:40:05.227", "Id": "518673", "Score": "2", "body": "Not a problem. And actually, you are correct that the code should compile, which is probably the only exception to the rule. If you can make a change that allows the code to compile WITHOUT invalidating anything said in one or more of the posted answers, then you're OK. Normally, people wait until the code is good before answering." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:44:23.733", "Id": "518674", "Score": "0", "body": "@Donald.McLean Aliright, unrollebacked. As mentionned in the comment, the code causing a compilation error was actually part of the demonstration that the feature is working as expected, so it's all a bit confusing" } ]
[ { "body": "<p><code>typedef enum lib_status lib_status;</code><br />\nYou don't need that in a C++ header; the enumeration tag is already a stand-alone type name in C++.</p>\n<p>There is an obligatory commented needed grumbling about the need to define all the relational operators individually due to the need to be compatible with C++(&lt;20). Likewise for defining <code>operator!=</code> after having defined <code>==</code>.</p>\n<p>Check out a library such as <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2</a> for writing the unit tests.</p>\n<p><code>static_assert(std::is_trivial_v&lt;lib::status&gt;);</code><br />\nNice to see you including this... you ought to make it part of the class template, as it should be the case for every use. It's not just for testing.</p>\n<p>The only real safely in your wrapper, from what can tell, is that different strong types are incompatible. So, you should try passing the wrong wrapped type for a parameter (where the argument type is a different strong type, and when the argument type is the wrong C enum type) <a href=\"https://www.codeproject.com/Tips/1247697/Unit-Tests-for-Code-that-is-Supposed-to-Not-Compil\" rel=\"nofollow noreferrer\">causes a compile-time error</a>.</p>\n<p><strong>update:</strong> The original code was very confusing that it contained lines mixed throughout that would not compile, with no indication that they won't. My above paragraph stands to point out that there are ways to include positive &quot;this won't compile&quot; checks in runnable unit tests.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:08:19.633", "Id": "518654", "Score": "0", "body": "\"You don't need that in a C++ header\" This library is explicitely meant as a wrapper around a C library, so it made sense to me that the usage example uses pure C syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:10:49.197", "Id": "518655", "Score": "0", "body": "\"you should try passing the wrong wrapped type\" I think I'm misreading this, isn't that what `lib::foo(LIB_STATUS_OK);` does, correctly failing to compile? Obviously, I can't possibly do anything about `lib_foo(LIB_STATUS_OK)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:12:38.843", "Id": "518656", "Score": "1", "body": "`you ought to make it part of the class template` Woops, copy-paste error. My actual code has an even stricter `static_assert(std::is_enum_v<EnumT>)` as part of the wrapper type. Good eye!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:14:41.817", "Id": "518658", "Score": "0", "body": "\"Check out a library such as Catch2 for writing the unit tests.\" Good advice! My actual library does it with doctest instead, I just wanted a godbolt-friendly version online." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:15:50.500", "Id": "518659", "Score": "0", "body": "@Frank The header only compiles in C++. Adding that typedef does not allow \"pure C syntax\"; in fact it's presence in C source is so you _don't_ have to write the `enum Tag` syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:17:21.870", "Id": "518660", "Score": "0", "body": "I thought it was kind of implicit that everything within the `extern \"C\"{}` block would be `#include`d from a C header. I'll amend the question to clarify that this is just for the sake of example," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:18:11.430", "Id": "518661", "Score": "0", "body": "re `lib::foo(LIB_STATUS_OK)` I missed it on casual reading. I thought this file compiles (as required by Code Review!). It's kind of hard to tell that you're supposed to manually try it and comment it out to run the rest of the tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:19:52.780", "Id": "518662", "Score": "2", "body": "Oh, I see what you mean: you emulated including the C header here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:20:22.090", "Id": "518663", "Score": "0", "body": "Oh, I thought that the requirement was \"behaves as expected\". I'll comment out all non-compiling code, but leave it in the godbolt link so that it not compiling is proven, and not just taken for granted" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:24:51.113", "Id": "518666", "Score": "0", "body": "Another quick comment re. \"you ought to make it part of the class template, as it should be the case for every use. It's not just for testing.\" Unfortunately, the real test is that the wrapper as a whole is trivial, and you can't check that condition on an incomplete type. So just doing it on a representative sample in the unit-test library is as good as it's going to get :(." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:27:48.183", "Id": "518667", "Score": "0", "body": "\"due to the need to be compatible with C++(<20).\" Actually, It is specifically BECAUSE of C++20 that those operators are so important. Otherwise, the compiler takes `lib::color::green == LIB_STATUS_OK` and makes it work via implicit casting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:53:47.510", "Id": "518711", "Score": "0", "body": "In C++20, just implement `operator<=>` for the same effect, rather than implementing all relations individually? Anyway, needs comments to explain like you do in this comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:56:53.953", "Id": "518712", "Score": "0", "body": "If I downloaded a library to use in real life and the unit tests did not compile, I'd suppose that to be a problem not \"expected\". I check-in/publish such things in the commented-out state, and there is another comment on the line indicating that this does not compile by design." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:05:47.293", "Id": "262766", "ParentId": "262755", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:52:16.507", "Id": "262755", "Score": "1", "Tags": [ "c++", "c++17" ], "Title": "Typesafe implicit wrapper for C enums" }
262755
<p>I am rather new to JavaScript and never really worked with promises before. My code works but I would like to learn if there is a better approach?</p> <p>I want to implement the following functionality:</p> <ul> <li>Query DB to check if user is in a team</li> <li>if yes, query DB for items belonging to that team</li> </ul> <p>Both functions return promises.</p> <p>Thanks a lot.</p> <pre class="lang-js prettyprint-override"><code>var AWS = require(&quot;aws-sdk&quot;); var _ = require(&quot;underscore&quot;); AWS.config.update({ region: &quot;ap-southeast-1&quot;, endpoint: &quot;http://localhost:8042&quot;, }); var dynamoDb = new AWS.DynamoDB.DocumentClient(); var userID = &quot;user123&quot;; var teamID = &quot;team456&quot;; function checkUserIsTeamMember(teamID, userID) { return new Promise(function (resolve, reject) { // get team let params = { TableName: &quot;someTable&quot;, ScanIndexForward: true, KeyConditionExpression: &quot;#PK = :PK And begins_with(#SK, :SK)&quot;, ExpressionAttributeValues: { &quot;:PK&quot;: &quot;T#&quot; + teamID, &quot;:SK&quot;: &quot;U#&quot; + userID, }, ExpressionAttributeNames: { &quot;#PK&quot;: &quot;PK&quot;, &quot;#SK&quot;: &quot;SK&quot;, }, }; dynamoDb .query(params) .promise() .then((data) =&gt; { if (data.Count &gt; 0) { resolve(&quot;User is team member.&quot;); } else { reject(&quot;User is not team member.&quot;); } }); }); } function getItems(teamID) { return new Promise(function (resolve, reject) { let params = { TableName: &quot;someTable&quot;, ScanIndexForward: true, IndexName: &quot;GSI2&quot;, KeyConditionExpression: &quot;#PK = :PK And begins_with(#SK, :SK)&quot;, ExpressionAttributeValues: { &quot;:PK&quot;: &quot;T#&quot; + teamID, &quot;:SK&quot;: &quot;I#&quot;, }, ExpressionAttributeNames: { &quot;#PK&quot;: &quot;GSI2PK&quot;, &quot;#SK&quot;: &quot;GSI2SK&quot;, }, }; // check first checkUserIsTeamMember(teamID, userID) .then((data) =&gt; { console.log(data); // resolve another promise resolve(dynamoDb.query(params).promise()); }) .catch((err) =&gt; { console.log(err); // return empty list if user is not authorized (not team member) // not sure if resolving this in the catch block is correct resolve([]); }); }); } getItems(teamID).then((data) =&gt; { console.log(data.Items); }); <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:13:47.790", "Id": "518642", "Score": "1", "body": "Welcome to the Code Review Community. It helps us give a better review when the title indicates what the code does." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:15:34.643", "Id": "262758", "Score": "1", "Tags": [ "node.js", "promise" ], "Title": "Calling promise-returning function within promise-returning function" }
262758
<p>Started learning C# second time. I have written a console program to calculate sum and count of even and odd numbers. Provided code :</p> <pre><code>using System; namespace Studying_ { class Program { static void Main(string[] args) { uint evenNumbersCount = 0; uint oddNumbersCount = 0; int sum = 0; Console.WriteLine(&quot;Enter the first number in the range to find out it odd or even. The program won't count numbers you entered in the sum&quot;); int numberOne = int.Parse(Console.ReadLine()); Console.WriteLine(&quot;Enter the second number&quot;); int numberTwo = int.Parse(Console.ReadLine()); if (numberTwo &lt; numberOne) { int a = numberTwo; numberTwo = numberOne; numberOne = a; } while(numberOne &lt; numberTwo - 1) { numberOne++; int result = numberOne % 2; sum += numberOne; switch (result) { case 0: evenNumbersCount++; break; case 1: oddNumbersCount++; break; } } Console.WriteLine(&quot;Sum - &quot; + sum + &quot; | Even - &quot; + evenNumbersCount + &quot; | Odd - &quot; + oddNumbersCount); Console.ReadKey(); } } } </code></pre> <blockquote> <p>Input : 2, 5<br /> Output : &quot;Sum - 7 | Even - 1 | Odd - 1<br /> 2 and 5 aren't counted</p> </blockquote> <p>Is this code good? Can I improve it or optimize?</p> <p>P.S. Sorry for my english and if I did something off-topic. Let me know if something is wrong.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:52:52.967", "Id": "518632", "Score": "0", "body": "Have you tested the results? The first number will not be counted as you increment it before summing. The second one will be excluded as well. Shouldn't the range be inclusive?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:59:37.300", "Id": "518635", "Score": "0", "body": "Yes, I did, it works as it supposed. I know how to make it counted if I need it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T23:46:25.977", "Id": "518722", "Score": "1", "body": "Just a small thing. Your main routine prompts the user with the string, \"Enter the first number in the range to find out it odd or even...\" That isn't bad and because I can see your code I know what are allowable values. I'd like to suggest you provide the range, something like, \"Enter an integer value from -2147483648 to 2147483647\". Or restrict it for the user to something like \"-10000 to 10000\". Its likely most people would think of integer values, rather than trying to enter something like 3.14159. But, just to prompt them is good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:20:32.520", "Id": "518725", "Score": "0", "body": "Are you interested in simplifications like just counting odd numbers, and then calculating even count as `evens = n - odds` where `n` is the length of the range? Obviously the whole thing here could be reduced to closed-form so you don't need to loop. (Odd and even are both about `n/2`, with adjustments based on the first and last numbers. And Gauss's `n * (n+1)/2` for the sum of 1..n can be adapted for a range, and also done without possible overflow if necessary, like clang does when optimizing a `sum+=i` loop like this. But I'm guessing that these are placeholders for real work.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:21:56.713", "Id": "518726", "Score": "0", "body": "Adding odd numbers can be reduced to `sum += i & 1` if you care to do it that way, taking advantage of the fact that C# (like most languages) uses binary integers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T08:06:26.083", "Id": "518753", "Score": "1", "body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T09:49:40.960", "Id": "518760", "Score": "0", "body": "@Heslacher, thank you, I have read this question on the link. Does it mean that I can just add self-answer with updated code If I want to share it with others? Furthermore, I can just ask new question with updated code, reffering to this one, If I want to know more (Of course it won't be dublicate question)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T09:58:53.947", "Id": "518761", "Score": "0", "body": "A self-answer should be in the form of a code-review and shouldn't just place the updated code and shouldn't repeat what other answerer already posted. A follow-up question would be better if you want the updated code to be reviewed." } ]
[ { "body": "<p>You should try your program whith different values.\nWhen asked for the first number, enter &quot;abcdef&quot;. Hit enter, and see what happens.</p>\n<p>In such a case, when you can't be sure that the string to parse is ok, use int.TryParse(...).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:00:11.527", "Id": "518636", "Score": "0", "body": "Yes, thanks. I know this program will throw exception if I enter \"abcdef\". The question is whether I can improve code somewhere to gain more performance or make better for understanding. Sorry for misunderstanding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:02:53.970", "Id": "518639", "Score": "2", "body": "Will it be better to use `try catch` instead of `TryParse`? If I use `TryParse()`, it will return zero and my calculating will be wrong. Isn't it good to use `try catch` to catch exception and do a warning then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T03:58:26.940", "Id": "518736", "Score": "2", "body": "@JediMan Good question. Try it with `TryParse` and you'll find it actually returns `false`! `TryParse` returns `true` if it is able to parse, and `false` otherwise. That means you can use it in an `if` block and end the program or display an error if the user entered bad input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T08:02:29.150", "Id": "518752", "Score": "0", "body": "@Nate Barbettini, understood and dealed with `TryParse()`, thank you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:48:01.437", "Id": "262761", "ParentId": "262759", "Score": "4" } }, { "body": "<p>The naming could be better. <code>numberOne</code>, <code>numberTwo</code> and <code>result</code> does not tell anything about what these numbers represent. Better <code>rangeStartExclusive</code> and <code>rangeEndExclusive</code>. The <code>...Exclusive</code> makes it clear that the bounds will not be counted.</p>\n<p>I also would use a for-loop. This is the standard way of looping a number range. It also allows us to easily define a loop variable. The problem of incrementing <code>numberOne</code> is that it makes it a range bound and a running variable at the same time. This double role decreases readability.</p>\n<p>Instead of an <code>int</code> result, I would use a Boolean telling its meaning.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>for (int n = rangeStartExclusive + 1; n &lt; rangeEndExclusive; n++) {\n bool isEven = n % 2 == 0;\n if (isEven) {\n evenNumbersCount++;\n } else {\n oddNumbersCount++;\n }\n sum += n;\n}\n</code></pre>\n<p>Alternatively, you could keep your original implementation and instead rename <code>result</code> to <code>remainder</code>.</p>\n<p>It is okay to give our number a non-descriptive name like <code>i</code> or <code>n</code>, often used in math to denote a whole number. <code>i</code> is often used for indexes.</p>\n<p>To keep the declaration and use of <code>isEven</code> close together, I have moved <code>sum += n</code> to the end of the loop. It looks strange if you first calculate <code>result</code>, then calculate an unrelated sum and only then use <code>result</code>.</p>\n<p>Why use <code>uint</code> for the count of even and odd numbers? This count will always be smaller than the range bounds given as <code>int</code>. The maximum <code>uint</code> is about the double of the maximum <code>int</code>.</p>\n<p>However, the sum could exceed the maximum <code>int</code>. The sum of all whole numbers starting at 1 and up to <code>n</code> is <code>n * (n + 1) / 2</code>. When starting counting at 1, this limits the maximum number at 65,535. Therefore, it would make sense to use <code>long</code> for the sum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:31:24.807", "Id": "518646", "Score": "0", "body": "Is there some advantages to use `if` instead of `switch`? In my opinion, `switch` is more readeable here. Or is it so because `switch` requires more performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:39:22.967", "Id": "518648", "Score": "0", "body": "The main reason was to be able to give the variable `result` the name `isEven`. You could also name it `remainder` instead and keep the original code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:06:04.053", "Id": "518723", "Score": "2", "body": "In traditional / pseudo-code 1-letter var names, `n` is most often used for loop upper bounds, with `i`, `j`, or `k` as a counter. It's not totally weird to use `n` as the loop counter / induction variable, but it's more common and idiomatic IMO for `n` to be loop invariant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:11:55.243", "Id": "518724", "Score": "1", "body": "Another advantage of `n % 2 == 0` is that this way works for negative odd numbers. @JediMan's switch would only count positive odd numbers, because `-5 % 2 == -1` not +1. Probably a good idea to mention that correctness reason along with stylistic reasons in this answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T12:42:03.233", "Id": "518766", "Score": "0", "body": "@PeterCordes, The reason I have chosen `n` is that while it is used as loop variable, this is not its primary intent. We want to perform a mathematical analysis (even/odd) on this number. For this purpose `n` is good. Maybe a more consequent approach would be to use `i` as loop variable and to pass it over to a method doing the math part as a parameter named `n`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:19:58.213", "Id": "262763", "ParentId": "262759", "Score": "7" } }, { "body": "<p>You already have answers, but lets add one more for learning purpose. This is another way of doing the same thing. Not a better way, just an alternative one to showcase some C# features. If you feel a bit overwhelm, it is normal. You don't have to know everything and nobody expect you to do. If you have any questions, feel free to post them in comment. I will be more than happy to answer them :)</p>\n<p>We will use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples\" rel=\"nofollow noreferrer\">tuple</a>, <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct\" rel=\"nofollow noreferrer\">tuple's deconstruction</a>, <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/linq/\" rel=\"nofollow noreferrer\">linq</a>, <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">interpolated string</a>, <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.lookup-2?view=net-5.0\" rel=\"nofollow noreferrer\">lookup</a>, <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator\" rel=\"nofollow noreferrer\">lambda operator</a> and more. Take the time to read the docs above, there are a lot of things going on below. Here we go:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n \npublic class Program\n{\n public static (int, int) SumCount(IEnumerable&lt;int&gt; source) =&gt; (source.Sum(), source.Count());\n\n public static (int, int, int) SumCount2(IEnumerable&lt;int&gt; source, Func&lt;int, bool&gt; predicate)\n {\n var results = source.ToLookup(predicate);\n var (evenSum, evenCount) = SumCount(results[true]);\n var (oddSum, oddCount) = SumCount(results[false]);\n return (evenSum + oddSum, evenCount, oddCount);\n }\n\n public static IEnumerable&lt;int&gt; RangeWithoutStart(int start, int end) =&gt; Enumerable.Range(start + 1, end - start - 1);\n\n public static void Main()\n {\n var start = 2;\n var end = 6;\n var range = RangeWithoutStart(start, end);\n var (sum, evenCount, oddCount) = SumCount2(range, x =&gt; x % 2 == 0);\n Console.WriteLine($&quot;Sum - { sum } | Even - { evenCount } | Odd - {oddCount}&quot;);\n }\n}\n</code></pre>\n<p><a href=\"https://dotnetfiddle.net/gQcoSI\" rel=\"nofollow noreferrer\">Try it Online</a></p>\n<p>The current implementation of <code>SumCount</code> will loop twice into <code>source</code>, we can reduce to one by using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-5.0\" rel=\"nofollow noreferrer\"><code>Aggregate</code></a>:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public static (int, int) SumCount(IEnumerable&lt;int&gt; source) =&gt; source.Aggregate((0, 0), (a, b) =&gt; (a.Item1 + b, a.Item2 + 1));\n</code></pre>\n<p>Learning concept:</p>\n<ul>\n<li>Beside <code>Main()</code>, everything is <a href=\"https://en.wikipedia.org/wiki/Pure_function\" rel=\"nofollow noreferrer\">pure</a>.</li>\n<li>We don't <a href=\"https://en.wikipedia.org/wiki/Immutable_object\" rel=\"nofollow noreferrer\">mutate</a> anything.</li>\n<li><code>SumCount2</code> is a <a href=\"https://en.wikipedia.org/wiki/Higher-order_function\" rel=\"nofollow noreferrer\">higher-order function</a>.</li>\n</ul>\n<p>These concepts are keys in <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">Functional Programming</a> but here it shows the beauty of a multi-paradigm language like C#.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:45:04.750", "Id": "518675", "Score": "0", "body": "I think this answer is too advanced for the beginner level of the OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:49:57.580", "Id": "518676", "Score": "2", "body": "@RickDavin I think it is nice to discover new way of doing stuff. I learnt linq by looking at example. I decided to post because I dont think that I am the only person who love to learn by example. I will add a caveat though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:41:17.227", "Id": "518698", "Score": "1", "body": "Thank you very much! This code is a set of symbols and words for me, so it definetily on another level for now) Currently, I'm studying with a course on youtube, but after the end, I promise to have a deal with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:05:08.133", "Id": "518702", "Score": "0", "body": "@JediMan You will have all the time needed. Have fun learning. C# is a great language." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:29:23.210", "Id": "262767", "ParentId": "262759", "Score": "6" } } ]
{ "AcceptedAnswerId": "262763", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T13:16:21.783", "Id": "262759", "Score": "6", "Tags": [ "c#", "beginner" ], "Title": "Calculate sum and count of even and odd numbers" }
262759
<p>A very easily stated problem that has a surprising number of gotchas - return a value that's midway between the two supplied values.</p> <p>Depending on the types given, we need to be aware of</p> <ul> <li>arithmetic overflow and underflow</li> <li>infinities</li> <li>NaNs</li> <li>rounding</li> </ul> <p>For pointers and iterators, the mean only makes sense if the values point into the same object; the results are otherwise undefined. For forward-only iterators, the arguments need to be in the correct order; for other types, either order is accepted.</p> <p>For aggregate types, we just need to compute the mean element-wise. I've provided code for arrays and complex numbers; third-party aggregates (e.g. &quot;point&quot; and &quot;vector&quot; geometric types) can be implemented by following the existing pattern.</p> <p>I expect the template to work unaltered for other arithmetic classes (e.g. bignum and rational types).</p> <pre><code>#include &lt;cmath&gt; #include &lt;concepts&gt; #include &lt;cstddef&gt; #include &lt;iterator&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; namespace std { template&lt;typename T&gt; class complex; template&lt;typename T, std::size_t N&gt; class array; } namespace _ { template&lt;typename T&gt; concept arithmetic = std::regular&lt;T&gt; &amp;&amp; requires(T a, T b) { a + (b - a); a &lt; b; }; template&lt;arithmetic T&gt; T midpoint(T a, T b) { if (a == b) { // this ensures infinities are correctly returned return a; } if constexpr (std::is_floating_point_v&lt;T&gt;) { if (std::isnan(a)) { return a; } if (std::isnan(b)) { return b; } } if constexpr (std::is_arithmetic_v&lt;T&gt;) { if ((a &lt; 0) != (b &lt; 0)) { return (a + b) / 2; } } if (a &gt; b) { using std::swap; swap(a, b); } return a + (b - a) / 2; } // Non-random-access iterators // a MUST be before b template&lt;std::forward_iterator T&gt; requires (!std::bidirectional_iterator&lt;T&gt;) T midpoint(T a, T b) { bool skip = false; T mid = a; while (a != b) { ++a; if (!skip) { ++mid; } skip = !skip; } return mid; } // Aggregate types follow // Pattern can be extended, e.g. for popular geometry types template&lt;arithmetic T&gt; std::complex&lt;T&gt; midpoint(std::complex&lt;T&gt; a, std::complex&lt;T&gt; b) { return { midpoint(a.real(), b.real()), midpoint(a.imag(), b.imag()) }; } template&lt;arithmetic T, std::size_t N&gt; std::array&lt;T,N&gt; midpoint(const std::array&lt;T,N&gt;&amp; a, const std::array&lt;T,N&gt;&amp; b) { std::array&lt;T,N&gt; result; for (std::size_t i = 0; i &lt; N; ++i) { result[i] = midpoint(a[i], b[i]); } return result; } } using _::midpoint; </code></pre> <h2>// Tests</h2> <pre><code>#include &lt;gtest/gtest.h&gt; #include &lt;climits&gt; TEST(midpoint, int) { EXPECT_EQ(midpoint(0, 0), 0); EXPECT_EQ(midpoint(0, 1), 0); EXPECT_EQ(midpoint(0, 2), 1); EXPECT_EQ(midpoint(1, 3), 2); EXPECT_EQ(midpoint(4, 1), 2); EXPECT_EQ(midpoint(INT_MIN, 0), INT_MIN/2); EXPECT_EQ(midpoint(INT_MAX, 0), INT_MAX/2); EXPECT_EQ(midpoint(INT_MAX, -INT_MAX), 0); } #include &lt;limits&gt; TEST(midpoint, double) { static constexpr auto inf = std::numeric_limits&lt;double&gt;::infinity(); static constexpr auto nan = std::numeric_limits&lt;double&gt;::quiet_NaN(); EXPECT_EQ(midpoint(0.0, 0.0), 0.0); EXPECT_EQ(midpoint(1.0, 2.0), 1.5); EXPECT_EQ(midpoint(1.0, inf), inf); EXPECT_EQ(midpoint(1.0, -inf), -inf); EXPECT_EQ(midpoint(inf, inf), inf); EXPECT_EQ(midpoint(-inf, -inf), -inf); EXPECT_TRUE(std::isnan(midpoint(inf, -inf))); EXPECT_TRUE(std::isnan(midpoint(nan, 0.0))); EXPECT_TRUE(std::isnan(midpoint(0.0, nan))); EXPECT_TRUE(std::isnan(midpoint(nan, nan))); } #include &lt;complex&gt; TEST(midpoint, complex) { auto const a = std::complex{2,10}; auto const b = std::complex{0,20}; auto const c = std::complex{1,15}; EXPECT_EQ(midpoint(a, b), c); } TEST(midpoint, pointer) { auto const s = &quot;_abcdefghijklmnopqrstuvwxyz&quot;; EXPECT_EQ(midpoint(s+1, s+25), s+13); EXPECT_EQ(midpoint(s+25, s+1), s+13); } #include &lt;string_view&gt; TEST(midpoint, iterator) { auto const s = std::string_view{&quot;abcdefghijklmnopqrstuvwxyz&quot;}; EXPECT_EQ(*midpoint(s.begin(), s.end()), 'n'); EXPECT_EQ(*midpoint(s.end(), s.begin()), 'n'); } #include &lt;forward_list&gt; TEST(midpoint, forward_iterator) { auto const s = std::string_view{&quot;abcdefghijklmnopqrstuvwxyz&quot;}; auto const l = std::forward_list(s.begin(), s.end()); EXPECT_EQ(*midpoint(l.begin(), l.end()), 'n'); } #include &lt;array&gt; TEST(midpoint, std_array) { auto const a = std::array{ 0, 10, 20}; auto const b = std::array{10, 10, 10}; auto const c = std::array{5, 10, 15}; EXPECT_EQ(midpoint(a, b), c); } </code></pre> <p>I've intentionally included some questionable choices:</p> <ul> <li><code>_</code> as a namespace name is legal, but is it a good choice for the implementation-private namespace?</li> <li>I believe I can forward-declare the template classes that belong to <code>std</code>, rather than drag in their entire headers.</li> <li>The <code>arithmetic</code> concept has very similar name to <code>std::is_arithmetic</code> - could/should I change that?</li> <li>The unit-tests still pass if I remove the early exit for NaN inputs, but should I retain them anyway? (The checks were once needed, but refactoring them has left them redundant).</li> <li>In the first test case, I assume that <code>-INT_MAX</code> is valid - could that legally overflow?</li> </ul> <p>I didn't yet enclose the code in a namespace - I would do that when I add include guards and make it a header.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:23:56.870", "Id": "518665", "Score": "2", "body": "[std::midpoint](https://en.cppreference.com/w/cpp/numeric/midpoint) was added in C++20, I believe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:29:47.060", "Id": "518668", "Score": "0", "body": "Thanks @Ayxan - I'm still waiting for Debian's cppreference package to get updated, and I missed that addition to C++20. Turns out I was [tag:reinventing-the-wheel] but didn't know it! The support for complex numbers and iterators is more than `std::midpoint` provides." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:38:50.147", "Id": "518672", "Score": "0", "body": "What is the point of `if ((a < 0) != (b < 0))`? Shouldn't the final `a + (b - a) / 2` work for all cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:26:29.883", "Id": "518681", "Score": "0", "body": "Maybe I should test `std::is_signed<T>` instead for that block?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:27:42.697", "Id": "518688", "Score": "0", "body": "Good idea. That would also obviate the need for `is_arithmetic_v` (and the slight ambiguity)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:46:58.630", "Id": "518709", "Score": "0", "body": "re _The arithmetic concept has very similar name to std::is_arithmetic - could/should I change that?_ **Can** you you `std::arithmetic` in place of `std::is_arithmetic_v` without changing anything else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:51:37.847", "Id": "518710", "Score": "0", "body": "how does `requires { a + (b - a); }` do anything other than seeing if `+` and `-` are defined for type `T`? We already know that `a` and `b` are the same type... Maybe worrying that `-` actually returns a different type? But pointers/iterators are not arithmetic types, so that name is confusing. In general, it can use comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T20:38:16.237", "Id": "518717", "Score": "1", "body": "Having a difference that's a distinct type from a position is normally part of an [_affine space_](https://en.wikipedia.org/wiki/Affine_space#Informal_description). Browsing that, I see the definition doesn't include scalar multiplication (which I thought was part of it) so that might be a good name. `T` is an `affine_point`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T19:12:09.933", "Id": "518786", "Score": "0", "body": "Why don’t you want it to work for bidirectional iterators?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T19:55:05.137", "Id": "518789", "Score": "1", "body": "I mean, you require forward iterators, but ban (via `requires (!std::bidirectional_iterator<T>)`) bidi iterators so, for example, `std::list::iterator` won’t work with any overload. Why ban bidi iterators?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T19:59:28.457", "Id": "518791", "Score": "0", "body": "@indi, it does seem that I need some additional tests for iterators that aren't pointers - I should have written `std::random_access_iterator` there. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T20:09:06.643", "Id": "518793", "Score": "0", "body": "@indi, mention that in an answer and you can have some points. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T20:26:36.033", "Id": "518795", "Score": "1", "body": "Heh. You got it. " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T12:31:49.123", "Id": "534299", "Score": "0", "body": "`using std::swap;` looks out of place, especially if your only using `swap` once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T12:58:24.823", "Id": "534301", "Score": "1", "body": "@jdt, it might look out of place, but that's the standard way to fall back to `std::swap` if no more specific `swap()` function is found during argument-dependent lookup." } ]
[ { "body": "<ul>\n<li><code>_</code> as a namespace name is legal, but is it a good choice for the implementation-private namespace?</li>\n</ul>\n<p>This causes undefined behavior. Identifiers that start with an underscore are reserved in the global scope.</p>\n<ul>\n<li>I believe I can forward-declare the template classes that belong to <code>std</code>, rather than drag in their entire headers</li>\n</ul>\n<p>Adding forward declarations to <code>std</code> is undefined behavior. Just include the appropriate headers instead.</p>\n<hr />\n<pre><code>if (std::isnan(a)) { return a; }\nif (std::isnan(b)) { return b; }\n</code></pre>\n<p>This could be simplified to:</p>\n<pre><code>if (std::isnan(a) || std::isnan(b)) { return NAN; }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:09:34.647", "Id": "518677", "Score": "0", "body": "\"[_Identifiers that start with an underscore are reserved in the global scope_](https://eel.is/c++draft/lex.name#3.2)\". I'd always believed that only identifiers that start with underscore followed by a letter or another underscore are reserved - thanks for picking up on that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:10:47.077", "Id": "518678", "Score": "0", "body": "Would it be better to just dispense with the `isnan()` check, since it's an unlikely path, and the arithmetic gives the correct result anyway?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:15:39.457", "Id": "518679", "Score": "2", "body": "@TobySpeight Yes, I would remove the `isnan` check since the rest of the function doesn't rely on that. I did check with GCC and clang. None seems to elide that check either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:28:04.493", "Id": "518682", "Score": "0", "body": "It looks like I can use `_` as a namespace identifier within my own namespace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:40:31.960", "Id": "518707", "Score": "0", "body": "A _nested_ detail namespace is not in the global scope. Putting _any_ simple name at global scope is asking for a clash as libraries and other code is combined. It's odd that his \"private details\" namespace is not nested but stand-alone -- that would be better off using his name." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:37:39.713", "Id": "262768", "ParentId": "262762", "Score": "3" } }, { "body": "<h1>Missing check for <code>&gt;</code> in <code>concept arithmetic</code></h1>\n<p>Your <code>concept arithmetic</code> checks for <code>&lt;</code>, in your code you are using both <code>&lt;</code> and <code>&gt;</code> to compare values of type <code>T</code>. Either check that both operators are supported, or use <code>if (!(a &lt; b))</code> to check if you need to swap values.</p>\n<h1>Consider not adding an overload for <code>std::array</code></h1>\n<p>You added an overload for computing the midpoint of a <code>std::array</code>, however that raises some questions. For example, if you do this, why are you not also supporting <code>std::vector</code> and other types as well? And is element-wise midpoint always the desired operation?</p>\n<p>Instead of adding yet more overloads, I would just avoid these questions by omitting this overload, and let the caller do it themselves. They can do this easily using <a href=\"https://en.cppreference.com/w/cpp/algorithm/transform\" rel=\"nofollow noreferrer\"><code>std::transform</code></a> or similar algorithms, for example:</p>\n<pre><code>std::vector&lt;float&gt; a{1, 2.718, 3.1415};\nstd::vector&lt;float&gt; b{9, 42, 1729};\nstd::vector&lt;float&gt; c;\nstd::transform(a.begin(), a.end(), b.begin(), std::back_inserter(c), midpoint);\n</code></pre>\n<h1>Pass parameters by <code>const</code> reference</h1>\n<p>I would pass parameters by <code>const</code> reference whenever possible in templates. An optimizing compiler will make this as fast as passing by value for small types, but for more complex types, especially thoses with non-trivial constructors, it might be forced to make expensive copies if you pass by value.</p>\n<h1>Be aware of C++20 iterator sentinels</h1>\n<p>C++20 allows ranges to have an <a href=\"https://en.cppreference.com/w/cpp/ranges/end\" rel=\"nofollow noreferrer\"><code>end()</code></a> iterator that has a different type than the <a href=\"https://en.cppreference.com/w/cpp/ranges/begin\" rel=\"nofollow noreferrer\"><code>begin()</code></a> iterator. You might want to support that for your overload that works on iterators. You can use the <a href=\"https://en.cppreference.com/w/cpp/iterator/sentinel_for\" rel=\"nofollow noreferrer\"><code>std::sentinel_for</code></a> concept to restrict the type of <code>b</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T19:52:41.383", "Id": "518788", "Score": "1", "body": "The `std::array` overload was to some extent a sample, but also a basis for geometric vector types which might use `std::array` as storage. Overloading for `std::vector` is generally less useful - and we're not able to compile-time ensure that they have equal lengths as we can for arrays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T20:22:58.560", "Id": "518794", "Score": "0", "body": "Thanks for the heads-up on sentinels. I think I'll want to use `std::ranges::distance(a, b)` to handle that transparently. I'll re-think the split between \"main\" and \"iterator\" overloads now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T18:52:12.303", "Id": "262816", "ParentId": "262762", "Score": "4" } } ]
{ "AcceptedAnswerId": "262816", "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T14:05:10.833", "Id": "262762", "Score": "9", "Tags": [ "c++" ], "Title": "Find the mean of two values" }
262762
<p>I was looking into Python 3.10's <a href="https://www.python.org/dev/peps/pep-0622/" rel="nofollow noreferrer">Structural Pattern Matching</a> syntax, and I want to refactor one of my code that uses <code>if-else</code>, using structural pattern matching. My code works, but I'm trying to find out if there's a better way to deal with a particular section.</p> <p>Let's consider this simple example problem, let's say I have the following list:</p> <pre><code>data = [ # index [1, 2, 5, 3, 4], # 0 [7, 5, 8, 4, 9], # 1 [2, 3, 4, 4, 5], # 2 [1, 3, 1, 6, 7], # 3 [5, 6, 0, 7, 8], # 4 [4, 3, 0, 7, 5], # 5 [4, 4, 4, 5, 4], # 6 [5, 2, 9, 3, 5], # 7 ] </code></pre> <p>What I want to do is:</p> <pre><code>IF: (there is a `4` *or* `5` at the *beginning*) prepend an `'l'`. ELIF: (there is a `4` *or* `5` at the *end*) prepend a `'r'`. ELIF: (there is a `4` *or* `5` at *both ends* of the list) IF: (Both are equal) prepend a `'b2'`, ELSE: prepend `'b1'` ELSE: IF : (There are at least **two** occurrences of `4` *and/or* `5`) prepend `'t'` ELSE: prepend `'x'` </code></pre> <p>Each inner_list may contain <strong>arbitrary amount of elements</strong>.</p> <h3>Expected Result</h3> <pre><code>index append_left 0 'r' 1 't' 2 'r' 3 'x' 4 'l' 5 'b1' 6 'b2' 7 'b2' </code></pre> <p>Now, I can do this using structural pattern matching, with the following code:</p> <pre><code>for i, inner_list in enumerate(data): match inner_list: case [(4 | 5) as left, *middle, (4 | 5) as right]: data[i].insert(0, ('b1', 'b2')[left == right]) case [(4 | 5), *rest]: data[i].insert(0, 'l') case [*rest, (4 | 5)]: data[i].insert(0, 'r') case [_, *middle, _] if (middle.count(4) + middle.count(5)) &gt;= 2: ## This part ## data[i].insert(0, 't') case _: data[i].insert(0, 'x') pprint(data) </code></pre> <h3>Output</h3> <pre><code>[['r', 1, 2, 5, 3, 4], ['t', 7, 5, 8, 4, 9], ['r', 2, 3, 4, 4, 5], ['x', 1, 3, 1, 6, 7], ['l', 5, 6, 0, 7, 8], ['b1', 4, 3, 0, 7, 5], ['b2', 4, 4, 4, 5, 4], ['b2', 5, 2, 9, 3, 5]] </code></pre> <p>The problem is the <code>##</code> marked block above. Of course I can move that part inside the block, and check there, but I was wondering whether the <code>if</code> part can be avoided altogether, i.e. some pattern that would match at least two <code>4</code> and/or <code>5</code>s.</p> <hr /> <p><strong>EDIT</strong> The <code>[_, *middle, _]</code> part is actually me being suggestive that I am looking for a pattern to match the scenario, I'm aware, in actuality this could be done like: <code>case _ if sum(i in (4, 5) for i in inner_list) &gt;= 2</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:44:57.200", "Id": "518699", "Score": "1", "body": "The reason why I mentioned the syntax `[(4 | 5), *rest]` is unfortunate is because it _slices_ the list which can be an expensive operation. Now, for every case you are performing a seperate slice. `[(4 | 5), *rest]` slices, `[_, *middle, _]` slices etc. The syntax in itself is clear, but not efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:49:26.327", "Id": "518700", "Score": "0", "body": "Yes, I concur, I just added the edit for `[_, *middle, _]`, which is unnecessary in every sense. At least the `*rest` part would be useful if I needed to use the `rest` (which I don't at the moment)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T23:32:30.637", "Id": "518908", "Score": "0", "body": "The implementation for `[(4|5), *rest]` isn't necessarily inefficient. There can only be one starred field, so the implementation could try to match the other parts of the pattern first. If the other parts succeed, the `*rest` matches whatever is left over--it always succeeds. So the actual slicing only has to occurs for a successful match. If you use `*_` instead of `*rest` the slicing isn't needed at all. Patterns like this, that match the beginning and/or end of a sequence, would be rather common and would be a good optimization target for the interpreter developers." } ]
[ { "body": "<p>Like you, I am excited about Python's new pattern matching. Unfortunately,\nI don't think your use case is a good fit. Every tool has strengths\nand weaknesses. In this specific situation, ordinary <code>if-else</code> logic\nseems easier to write, read, and understand. For example:</p>\n<pre><code>def get_prefix(xs):\n lft = xs[0]\n rgt = xs[-1]\n T45 = (4, 5)\n if lft in T45 and rgt in T45:\n return 'b2' if lft == rgt else 'b1'\n elif lft in T45:\n return 'l'\n elif rgt in T45:\n return 'r'\n elif sum(x in T45 for x in xs) &gt; 1:\n return 't'\n else:\n return 'x'\n\nnew_rows = [[get_prefix(row)] + row for row in data]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:40:45.160", "Id": "518690", "Score": "0", "body": "I kind of agree. And this is how my code was originally written, but thought I'd give the new thing a go, to see if I can use it to replace if else completely. btw isn't adding two lists O(n) as opposed to `insert` which is O(1)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:50:06.587", "Id": "518693", "Score": "0", "body": "I am mistaken, insert is indeed O(n), I conflated with deque.appendleft" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:56:17.300", "Id": "518694", "Score": "1", "body": "@Cyttorak Sadly, I mostly ignored your specific question (ie, is it *possible*). I don't know for certain. But if it's possible, it's likely to be even more elaborate than the current code you have. Regarding insert, your second comment is right. That said, if you care about speed, measure it for your specific case. These things can have counter-intuitive results, because some Python operations occur at C-speed, others at Python-speed. I wrote my example code that way mostly out of habit: functions should not mutate without good reason. But your use case might want to mutate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:20:23.090", "Id": "518695", "Score": "0", "body": "Yes, mutation would be fine here. About the potential solution being more elaborate, I was looking for something like this: in order to match key `b` in a dictionary `d = {'a': 'foo', 'b': 'bar', 'c': 'baz'}` it is sufficient to do `case {'b': 'bar', **rest}:`. Of course, it is easy for dicts as the keys are unique, and was historically thought of as unordered. But I was just checking if there were some new ways introduced in the new syntax that would make matching middle elements possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T07:02:35.913", "Id": "518746", "Score": "0", "body": "why not make the variable left and right instead of lft and rgt" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:36:40.590", "Id": "518774", "Score": "0", "body": "@hjpotter92 Shorter names are beneficial in a variety of ways (easier to type, read, and visually scan), but they do come at a cost (can be less clear). *In this specific context*, my judgment was that the short names are perfectly clear, and the vars were going to be used repeatedly, increasing the benefit of brevity. Basically, it was a cost-benefit decision -- like many other decisions when writing software." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:34:31.170", "Id": "262773", "ParentId": "262769", "Score": "4" } }, { "body": "<p>I like your implementation as a whole, I do not think the <code>if</code> part you mentioned is the problem. <code>[_, *middle, _]</code> is a bigger problem as it is expensive to split the list over and over again.</p>\n<p>Similarly if we are talking about performance using count is a tad lazy. What if our list contain thousand of values, and the list starts of as <code>[3,5,...]</code>\n<code>count</code> would count <em>every</em> five in the list, instead of returning after you found your desired number of fives.</p>\n<p>In a similar vein I really despite hardcoded variables. What if you suddenly needed to test 3 and 2 instead of 4 and 5. Or maybe you needed at least 3 fours or 2 fives. The dict lookups are performed as <code>O(1)</code></p>\n<pre><code>from pprint import pprint\n\nVALUES = [4, 5]\nSTARTS_WITH = {VALUES[0]: &quot;l&quot;, VALUES[1]: &quot;l&quot;}\nENDS_WITH = {VALUES[0]: &quot;r&quot;, VALUES[1]: &quot;r&quot;}\nSTART_AND_ENDS = &quot;b1&quot;\nSTART_OR_ENDS = &quot;b2&quot;\nMATCH_AT_LEAST_X_VALUES = &quot;t&quot;\nAT_LEAST_MATCH = {VALUES[0]: 2, VALUES[1]: 1}\nNO_MATCH = &quot;x&quot;\n\n\ndef contains_at_least_n_equal_values(lst, value, counts):\n count = 0\n for elem in lst:\n if elem == value:\n count += 1\n if count &gt;= counts:\n return True\n return False\n\n\ndef decorate(data):\n def symbol_2_append(first_digit, middle_digits, last_digit):\n if first_digit in STARTS_WITH:\n if last_digit in ENDS_WITH:\n return START_AND_ENDS if first_digit == last_digit else START_OR_ENDS\n else:\n return STARTS_WITH[first_digit]\n elif last_digit in ENDS_WITH:\n return ENDS_WITH[last_digit]\n # If VALUES occurs at least X times in the the middle digits\n # we return some string. X is defined in AT_LEAST_MATCH\n for value in VALUES:\n n = AT_LEAST_MATCH[value]\n if contains_at_least_n_equal_values(middle_digits, values, n):\n return MATCH_AT_LEAST_X_VALUES\n return NO_MATCH\n\n new_data = []\n\n for i, (first_digit, *middle_digits, last_digit) in enumerate(data):\n symbol = symbol_2_append(first_digit, middle_digits, last_digit)\n new_data.append([symbol, first_digit, *middle_digits, last_digit])\n\n return new_data\n\n\nif __name__ == &quot;__main__&quot;:\n\n data = [ # index\n [1, 2, 5, 3, 4], # 0\n [7, 5, 8, 4, 9], # 1\n [2, 3, 4, 4, 5], # 2\n [1, 3, 1, 6, 7], # 3\n [5, 6, 0, 7, 8], # 4\n [4, 3, 0, 7, 5], # 5\n [4, 4, 4, 5, 4], # 6\n [5, 2, 9, 3, 5], # 7\n ]\n\n new_data = decorate(data)\n\n pprint(new_data)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:35:04.580", "Id": "518697", "Score": "0", "body": "I don't like hardcoded variables either, however in my case (i.e. my actual program to which the above is an MRE), hardcoded vars is the reasonable way, as it is guaranteed there's a limited set of vars. About the `[_, *middle, _]` part, I could directly count over `inner_list`, or could have avoided `count` altogether saving me iterating the list twice, but here I wanted it to be kind of suggestive that, I am looking for something that would match the pattern as is, without having to do count or if. It seems like there isn't a way to match such a pattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:18:52.763", "Id": "262775", "ParentId": "262769", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:47:55.480", "Id": "262769", "Score": "3", "Tags": [ "python", "pattern-matching" ], "Title": "Structural Pattern Matching syntax to match a value in a list" }
262769
<p>Hello developers i have a got a code which is compares two txt files find their differences and notes them but i am wanting to add a feature which creates two txt files first one is for changed records and other one is for unchanged records what should i do here? Here is my code:</p> <pre class="lang-java prettyprint-override"><code>import java.io.*; import java.util.*; public class B { public static void main (String[] args) throws java.io.IOException { //Getting the name of the files to be compared. BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in)); System.out.println(&quot;Enter 1st File name:&quot;); String str = br2.readLine(); System.out.println(&quot;Enter 2nd File name:&quot;); String str1 = br2.readLine(); String s1=&quot;&quot;; String s2=&quot;&quot;, s3=&quot;&quot;, s4=&quot;&quot;; String y=&quot;&quot;, z=&quot;&quot;; //Reading the contents of the files BufferedReader br = new BufferedReader(new FileReader(str)); BufferedReader br1 = new BufferedReader(new FileReader(str1)); while((z = br1.readLine()) != null) s3 += z; while((y = br.readLine()) != null) s1 += y; System.out.println(); //String tokenizing int numTokens = 0; StringTokenizer st = new StringTokenizer(s1); String[] a = new String[10000]; for(int l = 0; l &lt; 10000; l++) { a[l]=&quot;&quot;; } int i=0; while (st.hasMoreTokens()) { s2 = st.nextToken(); a[i] = s2; i++; numTokens++; } int numTokens1 = 0; StringTokenizer st1 = new StringTokenizer(s3); String[] b = new String[10000]; for(int k = 0; k &lt; 10000; k++) { b[k]=&quot;&quot;; } int j=0; while (st1.hasMoreTokens()) { s4 = st1.nextToken(); b[j] = s4; j++; numTokens1++; } //comparing the contents of the files and printing the differences, if any. int x=0; for(int m=0;m&lt;a.length;m++) { if(!a[m].equals(b[m])) { x++; System.out.println(a[m] + &quot; -- &quot; + b[m]); System.out.println(); } } System.out.println(&quot;No. of differences : &quot; + x); if(x &gt; 0) { System.out.println(&quot;Files are not equal&quot;); } else { System.out.println(&quot;Files are equal. No difference found&quot;); } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:43:29.597", "Id": "518708", "Score": "3", "body": "Welcome to Code Review SE! This site is for reviewing already working code for improvements and optimizations, not solving problems with broken code or other issues. In fact, the tour page mentions that asking how to add features is off-topic for this site. Stack Overflow may be of more help; however, \"write code for me\" is out of scope there too. You should try to code this yourself first, and if you are running into issues, Stack Overflow is the apporpriate place to ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T06:56:46.650", "Id": "518745", "Score": "0", "body": "I agree with @hyper-neutrino, please see the [help/on-topic] if anything remains unclear." } ]
[ { "body": "<p>Welcom to Code Review!</p>\n<p>As @hyper-neutrino pointed, this site is to review working code. As such, here are some tips to improve the code you've provided:</p>\n<h1>Naming</h1>\n<p>Names are absolutely fundamental to help other developers (or even yourself after not working with the code while). So, to improve your code, the first step could be to use better names. For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>package test;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.StringTokenizer;\n\npublic class FileComparatorBetterNames {\n public static void main (String[] args) throws IOException\n {\n //Getting the name of the files to be compared.\n BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in));\n System.out.println(&quot;Enter 1st input filename: &quot;);\n String inputFilename1 = stdinReader.readLine();\n System.out.println(&quot;Enter 2nd input filename: &quot;);\n String inputFilename2 = stdinReader.readLine();\n\n String file1Lines = &quot;&quot;;\n String file2Lines = &quot;&quot;;\n String file1Line = &quot;&quot;;\n String file2Line = &quot;&quot;;\n\n //Reading the contents of the files\n BufferedReader file1Reader = new BufferedReader(new FileReader(inputFilename1));\n BufferedReader file2Reader = new BufferedReader(new FileReader(inputFilename2));\n\n while((file1Line = file1Reader.readLine()) != null)\n file1Lines += file1Line;\n\n while((file2Line = file2Reader.readLine()) != null)\n file2Lines += file2Line;\n\n System.out.println();\n\n //String tokenizing\n StringTokenizer file1Tokenizer = new StringTokenizer(file1Lines);\n String[] file1Tokens = new String[10000];\n for(int i = 0; i &lt; 10000; i++)\n {\n file1Tokens[i] = &quot;&quot;;\n }\n int j = 0;\n while (file1Tokenizer.hasMoreTokens())\n {\n file1Tokens[j] = file1Tokenizer.nextToken();;\n j++;\n }\n\n StringTokenizer file2Tokenizer = new StringTokenizer(file2Lines);\n String[] file2Tokens = new String[10000];\n for(int i = 0; i &lt; 10000; i++)\n {\n file2Tokens[i]=&quot;&quot;;\n }\n j = 0;\n while (file2Tokenizer.hasMoreTokens())\n {\n file2Tokens[j] = file2Tokenizer.nextToken();\n j++;\n }\n\n //comparing the contents of the files and printing the differences, if any.\n int numberOfDifferences = 0;\n for(int i = 0; i &lt; file1Tokens.length; i++)\n {\n if(!file1Tokens[i].equals(file2Tokens[i]))\n {\n numberOfDifferences++;\n System.out.println(file1Tokens[i] + &quot; -- &quot; + file2Tokens[i]);\n System.out.println();\n }\n }\n System.out.println(&quot;No. of differences : &quot; + numberOfDifferences);\n if(numberOfDifferences &gt; 0)\n {\n System.out.println(&quot;Files are not equal&quot;);\n } else \n {\n System.out.println(&quot;Files are equal. No difference found&quot;);\n }\n }\n}\n</code></pre>\n<h1>DRY - Dont Repeat Yourself</h1>\n<p>If there is some common logic within you code, you can extract them to methods:</p>\n<pre class=\"lang-java prettyprint-override\"><code>package test;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.StringTokenizer;\n\npublic class FileComparatorExtractLogic {\n public static void main (String[] args) throws IOException {\n new FileComparatorExtractLogic().run();\n }\n \n public void run() throws IOException{\n //Getting the name of the files to be compared.\n BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in));\n System.out.println(&quot;Enter 1st input filename: &quot;);\n String inputFilename1 = stdinReader.readLine();\n System.out.println(&quot;Enter 2nd input filename: &quot;);\n String inputFilename2 = stdinReader.readLine();\n\n String[] file1Tokens = getTokensFromFile(inputFilename1);\n String[] file2Tokens = getTokensFromFile(inputFilename2);\n\n //comparing the contents of the files and printing the differences, if any.\n int numberOfDifferences = 0;\n for(int m = 0; m &lt; file1Tokens.length; m++)\n {\n if(!file1Tokens[m].equals(file2Tokens[m]))\n {\n numberOfDifferences++;\n System.out.println(file1Tokens[m] + &quot; -- &quot; + file2Tokens[m]);\n System.out.println();\n }\n }\n System.out.println(&quot;No. of differences : &quot; + numberOfDifferences);\n if(numberOfDifferences &gt; 0)\n {\n System.out.println(&quot;Files are not equal&quot;);\n } else \n {\n System.out.println(&quot;Files are equal. No difference found&quot;);\n }\n }\n \n public String[] getTokensFromFile(String filename) throws IOException {\n BufferedReader fileReader = new BufferedReader(new FileReader(filename));\n \n String fileLines = &quot;&quot;;\n String fileLine;\n \n while((fileLine = fileReader.readLine()) != null)\n fileLines += fileLine;\n\n StringTokenizer fileTokenizer = new StringTokenizer(fileLines);\n String[] tokens = new String[10000];\n for(int l = 0; l &lt; 10000; l++)\n {\n tokens[l] = &quot;&quot;;\n }\n int i = 0;\n while (fileTokenizer.hasMoreTokens())\n {\n tokens[i] = fileTokenizer.nextToken();;\n i++;\n }\n \n return tokens;\n }\n}\n</code></pre>\n<h1>Streams</h1>\n<p>As of Java 8, <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/stream/Stream.html\" rel=\"nofollow noreferrer\">Streams</a> and <a href=\"https://www.baeldung.com/java-8-lambda-expressions-tips\" rel=\"nofollow noreferrer\">Lambdas</a> where added, and they help us make our code shorter are more readable:</p>\n<pre class=\"lang-java prettyprint-override\"><code>package test;\n\nimport java.io.BufferedReader;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class FileComparatorWithStreams {\n\n public static void main (String[] args) throws java.io.IOException {\n new FileComparatorWithStreams().run();\n }\n \n public void run() throws IOException {\n BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in));\n System.out.println(&quot;Enter 1st input filename: &quot;);\n String inputFilename1 = stdinReader.readLine();\n System.out.println(&quot;Enter 2nd input filename: &quot;);\n String inputFilename2 = stdinReader.readLine();\n\n List&lt;String&gt; file1Tokens = getTokensFromFile(inputFilename1);\n List&lt;String&gt; file2Tokens = getTokensFromFile(inputFilename2);\n\n // There is probably some way to do this with streams, but I cannot think of an elegant one right now\n int numberOfDifferences = 0;\n int smallestSize = Math.min(file1Tokens.size(), file2Tokens.size());\n String token1, token2;\n for (int i = 0; i &lt; smallestSize; i++) {\n token1 = file1Tokens.get(i);\n token2 = file2Tokens.get(i);\n if (!token1.equals(token2)) {\n numberOfDifferences++;\n System.out.println(token1 + &quot; -- &quot; + token2);\n }\n }\n\n System.out.println(&quot;No. of differences: &quot; + numberOfDifferences);\n if(numberOfDifferences &gt; 0) {\n System.out.println(&quot;Files are not equal&quot;);\n } else {\n System.out.println(&quot;Files are equal. No difference found&quot;);\n }\n }\n \n public List&lt;String&gt; getTokensFromFile(String filename) throws FileNotFoundException {\n BufferedReader fileReader = new BufferedReader(new FileReader(filename));\n return fileReader.lines()\n .map(line -&gt; Collections.list(new StringTokenizer(line)).stream()\n .map(s -&gt; (String) s))\n .flatMap(Function.identity())\n .collect(Collectors.toList());\n }\n}\n</code></pre>\n<h1>Exception and Resources handling</h1>\n<pre class=\"lang-java prettyprint-override\"><code>package test;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class FileComparatorExceptionAndResourceHandling {\n\n public static void main (String[] args) {\n new FileComparatorExceptionAndResourceHandling().run();\n }\n \n public void run() {\n String inputFilename1;\n String inputFilename2;\n \n try (BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in))) {\n System.out.println(&quot;Enter 1st input filename: &quot;);\n inputFilename1 = stdinReader.readLine();\n System.out.println(&quot;Enter 2nd input filename: &quot;);\n inputFilename2 = stdinReader.readLine();\n } catch (IOException e) {\n System.err.printf(&quot;Unexpected exception ocurred while reading from stdi: {}\\n&quot;, e);\n return;\n }\n\n List&lt;String&gt; file1Tokens = getTokensFromFile(inputFilename1);\n List&lt;String&gt; file2Tokens = getTokensFromFile(inputFilename2);\n\n int smallestSize = Math.min(file1Tokens.size(), file2Tokens.size());\n if (smallestSize == 0) {\n System.err.println(&quot;The given files are empty or could not be read&quot;);\n } else {\n // There is probably some way to do this with streams, but I cannot think of an elegant one right now\n int numberOfDifferences = 0;\n String token1, token2;\n for (int i = 0; i &lt; smallestSize; i++) {\n token1 = file1Tokens.get(i);\n token2 = file2Tokens.get(i);\n if (!token1.equals(token2)) {\n numberOfDifferences++;\n System.out.println(token1 + &quot; -- &quot; + token2);\n }\n }\n \n System.out.println(&quot;No. of differences: &quot; + numberOfDifferences);\n if(numberOfDifferences &gt; 0) {\n System.out.println(&quot;Files are not equal&quot;);\n } else {\n System.out.println(&quot;Files are equal. No difference found&quot;);\n }\n }\n }\n \n public List&lt;String&gt; getTokensFromFile(String filename) {\n List&lt;String&gt; tokens;\n \n // A try-with-resources ensures the reader will be closed\n try (BufferedReader fileReader = new BufferedReader(new FileReader(filename))) {\n tokens = fileReader.lines()\n .map(line -&gt; Collections.list(new StringTokenizer(line)).stream()\n .map(s -&gt; (String) s))\n .flatMap(Function.identity())\n .collect(Collectors.toList());\n } catch (IOException e) {\n System.err.printf(&quot;Unexpected IOException ocurred while reading file {}: {}\\n&quot;, filename, e);\n tokens = new ArrayList&lt;&gt;();\n }\n \n return tokens;\n }\n}\n</code></pre>\n<h1>Divide and Conquer</h1>\n<p>The <code>run</code> method is starting to get a bit complex. We can divide it into smaller chuncks to make it easier to read:</p>\n<pre class=\"lang-java prettyprint-override\"><code>package test;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class FileComparatorDivideAndConquer {\n \n private String inputFilename1;\n private String inputFilename2;\n\n public static void main (String[] args) {\n new FileComparatorDivideAndConquer().run();\n }\n \n public void run() {\n requestFilesToCompare();\n if (inputFilename1 == null || inputFilename2 == null) {\n return;\n }\n\n List&lt;String&gt; file1Tokens = getTokensFromFile(inputFilename1);\n List&lt;String&gt; file2Tokens = getTokensFromFile(inputFilename2);\n\n \n int smallestSize = Math.min(file1Tokens.size(), file2Tokens.size());\n if (smallestSize == 0) {\n System.err.println(&quot;The files could not be read, or are empty&quot;);\n } else {\n int numberOfDifferences = calculateFileDifferences(file1Tokens, file2Tokens, smallestSize);\n System.out.println(&quot;No. of differences: &quot; + numberOfDifferences);\n if(numberOfDifferences &gt; 0) {\n System.out.println(&quot;Files are not equal&quot;);\n } else {\n System.out.println(&quot;Files are equal. No difference found&quot;);\n }\n }\n }\n\n public List&lt;String&gt; getTokensFromFile(String filename) {\n List&lt;String&gt; tokens;\n \n // A try-with-resources ensures the reader will be closed\n try (BufferedReader fileReader = new BufferedReader(new FileReader(filename))) {\n tokens = fileReader.lines()\n .map(line -&gt; Collections.list(new StringTokenizer(line)).stream()\n .map(s -&gt; (String) s))\n .flatMap(Function.identity())\n .collect(Collectors.toList());\n } catch (IOException e) {\n System.err.printf(&quot;Unexpected IOException ocurred while reading file {}: {}\\n&quot;, filename, e);\n tokens = new ArrayList&lt;&gt;();\n }\n \n return tokens;\n }\n \n private void requestFilesToCompare() {\n try (BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in))) {\n System.out.println(&quot;Enter 1st input filename: &quot;);\n inputFilename1 = stdinReader.readLine();\n System.out.println(&quot;Enter 2nd input filename: &quot;);\n inputFilename2 = stdinReader.readLine();\n } catch (IOException e) {\n System.err.printf(&quot;Unexpected exception ocurred while reading from stdi: {}\\n&quot;, e);\n }\n }\n \n private int calculateFileDifferences(List&lt;String&gt; file1Tokens, List&lt;String&gt; file2Tokens, int smallestSize) {\n // There is probably some way to do this with streams, but I cannot think of an elegant one right now\n int numberOfDifferences = 0;\n String token1, token2;\n for (int i = 0; i &lt; smallestSize; i++) {\n token1 = file1Tokens.get(i);\n token2 = file2Tokens.get(i);\n if (!token1.equals(token2)) {\n numberOfDifferences++;\n System.out.println(token1 + &quot; -- &quot; + token2);\n }\n }\n return numberOfDifferences;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T19:56:12.723", "Id": "262777", "ParentId": "262770", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:12:39.207", "Id": "262770", "Score": "-3", "Tags": [ "java", "file" ], "Title": "Creating two txt file for changed and unchanged records" }
262770
<p>Scraping tables from the web get complicated when there are 2 or more values in a cell. In order to preserve the table structure, I have devised a way to count the row-number index of its xpath, implementing a nested list when the row number stays the same.</p> <pre class="lang-py prettyprint-override"><code> def get_structured_elements(name): &quot;&quot;&quot;For target data that is nested and structured, such as a table with multiple values in a single cell.&quot;&quot;&quot; driver = self.driver i = 2 # keep track of 'i' to retain the document structure. number_of_items = number_of_items_found() elements = [None] * number_of_items # len(elements) will exceed number_of_items. target_data = driver.find_elements(&quot;//table/tbody/tr[&quot; + i + &quot;]/td[2]/a&quot;) while i - 2 &lt; number_of_items: for item in target_data: # print(item.text, i-1) if elements[i - 2] == None: elements[i - 2] = item.text # set to item.text value if position is empty. else: elements[i - 2] = [elements[i - 2]] elements[i - 2].append(item.text) # make nested list and append new value if position is occupied. i += 1 return elements </code></pre> <p>This simple logic was working fine, until I sought to manage all locator variables in one place to make the code more reusable: How do I store this expression <code>&quot;//table/tbody/tr[&quot; + i + &quot;]/td[2]/a&quot;</code> in a list or dictionary so that it still works when plugged in?</p> <p>The solution (i.e. hack) I came up with is a function that takes in the front and back half of the iterating xpath as arguments, returning <code>front_half + str(i) + back_half</code> if <code>i</code> is part of the parent (iterator) function's local variable.</p> <pre class="lang-py prettyprint-override"><code>def split_xpath_at_i(front_half, back_half): &quot;&quot;&quot;Splits xpath string at its counter index. The 'else' part is to aviod errors when this function is called outside an indexed environment. &quot;&quot;&quot; if 'i' in locals(): string = front_half + str(i) + back_half else: string = front_half+&quot;SPLIT_i&quot;+back_half return string xpath = [split_xpath_at_i(&quot;//table/tbody/tr[&quot;,&quot;]/td[2]/a&quot;), &quot;//table/tbody/tr/td[3]/a[1]&quot; ] def xpath_index_iterator(): for i in range(10): print(split_xpath_at_i(&quot;//table/tbody/tr[&quot;,&quot;]/td[2]/a&quot;)) xpath_index_iterator() # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a # //table/tbody/tr[SPLIT_i]/td[2]/a </code></pre> <p>Problem is, <code>split_xpath_at_i</code> is blind to variables in its immediate environment. What I eventually came up with is to make use of the iterator function's <em>attribute</em> to define the counter <code>i</code> so that the variable can be made available to <code>split_xpath_at_i</code> like so:</p> <pre class="lang-py prettyprint-override"><code>def split_xpath_at_i(front_half, back_half): &quot;&quot;&quot;Splits xpath string at its counter index. The 'else' part is to aviod errors when this function is called outside an indexed environment. &quot;&quot;&quot; try: i = xpath_index_iterator.i except: pass if 'i' in locals(): string = front_half + str(i) + back_half else: string = front_half+&quot;SPLIT_i&quot;+back_half return string xpath = [split_xpath_at_i(&quot;//table/tbody/tr[&quot;,&quot;]/td[2]/a&quot;), &quot;//table/tbody/tr/td[3]/a[1]&quot; ] def xpath_index_iterator(): xpath_index_iterator.i = 0 lst = [] for xpath_index_iterator.i in range(10): print(split_xpath_at_i(&quot;//table/tbody/tr[&quot;,&quot;]/td[2]/a&quot;)) xpath_index_iterator() # //table/tbody/tr[0]/td[2]/a # //table/tbody/tr[1]/td[2]/a # //table/tbody/tr[2]/td[2]/a # //table/tbody/tr[3]/td[2]/a # //table/tbody/tr[4]/td[2]/a # //table/tbody/tr[5]/td[2]/a # //table/tbody/tr[6]/td[2]/a # //table/tbody/tr[7]/td[2]/a # //table/tbody/tr[8]/td[2]/a # //table/tbody/tr[9]/td[2]/a </code></pre> <p>The problem gets more complicated when I try to invoke <code>split_xpath_at_i</code> via a locator list:</p> <pre class="lang-py prettyprint-override"><code>def split_xpath_at_i(front_half, back_half): &quot;&quot;&quot;Splits xpath string at its counter index. The 'else' part is to aviod errors when this function is called outside an indexed environment. &quot;&quot;&quot; try: i = xpath_index_iterator.i except: pass if 'i' in locals(): string = front_half + str(i) + back_half else: string = front_half+&quot;SPLIT_i&quot;+back_half return string xpath = [split_xpath_at_i(&quot;//table/tbody/tr[&quot;,&quot;]/td[2]/a&quot;), &quot;//table/tbody/tr/td[3]/a[1]&quot; ] def xpath_index_iterator(): xpath_index_iterator.i = 0 lst = [] for xpath_index_iterator.i in range(10): # print(split_xpath_at_i(&quot;//table/tbody/tr[&quot;,&quot;]/td[2]/a&quot;)) lst.append(xpath[0]) return lst xpath_index_iterator() # ['//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a', # '//table/tbody/tr[9]/td[2]/a'] </code></pre> <p>What would a professional approach to this problem look like?</p> <hr /> <h1>The Entire Code:</h1> <p>The code below was modified from the <a href="https://selenium-python.readthedocs.io/page-objects.html" rel="nofollow noreferrer">Selenium manual</a>.</p> <p>I've asked a related question over <a href="https://stackoverflow.com/q/67866614/6210219">here</a> that concerns the general approach to Page Objects design.</p> <h2>test.py</h2> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from query import Input import page cnki = Input() driver = cnki.webpage('http://big5.oversea.cnki.net/kns55/') current_page = page.MainPage(driver) current_page.submit_search('禮學') current_page.switch_to_frame() result = page.SearchResults(driver) structured = result.get_structured_elements('titles') # I couldn't get this to work. simple = result.simple_get_structured_elements() # but this works fine. </code></pre> <h2>query.py</h2> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from selenium import webdriver class Input: &quot;&quot;&quot;This class provides a wrapper around actual working code.&quot;&quot;&quot; # CONSTANTS URL = None def __init__(self): self.driver = webdriver.Chrome def webpage(self, url): driver = self.driver() driver.get(url) return driver </code></pre> <h2>page.py</h2> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from element import BasePageElement from locators import InputLocators, OutputLocators from selenium.common.exceptions import TimeoutException, WebDriverException from selenium.common.exceptions import StaleElementReferenceException from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait class SearchTextElement(BasePageElement): &quot;&quot;&quot;This class gets the search text from the specified locator&quot;&quot;&quot; #The locator for search box where search string is entered locator = None class BasePage: &quot;&quot;&quot;Base class to initialize the base page that will be called from all pages&quot;&quot;&quot; def __init__(self, driver): self.driver = driver class MainPage(BasePage): &quot;&quot;&quot;Home page action methods come here. I.e. Python.org&quot;&quot;&quot; search_keyword = SearchTextElement() def submit_search(self, keyword): &quot;&quot;&quot;Submits keyword and triggers the search&quot;&quot;&quot; SearchTextElement.locator = InputLocators.SEARCH_FIELD self.search_keyword = keyword def select_dropdown_item(self, item): driver = self.driver by, val = InputLocators.SEARCH_ATTR driver.find_element(by, val + &quot;/option[text()='&quot; + item + &quot;']&quot;).click() def click_search_button(self): driver = self.driver element = driver.find_element(*InputLocators.SEARCH_BUTTON) element.click() def switch_to_frame(self): &quot;&quot;&quot;Use this function to get access to hidden elements. &quot;&quot;&quot; driver = self.driver driver.switch_to.default_content() driver.switch_to.frame('iframeResult') # Maximize the number of items on display in the search results. def max_content(self): driver = self.driver max_content = driver.find_element_by_css_selector('#id_grid_display_num &gt; a:nth-child(3)') max_content.click() def stop_loading_page_when_element_is_present(self, locator): driver = self.driver ignored_exceptions = (NoSuchElementException, StaleElementReferenceException) wait = WebDriverWait(driver, 30, ignored_exceptions=ignored_exceptions) wait.until( EC.presence_of_element_located(locator)) driver.execute_script(&quot;window.stop();&quot;) def next_page(self): driver = self.driver self.stop_loading_page_when_element_is_present(InputLocators.NEXT_PAGE) driver.execute_script(&quot;window.stop();&quot;) try: driver.find_element(*InputLocators.NEXT_PAGE).click() print(&quot;Navigating to Next Page&quot;) except (TimeoutException, WebDriverException): print(&quot;Last page reached&quot;) class SearchResults(BasePage): &quot;&quot;&quot;Search results page action methods come here&quot;&quot;&quot; def __init__(self, driver): self.driver = driver i = None # get_structured_element counter def wait_for_page_to_load(self): driver = self.driver wait = WebDriverWait(driver, 100) wait.until( EC.presence_of_element_located(*InputLocators.MAIN_BODY)) def get_single_element(self, name): &quot;&quot;&quot;Returns a single value as target data.&quot;&quot;&quot; driver = self.driver target_data = driver.find_element(*OutputLocators.CNKI[str(name.upper())]) # SearchTextElement.locator = OutputLocators.CNKI[str(name.upper())] # target_data = SearchTextElement() return target_data def number_of_items_found(self): &quot;&quot;&quot;Return the number of items found on a single page.&quot;&quot;&quot; driver = self.driver target_data = driver.find_elements(*OutputLocators.CNKI['INDEX']) return len(target_data) def get_elements(self, name): &quot;&quot;&quot;Returns simple list of values in specific data field in a table.&quot;&quot;&quot; driver = self.driver target_data = driver.find_elements(*OutputLocators.CNKI[str(name.upper())]) elements = [] for item in target_data: elements.append(item.text) return elements def get_structured_elements(self, name): &quot;&quot;&quot;For target data that is nested and structured, such as a table with multiple values in a single cell.&quot;&quot;&quot; driver = self.driver i = 2 # keep track of 'i' to retain the document structure. number_of_items = self.number_of_items_found() elements = [None] * number_of_items while i - 2 &lt; number_of_items: target_data = driver.find_elements(*OutputLocators.CNKI[str(name.upper())]) for item in target_data: print(item.text, i - 1) if elements[i - 2] == None: elements[i - 2] = item.text elif isinstance(elements[i - 2], list): elements[i - 2].append(item.text) else: elements[i - 2] = [elements[i - 2]] elements[i - 2].append(item.text) i += 1 return elements def simple_get_structured_elements(self): &quot;&quot;&quot;Simple structured elements code with fixed xpath.&quot;&quot;&quot; driver = self.driver i = 2 # keep track of 'i' to retain the document structure. number_of_items = self.number_of_items_found() elements = [None] * number_of_items while i - 2 &lt; number_of_items: target_data = driver.find_elements_by_xpath\ ('//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr['\ + str(i) + ']/td[2]/a') for item in target_data: print(item.text, i-1) if elements[i - 2] == None: elements[i - 2] = item.text elif isinstance(elements[i - 2], list): elements[i - 2].append(item.text) else: elements[i - 2] = [elements[i - 2]] elements[i - 2].append(item.text) i += 1 return elements </code></pre> <h2>element.py</h2> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from selenium.webdriver.support.ui import WebDriverWait class BasePageElement(): &quot;&quot;&quot;Base page class that is initialized on every page object class.&quot;&quot;&quot; def __set__(self, obj, value): &quot;&quot;&quot;Sets the text to the value supplied&quot;&quot;&quot; driver = obj.driver text_field = WebDriverWait(driver, 100).until( lambda driver: driver.find_element(*self.locator)) text_field.clear() text_field.send_keys(value) text_field.submit() def __get__(self, obj, owner): &quot;&quot;&quot;Gets the text of the specified object&quot;&quot;&quot; driver = obj.driver WebDriverWait(driver, 100).until( lambda driver: driver.find_element(*self.locator)) element = driver.find_element(*self.locator) return element.get_attribute(&quot;value&quot;) </code></pre> <h2>locators.py</h2> <p>This is where <code>split_xpath_at_i</code> sits.</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from selenium.webdriver.common.by import By # import page class InputLocators(): &quot;&quot;&quot;A class for main page locators. All main page locators should come here&quot;&quot;&quot; def dropdown_list_xpath(attribute, value): string = &quot;//select[@&quot; + attribute + &quot;='&quot; + value + &quot;']&quot; return string MAIN_BODY = (By.XPATH, '//GridTableContent/tbody') SEARCH_FIELD = (By.NAME, 'txt_1_value1') # (By.ID, 'search-content-box') SEARCH_ATTR = (By.XPATH, dropdown_list_xpath('name', 'txt_1_sel')) SEARCH_BUTTON = (By.ID, 'btnSearch') NEXT_PAGE = (By.LINK_TEXT, &quot;下頁&quot;) class OutputLocators(): &quot;&quot;&quot;A class for search results locators. All search results locators should come here&quot;&quot;&quot; def split_xpath_at_i(front_half, back_half): # try: # i = page.SearchResults.g_s_elem # except: # pass if 'i' in locals(): string = front_half + str(i) + back_half else: string = front_half+&quot;SPLIT_i&quot;+back_half return string CNKI = { &quot;TITLES&quot;: (By.XPATH, split_xpath_at_i('//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr[', ']/td[2]/a')), &quot;AUTHORS&quot;: (By.XPATH, split_xpath_at_i('//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr[', ']/td[3]/a')), &quot;JOURNALS&quot;: '//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr/td[4]/a', &quot;YEAR_ISSUE&quot;: '//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr/td[5]/a', &quot;DOWNLOAD_PATHS&quot;: '//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr/td/a[1]', &quot;INDEX&quot;: (By.XPATH, '//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr/td/a[2]') } # # Interim Data # CAPTIONS = # LINKS = # Target Data # TITLES = # AUTHORS = # JOURNALS = # VOL = # ISSUE = # DATES = # DOWNLOAD_PATHS = </code></pre> <h2></h2>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:55:20.313", "Id": "518684", "Score": "2", "body": "Can you include all of your scraping code, or at least a representative sample of HTML that you're trying to parse?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:58:08.203", "Id": "518685", "Score": "0", "body": "The whole code consist of a couple `.py` files. Would it be too much to post them here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:08:45.037", "Id": "518687", "Score": "2", "body": "Nope :) The code length limit is quite high, and for the purposes of a question like this, unless the files are perhaps 1000+ lines each, posting them full-form can only help your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:30:11.557", "Id": "518689", "Score": "0", "body": "Alright, it's done!" } ]
[ { "body": "<p>First: I would typically recommend that you replace your use of Selenium with direct <code>requests</code> calls. If it's possible, it's way more efficient than Selenium. It would look like the following, as a very rough start:</p>\n<pre><code>from time import time\nfrom typing import Iterable\nfrom urllib.parse import quote\nfrom requests import Session\n\ndef js_encode(u: str) -&gt; Iterable[str]:\n for char in u:\n code = ord(char)\n if code &lt; 128:\n yield quote(char).lower()\n else:\n yield f'%u{code:04x}'\n\n\ndef search(query: str):\n topic = '主题'\n # China Academic Literature Online Publishing Database\n catalog = '中国学术文献网络出版总库'\n databases = (\n '中国期刊全文数据库,' # China Academic Journals Full-text Database\n '中国博士学位论文全文数据库,' # China Doctoral Dissertation Full-text Database\n '中国优秀硕士学位论文全文数据库,' # China Master's Thesis Full-text Database\n '中国重要会议论文全文数据库,' # China Proceedings of Conference Full-text Database\n '国际会议论文全文数据库,' # International Proceedings of Conference Full-text Database\n '中国重要报纸全文数据库,' # China Core Newspapers Full-text Database\n '中国年鉴网络出版总库' # China Yearbook Full-text Database\n )\n\n with Session() as session:\n session.headers = {\n 'Accept':\n 'text/html,'\n 'application/xhtml+xml,'\n 'application/xml;q=0.9,'\n 'image/webp,'\n '*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'en-CA,en-GB;q=0.8,en;q=0.5,en-US;q=0.3',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'DNT': '1',\n 'Host': 'big5.oversea.cnki.net',\n 'Pragma': 'no-cache',\n 'Sec-GPC': '1',\n 'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) '\n 'Gecko/20100101 '\n 'Firefox/89.0',\n 'Upgrade-Insecure-Requests': '1',\n }\n\n with session.get(\n 'https://big5.oversea.cnki.net/kns55/brief/result.aspx',\n params={\n 'txt_1_value1': query,\n 'txt_1_sel': topic,\n 'dbPrefix': 'SCDB',\n 'db_opt': catalog,\n 'db_value': databases,\n 'search-action': 'brief/result.aspx',\n },\n ) as response:\n response.raise_for_status()\n search_url = response.url\n search_page = response.text\n\n encoded_query = ''.join(js_encode(',' + query))\n # epoch milliseconds\n timestamp = round(time()*1000)\n\n # page_params = {\n # 'curpage': 1,\n # 'RecordsPerPage': 20,\n # 'QueryID': 0,\n # 'ID': '',\n # 'turnpage': 1,\n # 'tpagemode': 'L',\n # 'Fields': '',\n # 'DisplayMode': 'listmode',\n # 'sKuaKuID': 0,\n # }\n\n with session.get(\n 'http://big5.oversea.cnki.net/kns55/brief/brief.aspx',\n params={\n 'pagename': 'ASP.brief_result_aspx',\n 'dbPrefix': 'SCDB',\n 'dbCatalog': catalog,\n 'ConfigFile': 'SCDB.xml',\n 'research': 'off',\n 't': timestamp,\n },\n cookies={\n 'FileNameS': quote('cnki:'),\n 'KNS_DisplayModel': '',\n 'CurTop10KeyWord': encoded_query,\n 'RsPerPage': '20',\n },\n headers={\n 'Referer': search_url,\n }\n ) as response:\n response.raise_for_status()\n results_iframe = response.text\n\n\ndef main():\n etiquette = '禮學'\n search(query=etiquette)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Unfortunately, the design of this website is violently awful. State is passed around using a mix of query parameters, cookies, and server-only context that you can't see and relies on request history in a non-trivial way. So even though the above produces, to my knowledge, identical parameters, headers and cookies to those that you see in real life on the website, there's a failure where a couple of dynamically-generated <code>&lt;script&gt;</code> sections in <code>brief.aspx</code> are silently omitted. So I'm giving up on this recommendation.</p>\n<p>Shifting gears:</p>\n<p>The following recommendations are going to cover scope and class usage, and these should get you toward sanity:</p>\n<ul>\n<li><p>The code in <code>test.py</code> needs to be moved into a function</p>\n</li>\n<li><p>Only <code>test.py</code> should have a shebang and none of your other files, since only <code>test.py</code> is a meaningful entry point.</p>\n</li>\n<li><p>Is <code>Input.URL</code> ever used? That probably needs to be deleted</p>\n</li>\n<li><p><code>Input.webpage</code> should not be returning anything; <code>driver</code> is already a member on the class.</p>\n</li>\n<li><p><code>Input</code> as a whole is suspect. It provides such a thin wrapper around <code>driver</code> as to be basically useless on its own. I would expect the <code>driver.get()</code> to be moved to <code>MainPage.__init__</code>.</p>\n</li>\n<li><p><code>InputLocators</code> also does not deserve to be a class. Those constants can basically be distributed to the point of use, i.e.</p>\n<pre><code> wait.until(\n EC.presence_of_element_located(\n By.XPATH, \n '//GridTableContent/tbody',\n )\n )\n</code></pre>\n</li>\n<li><p>Your <code>search_keyword</code> is strange - you start off initializing it as a static, and then change to using it as an instance variable in <code>submit_search</code>. Why? Also, what is <code>keyword</code>? You would benefit from using PEP484 type hints.</p>\n</li>\n<li><p><code>switch_to_frame</code> has timing issues and did not work for me at all until I added two waits:</p>\n<pre><code> WebDriverWait(driver, 100).until(\n lambda driver: driver.find_element(\n By.XPATH,\n '//iframe[@name=&quot;iframeResult&quot;]',\n ))\n driver.switch_to.frame('iframeResult')\n\n WebDriverWait(driver, 100).until(\n lambda driver: driver.find_element(\n By.XPATH,\n '//table[@class=&quot;GridTableContent&quot;]',\n ))\n</code></pre>\n</li>\n<li><p>Your <code>()</code> at the end of base-less classes can be dropped</p>\n</li>\n<li><p><code>OutputLocators.CNKI</code> is a dictionary. Why? <code>get_single_element</code> indexes into it, but <code>get_single_element</code> is itself never called.</p>\n</li>\n</ul>\n<p>This code:</p>\n<pre><code> elements = []\n for item in target_data:\n elements.append(item.text)\n return elements\n \n</code></pre>\n<p>can be replaced with a generator:</p>\n<pre><code>for item in target_data:\n yield item.text\n</code></pre>\n<p>This code:</p>\n<pre><code> i = None # get_structured_element counter\n</code></pre>\n<p>does nothing since all local variables are discarded at end of scope.</p>\n<p>This code:</p>\n<pre><code> if 'i' in locals():\n string = front_half + str(i) + back_half\n else:\n string = front_half+&quot;SPLIT_i&quot;+back_half\n</code></pre>\n<p>is never going to see its first branch evaluated, since <code>i</code> is not defined locally. I really don't know what you intended here.</p>\n<p>These long xpath tree traversals, such as</p>\n<pre><code>'//*[@id=&quot;Form1&quot;]/table/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr/td/a[2]'\n</code></pre>\n<p>are both fragile and difficult to read. In most cases you should be able to condense them by a mix of inner <code>//</code> to omit parts of the path, and judicious references to known attributes.</p>\n<p>You specifically ask about</p>\n<blockquote>\n<p><code>split_xpath_at_i</code> is blind to variables in its immediate environment</p>\n</blockquote>\n<p>If by &quot;its immediate environment&quot; you mean <code>CNKI</code> (etc) that's because its immediate environment, the class static scope, has not yet been initialized. <code>CNKI</code> can get a reference to it but not the opposite. If you want this to have some kind of state like a counter, then it needs to be promoted to an instance method with a <code>self</code> parameter. I don't know how <code>g_s_elem</code> factors into this because it's not defined anywhere.</p>\n<p>You ask:</p>\n<blockquote>\n<p>The SearchTextElement class with just one locator variable that is hardcoded - is that a good approach?</p>\n</blockquote>\n<p>Not really. First of all, you've again conflated static and instance variables, because you first initialize a static variable to <code>None</code> and then write an instance variable after construction. Why construct a class at all, if it only holds one member and has no methods?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:30:53.140", "Id": "518728", "Score": "0", "body": "I've tried the `requests` call method before, too. It got stuck after submitting the search query. Selenium provides the `driver.switch_to.frame('iframeResult')` to get past that stage and provide access to search result elements. I wonder if there is an equivalent in the `requests` world. What you are describing seems like a different issue altogether." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:42:48.433", "Id": "518729", "Score": "0", "body": "I see that you have `results_iframe = response.text` in your sample code as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:45:33.767", "Id": "518730", "Score": "0", "body": "I suspect the \"violently awful\" design is a deliberate feature to discourage scraping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:50:44.473", "Id": "518731", "Score": "1", "body": "There are better ways to discourage scraping - I honestly think this is just a product of bad design. For fun, read some of the JS code. It's legacy 12-year-old ASP with a big, crazy mishmash of iframes, AJAX, commented-out code blocks, and developer notes. Bonus points if you can find the comment a developer left confessing to a bad, bad hack. In short, never attribute to malice that which you can attribute to ignorance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T02:50:51.597", "Id": "518733", "Score": "0", "body": "Can I revise the code and update my question for further review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T02:57:31.283", "Id": "518734", "Score": "0", "body": "The [Selenium docs](https://selenium-python.readthedocs.io/page-objects.html) implement a locators class as well. (It is called `MainPageLocators`.) Isn't keeping all locators in one place a good design approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T03:56:40.183", "Id": "518735", "Score": "0", "body": "The `SearchTextElement` class with just one locator variable that is hardcoded - is that a good approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T04:27:47.300", "Id": "518740", "Score": "2", "body": "@Sati Updating your answer is discouraged. However, posting a new question with your incorporated changes are more than welcome" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:24:50.830", "Id": "518773", "Score": "0", "body": "_Isn't keeping all locators in one place a good design approach?_ If they're reused, perhaps. If they're single use, it's counterproductive - someone following the code will have to branch off to another location to understand what's happening." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T15:26:30.003", "Id": "518778", "Score": "0", "body": "Yeah, I *do* intend to reuse the code for other websites." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T15:27:43.760", "Id": "518779", "Score": "0", "body": "OK; but the likelihood that other websites require the same locators is fairly slim, right? Every website's DOM is different. This seems like premature abstraction." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T01:17:27.157", "Id": "262782", "ParentId": "262772", "Score": "3" } } ]
{ "AcceptedAnswerId": "262782", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T16:53:03.607", "Id": "262772", "Score": "3", "Tags": [ "python", "selenium", "xpath" ], "Title": "Getting xpath indices to count forward to preserve table structure" }
262772
<p><a href="https://codesandbox.io/s/react-quiz-kb1xb" rel="nofollow noreferrer">https://codesandbox.io/s/react-quiz-kb1xb</a></p> <p>I was wondering what could be improved upon it. I am looking at how it's using Redux and how it's also using hooks and I don't really see anything wrong with it, but I am wondering if it could be improved upon.</p> <pre><code>import React, { Component } from 'react'; import { connect } from 'react-redux'; class ResultTile extends Component { isCorrect(options, answers, index) { let i options.map((value, index1) =&gt; { if (value.isAnswer === true) i = index1 return null }) if (options[i].name === answers[index]) return true else return false } getAnswer(options) { let answer options.map((val, index) =&gt; { if (val.isAnswer === true) { answer = options[index].name } return null }) return answer } render() { let key = 0 return ( this.props.questions.map((question, index) =&gt; { return ( &lt;div key={question.id - 1000} className={this.isCorrect(question.options, this.props.answers, index) ? &quot;alert alert-success mx-auto px-4 py-1 w-100 &quot; : &quot;alert alert-danger mx-auto px-4 py-1 w-100&quot;} role=&quot;alert&quot;&gt; &lt;p className=&quot;font-weight-bold&quot; &gt; &lt;strong&gt; Q{question.id - 1000}.&lt;/strong&gt; {question.name} &lt;/p&gt; &lt;div className=&quot;container&quot;&gt; &lt;div className=&quot;row&quot;&gt; &lt;form className=&quot; &quot;&gt; {question.options.map((option) =&gt; { return &lt;div key={key++} className=&quot;form-check&quot;&gt; &lt;input className=&quot;form-check-input key&quot; type=&quot;radio&quot; checked={option.name === this.props.answers[index]} disabled /&gt; &lt;label className=&quot;form-check-label&quot;&gt; {option.name} &lt;/label&gt; &lt;/div&gt; }) } &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;alert alert-dark p-1 mt-3 mb-2 w-100&quot; role=&quot;alert&quot;&gt; Right answer is : &lt;strong&gt;{this.getAnswer(question.options)}&lt;/strong&gt; &lt;/div&gt; &lt;/div&gt; ) } ) ); } } const mapStateToProps = state =&gt; { return { answers: state.answers, questions: state.questions } } const mapDispatchToProps = dispatch =&gt; { return { updateBonus: () =&gt; dispatch({ type: &quot;UPDATE_BONUS&quot;, value: 100 }), } } export default connect(mapStateToProps, mapDispatchToProps)(ResultTile); </code></pre> <p>You can check the whole app, or just this component in particular, because it's one of the bigger components.</p>
[]
[ { "body": "<p>There are many ways that you can use newer syntaxes to make this cleaner:</p>\n<ul>\n<li>Function component instead of class component.</li>\n<li>Replace <code>connect</code> with react-redux hooks.</li>\n<li>Create your actions with redux-toolkit.</li>\n<li>Write better loops with specific array methods.</li>\n</ul>\n<hr />\n<p>For that last point about array methods, here's a good example:</p>\n<pre><code>getAnswer(options) {\n let answer\n options.map((val, index) =&gt; {\n if (val.isAnswer === true) {\n answer = options[index].name\n }\n return null\n })\n\n return answer\n}\n</code></pre>\n<p>We could rewrite that with <code>.find()</code> to find the correct answer. Your current use of <code>.map()</code> doesn't make any sense because you aren't using the mapped array. You are using it like a <code>forEach()</code>. But <code>find()</code> is more appropriate to this situation.</p>\n<pre><code>getAnswer(options) {\n // Find the first option with a true value of `isAnswer`.\n const correctOption = options.find(option =&gt; option.isAnswer);\n // Return its name\n return correctOption?.name;\n}\n</code></pre>\n<p>Which could easily be a one-liner:</p>\n<pre><code>const getAnswer = (options) =&gt; options.find(option =&gt; option.isAnswer)?.name;\n</code></pre>\n<p>But I would kill both that function and your overly-complex <code>isCorrect</code> function and evaluate them inside of your loop:</p>\n<pre><code>{questions.map((question, index) =&gt; {\n const selectedAnswer = answers[index];\n const correctAnswer = question.options.find(option =&gt; option.isAnswer)?.name;\n const isCorrect = selectedAnswer === correctAnswer;\n</code></pre>\n<hr />\n<p>You have some other functions that aren't entirely necessary, for example:</p>\n<pre><code>isAnswered = (index, answers) =&gt; {\n if (answers[index]) {\n return true\n }\n return false\n}\n</code></pre>\n<p>This is the same as simply checking the boolean value of <code>answers[index]</code> with <code>!!answers[index]</code>.</p>\n<p>You could simplify it to a one-liner:</p>\n<pre><code>isAnswered = (index, answers) =&gt; !!answers[index]\n</code></pre>\n<p>But it's just as easy to write the <code>!!answers[index]</code> directly instead of calling <code>isAnswered(index, answer)</code>.</p>\n<hr />\n<p>Here's how you can rewrite your reducer with Redux Toolkit:</p>\n<pre><code>import questions from &quot;./questions&quot;;\nimport { createSlice } from &quot;@reduxjs/toolkit&quot;;\n\nconst initialState = {\n questions: questions,\n\n counter: 0,\n\n answers: []\n};\n\nconst slice = createSlice({\n name: &quot;quiz&quot;,\n initialState,\n reducers: {\n jumpToFirst: (state) =&gt; {\n state.counter = 0;\n },\n jumpToLast: (state) =&gt; {\n state.counter = state.questions.length - 1;\n },\n jumpToQuestion: (state, action) =&gt; {\n state.counter = action.payload;\n },\n prev: (state) =&gt; {\n state.counter--;\n },\n next: (state) =&gt; {\n state.counter++;\n },\n updateAnswer: (state, action) =&gt; {\n const { index, answer } = action;\n state.answers[index] = answer;\n }\n }\n});\n\nexport default slice.reducer;\n\nexport const {\n jumpToFirst,\n jumpToLast,\n jumpToQuestion,\n prev,\n next,\n updateAnswer\n} = slice.actions;\n</code></pre>\n<p>We now have action creator functions so that you can dispatch <code>prev()</code> instead of <code>{type: &quot;PREV&quot;}</code>. This ensures that your type names are always correct.</p>\n<hr />\n<p>But we can slim down that reducer a lot because you might be suffering from a bit of action-overload. Though there's nothing <em>wrong</em> with these actions, you don't <em>need</em> <code>jumpToFirst</code>, <code>jumpToLast</code>, <code>prev</code>, or <code>next</code> as these are all specific instances of <code>jumpToQuestion</code>. You really only need <code>jumpToQuestion</code> and <code>updateAnswer</code>.</p>\n<p>Here's how the <code>QuestionNavigation</code> component might look with a single action type, using a <code>createButton</code> helper function to cut back on the repetitiveness of the four buttons. Now if you want to change the button styling it's just one place instead of four.</p>\n<pre><code>import React from &quot;react&quot;;\nimport { useDispatch, useSelector } from &quot;react-redux&quot;;\nimport { jumpToQuestion } from &quot;../redux/reducer&quot;;\n\nexport default function QuestionNavigation() {\n const lastIndex = useSelector((state) =&gt; state.questions.length - 1);\n const currentIndex = useSelector((state) =&gt; state.counter);\n\n const dispatch = useDispatch();\n\n const isFirst = currentIndex === 0;\n const isLast = currentIndex === lastIndex;\n\n const createButton = (text, index, disabled) =&gt; {\n return (\n &lt;button\n onClick={() =&gt; dispatch(jumpToQuestion(index))}\n className=&quot;btn btn-sm btn-primary m-2&quot;\n disabled={disabled}\n &gt;\n {text}\n &lt;/button&gt;\n );\n };\n\n return (\n &lt;div className=&quot;container mt-2&quot;&gt;\n &lt;hr /&gt;\n &lt;div className=&quot;row justify-content-center&quot;&gt;\n {createButton(&quot;First&quot;, 0, isFirst)}\n {createButton(&quot;Prev&quot;, currentIndex - 1, isFirst)}\n {createButton(&quot;Next&quot;, currentIndex + 1, isLast)}\n {createButton(&quot;Last&quot;, lastIndex, isLast)}\n &lt;/div&gt;\n &lt;hr /&gt;\n &lt;/div&gt;\n );\n}\n</code></pre>\n<hr />\n<p>Here's my revised version of the <code>ResultTile</code>:</p>\n<pre><code>import React from &quot;react&quot;;\nimport { useSelector } from &quot;react-redux&quot;;\n\nexport default function ResultTile() {\n const questions = useSelector((state) =&gt; state.questions);\n\n const answers = useSelector((state) =&gt; state.answers);\n\n return (\n &lt;&gt;\n {questions.map((question, index) =&gt; {\n const selectedAnswer = answers[index];\n const correctAnswer = question.options.find((option) =&gt; option.isAnswer)?.name;\n const isCorrect = selectedAnswer === correctAnswer;\n return (\n &lt;div\n key={question.id}\n className={\n &quot;alert mx-auto px-4 py-1 w-100 &quot; +\n (isCorrect ? &quot;alert-success&quot; : &quot;alert-danger&quot;)\n }\n role=&quot;alert&quot;\n &gt;\n &lt;p className=&quot;font-weight-bold&quot;&gt;\n &lt;strong&gt; Q{question.id - 1000}.&lt;/strong&gt; {question.name}\n &lt;/p&gt;\n &lt;div className=&quot;container&quot;&gt;\n &lt;div className=&quot;row&quot;&gt;\n &lt;form className=&quot; &quot;&gt;\n {question.options.map((option) =&gt; (\n &lt;div key={option.name} className=&quot;form-check&quot;&gt;\n &lt;input\n className=&quot;form-check-input key&quot;\n type=&quot;radio&quot;\n checked={option.name === selectedAnswer}\n disabled\n /&gt;\n &lt;label className=&quot;form-check-label&quot;&gt;{option.name}&lt;/label&gt;\n &lt;/div&gt;\n ))}\n &lt;/form&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;div className=&quot;alert alert-dark p-1 mt-3 mb-2 w-100&quot; role=&quot;alert&quot;&gt;\n Right answer is: &lt;strong&gt;{correctAnswer}&lt;/strong&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n );\n })}\n &lt;/&gt;\n );\n}\n</code></pre>\n<p><a href=\"https://codesandbox.io/s/react-quiz-forked-t1ih1?file=/src/component/questionTile.js\" rel=\"nofollow noreferrer\">Complete CodeSandbox</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T04:56:20.863", "Id": "266311", "ParentId": "262779", "Score": "2" } } ]
{ "AcceptedAnswerId": "266311", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T20:43:27.543", "Id": "262779", "Score": "2", "Tags": [ "react.js", "redux" ], "Title": "React quiz app with Redux, React Router" }
262779
<p>EDIT: code snippet added, check the output in JS console</p> <p>I wrote the following binary search algorithm in JS, for the first time in my experience. The variable <code>sampleObj</code> is a random object array in the form of: <code>[{index: 5, sample: 3}, {index: 8, sample: 1}, ...]</code>, the final <code>console.log(sampleObj)</code> should log target value and index in an object if found, <code>'not found'</code> if not found</p> <p>My idea is:</p> <ol> <li>sort the sample object array from small to large value, along with the index of each value,</li> <li>find the middle value of the array, if it equals to <code>target</code>, return the object; if it's larger, assign the first half of the object array to <code>sampleObj</code>, otherwise assign the second half,</li> <li>repeat until found or not found.</li> </ol> <p>The code consists of 3 main parts:</p> <ol> <li>generate sample object array,</li> <li>define binary search method,</li> <li>conduct a binary search.</li> </ol> <p>Here is the code, it passed all my test cases, but what can I improve?</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>// sample size const N = 20; const sample = Array.from({length: N}, () =&gt; Math.floor(Math.random() * N)); // define target value const target = 0; const indices = [...Array(N).keys()]; const sampleWithIndices = [sample, indices]; let sampleObj; console.log(sampleWithIndices); console.log(`target is ${target}`); // 1. generate sample object array const generateObj = (origin) =&gt; { let output = []; for(let i = 0; i &lt; origin.length; i++) { let index = [...Array(N).keys()]; output[i] = { 'sample': origin[i], 'index': index[i] } } return output; }; sampleObj = generateObj(sample); // sort sample object by sample array const sortSampleObj = (input) =&gt; { return input.sort((a, b) =&gt; { return a.sample - b.sample }) }; sampleObj = sortSampleObj(sampleObj); // 2. define binary search method const binarySearch = (inputObj, inputMidIndex, inputMidSampleValue, inputTarget) =&gt; { if(inputMidSampleValue === inputTarget) { inputObj = [inputObj[inputMidIndex]]; } else if(inputMidSampleValue &gt; inputTarget) { inputObj = inputObj.slice(0, inputMidIndex); } else { inputObj = inputObj.slice(inputMidIndex); } return inputObj; }; // 3. conduct binary search let midIndex, midSampleValue, maxIterations; maxIterations = Math.round(sampleObj.length / 2); for(let i = 0; i &lt; maxIterations; i++) { midIndex = Math.round(sampleObj.length / 2) - 1; midSampleValue = sampleObj[midIndex].sample; sampleObj = binarySearch(sampleObj, midIndex, midSampleValue, target); if (sampleObj.length === 1) { sampleObj = sampleObj[0].sample === target ? sampleObj : 'not found'; break; } } console.log(sampleObj)</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T02:23:14.407", "Id": "518732", "Score": "0", "body": "Hi @user122973 - the obvious problem is there's a lot of \"assumptions\" in the code. e.g. something named _sampleObj_ is used as an array... not sure many people would think that .." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T09:23:01.067", "Id": "518758", "Score": "0", "body": "Could you please edit your post and provide a working sample of your code in a code snippet (ctrl + m)? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T09:27:30.297", "Id": "518759", "Score": "1", "body": "@kemicofaghost sorry I should have thought that, snippet added" } ]
[ { "body": "<h2>Review</h2>\n<p>The general impression at first look is that the code is rather messy with poor formatting, poorly organised and a lot of noisy, redundant and/or long winded code.</p>\n<p>When testing the code I found bugs. The general rule at Code Review is that code should work to the best of your knowledge. However I do not think you knew that it could fail.</p>\n<p>Thorough testing would have found the bug. Always test your code</p>\n<h2>Bugs</h2>\n<p>There are bugs. The fact that you use the value <code>maxIterations</code> to terminate the loop shows you were somewhat aware of a problem.</p>\n<h2>Main bug</h2>\n<p>For input array of 20 items, items at sorted index of 3, 5, 8, 10, 13, 15, 19 are not found because the function <code>binarySearch</code> does not correctly split the array into smaller parts.</p>\n<h2>Minor problems</h2>\n<p>Further and minor problems are the inconsistent result, both <code>undefined</code> and <code>&quot;not found&quot;</code> have the same meaning (no result).</p>\n<p>The found item is added to an array while <code>&quot;not found&quot;</code> string and <code>undefined</code> are not in an array.</p>\n<p>This make working with the result difficult.</p>\n<p>Personally <code>undefined</code> is preferred over a string as a failed result, and the result (as there can be only one) should be a reference rather than an array containing a reference. (see rewrite)</p>\n<h2>Complexity</h2>\n<p>Your complexity <span class=\"math-container\">\\$O(n)\\$</span> is way above what a binary search should be <span class=\"math-container\">\\$O(log(n))\\$</span></p>\n<p>Binary search is fast because at most it need only test <span class=\"math-container\">\\$O(log(n))\\$</span> items to find a match or know there is no match. Eg for 32 items you test only 5 items</p>\n<p>However you copy parts of the array each time you step the search (half the items of the previous half).</p>\n<p>Making a copy means you need to step over each item copied (hidden iteration by JS engine when you call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array slice\">Array.slice</a>). Thus the worst case is <span class=\"math-container\">\\$O(n)\\$</span> which is the same as a linear search. Example An array of 32 will require the copying of 16 + 8 + 4 + 2 + 1 items (31) in the worst case</p>\n<p>The rewrite uses a bounds to calculate the next index to test. It does not copy any part of the array.</p>\n<h2>General Points</h2>\n<h3>Code noise</h3>\n<p>Code noise is anything that is</p>\n<ul>\n<li>Code not required or is excessively complex (source code complexity)</li>\n<li>Code that can be written in a standard shorter form</li>\n<li>Repeated code</li>\n</ul>\n<p><strong>Shorter form</strong></p>\n<ul>\n<li><p>Property names</p>\n<p>There is no need to wrap object property names in quotes. Eg You have <code>output[i] = {'sample': origin[i], 'index': index[i]}</code> can be <code>output[i] = {sample: origin[i], index: index[i]}</code></p>\n</li>\n<li><p>Implied return</p>\n<p>Arrow function can have an implied return. For example the sort function can be <code>input.sort((a, b) =&gt; a.sample - b.sample);</code> (same as <code>input.sort((a, b) =&gt; { return a.sample - b.sample); }</code>) the return is implied if you do not include <code>{}</code> around the functions code block.</p>\n</li>\n</ul>\n<p><strong>Not required</strong></p>\n<ul>\n<li><p>Excessive complexity</p>\n<ul>\n<li><p>In <code>generateObj</code> you create an array of indexes <code>[...Array(N).keys()]</code> then index that array to get an index <code>index: index[i]</code>. I am not sure why you do this as you have the index already as <code>i</code></p>\n<ul>\n<li><p>There is no need to loop till <code>maxIterations</code>, you can use a while loop to exit when the array size is 1. (I understand you used it to avoid the bugs)</p>\n</li>\n<li><p>It is best to calculate values as close to the point you need them.</p>\n<p>The variables <code>midIndex</code> and <code>midSampleValue</code> are created outside the function that uses them <code>binarySearch</code>. These values are not used outside that function.</p>\n<p>As that function has all the data required to calculate theses values it is far simpler to calculate them in that function rather than outside and needing to pass them as arguments.</p>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><p>Redundant assign</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array sort\">Array.sort</a> sorts the array in place. There is no need to reassign it. <code>sampleObj = sortSampleObj(sampleObj);</code> is the same as <code>sortSampleObj(sampleObj);</code></p>\n</li>\n</ul>\n<h2>Style</h2>\n<p>Some style points.</p>\n<ul>\n<li><p>Use <code>const</code> for constants.</p>\n</li>\n<li><p>Take care to correctly indent code.</p>\n</li>\n<li><p>Always create functions rather than use inline code. In the rewrite the search is a function. This makes the code portable, gives semantic meaning to the code, allows for a cleaner exit.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite fixes bugs and has the correct complexity <span class=\"math-container\">\\$O(log(n))\\$</span> for a binary search.</p>\n<h3>Notes</h3>\n<ul>\n<li><p>The rewrite function <code>binarySearch</code> does the search</p>\n</li>\n<li><p>The search function takes an additional argument <code>propName</code> that defines the name of the property that the search is looking for. It defaults to <code>&quot;sample&quot;</code></p>\n</li>\n<li><p>The function returns the item found or undefined</p>\n</li>\n<li><p>There is a usage example at the bottom.</p>\n</li>\n</ul>\n<p>There are many ways to implement a binary search. The rewrite creates a bounds <code>top</code> and <code>bottom</code> The mid point <code>idx</code> is halfway between top and bottom and is the item to test. If the tested point is greater then <code>top</code> is set to the mid point <code>idx</code> else <code>bottom</code> is set to mid point <code>idx</code>.</p>\n<p>I use binary operator right shift <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Right shift\">&gt;&gt; (Right shift)</a> to half values as it does a divide and floor in one step. Eg <code>val &gt;&gt; 1</code> is the same as <code>Math.floor(val / 2)</code></p>\n<pre><code>function binarySearch(data, targetValue, propName = &quot;sample&quot;) {\n var top = data.length - 1, bottom = 0, idx = top &gt;&gt; 1; \n while (top &gt;= bottom){\n const item = data[idx], val = item[propName]; \n if (val === targetValue) { return item }\n val &lt; targetValue ? bottom = idx + 1 : top = idx - 1;\n idx = (bottom + top) &gt;&gt; 1;\n } \n}\nconst data = [{sample: 1, idx 0}, {sample: 10, idx 1}, {sample: 20, idx 2}];\nconsole.log(binarySearch(data, 10)?.idx ?? &quot;Not found&quot;)\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T15:47:27.403", "Id": "518780", "Score": "0", "body": "As a discussion, when you mentioned in main bug: **For input array of 20 items, items at sorted index of 3, 5, 8, 10, 13, 15, 19 are not found**, I tried searching 0 in `[9, 13, 17, 11, 8, 0, 1, 1, 13, 15, 10, 10, 19, 11, 9, 1, 14, 15, 5, 4]` and the algorithm returned `{index: 5, sample 0}`, so I suppose item at the sorted index of 5 could be found? Also for `[4, 18, 19, 9, 15, 19, 17, 5, 7, 1, 11, 16, 2, 12, 10, 0, 2, 16, 7, 18]`, 0 could be found at index 15." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T16:23:54.497", "Id": "518781", "Score": "0", "body": "@user122973 In both examples you provide 0 would be at sorted index 0 (the index of the item when sorted does not match the `item.index` value)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T19:58:03.353", "Id": "518892", "Score": "0", "body": "Can you explain the last line of syntax `binarySearch(data, 10)?.idx ?? \"Not found\"`, especially `?.idx ?? 'not found'`. What is the `.idx` after the ternary operator, and why does `??` return 'not found'?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T15:26:15.237", "Id": "262805", "ParentId": "262780", "Score": "2" } } ]
{ "AcceptedAnswerId": "262805", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T22:36:13.213", "Id": "262780", "Score": "4", "Tags": [ "javascript", "binary-search" ], "Title": "JavaScript Binary Search -- first try" }
262780
<p>My code works just fine but it seems like I have too many variables which could confuse people from what the code does. Any ideas? Or does this look fine. Feel free to add any other tips to make my code more efficient.</p> <p>This subroutine is for a button which when clicked rotates a players position. (The overall program is a rotation management application for football)</p> <pre><code>Private Sub btnConfirmRotation_Click(sender As Object, e As EventArgs) Handles btnConfirmRotation.Click If comPlayersToBeRotated.SelectedIndex &lt; 0 Then 'If there are no players to be rotated the button does nothing Exit Sub End If Dim lineIndex As Integer = alreadyAdded(comPlayersToBeRotated.SelectedIndex) 'Gets the line index in the text file for the players details Dim allPlayers As String() = System.IO.File.ReadAllLines(myFile) 'List of all details Dim entireFile As String = System.IO.File.ReadAllText(myFile) 'String of entire file Dim playerDetails As String() = allPlayers(lineIndex).Split(&quot;|&quot;) 'Gets the details of the selected player in the combo box Dim positionOfPlayerRotating As String = playerDetails(3) 'Assigns position portion of array Dim rotationOfPlayerRotating As String = playerDetails(2) 'Assigns jersey of person they are rotating with portion of array For Each line In allPlayers Dim thisPlayersDetails As String() = line.Split(&quot;|&quot;) 'The line its on is split into each section of the details Dim positionOfThisPlayer As String = thisPlayersDetails(3) Dim jerseyOfThisPlayer As String = thisPlayersDetails(1) Dim temp As String If rotationOfPlayerRotating = jerseyOfThisPlayer Then 'Swaps &quot;position&quot; temp = thisPlayersDetails(3) thisPlayersDetails(3) = positionOfPlayerRotating playerDetails(3) = temp 'Rewrites file entireFile = entireFile.Replace(line, String.Join(&quot;|&quot;, thisPlayersDetails)) entireFile = entireFile.Replace(allPlayers(lineIndex), String.Join(&quot;|&quot;, playerDetails)) System.IO.File.WriteAllText(myFile, entireFile) 'Actually writes to file 'Sets to default if items are above zero so i dont get an out of range exception If comPlayersToBeRotated.Items.Count &gt; 0 Then comPlayersToBeRotated.SelectedIndex = 0 End If If lbxPlayers.SelectedIndex &gt;= 0 Then 'If an item is selected ShowDetails() 'Shows the detail of that player, even if its not the player that rotated so when it is, the details update End If End If Next 'Removes that player from the combo box and adds to already rotated so it won't keep rotating the first player alreadyAdded.RemoveAt(comPlayersToBeRotated.SelectedIndex) alreadyRotated.Add(lineIndex) comPlayersToBeRotated.Items.RemoveAt(comPlayersToBeRotated.SelectedIndex) End Sub </code></pre>
[]
[ { "body": "<p>Sometimes you are in the need for a lot of variables. The best way to make your code not confusing for others is to name the variables meaningful and easy to distinguish.</p>\n<p>For example the variables</p>\n<pre><code>Dim positionOfPlayerRotating As String\nDim rotationOfPlayerRotating As String\n</code></pre>\n<p>are difficult to distinguish.</p>\n<p>That beeing said, there would be another possibility, <strong>use classes</strong>.</p>\n<p>How about adding a class <code>Player</code> with properties <code>Position</code>, <code>Jersey</code>, <code>Rotation</code> and whatever properties you need.<br />\nNext having a <code>Dim players as List(Of Player)</code> which can be loaded from your file <code>myFile</code>. Doing this at the start of your application you wouldn't need to load it every time you are clicking this button or in other methods where you need the players.<br />\nNow you could have e.g</p>\n<pre><code>Dim rotatingPlayer as Player = ... retrieve e.g from combobox comPlayersToBeRotated\nFor Each player As Player in players\n If rotatingPlayer.Rotation = player.Jersey Then \n ' Do what has to be done\n End If\nNext\n</code></pre>\n<p>which would be more readable without having the need for that much variables.<br />\nYou could also use <code>Linq</code> to &quot;filter&quot; the players like so</p>\n<pre><code>For Each player As Player in players.Where(Function(p) p.Jersey = rotatingPlayer.Rotation) \n ' Do what has to be done\nNext\n</code></pre>\n<p>which would only iterate over the players which <code>Jersey</code> property equals the <code>Rotation</code> property of the <code>rotatingPlayer</code>.</p>\n<p>Saving could take place either by having a &quot;save-button&quot; or at the end of the application. In your current method you are saving the players each time the condition <code>rotationOfPlayerRotating = jerseyOfThisPlayer</code> is true.</p>\n<p>Althought I come from a VB background you may assume that the provided code maybe isn't correct because I have switched to C# some years ago.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T13:21:30.990", "Id": "262795", "ParentId": "262785", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T04:51:39.167", "Id": "262785", "Score": "0", "Tags": [ "performance", "vb.net" ], "Title": "Rotation Management Application" }
262785
<h2>What it does</h2> <p>Calculates the mean difference for a list of any combination of ints (I think).</p> <h2>What I want to know</h2> <p>The only other way I can think of doing this is using recursion.</p> <p>I’d like to know if there are other better ways to do this.</p> <p>Also the reason I done this is because I wanted to calculate the mean difference between time stamps I have in another script, so used this as an exercise, that one will be more difficult since it’s 24 hr time, when it gets to the part of switching from:</p> <p><code>12:00 -&gt; 00:00</code></p> <h3>Code:</h3> <pre class="lang-py prettyprint-override"><code>nums = [3, 1, 2, 5, 1, 5, -7, 9, -8, -3, 3] l = len(nums) - 1 diff_list = [] for i in range(l): diff = nums[0] - nums[1] if diff &lt; 0: diff = nums[1] - nums[0] diff_list.append(diff) nums.pop(0) mean = sum(diff_list)/len(diff_list) print(round(mean, 1)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T08:59:52.423", "Id": "518756", "Score": "0", "body": "I would advice you against using list comprehensions for timestamps. Time can be a tricky thing to deal with, timezones, leap years, leap seconds. Etc. Again a [quick google search](https://stackoverflow.com/questions/36481189/python-finding-difference-between-two-time-stamps-in-minutes), should head you in the direction of always using [`datetime`](https://docs.python.org/3/library/datetime.html) when dealing with time. Feel free to post a follow up question if you want further comments on your particular implementation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T10:51:50.070", "Id": "518762", "Score": "0", "body": "Thank you, I think I will once I get going with it, you’ve been very helpful thanks :)" } ]
[ { "body": "<p>You can reduce a lot of your code just by using pythons builtin <code>abs</code> function. I also used list comprehension to shorted your code, so your entire loop code is now in one line.</p>\n<p>This also looks like a great candidate for a function. Now, you can pass any collection of numbers to the function, allowing you to reuse this code however many times you want.</p>\n<pre><code>from typing import List\n\ndef mean_difference(nums: List[int]) -&gt; None:\n diff_list = [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]\n mean = sum(diff_list) / len(diff_list)\n return round(mean, 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T08:28:14.123", "Id": "518755", "Score": "0", "body": "Thanks a lot I really wanted to use list comprehension for this one, but got stuck with annoying old for, this is really nice" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T06:42:07.227", "Id": "262787", "ParentId": "262786", "Score": "4" } }, { "body": "<h3><a href=\"https://en.wikipedia.org/wiki/Reinventing_the_wheel\" rel=\"nofollow noreferrer\">Reinventing the wheel</a></h3>\n<p>Now I will try not to sound too harsh, but did you attempt to google the problem at hand before starting? Building habits in programming is important, but it is equally important to building upon existing code. A quck search gives me the following useful links <a href=\"https://stackoverflow.com/questions/63588328/minimum-absolute-difference-between-elements-in-two-numpy-arrays\">here</a>, <a href=\"https://stackoverflow.com/questions/2400840/python-finding-differences-between-elements-of-a-list\">here</a> and <a href=\"https://stackoverflow.com/questions/29745593/finding-differences-between-all-values-in-an-list\">here</a>.</p>\n<h3>General comments</h3>\n<pre><code>l = len(nums) - 1\n</code></pre>\n<p>This needs a better name. A good rule of thumb is to avoid <a href=\"https://medium.com/pragmatic-programmers/avoid-single-letter-names-11c621cbd188\" rel=\"nofollow noreferrer\">single letter variables</a>. Secondly this variable is only used once, and thus is not needed. As you could have done</p>\n<pre><code>for i in range(len(nums)-1):\n</code></pre>\n<p>which is just as clear. As mentioned the next part could be shortened to</p>\n<pre><code>diff = abs(nums[0] - nums[1])\n</code></pre>\n<p>Perhaps the biggest woopsie in your code is <code>nums.pop(0)</code> for two reasons</p>\n<ol>\n<li>It modifies your original list. Assume you have calculated and the mean differences, but now want to access the first element in your list: <code>nums[0]</code> what happens?</li>\n<li>Secondly <code>pop</code> is an expensive operation, as it shifts the indices for every element in the list for every pop.</li>\n</ol>\n<p>Luckily we are iterating over the indices so we can use them to avoid poping. Combining we get</p>\n<pre><code>for i in range(len(nums) - 1):\n diff = abs(nums[i-1] - nums[i])\n diff_list.append(diff)\n</code></pre>\n<p>However, this can be written in a single line if wanted as other answers have shown. <code>zip</code> is another solution for a simple oneliner, albeit it should be slightly slower due to slicing. I do not know how important performance is to you, so zip might be fine</p>\n<pre><code>[abs(j - i) for i, j in zip(nums, nums[1:])]\n</code></pre>\n<p>If speed is important it could be worth checking out <code>numpy</code></p>\n<h3>Improvements</h3>\n<p>Combining everything, adding hints and struct and a numpy version we get</p>\n<pre><code>import numpy as np\nfrom typing import List\n\n\ndef element_difference_1(nums: List[int]) -&gt; List[int]:\n return [abs(j - i) for i, j in zip(nums, nums[1:])]\n\n\ndef element_difference_2(nums: List[int]) -&gt; List[int]:\n return [abs(nums[i + 1] - nums[i]) for i in range(len(nums) - 1)]\n\n\ndef mean_value(lst: List[int]) -&gt; float:\n return sum(lst) / len(lst)\n\n\ndef mean_difference(nums: List[int], diff_function, rounding: int = 1) -&gt; None:\n num_diffs = diff_function(nums)\n mean = mean_value(num_diffs)\n return round(mean, rounding)\n\n\ndef mean_difference_np(lst) -&gt; float:\n return np.mean(np.abs(np.diff(lst)))\n\n\nif __name__ == &quot;__main__&quot;:\n nums = [3, 1, 2, 5, 1, 5, -7, 9, -8, -3, 3]\n print(mean_difference(nums, element_difference_1))\n print(mean_difference(nums, element_difference_2))\n print(mean_difference_np(np.array(nums)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T08:25:06.330", "Id": "518754", "Score": "0", "body": "Thank you, I wanted this to be list comprehensions (got a bunch from you) as I’m getting bored of for loops I like your approach, they should’ve just made python a strictly typed language I’m seeing everyone importing from typing these days. I didn’t google it heh heh I was just practicing in preparation for finding the difference between my timestamp script, didn’t know pop was expensive thanks for the heads up, the list is disposable, that’s why I wasn’t worried about messing it up :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T09:02:03.147", "Id": "518757", "Score": "0", "body": "Thanks for going through all that with me I’ll keep this and learn from it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T07:20:45.500", "Id": "262788", "ParentId": "262786", "Score": "4" } } ]
{ "AcceptedAnswerId": "262788", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T06:06:03.417", "Id": "262786", "Score": "4", "Tags": [ "python-3.x", "mathematics" ], "Title": "Mean difference calculator for any int combination" }
262786
<p>(This is follow-up <a href="https://codereview.stackexchange.com/questions/262759/calculate-sum-and-count-of-even-and-odd-numbers?noredirect=1#comment518761_262759">question</a>). I updated my console program code to calculate sum and count of even and odd numbers. Provided code :</p> <pre><code>using System; namespace Studying_ { class Program { static void Main(string[] args) { uint evenNumbersCount = 0; uint oddNumbersCount = 0; int rangeStartInclusive, rangeEndInclusive; long sum; while (true) { Console.WriteLine(&quot;Enter the first number in the range to find out it odd or even.&quot;); if (int.TryParse(Console.ReadLine(), out rangeStartInclusive) == false) { Console.WriteLine(&quot;Incorrect number. Press R to try again. Press any key to exit.&quot;); if (Console.ReadKey().KeyChar == 'r' || Console.ReadKey().KeyChar == 'R') { Console.Clear(); continue; } else break; } Console.WriteLine(&quot;Enter the second number&quot;); if (int.TryParse(Console.ReadLine(), out rangeEndInclusive) == false) { Console.WriteLine(&quot;Incorrect number. Press R to try again. Press any key to exit.&quot;); if (Console.ReadKey().KeyChar == 'r' || Console.ReadKey().KeyChar == 'R') { Console.Clear(); continue; } else break; } if (rangeEndInclusive &lt; rangeStartInclusive) (rangeStartInclusive, rangeEndInclusive) = (rangeEndInclusive, rangeStartInclusive); for (int n = rangeStartInclusive; n &lt;= rangeEndInclusive; n++) { bool isEven = n % 2 == 0; if (isEven) evenNumbersCount++; else oddNumbersCount++; } sum = (rangeEndInclusive - rangeStartInclusive + 1) * (rangeStartInclusive + rangeEndInclusive) / 2; Console.WriteLine(&quot;Sum - &quot; + sum + &quot; | Even - &quot; + evenNumbersCount + &quot; | Odd - &quot; + oddNumbersCount); Console.WriteLine(&quot;Press R to try again. Press any key to exit.&quot;); char key = Console.ReadKey().KeyChar; if (key == 'r' || key == 'R') { evenNumbersCount = 0; oddNumbersCount = 0; Console.Clear(); continue; } else break; } } } } </code></pre> <blockquote> <p>Input: 2, 5<br /> Output: Sum - 14 | Even - 2 | Odd - 2<br /> (2,3,4,5) counts.</p> </blockquote> <p>The question is whether I can improve my code. I have some doubts about this <code>if</code> with upper- and lowercase. Are there some ways to improve it?</p> <blockquote> <p><code>if (Console.ReadKey().KeyChar == 'r' || Console.ReadKey().KeyChar == 'R')</code></p> </blockquote> <p>Also, too many messages like</p> <blockquote> <p><code>Console.WriteLine(&quot;Press R to try again. Press any key to exit.&quot;);</code></p> </blockquote> <p>Maybe I should initialize method <code>Exit()</code> or <code>NewTry()</code> (Haven't gotten to the methods yet, but I once studied them). The code will be more readable, but will it affect on performance? Expecting for your feedbacks.</p> <p>P.S. Sorry for my english skills.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T11:22:43.007", "Id": "518763", "Score": "0", "body": "From what perspective do you want improvement(s)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T13:00:48.550", "Id": "518767", "Score": "0", "body": "I guess from any one. I want people to share with me if I can make something simpler or in a better way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:01:13.273", "Id": "518770", "Score": "0", "body": "I think you misunderstood my question. Which [quality attribute](https://en.wikipedia.org/wiki/List_of_system_quality_attributes) needs improvement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:09:09.483", "Id": "518772", "Score": "0", "body": "My apologies, I tried to understand your question... Probably my english skills are not good enough. Or I am completly zero in these things and even don't know what I want. I tried to explain in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T18:17:21.710", "Id": "518783", "Score": "1", "body": "`if (Console.ReadKey().Key == ConsoleKey.R)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:34:21.420", "Id": "519457", "Score": "1", "body": "@aepot, thanks, this is the most easier way given here." } ]
[ { "body": "<p>I like that you use <code>Inclusive</code> as part of some names because it adds to clarity. When I see <code>n &lt;= rangeEndInclusive</code> there is no doubt that it correctly used, whereas <code>n &lt; rangeEndInclusive</code> or even <code>n &lt;= rangeEndInclusive</code> would raise doubts.</p>\n<p>I can appreciate you are a beginner and willing to learn. To that end, one does not typically end object names with an underscore. So <code>namespace Studying_</code> should just be <code>namespace Studying</code>.</p>\n<p>Here at CR, we have a strong preference to always use <code>{ }</code>. You have several instance with conditionals where you do not do this.</p>\n<p>I would not use <code>uint</code> for <code>evenNumbersCount</code> and <code>oddNumbersCount</code>. The input values are <code>int</code>, so pretty sure you will never exceed an <code>int</code>. While they never will they be less than 0, they should still be declared as <code>int</code>.</p>\n<p>Declare one variable per line. So break <code>int rangeStartInclusive, rangeEndInclusive;</code> into 2 different lines.</p>\n<p>It is probably correct that <code>sum</code> is a <code>long</code> since you could specify a number from <code>1</code> to <code>int.MaxValue</code>. Just wait a while to have that calculate since it's 2.1 billion values.</p>\n<p>One coding principle to adopt as your own personal philosophy is Don't Repeat Yourself or DRY. Try to keep your code DRY. When you prompt for the 2 numbers, much of that code is repetitive. Try to see if you can rework it into its own method. I leave that as an exercise to you.</p>\n<p>An alternative to counting odds and evens:</p>\n<pre><code>int[] count = new int[2];\nfor (int n = rangeStartInclusive; n &lt;= rangeEndInclusive; n++)\n{\n count[n % 2]++;\n}\n\nConsole.WriteLine($&quot;Odd count = {count[1]}&quot;);\nConsole.WriteLine($&quot;Even count = {count[0]}&quot;);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:45:17.160", "Id": "519461", "Score": "0", "body": "Thank you, I think this answer is the most valuable. But I cannot understand what `{ }` preference do you mean? Do you mean I should add `{ }` in `if (isEven) evenNumbersCount++; else oddNumbersCount++;` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T11:58:14.183", "Id": "519480", "Score": "1", "body": "@JediMan For `if` or `for` blocks, CR prefers to use `{ }` rather than just 1 line. The one code block I posted has an example. The braces could have been omitted, but it is considered a good practice to always use them in case you ever modify the code by adding extra lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T12:10:16.317", "Id": "519483", "Score": "0", "body": "thank you for advice." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T16:10:35.687", "Id": "262806", "ParentId": "262789", "Score": "1" } }, { "body": "<h2>Review</h2>\n<p>Welcome to Code Review. There are few suggestions as below.</p>\n<h3><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a></h3>\n<p>As some answers mentioned in the question you linked, you can use string interpolation and <code>Console.WriteLine(&quot;Sum - &quot; + sum + &quot; | Even - &quot; + evenNumbersCount + &quot; | Odd - &quot; + oddNumbersCount);</code> is going to be <code>Console.WriteLine($&quot;Sum - {sum} | Even - {evenNumbersCount} | Odd - {oddNumbersCount}&quot;);</code></p>\n<h3>Create methods</h3>\n<p>DRY - <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't repeat yourself</a>. The part of reading the first number and the second number are similar. Moreover, you write three times <code>if (Console.ReadKey().KeyChar == 'r' || Console.ReadKey().KeyChar == 'R')</code> You can create static methods (for example, <code>GetNumber</code> and <code>CheckExit</code> here) to do these things.</p>\n<pre><code>static void Main(string[] args)\n{\n uint evenNumbersCount = 0;\n uint oddNumbersCount = 0;\n int rangeStartInclusive, rangeEndInclusive;\n long sum;\n\n while (true)\n {\n Console.WriteLine(&quot;Enter the first number in the range to find out it odd or even.&quot;);\n if (GetNumber(out rangeStartInclusive) == false) continue;\n\n Console.WriteLine(&quot;Enter the second number&quot;);\n if (GetNumber(out rangeEndInclusive) == false) continue;\n\n if (rangeEndInclusive &lt; rangeStartInclusive)\n (rangeStartInclusive, rangeEndInclusive) = (rangeEndInclusive, rangeStartInclusive);\n\n for (int n = rangeStartInclusive; n &lt;= rangeEndInclusive; n++)\n {\n bool isEven = n % 2 == 0;\n\n if (isEven)\n evenNumbersCount++;\n else\n oddNumbersCount++;\n }\n\n sum = (rangeEndInclusive - rangeStartInclusive + 1) * (rangeStartInclusive + rangeEndInclusive) / 2;\n\n Console.WriteLine($&quot;Sum - {sum} | Even - {evenNumbersCount} | Odd - {oddNumbersCount}&quot;);\n\n CheckExit(&quot;Press R to try again. Press any key to exit.&quot;);\n evenNumbersCount = 0;\n oddNumbersCount = 0;\n Console.Clear();\n \n }\n}\n\nprivate static bool GetNumber(out int result)\n{\n if (int.TryParse(Console.ReadLine(), out result) == false)\n {\n return CheckExit(&quot;Incorrect number. Press R to try again. Press any key to exit.&quot;);\n }\n return true;\n}\n\nprivate static bool CheckExit(string message)\n{\n Console.WriteLine(message);\n if (Console.ReadKey().KeyChar == 'r' || Console.ReadKey().KeyChar == 'R')\n {\n Console.Clear();\n return false;\n }\n else\n Environment.Exit(0);\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T17:31:46.847", "Id": "262811", "ParentId": "262789", "Score": "1" } }, { "body": "<p>for your question :</p>\n<pre><code>if (Console.ReadKey().KeyChar == 'r' || Console.ReadKey().KeyChar == 'R')\n</code></pre>\n<p>it can be simplified using <code>StringComparison</code> to ignore case:</p>\n<pre><code>if(Console.ReadLine().Equals(&quot;r&quot;, StringComparison.OrdinalIgnoreCase))\n{\n Environment.Exit(0);\n}\n</code></pre>\n<p>Also, your user input validation is a good start, but still need a better handling. As the current approach will invalidate the results or throw some exceptions if either inputs is invalid.</p>\n<p>To improve this approach, you need to ensure that your application always gets the correct value from the user, and prevent the application from moving to the next step if it's invalid. This means, on every input, you'll put the user in a loop to validate the given input, if the input is invalid, then notify the user to get a new input or exit. So, each step will either pass the validation or exit the application by the user.</p>\n<p>Example :</p>\n<pre><code>Console.WriteLine(&quot;Enter the first number in the range to find out it odd or even.&quot;);\n\nwhile(int.TryParse(Console.ReadLine(), out rangeStartInclusive) == false)\n{\n Console.WriteLine(&quot;Invalid input, only integers are expected. Please enter an integer number OR Press R to exit.&quot;);\n\n if(Console.ReadLine().Equals(&quot;r&quot;, StringComparison.OrdinalIgnoreCase))\n {\n Environment.Exit(0);\n } \n}\n</code></pre>\n<p>Instead of asking the user to enter <code>R</code> to continue, you need to ask the user to input <code>R</code> to exit (or whatever letter you like). This would forces the user to enter only correct inputs (take it or leave situation). As you need to narrow down user freedom to control the inputs and avoid any unhandled cases and to minimize code vulnerabilities (play it safe). (this is something you should keep in mind as it would increase your code security awareness over the time).</p>\n<p>Now, you can take this loop and move it to another method to reuse it on each user input.</p>\n<p>example :</p>\n<pre><code>private static int GetUserInputAsInt(string message) \n{\n int result = 0;\n \n Console.WriteLine(message);\n \n while(int.TryParse(Console.ReadLine(), out result) == false)\n {\n Console.WriteLine(&quot;Invalid input, only integers are expected. Please enter an integer number OR Press R to exit.&quot;);\n\n if(Console.ReadLine().Equals(&quot;r&quot;, StringComparison.OrdinalIgnoreCase))\n {\n Environment.Exit(0);\n } \n }\n\n return result;\n}\n</code></pre>\n<p>then you can simply do this :</p>\n<pre><code>int rangeStartInclusive = GetUserInputAsInt(&quot;Enter the first number in the range to find out it odd or even.&quot;);\n\nint rangeEndInclusive = GetUserInputAsInt(&quot;Enter the second number&quot;);\n</code></pre>\n<p>Now, you do a method for counting the odds and evens and summing!, and since you're working with mathematical scope, you will also need to do more researching about it, to simplify your work more further.</p>\n<p>For instance, you don't need a loop to count the odds and evens, there is a mathematical pattern (not my greatest subject), not sure if there is a solid formula that can be used, but from what I can see you can determine the number of odds by subtracting the numbers and dividing them by 2.</p>\n<p>Example :</p>\n<pre><code>input : 10,50 \nOdds = 50 - 10 = 40 = 40 / 2 = 20\nSum = 10 + 20 = 30 x 20 = 600\n---------------\ninput : 22,30 \nOdds = 30 - 22 = 8 = 8 / 2 = 4\nSum = 22 + 4 = 26 x 4 = 104\n---------------\n// with odds inputs\ninput : 1,10 \nOdds = 10 - 1 = 9 = (9 - 1) / 2 = 4 + 1 = 5\nSum = 1 + 9 = (10 / 2) x 5 = 25\n---------------\ninput : 11,30 \nOdds = 30 - 11 = 19 = (19 - 1) / 2 = 9 + 1 = 10\nSum = 11 + 19 = (30/ 2) x 10 = 150\n</code></pre>\n<p>So, we can use this to our advantage and elimnate the need of the loops by doing something like :</p>\n<pre><code>public static int CountOddNumbers(int leftHand, int rightHand)\n{\n if(leftHand == 0 &amp;&amp; rightHand == 0) { return 0; }\n\n int subtractHands = Math.Abs(leftHand - rightHand);\n\n if(subtractHands == 0) { return 0; }\n\n int count = subtractHands / 2;\n\n if(count == 0) { return 1; }\n\n if(leftHand % 2 != 0 || rightHand % 2 != 0) { count++; }\n\n return count;\n}\n\npublic static int SumOddNumbers(int leftHand, int rightHand)\n{\n int count = CountOddNumbers(leftHand, rightHand);\n\n int sum = Math.Min(leftHand , rightHand) + count;\n \n if(leftHand % 2 != 0 || rightHand % 2 != 0) { count++; }\n\n sum *= count;\n \n return sum; \n}\n</code></pre>\n<p>for the even numbers, I found that the count of odd numbers is always equal to even numbers, not sure if there is edge cases to this, but we can do this :</p>\n<pre><code>public static int CountEvenNumbers(int leftHand, int rightHand)\n{\n int odds = CountOddNumbers(leftHand, rightHand);\n\n int subtractHands = Math.Abs(leftHand - rightHand) + 1;\n\n return subtractHands - odds;\n}\n</code></pre>\n<p>Now, revising your code would be something like this :</p>\n<pre><code>public static void Main(string[] args)\n{\n int rangeStartInclusive = GetUserInputAsInt(&quot;Enter the first number in the range to find out it odd or even.&quot;);\n \n int rangeEndInclusive = GetUserInputAsInt(&quot;Enter the second number&quot;);\n \n int oddNumbersCount = CountOddNumbers(rangeStartInclusive, rangeEndInclusive);\n \n int evenNumbersCount = CountEvenNumbers(rangeStartInclusive, rangeEndInclusive);\n \n int sum = SumOddNumbers(rangeStartInclusive, rangeEndInclusive);\n \n Console.WriteLine($&quot;Sum: {sum} | Even: {evenNumbersCount} | Odd: {oddNumbersCount}&quot;);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:40:13.720", "Id": "519459", "Score": "0", "body": "Thank you, I know math and thought about this realization. It would be much faster, you're right." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T21:57:15.140", "Id": "262865", "ParentId": "262789", "Score": "1" } }, { "body": "<p>If you ever get interested in converting the code from procedural to object-oriented, here are some thoughts on an object model (excluding the user input piece):</p>\n<pre><code>public class Number\n{\n public int Value { get; private set; } \n public bool IsEven { get; private set; }\n public bool IsOdd { get; private set; }\n \n public Number(int i) \n {\n Value = i;\n IsEven = Value % 2 == 0;\n IsOdd = !IsEven;\n }\n}\n\npublic class Numbers\n{\n public List&lt;Number&gt; Items { get; private set; }\n\n public Numbers(List&lt;Number&gt; items) =&gt; Items = items;\n\n public int Total() =&gt; Items.Sum(n =&gt; n.Value);\n public List&lt;Number&gt; Odds() =&gt; Items.Where(i =&gt; i.IsOdd).ToList();\n public List&lt;Number&gt; Evens() =&gt; Items.Where(i =&gt; i.IsEven).ToList();\n\n public override string ToString() =&gt;\n $&quot;Sum: {Total():N0} | Evens: {Evens().Count:N0} | Odds: {Odds().Count:N0}&quot;;\n}\n\npublic class App\n{\n public void Run()\n {\n var range = Enumerable.Range(1, 10).Select(i =&gt; new Number(i)).ToList();\n var numbers = new Numbers(range);\n Console.WriteLine(numbers.ToString());\n }\n}\n\nclass Program \n{\n static void Main()\n {\n var app = new App();\n app.Run();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T14:31:43.317", "Id": "519091", "Score": "0", "body": "Feels like overkill to determine odd or even. Plus your IsEven and IsOdd should be class properties instead of methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T12:43:56.170", "Id": "519166", "Score": "0", "body": "Good point, I switched IsEven and IsOdd to properties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:37:13.763", "Id": "519458", "Score": "0", "body": "This is good, but not quite my level yet. What is the advantage in converting code from procedural to object-oriented?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T15:58:11.593", "Id": "519966", "Score": "0", "body": "Good question. While you can write procedural code in it, C# is an object-oriented language, so it's best-suited to writing object-oriented code. Object-oriented programming is its own discipline, subject to many holy wars about its validity and usefulness." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T20:58:47.360", "Id": "262954", "ParentId": "262789", "Score": "1" } } ]
{ "AcceptedAnswerId": "262806", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T11:02:43.310", "Id": "262789", "Score": "0", "Tags": [ "c#", "beginner" ], "Title": "Calculating sum and count of even and odd numbers (follow-up)" }
262789
<p>(See the previous version <a href="https://codereview.stackexchange.com/questions/213961/a-simple-clusterness-measure-of-data-in-one-dimension-using-java">here</a>.)</p> <p>(See the next version <a href="https://codereview.stackexchange.com/questions/262932/a-simple-clusterness-measure-of-data-in-one-dimension-using-java-follow-up-2">here</a>.)</p> <p>This time, I have incorporated all the suggestions made by <a href="https://codereview.stackexchange.com/users/149394/roman">Roman</a>; my new version follows.</p> <pre><code>package com.github.coderodde.codereview.notepad; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * This class implements a method for computing clusterness measure (CM). CM * asks for a set of points {@code x_1, x_2, ..., x_n}, and it returns a * number within {@code [0, 1]}. The idea behind CM is that it returns 0 when * all the data points are equal and 1 whenever all adjacent points are * equidistant. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.61 (Jun 10, 2019) * @since 1.6 (Feb 21, 2019) */ public final class ClusternessMeasure { public double computeClusternessMeasure(Collection&lt;Double&gt; points) { return computeClusternessMeasure(new SortedMeasurementPoints(points)); } public double computeClusternessMeasure(SortedMeasurementPoints points) { double minimumPoint = points.get(0); double maximumPoint = points.get(points.indexOfLastEntry()); double range = maximumPoint - minimumPoint; if (range == 0.0) { // Once here, all data points are equal and so CM must be 1.0. return 1.0; } double expectedDifference = range / points.indexOfLastEntry(); double sum = 0.0; for (int i = 0; i &lt; points.indexOfLastEntry(); i++) { double currentDifference = points.get(i + 1) - points.get(i); sum += Math.min( Math.abs(expectedDifference - currentDifference), expectedDifference); } return sum / range; } public static final class SortedMeasurementPoints { private final List&lt;Double&gt; points; public SortedMeasurementPoints(Collection&lt;Double&gt; points) { List&lt;Double&gt; pointsAsList = new ArrayList&lt;&gt;(points); Collections.sort(pointsAsList); this.points = pointsAsList; } public double get(int index) { return points.get(index); } public int indexOfLastEntry() { return points.size() - 1; } } public static void main(String[] args) { ClusternessMeasure cm = new ClusternessMeasure(); // CM = 0.0 System.out.println( cm.computeClusternessMeasure( Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0))); // CM = 1.0 System.out.println( cm.computeClusternessMeasure( Arrays.asList(2.0, 2.0, 2.0))); System.out.println( cm.computeClusternessMeasure( Arrays.asList(1.0, 2.0, 3.0, 5.0, 4.0, 6.0, 7.1))); System.out.println( cm.computeClusternessMeasure( Arrays.asList(1.0, 1.2, 3.0, 3.0, 3.0))); } } </code></pre> <p><strong>Critique request</strong></p> <p>I would like to receive the comments regarding both the code and idea. Thank you in advance.</p>
[]
[ { "body": "<h2>Tests</h2>\n<p>Unit tests are better than printing to the console. One example:</p>\n<pre><code>@Test\npublic void testReturn0WhenEquidistantPoints() {\n ClusternessMeasure cm = new ClusternessMeasure();\n List&lt;Double&gt; points = List.of(1.0, 2.0, 3.0, 4.0, 5.0);\n double expected = 0.0;\n double delta = 0.0;\n\n double actual = cm.computeClusternessMeasure(points);\n\n assertEquals(expected, actual, delta);\n}\n</code></pre>\n<p>In this way, there is no need to check if the code prints the correct output to the console, Junit will take care of it.</p>\n<h2>Static</h2>\n<p>From what I see, <code>ClusternessMeasure</code> holds no state, so its methods could be static. You could have something like:</p>\n<pre><code>double result = ClusternessMeasure.compute(points);\n</code></pre>\n<h2>Streams</h2>\n<p>Depending on the version of Java you plan to use, in this part:</p>\n<pre><code>public SortedMeasurementPoints(Collection&lt;Double&gt; points) {\n List&lt;Double&gt; pointsAsList = new ArrayList&lt;&gt;(points);\n Collections.sort(pointsAsList);\n this.points = pointsAsList;\n}\n</code></pre>\n<p>you could use Streams:</p>\n<pre><code>public SortedMeasurementPoints(Collection&lt;Double&gt; points) {\n this.points = points.stream().sorted()\n .collect(Collectors.toUnmodifiableList());\n}\n</code></pre>\n<p>It is also handy that the result will be an unmodifiable list since <code>points</code> don't need to change.</p>\n<h2>Design</h2>\n<p>The class <code>ClusternessMeasure</code> exposes two public methods:</p>\n<ol>\n<li><code>double computeClusternessMeasure(Collection&lt;Double&gt; points)</code></li>\n<li><code>double computeClusternessMeasure(SortedMeasurementPoints points)</code></li>\n</ol>\n<p>Both give the same result, but the second requires an instance of <code>SortedMeasurementPoints</code>. The caller (likely) won't already have an instance of it so it needs to study that class to know wheater he needs it or not. Finally, realizing that passing an unsorted collection is the same as wrapping it in a <code>SortedMeasurementPoints</code>. For this reason, I think that the second method is an unnecessary burden for the caller, and it can be private.</p>\n<h2>Input validation</h2>\n<pre><code>List&lt;Double&gt; buggyList = Arrays.asList(1.0,null);\ncm.computeClusternessMeasure(buggyList); // NullPointerException\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T02:43:19.877", "Id": "262871", "ParentId": "262790", "Score": "1" } } ]
{ "AcceptedAnswerId": "262871", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T12:04:09.970", "Id": "262790", "Score": "1", "Tags": [ "java", "machine-learning", "numerical-methods" ], "Title": "A simple clusterness measure of data in one dimension using Java - follow-up" }
262790
<p>(See the previous version <a href="https://codereview.stackexchange.com/questions/250586/a-simple-c-winapi-program-for-terminating-processes-via-process-image-names-fo">here</a>.)</p> <p><strong>What's new</strong></p> <ol> <li><code>get_last_err_msg</code> renamed to <code>MyGetLastErrorMessage</code></li> <li>The caller to <code>MyGetLastErrorMessage</code> is responsible for <code>free</code>ing the string</li> <li>The error messages are set to <code>NULL</code> after freeing</li> <li>Instead of <code>char*</code>, a WinAPI type <code>LPCSTR</code> is used</li> </ol> <p><strong>Code</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;windows.h&gt; #include &lt;shlwapi.h&gt; #include &lt;TlHelp32.h&gt; #pragma comment(lib, &quot;Shlwapi.lib&quot;) static LPCSTR MyGetLastErrorMessage() { DWORD errorMessageId = GetLastError(); if (errorMessageId == 0) { return &quot;no errors&quot;; } LPCSTR messageBuffer = NULL; size_t size = FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&amp; messageBuffer, 65535, // MSDN tells max length is 64K NULL); return messageBuffer; } int main(int argc, char* argv[]) { if (argc != 2) { char* bname = _strdup(argv[0]); PathStripPath(bname); fprintf(stderr, &quot;%s PROCESS_NAME\n&quot;, bname); free(bname); return EXIT_FAILURE; } PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (snapshot == INVALID_HANDLE_VALUE) { LPCSTR szLastErrorMessage = MyGetLastErrorMessage(); fprintf( stderr, &quot;Error: could not get the process snapshot. &quot; &quot;Cause: %s\n&quot;, szLastErrorMessage); free((void*) szLastErrorMessage); szLastErrorMessage = NULL; return EXIT_FAILURE; } size_t totalProcesses = 0; size_t totalProcessesMatched = 0; size_t totalProcessesTerminated = 0; if (Process32First(snapshot, &amp;entry)) { do { totalProcesses++; if (strcmp(entry.szExeFile, argv[1]) != 0) { continue; } totalProcessesMatched++; HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, entry.th32ProcessID); if (hProcess == NULL) { LPCSTR szLastErrorMessage = MyGetLastErrorMessage(); fprintf(stderr, &quot;Error: could not open the process with ID = %d, &quot; &quot;called \&quot;%s\&quot;. &quot; &quot;Cause: %s&quot;, entry.th32ProcessID, entry.szExeFile, szLastErrorMessage); free((void*) szLastErrorMessage); szLastErrorMessage = NULL; } else { if (TerminateProcess(hProcess, 0)) { totalProcessesTerminated++; printf(&quot;Terminated process ID %d\n&quot;, entry.th32ParentProcessID); } else { LPCSTR szLastErrorMessage = MyGetLastErrorMessage(); fprintf( stderr, &quot;Warning: could not terminate the process with ID %d. &quot; &quot;Cause: %s&quot;, entry.th32ProcessID, szLastErrorMessage); free((void*) szLastErrorMessage); szLastErrorMessage = NULL; } if (!CloseHandle(hProcess)) { LPCSTR szLastErrorMessage = MyGetLastErrorMessage(); fprintf( stderr, &quot;Warning: could not close the handle to the process ID %d. &quot; &quot;Cause: %s&quot;, entry.th32ProcessID, szLastErrorMessage); free((void*) szLastErrorMessage); szLastErrorMessage = NULL; } } } while (Process32Next(snapshot, &amp;entry)); } BOOL snapshotHandleClosed = CloseHandle(snapshot); if (!snapshotHandleClosed) { LPCSTR szLastErrorMessage = MyGetLastErrorMessage(); fprintf(stderr, &quot;Warning: could not close the process snapshot. Cause: %s&quot;, szLastErrorMessage); free((void*) szLastErrorMessage); szLastErrorMessage = NULL; } printf(&quot;Info: total processes: %zu, &quot; &quot;total matching processes: %zu, total terminated: %zu.\n&quot;, totalProcesses, totalProcessesMatched, totalProcessesTerminated); return EXIT_SUCCESS; } </code></pre> <p><strong>Critique request</strong></p> <p>Please tell me anything that comes to mind.</p>
[]
[ { "body": "<p>Copying and pasting from my previous answer, your (feasible) options for error string memory management are</p>\n<ul>\n<li>Make the caller contract such that the caller is responsible for calling <code>LocalFree</code>, or</li>\n<li>Have <code>get_last_err_msg()</code> accept a buffer and size instead, and simply have <code>FormatMessage</code> fill that buffer</li>\n</ul>\n<p>I made a mistake in offering the first without a warning on memory sections, since that's not going to work given your inconsistent use of string literals and heap-allocated strings. In your previous question this was an unobtrusive but still problematic <code>&quot;&quot;</code>; now it's a <code>&quot;no errors&quot;</code>. You can easily get into hot water if a call fails but the error message ID is 0 - you're unconditionally freeing the string, and attempting to free a string literal is going to ruin your day.</p>\n<p>So you can either:</p>\n<ul>\n<li>in the case of &quot;no errors&quot;, conditionally allocate, <code>strcpy</code> and return your buffer; or</li>\n<li>do option 2 from above, which would be a <code>strcpy</code> only.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T14:46:38.750", "Id": "262852", "ParentId": "262793", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T13:00:01.607", "Id": "262793", "Score": "1", "Tags": [ "c", "windows", "winapi" ], "Title": "A simple C WinAPI program for terminating processes via process image names - follow-up 4" }
262793
<p>I put this together for a task and thought some feedback would be useful.</p> <pre><code>class Matrix&lt;T : Ring&lt;T&gt;&gt;(val size: Size, init: (x: Int, y: Int) -&gt; T) : Ring&lt;Matrix&lt;T&gt;&gt; { init { require(size.x &gt; 0 &amp;&amp; size.y &gt; 0) { &quot;Zero size Matrix is invalid.&quot; } } // Use a list of lists for the data private val a: List&lt;List&lt;T&gt;&gt; = List(size.y) { y -&gt; List(size.x) { x -&gt; init.invoke(x, y) } } // NB: These are memoised `zero` and `one` of T, not Matrix&lt;T&gt; private val zero: T = a[0][0].zero() private val one: T = a[0][0].one() // Allows matrix[x,y] operator fun get(x: Int, y: Int): T = a[y][x] // Entrywise sum override operator fun plus(b: Matrix&lt;T&gt;): Matrix&lt;T&gt; { require(size == b.size) { &quot;Matrix addition requires matrices of the same size. ($size != ${b.size})&quot; } return Matrix(size) { x, y -&gt; this[x, y] + b[x, y] } } // Normal matrix multiply override operator fun times(b: Matrix&lt;T&gt;): Matrix&lt;T&gt; { require(size.x == b.size.y) { &quot;Matrix multiplication requires the same number of columns in the multiplicand as rows in the multiplier. (${size.x} != ${b.size.y})&quot; } return Matrix(Size(b.size.x, size.y)) { x, y -&gt; (0 until size.x).sumBy { n -&gt; this[n, y] * b[x, n] } } } // Scalar multiply operator fun times(c: T): Matrix&lt;T&gt; = Matrix(size) { x, y -&gt; this[x, y] * c } // zero() and one() are memoized - not sure if this is worthwhile. @Suppress(&quot;UNCHECKED_CAST&quot;) override fun zero(): Matrix&lt;T&gt; = ZEROS.computeIfAbsent(Pair(size, zero)) { Matrix(size) { _, _ -&gt; zero } } as Matrix&lt;T&gt; @Suppress(&quot;UNCHECKED_CAST&quot;) override fun one(): Matrix&lt;T&gt; = ONES.computeIfAbsent(Triple(size, zero, one)) { Matrix(size) { x, y -&gt; if (x == y) one else zero } } as Matrix&lt;T&gt; // Transpose. fun transpose(): Matrix&lt;T&gt; = Matrix(Size(size.y, size.x)) { x, y -&gt; this[y, x] } // Power fun pow(n: Int): Matrix&lt;T&gt; = pow(n.toBigInteger()) // Using Exponentiation by Squaring - https://en.wikipedia.org/wiki/Exponentiation_by_squaring fun pow(n: BigInteger): Matrix&lt;T&gt; = when (n) { BigInteger.ZERO -&gt; one() BigInteger.ONE -&gt; this else -&gt; { val v = (this * this).pow(n shr 1) if(n.testBit(0)) v * this else v } } // pow(2^n) - Just square it n times. fun pow2n(n: Int): Matrix&lt;T&gt; = (0 until n).fold(this) { v, _ -&gt; v * v } fun row(i: Int): Iterable&lt;T&gt; = a[i].asIterable() fun col(i: Int): Iterable&lt;T&gt; = a.map { it[i] } // Normal sumBy returns `Int` - I want a T private inline fun Iterable&lt;Int&gt;.sumBy(selector: (Int) -&gt; T): T = this.fold(zero) { v, i -&gt; v + selector(i) } override fun toString(): String = &quot;{${size}:${if (size.y &gt; 1) &quot;\n&quot; else &quot;&quot;}&quot; + a.joinToString(prefix = &quot;[&quot;, separator = &quot;]\n[&quot;, postfix = &quot;]&quot;) { it.joinToString(separator = &quot;,&quot;) { v -&gt; v.toString() } } + &quot;}&quot; override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return (a == (other as Matrix&lt;*&gt;).a) } override fun hashCode(): Int = a.hashCode() companion object { // Multitons for zero and one so we don't create more than we need and equals will shortcut. // The zeros map is keyed on the size and zero of the field. private val ZEROS: ConcurrentMap&lt;Pair&lt;Size, Ring&lt;*&gt;&gt;, Matrix&lt;*&gt;&gt; = ConcurrentHashMap() // The ones map is keyed on the size, zero AND one of the field. private val ONES: ConcurrentMap&lt;Triple&lt;Size, Ring&lt;*&gt;, Ring&lt;*&gt;&gt;, Matrix&lt;*&gt;&gt; = ConcurrentHashMap() } } </code></pre> <p>Here's <code>Ring</code></p> <pre><code>/** * Defines an object with operators + and *, a zero and an identity * * Technically this is actually an `Rng` but Ring is close enough and easier to say. * * See https://en.wikipedia.org/wiki/Ring_(mathematics) */ interface Ring&lt;T&gt; { operator fun plus(b: T): T operator fun times(b: T): T fun zero(): T fun one(): T } </code></pre> <p>Here's a <code>BigInteger</code> implementation of <code>Ring</code>.</p> <pre><code>data class BigIntegerRing(private val v: BigInteger) : Ring&lt;BigIntegerRing&gt; { override fun zero(): BigIntegerRing = ZERO override fun one(): BigIntegerRing = ONE override fun plus(b: BigIntegerRing): BigIntegerRing = BigIntegerRing(v + b.v) override fun times(b: BigIntegerRing): BigIntegerRing = BigIntegerRing(v * b.v) override fun toString() = v.toString() companion object { val ZERO: BigIntegerRing = BigIntegerRing(BigInteger.ZERO) val ONE: BigIntegerRing = BigIntegerRing(BigInteger.ONE) // Make a matrix from Ints fun matrix(size: Size, init: (x: Int, y: Int) -&gt; Int): Matrix&lt;BigIntegerRing&gt; = Matrix(size) { x, y -&gt; BigIntegerRing(init(x, y).toBigInteger()) } } } </code></pre> <p>And a Galois Field(2) Ring.</p> <pre><code>enum class GF2 : Ring&lt;GF2&gt; { ZERO, ONE; override fun zero(): GF2 = ZERO override fun one(): GF2 = ONE // plus -&gt; xor override fun plus(b: GF2): GF2 = if (this === b) ZERO else ONE // times -&gt; and override fun times(b: GF2): GF2 = if (this === ONE &amp;&amp; b === ONE) ONE else ZERO override fun toString(): String = ordinal.toString() companion object { // Factory from boolean. operator fun invoke(b: Boolean): GF2 = if (b) ONE else ZERO // Make a matrix fun matrix(size: Size, init: (x: Int, y: Int) -&gt; GF2): Matrix&lt;GF2&gt; = Matrix(size, init) } } </code></pre> <p>And of course <code>Size</code> is trivial.</p> <pre><code>data class Size(val x: Int, val y: Int) { override fun toString() = &quot;(${x}x${y})&quot; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T13:27:49.850", "Id": "262796", "Score": "1", "Tags": [ "kotlin" ], "Title": "Matrix implementation in Kotlin" }
262796
<p>I was looking at a dataset with a <code>year</code> column. I wanted all the years with matching a particular event. I then get a list of years which is not easy to read:</p> <pre><code>2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020 </code></pre> <p>It would be much better to display them as:</p> <pre><code>2010-2013, 2015, 2017-2020 </code></pre> <p>I was looking for a builtin function in Python, but eventually, I wrote this:</p> <pre><code>import numpy as np def ranges(array): start = None for i, k in zip(np.diff(array, append=[array[-1]]), array): if i == 1: if start is None: start = k continue yield(k if start is None else (start, k)) start = None </code></pre> <p>Is there a more pythonic way that does the same with less?</p> <p>At the end I could do this:</p> <pre><code>years = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020] ', '.join([f'{x[0]}-{x[1]}' if isinstance(x, tuple) else str(x) for x in ranges(years)]) </code></pre>
[]
[ { "body": "<p>I'm glad you asked this question, as I've had a difficult time finding the solution recently as well. However, I have now found that the solution is to use the <code>more_itertools</code> <a href=\"https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consecutive_groups\" rel=\"nofollow noreferrer\">consecutive_groups</a> function:</p>\n<pre><code>from more_itertools import consecutive_groups\nx = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020]\n\n# create an intermediate list to avoid having unnecessary list calls in the next line\nsubsets = [list(group) for group in consecutive_groups(x)]\n\nresult = [f&quot;{years[0]}-{years[-1]}&quot; if len(years) &gt; 1 else f&quot;{years[0]}&quot; for years in subsets]\n# ['2010-2013', '2015', '2017-2020']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:33:14.837", "Id": "262801", "ParentId": "262797", "Score": "5" } }, { "body": "<p>I like the <code>more_itertools</code> answer by @kraigolas as it is super clean. However, I don't know this module at all (looks like maybe I should look into it though). So if it were me, and since you already have a solution using <code>numpy</code> I might do:</p>\n<pre><code>def get_intervals(data):\n intervals = numpy.split(data, numpy.where(numpy.diff(data) &gt; 1)[0] + 1)\n return [(interval[0], interval[-1]) for interval in intervals]\n</code></pre>\n<p>To print I would then use a format method like:</p>\n<pre><code>def fmt_for_print(interval):\n return f&quot;{ interval[0] }&quot; if interval[0] == interval[1] else f&quot;{ interval[0] }-{ interval[1] }&quot;\n</code></pre>\n<p>Then you can:</p>\n<pre><code>years = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020]\nprint(', '.join([fmt_for_print(interval) for interval in get_intervals(years)]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T15:01:29.890", "Id": "262803", "ParentId": "262797", "Score": "1" } } ]
{ "AcceptedAnswerId": "262801", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T13:32:50.247", "Id": "262797", "Score": "5", "Tags": [ "python", "algorithm" ], "Title": "Find all subranges of consecutive values in an array" }
262797
<p>I want to implement a client storage mechanism that is as persistent as a session cookie but with more storage capacity.</p> <p>I am doing this by encrypting the data before storing it and saving the keys in a session cookie, when this session cookie is gone the data can not be restored. Data is stored in a permanent webStorage such as localStorage or IndexedDB. I'll just talk about the localStorage case here.</p> <p>The reason I am asking for a code review is concerning the security of that storage. Is it possible that different tabs generate different browserSession keys? Can an IV-reuse happen if multiple tabs are open at the same time? Am I using the WebCryptoApi correctly? I am leaking the keys to the server, is this a serious security issue considering I am storing sensitive data? Is there a way for the keys NOT to be sent to the server?</p> <p>The code is separated into 4 parts. The first two (cookies, conversions) are just here for completeness, the other two provide the functionality I am looking for.</p> <ol> <li>cookies</li> <li>conversions</li> <li>browserSession: From here I manage keys and nonces that can be used in the browserSession. The name is not perfect, but this can be thought of as a keyChain.</li> <li>browserSessionStorage: Using keys and nonces from browserSession, this implements a storage mechanism that is used similar to localStorage and sessionStorage</li> </ol> <p>Ad 1) cookies:</p> <pre><code>let cookies = { set: function(name, value, options={}) { let cookie = name + &quot;=&quot; + value; for(let key in options) { if(key != 'secure') { cookie += ';' + key + '=' + options[key]; } else if(options[key] == true) { cookie += ';' + key; } } document.cookie = cookie; }, get: function(name) { name = name + &quot;=&quot;; for(let cookie of document.cookie.split(';')) { cookie = cookie.trimLeft(); if(cookie.startsWith(name)) { return cookie.substring(name.length, cookie.length); } } return undefined; }, delete: function(name, options={}) { if(typeof options != &quot;object&quot;) { options = {}; } options['max-age'] = 0; cookies.set(name, false, options); }, httpOnly: function(name) { let tmp = cookies.get(name); if(tmp !== undefined) { // this is not a httpOnly cookie return false; } // cookie not existing or httpOnly, check whatever it is by trying to write it cookies.set(name, &quot;test&quot;); let value = cookies.get(name); if(value === undefined) { // this is a httpOnly cookie return true; } else { // not httpOnly, remove the cookie again cookies.delete(name); return false; } } } </code></pre> <p>Ad 2) conversions:</p> <pre><code>function buffer2uint8Array(buffer) { return new Uint8Array(buffer); } function uint8Array2utf8(uint8Array) { return String.fromCharCode(...uint8Array); } function buffer2utf8(buffer) { let uint8Array = buffer2uint8Array(buffer); return uint8Array2utf8(uint8Array); } function utf82uint8Array(utf8) { return Uint8Array.from([...utf8].map(ch =&gt; ch.charCodeAt())) } function utf82base64(utf8) { return btoa(utf8); } function base642utf8(base64) { return atob(base64); } function uint8Array2base64(uint8Array) { let utf8 = uint8Array2utf8(uint8Array); return utf82base64(utf8); } function buffer2base64(buffer) { let uint8Array = buffer2uint8Array(buffer); let utf8 = uint8Array2utf8(uint8Array); return utf82base64(utf8); } function base642uint8Array(base64) { let utf8 = base642utf8(base64); return utf82uint8Array(utf8); } function uint16Array2utf16(uint16Array) { return String.fromCharCode(...uint16Array); } function uint8Array2utf16(uint8Array) { let uint16Array = new Uint16Array(uint8Array.buffer); return uint16Array2utf16(uint16Array); } function utf162uint16Array(utf16) { return Uint16Array.from([...utf16].map(ch =&gt; ch.charCodeAt())) } function utf162uint8Array(utf16) { let uint16Array = utf162uint16Array(utf16); return new Uint8Array(uint16Array.buffer); } </code></pre> <p>Ad 3) browserSession:</p> <pre><code>// provides browserSession keys and nonces // dependencies: // - conversions // - cookies let browserSession = (function() { class Counter { constructor(uint8Array) { this.uint8Array = uint8Array; } next() { let carry = true; for(let i = this.uint8Array.byteLength; i &gt; 0; --i) { let index = i-1; let prev = this.uint8Array[index]; this.uint8Array[index] += 1 * carry; carry = prev == 255 &amp;&amp; this.uint8Array[index] == 0; } if(carry) { throw(&quot;IV overflow&quot;); } return this.uint8Array; } } let browserSession = { hasKey: function(keyName) { if(keyName === null || keyName === undefined) { throw([{&quot;Invalid key name&quot; : keyName }]); } let keys = cookies.get('browserSessionKeys'); keys = keys ? JSON.parse(keys) : {}; return keyName in keys; }, key: function(keyName, keyByteLength, nonceByteLength) { if(keyName === null || keyName === undefined) { throw([{&quot;invalid key name&quot; : keyName }]); } let keys = cookies.get('browserSessionKeys'); keys = keys ? JSON.parse(keys) : {}; if(keyName in keys == false) { keys[keyName] = uint8Array2base64(crypto.getRandomValues(new Uint8Array(keyByteLength))); cookies.set('browserSessionKeys', JSON.stringify(keys), {secure:true}); let nonces = localStorage.getItem('browserSessionNonces'); nonces = nonces ? JSON.parse(nonces) : {}; nonces[keyName] = uint8Array2utf8(new Uint8Array(nonceByteLength)); localStorage.setItem('browserSessionNonces', JSON.stringify(nonces)); } return base642uint8Array(keys[keyName]); }, nonce: function(keyName, nonceByteLength) { if(keyName === null || keyName === undefined) { throw([{&quot;invalid key name&quot; : keyName }]); } if(browserSession.hasKey(keyName) == false) { throw([{&quot;key not initialized&quot; : keyName }]); } let nonces = JSON.parse(localStorage.getItem('browserSessionNonces')); let returnNonce = utf82uint8Array(nonces[keyName]); { // update nonce let nonce = new Counter(utf82uint8Array(nonces[keyName])); nonces[keyName] = uint8Array2utf8(nonce.next()); localStorage.setItem('browserSessionNonces', JSON.stringify(nonces)); } return returnNonce; }, } return browserSession; })(); if(cookies.get('browserSessionKeys') == null) { localStorage.removeItem('browserSessionNonces'); } </code></pre> <p>Ad 4) browserSessionStorage</p> <pre><code>// creates a browserSessionStorage that is accessible as long as the browserSession lasts // the data is managed from localStorage // dependencies: // - browserSession // - conversions let browserSessionStorage = (function() { let storagePrefix = 'browserSessionStorage.'; function withPrefix(keyName) { let encoder = new TextEncoder(); let decoder = new TextDecoder(); return storagePrefix + decoder.decode(encoder.encode(keyName)); } let browserSessionStorage = { removeItem: function(keyName) { keyName = withPrefix(keyName); localStorage.removeItem(keyName); }, clear: function() { for(let key in localStorage) { if(key.startsWith(storagePrefix)) { localStorage.removeItem(key); } } }, }; let keyByteLength = 256 / 8; let ivByteLength = 96 / 8; if(browserSession.hasKey('browserSessionStorageKey') == false) { browserSessionStorage.clear(); // initialize key and nonce browserSession.key('browserSessionStorageKey', keyByteLength, ivByteLength); } let key = (function() { let key = null; return async function() { if(key == null) { let rawKey = browserSession.key('browserSessionStorageKey'); key = await crypto.subtle.importKey( 'raw', rawKey, 'AES-GCM', true, ['encrypt','decrypt'] ); } return key; } })(); function nextIv() { return browserSession.nonce('browserSessionStorageKey'); } browserSessionStorage.setItem = async function(keyName, keyValue) { keyName = withPrefix(keyName); // encrypt the encoded keyValue let encoded = new TextEncoder().encode(keyValue); let iv = nextIv(); let encrypted = await window.crypto.subtle.encrypt({ name: &quot;AES-GCM&quot;, iv: iv }, await key(), encoded); encrypted = new Uint8Array([ ...iv, ...new Uint8Array(encrypted) ]); localStorage.setItem(keyName, uint8Array2utf8(encrypted)); }; browserSessionStorage.getItem = async function(keyName) { keyName = withPrefix(keyName); // item may not exist let value = localStorage.getItem(keyName); if(value != null) { // decryption let encrypted = utf82uint8Array(value); let iv = encrypted.subarray(0, ivByteLength); encrypted = encrypted.subarray(ivByteLength); let decrypted = await window.crypto.subtle.decrypt({ name: &quot;AES-GCM&quot;, iv: iv }, await key(), encrypted); value = new TextDecoder().decode(decrypted); } return value; }; return browserSessionStorage; })(); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:11:01.420", "Id": "262798", "Score": "2", "Tags": [ "javascript", "session", "encryption", "browser-storage" ], "Title": "Javascript client storage with the same persistence as a session cookie" }
262798
<p>I have developed a game that allows you to play a full game of Tetris. I haven't really been getting the runs and plays. So I have a request for your reading... Can you possibly give me ideas and or make the code a little simpler.</p> <p>Here's the code that I made:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/python &quot;&quot;&quot; Python implementation of text-mode version of the Tetris game Quick play instructions: - a (return): move piece left - d (return): move piece right - w (return): rotate piece counter clockwise - s (return): rotate piece clockwise - e (return): just move the piece downwards as is &quot;&quot;&quot; import os import random import sys from copy import deepcopy # DECLARE ALL THE CONSTANTS BOARD_SIZE = 20 # Extra two are for the walls, playing area will have size as BOARD_SIZE EFF_BOARD_SIZE = BOARD_SIZE + 2 PIECES = [ [[1], [1], [1], [1]], [[1, 0], [1, 0], [1, 1]], [[0, 1], [0, 1], [1, 1]], [[0, 1], [1, 1], [1, 0]], [[1, 1], [1, 1]] ] # Constants for user input MOVE_LEFT = 'a' MOVE_RIGHT = 'd' ROTATE_ANTICLOCKWISE = 'w' ROTATE_CLOCKWISE = 's' NO_MOVE = 'e' QUIT_GAME = 'q' def print_board(board, curr_piece, piece_pos, error_message=''): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Details: -------- Prints out the board, piece and playing instructions to STDOUT If there are any error messages then prints them to STDOUT as well &quot;&quot;&quot; os.system('cls' if os.name=='nt' else 'clear') print(&quot;Text mode version of the TETRIS game\n\n&quot;) board_copy = deepcopy(board) curr_piece_size_x = len(curr_piece) curr_piece_size_y = len(curr_piece[0]) for i in range(curr_piece_size_x): for j in range(curr_piece_size_y): board_copy[piece_pos[0]+i][piece_pos[1]+j] = curr_piece[i][j] | board[piece_pos[0]+i][piece_pos[1]+j] # Print the board to STDOUT for i in range(EFF_BOARD_SIZE): for j in range(EFF_BOARD_SIZE): if board_copy[i][j] == 1: print(&quot;*&quot;, end='') else: print(&quot; &quot;, end='') print(&quot;&quot;) print(&quot;Quick play instructions:\n&quot;) print(&quot; - a (return): move piece left&quot;) print(&quot; - d (return): move piece right&quot;) print(&quot; - w (return): rotate piece counter clockwise&quot;) print(&quot; - s (return): rotate piece clockwise&quot;) # In case user doesn't want to alter the position of the piece # and he doesn't want to rotate the piece either and just wants to move # in the downward direction, he can choose 'f' print(&quot; - e (return): just move the piece downwards as is&quot;) print(&quot; - q (return): to quit the game anytime&quot;) if error_message: print(error_message) print(&quot;Your move:&quot;,) def init_board(): &quot;&quot;&quot; Parameters: ----------- None Returns: -------- board - the matrix with the walls of the gameplay &quot;&quot;&quot; board = [[0 for x in range(EFF_BOARD_SIZE)] for y in range(EFF_BOARD_SIZE)] for i in range(EFF_BOARD_SIZE): board[i][0] = 1 for i in range(EFF_BOARD_SIZE): board[EFF_BOARD_SIZE-1][i] = 1 for i in range(EFF_BOARD_SIZE): board[i][EFF_BOARD_SIZE-1] = 1 return board def get_random_piece(): &quot;&quot;&quot; Parameters: ----------- None Returns: -------- piece - a random piece from the PIECES constant declared above &quot;&quot;&quot; idx = random.randrange(len(PIECES)) return PIECES[idx] def get_random_position(curr_piece): &quot;&quot;&quot; Parameters: ----------- curr_piece - piece which is alive in the game at the moment Returns: -------- piece_pos - a randomly (along x-axis) chosen position for this piece &quot;&quot;&quot; curr_piece_size = len(curr_piece) # This x refers to rows, rows go along y-axis x = 0 # This y refers to columns, columns go along x-axis y = random.randrange(1, EFF_BOARD_SIZE-curr_piece_size) return [x, y] def is_game_over(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- True - if game is over False - if game is live and player can still move &quot;&quot;&quot; # If the piece cannot move down and the position is still the first row # of the board then the game has ended if not can_move_down(board, curr_piece, piece_pos) and piece_pos[0] == 0: return True return False def get_left_move(piece_pos): &quot;&quot;&quot; Parameters: ----------- piece_pos - position of piece on the board Returns: -------- piece_pos - new position of the piece shifted to the left &quot;&quot;&quot; # Shift the piece left by 1 unit new_piece_pos = [piece_pos[0], piece_pos[1] - 1] return new_piece_pos def get_right_move(piece_pos): &quot;&quot;&quot; Parameters: ----------- piece_pos - position of piece on the board Returns: -------- piece_pos - new position of the piece shifted to the right &quot;&quot;&quot; # Shift the piece right by 1 unit new_piece_pos = [piece_pos[0], piece_pos[1] + 1] return new_piece_pos def get_down_move(piece_pos): &quot;&quot;&quot; Parameters: ----------- piece_pos - position of piece on the board Returns: -------- piece_pos - new position of the piece shifted downward &quot;&quot;&quot; # Shift the piece down by 1 unit new_piece_pos = [piece_pos[0] + 1, piece_pos[1]] return new_piece_pos def rotate_clockwise(piece): &quot;&quot;&quot; Paramertes: ----------- piece - matrix of the piece to rotate Returns: -------- piece - Clockwise rotated piece Details: -------- We first reverse all the sub lists and then zip all the sublists This will give us a clockwise rotated matrix &quot;&quot;&quot; piece_copy = deepcopy(piece) reverse_piece = piece_copy[::-1] return list(list(elem) for elem in zip(*reverse_piece)) def rotate_anticlockwise(piece): &quot;&quot;&quot; Paramertes: ----------- piece - matrix of the piece to rotate Returns: -------- Anti-clockwise rotated piece Details: -------- If we rotate any piece in clockwise direction for 3 times, we would eventually get the piece rotated in anti clockwise direction &quot;&quot;&quot; piece_copy = deepcopy(piece) # Rotating clockwise thrice will be same as rotating anticlockwise :) piece_1 = rotate_clockwise(piece_copy) piece_2 = rotate_clockwise(piece_1) return rotate_clockwise(piece_2) def merge_board_and_piece(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- None Details: -------- Fixes the position of the passed piece at piece_pos in the board This means that the new piece will now come into the play We also remove any filled up rows from the board to continue the gameplay as it happends in a tetris game &quot;&quot;&quot; curr_piece_size_x = len(curr_piece) curr_piece_size_y = len(curr_piece[0]) for i in range(curr_piece_size_x): for j in range(curr_piece_size_y): board[piece_pos[0]+i][piece_pos[1]+j] = curr_piece[i][j] | board[piece_pos[0]+i][piece_pos[1]+j] # After merging the board and piece # If there are rows which are completely filled then remove those rows # Declare empty row to add later empty_row = [0]*EFF_BOARD_SIZE empty_row[0] = 1 empty_row[EFF_BOARD_SIZE-1] = 1 # Declare a constant row that is completely filled filled_row = [1]*EFF_BOARD_SIZE # Count the total filled rows in the board filled_rows = 0 for row in board: if row == filled_row: filled_rows += 1 # The last row is always a filled row because it is the boundary # So decrease the count for that one filled_rows -= 1 for i in range(filled_rows): board.remove(filled_row) # Add extra empty rows on the top of the board to compensate for deleted rows for i in range(filled_rows): board.insert(0, empty_row) def overlap_check(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- True - if piece do not overlap with any other piece or walls False - if piece overlaps with any other piece or board walls &quot;&quot;&quot; curr_piece_size_x = len(curr_piece) curr_piece_size_y = len(curr_piece[0]) for i in range(curr_piece_size_x): for j in range(curr_piece_size_y): if board[piece_pos[0]+i][piece_pos[1]+j] == 1 and curr_piece[i][j] == 1: return False return True def can_move_left(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- True - if we can move the piece left False - if we cannot move the piece to the left, means it will overlap if we move it to the left &quot;&quot;&quot; piece_pos = get_left_move(piece_pos) return overlap_check(board, curr_piece, piece_pos) def can_move_right(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- True - if we can move the piece left False - if we cannot move the piece to the right, means it will overlap if we move it to the right &quot;&quot;&quot; piece_pos = get_right_move(piece_pos) return overlap_check(board, curr_piece, piece_pos) def can_move_down(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- True - if we can move the piece downwards False - if we cannot move the piece to the downward direction &quot;&quot;&quot; piece_pos = get_down_move(piece_pos) return overlap_check(board, curr_piece, piece_pos) def can_rotate_anticlockwise(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- True - if we can move the piece anti-clockwise False - if we cannot move the piece to anti-clockwise might happen in case rotating would overlap with any existing piece &quot;&quot;&quot; curr_piece = rotate_anticlockwise(curr_piece) return overlap_check(board, curr_piece, piece_pos) def can_rotate_clockwise(board, curr_piece, piece_pos): &quot;&quot;&quot; Parameters: ----------- board - matrix of the size of the board curr_piece - matrix for the piece active in the game piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix w.r.t. the board Returns: -------- True - if we can move the piece clockwise False - if we cannot move the piece to clockwise might happen in case rotating would overlap with any existing piece &quot;&quot;&quot; curr_piece = rotate_clockwise(curr_piece) return overlap_check(board, curr_piece, piece_pos) def play_game(): &quot;&quot;&quot; Parameters: ----------- None Returns: -------- None Details: -------- - Initializes the game - Reads player move from the STDIN - Checks for the move validity - Continues the gameplay if valid move, else prints out error msg without changing the board - Fixes the piece position on board if it cannot be moved - Pops in new piece on top of the board - Quits if no valid moves and possible for a new piece - Quits in case user wants to quit &quot;&quot;&quot; # Initialize the game board, piece and piece position board = init_board() curr_piece = get_random_piece() piece_pos = get_random_position(curr_piece) print_board(board, curr_piece, piece_pos) # Get player move from STDIN player_move = input() while (not is_game_over(board, curr_piece, piece_pos)): ERR_MSG = &quot;&quot; do_move_down = False if player_move == MOVE_LEFT: if can_move_left(board, curr_piece, piece_pos): piece_pos = get_left_move(piece_pos) do_move_down = True else: ERR_MSG = &quot;Cannot move left!&quot; elif player_move == MOVE_RIGHT: if can_move_right(board, curr_piece, piece_pos): piece_pos = get_right_move(piece_pos) do_move_down = True else: ERR_MSG = &quot;Cannot move right!&quot; elif player_move == ROTATE_ANTICLOCKWISE: if can_rotate_anticlockwise(board, curr_piece, piece_pos): curr_piece = rotate_anticlockwise(curr_piece) do_move_down = True else: ERR_MSG = &quot;Cannot rotate anti-clockwise !&quot; elif player_move == ROTATE_CLOCKWISE: if can_rotate_clockwise(board, curr_piece, piece_pos): curr_piece = rotate_clockwise(curr_piece) do_move_down = True else: ERR_MSG = &quot;Cannot rotate clockwise!&quot; elif player_move == NO_MOVE: do_move_down = True elif player_move == QUIT_GAME: print(&quot;Bye. Thank you for playing!&quot;) sys.exit(0) else: ERR_MSG = &quot;That is not a valid move!&quot; if do_move_down and can_move_down(board, curr_piece, piece_pos): piece_pos = get_down_move(piece_pos) # This means the current piece in the game cannot be moved # We have to fix this piece in the board and generate a new piece if not can_move_down(board, curr_piece, piece_pos): merge_board_and_piece(board, curr_piece, piece_pos) curr_piece = get_random_piece() piece_pos = get_random_position(curr_piece) # Redraw board print_board(board, curr_piece, piece_pos, error_message=ERR_MSG) # Get player move from STDIN player_move = input() print(&quot;GAME OVER!&quot;) if __name__ == &quot;__main__&quot;: play_game() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p><strong>Type annotations</strong> (<a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a>) are a good idea to further increase the readability of your code. They also allow for type checking.</p>\n<hr />\n<p><strong><code>get_random_piece</code></strong></p>\n<pre><code>idx = random.randrange(len(PIECES))\nreturn PIECES[idx]\n</code></pre>\n<p>is better expressed as</p>\n<pre><code>return random.choice(PIECES)\n</code></pre>\n<hr />\n<p><strong><code>get_random_position</code></strong> should return a <code>tuple</code> (<code>(x, y)</code>), as the return value doesn't need to be mutable. This is true for most of the positions you're passing around.</p>\n<hr />\n<p><strong><code>is_game_over</code></strong> follows the pattern</p>\n<pre><code>if condition:\n return True\n\nreturn False\n</code></pre>\n<p>which can always be simplified to</p>\n<pre><code>return condition\n</code></pre>\n<p>So in your case:</p>\n<pre><code>return not can_move_down(board, curr_piece, piece_pos) and piece_pos[0] == 0\n</code></pre>\n<p>I would also suggest switching the two conditions</p>\n<pre><code>return piece_pos[0] == 0 and not can_move_down(board, curr_piece, piece_pos)\n</code></pre>\n<p>as it should be slightly more efficient (obviously not performance critical here, but generally good to know / understand). <code>can_move_down(...)</code> is now only called for pieces in the first row instead of all pieces.</p>\n<hr />\n<p><strong><code>rotate_clockwise</code></strong> / <strong><code>rotate_anticlockwise</code></strong></p>\n<p>Creating a <code>deepcopy</code> of every piece seems wasteful, as the piece's initial orientation isn't used again inside the function. After calling <code>rotate_anticlockwise</code> you have four copies of <code>piece</code> in memory, three of which aren't used again. You could instead rotate the pieces in-place.</p>\n<p>If you actually do need both states (<code>can_rotate_anticlockwise</code>, <code>can_rotate_clockwise</code>), the calling functions should handle that logic and create a <code>deepcopy(piece)</code> and pass that to <code>rotate_clockwise</code>.</p>\n<hr />\n<p><strong>Code duplication</strong></p>\n<p>You have this code snippet</p>\n<pre><code>curr_piece_size_x = len(curr_piece)\ncurr_piece_size_y = len(curr_piece[0])\nfor i in range(curr_piece_size_x):\n for j in range(curr_piece_size_y):\n board[piece_pos[0] + i][piece_pos[1] + j] = curr_piece[i][j] | board[piece_pos[0] + i][piece_pos[1] + j]\n</code></pre>\n<p>twice in your code. It should probably move into its own function.</p>\n<hr />\n<p><strong><code>overlap_check</code></strong></p>\n<p>I would expect this function to return <code>True</code> if an overlap is found. It is well-documented, but uninuitive.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T15:25:49.097", "Id": "262804", "ParentId": "262802", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:41:10.213", "Id": "262802", "Score": "3", "Tags": [ "python" ], "Title": "python - Tetris Game" }
262802
<p>I have a method where I fetch user input, check if certain values exist, and based on that build my own custom input object that I would use to search in a database. The code for the search method is as follows.</p> <pre><code>public SearchDocumentResult searchData(EmployeeInput employeeInput) { EmployeeInput getEmployeeInputForSearch = buildApplicationInputForSearch(employeeInput); if (employeeInput != null) { return super.searchForExactData(getEmployeeInputForSearch); } else { return super.searchForCloseMatchData(getTestPersonInput); } } </code></pre> <p>The methods with multiple if checks on the input are as follows. Both the below methods and the above method exist in the same class.</p> <pre><code>private Application buildApplicationInputForSearch(Application applicationInput) { Application.Builder applicationForSearch = Application.builder(); String jobIdFromInput = applicationInput.getJobId(); applicationForSearch.withIsTagged(applicationInput.isTagged()); if (!StringUtils.isEmpty(jobIdFromInput)) { applicationForSearch.withJobId(jobIdFromInput); } FormSection formSectionInput = applicationInput.getFormSection(); if (formSectionInput != null) { this.buildFormSectionInputForSearch(formSectionInput); } return applicationForSearch.build(); } private FormSection buildFormSectionInputForSearch(FormSection formSectionInput) { FormSection.Builder formSectionForSearch = FormSection.builder(); String formCountry = formSectionInput.getCountry(); Map&lt;String, String&gt; employeeQuestions = formSectionInput.getEmployeeQuestions(); Map&lt;String, String&gt; applicationQuestions = formSectionInput.getApplicationQuestions(); List&lt;String&gt; formNames = formSectionInput.getNames(); if (!StringUtils.isEmpty(formCountry)) { formSectionForSearch.withCountry(formCountry); } if (formNames.size() &gt; 0) { formSectionForSearch.withNames(formNames); } if (employeeQuestions.size() &gt; 0) { formSectionForSearch.withEmployeeQuestions(employeeQuestions); } if (applicationQuestions.size() &gt; 0) { formSectionForSearch.withApplicationQuestions(applicationQuestions); } return formSectionForSearch.build(); } </code></pre> <p>The <code>EmployeeInput</code> is a model class that gets generated through a library and therefore I cannot make that use Java Optional for fields that may or may not exist. Using this <code>EmployeeInput</code> object as it is, how can I make this code more readable, with less if conditions? Any help would be much appreciated.</p>
[]
[ { "body": "<pre><code>if (formSectionInput != null) {\n this.buildFormSectionInputForSearch(formSectionInput);\n }\n</code></pre>\n<p>can be replaced with:</p>\n<pre><code>Optional.ofNullable(formSectioninput).map(this::buildFormSectionInputForSearch);\n</code></pre>\n<p>I dont understand the need of <code>if</code> condition in the statements like below:</p>\n<pre><code>if (formNames.size() &gt; 0) {\n formSectionForSearch.withNames(formNames);\n }\n</code></pre>\n<p>If you are expecting that formNames can be null then you should not use <code>.size()</code>, it can throw <code>NullPointer</code> exception. You should do similar to above example:</p>\n<pre><code>Optional.ofNullable(formNames).map(formSectionForSearch::withNames);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T03:17:03.477", "Id": "262872", "ParentId": "262807", "Score": "1" } }, { "body": "<p>Move the condition - <em>if it is not contextual</em> - into the guarded method:</p>\n<pre><code>if (!StringUtils.isEmpty(formCountry)) {\n formSectionForSearch.withCountry(formCountry);\n}\nif (formNames.size() &gt; 0) {\n ...\n}\n</code></pre>\n<p>So:</p>\n<pre><code>formSectionForSearch.withCountry(formCountry);\nformSectionForSearch.withNames(formNames);\n\nvoid withCountry(String formCountry) {\n if (!StringUtils.isEmpty(formCountry)) {\n ...\n }\n}\n\nvoid withNames(List&lt;String&gt; formNames) {\n if (!formNames.isEmpty()) {\n formSectionForSearch.withNames(formNames);\n }\n}\n</code></pre>\n<p>On reuse in N call sites (here unlikely) it will even reduce code. And it creates more secure code for calling the method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T10:02:45.970", "Id": "262879", "ParentId": "262807", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T16:26:22.690", "Id": "262807", "Score": "0", "Tags": [ "java", "object-oriented", "complexity", "cyclomatic-complexity" ], "Title": "Optimizing methods with multiple if checks on getter values" }
262807
<p>I have a daemon which I am able to interact with through a cli-client. The daemon will perform some tasks in future e.g. monitoring the rate at which files are added to a directory.</p> <p>Right now when I add a new function I need to write</p> <ol> <li>The function I would like to trigger</li> <li>A message format which the client can send to the daemon to execute the function</li> <li>A function in the client which takes the users command line argument and turns them in to a string which is sent to the daemon</li> </ol> <p>Is there a better way of designing this interaction?</p> <p><strong>Below is the daemon</strong></p> <pre><code>##################### Daemon ################################## ##################### Just for context ######################## from multiprocessing.connection import Listener class Nark: def __init__(self, folder_path): self.path = folder_path def change_path(self, folder_path): self.path = folder_path def get_path(self): return self.path class NarkPool: def __init__(self): self.narkdict = {} def add_nark(self, name, path): self.narkdict[name] = Nark(path) def remove_nark(self, name): self.narkdict.pop(name) def change_path(self, name, path): self.narkdict[name].change_path(path) def get_path(self, name): return self.narkdict[name].get_path() def get_names(self): return list(self.narkdict.keys()) ################### Important Part Below ############################# address = ('localhost', 7389) listener = Listener(address) narks = NarkPool() while True: conn = listener.accept() print ('connection accepted from', listener.last_accepted) while True: msg = conn.recv() command = msg.split(' ') # command input would be eg. add &lt;name&gt; &lt;path&gt; # Manually define action to be taken based on each command if command[0] == 'add' : narks.add_nark(command[1], command[2]) if command[0] == 'remove' : narks.remove(command[1]) if command[0] == 'change_path': narks.change_path(command[1], command[2]) if command[0] == 'get_path' : conn.send(narks.get_path(command[1])) if command[0] == 'list': conn.send(narks.get_names()) if msg : conn.close() break listener.close() </code></pre> <p><strong>And here is the client:</strong></p> <pre><code>################# Client ########################## import click from multiprocessing.connection import Client adress = ('localhost', 7389) @click.group() def cli(): pass # for each possible daemon command create a function which # takes respective user input and sends it to daemon @cli.command() @click.argument('name') @click.argument('path') def add_nark(name, path): conn = Client(adress) conn.send(f'add {name} {path}') conn.close() @cli.command() @click.argument('name') def remove_nark(name): conn = Client(adress) conn.send(f'remove {name}') conn.close() @cli.command() @click.argument('name') @click.argument('path') def change_path(name, path): conn = Client(adress) conn.send(f'change_path {name} {path}') conn.close() @cli.command() @click.argument('name') def get_path(name): conn = Client(adress) conn.send(f'get_path {name}') msg = False while not msg: msg = conn.recv() print(msg) conn.close() @cli.command() def list_runs(): conn = Client(adress) conn.send(f'list') msg = False while not msg: msg = conn.recv() print(msg) conn.close() if __name__ == '__main__': cli() </code></pre>
[]
[ { "body": "<p>Maybe its not the best approach, but it gets the work done:</p>\n<h1>Intended approach</h1>\n<p>Instead of having to declare/modify/delete functions every time a command is added/changed/deleted, the idea is to have a list with all command, and then create the corresponding cli commands dynamically.</p>\n<p>This way, we could say the commands in your post could be represented as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\n\nCommand = namedtuple(\n 'Command',\n (\n 'cli_command',\n 'serv_command',\n 'args',\n 'request_responde_and_show_it'\n )\n)\n\nCOMMANDS = (\n Command(\n cli_command='add_nark',\n serv_command='add',\n args=('name', 'path'),\n request_responde_and_show_it=False\n ),\n Command(\n cli_command='remove_nark',\n serv_command='remove',\n args=('name',),\n request_responde_and_show_it=False\n ),\n Command(\n cli_command='change_path',\n serv_command='change_path',\n args=('name', 'path'),\n request_responde_and_show_it=False\n ),\n Command(\n cli_command='get_path',\n serv_command='get_path',\n args=('name',),\n request_responde_and_show_it=True\n ),\n Command(\n cli_command='list_runs',\n serv_command='list',\n args=(),\n request_responde_and_show_it=True\n ),\n)\n</code></pre>\n<p>Now, lets review step by step how we could dynamically declare the cli commands.</p>\n<h1>Common structure</h1>\n<p>All of these functions have pretty much the same body, which could be made generic as such:</p>\n<pre class=\"lang-py prettyprint-override\"><code>command = 'add'\nargs = ('name', 'path')\nrequest_responde_and_show_it = False\nwith Client(ADDRESS) as conn:\n conn.send(command + ' ' + ' '.join(args))\n if request_responde_and_show_it:\n print(conn.recv())\n</code></pre>\n<h1>Dynamically declare functions</h1>\n<p>Now, knowing this, we can dynamically declare functions for each of our commands.</p>\n<p>To dynamically declare functions with a varying number of arguments, I found <a href=\"https://snipplr.com/view/17819\" rel=\"nofollow noreferrer\">this</a> approach, but I could not manage to make it work (I know <code>function.func_code</code> has now changed to <code>function.__code__</code> and <code>function.func_globals</code> to <code>function.__globals__</code>, but still).</p>\n<p>So, the approach I found to work is using <code>exec()</code> along with multiline-strings:</p>\n<pre class=\"lang-py prettyprint-override\"><code>function_name = 'add_nark'\nargs = ('name', 'path')\n# Create a string contaning the arguments separated by commas\nargs_code_str = f'{args}'.replace(&quot;'&quot;, '').replace('(', '').replace(')', '')\n# Declare function on local scope\nexec(f'''\ndef {function_name}({args_code_str}):\n # do stuff here\n''')\n</code></pre>\n<h1>Annotating functions dynamically</h1>\n<p>Annotating a function like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@my_decorator('some_argument')\ndef my_function():\n pass\n</code></pre>\n<p>is equivalent to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def my_function():\n pass\nmy_function = my_decorator('some_argument')(my_function)\n</code></pre>\n<h1>Altogether</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from multiprocessing.connection import Client\nfrom collections import namedtuple\n\nimport click\n\nCommand = namedtuple(\n 'Command',\n (\n 'cli_command',\n 'serv_command',\n 'args',\n 'request_responde_and_show_it'\n )\n)\n\nCOMMANDS = (\n Command(\n cli_command='add_nark',\n serv_command='add',\n args=('name', 'path'),\n request_responde_and_show_it=False\n ),\n Command(\n cli_command='remove_nark',\n serv_command='remove',\n args=('name',),\n request_responde_and_show_it=False\n ),\n Command(\n cli_command='change_path',\n serv_command='change_path',\n args=('name', 'path'),\n request_responde_and_show_it=False\n ),\n Command(\n cli_command='get_path',\n serv_command='get_path',\n args=('name',),\n request_responde_and_show_it=True\n ),\n Command(\n cli_command='list_runs',\n serv_command='list',\n args=(),\n request_responde_and_show_it=True\n ),\n)\n\n\n@click.group()\ndef cli():\n pass\n\n\ndef send_command_to_server(command, args, request_responde_and_show_it):\n print(f'called send_command_to_server with: {command}, {args}, {request_responde_and_show_it}')\n with Client(ADDRESS) as conn:\n conn.send(command + ' ' + ' '.join(args))\n if request_responde_and_show_it:\n print(conn.recv())\n\n\ndef transform_args_to_code_str(args):\n return f'{args}'.replace(&quot;'&quot;, '').replace('(', '').replace(')', '')\n\n\ndef create_function(command):\n args_code_str = transform_args_to_code_str(command.args)\n # Declare function on local scope\n exec(f'''\ndef {command.cli_command}({args_code_str}):\n send_command_to_server('{command.serv_command}', ({args_code_str}),\n {command.request_responde_and_show_it})\n''')\n created_function = vars()[command.cli_command]\n return created_function\n\n\ndef create_cli_command(command):\n created_function = create_function(command)\n # Equivalent to annotating the created function with @cli.command()\n cli_command = cli.command()(created_function)\n for arg in command.args:\n # Equivalent to annotating cli_command with @click.argument('someargument')\n cli_command = click.argument(arg)(cli_command)\n\n\ndef create_cli_commands(commands):\n for command in commands:\n create_cli_command(command)\n\n\nif __name__ == '__main__':\n create_cli_commands(COMMANDS)\n cli()\n</code></pre>\n<p>Now, if you wished to, you could even extract the <code>COMMANDS</code> to a json file, so you don't even have to worry about this script when modifying the server</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T17:16:19.187", "Id": "518880", "Score": "0", "body": "Thank you so much for this great contribution, the answers I have gotten so far are a lot for me to understand so might take a bit for me to follow up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T19:39:30.000", "Id": "518889", "Score": "0", "body": "This is already a really big improvement! After thinking about it I had some ideas and would love to hear your feedback: (1) Instead of sending a string I could send a dict with the arguments (2) Maybe I could build the named tuple in the daemon and send it to the client after it first connects (3) If I can send the tuples over, maybe I can instead try to build the whole cli() function in the daemon and send it over to the client" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T19:50:12.587", "Id": "518891", "Score": "0", "body": "regarding (2) and (3) I found this library https://google.github.io/python-fire/ which can turn python objects in to a cli so maybe I can use a similar approach to derive the cli from my functions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T20:31:37.007", "Id": "518894", "Score": "1", "body": "@sev Question 1 - Yes, that is probably a good idea. Send the whole command as json. That will make it easier to parse in the server, and also easier to read/debug the code. Question 2 - That sounds interesting. That way, you would only declare the messages structure once, and the client wouldn't even need to know what the server commands are. However, I would then stop using `cli-command` names (`add-nark`) different from the `server-command` names (`add`). As that would mean the server needs to know part of the client's logic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T20:33:21.770", "Id": "518895", "Score": "1", "body": "@sev Question 3 - I would definetly not build the cli in the server. Then, what is even the point of having a client and a server? The client logic (presentation, in this case), needs to be separated from the server logic (actual processing)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T20:42:08.677", "Id": "518899", "Score": "0", "body": "@sev Regarding the use of the `fire` module, that would take away the hustle of adding decorators for each of the command argument. However, I don't know if it would reduce the client's complexity. Although we would no longer need to add those decorators, we would have to declare all methods inside a class, to pass it onto `fire.Fire`. And that would make the dinamic function declaration's more complex, which already is the hardest part to debug in the code, so you probably don't want to do that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T08:12:03.093", "Id": "518916", "Score": "0", "body": "Regarding (3) What I (kind of) meant to say was I could write a function which takes another function as an argument and returns the corresponding command tuple. And maybe I could look at the fire library to see how they accomplish this task" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T16:58:28.790", "Id": "518937", "Score": "1", "body": "@sev Actually, now that I think about it, what you are doing is RPC (Remote Procedure Call) through a cli. So, maybe you could actually use `xmlrpc` (see [here](https://docs.python.org/3/library/xmlrpc.client.html#xmlrpc.client.ServerProxy.system.methodHelp)), and register the server proxy through `fire`. That would probably make your client about 10 lines of code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T22:28:44.457", "Id": "518962", "Score": "0", "body": "I tried doing this but am running in to some problems https://stackoverflow.com/questions/67929141/using-rpc-to-create-cli-client-for-controlling-daemon" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T21:45:55.093", "Id": "262820", "ParentId": "262809", "Score": "1" } }, { "body": "<h1>In your daemon file:</h1>\n<ul>\n<li>You are writing getters and setters which are not <em>pythonic</em> because there is no <code>private</code> keyword in python and all attributes are public. Python prefers using <a href=\"https://docs.python.org/3/library/functions.html#property\" rel=\"nofollow noreferrer\">@property</a> decorator for meaningful getters and setters, which is one of many kind of <a href=\"https://docs.python.org/3/howto/descriptor.html#properties\" rel=\"nofollow noreferrer\">descriptors</a>, which might do validation, logging or other tasks before getting or setting the value.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>\ndef valid_path(path):\n &quot;&quot;&quot;Checks if path is valid&quot;&quot;&quot;\n pass\n\nclass Nark:\n def __init__(self, folder_path):\n # I did not prefix the attribute with an underscore;\n # so the user of the class when accessing gets redirected to the property,\n # and cannot access that attribute without\n # messing with the internal workings of the class like __dict__\n self.path = folder_path\n \n @property\n def path(self):\n return self.path\n \n @path.setter\n def path(self, foldr_path):\n if not valid_path(folder_path):\n raise ValueError(&quot;Not a valid path&quot;)\n\n self.path = folder_path\n\n</code></pre>\n<p>You can even wrap the validation in a <a href=\"https://realpython.com/primer-on-python-decorators/\" rel=\"nofollow noreferrer\">decorator</a>, to abstract it.</p>\n<pre class=\"lang-py prettyprint-override\"><code>\nfrom functools import wraps\n\ndef valid_path(path):\n &quot;&quot;&quot;Checks if path is valid&quot;&quot;&quot;\n pass\n\ndef path_must_be_valid(func):\n @wraps(func) \n def inner(self, path):\n if not valid_path(path):\n raise ValueError(&quot;Path must satisfy certain properties&quot;)\n \n return func(self, path)\n return inner\n\n\nclass Nark:\n def __init__(self, folder_path):\n # I did not prefix the attribute with an underscore;\n # so the user of the class when accessing gets redirected to the property,\n # and cannot access that attribute without\n # messing with the internal workings of the class like __dict__\n self.path = folder_path\n \n @property\n def path(self):\n return self.path\n \n @path.setter\n @path_must_be_valid\n def path(self, foldr_path):\n self.path = folder_path\n</code></pre>\n<ul>\n<li><p>I think creating a <code>NarkPool</code> class is not useful; because the <code>Nark</code> class itself does validation, you can just store the <code>Nark</code>s in a <code>dict</code>.</p>\n</li>\n<li><p>You are not handling the exceptions that might happen if a key is not in the <code>narkdict</code>, for example: if you try to access a path that doesn't exists it will throw and exception and the daemon will terminate.</p>\n</li>\n</ul>\n<p>You can use the <code>get</code> method on <code>dict</code>s, which accepts a default argument to be returned if the key is not found in the <code>dict</code>.</p>\n<p>Or you can use a <code>try</code> <code>except</code> block to handle the <code>exception</code>.</p>\n<ul>\n<li>When using <code>if</code>s in python all <code>if</code>s are executed so\nyou are checking the command type 5 times, you can use <code>elif</code> which will stop checking other branches if one of them is executed.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>narks = {}\n\nwhile True:\n conn = listener.accept()\n print ('connection accepted from', listener.last_accepted)\n while True:\n msg = conn.recv()\n # Python has a neat feature called unpacking values from sequences\n try:\n command, path, *additional_params = msg.split(' ') # command input would be eg. add &lt;name&gt; &lt;path&gt;\n except ValueError:\n print(&quot;Invalid command&quot;)\n try:\n # Manually define action to be taken based on each command\n if command == 'add':\n narks[path] = Nark(additional_parameters[1])\n elif command == 'remove':\n narks.pop(path)\n elif command == 'change_path':\n narks[path].path = additional_parameters[1]\n elif command == 'get_path':\n conn.send(narks[path])\n elif command == 'list':\n conn.send(narks.keys())\n else:\n print(f&quot;I do not recognize the command {command}&quot;)\n \n except KeyError:\n print(f&quot;Path {path} is not valid&quot;)\n\n if msg:\n conn.close()\n break\n\nlistener.close()\n\n</code></pre>\n<ul>\n<li>I would suggest using a tools like <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">pylint</a>, <a href=\"https://github.com/PyCQA/pyflakes\" rel=\"nofollow noreferrer\">pyflakes</a> or <a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\">black</a>; to autoformat and lint your code.</li>\n</ul>\n<h1>In your client file</h1>\n<p>Your client code is small, so it does not need a lot of changes.</p>\n<p>The only thing that I suggest you do, is noticing the similarities between functions and abstract it either using a <a href=\"https://realpython.com/primer-on-python-decorators/\" rel=\"nofollow noreferrer\">decorator</a> or a <a href=\"https://en.wikipedia.org/wiki/Higher-order_function\" rel=\"nofollow noreferrer\">higher order function</a>.</p>\n<p>I hope my answer has helped you in any useful way.</p>\n<p><strong>Cheers</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T10:57:03.897", "Id": "518837", "Score": "0", "body": "I think that here, the `@property` offers nothing of value over a plain member variable - for the reasons you've already described. It's just a fancier getter/setter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T17:15:51.923", "Id": "518879", "Score": "0", "body": "Thank you so much for this great contribution, the answers I have gotten so far are a lot for me to understand to might take a bit for me to follow up. I have now started using pylint and black and also put a github action which uses them to check for code quality now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T19:12:37.330", "Id": "518886", "Score": "0", "body": "first question: why would I use `nark_pool` to check the validity of the inputs rather than just checking in `nark` itself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T19:20:06.327", "Id": "518887", "Score": "1", "body": "@sev After thinking for a while, I think your approach is better, because the `Nark` class itself should be responsible for validating the paths.\n\nI will edit the answer to reflect the changes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T21:58:22.983", "Id": "262821", "ParentId": "262809", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T16:50:49.490", "Id": "262809", "Score": "3", "Tags": [ "python", "design-patterns", "console", "ipc" ], "Title": "CLI-Client for interacting with daemon" }
262809