body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The situation is, I have two fields in a database (or that can be derived) - when the message was received (<code>Received</code>, of type <code>DateTime</code>), and the day of the month (but not the month itself) that the message was supposed to be received (<code>DayOfRun</code> of type <code>Integer</code>, which is the last two digits of an ID column that <em>doesn't</em> otherwise contain date-time information). I need to know the difference (in whole days, ignoring the time) between the two. If the message arrived <em>before</em> the day of run, the number will be negative.</p> <p>I can guarantee that the entries will not differ by more than half a month in either direction.</p> <p>The pseudo-code logic I have come up with is as follows:</p> <pre><code>DayOfRun = Extract last two characters from ID Field DayReceived = Extract DayOfMonth from Received; DaysInPreviousMonth = Extract Count of Days in (Month before Received) Pick the closest to 0 from the following: A: If DayReceived &lt; DayOfRun then : DaysInPreviousMonth + DayReceived - DayOfRun ; : Otherwise : DaysInPreviousMonth + DayOfRun - DayReceived ; B: DayReceived - DayOfRun; </code></pre> <p>Examples:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Day of Run</th> <th>Received</th> <th>Answer</th> <th>Reasoning</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>2021-04-29</td> <td>-2</td> <td>29th April is 2 days before 1st May (can't be 1st April - would be too far away)</td> </tr> <tr> <td>28</td> <td>2021-05-02</td> <td>4</td> <td>02nd May is 4 days after 28th April (which gives a smaller absolute number than assuming 28th May, which would be too far away anyway)</td> </tr> <tr> <td>14</td> <td>2021-04-28</td> <td>14</td> <td>28th April is 14 days after 14th April (which gives a smaller absolute number than if we assumed 14th May)</td> </tr> </tbody> </table> </div> <p>My KQL to implement this logic is as follows:</p> <pre><code>tableName | project DayOfRun = toint(substring(['ID Field'], -2, 2)), ['Day Of Month Received'] = datetime_part(&quot;day&quot;,ErrorTimestamp), ErrorTimestamp | where DayOfRun &lt;&gt; ['Day Of Month Received'] | project ['Days In Previous Month'] = datetime_part(&quot;day&quot;,endofmonth( datetime_add(&quot;month&quot;,-1, ErrorTimestamp))), DayOfRun, ['Day Of Month Received'] | project ['Day Of Month Received'], Diff = (['Day Of Month Received'] - DayOfRun), CrossMonthDiff = iif(['Day Of Month Received'] &lt; DayOfRun,(['Days In Previous Month']+['Day Of Month Received']-DayOfRun),(['Days In Previous Month']+DayOfRun-['Day Of Month Received'])) | summarize ['Day Of Month Received'], ['Difference (Days)'] = iif(min_of(abs(Diff),abs(CrossMonthDiff)) == abs(Diff),Diff,CrossMonthDiff) | order by ['Difference (Days)'] desc, ['Day Of Month Received'] asc </code></pre> <p>This query seems overly complex, and is quite slow to run. Any thoughts on how to improve either the logic or the query itself?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T14:29:02.337", "Id": "513904", "Score": "0", "body": "Feel free to suggest better tags" } ]
[ { "body": "<p>A few suggestions:</p>\n<ol>\n<li><p>You're performing string manipulations, and then extracting numbers out of the string result, which is slow. The best thing to do is to ingest the data in a better format in the first place (so that the number you're extracting will be ingested in a separate numeric column). If it's not possible to do it in ingestion, then you should do it in an <a href=\"https://docs.microsoft.com/azure/data-explorer/kusto/management/update-policy\" rel=\"nofollow noreferrer\">Update Policy</a>.</p>\n</li>\n<li><p>You didn't add any filters on datetime columns, meaning you're querying the whole table. For this to work efficiently, you need all the data to be in the hot cache. Is this your case? To see the effective retention and caching policies for the table, run <code>.show table tableName details | project RetentionPolicy, CachingPolicy</code>.</p>\n</li>\n<li><p>You might want to try using <code>summarize hint.strategy=shuffle</code> (see <a href=\"https://docs.microsoft.com/azure/data-explorer/kusto/query/shufflequery\" rel=\"nofollow noreferrer\">this</a> for more info).</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T04:43:56.437", "Id": "260482", "ParentId": "260339", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T14:28:45.617", "Id": "260339", "Score": "2", "Tags": [ "database", "data-visualization", "azure" ], "Title": "Simplify a complex KQL Query" }
260339
<p>Is there a way to unify or refactor two methods that do basically the same but the difference being of handling a type of object or a collection of the same type of object?</p> <p>The following is an implementation of two methods that have very similar behavior. They handle a cache for an API, so when someone asks for a value or a set of values, it verifies that the entry is in cache already. If not, they call the method that will return from an external API: a value or a set of values. Finally the methods, update the cache and return the value/values.</p> <pre><code>public async Task&lt;T&gt; GetValue&lt;T&gt;(string cacheKey, Func&lt;Task&lt;T&gt;&gt; getItem, MemoryCacheEntryOptions memoryCacheEntryOptions = null) { if (_memoryCache.TryGetValue(cacheKey, out T cacheEntry)) { return cacheEntry; } else { cacheEntry = await getItem(); return SetValue(cacheKey, cacheEntry, memoryCacheEntryOptions); } } public async Task&lt;IList&lt;T&gt;&gt; GetValues&lt;T&gt;(string cacheKey, Func&lt;Task&lt;IList&lt;T&gt;&gt;&gt; getItems, MemoryCacheEntryOptions memoryCacheEntryOptions = null) { if (_memoryCache.TryGetValue(cacheKey, out IList&lt;T&gt; cacheEntries)) { return cacheEntries; } else { cacheEntries = await getItems(); return SetValues(cacheKey, cacheEntries, memoryCacheEntryOptions); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T19:53:27.363", "Id": "513936", "Score": "1", "body": "Guys the code is compiling. If it does not compile (it does) you can abstract the idea of the methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T20:21:03.820", "Id": "513944", "Score": "1", "body": "Syntax option: `public async Task<T> GetValue<T>(string cacheKey, Func<Task<T>> getItem, MemoryCacheEntryOptions memoryCacheEntryOptions = null) => _memoryCache.TryGetValue(cacheKey, out T cacheEntry) ? cacheEntry : SetValue(cacheKey, await getItem(), memoryCacheEntryOptions);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T20:38:40.120", "Id": "513947", "Score": "1", "body": "Btw, `GetValue<T>` would be enough, as it can do the job for `GetValues<T>`, look: `public Task<IList<T>> GetValues<T>(string cacheKey, Func<Task<IList<T>>> getItems, MemoryCacheEntryOptions memoryCacheEntryOptions = null) => GetValue(cacheKey, getItems, memoryCacheEntryOptions);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T00:35:34.850", "Id": "513958", "Score": "0", "body": "@aepot Wooow! How is it possible that getValue can return a List<T> and T at the same time?!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T06:29:33.133", "Id": "513974", "Score": "1", "body": "Because `T` isn't a type name but like a placeholder for any real type. With generic type you tell compiler \"I don't know the real type but it will be the same type here, here and here\". T and T is the same type, the same for `List<T>`. But you can drop details about `IList` because you don't use the interface methods which `IList` provides. Then `IList` can be just a `T`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T10:13:58.693", "Id": "513985", "Score": "1", "body": "Awesome, so I can use T to represent a T, IList<T>, IList<IList<T>>, etc as long as I don't use methods from IList. And if I do, I can do what @Kevin answered. Thanks, I learned something really useful!!!!!!!!!!!!!!!!!!!!!" } ]
[ { "body": "<p>I'm not sure I fully understand the question, but the first thing that leapt to mind is:</p>\n<pre><code>&lt;T&gt; can encompass a IList&lt;SomeType&gt; already.\n</code></pre>\n<p>I mean, the first 75% of GetValue() <em>already works</em> with using IList as the generic type:</p>\n<pre><code>public async Task&lt;T&gt; GetValue&lt;T&gt;(\n string cacheKey,\n Func&lt;Task&lt;T&gt;&gt; getItem,\n MemoryCacheEntryOptions memoryCacheEntryOptions = null)\n{\n if (_memoryCache.TryGetValue(cacheKey, out T cacheEntry))\n {\n return cacheEntry;\n }\n else\n {\n cacheEntry = await getItem(); \n\n return SetValue(cacheKey, cacheEntry, memoryCacheEntryOptions);\n }\n}\n</code></pre>\n<p>... <code>memoryCache.TryGetValue()</code> works exactly the same, and will operate correctly. <code>cacheEntry</code> will be the correct type (an <code>IList</code> of something.) <code>getItem()</code> works perfectly, too, since it's a <code>Func</code> that returns the appropriate <code>IList</code>.</p>\n<p>Literally the only thing that's different is <code>SetValue</code> vs <code>SetValues</code>. Which, from your original post, looks to be the call into the 3rd party API.</p>\n<p>Well, it begs the question of whether <code>SetValue()</code> in the vendor API will work for an <code>IList</code>?\nIf it does, your probably is immediately solved: just use <code>GetValue</code> for everything and call it a day.</p>\n<p>Assuming that it doesn't, maybe the question would be whether something like this would work:</p>\n<pre><code>public async Task&lt;T&gt; GetValue&lt;T&gt;(string cacheKey, Func&lt;Task&lt;T&gt;&gt; getItem, MemoryCacheEntryOptions memoryCacheEntryOptions = null)\n{\n return GetValue(cacheKey, getItem, x =&gt; SetValue(cacheKey, x, memoryCacheEntryOptions));\n}\npublic async Task&lt;T&gt; GetValues&lt;T&gt;(string cacheKey, Func&lt;Task&lt;T&gt;&gt; getItem, MemoryCacheEntryOptions memoryCacheEntryOptions = null)\n{\n return GetValue(cacheKey, getItem, x =&gt; SetValues(cacheKey, x, memoryCacheEntryOptions));\n}\n\nprivate async Task&lt;T&gt; GetValue&lt;T&gt;(string cacheKey, Func&lt;Task&lt;T&gt;&gt; getItem, Func&lt;T, Task&lt;T&gt;&gt; setItem)\n{\n if (_memoryCache.TryGetValue(cacheKey, out T cacheEntry))\n {\n return cacheEntry;\n }\n else\n {\n cacheEntry = await getItem(); \n\n return setItem(cacheEntry);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T01:33:59.200", "Id": "260353", "ParentId": "260342", "Score": "2" } } ]
{ "AcceptedAnswerId": "260353", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T15:46:02.040", "Id": "260342", "Score": "0", "Tags": [ "c#" ], "Title": "Is it possible to refactor these two similar methods that handle T and List<T>?" }
260342
<p>I am not very familiar with Swing but am attempting to make a Reddit GUI. I've finally got everything to work as expected but I must admit, it's quite mundane and not very nice to look at. I want to add some visually appealing things to it but as I said I am very new to Swing. I got help making the components and such for my idea, so I'm feeling a little over-whelmed.</p> <p>What the program currently does is fetches headlines from the top of subreddits that the user inputs. As you can see from the screenshot, it isn't nice to look at as I was saying. Any advice design wise would be appreciated!</p> <p><img src="https://i.ibb.co/hFbVMJg/reddit.png" alt="Screenshot of program" /></p> <p>P.S. This is definitely advanced for me, so just want to side note I didn't somehow create this from scratch without help. Also have since fixed the crooked Reddit icon.</p> <pre><code>package com.Will.me; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Reddit extends JFrame { static JPanel mainPanel = new JPanel(); static JTextField textField = new JTextField(20); static JButton search = new JButton(&quot;Search&quot;); static JButton[] numbers = new JButton[28]; static JButton[] headlines = new JButton[28]; static JLabel[] votes = new JLabel[28]; static JLabel title = new JLabel(&quot;\tHeadlines from r/&quot;); public Reddit(){ mainPanel.setLayout(null); setUpComponents(); title.setVisible(false); search.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { title.setVisible(true); String str = textField.getText(); title.setText(&quot;&quot;); title.setText(&quot;\tHeadline from r/&quot;+str); getSubReddit(str); } }); add(mainPanel); setTitle(&quot;Reddit&quot;); setSize(900,600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void setUpComponents(){ JLabel redditIcon = new JLabel(); redditIcon.setBounds(10, 10, 100, 100); resizeRedditLogo(redditIcon); mainPanel.add(redditIcon); textField.setBounds(160, 20, 250, 30); search.setBounds(415, 23, 85, 25); textField.setBackground(Color.decode(&quot;#8B0000&quot;)); search.setOpaque(true); search.setBorderPainted(false); search.setBackground(Color.decode(&quot;#8B0000&quot;)); search.setForeground(Color.WHITE); search.setBorder(BorderFactory.createRaisedBevelBorder()); int y = 120; for (int i = 0; i &lt; numbers.length;i++){ numbers[i] = new JButton(String.valueOf(i+1)); numbers[i].setBounds(20, y, 40,30); numbers[i].setBackground(Color.decode(&quot;#8B0000&quot;)); numbers[i].setOpaque(true); numbers[i].setForeground(Color.WHITE); numbers[i].setBorder(BorderFactory.createLoweredSoftBevelBorder()); y+= 40; numbers[i].setBorderPainted(false); mainPanel.add(numbers[i]); } int y2 = 120; for (int i = 0; i &lt; headlines.length;i++){ headlines[i] = new JButton(&quot;&quot;); headlines[i].setBounds(70, y2, 650,30); headlines[i].setBackground(Color.decode(&quot;#8B0000&quot;)); headlines[i].setOpaque(true); headlines[i].setForeground(Color.WHITE); headlines[i].setBorder(BorderFactory.createLoweredSoftBevelBorder()); y2+= 40; headlines[i].setBorderPainted(false); mainPanel.add(headlines[i]); } int y3 = 120; JLabel voteTitle = new JLabel(&quot;# Votes&quot;); voteTitle.setFont(new Font(&quot;Arial&quot;, Font.BOLD, 30)); voteTitle.setForeground(Color.WHITE); voteTitle.setBounds(755, 70, 120, 30); mainPanel.add(voteTitle); for (int i = 0; i &lt; votes.length;i++){ votes[i] = new JLabel(&quot;&quot;); votes[i].setBounds(750, y3, 120,30); votes[i].setForeground(Color.WHITE); votes[i].setBorder(BorderFactory.createRaisedBevelBorder()); y3+= 40; votes[i].setBorder(BorderFactory.createRaisedBevelBorder()); mainPanel.add(votes[i]); } textField.setForeground(Color.WHITE); title.setBorder(BorderFactory.createRaisedBevelBorder()); title.setBounds(105, 70, 605, 30); title.setFont(new Font(&quot;Arial&quot;, Font.BOLD, 18)); title.setForeground(Color.WHITE); mainPanel.add(title); mainPanel.setBackground(Color.RED); mainPanel.add(textField); mainPanel.add(search); } public static void getSubReddit(String sub){ try { Document doc = Jsoup.connect(&quot;https://old.reddit.com/r/&quot;+sub).get(); Elements el = doc.select(&quot;p.title&quot;); Elements score = doc.select(&quot;div.score.unvoted&quot;); int i,j; for (i=0,j=0;i&lt;el.size() &amp;&amp; j&lt;score.size();i++,j++){ headlines[i].setText(el.get(i).text()); votes[j].setText(score.get(j).text()); } } catch (Exception e) { System.out.println(e.toString()); } } public static void resizeRedditLogo(JLabel label){ try { ImageIcon imageIcon = new ImageIcon(new ImageIcon(&quot;../RedditGUI/src/reddit1.png&quot;).getImage().getScaledInstance(120, 120, Image.SCALE_DEFAULT)); label.setIcon(imageIcon); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new Reddit(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T17:39:00.013", "Id": "513917", "Score": "0", "body": "Welcome to Code Review! While you provided a screenshot, it would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T21:29:23.120", "Id": "513948", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ thank you for the welcome and letting me know, do I just edit this post or I have to repost and edited version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T21:30:14.253", "Id": "513949", "Score": "0", "body": "No problem. Please just [edit] the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T21:46:45.223", "Id": "513952", "Score": "0", "body": "There are way too many static fields and methods. The only static method in your whole Swing GUI should be the main method. Oracle has a nifty tutorial, [Creating a GUI With JFC/Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html). Skip the Netbeans section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T22:27:11.047", "Id": "513955", "Score": "0", "body": "@GilbertLeBlanc thank you. Would you have any advise for the external appearance UI?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T04:52:40.673", "Id": "513971", "Score": "0", "body": "Don't use null layouts and absolute positioning. Swing has [layout managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) that allow you to create different layouts. I wouldn't worry about icons and colors in the beginning. Get the application to work properly first, then add colors and icons. Finally, when I create a Swing GUI, I use the [model / view / controller](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) (MVC) pattern." } ]
[ { "body": "<p>About the code itself, you should try to separate the view from the &quot;logic&quot; by applying one of the various patterns (MVC and MVP being the most used), as said by Gilbert La Blanc in his comment,</p>\n<p>About the visual part, it is easier to create components that provide high level functionality(ies) and that you use to compose your main view.</p>\n<p>For the &quot;layouting&quot;, why not using a <em>JList</em> with a custom renderer to display each line. If you need clickable buttons (that are not implemented as far as I can see in your code) then you can use a <em>Box</em> or a <em>BoxLayout</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T11:45:27.023", "Id": "260369", "ParentId": "260345", "Score": "1" } }, { "body": "<p><em>Intro.</em> Sorry, I jumped in this question without taking time to read it in details. Since you are new there must be more to say in order to create an helpful answer. And I prefer to create a new one instead of editing the first one.</p>\n<hr />\n<h1>The easy way,</h1>\n<p>If you do not want to change so much:</p>\n<ol>\n<li><p>You can try to remove the static fields. Ideally, nothing should be static instead of the <code>main</code> entry point.</p>\n</li>\n<li><p>You should also try to extract the parsing to a dedicated class. This will lead to a better separation of concerns and encapsulation and will let you test it or interchange it later.</p>\n</li>\n<li><p>Create components. Individual components will clean-up and clarify the construction of your UI.</p>\n</li>\n<li><p>Use layout managers to position the components.</p>\n</li>\n</ol>\n<hr />\n<h1>The hard way,</h1>\n<p>So, yes. As said in my simpler answer and by <em>Gilbert Le Blanc</em> you should try to implement a pattern to separate the UI from the &quot;logic&quot;. The <em>MVC</em> pattern is a common one in GUI applications, it is also the one used by advanced Swing components.</p>\n<p>Then why not trying to create three classes:</p>\n<ol>\n<li>A <strong>model</strong> that represent the state of your application; the list of results.</li>\n<li>A <strong>view</strong> that contains the graphical components used to display the results from the model.</li>\n<li>A <strong>controller</strong> to receive actions from the view and update the model accordingly.</li>\n</ol>\n<h2>Model</h2>\n<p>Your model is barely a <code>List&lt;Subreddit&gt;</code> where <code>Subreddit</code> is a <em>DTO</em> with a <code>title</code> and a <code>score</code>. But your view should be notified when this list changes, that's why you have to create a dedicated class for it and add some boilerplate to register and notify one (or many) listeners.</p>\n<h2>View</h2>\n<p>Your view is your <code>JFrame</code> (or any <code>Container</code> displayed inside a <code>JFrame</code>). This view should listen register a listener on the model so that it can refresh it when the results changes.</p>\n<pre><code>class RedditAppView extends JFrame {\n public RedditAppView(RedditAppModel model) {\n model.addModelListener(new RedditAppModel.ModelAdapter(){\n public void onResultsChanged(List&lt;Subbreddit&gt; results) {\n refresh();\n }\n });\n }\n}\n</code></pre>\n<p>It is easier to use a <code>LayoutManager</code> than using absolute layout in your views because the layout manager will take care of many part when you resize your application and when a component change. I like the <code>GridBagLayout</code>, it is a verbose layout (but Java and Swing are verbose too) but you can achieve almost everything with it and it is quite easy to reason about. However it can be very complex to create and maintain a large view. That's why we usually create components to encapsulate a functionality. In your case you can create:</p>\n<ul>\n<li>A <code>Logo</code> that will take care of resizing itself.</li>\n<li>A <code>SearchForm</code> that contains the <code>JTextField</code> and <code>JButton</code> add accept one event listener to be notified when the user click on the button, or press enter, or wait 3 seconds, .. that's one advantage of componentization; you can evolve one part of your app without touchhing the rest of the code.</li>\n<li>A <em>list of results</em>. It can be a <code>JList</code> inside a <code>JScrollPane</code>. You can configure a custom renderer on that list to render the <code>Subreddit</code> in a more appealing way than the default <code>toString</code>.</li>\n</ul>\n<p>Your view hierarchy may looks like:</p>\n<pre><code>RedditAppView\n |- Container\n | |- Logo\n | |- SearchForm\n | |- ResultList\n | | |- JLabel (&quot;# Votes&quot;)\n | | |- JScrollPane\n | | | |- JList with Renderer\n</code></pre>\n<p>If you use the model as suggested, then you can create a class that adapt your <code>RedditAppModel</code> to a <code>JListModel</code>. By doing that you don't need to <code>refresh</code> by yourself, the list of result will be updated automatically:</p>\n<pre><code>class ResultListModelAdapter extends DefaultListModel&lt;Subreddit&gt; {\n private final RedditAppModel model;\n private ResultListModelAdapter(RedditAppModel model) {\n this.model = model;\n this.model.addModelListener(new RedditAppModel.ModelAdapter() {\n @Override\n public void onResultsChanged(List&lt;Subreddit&gt; results) {\n int end = Math.max(getSize(), results.size()); // Not sure it is needed\n fireContentsChanged(this, 0, end);\n }\n });\n }\n\n @Override\n public int getSize() {\n return model.getResultsCount()\n }\n\n @Override\n public Subreddit getElementAt(int index) {\n return model.getResultAt(index);\n }\n}\n</code></pre>\n<h2>Controller</h2>\n<p>A class that will handle user actions and reflect them on the model. Your controller will have one single <code>search</code> action called when the view receive.</p>\n<pre><code>class RedditAppController {\n private final RedditAppModel model;\n\n public RedditAppController(RedditAppModel model, RedditApi api) {\n this.model = model;\n this.api = api;\n }\n\n void onSearch(String term) {\n List&lt;Subreddit&gt; results = // Jsoup things\n model.setResults(results);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T18:58:20.297", "Id": "260391", "ParentId": "260345", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T16:15:59.120", "Id": "260345", "Score": "2", "Tags": [ "java", "beginner", "swing", "gui" ], "Title": "reddit-like GUI" }
260345
<p>I have ~40,000 JPEG images from the <a href="https://www.kaggle.com/c/siim-isic-melanoma-classification" rel="nofollow noreferrer">Kaggle</a> melanoma classification competition. I created the following functions to denoise the images:</p> <pre><code># Denoising functions def denoise_single_image(img_path): img = cv2.imread(f'../data/jpeg/{img_path}') dst = cv2.fastNlMeansDenoising(img, 10,10,7,21) cv2.imwrite(f'../processed_data/jpeg/{img_path}', dst) print(f'{img_path} denoised.') def denoise(data): img_list = os.listdir(f'../data/jpeg/{data}') with concurrent.futures.ProcessPoolExecutor() as executor: tqdm.tqdm(executor.map(denoise_single_image, (f'{data}/{img_path}' for img_path in img_list))) </code></pre> <p>The <code>denoise</code> function uses <code>concurrent.futures</code> to map the <code>denoise_single_image()</code> function over the full list of images.</p> <p><code>ProcessPoolExecutor()</code> was used based on the assumption of denoising as a CPU-heavy task, rather than an I/O-intensitve task.</p> <p>As it stands now, this function takes hours to run. With a CUDA-configured Nvidia GPU and 6 GB VRAM, I'd like to optimize this further.</p> <p>Is there any way to improve the speed of this function?</p> <p><a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow noreferrer">Multi-core processing documentation</a><br/> <a href="https://docs.opencv.org/4.5.2/" rel="nofollow noreferrer">OpenCV documentation</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T07:25:27.630", "Id": "513978", "Score": "1", "body": "Welcome to Code Review. What Python version are you using?" } ]
[ { "body": "<p>You may look at opencv <a href=\"https://learnopencv.com/opencv-transparent-api/\" rel=\"nofollow noreferrer\">Transparent API</a></p>\n<pre><code>#\nimgUMat = cv2.UMat(img)\ndst = cv2.fastNlMeansDenoising(imgUMat, 10,10,7,21)\n#\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T10:49:17.910", "Id": "260365", "ParentId": "260355", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T03:18:59.100", "Id": "260355", "Score": "2", "Tags": [ "python", "image", "opencv", "multiprocessing" ], "Title": "Multi-core OpenCV denoising" }
260355
<p>I've improved my N-dimensional C++20 matrix project (<a href="https://codereview.stackexchange.com/questions/260197/c20-n-dimensional-minimal-matrix-class">C++20 : N-dimensional minimal Matrix class</a>).</p> <p>Implemented general matrix addition/subtraction, elementwise multiplication/division, dot product, matrix product, reshape, transpose.</p> <p>There's a lot of code:</p> <p>ObjectBase.h</p> <pre><code>#ifndef FROZENCA_OBJECTBASE_H #define FROZENCA_OBJECTBASE_H #include &lt;functional&gt; #include &lt;utility&gt; #include &quot;MatrixUtils.h&quot; namespace frozenca { template &lt;typename Derived&gt; class ObjectBase { private: Derived&amp; self() { return static_cast&lt;Derived&amp;&gt;(*this); } const Derived&amp; self() const { return static_cast&lt;const Derived&amp;&gt;(*this); } protected: ObjectBase() = default; ~ObjectBase() noexcept = default; public: auto begin() { return self().begin(); } auto begin() const { return self().begin(); } auto cbegin() const { return self().cbegin(); } auto end() { return self().end(); } auto end() const { return self().end(); } auto cend() const { return self().cend(); } auto rbegin() { return self().rbegin(); } auto rbegin() const { return self().rbegin(); } auto crbegin() const { return self().crbegin(); } auto rend() { return self().rend(); } auto rend() const { return self().rend(); } auto crend() const { return self().crend(); } template &lt;typename F&gt; requires std::invocable&lt;F, typename Derived::reference&gt; ObjectBase&amp; applyFunction(F&amp;&amp; f); template &lt;typename F, typename... Args&gt; requires std::invocable&lt;F, typename Derived::reference, Args...&gt; ObjectBase&amp; applyFunction(F&amp;&amp; f, Args&amp;&amp;... args); template &lt;typename DerivedOther, typename F&gt; requires std::invocable&lt;F, typename Derived::reference, typename DerivedOther::reference&gt; ObjectBase&amp; applyFunction(const ObjectBase&lt;DerivedOther&gt;&amp; other, F&amp;&amp; f); template &lt;typename DerivedOther, typename F, typename... Args&gt; requires std::invocable&lt;F, typename Derived::reference, typename DerivedOther::reference, Args...&gt; ObjectBase&amp; applyFunction(const ObjectBase&lt;DerivedOther&gt;&amp; other, F&amp;&amp; f, Args&amp;&amp;... args); template &lt;isNotMatrix U&gt; requires Addable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v = val;}); } template &lt;isNotMatrix U&gt; requires Addable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator+=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v += val;}); } template &lt;isNotMatrix U&gt; requires Subtractable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator-=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v -= val;}); } template &lt;isNotMatrix U&gt; requires Multipliable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator*=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v *= val;}); } template &lt;isNotMatrix U&gt; requires Dividable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator/=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v /= val;}); } template &lt;isNotMatrix U&gt; requires Remaindable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator%=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v %= val;}); } template &lt;isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator&amp;=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v &amp;= val;}); } template &lt;isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator|=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v |= val;}); } template &lt;isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator^=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v ^= val;}); } template &lt;isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator&lt;&lt;=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v &lt;&lt;= val;}); } template &lt;isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&amp; operator&gt;&gt;=(const U&amp; val) { return applyFunction([&amp;val](auto&amp; v) {v &gt;&gt;= val;}); } }; template &lt;typename Derived&gt; template &lt;typename F&gt; requires std::invocable&lt;F, typename Derived::reference&gt; ObjectBase&lt;Derived&gt;&amp; ObjectBase&lt;Derived&gt;::applyFunction(F&amp;&amp; f) { for (auto it = begin(); it != end(); ++it) { f(*it); } return *this; } template &lt;typename Derived&gt; template &lt;typename F, typename... Args&gt; requires std::invocable&lt;F, typename Derived::reference, Args...&gt; ObjectBase&lt;Derived&gt;&amp; ObjectBase&lt;Derived&gt;::applyFunction(F&amp;&amp; f, Args&amp;&amp;... args) { for (auto it = begin(); it != end(); ++it) { f(*it, std::forward&lt;Args...&gt;(args...)); } return *this; } template &lt;typename Derived&gt; template &lt;typename DerivedOther, typename F&gt; requires std::invocable&lt;F, typename Derived::reference, typename DerivedOther::reference&gt; ObjectBase&lt;Derived&gt;&amp; ObjectBase&lt;Derived&gt;::applyFunction(const ObjectBase&lt;DerivedOther&gt;&amp; other, F&amp;&amp; f) { for (auto it = begin(), it2 = other.begin(); it != end(); ++it, ++it2) { f(*it, *it2); } return *this; } template &lt;typename Derived&gt; template &lt;typename DerivedOther, typename F, typename... Args&gt; requires std::invocable&lt;F, typename Derived::reference, typename DerivedOther::reference, Args...&gt; ObjectBase&lt;Derived&gt;&amp; ObjectBase&lt;Derived&gt;::applyFunction(const ObjectBase&lt;DerivedOther&gt;&amp; other, F&amp;&amp; f, Args&amp;&amp;... args) { for (auto it = begin(), it2 = other.begin(); it != end(); ++it, ++it2) { f(*it, *it2, std::forward&lt;Args...&gt;(args...)); } return *this; } template &lt;typename Derived, isNotMatrix U&gt; requires Addable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator+(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res += val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires Subtractable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator-(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res -= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires Multipliable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator*(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res *= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires Dividable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator/(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res /= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires Remaindable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator%(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res %= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator&amp;(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res &amp;= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator^(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res ^= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator|(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res |= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator&lt;&lt;(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res &lt;&lt;= val; return res; } template &lt;typename Derived, isNotMatrix U&gt; requires BitMaskable&lt;typename Derived::value_type, U&gt; ObjectBase&lt;Derived&gt; operator&gt;&gt;(const ObjectBase&lt;Derived&gt;&amp; m, const U&amp; val) { ObjectBase&lt;Derived&gt; res = m; res &gt;&gt;= val; return res; } } // namespace frozenca #endif //FROZENCA_OBJECTBASE_H </code></pre> <p>MatrixBase.h</p> <pre><code>#ifndef FROZENCA_MATRIXBASE_H #define FROZENCA_MATRIXBASE_H #include &lt;numeric&gt; #include &quot;ObjectBase.h&quot; #include &quot;MatrixInitializer.h&quot; namespace frozenca { template &lt;std::semiregular T, std::size_t N&gt; class MatrixView; template &lt;typename Derived, std::semiregular T, std::size_t N&gt; class MatrixBase : public ObjectBase&lt;MatrixBase&lt;Derived, T, N&gt;&gt; { static_assert(N &gt; 1); public: static constexpr std::size_t ndim = N; private: std::array&lt;std::size_t, N&gt; dims_; std::size_t size_; std::array&lt;std::size_t, N&gt; strides_; public: MatrixBase() = delete; using Base = ObjectBase&lt;MatrixBase&lt;Derived, T, N&gt;&gt;; using Base::applyFunction; using Base::operator=; using Base::operator+=; using Base::operator-=; using Base::operator*=; using Base::operator/=; using Base::operator%=; Derived&amp; self() { return static_cast&lt;Derived&amp;&gt;(*this); } const Derived&amp; self() const { return static_cast&lt;const Derived&amp;&gt;(*this); } protected: ~MatrixBase() noexcept = default; MatrixBase(const std::array&lt;std::size_t, N&gt;&amp; dims); template &lt;std::size_t M&gt; requires (M &lt; N) MatrixBase(const std::array&lt;std::size_t, M&gt;&amp; dims); template &lt;IndexType... Dims&gt; explicit MatrixBase(Dims... dims); template &lt;typename DerivedOther, std::semiregular U&gt; requires std::is_convertible_v&lt;U, T&gt; MatrixBase(const MatrixBase&lt;DerivedOther, U, N&gt;&amp;); MatrixBase(typename MatrixInitializer&lt;T, N&gt;::type init); public: template &lt;typename U&gt; MatrixBase(std::initializer_list&lt;U&gt;) = delete; template &lt;typename U&gt; MatrixBase&amp; operator=(std::initializer_list&lt;U&gt;) = delete; using value_type = T; using reference = T&amp;; using const_reference = const T&amp;; using pointer = T*; public: friend void swap(MatrixBase&amp; a, MatrixBase&amp; b) noexcept { std::swap(a.size_, b.size_); std::swap(a.dims_, b.dims_); std::swap(a.strides_, b.strides_); } auto begin() { return self().begin(); } auto begin() const { return self().begin(); } auto cbegin() const { return self().cbegin(); } auto end() { return self().end(); } auto end() const { return self().end(); } auto cend() const { return self().cend(); } auto rbegin() { return self().rbegin(); } auto rbegin() const { return self().rbegin(); } auto crbegin() const { return self().crbegin(); } auto rend() { return self().rend(); } auto rend() const { return self().rend(); } auto crend() const { return self().crend(); } template &lt;IndexType... Args&gt; reference operator()(Args... args); template &lt;IndexType... Args&gt; const_reference operator()(Args... args) const; reference operator[](const std::array&lt;std::size_t, N&gt;&amp; pos); const_reference operator[](const std::array&lt;std::size_t, N&gt;&amp; pos) const; [[nodiscard]] std::size_t size() const { return size_;} [[nodiscard]] const std::array&lt;std::size_t, N&gt;&amp; dims() const { return dims_; } [[nodiscard]] std::size_t dims(std::size_t n) const { if (n &gt;= N) { throw std::out_of_range(&quot;Out of range in dims&quot;); } return dims_[n]; } [[nodiscard]] const std::array&lt;std::size_t, N&gt;&amp; strides() const { return strides_; } [[nodiscard]] std::size_t strides(std::size_t n) const { if (n &gt;= N) { throw std::out_of_range(&quot;Out of range in strides&quot;); } return strides_[n]; } auto dataView() const { return self().dataView(); } auto origStrides() const { return self().origStrides(); } MatrixView&lt;T, N&gt; submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin); MatrixView&lt;T, N&gt; submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin, const std::array&lt;std::size_t, N&gt;&amp; pos_end); MatrixView&lt;T, N - 1&gt; row(std::size_t n); MatrixView&lt;T, N - 1&gt; col(std::size_t n); MatrixView&lt;T, N - 1&gt; operator[](std::size_t n) { return row(n); } MatrixView&lt;T, N&gt; submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin) const; MatrixView&lt;T, N&gt; submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin, const std::array&lt;std::size_t, N&gt;&amp; pos_end) const; MatrixView&lt;T, N - 1&gt; row(std::size_t n) const; MatrixView&lt;T, N - 1&gt; col(std::size_t n) const; MatrixView&lt;T, N - 1&gt; operator[](std::size_t n) const { return row(n); } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const MatrixBase&amp; m) { os &lt;&lt; '{'; for (std::size_t i = 0; i != m.dims(0); ++i) { os &lt;&lt; m[i]; if (i + 1 != m.dims(0)) { os &lt;&lt; &quot;, &quot;; } } return os &lt;&lt; '}'; } template &lt;typename DerivedOther1, typename DerivedOther2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::invocable&lt;MatrixView&lt;T, N - 1&gt;&amp;, const MatrixView&lt;U, std::min(N1, N - 1)&gt;&amp;, const MatrixView&lt;V, std::min(N2, N - 1)&gt;&amp;&gt; F&gt; requires (std::max(N1, N2) == N) MatrixBase&amp; applyFunctionWithBroadcast(const MatrixBase&lt;DerivedOther1, U, N1&gt;&amp; m1, const MatrixBase&lt;DerivedOther2, V, N2&gt;&amp; m2, F&amp;&amp; f); }; template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixBase&lt;Derived, T, N&gt;::MatrixBase(const std::array&lt;std::size_t, N&gt;&amp; dims) : dims_ {dims} { if (std::ranges::find(dims_, 0lu) != std::end(dims_)) { throw std::invalid_argument(&quot;Zero dimension not allowed&quot;); } size_ = std::accumulate(std::begin(dims_), std::end(dims_), 1lu, std::multiplies&lt;&gt;{}); strides_ = computeStrides(dims_); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; template &lt;std::size_t M&gt; requires (M &lt; N) MatrixBase&lt;Derived, T, N&gt;::MatrixBase(const std::array&lt;std::size_t, M&gt;&amp; dims) : MatrixBase (prepend&lt;N, M&gt;(dims)) {} template &lt;typename Derived, std::semiregular T, std::size_t N&gt; template &lt;IndexType... Dims&gt; MatrixBase&lt;Derived, T, N&gt;::MatrixBase(Dims... dims) : dims_{static_cast&lt;std::size_t&gt;(dims)...} { static_assert(sizeof...(Dims) == N); static_assert((std::is_integral_v&lt;Dims&gt; &amp;&amp; ...)); if (std::ranges::find(dims_, 0lu) != std::end(dims_)) { throw std::invalid_argument(&quot;Zero dimension not allowed&quot;); } size_ = std::accumulate(std::begin(dims_), std::end(dims_), 1lu, std::multiplies&lt;&gt;{}); strides_ = computeStrides(dims_); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; template &lt;typename DerivedOther, std::semiregular U&gt; requires std::is_convertible_v&lt;U, T&gt; MatrixBase&lt;Derived, T, N&gt;::MatrixBase(const MatrixBase&lt;DerivedOther, U, N&gt;&amp; other) : MatrixBase(other.dims()) {} template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixBase&lt;Derived, T, N&gt;::MatrixBase(typename MatrixInitializer&lt;T, N&gt;::type init) : MatrixBase(deriveDims&lt;N&gt;(init)) {} template &lt;typename Derived, std::semiregular T, std::size_t N&gt; template &lt;IndexType... Args&gt; typename MatrixBase&lt;Derived, T, N&gt;::reference MatrixBase&lt;Derived, T, N&gt;::operator()(Args... args) { return const_cast&lt;typename MatrixBase&lt;Derived, T, N&gt;::reference&gt;(std::as_const(*this).operator()(args...)); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; template &lt;IndexType... Args&gt; typename MatrixBase&lt;Derived, T, N&gt;::const_reference MatrixBase&lt;Derived, T, N&gt;::operator()(Args... args) const { static_assert(sizeof...(args) == N); std::array&lt;std::size_t, N&gt; pos {std::size_t(args)...}; return operator[](pos); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; typename MatrixBase&lt;Derived, T, N&gt;::reference MatrixBase&lt;Derived, T, N&gt;::operator[](const std::array&lt;std::size_t, N&gt;&amp; pos) { return const_cast&lt;typename MatrixBase&lt;Derived, T, N&gt;::reference&gt;(std::as_const(*this).operator[](pos)); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; typename MatrixBase&lt;Derived, T, N&gt;::const_reference MatrixBase&lt;Derived, T, N&gt;::operator[](const std::array&lt;std::size_t, N&gt;&amp; pos) const { if (!std::equal(std::cbegin(pos), std::cend(pos), std::cbegin(dims_), std::less&lt;&gt;{})) { throw std::out_of_range(&quot;Out of range in element access&quot;); } return *(cbegin() + std::inner_product(std::cbegin(pos), std::cend(pos), std::cbegin(strides_), 0lu)); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N&gt; MatrixBase&lt;Derived, T, N&gt;::submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin) { return submatrix(pos_begin, dims_); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N&gt; MatrixBase&lt;Derived, T, N&gt;::submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin) const { return submatrix(pos_begin, dims_); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N&gt; MatrixBase&lt;Derived, T, N&gt;::submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin, const std::array&lt;std::size_t, N&gt;&amp; pos_end) { return std::as_const(*this).submatrix(pos_begin, pos_end); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N&gt; MatrixBase&lt;Derived, T, N&gt;::submatrix(const std::array&lt;std::size_t, N&gt;&amp; pos_begin, const std::array&lt;std::size_t, N&gt;&amp; pos_end) const { if (!std::equal(std::cbegin(pos_begin), std::cend(pos_begin), std::cbegin(pos_end), std::less&lt;&gt;{})) { throw std::out_of_range(&quot;submatrix begin/end position error&quot;); } std::array&lt;std::size_t, N&gt; view_dims; std::transform(std::cbegin(pos_end), std::cend(pos_end), std::cbegin(pos_begin), std::begin(view_dims), std::minus&lt;&gt;{}); MatrixView&lt;T, N&gt; view(view_dims, const_cast&lt;T*&gt;(&amp;operator[](pos_begin)), strides()); return view; } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N - 1&gt; MatrixBase&lt;Derived, T, N&gt;::row(std::size_t n) { return std::as_const(*this).row(n); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N - 1&gt; MatrixBase&lt;Derived, T, N&gt;::row(std::size_t n) const { const auto&amp; orig_dims = dims(); if (n &gt;= orig_dims[0]) { throw std::out_of_range(&quot;row index error&quot;); } std::array&lt;std::size_t, N - 1&gt; row_dims; std::copy(std::cbegin(orig_dims) + 1, std::cend(orig_dims), std::begin(row_dims)); std::array&lt;std::size_t, N&gt; pos_begin = {n, }; std::array&lt;std::size_t, N - 1&gt; row_strides; std::array&lt;std::size_t, N&gt; orig_strides; if constexpr (std::is_same_v&lt;Derived, MatrixView&lt;T, N&gt;&gt;) { orig_strides = origStrides(); } else { orig_strides = strides(); } std::copy(std::cbegin(orig_strides) + 1, std::cend(orig_strides), std::begin(row_strides)); MatrixView&lt;T, N - 1&gt; nth_row(row_dims, const_cast&lt;T*&gt;(&amp;operator[](pos_begin)), row_strides); return nth_row; } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N - 1&gt; MatrixBase&lt;Derived, T, N&gt;::col(std::size_t n) { return std::as_const(*this).col(n); } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; MatrixView&lt;T, N - 1&gt; MatrixBase&lt;Derived, T, N&gt;::col(std::size_t n) const { const auto&amp; orig_dims = dims(); if (n &gt;= orig_dims[N - 1]) { throw std::out_of_range(&quot;row index error&quot;); } std::array&lt;std::size_t, N - 1&gt; col_dims; std::copy(std::cbegin(orig_dims), std::cend(orig_dims) - 1, std::begin(col_dims)); std::array&lt;std::size_t, N&gt; pos_begin = {0}; pos_begin[N - 1] = n; std::array&lt;std::size_t, N - 1&gt; col_strides; std::array&lt;std::size_t, N&gt; orig_strides; if constexpr (std::is_same_v&lt;Derived, MatrixView&lt;T, N&gt;&gt;) { orig_strides = origStrides(); } else { orig_strides = strides(); } std::copy(std::cbegin(orig_strides), std::cend(orig_strides) - 1, std::begin(col_strides)); MatrixView&lt;T, N - 1&gt; nth_col(col_dims, const_cast&lt;T*&gt;(&amp;operator[](pos_begin)), col_strides); return nth_col; } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; template &lt;typename DerivedOther1, typename DerivedOther2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::invocable&lt;MatrixView&lt;T, N - 1&gt;&amp;, const MatrixView&lt;U, std::min(N1, N - 1)&gt;&amp;, const MatrixView&lt;V, std::min(N2, N - 1)&gt;&amp;&gt; F&gt; requires (std::max(N1, N2) == N) MatrixBase&lt;Derived, T, N&gt;&amp; MatrixBase&lt;Derived, T, N&gt;::applyFunctionWithBroadcast(const MatrixBase&lt;DerivedOther1, U, N1&gt;&amp; m1, const MatrixBase&lt;DerivedOther2, V, N2&gt;&amp; m2, F&amp;&amp; f) { if constexpr (N1 == N) { if constexpr (N2 == N) { auto r = dims(0); auto r1 = m1.dims(0); auto r2 = m2.dims(0); if (r1 == r) { if (r2 == r) { for (std::size_t i = 0; i &lt; r; ++i) { auto row = this-&gt;row(i); f(row, m1.row(i), m2.row(i)); } } else { // r2 &lt; r == r1 auto row2 = m2.row(0); for (std::size_t i = 0; i &lt; r; ++i) { auto row = this-&gt;row(i); f(row, m1.row(i), row2); } } } else if (r2 == r) { // r1 &lt; r == r2 auto row1 = m1.row(0); for (std::size_t i = 0; i &lt; r; ++i) { auto row = this-&gt;row(i); f(row, row1, m2.row(i)); } } else { assert(0); // cannot happen } } else { // N2 &lt; N == N1 auto r = dims(0); assert(r == m1.dims(0)); MatrixView&lt;V, N2&gt; view2 (m2); for (std::size_t i = 0; i &lt; r; ++i) { auto row = this-&gt;row(i); f(row, m1.row(i), view2); } } } else if constexpr (N2 == N) { // N1 &lt; N == N2 auto r = dims(0); assert(r == m2.dims(0)); MatrixView&lt;U, N1&gt; view1 (m1); for (std::size_t i = 0; i &lt; r; ++i) { auto row = this-&gt;row(i); f(row, view1, m2.row(i)); } } else { assert(0); // cannot happen } return *this; } template &lt;typename Derived, std::semiregular T&gt; class MatrixBase&lt;Derived, T, 1&gt; : public ObjectBase&lt;MatrixBase&lt;Derived, T, 1&gt;&gt; { public: static constexpr std::size_t ndim = 1; private: std::size_t dims_; std::size_t strides_; Derived&amp; self() { return static_cast&lt;Derived&amp;&gt;(*this); } const Derived&amp; self() const { return static_cast&lt;const Derived&amp;&gt;(*this); } public: MatrixBase() = delete; using Base = ObjectBase&lt;MatrixBase&lt;Derived, T, 1&gt;&gt;; using Base::applyFunction; using Base::operator=; using Base::operator+=; using Base::operator-=; using Base::operator*=; using Base::operator/=; using Base::operator%=; protected: ~MatrixBase() noexcept = default; template &lt;typename Dim&gt; requires std::is_integral_v&lt;Dim&gt; explicit MatrixBase(Dim dim) : dims_(dim), strides_(1) {}; template &lt;typename DerivedOther, std::semiregular U&gt; requires std::is_convertible_v&lt;U, T&gt; MatrixBase(const MatrixBase&lt;DerivedOther, U, 1&gt;&amp;); MatrixBase(typename MatrixInitializer&lt;T, 1&gt;::type init); public: using value_type = T; using reference = T&amp;; using const_reference = const T&amp;; using pointer = T*; public: friend void swap(MatrixBase&amp; a, MatrixBase&amp; b) noexcept { std::swap(a.size_, b.size_); std::swap(a.dims_, b.dims_); std::swap(a.strides_, b.strides_); } auto begin() { return self().begin(); } auto begin() const { return self().begin(); } auto cbegin() const { return self().cbegin(); } auto end() { return self().end(); } auto end() const { return self().end(); } auto cend() const { return self().cend(); } auto rbegin() { return self().rbegin(); } auto rbegin() const { return self().rbegin(); } auto crbegin() const { return self().crbegin(); } auto rend() { return self().rend(); } auto rend() const { return self().rend(); } auto crend() const { return self().crend(); } template &lt;typename Dim&gt; requires std::is_integral_v&lt;Dim&gt; reference operator()(Dim dim) { return operator[](dim); } template &lt;typename Dim&gt; requires std::is_integral_v&lt;Dim&gt; const_reference operator()(Dim dim) const { return operator[](dim); } [[nodiscard]] std::array&lt;std::size_t, 1&gt; dims() const { return {dims_}; } [[nodiscard]] std::size_t dims(std::size_t n) const { if (n &gt;= 1) { throw std::out_of_range(&quot;Out of range in dims&quot;); } return dims_; } [[nodiscard]] std::size_t strides() const { return strides_; } auto dataView() const { return self().dataView(); } auto origStrides() const { return self().origStrides(); } MatrixView&lt;T, 1&gt; submatrix(std::size_t pos_begin); MatrixView&lt;T, 1&gt; submatrix(std::size_t pos_begin, std::size_t pos_end); T&amp; row(std::size_t n); T&amp; col(std::size_t n); T&amp; operator[](std::size_t n) { return *(begin() + n); } MatrixView&lt;T, 1&gt; submatrix(std::size_t pos_begin) const; MatrixView&lt;T, 1&gt; submatrix(std::size_t pos_begin, std::size_t pos_end) const; const T&amp; row(std::size_t n) const; const T&amp; col(std::size_t n) const; const T&amp; operator[](std::size_t n) const { return *(cbegin() + n); } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const MatrixBase&amp; m) { os &lt;&lt; '{'; for (std::size_t i = 0; i != m.dims_; ++i) { os &lt;&lt; m[i]; if (i + 1 != m.dims_) { os &lt;&lt; &quot;, &quot;; } } return os &lt;&lt; '}'; } template &lt;typename DerivedOther1, typename DerivedOther2, std::semiregular U, std::semiregular V, std::invocable&lt;T&amp;, const U&amp;, const V&amp;&gt; F&gt; MatrixBase&amp; applyFunctionWithBroadcast(const frozenca::MatrixBase&lt;DerivedOther1, U, 1&gt;&amp; m1, const frozenca::MatrixBase&lt;DerivedOther2, V, 1&gt;&amp; m2, F&amp;&amp; f); }; template &lt;typename Derived, std::semiregular T&gt; MatrixBase&lt;Derived, T, 1&gt;::MatrixBase(typename MatrixInitializer&lt;T, 1&gt;::type init) : MatrixBase(deriveDims&lt;1&gt;(init)[0]) { } template &lt;typename Derived, std::semiregular T&gt; MatrixView&lt;T, 1&gt; MatrixBase&lt;Derived, T, 1&gt;::submatrix(std::size_t pos_begin) { return submatrix(pos_begin, dims_); } template &lt;typename Derived, std::semiregular T&gt; MatrixView&lt;T, 1&gt; MatrixBase&lt;Derived, T, 1&gt;::submatrix(std::size_t pos_begin) const { return submatrix(pos_begin, dims_); } template &lt;typename Derived, std::semiregular T&gt; MatrixView&lt;T, 1&gt; MatrixBase&lt;Derived, T, 1&gt;::submatrix(std::size_t pos_begin, std::size_t pos_end) { return std::as_const(*this).submatrix(pos_begin, pos_end); } template &lt;typename Derived, std::semiregular T&gt; MatrixView&lt;T, 1&gt; MatrixBase&lt;Derived, T, 1&gt;::submatrix(std::size_t pos_begin, std::size_t pos_end) const { if (pos_begin &gt;= pos_end) { throw std::out_of_range(&quot;submatrix begin/end position error&quot;); } MatrixView&lt;T, 1&gt; view ({pos_end - pos_begin}, const_cast&lt;T*&gt;(&amp;operator[](pos_begin)), {strides_}); return view; } template &lt;typename Derived, std::semiregular T&gt; T&amp; MatrixBase&lt;Derived, T, 1&gt;::row(std::size_t n) { return const_cast&lt;T&amp;&gt;(std::as_const(*this).row(n)); } template &lt;typename Derived, std::semiregular T&gt; const T&amp; MatrixBase&lt;Derived, T, 1&gt;::row(std::size_t n) const { if (n &gt;= dims_) { throw std::out_of_range(&quot;row index error&quot;); } const T&amp; val = operator[](n); return val; } template &lt;typename Derived, std::semiregular T&gt; T&amp; MatrixBase&lt;Derived, T, 1&gt;::col(std::size_t n) { return row(n); } template &lt;typename Derived, std::semiregular T&gt; const T&amp; MatrixBase&lt;Derived, T, 1&gt;::col(std::size_t n) const { return row(n); } template &lt;typename Derived, std::semiregular T&gt; template &lt;typename DerivedOther1, typename DerivedOther2, std::semiregular U, std::semiregular V, std::invocable&lt;T&amp;, const U&amp;, const V&amp;&gt; F&gt; MatrixBase&lt;Derived, T, 1&gt;&amp; MatrixBase&lt;Derived, T, 1&gt;::applyFunctionWithBroadcast( const frozenca::MatrixBase&lt;DerivedOther1, U, 1&gt;&amp; m1, const frozenca::MatrixBase&lt;DerivedOther2, V, 1&gt;&amp; m2, F&amp;&amp; f) { // real update is done here by passing lvalue reference T&amp; auto r = dims(0); auto r1 = m1.dims(0); auto r2 = m2.dims(0); if (r1 == r) { if (r2 == r) { for (std::size_t i = 0; i &lt; r; ++i) { f(this-&gt;row(i), m1.row(i), m2.row(i)); } } else { // r2 &lt; r == r1 auto row2 = m2.row(0); for (std::size_t i = 0; i &lt; r; ++i) { f(this-&gt;row(i), m1.row(i), row2); } } } else if (r2 == r) { // r1 &lt; r == r2 auto row1 = m1.row(0); for (std::size_t i = 0; i &lt; r; ++i) { f(this-&gt;row(i), row1, m2.row(i)); } } return *this; } } // namespace frozenca #endif //FROZENCA_MATRIXBASE_H </code></pre> <p>(Stackexchange says OP is too long so I replace two files as links)</p> <p>MatrixImpl.h (<a href="https://github.com/frozenca/Ndim-Matrix/blob/main/MatrixImpl.h" rel="nofollow noreferrer">https://github.com/frozenca/Ndim-Matrix/blob/main/MatrixImpl.h</a>)</p> <p>MatrixView.h (<a href="https://github.com/frozenca/Ndim-Matrix/blob/main/MatrixView.h" rel="nofollow noreferrer">https://github.com/frozenca/Ndim-Matrix/blob/main/MatrixView.h</a>)</p> <p>MatrixUtils.h</p> <pre><code>#ifndef FROZENCA_MATRIXUTILS_H #define FROZENCA_MATRIXUTILS_H #include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;concepts&gt; #include &lt;cstddef&gt; #include &lt;initializer_list&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;memory&gt; #include &lt;stdexcept&gt; #include &lt;type_traits&gt; namespace frozenca { template &lt;std::semiregular T, std::size_t N&gt; class Matrix; template &lt;std::semiregular T, std::size_t N&gt; class MatrixView; template &lt;typename Derived, std::semiregular T, std::size_t N&gt; class MatrixBase; template &lt;typename Derived&gt; class ObjectBase; template &lt;typename T&gt; constexpr bool NotMatrix = true; template &lt;std::semiregular T, std::size_t N&gt; constexpr bool NotMatrix&lt;Matrix&lt;T, N&gt;&gt; = false; template &lt;std::semiregular T, std::size_t N&gt; constexpr bool NotMatrix&lt;MatrixView&lt;T, N&gt;&gt; = false; template &lt;typename Derived, std::semiregular T, std::size_t N&gt; constexpr bool NotMatrix&lt;MatrixBase&lt;Derived, T, N&gt;&gt; = false; template &lt;typename Derived&gt; constexpr bool NotMatrix&lt;ObjectBase&lt;Derived&gt;&gt; = false; template &lt;typename T&gt; concept isNotMatrix = NotMatrix&lt;T&gt; &amp;&amp; std::semiregular&lt;T&gt;; template &lt;typename T&gt; concept isMatrix = !NotMatrix&lt;T&gt;; template &lt;typename T&gt; concept OneExists = requires () { { T{0} } -&gt; std::convertible_to&lt;T&gt;; { T{1} } -&gt; std::convertible_to&lt;T&gt;; }; template &lt;typename A, typename B&gt; concept WeakAddable = requires (A a, B b) { a + b; }; template &lt;typename A, typename B&gt; concept WeakSubtractable = requires (A a, B b) { a - b; }; template &lt;typename A, typename B&gt; concept WeakMultipliable = requires (A a, B b) { a * b; }; template &lt;typename A, typename B&gt; concept WeakDividable = requires (A a, B b) { a / b; }; template &lt;typename A, typename B&gt; concept WeakRemaindable = requires (A a, B b) { a / b; a % b; }; template &lt;typename A, typename B, typename C&gt; concept AddableTo = requires (A a, B b) { { a + b } -&gt; std::convertible_to&lt;C&gt;; }; template &lt;typename A, typename B, typename C&gt; concept SubtractableTo = requires (A a, B b) { { a - b } -&gt; std::convertible_to&lt;C&gt;; }; template &lt;typename A, typename B, typename C&gt; concept MultipliableTo = requires (A a, B b) { { a * b } -&gt; std::convertible_to&lt;C&gt;; }; template &lt;typename A, typename B, typename C&gt; concept DividableTo = requires (A a, B b) { { a / b } -&gt; std::convertible_to&lt;C&gt;; }; template &lt;typename A, typename B, typename C&gt; concept RemaindableTo = requires (A a, B b) { { a / b } -&gt; std::convertible_to&lt;C&gt;; { a % b } -&gt; std::convertible_to&lt;C&gt;; }; template &lt;typename A, typename B, typename C&gt; concept BitMaskableTo = requires (A a, B b) { { a &amp; b } -&gt; std::convertible_to&lt;C&gt;; { a | b } -&gt; std::convertible_to&lt;C&gt;; { a ^ b } -&gt; std::convertible_to&lt;C&gt;; { a &lt;&lt; b } -&gt; std::convertible_to&lt;C&gt;; { a &gt;&gt; b } -&gt; std::convertible_to&lt;C&gt;; }; template &lt;typename A, typename B&gt; concept Addable = AddableTo&lt;A, B, A&gt;; template &lt;typename A, typename B&gt; concept Subtractable = SubtractableTo&lt;A, B, A&gt;; template &lt;typename A, typename B&gt; concept Multipliable = MultipliableTo&lt;A, B, A&gt;; template &lt;typename A, typename B&gt; concept Dividable = DividableTo&lt;A, B, A&gt;; template &lt;typename A, typename B&gt; concept Remaindable = RemaindableTo&lt;A, B, A&gt;; template &lt;typename A, typename B&gt; concept BitMaskable = BitMaskableTo&lt;A, B, A&gt;; template &lt;typename A, typename B&gt; requires WeakAddable&lt;A, B&gt; inline decltype(auto) Plus(A a, B b) { return a + b; } template &lt;typename A, typename B&gt; requires WeakSubtractable&lt;A, B&gt; inline decltype(auto) Minus(A a, B b) { return a - b; } template &lt;typename A, typename B&gt; requires WeakMultipliable&lt;A, B&gt; inline decltype(auto) Multiplies(A a, B b) { return a * b; } template &lt;typename A, typename B&gt; requires WeakDividable&lt;A, B&gt; inline decltype(auto) Divides(A a, B b) { return a / b; } template &lt;typename A, typename B&gt; requires WeakRemaindable&lt;A, B&gt; inline decltype(auto) Modulus(A a, B b) { return a % b; } template &lt;typename A, typename B&gt; using AddType = std::invoke_result_t&lt;decltype(Plus&lt;A, B&gt;), A, B&gt;; template &lt;typename A, typename B&gt; using SubType = std::invoke_result_t&lt;decltype(Minus&lt;A, B&gt;), A, B&gt;; template &lt;typename A, typename B&gt; using MulType = std::invoke_result_t&lt;decltype(Multiplies&lt;A, B&gt;), A, B&gt;; template &lt;typename A, typename B&gt; using DivType = std::invoke_result_t&lt;decltype(Divides&lt;A, B&gt;), A, B&gt;; template &lt;typename A, typename B&gt; using ModType = std::invoke_result_t&lt;decltype(Modulus&lt;A, B&gt;), A, B&gt;; template &lt;typename A, typename B&gt; concept DotProductable = Addable&lt;MulType&lt;A, B&gt;, MulType&lt;A, B&gt;&gt;; template &lt;typename A, typename B, typename C&gt; concept DotProductableTo = DotProductable&lt;A, B&gt; &amp;&amp; MultipliableTo&lt;A, B, C&gt; &amp;&amp; Addable&lt;C, C&gt;; template &lt;typename A, typename B, typename C&gt; requires AddableTo&lt;A, B, C&gt; inline void PlusTo(C&amp; c, const A&amp; a, const B&amp; b) { c = a + b; } template &lt;typename A, typename B, typename C&gt; requires SubtractableTo&lt;A, B, C&gt; inline void MinusTo(C&amp; c, const A&amp; a, const B&amp; b) { c = a - b; } template &lt;typename A, typename B, typename C&gt; requires MultipliableTo&lt;A, B, C&gt; inline void MultipliesTo(C&amp; c, const A&amp; a, const B&amp; b) { c = a * b; } template &lt;typename A, typename B, typename C&gt; requires DividableTo&lt;A, B, C&gt; inline void DividesTo(C&amp; c, const A&amp; a, const B&amp; b) { c = a / b; } template &lt;typename A, typename B, typename C&gt; requires RemaindableTo&lt;A, B, C&gt; inline void ModulusTo(C&amp; c, const A&amp; a, const B&amp; b) { c = a % b; } template &lt;typename... Args&gt; inline constexpr bool All(Args... args) { return (... &amp;&amp; args); }; template &lt;typename... Args&gt; inline constexpr bool Some(Args... args) { return (... || args); }; template &lt;std::size_t M, std::size_t N&gt; requires (N &lt; M) std::array&lt;std::size_t, M&gt; prependDims(const std::array&lt;std::size_t, N&gt;&amp; arr) { std::array&lt;std::size_t, M&gt; dims; std::ranges::fill(dims, 1u); std::ranges::copy(arr, std::begin(dims) + (M - N)); return dims; } template &lt;std::size_t M, std::size_t N&gt; bool bidirBroadcastable(const std::array&lt;std::size_t, M&gt;&amp; sz1, const std::array&lt;std::size_t, N&gt;&amp; sz2) { if constexpr (M == N) { return (std::ranges::equal(sz1, sz2, [](const auto&amp; d1, const auto&amp; d2) { return (d1 == d2) || (d1 == 1) || (d2 == 1);})); } else if constexpr (M &lt; N) { return bidirBroadcastable(prependDims&lt;N, M&gt;(sz1), sz2); } else { static_assert(M &gt; N); return bidirBroadcastable(sz1, prependDims&lt;M, N&gt;(sz2)); } } template &lt;std::size_t M, std::size_t N&gt; std::array&lt;std::size_t, std::max(M, N)&gt; bidirBroadcastedDims(const std::array&lt;std::size_t, M&gt;&amp; sz1, const std::array&lt;std::size_t, N&gt;&amp; sz2) { if constexpr (M == N) { if (!bidirBroadcastable(sz1, sz2)) { throw std::invalid_argument(&quot;Cannot broadcast&quot;); } std::array&lt;std::size_t, M&gt; sz; std::ranges::transform(sz1, sz2, std::begin(sz), [](const auto&amp; d1, const auto&amp; d2) { return std::max(d1, d2); }); return sz; } else if constexpr (M &lt; N) { return bidirBroadcastedDims(prependDims&lt;N, M&gt;(sz1), sz2); } else { static_assert(M &gt; N); return bidirBroadcastedDims(sz1, prependDims&lt;M, N&gt;(sz2)); } } template &lt;std::size_t M&gt; requires (M &gt; 1) std::array&lt;std::size_t, M - 1&gt; dotDims(const std::array&lt;std::size_t, M&gt;&amp; sz1, const std::array&lt;std::size_t, 1&gt;&amp; sz2) { if (sz1[M - 1] != sz2[0]) { throw std::invalid_argument(&quot;Cannot do dot product, shape is not aligned&quot;); } std::array&lt;std::size_t, M - 1&gt; sz; std::copy(std::begin(sz1), std::begin(sz1) + (M - 1), std::begin(sz)); return sz; } template &lt;std::size_t M, std::size_t N&gt; requires (N &gt; 1) std::array&lt;std::size_t, M + N - 2&gt; dotDims(const std::array&lt;std::size_t, M&gt;&amp; sz1, const std::array&lt;std::size_t, N&gt;&amp; sz2) { if (sz1[M - 1] != sz2[N - 2]) { throw std::invalid_argument(&quot;Cannot do dot product, shape is not aligned&quot;); } std::array&lt;std::size_t, M + N - 2&gt; sz; std::copy(std::begin(sz1), std::begin(sz1) + (M - 1), std::begin(sz)); std::copy(std::begin(sz2), std::begin(sz2) + (N - 2), std::begin(sz) + (M - 1)); std::copy(std::begin(sz2) + (N - 1), std::end(sz2), std::begin(sz) + (M + N - 3)); return sz; } template &lt;std::size_t M, std::size_t N&gt; std::array&lt;std::size_t, std::max(M, N)&gt; matmulDims(const std::array&lt;std::size_t, M&gt;&amp; sz1, const std::array&lt;std::size_t, N&gt;&amp; sz2) { if constexpr (M == 1) { std::array&lt;std::size_t, 2&gt; sz1_ = {1, sz1[0]}; return matmulDims(sz1_, sz2); } else if constexpr (N == 1) { std::array&lt;std::size_t, 2&gt; sz2_ = {sz2[0], 1}; return matmulDims(sz1, sz2_); } assert(M &gt;= 2 &amp;&amp; N &gt;= 2); if (sz1[M - 1] != sz2[N - 2]) { throw std::invalid_argument(&quot;Cannot do dot product, shape is not aligned&quot;); } std::array&lt;std::size_t, 2&gt; last_sz = {sz1[M - 2], sz2[N - 1]}; if constexpr (M == 2) { if constexpr (N == 2) { return last_sz; } else { // M = 2, N &gt; 2 std::array&lt;std::size_t, N&gt; res_sz; std::copy(std::begin(sz2), std::begin(sz2) + (N - 2), std::begin(res_sz)); std::copy(std::begin(last_sz), std::end(last_sz), std::begin(res_sz) + (N - 2)); return res_sz; } } else if constexpr (N == 2) { // M &gt; 2, N = 2 std::array&lt;std::size_t, M&gt; res_sz; std::copy(std::begin(sz1), std::begin(sz2) + (M - 2), std::begin(res_sz)); std::copy(std::begin(last_sz), std::end(last_sz), std::begin(res_sz) + (M - 2)); return res_sz; } else { // M &gt; 2, N &gt; 2 std::array&lt;std::size_t, std::max(M, N)&gt; res_sz; std::array&lt;std::size_t, M - 2&gt; sz1_front; std::array&lt;std::size_t, N - 2&gt; sz2_front; std::copy(std::begin(sz1), std::begin(sz1) + (M - 2), std::begin(sz1_front)); std::copy(std::begin(sz2), std::begin(sz2) + (N - 2), std::begin(sz2_front)); auto common_sz = bidirBroadcastedDims(sz1_front, sz2_front); std::copy(std::begin(common_sz), std::end(common_sz), std::begin(res_sz)); std::copy(std::begin(last_sz), std::end(last_sz), std::end(res_sz) - 2); return res_sz; } } template &lt;typename... Args&gt; concept IndexType = All(std::is_integral_v&lt;Args&gt;...); template &lt;std::size_t N&gt; std::array&lt;std::size_t, N&gt; computeStrides(const std::array&lt;std::size_t, N&gt;&amp; dims) { std::array&lt;std::size_t, N&gt; strides; std::size_t str = 1; for (std::size_t i = N - 1; i &lt; N; --i) { strides[i] = str; str *= dims[i]; } return strides; } template &lt;std::size_t N, typename Initializer&gt; bool checkNonJagged(const Initializer&amp; init) { auto i = std::cbegin(init); for (auto j = std::next(i); j != std::cend(init); ++j) { if (i-&gt;size() != j-&gt;size()) { return false; } } return true; } template &lt;std::size_t N, typename Iter, typename Initializer&gt; void addDims(Iter&amp; first, const Initializer&amp; init) { if constexpr (N &gt; 1) { if (!checkNonJagged&lt;N&gt;(init)) { throw std::invalid_argument(&quot;Jagged matrix initializer&quot;); } } *first = std::size(init); ++first; if constexpr (N &gt; 1) { addDims&lt;N - 1&gt;(first, *std::begin(init)); } } template &lt;std::size_t N, typename Initializer&gt; std::array&lt;std::size_t, N&gt; deriveDims(const Initializer&amp; init) { std::array&lt;std::size_t, N&gt; dims; auto f = std::begin(dims); addDims&lt;N&gt;(f, init); return dims; } template &lt;std::semiregular T&gt; void addList(std::unique_ptr&lt;T[]&gt;&amp; data, const T* first, const T* last, std::size_t&amp; index) { for (; first != last; ++first) { data[index] = *first; ++index; } } template &lt;std::semiregular T, typename I&gt; void addList(std::unique_ptr&lt;T[]&gt;&amp; data, const std::initializer_list&lt;I&gt;* first, const std::initializer_list&lt;I&gt;* last, std::size_t&amp; index) { for (; first != last; ++first) { addList(data, first-&gt;begin(), first-&gt;end(), index); } } template &lt;std::semiregular T, typename I&gt; void insertFlat(std::unique_ptr&lt;T[]&gt;&amp; data, std::initializer_list&lt;I&gt; list) { std::size_t index = 0; addList(data, std::begin(list), std::end(list), index); } inline long quot(long a, long b) { return (a / b) - (a % b &lt; 0); } inline long mod(long a, long b) { return (a % b + b) % b; } } // namespace frozenca #endif //FROZENCA_MATRIXUTILS_H </code></pre> <p>MatrixInitializer.h</p> <pre><code>#ifndef FROZENCA_MATRIXINITIALIZER_H #define FROZENCA_MATRIXINITIALIZER_H #include &lt;cstddef&gt; #include &lt;concepts&gt; #include &lt;initializer_list&gt; namespace frozenca { template &lt;std::semiregular T, std::size_t N&gt; struct MatrixInitializer { using type = std::initializer_list&lt;typename MatrixInitializer&lt;T, N - 1&gt;::type&gt;; }; template &lt;std::semiregular T&gt; struct MatrixInitializer&lt;T, 1&gt; { using type = std::initializer_list&lt;T&gt;; }; template &lt;std::semiregular T&gt; struct MatrixInitializer&lt;T, 0&gt;; } // namespace frozenca #endif //FROZENCA_MATRIXINITIALIZER_H </code></pre> <p>MatrixOps.h</p> <pre><code>#ifndef FROZENCA_MATRIXOPS_H #define FROZENCA_MATRIXOPS_H #include &quot;MatrixImpl.h&quot; namespace frozenca { // Matrix constructs template &lt;std::semiregular T, std::size_t N&gt; Matrix&lt;T, N&gt; empty(const std::array&lt;std::size_t, N&gt;&amp; arr) { Matrix&lt;T, N&gt; mat (arr); return mat; } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; Matrix&lt;T, N&gt; empty_like(const MatrixBase&lt;Derived, T, N&gt;&amp; base) { Matrix&lt;T, N&gt; mat (base.dims()); return mat; } template &lt;OneExists T&gt; Matrix&lt;T, 2&gt; eye(std::size_t n, std::size_t m) { Matrix&lt;T, 2&gt; mat (n, m); for (std::size_t i = 0; i &lt; std::min(n, m); ++i) { mat(i, i) = T{1}; } return mat; } template &lt;OneExists T&gt; Matrix&lt;T, 2&gt; eye(std::size_t n) { return eye&lt;T&gt;(n, n); } template &lt;OneExists T&gt; Matrix&lt;T, 2&gt; identity(std::size_t n) { return eye&lt;T&gt;(n, n); } template &lt;OneExists T, std::size_t N&gt; Matrix&lt;T, N&gt; ones(const std::array&lt;std::size_t, N&gt;&amp; arr) { Matrix&lt;T, N&gt; mat (arr); std::ranges::fill(mat, T{1}); return mat; } template &lt;typename Derived, OneExists T, std::size_t N&gt; Matrix&lt;T, N&gt; ones_like(const MatrixBase&lt;Derived, T, N&gt;&amp; base) { Matrix&lt;T, N&gt; mat (base.dims()); std::ranges::fill(mat, T{1}); return mat; } template &lt;std::semiregular T, std::size_t N&gt; Matrix&lt;T, N&gt; zeros(const std::array&lt;std::size_t, N&gt;&amp; arr) { Matrix&lt;T, N&gt; mat (arr); std::ranges::fill(mat, T{0}); return mat; } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; Matrix&lt;T, N&gt; zeros_like(const MatrixBase&lt;Derived, T, N&gt;&amp; base) { Matrix&lt;T, N&gt; mat (base.dims()); std::ranges::fill(mat, T{0}); return mat; } template &lt;std::semiregular T, std::size_t N&gt; Matrix&lt;T, N&gt; full(const std::array&lt;std::size_t, N&gt;&amp; arr, const T&amp; fill_value) { Matrix&lt;T, N&gt; mat (arr); std::ranges::fill(mat, fill_value); return mat; } template &lt;typename Derived, std::semiregular T, std::size_t N&gt; Matrix&lt;T, N&gt; full_like(const MatrixBase&lt;Derived, T, N&gt;&amp; base, const T&amp; fill_value) { Matrix&lt;T, N&gt; mat (base.dims()); std::ranges::fill(mat, fill_value); return mat; } // binary matrix operators namespace { template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2, std::size_t N&gt; requires AddableTo&lt;U, V, T&gt; &amp;&amp; (std::max(N1, N2) == N) void AddTo(MatrixView&lt;T, N&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { if constexpr (N == 1) { m.applyFunctionWithBroadcast(m1, m2, PlusTo&lt;U, V, T&gt;); } else { m.applyFunctionWithBroadcast(m1, m2, AddTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); } } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2, std::size_t N&gt; requires SubtractableTo&lt;U, V, T&gt; &amp;&amp; (std::max(N1, N2) == N) void SubtractTo(MatrixView&lt;T, N&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { if constexpr (N == 1) { m.applyFunctionWithBroadcast(m1, m2, MinusTo&lt;U, V, T&gt;); } else { m.applyFunctionWithBroadcast(m1, m2, SubtractTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); } } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2, std::size_t N&gt; requires MultipliableTo&lt;U, V, T&gt; &amp;&amp; (std::max(N1, N2) == N) void MultiplyTo(MatrixView&lt;T, N&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { if constexpr (N == 1) { m.applyFunctionWithBroadcast(m1, m2, MultipliesTo&lt;U, V, T&gt;); } else { m.applyFunctionWithBroadcast(m1, m2, MultiplyTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); } } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2, std::size_t N&gt; requires DividableTo&lt;U, V, T&gt; &amp;&amp; (std::max(N1, N2) == N) void DivideTo(MatrixView&lt;T, N&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { if constexpr (N == 1) { m.applyFunctionWithBroadcast(m1, m2, DividesTo&lt;U, V, T&gt;); } else { m.applyFunctionWithBroadcast(m1, m2, DivideTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); } } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2, std::size_t N&gt; requires RemaindableTo&lt;U, V, T&gt; &amp;&amp; (std::max(N1, N2) == N) void ModuloTo(MatrixView&lt;T, N&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { if constexpr (N == 1) { m.applyFunctionWithBroadcast(m1, m2, ModulusTo&lt;U, V, T&gt;); } else { m.applyFunctionWithBroadcast(m1, m2, ModuloTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); } } } // anonymous namespace template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::semiregular T = AddType&lt;U, V&gt;&gt; requires AddableTo&lt;U, V, T&gt; decltype(auto) operator+ (const MatrixBase&lt;Derived1, U, N1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N2&gt;&amp; m2) { constexpr std::size_t N = std::max(N1, N2); auto dims = bidirBroadcastedDims(m1.dims(), m2.dims()); Matrix&lt;T, N&gt; res = zeros&lt;T, N&gt;(dims); res.applyFunctionWithBroadcast(m1, m2, AddTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); return res; } template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::semiregular T = SubType&lt;U, V&gt;&gt; requires SubtractableTo&lt;U, V, T&gt; decltype(auto) operator- (const MatrixBase&lt;Derived1, U, N1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N2&gt;&amp; m2) { constexpr std::size_t N = std::max(N1, N2); auto dims = bidirBroadcastedDims(m1.dims(), m2.dims()); Matrix&lt;T, N&gt; res = zeros&lt;T, N&gt;(dims); res.applyFunctionWithBroadcast(m1, m2, SubtractTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); return res; } template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::semiregular T = MulType&lt;U, V&gt;&gt; requires MultipliableTo&lt;U, V, T&gt; decltype(auto) operator* (const MatrixBase&lt;Derived1, U, N1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N2&gt;&amp; m2) { constexpr std::size_t N = std::max(N1, N2); auto dims = bidirBroadcastedDims(m1.dims(), m2.dims()); Matrix&lt;T, N&gt; res = zeros&lt;T, N&gt;(dims); res.applyFunctionWithBroadcast(m1, m2, MultiplyTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); return res; } template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::semiregular T = DivType&lt;U, V&gt;&gt; requires DividableTo&lt;U, V, T&gt; decltype(auto) operator/ (const MatrixBase&lt;Derived1, U, N1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N2&gt;&amp; m2) { constexpr std::size_t N = std::max(N1, N2); auto dims = bidirBroadcastedDims(m1.dims(), m2.dims()); Matrix&lt;T, N&gt; res = zeros&lt;T, N&gt;(dims); res.applyFunctionWithBroadcast(m1, m2, DivideTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); return res; } template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::semiregular T = ModType&lt;U, V&gt;&gt; requires RemaindableTo&lt;U, V, T&gt; decltype(auto) operator% (const MatrixBase&lt;Derived1, U, N1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N2&gt;&amp; m2) { constexpr std::size_t N = std::max(N1, N2); auto dims = bidirBroadcastedDims(m1.dims(), m2.dims()); Matrix&lt;T, N&gt; res = zeros&lt;T, N&gt;(dims); res.applyFunctionWithBroadcast(m1, m2, ModuloTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); return res; } } // namespace frozenca #endif //FROZENCA_MATRIXOPS_H </code></pre> <p>LinalgOps.h (LINEAR ALGEBRA OPERATIONS)</p> <pre><code>#ifndef FROZENCA_LINALGOPS_H #define FROZENCA_LINALGOPS_H #include &quot;Matrix.h&quot; namespace frozenca { namespace { template &lt;std::semiregular U, std::semiregular V, std::semiregular T&gt; requires DotProductableTo&lt;U, V, T&gt; void DotTo(T&amp; m, const MatrixView&lt;U, 1&gt;&amp; m1, const MatrixView&lt;V, 1&gt;&amp; m2) { m += std::inner_product(std::begin(m1), std::end(m1), std::begin(m2), T{0}); } template &lt;std::semiregular U, std::semiregular V, std::semiregular T&gt; requires DotProductableTo&lt;U, V, T&gt; void DotTo(MatrixView&lt;T, 1&gt;&amp; m, const MatrixView&lt;U, 1&gt;&amp; m1, const MatrixView&lt;V, 2&gt;&amp; m2) { assert(m.dims(0) == m2.dims(1)); std::size_t c = m2.dims(1); for (std::size_t j = 0; j &lt; c; ++j) { auto col2 = m2.col(j); m[j] += std::inner_product(std::begin(m1), std::end(m1), std::begin(col2), T{0}); } } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N2&gt; requires DotProductableTo&lt;U, V, T&gt; &amp;&amp; (N2 &gt; 2) void DotTo(MatrixView&lt;T, N2 - 1&gt;&amp; m, const MatrixView&lt;U, 1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { assert(m.dims(0) == m2.dims(0)); std::size_t r = m.dims(0); for (std::size_t i = 0; i &lt; r; ++i) { auto row0 = m.row(i); auto row2 = m2.row(i); DotTo(row0, m1, row2); } } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2&gt; requires DotProductableTo&lt;U, V, T&gt; &amp;&amp; (N1 &gt; 1) void DotTo(MatrixView&lt;T, N1 - 1&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, 1&gt;&amp; m2) { assert(m.dims(0) == m1.dims(0)); std::size_t r = m.dims(0); for (std::size_t i = 0; i &lt; r; ++i) { auto row0 = m.row(i); auto row1 = m1.row(i); DotTo(row0, row1, m2); } } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2&gt; requires DotProductableTo&lt;U, V, T&gt; &amp;&amp; (N1 &gt; 1) &amp;&amp; (N2 &gt; 1) void DotTo(MatrixView&lt;T, N1 + N2 - 2&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { assert(m.dims(0) == m1.dims(0)); std::size_t r = m.dims(0); for (std::size_t i = 0; i &lt; r; ++i) { auto row0 = m.row(i); auto row1 = m1.row(i); DotTo(row0, row1, m2); } } template &lt;typename Derived0, typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2&gt; requires DotProductableTo&lt;U, V, T&gt; void DotTo(MatrixBase&lt;Derived0, T, (N1 + N2 - 2)&gt;&amp; m, const MatrixBase&lt;Derived1, U, N1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N2&gt;&amp; m2) { MatrixView&lt;T, (N1 + N2 - 2)&gt; m_view (m); MatrixView&lt;U, N1&gt; m1_view (m1); MatrixView&lt;V, N2&gt; m2_view (m2); DotTo(m_view, m1_view, m2_view); } template &lt;std::semiregular U, std::semiregular V, std::semiregular T, std::size_t N1, std::size_t N2, std::size_t N&gt; requires DotProductableTo&lt;U, V, T&gt; &amp;&amp; (std::max(N1, N2) == N) void MatmulTo(MatrixView&lt;T, N&gt;&amp; m, const MatrixView&lt;U, N1&gt;&amp; m1, const MatrixView&lt;V, N2&gt;&amp; m2) { if constexpr (N == 2) { DotTo(m, m1, m2); } else { m.applyFunctionWithBroadcast(m1, m2, MatmulTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); } } } // anonymous namespace template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::size_t M, std::size_t N, std::semiregular T = MulType&lt;U, V&gt;&gt; requires DotProductableTo&lt;U, V, T&gt; decltype(auto) dot(const MatrixBase&lt;Derived1, U, M&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N&gt;&amp; m2) { auto dims = dotDims(m1.dims(), m2.dims()); Matrix&lt;T, (M + N - 2)&gt; res = zeros&lt;T, (M + N - 2)&gt;(dims); DotTo(res, m1, m2); return res; } template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::semiregular T = MulType&lt;U, V&gt;&gt; requires DotProductableTo&lt;U, V, T&gt; decltype(auto) dot(const MatrixBase&lt;Derived1, U, 1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, 1&gt;&amp; m2) { auto dims = dotDims(m1.dims(), m2.dims()); T res {0}; DotTo(res, m1, m2); return res; } template &lt;typename Derived1, typename Derived2, std::semiregular U, std::semiregular V, std::size_t N1, std::size_t N2, std::semiregular T = MulType&lt;U, V&gt;&gt; requires DotProductableTo&lt;U, V, T&gt; decltype(auto) matmul(const MatrixBase&lt;Derived1, U, N1&gt;&amp; m1, const MatrixBase&lt;Derived2, V, N2&gt;&amp; m2) { constexpr std::size_t N = std::max(N1, N2); auto dims = matmulDims(m1.dims(), m2.dims()); Matrix&lt;T, N&gt; res = zeros&lt;T, N&gt;(dims); res.applyFunctionWithBroadcast(m1, m2, MatmulTo&lt;U, V, T, std::min(N1, N - 1), std::min(N2, N - 1), N - 1&gt;); return res; } } // namespace frozenca #endif //FROZENCA_LINALGOPS_H </code></pre> <p>Matrix.h</p> <pre><code>#ifndef FROZENCA_MATRIX_H #define FROZENCA_MATRIX_H #include &quot;MatrixImpl.h&quot; #include &quot;MatrixOps.h&quot; #include &quot;LinalgOps.h&quot; #endif //FROZENCA_MATRIX_H </code></pre> <p>Feel free to comment anything!</p> <p>What I don't like:</p> <ul> <li>Too much expose of APIs to users. I hate C++ <code>include</code>s, I'm really waiting C++20 modules! (Current module implementation in MSVC 19.28 is broken, it fails to work in my code)</li> <li>.reshape(). It should move the buffer so takes rvalue reference, but I wonder something better.</li> <li>The helper functions are becoming too template-heavy. Precisely, I don't like functions like <code>applyFunctionWithBroadcasting</code> are generated differently with every different N &gt; 1 even if what they do is the same. But I need specialization for N = 1 (because submatrix, row, col should return <code>T&amp;</code>), so I don't know better way.</li> </ul> <p>To see what is going on with &quot;Broadcasting&quot;, dot product and matrix multiplication, see below:</p> <p><a href="https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md" rel="nofollow noreferrer">https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md</a></p> <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.dot.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.dot.html</a></p> <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.matmul.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.matmul.html</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T05:57:12.687", "Id": "260359", "Score": "1", "Tags": [ "c++", "matrix", "c++20" ], "Title": "C++20 : Ndim Matrix, broadcasting, np.dot() and np.matmul()" }
260359
<p>I have to find the sum of number after performing square operation in the given input the negative numbers need to be ignored. The input Format is, first line is number of test cases followed by N as number of test inputs in new line followed by N space seperated numbers. The task need to be done using golang without using for loop. Output need to be print in new line for each test case.</p> <pre><code>3 4 3 -1 1 14 5 9 6 -53 32 16 6 3 -4 12 2 5 7 </code></pre> <p>Below is my attempt to achieve the task using recurrsion.</p> <pre><code>package main import &quot;fmt&quot; func findSquareSum(x int, a []int, iteration int) { var num int if x &gt; 0 { fmt.Scanf(&quot;%d&quot;, &amp;num) if num &gt; 0 { a[iteration-1] += num * num } findSquareSum(x-1, a, iteration) } } func readTest(x int, a []int){ var input int if x &gt; 0{ fmt.Scanf(&quot;%d&quot;, &amp;input) findSquareSum(input,a,x) readTest(x-1,a) } } func printResult(x int, a []int){ if (x &gt; 0){ fmt.Println(a[x-1]) printResult(x-1,a) } } func main() { var test int fmt.Scanf(&quot;%d&quot;, &amp;test) a := make([]int, test) readTest(test,a) printResult(test,a) } </code></pre> <p>My question is as there is no base case in the recursive function. How the programm is working as per expectations?</p>
[]
[ { "body": "<p>There is a base case... it's the line <code>if x &gt; 0 {</code></p>\n<p>compare to the for loop version</p>\n<p><code>for x=input: x&gt;0: x=x-1 {</code></p>\n<p><code>findSquareSum(input,a,x)</code> sets x=input</p>\n<p><code>if x &gt; 0 {</code> is the condition check</p>\n<p><code>findSquareSum(x-1, a, iteration)</code> decrements x</p>\n<p>also consider the modified fucntion</p>\n<pre><code>func findSquareSum(x int, a []int, iteration int) {\n var num int\n if x &lt;= 0 { return }\n \n fmt.Scanf(&quot;%d&quot;, &amp;num)\n if num &gt; 0 {\n a[iteration-1] += num * num\n }\n findSquareSum(x-1, a, iteration)\n}\n</code></pre>\n<p>now it should look more like the base cases we are to seeing. It should also be clear that this is equivalent to the askers version (unless my go syntax is wrong!)</p>\n<p>similarly</p>\n<pre><code>func readTest(x int, a []int){\n var input int\n if x &lt;= 0 { return }\n fmt.Scanf(&quot;%d&quot;, &amp;input)\n findSquareSum(input,a,x)\n readTest(x-1,a)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T10:35:23.090", "Id": "260364", "ParentId": "260360", "Score": "1" } } ]
{ "AcceptedAnswerId": "260364", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T06:59:26.657", "Id": "260360", "Score": "0", "Tags": [ "recursion", "go" ], "Title": "Perform sum of squared numbers without using for loop" }
260360
<p>Exactly what the title says, this is a C++ class that attempts to read a file into a null-terminated string as efficiently as possible, using POSIX APIs. Obviously this is not intended to be portable code (other than between POSIX-compliant operating systems and GCC or clang), and the <code>Slurp</code> class would have a more extensive API in &quot;real&quot; code.</p> <p>But, is there any room for improvement in terms of correctness or efficiency?</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef SLURP_H #define SLURP_H class Slurp { void *begin_{nullptr}; void *end_; public: Slurp() = delete; Slurp(Slurp&amp;) = delete; Slurp &amp;operator=(Slurp) = delete; [[gnu::nonnull]] Slurp(const char path[]); ~Slurp(); [[gnu::const, gnu::returns_nonnull]] const char *begin() const noexcept; [[gnu::const, gnu::returns_nonnull]] const char *end() const noexcept; }; #endif //SLURP_H // Slurp.cc #include &lt;fcntl.h&gt; #include &lt;sys/mman.h&gt; #include &lt;sys/stat.h&gt; #include &lt;unistd.h&gt; #include &lt;cerrno&gt; #include &lt;cstdlib&gt; #include &lt;cstring&gt; #include &lt;system_error&gt; using namespace std; #define ERROR_IF(CONDITION) do {\ if (__builtin_expect((CONDITION), false))\ throw system_error(errno, system_category());\ } while (false) #define ERROR_IF_POSIX(POSIX_PREFIXED_FUNCTION_CALL) do {\ const int error_number = posix_##POSIX_PREFIXED_FUNCTION_CALL;\ if (__builtin_expect(error_number, 0))\ throw system_error(error_number, system_category());\ } while (false) Slurp::Slurp(const char path[]) { class FileDescriptor { const int fd_; public: FileDescriptor(int fd) : fd_{fd} {ERROR_IF(fd_ == -1);} ~FileDescriptor() {close(fd_);} [[gnu::const]] operator int() const noexcept {return fd_;} }; FileDescriptor fd{open(path, O_RDONLY)}; ERROR_IF_POSIX(fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)); struct stat file_statistics; ERROR_IF(fstat(fd, &amp;file_statistics)); constexpr char32_t NullChar = U'\0'; const size_t fsize = static_cast&lt;size_t&gt;(file_statistics.st_size), blksize = static_cast&lt;size_t&gt;(file_statistics.st_blksize), bufsize = fsize + sizeof NullChar; ERROR_IF_POSIX(memalign(&amp;begin_, blksize, bufsize)); end_ = static_cast&lt;char*&gt;(begin_) + fsize; ERROR_IF_POSIX(madvise(begin_, bufsize, POSIX_MADV_SEQUENTIAL)); ERROR_IF(read(fd, begin_, fsize) == -1); memcpy(end_, &amp;NullChar, sizeof NullChar); // ensure null termination } Slurp::~Slurp() {free(begin_);} const char *Slurp::begin() const noexcept {return static_cast&lt;char*&gt;(begin_);} const char *Slurp::end() const noexcept {return static_cast&lt;char*&gt;(end_);} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T15:20:47.317", "Id": "514007", "Score": "0", "body": "Why do you not trust the efficiency of `fstream`? Have you come to the conclusion that you need your own code based on an actual performance profile?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T15:25:32.610", "Id": "514008", "Score": "0", "body": "I was inspired by [this blog post](https://insanecoding.blogspot.com/2011/11/reading-in-entire-file-at-once-in-c.html), where the (unspecified by the author) \"POSIX\" method of reading a file into a string was the most performant." } ]
[ { "body": "<p>This is a good project, one that could be very useful in practice. I’ve had two or three C++ blogs over the years, and every time I spin up a new one, I include an updated version of a very old post I wrote about reading an entire file into a string. It’s not an easy problem to solve efficiently, for a number of complicated reasons. Eschewing the standard library and going directly to underlying POSIX API is not a bad idea; one of the sources of inefficiency is the fact that the standard library will buffer everything, meaning you end up with an unnecessary “middle man” between your code and the actual file data.</p>\n<p>I am not an expert in the POSIX APIs, so take everything I say in that area with a grain of salt. However, the algorithm itself looks okay; I don’t see anything <em>wrong</em> with it. There are a few things I think are probably unnecessary and useless, but nothing that introduces potential dangers. I’ll get into details about the algorithm as we come to them in the code.</p>\n<p>Normally I would start with a design review, but… well, frankly, there doesn’t really look like there’s much in the way of design here. Your focus appears to be on the reading algorithm, and very little else. Which… not a good thing. That’s actually the <em>opposite</em> of how you write good code. And it shows here. To word it another way, the actual file-reading code is probably fine… but to actually <em>use</em> it in practical code (the way it’s currently written) would be difficult, at best.</p>\n<p>For example, the iterators return <code>char const*</code>, and there looks like a lot of effort to <code>NUL</code>-terminate the data. So… is it meant to be string data? If so, why isn’t there a <code>c_str()</code> function? Or a conversion to <code>string_view</code>? On the other hand, if it’s not meant to be a string, just raw byte data read from a file, why not use <code>std::byte</code>? Why isn’t there a <code>data()</code> function?</p>\n<p>Better yet, why not just read the data directly into an existing container, like <code>std::string</code> (for text data) or <code>std::vector&lt;std::byte&gt;</code> (for binary data)?</p>\n<p>But I get it; your focus was on the read algorithm, not making an actually useful interface. That’s fine for experimentation, but when you’re eventually putting this code to use in a real-world library, the place that <em>really</em> needs focus is the public interface… not the low-level reading code. If your public interface sucks, then even if the reading code is the most brilliant code ever, the whole library still sucks for the user. But if your public interface is really good, then even if the reading code sucks… well, you can fix that under the hood, and users of your public interface won’t notice (except for maybe seeing performance gains).</p>\n<p>Also, you should really get into the habit of testing your code. And by that I don’t mean “write it, then write a <code>main()</code> function that tries it out and if it all compiles and appears to run and produce correct-looking output, that’s that”. I mean fully unit-testing the code.</p>\n<p>So, let’s get into the actual code.</p>\n<h2>Code review</h2>\n<h3><code>Slurp.hh</code></h3>\n<pre><code> void *begin_{nullptr};\n void *end_;\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl18-use-c-style-declarator-layout\" rel=\"noreferrer\">The convention in C++ is to put all the type information together</a>. In other words:</p>\n<ul>\n<li><code>void *end_;</code>: This is C style.</li>\n<li><code>void* end_;</code>: This is C++ style. (Well, other than that we try to avoid <code>void*</code> in C++.)</li>\n</ul>\n<p>There is an alternative design to consider. Rather than holding two pointers, it might make more sense to hold a pointer and a size. Why? It makes it much easier to maintain and check the class invariant. If you use a pair of pointers, you have to make sure that <code>end_</code> comes after <code>begin_</code>. But there is no portable way to ensure that (comparing random pointers is UB). On the other hand, if you use a pointer and a size, there is no possible way that the “end” can be before the beginning (assuming the size is unsigned, which is standard practice, but even if it’s signed, it’s trivial to check that the size is greater than zero).</p>\n<p>It’s not really a big deal, and two pointers does work just fine in practice. It’s just something I’ve seen experts have <em>opinions</em> on.</p>\n<p>I also don’t get why these are <code>void*</code>. <code>void*</code> makes a lot less sense in C++ than it does in C, and in this case… I can’t see the point of it at all. If this is supposed to be character data—a string—then why aren’t these <code>char*</code>? That sure seems to be the intention, what with all the <code>NUL</code> terminating and casting in <code>begin()</code> and <code>end()</code>. If this is supposed to be <em>binary</em> data, then <code>unsigned char*</code> or, better, <code>std::byte*</code> make more sense. <code>void*</code> just doesn’t make sense, not least because you’re just casting it to <code>char*</code> before using it anyway.</p>\n<p>Anywho, aside from all that, there doesn’t seem to be a reason why <code>end_</code> couldn’t also have an initializer.</p>\n<pre><code> Slurp() = delete;\n</code></pre>\n<p>This line is technically unnecessary, because the fact that you have the constructor <code>Slurp(char const[])</code> means that you have already disabled the default constructor.</p>\n<p>Still, it doesn’t hurt, and it does express intent, so I’d leave it.</p>\n<pre><code> Slurp(Slurp&amp;) = delete;\n Slurp &amp;operator=(Slurp) = delete;\n</code></pre>\n<p>These will probably “work”, but if your intention is to disable copying, then they are malformed. They should be:</p>\n<pre><code> Slurp(Slurp const&amp;) = delete;\n auto operator=(Slurp const&amp;) -&gt; Slurp&amp; = delete;\n // or:\n // Slurp&amp; operator=(Slurp const&amp;) = delete;\n</code></pre>\n<p>Disabling copying makes sense, given that copying will probably be fairly expensive. If someone <em>really</em> wants to copy the data, they can always do something like:</p>\n<pre><code>auto const data = Slurp{&quot;input.data&quot;};\n\nauto const data_copy = std::vector(data.begin(), data.end());\n</code></pre>\n<p>But you might consider making the type <em>movable</em>. That could be <em>very</em> handy. It wouldn’t even be hard to do; you just need to make the class aware of a “null” or moved-from state, perhaps like so:</p>\n<pre><code>class Slurp\n{\nprivate:\n void* begin_ = nullptr;\n void* end_ = nullptr;\n\npublic:\n [[gnu::nonnull]] explicit Slurp(char const* path)\n {\n // your existing constructor code...\n }\n\n Slurp(Slurp&amp;&amp; other) noexcept\n {\n std::ranges::swap(begin_, other.begin_);\n std::ranges::swap(end_, other.end_);\n }\n\n ~Slurp()\n {\n if (begin_) // note the if test\n std::free(begin_);\n }\n\n auto operator=(Slurp&amp;&amp; other) noexcept -&gt; Slurp&amp;\n {\n std::ranges::swap(begin_, other.begin_);\n std::ranges::swap(end_, other.end_);\n return *this;\n }\n\n Slurp(Slurp const&amp;) = delete;\n auto operator=(Slurp const&amp;) -&gt; Slurp&amp; = delete;\n};\n</code></pre>\n<p>Being able to very cheaply moved the slurped data around could be <em>very</em> handy indeed.</p>\n<pre><code> [[gnu::nonnull]] Slurp(const char path[]);\n</code></pre>\n<p>Writing functions that <em>look</em> like they take arrays like this is a really bad idea. (<em>Except</em> for <code>main()</code>, which is just special in a lot of ways.) I’ve lost count of the number of newbies who think that this actually takes an array argument, and then think they can do <code>sizeof(path) / sizeof(path[0])</code> to get the number of elements. Yes, you and I and other experts know what’s really going on, but you shouldn’t be writing code that’s only readable by experts. Down that path lies madness.</p>\n<p>On the other hand <code>Slurp(const char* path)</code> or <code>Slurp(char const* path)</code> are unlikely to confuse beginners, and, really, tell the truth of what’s going on much better.</p>\n<p>As a general rule, all constructors that take a single argument should be marked <code>explicit</code> (unless you have a damn good reason not to). Yes, explicit should really be the default, but that ship sailed a long time ago.</p>\n<p>In addition to this constructor, it would help usability if you could use strings or—even better—<em>actual paths</em> with this class. It would be trivial to do, too:</p>\n<pre><code>explicit Slurp(std::string const&amp; path) :\n Slurp{path.c_str()}\n{}\n\nexplicit Slurp(std::filesystem::path const&amp; path) :\n Slurp{path.c_str()}\n{}\n</code></pre>\n<p>Now this next bit is going to get <em>really</em> complicated. Brace yourself.</p>\n<h3><code>gnu::const</code> on non-static member functions</h3>\n<pre><code> [[gnu::const, gnu::returns_nonnull]] const char *begin() const noexcept;\n</code></pre>\n<p>The issue here the <code>gnu::const</code> attribute. I am not a GCC expert, but from my understanding of <code>gnu::const</code>, it sure seems like using it for a member function is an absolutely terrible, and dangerous, idea.</p>\n<p>Here’s why.</p>\n<p><code>gnu::const</code> means that a function’s output depends <em><strong>ONLY</strong></em> on the function’s arguments. And I mean <em><strong>ONLY</strong></em>. The function’s behaviour <em>cannot</em> be affected by anything else; it doesn’t matter what state the rest of the program happens to be in (well, I mean, the state has to be <em>valid</em>… if the abstract machine’s state is kerfuckt, then all bets are off in any case), the function’s return value will <em><strong>ALWAYS</strong></em> be the same, given the same arguments.</p>\n<p>This makes sense for, say, a function like: <code>auto twice(int i) { return i * 2; }</code>. It doesn’t matter what’s going on with the rest of the program, like how many exceptions are in flight or how many files are open or how much memory has been allocated. So long as the function <em>can</em> complete without UB (for example, there is no stack overflow), then it will <em><strong>ALWAYS</strong></em> return the same result for the same arguments. <code>twice(32)</code> will <em><strong>ALWAYS</strong></em> return <code>64</code>. <em><strong>ALWAYS</strong></em>. GCC can use that information to optimize. For example, if you call <code>twice(14)</code> a million times in your program, GCC might cache the result of the first call, and then replace every other call with just loading that cached value.</p>\n<p>So far none of this sounds problematic, I suppose. Well, now let’s talk about non-static member functions.</p>\n<p>There is a very important key feature of non-static class member functions: the implicit <code>this</code>.</p>\n<p>You see, every non-static class member function has a hidden <code>this</code> argument. We usually pretend it’s the first argument (but it doesn’t actually have to be, in reality, it’s usually passed in a specific register), so your <code>begin()</code> function <em>actually</em> looks like <code>begin(Slurp const*)</code>:</p>\n<pre><code>// what you write:\nauto Slurp::begin() const noexcept -&gt; char const*\n{\n return begin_;\n}\n\n// what the compiler actually implements:\nauto Slurp__begin(Slurp const* this) noexcept -&gt; char const*\n{\n return this-&gt;begin_;\n}\n</code></pre>\n<p>Normally, this isn’t something you need to think about.</p>\n<p>However… remember what <code>gnu::const</code> means. It means that <code>begin()</code> will <em><strong>ALWAYS</strong></em> return the same result, when called with the same argument.</p>\n<p>So let’s imagine you write this:</p>\n<pre><code>auto const s = Slurp{&quot;data.file&quot;};\n\nauto p1 = s.begin();\nauto p2 = s.begin();\nauto p3 = s.begin();\nauto p4 = s.begin();\nauto p5 = s.begin();\n</code></pre>\n<p>The above is theoretically:</p>\n<pre><code>auto const s = Slurp{&quot;data.file&quot;};\n\nauto p1 = Slurp__begin(&amp;s);\nauto p2 = Slurp__begin(&amp;s);\nauto p3 = Slurp__begin(&amp;s);\nauto p4 = Slurp__begin(&amp;s);\nauto p5 = Slurp__begin(&amp;s);\n</code></pre>\n<p>But since <code>begin()</code> is <code>gnu::const</code>, once we know the result of calling it with address of <code>s</code>, we can assume that will <em><strong>ALWAYS</strong></em> be the result of calling it with that address. So the compiler could do:</p>\n<pre><code>auto p1 = Slurp__begin(&amp;s);\nauto p2 = p1;\nauto p3 = p1;\nauto p4 = p1;\nauto p5 = p1;\n</code></pre>\n<p>(And it probably will.)</p>\n<p>So far no problems. There is currently no way for the value of <code>begin_</code> to change once a <code>Slurp</code> object has been constructed, so the above code is a perfectly valid optimization.</p>\n<p>However, suppose you implemented moving—or copying, or <em>any</em> way to change the data in a <code>Slurp</code> object. Then you wrote this:</p>\n<pre><code>auto const s = Slurp{&quot;data.file&quot;};\n\nauto p1 = s.begin();\nauto p2 = s.begin();\n\ns = Slurp{&quot;other.file&quot;}; // this line will construct a new Slurp,\n // and REPLACE the internals of `s` with the\n // new data\n\nauto p3 = s.begin();\nauto p4 = s.begin();\n</code></pre>\n<p>Now the <em>address</em> of <code>s</code> hasn’t changed… but it’s internal data—in particular, the value of <code>begin_</code>—<em>has</em> changed. The compiler sees the above code as:</p>\n<pre><code>auto const s = Slurp{&quot;data.file&quot;};\n\nauto p1 = Slurp__begin(&amp;s);\nauto p2 = Slurp__begin(&amp;s);\n\ns = Slurp{&quot;other.file&quot;};\n\nauto p3 = Slurp__begin(&amp;s);\nauto p4 = Slurp__begin(&amp;s);\n</code></pre>\n<p>And it does the optimization:</p>\n<pre><code>auto const s = Slurp{&quot;data.file&quot;};\n\nauto p1 = Slurp__begin(&amp;s);\nauto p2 = p1;\n\ns = Slurp{&quot;other.file&quot;};\n\nauto p3 = p1;\nauto p4 = p1;\n</code></pre>\n<p>Except after the move assignment, <code>p1</code> is now a dangling pointer. Which means <code>p3</code> and <code>p4</code> are dangling pointers, too.</p>\n<p>This is a disaster.</p>\n<p>Now you may be thinking: “Meh, no problem; my class is non-copyable, non-movable, <em>and</em> immutable. This problem doesn’t affect me.”</p>\n<p>Wanna bet?</p>\n<p>Remember, <code>gnu::const</code> isn’t about the <em>object</em>. It’s about the <em>arguments to the function</em>. In the example above, the object’s internals changed, but the address of the object didn’t, so the argument to <code>begin()</code> didn’t either, and that was the problem. So if the object’s internals can’t possibly change… no problem, right?</p>\n<p>Wrong.</p>\n<p>Because even if it is impossible to change the internals of an object, it is still possible to create an object… destroy it… then create a whole new object at the same memory address… <em>and it is the <strong>address</strong> that matters</em>. Because <em>that</em> is what is being used as the function argument to <code>begin()</code>.</p>\n<p>Here’s just one example of how that could happen:</p>\n<pre><code>auto s = std::optional&lt;Slurp&gt;{std::in_place, &quot;data.file&quot;};\n\nauto p1 = s-&gt;begin();\nauto p2 = s-&gt;begin();\n\ns.emplace(&quot;other.file&quot;); // destroys contained Slurp object, then\n // constructs a new one in the same place... so it\n // has the same address\n\nauto p3 = s-&gt;begin();\nauto p4 = s-&gt;begin();\n</code></pre>\n<p>Which eventually optimizes to:</p>\n<pre><code>auto s = std::optional&lt;Slurp&gt;{std::in_place, &quot;data.file&quot;};\n\nauto p1 = s-&gt;begin();\nauto p2 = p1;\n\ns.emplace(&quot;other.file&quot;);\n\nauto p3 = p1;\nauto p4 = p1;\n</code></pre>\n<p>And ends up with the same problem.</p>\n<p>But you don’t even need <code>std::optional</code>! This problem could be triggered with even this code:</p>\n<pre><code>auto f()\n{\n auto s = Slurp{&quot;data.file&quot;};\n\n auto p = s.begin();\n}\n\nauto some_other_function()\n{\n f();\n f();\n}\n</code></pre>\n<p>What might happen above is the first call to <code>f()</code> happens to place <code>s</code> at some address on the stack… then when <code>f()</code> ends, <code>s</code> is destroyed… then <code>f()</code> is called <em>again</em> and <em>just happens</em> to place the <em>new</em> <code>s</code> <em>at the same address on the stack</em>. But of course, the allocation done within the <code>Slurp</code> constructor (the <code>posix_memalign()</code> call) may be entirely different. So <code>p</code> <em><strong>SHOULD</strong></em> have two entirely different values with the two successive calls to <code>f()</code> <em>even though the address of <code>s</code></em> (and thus, the argument passed to <code>begin()</code>) <em>is the same for both calls</em>. But <code>gnu::const</code> says it won’t; <code>gnu::const</code> says that if the argument is the same, the result is the same.</p>\n<p>Once again: catastrophe.</p>\n<p>To get a clearer view of why, imagine the calls to <code>f()</code> are inlined. Inlining isn’t necessary to trigger the problem, but it helps illustrate. If the calls are inlined, <code>some_other_function()</code> will look like:</p>\n<pre><code>auto some_other_function()\n{\n {\n auto s = Slurp{&quot;data.file&quot;};\n\n auto p = s.begin();\n\n // s is destroyed here\n }\n\n {\n auto s = Slurp{&quot;data.file&quot;};\n\n auto p = s.begin();\n\n // s is destroyed here\n }\n}\n</code></pre>\n<p>After the first <code>s</code> is destroyed, the second <code>s</code> may very well be constructed at the exact same location… let’s call it <code>STACK_ADDRESS</code>. So:</p>\n<pre><code>auto some_other_function()\n{\n {\n auto s = Slurp{&quot;data.file&quot;};\n\n auto p = Slurp__begin(STACK_ADDRESS);\n\n // s is destroyed here\n }\n\n {\n auto s = Slurp{&quot;data.file&quot;};\n\n auto p = Slurp__begin(STACK_ADDRESS);\n\n // s is destroyed here\n }\n}\n</code></pre>\n<p>The two calls to <code>begin()</code> are identical, and <code>gnu::const</code> promises that that means the result will be identical, so the compiler might do:</p>\n<pre><code>auto some_other_function()\n{\n auto __p_inlined = static_cast&lt;char const*&gt;(nullptr);\n\n {\n auto s = Slurp{&quot;data.file&quot;};\n\n __p_inlined = Slurp__begin(STACK_ADDRESS);\n auto p = __p_inlined;\n\n // s is destroyed here\n }\n\n {\n auto s = Slurp{&quot;data.file&quot;};\n\n auto p = __p_inlined;\n\n // s is destroyed here\n }\n}\n</code></pre>\n<p>And, boom.</p>\n<p>Whew, that was a long digression. The tl;dr is “don’t use <code>gnu::const</code> for (non-static) member functions”… but I think it’s important to understand <em>why</em>.</p>\n<p>And, really, it seems kinda pointless in modern C++. If it is possible for a function to be <code>gnu::const</code>, then it is <em>almost certainly</em> also possible for it to be <code>constexpr</code>… in which case the compiler can optimize it <em>far</em> more aggressively than it could possibly optimize a function that is merely <code>gnu::const</code> (but not wholly visible).</p>\n<h3><code>Slurp.cc</code></h3>\n<pre><code>using namespace std;\n</code></pre>\n<p>Never, ever do this at file scope. No, not even in a non-header file. Just use <code>std::</code>.</p>\n<pre><code>#define ERROR_IF(CONDITION) do {\\\n if (__builtin_expect((CONDITION), false))\\\n throw system_error(errno, system_category());\\\n } while (false)\n\n#define ERROR_IF_POSIX(POSIX_PREFIXED_FUNCTION_CALL) do {\\\n const int error_number = posix_##POSIX_PREFIXED_FUNCTION_CALL;\\\n if (__builtin_expect(error_number, 0))\\\n throw system_error(error_number, system_category());\\\n } while (false)\n</code></pre>\n<p>Avoid macros. There’s no good reason for them here. Inlined functions will be just as efficient… not that it really matters, because these are error cases after all. For example:</p>\n<pre><code>namespace {\n\nauto error_if(int result)\n{\n if (result != 0) [[unlikely]]\n throw std::system_error{errno, std::system_category()};\n}\n\nauto error_if_posix(int error_number)\n{\n if (error_number != 0) [[unlikely]]\n throw std::system_error{error_number, std::system_category()};\n}\n\n} // anonymous namespace\n\nSlurp::Slurp(char const* path)\n{\n // ... [snip] ...\n\n error_if_posix(::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL));\n\n struct ::stat file_statistics{};\n error_if(::fstat(fd, &amp;file_statistics));\n\n // ... etc.\n</code></pre>\n<p>But even that’s not really great, because it just obfuscates the function’s logic. I don’t see how it’s really an improvement over:</p>\n<pre><code>Slurp::Slurp(char const* path)\n{\n // ... [snip] ...\n\n if (auto const res = ::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); res != 0) [[unlikely]]\n throw std::system_error{res, std::system_category()};\n\n struct ::stat file_statistics{};\n if (auto const res = ::fstat(fd, &amp;file_statistics); res != 0) [[unlikely]]\n throw std::system_error{errno, std::system_category()};\n\n // ... etc.\n</code></pre>\n<p>The only thing I might do is maybe avoid repeating <code>std::system_category</code> by doing:</p>\n<pre><code>namespace {\n\nauto posix_error(int err)\n{\n return std::system_error{err, std::system_category()};\n}\n\n} // anonymous namespace\n\nSlurp::Slurp(char const* path)\n{\n // ... [snip] ...\n\n if (auto const res = ::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); res != 0) [[unlikely]]\n throw posix_error(res);\n\n auto file_statistics = ::stat{};\n if (auto const res = ::fstat(fd, &amp;file_statistics); res != 0) [[unlikely]]\n throw posix_error(errno);\n\n // ... etc.\n</code></pre>\n<p>I just don’t see the benefit of hiding the <code>throw</code>s. Yes, I get that it is somewhat ugly to have to check the return code every function call… but this is a C API; that’s just the nature of the game.</p>\n<p>If you <em>really</em> don’t want all that ugly C-ish code, the right move is to properly wrap the API… not to obfuscate your logic by hiding it behind macros. For example:</p>\n<pre><code>Slurp::Slurp(char const* path)\n{\n auto const fd = posix::open(path, O_RDONLY);\n\n posix::fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);\n\n auto const file_statistics = posix::fstat(fd);\n\n // ... etc.\n</code></pre>\n<p>(Note that implied is that each call above throws on failure, like a good C++ API should.)</p>\n<p>But it’s really an all-or-nothing deal. Either completely wrap the API into a <em>proper</em> C++ API, so the usage just looks like regular C++… which maintainers of the code should be familiar with. <em>Or</em> use the C API as-is—don’t hide it behind macros—so people who actually <em>know</em> the POSIX API inside and out can look at your code and immediately spot what’s going on (and any potential problems). Going half-way just annoys both parties, with no real benefits.</p>\n<pre><code> class FileDescriptor {\n const int fd_;\n public:\n FileDescriptor(int fd) : fd_{fd} {ERROR_IF(fd_ == -1);}\n ~FileDescriptor() {close(fd_);}\n [[gnu::const]] operator int() const noexcept {return fd_;}\n };\n</code></pre>\n<p>This is a <em>really</em> useful class! Rather than burying it as an implementation detail, it could be part of a public API. You’d need to flesh it out a bit (and make it non-copyable, but perhaps movable), but it’s pretty cool.</p>\n<pre><code>FileDescriptor fd{open(path, O_RDONLY)};\n</code></pre>\n<p>This goes back to the “never use <code>using namespace std;</code>” rule: function names like <code>open()</code> are <em>extremely</em> common, and there is a very high chance of conflict between the POSIX function, and some function you might put in your class in the future. If that were to happen, if you are <em>lucky</em>, you’ll get a compile error… but I’ve seen cases where behaviour subtly changes because the wrong function is called.</p>\n<p>To make sure you get the right function, you should explicitly qualify it. In this case, because it’s a POSIX function that doesn’t exist in a namespace, you have to use <code>::open()</code>.</p>\n<p>You should do this for all the POSIX functions.</p>\n<pre><code>constexpr char32_t NullChar = U'\\0';\n</code></pre>\n<p>I’m a little baffled by the logic here.</p>\n<p>Okay, so you want the data to be null-terminated. Fine, sure. But… you’re treating the data as an array of <code>char</code>… not <code>char32_t</code>. So… huh?</p>\n<p>The only thing I can figure is that you’re imagining that maybe someone might possibly want to <code>reinterpret_cast</code> the <code>char const*</code> to <code>char32_t const*</code>, and treat the data as a UTF-32 <code>NUL</code>-terminated string. That seems a pretty odd thing to presume. And it’s even odder when you consider that the <code>Slurp</code> class doesn’t even model a <code>NUL</code>-terminated string in <em>any</em> sense. There is no <code>c_str()</code> function, for example. Even if there were, it’s hard to see why it should return a <code>char32_t const*</code> and not a <code>char const*</code>.</p>\n<p>Aside from being odd, it may also be wrong. You are aligning the memory according to <code>file_statistics.st_blksize</code>… not <code>alignof(char32_t)</code>. In other words, if you’re thinking that you can just <code>reinterpret_cast</code> the result of <code>begin()</code> to a <code>char32_t const*</code> and treat it as a UTF-32 string… you may be in for a nasty surprise when your program crashes due to a a misaligned read. Or, possibly, just garbled text (that is probably illegal Unicode). (And all this is assuming the endianness of the UTF-32 data is correct.)</p>\n<p>I mean, if you really wanted to read file data as a UTF-32 string, why wouldn’t you read it into a <code>std::u32string</code>? Similarly, if you want a regular string, why not read it directly into a <code>std::string</code>? In either case, all the allocation and alignment headaches are taken care of, and the <code>NUL</code> termination is automatic. And if you want binary data, why not read directly into a <code>std::vector&lt;std::byte&gt;</code>?</p>\n<p>I’ll be getting back to that idea later.</p>\n<pre><code>ERROR_IF_POSIX(memalign(&amp;begin_, blksize, bufsize));\n</code></pre>\n<p>Honestly, I don’t see the point of this.</p>\n<p>Okay, I get that the file you’re reading probably has a preferred block size, and if you were mem-mapping the file, or reading it <em>directly</em> from storage, then yes, you’d need aligned memory. But you’re doing neither.</p>\n<p>Internally, when you open the file (and specify the access characteristics via <code>posix_fadvise()</code>) a buffer gets created. (I <em>think</em> you can avoid this by using direct input, but that’s beyond the scope here. <code>mmap()</code> is another way to avoid the buffer, but that’s another beast altogether.) Then you are reading from that buffer into your program’s memory space. Now, the <em>buffer</em> needs to be aligned to the block size of the file, so that the file can be read efficiently a block at a time. But <em>your</em> memory… the memory you allocate to read the file data (from the buffer) into… <em>that</em> does not need to be aligned to the block size of the file… because with that memory, you are not reading directly from the file, you are reading memory-to-memory (from the kernel’s buffer, to your array).</p>\n<p>Follow? Block-alignment only matters for the initial read of the file from the device. <em><strong>THAT</strong></em> needs to be block-aligned. But unless you’re doing <em>direct</em> input, that’s happening in the kernel (usually), and then <code>read()</code> copies from that buffer to your desired location. Once the data is already in RAM, it’s just a memory-to-memory copy… which is just a <code>rep stosb</code> or some SSE or AVX operation. That <em>doesn’t</em> need to be aligned.⁕</p>\n<p>⁕ (Ugh, in order to make this not <em>too</em> absurdly long, I have to gloss over or outright ignore a <em>lot</em> of hyper-technical details, so I <em>know</em> there are nerds out there just champing at the bit to “akshually…” me in the comments. Okay, yes, the data <em>does</em> need to be aligned for super-fast memory-to-memory transfer… both the source and destination data, with penalties for <em>not</em> being aligned varying depending on your processor architecture. <em><strong>HOWEVER</strong></em>… the default C++ allocator in any serious-grade standard library is almost certainly already aligning every allocation to take advantage of those efficiencies by default. So unless you’re doing something “clever”, you don’t need to worry about it.)</p>\n<p>In other words, you’re wasting your time using <code>posix_memalign()</code>. You gain nothing from it. You could just as well be using <code>malloc()</code> or <code>new</code>.</p>\n<p>Which brings us back again to the idea of reading directly into <code>std::string</code> or <code>std::vector&lt;std::byte&gt;</code>. But let me postpone that for a bit more, because we’re almost at the end of the code, so let’s get through that first.</p>\n<pre><code>ERROR_IF_POSIX(madvise(begin_, bufsize, POSIX_MADV_SEQUENTIAL));\n</code></pre>\n<p>I’ll admit that I don’t understand how this call isn’t failing. I <em>thought</em> <code>posix_madvise()</code> was only for memory-mapped memory. I would have guessed you’d get a <code>EBADF</code> from trying to use it on random memory. TIL, I guess.</p>\n<p>But I do suspect the call is just being ignored. My understanding of <code>POSIX_MADV_SEQUENTIAL</code> is that it signals to the kernel to make a larger look-ahead buffer… which makes sense if you’re mem-mapping a file into memory, but is just nonsense for RAM. (Where you gonna put the look-ahead buffer for RAM? Super-duper-RAM?)</p>\n<pre><code>ERROR_IF(read(fd, begin_, fsize) == -1);\n</code></pre>\n<p><code>read()</code> can fail spuriously for a number of reasons, like a signal interrupting it, and end up doing only a partial read. You can’t just write a <code>read()</code> call like this; you need to call it in a loop and keep doing reads until you’ve read <code>fsize</code> bytes in total or until <code>read()</code> returns zero.</p>\n<pre><code>memcpy(end_, &amp;NullChar, sizeof NullChar); // ensure null termination\n</code></pre>\n<p>I mean… why not just <code>std::fill_n(end, 4, 0);</code>? It would probably be faster. (Unless your optimizer is smart enough to transform that <code>memcpy()</code> into a <code>memset()</code>, in which case it will probably be equally fast.)</p>\n<h2>Reading directly into containers</h2>\n<p>Okay, the biggest problem with <code>Slurp</code> is that it’s a specialized type. Even if it had a perfect interface, it’s still not a string. If I need a <code>std::string</code>, which is very common, then I’ll be forced to copy the entire <code>Slurp</code> object into a <code>std::string</code>. What a waste.</p>\n<p>What if you just read the file’s contents directly into a <code>std::string</code>. Or, if it’s binary data, into a <code>std::vector&lt;std::byte&gt;</code>. Remember, there is no need to use <code>posix_memalign()</code> to specially align the memory to the original file’s preferred block size. The default allocator will align things just fine. So you <em>can</em> just use standard containers.</p>\n<p>(But, FYI, even if the default allocator <em>didn’t</em> align things just fine, it would still be a better solution to use a custom allocator, and standard containers, rather that rolling your own, half-assed container.)</p>\n<p>For example, to read into a string (note: untested, rough code):</p>\n<pre><code>auto read_into_string(std::filesystem::path const&amp; path)\n{\n // file_descriptor is a class basically identical to yours\n auto const fd = file_descriptor{::open(path.c_str(), O_RDONLY)};\n\n // get the file size from the file descriptor\n auto const file_size = [&amp;]\n {\n struct ::stat fstats{};\n if (auto const res = ::fstat(fd, &amp;fstats); res != 0)\n throw std::system_error{errno, std::system_category()};\n return fstats.st_size;\n }();\n\n // create the string we'll be reading into\n auto s = std::string{};\n s.resize(file_size);\n\n // this is the read loop\n auto pos = std::string::size_type{};\n while (true)\n {\n auto const last_read = ::read(fd, s.data() + pos, s.size() - pos);\n if (last_read &lt; 0)\n throw std::system_error{errno, std::system_category()};\n else if (last_read == 0)\n break;\n\n // this should never happen\n if (last_read &gt; (s.size() - pos)) [[unlikely]]\n throw std::runtime_error{&quot;more data in file than file size&quot;};\n\n pos += last_read;\n }\n\n // this should never happen\n if (pos != s.size()) [[unlikely]]\n throw std::runtime_error{&quot;failed to read entire file&quot;};\n\n return s;\n}\n</code></pre>\n<p>And the usage:</p>\n<pre><code>auto const string_data = read_into_string(&quot;file.txt&quot;);\n</code></pre>\n<p>And <code>string_data</code> is a <code>std::string</code>.</p>\n<p>The <em>only</em> thing that I suspect might make this code slower than your code, and only for very, very large files, is that there is no way (AFAIK) to allocate a <code>std::string</code> without initializing its contents. In other words, <code>s.resize(n)</code> doesn’t does just allocate <code>n</code> bytes (internally), it also <em>zeros</em> those bytes… which is a total waste of time for us. You shouldn’t have this inefficiency if you’re reading binary data into a <code>std::vector&lt;std::byte&gt;</code> (for which the code is otherwise identical).</p>\n<p>But even that <code>std::string</code> inefficiency should be tolerable (unless your files are <em>huge</em>), because you get the benefit of actually having an honest-to-goodness string. Which basically works everywhere, and which many APIs specifically need, in one form or another.</p>\n<p>And, frankly, I seriously doubt you’ll even notice it, because, again, unless you’re dealing with <em>huge</em> files, the cost of that zeroing will be completely <em>dwarfed</em> by the I/O costs.</p>\n<p>Anywho, this is getting way too long, and I’ve been sitting on it for days, so, I’ll just go ahead and publish what I’ve got.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T01:05:52.437", "Id": "514503", "Score": "0", "body": "Thanks for giving me such a thorough answer! My detailed response to you is in my own answer below." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T00:36:10.690", "Id": "260590", "ParentId": "260373", "Score": "5" } }, { "body": "<p>I would expect <code>Slurp.cc</code> to include <code>Slurp.h</code> - in fact, I can't see how you could compile it without the definitions there. I recommend making it the first include, to detect whether any dependencies are introduced.</p>\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>Bringing all of the <code>std</code> identifiers into the global namespace is usually a bad idea - just write <code>std::size_t</code> and other identifiers in full.</p>\n<p>It seems strange to use a <code>std::char32_t</code> as terminator for a string of <code>char</code>. If we need to read files with different character types, then I would expect to handle that using a template class.</p>\n<p>Obviously files with embedded null characters will appear truncated when interpreted as (null-terminated) C strings; it's good that you provide <code>begin()</code> and <code>end()</code> so users can wrap in <code>std::string_view</code> - although start and length would feed better to its constructor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T20:58:36.903", "Id": "514497", "Score": "0", "body": "1) In case it wasn't clear, my code snippet was supposed to be `Slurp.cc` after `Slurp.h` was included. 2) It's just `char32_t`, no `std::` (it's a fundamental type). 3) The character encoding (or lack thereof) of a file is not necessarily known at compile-time so I find it most correct to always handle the case where the file is encoded as UTF-32. In \"real\" code `Slurp` would provide different \"views\" or iterators for different character encodings." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T18:56:06.130", "Id": "260622", "ParentId": "260373", "Score": "0" } }, { "body": "<p>Here is how I've updated my code, for C++20, to make the API more usable and full-featured, and with feedback from indi. After that I've written a response to indi's feedback, since I think he deserves one and it's too long and detailed to do so in comments.</p>\n<hr />\n<p>Demangle.h</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifndef DEMANGLE_H\n#define DEMANGLE_H\n\n#include &lt;cxxabi.h&gt;\n\n#include &lt;cstdlib&gt;\n#include &lt;new&gt;\n#include &lt;string_view&gt;\n#include &lt;typeinfo&gt;\n\ntemplate&lt;typename T&gt;\nclass Demangle {\n char *name{nullptr};\n\n Demangle(std::string_view s)\n : name{static_cast&lt;char*&gt;(std::calloc(s.size() + 1, 1))}\n {\n if (!name)\n throw std::bad_alloc{};\n\n s.copy(name, s.size());\n }\npublic:\n Demangle() {\n int status;\n name = abi::__cxa_demangle(\n typeid(T).name(), nullptr, nullptr, &amp;status);\n\n if (!name)\n throw std::bad_alloc{};\n }\n\n Demangle(const Demangle &amp;other) : Demangle{std::string_view{other}} {}\n\n Demangle(Demangle &amp;&amp;other) noexcept {std::swap(name, other.name);}\n\n Demangle &amp;operator=(Demangle rhs) noexcept {\n std::swap(name, rhs.name);\n return *this;\n }\n\n ~Demangle() {std::free(name);}\n\n operator std::string_view() const noexcept {return name;}\n};\n\n#endif//DEMANGLE_H\n</code></pre>\n<p>FileDescriptor.h</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifndef FILE_DESCRIPTOR_H\n#define FILE_DESCRIPTOR_H\n\nclass FileDescriptor {\n const int fd_;\npublic:\n explicit FileDescriptor(int fd);\n [[gnu::nonnull]] FileDescriptor(const char path[], int oflag);\n /* std::string / std::filesystem::path / similar constructor\n */\n template&lt;class T&gt;\n FileDescriptor(const T &amp;t, int oflag)\n : FileDescriptor{t.c_str(), oflag} {}\n\n ~FileDescriptor();\n\n [[gnu::const]] operator const int&amp;() const noexcept;\n};\n\n#endif//FILE_DESCRIPTOR_H\n</code></pre>\n<p>ProjectConcepts.h</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifndef PROJECT_CONCEPTS_H\n#define PROJECT_CONCEPTS_H\n\n#include &lt;type_traits&gt;\n\nnamespace Project {\n\ntemplate&lt;typename T&gt;\nconcept TriviallyCopyable = std::is_trivially_copyable_v&lt;T&gt;;\n\n}//Project\n\n#endif//PROJECT_CONCEPTS_H\n</code></pre>\n<p>Slurp.h</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifndef SLURP_H\n#define SLURP_H\n\n#include &quot;Demangle.h&quot;\n#include &quot;FileDescriptor.h&quot;\n#include &quot;ProjectConcepts.h&quot;\n\n#include &lt;filesystem&gt;\n#include &lt;initializer_list&gt;\n#include &lt;span&gt;\n#include &lt;stdexcept&gt;\n#include &lt;string&gt;\n\nclass Slurp {\n template&lt;typename T&gt;\n static constexpr bool IsSmol = sizeof(T) == 1;\n\n struct Bounds {void *begin{nullptr}, *end;} b;\n\n template&lt;Project::TriviallyCopyable T&gt;\n std::initializer_list&lt;T*&gt; init() const noexcept(IsSmol&lt;T&gt;) {\n if (size() % sizeof(T)) [[unlikely]] {\n const Demangle&lt;T&gt; tp_name;\n throw std::logic_error{std::string{\n &quot;can't interpret file as array of &quot;} + tp_name};\n }\n return {static_cast&lt;T*&gt;(b.begin), static_cast&lt;T*&gt;(b.end)};\n }\npublic:\n Slurp(const Slurp&amp;) = delete;\n Slurp &amp;operator=(const Slurp&amp;) = delete;\n\n Slurp(Slurp &amp;&amp;other) noexcept;\n Slurp &amp;operator=(Slurp &amp;&amp;rhs) noexcept;\n\n explicit Slurp(const FileDescriptor &amp;fd);\n [[gnu::nonnull]] Slurp(const char path[]);\n explicit Slurp(const std::string &amp;path);\n explicit Slurp(const std::filesystem::path &amp;path);\n\n ~Slurp();\n\n [[gnu::returns_nonnull]] const char *begin() const noexcept;\n [[gnu::returns_nonnull]] const char *end() const noexcept;\n\n std::size_t size() const noexcept;\n\n template&lt;Project::TriviallyCopyable T, class Traits=std::char_traits&lt;T&gt;&gt;\n operator std::basic_string_view&lt;T, Traits&gt;() const noexcept(IsSmol&lt;T&gt;) {\n return init&lt;T&gt;();\n }\n template&lt;Project::TriviallyCopyable T&gt;\n operator std::span&lt;T&gt;() &amp; noexcept(IsSmol&lt;T&gt;) {\n return init&lt;T&gt;();\n }\n template&lt;Project::TriviallyCopyable T&gt;\n operator std::span&lt;const T&gt;() const noexcept(IsSmol&lt;T&gt;) {\n return init&lt;T&gt;();\n }\n};\n\n#endif//SLURP_H\n</code></pre>\n<p>SystemErrorIf.h</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifndef SYSTEM_ERROR_IF_H\n#define SYSTEM_ERROR_IF_H\n\n#include &lt;cerrno&gt;\n#include &lt;system_error&gt;\n\nnamespace SystemErrorIf {\n\nconstexpr void condition(bool condition) {\n if (condition) [[unlikely]]\n throw std::system_error{errno, std::system_category()};\n}\n\nconstexpr void code(int error_number) {\n if (error_number) [[unlikely]]\n throw std::system_error{error_number, std::system_category()};\n}\n\n}//SystemErrorIf\n\n#endif//SYSTEM_ERROR_IF_H\n</code></pre>\n<p>FileDescriptor.cc</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &quot;FileDescriptor.h&quot;\n#include &quot;SystemErrorIf.h&quot;\n\n#include &lt;fcntl.h&gt;\n#include &lt;unistd.h&gt;\n\nFileDescriptor::FileDescriptor(int fd) : fd_{fd} {\n SystemErrorIf::condition(fd_ == -1);\n}\nFileDescriptor::FileDescriptor(const char path[], int oflag)\n : FileDescriptor{::open(path, oflag)} {}\n\nFileDescriptor::~FileDescriptor() {::close(fd_);}\n\nFileDescriptor::operator const int&amp;() const noexcept {return fd_;}\n</code></pre>\n<p>Slurp.cc</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &quot;Slurp.h&quot;\n#include &quot;SystemErrorIf.h&quot;\n\n#include &lt;fcntl.h&gt;\n#include &lt;sys/mman.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;unistd.h&gt;\n\n#include &lt;cstring&gt;\n\nSlurp::Slurp(Slurp &amp;&amp;other) noexcept {std::swap(b, other.b);}\n\nSlurp &amp;Slurp::operator=(Slurp &amp;&amp;rhs) noexcept {\n std::swap(b, rhs.b);\n return *this;\n}\n\nSlurp::Slurp(const FileDescriptor &amp;fd) {\n namespace ErrorIf = SystemErrorIf;\n\n ErrorIf::code(::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL));\n\n struct ::stat file_statistics;\n\n ErrorIf::condition(::fstat(fd, &amp;file_statistics));\n\n ::ssize_t fsize = file_statistics.st_size;\n\n const auto bufsize = static_cast&lt;std::size_t&gt;(fsize) + sizeof(char32_t),\n blksize = static_cast&lt;std::size_t&gt;(file_statistics.st_blksize);\n\n ErrorIf::code(::posix_memalign(&amp;b.begin, blksize, bufsize));\n\n ErrorIf::code(::posix_madvise(b.begin, bufsize, POSIX_MADV_SEQUENTIAL));\n\n b.end = b.begin;\n\n while (fsize &gt; 0) {\n const auto nread = ::read(\n fd, b.end, static_cast&lt;std::size_t&gt;(fsize));\n\n ErrorIf::condition(nread == -1);\n b.end = static_cast&lt;char*&gt;(b.end) + nread;\n fsize -= nread;\n }\n\n std::memset(b.end, 0, sizeof(char32_t)); // ensure null termination\n}\nSlurp::Slurp(const char path[]) : Slurp{FileDescriptor{path, O_RDONLY}} {}\nSlurp::Slurp(const std::string &amp;path) : Slurp{path.c_str()} {}\nSlurp::Slurp(const std::filesystem::path &amp;path) : Slurp{path.c_str()} {}\n\nSlurp::~Slurp() {std::free(b.begin);}\n\nconst char *Slurp::begin() const noexcept {return static_cast&lt;char*&gt;(b.begin);}\nconst char *Slurp::end() const noexcept {return static_cast&lt;char*&gt;(b.end);}\n\nstd::size_t Slurp::size() const noexcept {return end() - begin();}\n</code></pre>\n<hr />\n<p>indi, first of all, thank you for putting so much effort into your answer. Even if I don't agree with everything you said, I really appreciate the work you put in.</p>\n<blockquote>\n<p>The convention in C++ is to put all the type information together</p>\n</blockquote>\n<p>I don't think there's any particular &quot;convention&quot; in C++ (or C for that matter). It's my personal preference/style to put sigils (<code>*</code>, <code>&amp;</code>, <code>&amp;&amp;</code>) next to identifiers and not types.</p>\n<blockquote>\n<p>Rather than holding two pointers, it might make more sense to hold a pointer and a size.</p>\n</blockquote>\n<p>Again, this is more of a personal preference thing.</p>\n<blockquote>\n<p>I also don’t get why [the <code>begin_</code> and <code>end_</code> pointers] are <code>void*</code></p>\n</blockquote>\n<p>Two reasons, first because the file may have any or no character encoding, so <code>void*</code> is semantically appropriate (whereas <code>char*</code> implies ASCII-compatible text and <code>unsigned char*</code> or <code>std::byte*</code> imply an unstructured stream of binary data), and second because <code>posix_memalign(3)</code> (which, as you say, may be overkill) takes a <code>void**</code>, to which a <code>char**</code> would need to be <code>reinterpret_cast</code>, and I don't want to open up that whole can of worms.</p>\n<blockquote>\n<p>This [deleted default constructor] is technically unnecessary</p>\n</blockquote>\n<p>Good point.</p>\n<blockquote>\n<p>if your intention is to disable copying, then [the deleted copy constructor and copy assignment operator] are malformed.</p>\n</blockquote>\n<p>I don't believe so, but it's not worth looking into this just to save a few characters, so I'll write these your way from now on.</p>\n<blockquote>\n<p>you might consider making the type <em>movable.</em></p>\n</blockquote>\n<p>Done.</p>\n<blockquote>\n<p>Writing functions that <em>look</em> like they take arrays like this is a really bad idea.</p>\n</blockquote>\n<p>This is a low-level I/O routine, it's not written for beginners. While it does go back to a really bad language design decision on the part of the creators of C, I don't think you have to be an &quot;expert&quot; to know that <code>foo(const char bar[])</code> takes a pointer. I think it's more semantic to write <code>*bar</code> when <code>bar</code> points to a single object and <code>bar[]</code> when, as in this case, it points to an array.</p>\n<p>I am flattered you think I'm an expert! :)</p>\n<blockquote>\n<p>As a general rule, all constructors that take a single argument should be marked <code>explicit</code> (unless you have a damn good reason not to)</p>\n</blockquote>\n<p>I like <code>explicit</code> too but in this case I don't think there's any need for extra ceremony if a class has an <code>operator char*</code>/<code>const char*</code>.</p>\n<blockquote>\n<p>In addition to this constructor, it would help usability if you could use strings or—even better—<em>actual paths</em> with this class.</p>\n</blockquote>\n<p>Done, and part of what I intended to do anyway.</p>\n<blockquote>\n<p><code>gnu::const</code> on non-static member functions</p>\n</blockquote>\n<p>I don't think your interpretation of <code>gnu::const</code> is correct. The compiler knows when a new object has been created, even if it shares the same address as a previous object. But it's a moot point since as per your suggestion I made <code>Slurp</code> movable, and so removed <code>gnu::const</code> from its member functions.</p>\n<blockquote>\n<p>Never, ever [<code>using namespace std;</code>] at file scope. No, not even in a non-header file.</p>\n</blockquote>\n<p>Opinions on this differ, I don't think it's that big a deal in a non-header file, particularly a short one with few includes, but I'll remove it anyway.</p>\n<blockquote>\n<p>Avoid macros.</p>\n</blockquote>\n<p>I was targeting C++11 in the original question's code, and wanted to ensure these were inlined. Since I'm targeting C++20 in this code I can and have made them <code>constexpr</code> functions instead.</p>\n<blockquote>\n<p>But even that’s not really great, because it just obfuscates the function’s logic. I don’t see how it’s really an improvement</p>\n</blockquote>\n<p>I guess it's a bit of a Ruby-ism (Don't Repeat Yourself) that I tend to do in other languages also. When I see repeated logic I extract it to a function (or macro as the case may be).</p>\n<blockquote>\n<p>If you really don’t want all that ugly C-ish code, the right move is to properly wrap the API…</p>\n</blockquote>\n<p>Maybe, but I'd say that's out of scope for now.</p>\n<blockquote>\n<p>This is a <em>really</em> useful class! Rather than burying it as an implementation detail, it could be part of a public API.</p>\n</blockquote>\n<p>Done.</p>\n<blockquote>\n<p>You’d need to flesh it out a bit (and make it non-copyable, but perhaps movable)</p>\n</blockquote>\n<p>I don't think it makes sense for a file descriptor to be movable; a POSIX file descriptor is conceptually unique, immutable and identifies a single object which is opened and closed exactly once (per file descriptor).</p>\n<blockquote>\n<p>To make sure you get the right function, you should explicitly qualify it.</p>\n</blockquote>\n<p>Done, although IIRC the POSIX standard may allow for some of these functions to be implemented as macros, in which case this may lead to compilation errors on certain (hypothetical) platforms.</p>\n<blockquote>\n<p>The only thing I can figure is that you’re imagining that maybe someone might possibly want to <code>reinterpret_cast</code> the <code>char const*</code> to <code>char32_t const*</code>, and treat the data as a UTF-32 <code>NUL</code>-terminated string.</p>\n</blockquote>\n<p>Yes, that's what I'm intending.</p>\n<blockquote>\n<p>And it’s even odder when you consider that the <code>Slurp</code> class doesn’t even model a <code>NUL</code>-terminated string in any sense.</p>\n</blockquote>\n<p>It was intentionally bare-bones for explication purposes, as you can see it's more full-featured in my updated code.</p>\n<blockquote>\n<p>You are aligning the memory according to <code>file_statistics.st_blksize</code>… not <code>alignof(char32_t)</code>. In other words, if you’re thinking that you can just <code>reinterpret_cast</code> the result of <code>begin()</code> to a <code>char32_t const*</code> and treat it as a UTF-32 string… you may be in for a nasty surprise when your program crashes due to a a misaligned read.</p>\n</blockquote>\n<p>Well I'm assuming (perhaps strictly incorrectly) that <code>st_blksize</code> (512 on Linux) &gt; <code>alignof(char32_t)</code> (4), and I'm pretty sure any allocation function (<code>posix_memalign(3)</code> included) will always allocate memory that's at least suitably aligned for <code>std::max_align_t</code>.</p>\n<blockquote>\n<p>And all this is assuming the endianness of the UTF-32 data is correct.</p>\n</blockquote>\n<p>Probably something I should look into, though I haven't addressed it in the below code.</p>\n<blockquote>\n<p>if you want a regular string, why not read it directly into a <code>std::string</code>?</p>\n</blockquote>\n<p>Because it introduces overhead and I intend for this class to be as efficient as possible. It's trivial to construct a <code>std::string</code> (or <code>std::u32string</code>, <code>std::vector&lt;std::byte&gt;</code>, etc.) from it if desired.</p>\n<blockquote>\n<p>Honestly, I don’t see the point of [using <code>posix_memalign(3)</code>].</p>\n</blockquote>\n<p>You may be correct, I need to write some benchmarks to see what the performance of <code>posix_memalign(3)</code> is compared to <code>malloc(3)</code>.</p>\n<blockquote>\n<p>I <em>thought</em> <code>posix_madvise()</code> was only for memory-mapped memory.</p>\n</blockquote>\n<p>I don't think so? The man page says nothing about that. Again I should probably write a benchmark.</p>\n<blockquote>\n<p><code>read()</code> can fail spuriously for a number of reasons, like a signal interrupting it, and end up doing only a partial read. You can’t just write a <code>read()</code> call like this; you need to call it in a loop and keep doing reads until you’ve read <code>fsize</code> bytes in total</p>\n</blockquote>\n<p>Good point, and done.</p>\n<blockquote>\n<p>I mean… why not just <code>std::fill_n(end, 4, 0);</code>? It would probably be faster. (Unless your optimizer is smart enough to transform that <code>memcpy()</code> into a <code>memset()</code>, in which case it will probably be equally fast.)</p>\n</blockquote>\n<p>Good point re: <code>memset(3)</code>. In this (&quot;C with classes&quot;-ish) context I prefer it to <code>std::fill_n()</code>.</p>\n<blockquote>\n<p>Reading directly into containers</p>\n</blockquote>\n<p>I largely agree with you, but I'm not doing so for three reasons: 1) Part of the point of this exercise was to be as efficient as possible, and reading into a container creates overhead. 2) <code>Slurp</code> is supposed to model any possible character encoding (or lack thereof) that a file might have. 3) C++17 and C++20 eliminate much of the need for this (at least for newly-written APIs) with <code>std::basic_string_view</code> and <code>std::span</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T01:04:08.730", "Id": "260684", "ParentId": "260373", "Score": "0" } } ]
{ "AcceptedAnswerId": "260590", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T14:26:50.033", "Id": "260373", "Score": "3", "Tags": [ "c++", "linux", "io", "posix", "gcc" ], "Title": "Efficiently read a file into a (C) string using POSIX APIs" }
260373
<p>I've written a method that is going to set a bit array by passing bool parameters to be able send correct command</p> <pre><code>private byte _mode; public void SetConfiguration( bool mode1, bool mode2, bool mode3, bool mode4, bool mode5, bool mode6, bool mode7, bool mode8) { var setBits = new BitArray(8); setBits.Set(0, mode1); setBits.Set(1, mode2); setBits.Set(2, mode3); setBits.Set(3, mode4); setBits.Set(4, mode5); setBits.Set(5, mode6); setBits.Set(6, mode7); setBits.Set(7, mode8); byte[] byteSet = new byte[1]; setBits.CopyTo(byteSet, 0); _mode = byteSet[0]; } </code></pre> <p>So depending on what command the application is sending I am going to set it with boolean. What bothers me is that the method has too many bool parameters and I'm wondering if anyone have an idea how to write this in a better way</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T07:21:06.373", "Id": "514049", "Score": "0", "body": "Do you know that there is a `BitArray` [ctor](https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.-ctor#System_Collections_BitArray__ctor_System_Boolean___) which accepts `bool[]`?" } ]
[ { "body": "<p>You could use a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params\" rel=\"nofollow noreferrer\"><code>params</code> array</a> to pass the parameters</p>\n<pre><code>public void SetConfiguration(params bool[] modes)\n{\n var setBits = new BitArray(8);\n\n for (int i = 0; i &lt; modes.Length; i++)\n {\n setBits.Set(i, modes[i]);\n }\n\n byte[] byteSet = new byte[1];\n setBits.CopyTo(byteSet, 0);\n _mode = byteSet[0];\n}\n</code></pre>\n<p>You might want to add tests to ensure <code>modes</code> is not longer than 8 or you could expand the code to automatically set more than one byte in such cases. Shorter should be okay.</p>\n<p>You can call it with individual parameters or with a <code>bool</code> array.</p>\n<pre><code>SetConfiguration(false, true, true, false, true, true, true, false);\n\nvar modes = new bool[] {false, true, true, false, true, true, true, false};\nSetConfiguration(modes);\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T15:30:45.623", "Id": "514009", "Score": "0", "body": "What if `modes.Length` were different from 8?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T15:36:15.613", "Id": "514010", "Score": "1", "body": "This is why I suggested to add a test." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T15:04:45.417", "Id": "260376", "ParentId": "260374", "Score": "1" } }, { "body": "<p>I am going to expand upon @OlivierJacot-Descombes answer and offer an alternative. You do not have to limit yourself to a single method signature. And you do not have to use a <code>BitArray</code>. My answer is strictly offered as an alternative but I make no claim as to performance. But since the backing data storage to a <code>BitArray</code> is an internal <code>int[]</code>, much of the bit-twiddling I perform is also performed by <code>BitArray</code>.</p>\n<pre><code>public void SetConfiguration(bool mode1,\n bool mode2,\n bool mode3,\n bool mode4,\n bool mode5,\n bool mode6,\n bool mode7,\n bool mode8) \n =&gt; SetConfiguration(new bool[] { mode1, mode2, mode3, mode4, mode5, mode6, mode7, mode8 });\n\npublic static void SetConfiguration(params bool[] modes)\n{\n if (modes == null)\n {\n throw new ArgumentNullException(nameof(modes));\n }\n if (modes.Length != 8)\n {\n throw new ArgumentException($&quot;Array {nameof(modes)} must have a Length of 8.&quot;);\n }\n\n byte result = (byte)(modes[0] ? 1 : 0);\n\n for (int i = 1; i &lt; modes.Length; i++)\n {\n if (modes[i])\n {\n result += (byte)(2 &lt;&lt; (i - 1));\n }\n\n }\n\n _mode = result;\n}\n</code></pre>\n<p><strong>MORE THINGS TO CONSIDER</strong></p>\n<p><strong>ONE BIT AT A TIME</strong>\nIf you intend to sometimes fiddle with only a single flag or bit at a time, you may want to consider this method signature:</p>\n<pre><code>public void SetConfiguration(bool mode1 = false,\n bool mode2 = false,\n bool mode3 = false,\n bool mode4 = false,\n bool mode5 = false,\n bool mode6 = false,\n bool mode7 = false,\n bool mode8 = false) \n =&gt; SetConfiguration(new bool[] { mode1, mode2, mode3, mode4, mode5, mode6, mode7, mode8 });\n</code></pre>\n<p><strong>NAMING</strong>\nYour name choice of mode reflects the mode of configuration. I get that. But these methods are manipulating flags or bits, so the naming could be changed to reflect that with parameters of <code>flag1</code> or <code>bit1</code>. BUT I would also then suggest the parameter names should reflect 0-indexing. Thus, <code>flag0</code> or <code>bit0</code>.</p>\n<p><strong>RETURN INT</strong>\nThe <code>SetConfiguration</code> is a <code>void</code> but it sets a class level object named <code>_mode</code>. The bit-twiddling part could be a more generalized, static method that returns an <code>int</code>. This would make it reusable anywhere you want to twiddle with bits and return an integer. If you do this, then the method name would need to be changed since it no longer sets a value, but rather would get a value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T16:21:20.663", "Id": "260380", "ParentId": "260374", "Score": "0" } }, { "body": "<p>Consider making the settings more readable and strong-typed:</p>\n<pre><code>public enum Modes{\n Mode1 = 1,\n Mode2 = 2,\n Mode3 = 4,\n Mode4 = 8,\n}\n\npublic class Config\n{\n private Modes configVal;\n \n public void SetConfig(Modes modes){\n this.configVal = modes;\n }\n \n public bool AreAllSet(Modes modesAllSet)\n {\n return ((int)this.configVal &amp; (int)modesAllSet) == (int)modesAllSet;\n }\n\n public bool AreAnySet(Modes modesAllSet)\n {\n return ((int)this.configVal &amp; (int)modesAllSet) != 0;\n }\n\n}\n</code></pre>\n<p>Then you can use them like this:</p>\n<pre><code> var conf = new Config();\n conf.SetConfig(Modes.Mode1 | Modes.Mode2);\n\n Console.WriteLine(&quot;Mode 1: &quot; + conf.AreAllSet(Modes.Mode1));\n Console.WriteLine(&quot;Mode 2: &quot; + conf.AreAllSet(Modes.Mode2));\n Console.WriteLine(&quot;Mode 1+2: &quot; + conf.AreAllSet(Modes.Mode1 | Modes.Mode2));\n\n Console.WriteLine(&quot;Mode 3: &quot; + conf.AreAllSet(Modes.Mode3));\n Console.WriteLine(&quot;Mode 1+3: &quot; + conf.AreAllSet(Modes.Mode1 | Modes.Mode3));\n\n Console.WriteLine(&quot;Mode 1|3: &quot; + conf.AreAnySet(Modes.Mode1 | Modes.Mode3));\n</code></pre>\n<ul>\n<li>You still have the bit representation in the <code>configVal</code> field if it's needed</li>\n<li>You can choose which bit to set in a single parameter, no need to pass 8 of them to set one</li>\n<li>You could implement Set and Unset methods that modify the settings instead of replacing them: <code>configVal |= modes</code> to set or <code>configVal = (configVal | modes) ^ modes</code> to unset</li>\n<li>you could still implement bit array or bool methods for init, but your code for using the settings will be cleaner</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T20:30:20.430", "Id": "260433", "ParentId": "260374", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T14:55:02.193", "Id": "260374", "Score": "2", "Tags": [ "c#", ".net", "bitwise" ], "Title": "How to refactor a method with many prameters that sets a bit array" }
260374
<p>I've got this algorithm that's &quot;complex&quot;. The comments in code give examples of how large the various data types could be. My CPU usage is less than 10% when running this and RAM usage is good. No leakage or anything.</p> <p>I have a list of arrays, where each array is x coordinates. We are storing a list of several x coordinate-groups essentially. = <code>xs</code> in code.<br /> And I have the same thing but for y-values = <code>ys</code>.</p> <p>Each array in <code>xs</code> and <code>ys</code> are different sizes. HOWEVER, the size of <code>xs</code> and <code>ys</code> is always the same. So if an array in xs contains 321654 elements then there is a corresponding array in ys with exactly 321654 elements.</p> <p>The corresponding elements or &quot;paired&quot; <code>xs</code> and <code>ys</code> arrays are always at the same index in their corresponding list. So if xs_array[321654] is in <code>xs[4]</code> then ys_array[321654] is at <code>ys[4]</code>.</p> <p>The following code aims to get mean values, standard deviation and -1std and +1std from mean, as y coordinates from a collection of coordinates. It does this by taking the smallest arrays (the smallest set of x and y coordinates. It then looks at each array in <code>xs</code> and finds the index at which the x-coordinates are in the array. It then goes into <code>ys</code>, finds the corresponding <code>xs</code> array, and gets the y value from the x-coordinate. It goes through this, adds it all up. calculate, mean, std etc etc.</p> <pre><code> List&lt;Double[]&gt; xs; //each array may be be e.g 40000 elements. and the list contains 50 - 100 of those List&lt;Double[]&gt; ys; //a list containing arrays with an exact equal size as xs public void main_algorithm() { int TheSmallestArray = GetSmallestArray(xs); //get the smallest array out of xs and store the size in TheSmallestArray for (int i = 0; i &lt; TheSmallestArray; i++) { double The_X_at_element = The_Smallest_X_in_xs[i]; //store the value at the index i //go through each array find the element at which x_values is at. If it doesnt exist, find the closest element. List&lt;Double&gt; elements = new List&lt;double&gt;(); //create a new list of doubles for (int o = 0; o&lt;xs.Count(); o++) //go through each array in xs { //go through the array o and find the index at which the number or closest number of the_X_at_element is int nearestIndex = Array.IndexOf(xs[o], xs[o].OrderBy(number =&gt; Math.Abs(number - The_X_at_element)).First()); double The_Y_at_index = ys[o][nearestIndex]; //go through ys and get the value at this index elements.Add(The_Y_at_index); store the value in elements } mean_values.Add(elements.Mean()); //get the mean of all the values from ys taken standard_diviation_values.Add(elements.PopulationStandardDeviation());//get the mean of all the values from ys taken Std_MIN.Add(mean_values[i] - standard_diviation_values[i]); //store the mean - std and add to min Std_MAX.Add(mean_values[i] + standard_diviation_values[i]); //store the mean + std and add to max } } public int GetSmallestArray(List&lt;double[]&gt; arrays) { int TheSmallestArray = int.MaxValue; foreach(double[] ds in arrays) { if(ds.Length &lt; TheSmallestArray) { TheSmallestArray = ds.Length; //store the length as TheSmallestArray The_Smallest_X_in_xs = ds;//and the entirety of the array ds as TheSmallestArray_xs } } return TheSmallestArray; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T17:55:31.773", "Id": "514023", "Score": "0", "body": "Can the arrays be sorted prior to calling this code? Being able to do a binary search to find `nearestIndex` would improve performance" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:01:17.760", "Id": "534680", "Score": "0", "body": "There is a lot of context missing here: What significance is the shortest *xs* array? Does the order of elements in `mean_values`, Std_MIN`/`MAX` & `standard_diviation_values` (sic) matter (beyond values at the same index describing the same thing - quite redundantly), what are they used for?" } ]
[ { "body": "<p>The question does not contain an explicit specification of what the code is to achieve.<br />\nThe code presented for review suffers from that very problem - How can anyone tell what deviations are allowable?</p>\n<ul>\n<li>variable names are an odd mix of <em>PascalCase</em> and <em>snake_case</em></li>\n</ul>\n<p>Tactical:</p>\n<ul>\n<li>if <code>GetSmallestArray()</code> returned an array (the name suggests this), the length could be (re-) established without an enclosing-scope variable</li>\n<li>use an ordered clone <code>shortestX</code> of the smallest array(<code>xs</code>)\nand two arrays <code>noGreater</code> and <code>noSmaller</code> of same size</li>\n<li>for each array of x values<br />\n   initialise <code>noGreater</code> and <code>noSmaller</code> suitably<br />\n   find each value in <code>shortestX</code> (or the ones just below and/or above)<br />\n     and update <code>noGreater</code> and <code>noSmaller</code> accordingly<br />\n   for each value in <code>shortestX</code>, take the closer one from <code>noGreater</code><br />\n     and <code>noSmaller</code>, find and use its index in the current array</li>\n</ul>\n<p>Strategic:</p>\n<p><code>CPU usage is less than 10%</code> Guess: the computer showing this has many cores and uses few.<br />\nIf above change in algorithm does not improve run time to <em>good enough</em>,</p>\n<ul>\n<li>look for further improvements in data presentation and processing</li>\n<li>only then give concurrency more than a side-glance</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T20:03:52.820", "Id": "270681", "ParentId": "260375", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T14:58:53.613", "Id": "260375", "Score": "2", "Tags": [ "c#", "performance", "algorithm", ".net", "sorting" ], "Title": "How to make this algorithm faster. Calculates and searches through large arrays" }
260375
<p>I've recently found myself in need of several <code>numpy</code> functions in C++. I've decided to write my own header-only implementation of the <code>numpy.array</code>, including functions that I most commonly use in my projects. The biggest piece of advice I'm looking for is memory management. I create a lot of temporary arrays to swap axes among other numpy functions, and while I free the memory afterwards, I feel there's a better way to accomplish what I want.</p> <p>This is specifically compiled in <code>c++17</code> so I can use the <code>auto</code> keyword when unpacking elements from the tuple.</p> <p><strong>numpp.hpp</strong></p> <pre><code>/** * Num++ Header File. * @author Ben Antonellis **/ // https://numpy.org/doc/stable/reference/arrays.ndarray.html #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;tuple&gt; namespace numpp { enum datatype { int8, int16, int32, int64 }; enum op { add, sub, mul, div }; template &lt;class T&gt; class array { public: T** arr; int rows; int cols; numpp::datatype type; /** * Constructor for an numpp array. * * @param arr A two dimensional array of type T. * @param type A numpp datatype representing the data stored in the array. * * @return void. **/ template &lt;int rows, int cols&gt; array(T (&amp;arr)[rows][cols], const numpp::datatype&amp; type) { this-&gt;rows = rows; this-&gt;cols = cols; this-&gt;type = type; this-&gt;arr = new T*[this-&gt;rows * this-&gt;cols]; for (int i = 0; i &lt; this-&gt;rows; i++) { this-&gt;arr[i] = new T[this-&gt;cols]; } for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] = arr[i][j]; } } } array(const int&amp; width, const int&amp; height) { this-&gt;rows = width; this-&gt;cols = height; this-&gt;type = type; this-&gt;arr = new T*[this-&gt;rows * this-&gt;cols]; for (int i = 0; i &lt; this-&gt;rows; i++) { this-&gt;arr[i] = new T[this-&gt;cols]; } for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] = 0; } } } /** * Destructor. Remember to delete ALL information. **/ ~array() { for (int i = 0; i &lt; rows; i++) { delete this-&gt;arr[i]; } delete this-&gt;arr; } /** * Prints the entire numpp array to the console. **/ void print(void) const { for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { std::cout &lt;&lt; this-&gt;arr[i][j] &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; std::endl; } } // Memory Layout // /** * Returns a tuple of array dimensions. **/ std::tuple&lt;int, int&gt; shape(void) const { return {this-&gt;rows, this-&gt;cols}; } /** * Returns a tuple of bytes to step in each dimension when traversing the array. **/ std::tuple&lt;int, int&gt; strides(void) const { return { sizeof(this-&gt;arr[0][0]), sizeof(this-&gt;arr[0][0]) * this-&gt;rows }; } /** * Returns the number of array dimensions. **/ int ndim(void) const { return this-&gt;rows; } /** * Returns the number of elements in the array. **/ int size(void) const { return this-&gt;rows * this-&gt;cols; } /** * Returns the length of one array element in bytes. **/ int itemsize(void) const { return sizeof(this-&gt;arr[0][0]); } /** * Returns the total amount of bytes consumed by the elements of the array. **/ int nbytes(void) const { return sizeof(this-&gt;arr[0][0]) * this-&gt;size(); } // Array Conversion // /** * Copies an element of an array to a standard value and returns it. * * @param index N-th index of the two dimensional array. **/ int item(const int&amp; index) const { int pos = 0; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { if (pos == index) return this-&gt;arr[i][j]; pos++; } } return -1; } /** * Copies an element of an array to a standard scalar and returns it. * * @param x Row of array. * @param y Column of array. **/ int item(const int&amp; x, const int&amp; y) const { return this-&gt;arr[x][y]; } /** * Modifies the passed array as an n-dimension level deep nested list of values. * * @param destination Array to insert values into. **/ void tolist(T* destination[]) const { *destination = new T[this-&gt;size()]; for (int i = 0; i &lt; this-&gt;size(); i++) { (*destination)[i] = this-&gt;item(i); } } /** * Insert value into array at given index. * * @param index N-th index of array. * @param value Value to place at index. **/ void itemset(const int&amp; index, const T&amp; value) { int pos = 0; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { if (pos == index) { this-&gt;arr[i][j] = value; return; } pos++; } } } /** * Insert value into array at given index. * * @param x Row of array. * @param y Column of array. * @param value Value to place at [x][y] of array. **/ void itemset(const int&amp; x, const int&amp; y, const T&amp; value) { this-&gt;arr[x][y] = value; } /** * Returns a flattened representation of the array. * Default seperator is a space. **/ std::string tostring(void) const { return this-&gt;tostring(' '); } /** * Returns a flattened representation of the array, seperated by the passed character. * * @param seperator Character to seperate values. **/ std::string tostring(const char&amp; seperator) const { std::string str; for (int i = 0; i &lt; this-&gt;size(); i++) { str += std::to_string(this-&gt;item(i)) + seperator; } str.pop_back(); // Removes trailing seperator. return str; } /** * Writes the array to the given filepath. Each value will * be on its own line. * * @param filepath Path to file. **/ int tofile(const std::string&amp; filepath) const { return this-&gt;tofile(filepath, '\n'); } /** * Writes the array to the given filepath with values being seperated. * * @param filepath Path to file. * @param seperator Character to seperate values. **/ int tofile(const std::string&amp; filepath, const char&amp; seperator) const { std::ofstream file(filepath); file &lt;&lt; this-&gt;tostring(seperator); file.close(); return !file.is_open(); } /** * Fills the entire array with the passed value. * * @param value Value to fill array. **/ void fill(const T&amp; value) { for (int i = 0; i &lt; this-&gt;size(); i++) { this-&gt;itemset(i, value); } } // Shape Manipulation // /** * Returns an array containing the same data but with a new shape. * The x, y of the new array need to be convertable from the previous * array. * * @param x Width of new array. * @param y Height of new array. **/ array* reshape(const int&amp; x, const int&amp; y) { if (x * y != this-&gt;size()) throw &quot;(numpp::reshape) : x * y does not equal numpp array size!&quot;; array* destination = new array(x, y); T* thisTemp = new T[this-&gt;size()]; T* otherTemp = new T[destination-&gt;size()]; this-&gt;tolist(&amp;thisTemp); destination-&gt;tolist(&amp;otherTemp); for (int i = 0; i &lt; this-&gt;size(); i++) { otherTemp[i] = thisTemp[i]; } for (int i = 0; i &lt; this-&gt;size(); i++) { destination-&gt;itemset(i, otherTemp[i]); } delete[] thisTemp; delete[] otherTemp; return destination; } /** * Changes the shape and size of the array in-place. * * @param x Width of new array. * @param y Height of new array. **/ void resize(const int&amp; x, const int&amp; y) { if (x * y != this-&gt;size()) throw &quot;(numpp::reshape) : x * y does not equal numpp array size!&quot;; array* destination = new array(x, y); T* thisTemp = new T[this-&gt;size()]; T* otherTemp = new T[destination-&gt;size()]; this-&gt;tolist(&amp;thisTemp); destination-&gt;tolist(&amp;otherTemp); for (int i = 0; i &lt; this-&gt;size(); i++) { otherTemp[i] = thisTemp[i]; } for (int i = 0; i &lt; this-&gt;size(); i++) { destination-&gt;itemset(i, otherTemp[i]); } this-&gt;arr = destination-&gt;arr; this-&gt;rows = destination-&gt;rows; this-&gt;cols = destination-&gt;cols; this-&gt;type = destination-&gt;type; delete[] thisTemp; delete[] otherTemp; } // Item selection and manipulation // /** * Returns an array formed from the elements of the current array at the given indices. * * @param indices Array of indices to extrapolate data from. * @param count Number of indices. * @param results Where the elements will be stored. **/ void take(int* indices, const int&amp; count, T* results[]) { *results = new T[count]; for (int i = 0; i &lt; count; i++) { (*results)[i] = this-&gt;item(indices[i]); } } /** * Places the array of values at the array of indices in the current array. * * @param indices Array of indices. * @param values Array of values. * @param count Number of indices/values. **/ void put(int* indices, T* values, const int&amp; count) { for (int i = 0; i &lt; count; i++) { this-&gt;itemset(i, values[i]); } } /** * Modifies each value of the array by the value and operator passed. * * @param value Value to input. * @param op Addition, subtraction, multiplication, or divison **/ void modify(const T&amp; value, const numpp::op&amp; op) { for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { if (op == numpp::op::add) this-&gt;arr[i][j] += value; if (op == numpp::op::sub) this-&gt;arr[i][j] -= value; if (op == numpp::op::mul) this-&gt;arr[i][j] *= value; if (op == numpp::op::div) this-&gt;arr[i][j] /= value; } } } // Sorting Algorithm // (Insertion) /** * Performs the Insertion Sort algorithm on the numpp array. **/ void sort(void) { // Convert numpp array to one dimensional list T* temp = new T[this-&gt;size()]; this-&gt;tolist(&amp;temp); // Perform sorting algorithm int key, j; for (int i = 0; i &lt; this-&gt;size(); i++) { key = temp[i]; j = i - 1; while (j &gt;= 0 &amp;&amp; temp[j] &gt; key) { temp[j + 1] = temp[j]; j--; } temp[j + 1] = key; } // Replace numpp array values with new values int pos = 0; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] = temp[pos]; pos++; } } // Erase memory delete[] temp; } /** * Returns the indices where the elements are not zero. **/ int nonzero(int* temp[]) { // Get the count of non zero elements int count = 0; for (int i = 0; i &lt; this-&gt;size(); i++) { if (this-&gt;item(i) != 0) count++; } // Create array for storing elements *temp = new int[count]; // Loop again finding and adding these elements for (int i = 0; i &lt; this-&gt;size(); i++) { T val = this-&gt;item(i); if (val != 0) (*temp)[i] = val; } // Return number of non-zero elements return count; } // Calculation // /** * Returns the maximum value in the array. **/ T max(void) const { int value = INT32_MIN; for (int i = 0; i &lt; this-&gt;size(); i++) { T temp = this-&gt;item(i); if (temp &gt; value) value = temp; } return value; } /** * Returns the maximum value on the axis. * * @param axis Axis of array. **/ T max(const int&amp; axis) const { int value = INT32_MIN; for (int i = 0; i &lt; this-&gt;cols; i++) { T temp =this-&gt;arr[axis][i]; if (temp &gt; value) value = temp; } return value; } /** * Returns the minimum value in the array. **/ T min(void) const { int value = INT32_MAX; for (int i = 0; i &lt; this-&gt;size(); i++) { T temp = this-&gt;item(i); if (temp &lt; value) value = temp; } return value; } /** * Returns the minimum value on the axis. * * @param axis Axis of array. **/ T min(const int&amp; axis) const { int value = INT32_MAX; for (int i = 0; i &lt; this-&gt;cols; i++) { T temp = this-&gt;arr[axis][i]; if (temp &lt; value) value = temp; } return value; } /** * Returns the sum of all elements in the array. **/ T sum(void) const { int value = 0; for (int i = 0; i &lt; this-&gt;size(); i++) { value += this-&gt;item(i); } return value; } /** * Returns the sum of all elements on the axis. * * @param axis Axis of array. **/ T sum(const int&amp; axis) const { int value = 0; for (int i = 0; i &lt; this-&gt;cols; i++) { value += this-&gt;arr[axis][i]; } return value; } /** * Returns the mean value of all elements in the array. **/ T mean(void) const { return this-&gt;sum() / this-&gt;size(); } /** * Returns the mean value of all elements on the axis. * * @param axis Axis of array. **/ T mean(const int&amp; axis) const { return this-&gt;sum(axis) / this-&gt;cols; } /** * Returns true if all elements int the array are true. * For integer numpp arrays, this will determine if all the * values are non-zero. **/ bool all(void) const { for (int i = 0; i &lt; this-&gt;size(); i++) { if (!this-&gt;item(i)) return false; } return true; } /** * Returns true if all the elements on the axis are true. * For integer numpp arrays, this will determine if all the * values are non-zero. * * @param axis Axis of array. **/ bool all(const int&amp; axis) const { for (int i = 0; i &lt; this-&gt;cols; i++) { if (!this-&gt;arr[axis][i]) return false; } return true; } /** * Returns true if any of the elements in the array are true. * For integer numpp arrays, this will determine if any of the * values are non-zero. **/ bool any(void) const { for (int i = 0; i &lt; this-&gt;size(); i++) { if (this-&gt;item(i)) return true; } return false; } /** * Returns true if any of the elements on the axis are true. * For integer numpp arrays, this will determine if any of the * values are non-zero. * * @param axis Axis of array. **/ bool any(const int&amp; axis) const { for (int i = 0; i &lt; this-&gt;cols; i++) { if (this-&gt;arr[axis][i]) return true; } return false; } // Arithmetic, matrix multiplication, and comparison operators // bool operator&lt;(const array&amp; other) const { return this-&gt;size() &lt; other.size(); } bool operator&lt;=(const array&amp; other) const { return this-&gt;size() &lt;= other.size(); } bool operator&gt;(const array&amp; other) const { return this-&gt;size() &gt; other.size(); } bool operator&gt;=(const array&amp; other) const { return this-&gt;size() &gt;= other.size(); } bool operator==(const array&amp; other) const { return this-&gt;size() == other.size(); } bool operator!=(const array&amp; other) const { return this-&gt;size() != other.size(); } array* operator=(const array* other) { this-&gt;arr = other-&gt;arr; this-&gt;rows = other-&gt;rows; this-&gt;cols = other-&gt;cols; this-&gt;type = other-&gt;type; return this; } array* operator+(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] += other-&gt;arr[i][j]; } } return this; } array* operator-(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] -= other-&gt;arr[i][j]; } } return this; } array* operator*(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] *= other-&gt;arr[i][j]; } } return this; } array* operator/(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] /= other-&gt;arr[i][j]; } } return this; } array* operator+=(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] += other-&gt;arr[i][j]; } } return this; } array* operator-=(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] -= other-&gt;arr[i][j]; } } return this; } array* operator*=(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] *= other-&gt;arr[i][j]; } } return this; } array* operator/=(const array* other) { if (this != other) return NULL; for (int i = 0; i &lt; this-&gt;rows; i++) { for (int j = 0; j &lt; this-&gt;cols; j++) { this-&gt;arr[i][j] /= other-&gt;arr[i][j]; } } return this; } }; } </code></pre> <p>And here's a test file, <code>main.cpp</code></p> <pre><code>#include &quot;numpp.hpp&quot; int main() { int x[3][4] = { {0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11} }; numpp::array&lt;int&gt; arr(x, numpp::int32); arr.print(); const auto [width, height] = arr.shape(); std::cout &lt;&lt; &quot;Width: &quot; &lt;&lt; width &lt;&lt; &quot; Height: &quot; &lt;&lt; height &lt;&lt; std::endl; const auto [indexStep, rowStep] = arr.strides(); std::cout &lt;&lt; &quot;Index Step: &quot; &lt;&lt; indexStep &lt;&lt; &quot; Row Step: &quot; &lt;&lt; rowStep &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Array Dimensions: &quot; &lt;&lt; arr.ndim() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Array Size: &quot; &lt;&lt; arr.size() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Item Size: &quot; &lt;&lt; arr.itemsize() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Number of bytes: &quot; &lt;&lt; arr.nbytes() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Item at index 5: &quot; &lt;&lt; arr.item(5) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Item at index [2][3]: &quot; &lt;&lt; arr.item(2, 3) &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T16:19:45.367", "Id": "514016", "Score": "2", "body": "From a quick look, you're badly mishandling memory and leaking a lot of it. You also have mismatched `new[]` vs `delete` usage (`new[]` needs to use `delete[]`). These should be addressed, and more extensive test code added. As it is, it will be unnaturally difficult to use your arithmetic operators (which should use references, not pointers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T15:51:24.700", "Id": "514076", "Score": "0", "body": "Here is something I cobbled with. Take a look if you're interested. https://github.com/frozenca/Ndim-Matrix" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T16:01:09.060", "Id": "260378", "Score": "3", "Tags": [ "c++", "c++17" ], "Title": "Num++: A numpy implementation written in C++" }
260378
<p>I am trying to solve <a href="https://www.interviewbit.com/problems/stringoholics/" rel="nofollow noreferrer">https://www.interviewbit.com/problems/stringoholics/</a> InterviewBit problem.</p> <p><strong>Problem Statement:</strong></p> <blockquote> <p>You are given an array A consisting of strings made up of the letters ‘a’ and ‘b’ only. Each string goes through a number of operations, where:</p> <ol> <li>At time 1, you circularly rotate each string by 1 letter.</li> <li>At time 2, you circularly rotate the new rotated strings by 2 letters.</li> <li>At time 3, you circularly rotate the new rotated strings by 3 letters.</li> <li>At time i, you circularly rotate the new rotated strings by i % length(string) letters.</li> </ol> <p>Eg: String is &quot;abaa&quot;</p> <ol> <li>At time 1, string is &quot;baaa&quot;, as 1 letter is circularly rotated to the back</li> <li>At time 2, string is &quot;aaba&quot;, as 2 letters of the string &quot;baaa&quot; is circularly rotated to the back</li> <li>At time 3, string is &quot;aaab&quot;, as 3 letters of the string &quot;aaba&quot; is circularly rotated to the back</li> <li>At time 4, string is again &quot;aaab&quot;, as 4 letters of the string &quot;aaab&quot; is circularly rotated to the back</li> <li>At time 5, string is &quot;aaba&quot;, as 1 letters of the string &quot;aaab&quot; is circularly rotated to the back</li> </ol> <p>After some units of time, a string becomes equal to it’s original self. Once a string becomes equal to itself, it’s letters start to rotate from the first letter again (process resets). So, if a string takes t time to get back to the original, at time t+1 one letter will be rotated and the string will be it’s original self at 2t time. You have to find the minimum time, where maximum number of strings are equal to their original self. As this time can be very large, give the answer modulo 10<sup>9</sup>+7.</p> <p>Note: Your solution will run on multiple test cases so do clear global variables after using them.</p> <p>Input:</p> <p>A: Array of strings. Output:</p> <p>Minimum time, where maximum number of strings are equal to their original self. Constraints:</p> <p>1 &lt;= size(A) &lt;= 10^5 1 &lt;= size of each string in A &lt;= 10^5 Each string consists of only characters 'a' and 'b' Summation of length of all strings &lt;= 10^7</p> </blockquote> <p><strong>But I got Time Limit Exceed Error.</strong></p> <p>I followed the below approach:</p> <blockquote> <p>With respect to a single string, the total number of bits rotated after N operations is 1+2+3+….+N which is (N*(N+1))/2. We get back the original string only when the total number of rotated bits is a multiple of the length of the string S(LEN).</p> <p>This can be done in O(N) time for each string (Summation of length of all strings is &lt;= 1e6), by finding all (N(N+1))/2 where N starts from 1 and goes upto (2LEN-1).</p> <p>But there is a catch, this wont always give you the minimum number of operations. Its possible that during rotation, you can get the original string before the number of bits rotated is a multiple of LEN.</p> <p>Example: S=&gt; 100100 Here, in 2 operations, we get the original string back. This takes place because the string is made up of recurring substrings.</p> <p>Assume string A to be 100 S =&gt; AA Hence, over here our length S of string is the length of recurring substring A, so N*(N+1)/2 should be a multiple of length of A.</p> <p>Length of recurring substring can easily be found out using KMP algorithm in O(N) time complexity for each string.</p> <p>Find the minimum number of operations for each string, and take the LCM of all these values to get the answer.</p> </blockquote> <p>My Solution:</p> <pre><code>#define MOD 1000000007 int findSmallestString(string A) { int n = A.length(); vector&lt;int&gt; lps(n + 1, 0); int index = 0, i = 1; while(i &lt; n) { if(A[index] == A[i]) { lps[i] = index + 1; index++; i++; } else { if(index != 0) { index = lps[index - 1]; } else { lps[i] = 0; i++; } } } int t1 = lps[n - 1]; int t2 = n - t1; if(t1 &lt; t2 || (t1 % t2 != 0)) return n; return t2; } int Solution::solve(vector&lt;string&gt; &amp;A) { int n = A.size(); vector&lt;int&gt; v(n); for(int i = 0; i &lt; n; i++) { long long len = findSmallestString(A[i]); long long k = 1; while(1) { long long rotates = (k * (k + 1)) / 2; if(rotates % len == 0) { v[i] = k; break; } k++; } } long long ans = 1ll; for(int i = 0; i &lt; n; i++) { for(int j = i + 1; j &lt; n &amp;&amp; v[i] != 1; j++) { v[j] = v[j] / __gcd(v[i], v[j]); } ans = ((ans % MOD) * (v[i] % MOD)) % MOD; } return ans; } </code></pre> <p>Is there any way to optimize the solution?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T14:50:08.423", "Id": "514071", "Score": "0", "body": "Please include the text of the code challenge in the question, links can break." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T20:42:15.410", "Id": "518718", "Score": "0", "body": "\"its\" not \"it's\" in \"it’s original self\". \"it's\" is a contraction for \"it is\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T05:02:26.723", "Id": "518741", "Score": "0", "body": "@JDlugosz while that [is the case](https://english.stackexchange.com/q/13148/213844) the OP was merely quoting [the source of the challenge](https://www.interviewbit.com/problems/stringoholics/). Perhaps it would be more constructive to contact that organization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T13:44:32.153", "Id": "518769", "Score": "0", "body": "It would be proper to insert [\"[sic]\"](https://www.merriam-webster.com/dictionary/sic) in the quoted passage." } ]
[ { "body": "<pre><code>#define MOD 1000000007\n</code></pre>\n<p>Don't use <code>#define</code>. This should be</p>\n<pre><code>constexpr int MOD = 1000000007;\n</code></pre>\n<p>(and this is assuming that ints are big enough to hold that value!)</p>\n<pre><code>int findSmallestString(string A)\n</code></pre>\n<p>Why are you passing <code>A</code> by value, duplicating the string? Write <code>const string&amp;</code> as a matter of course; but use <code>string_view</code> for parameters when that makes sense.</p>\n<pre><code>int n = A.length();\n</code></pre>\n<p>You mean <code>size_t</code>, not <code>int</code>. Is this going to change? I think it should not; you should write</p>\n<pre><code>const auto n = A.length();\n</code></pre>\n<hr />\n<p>Later, you call it as</p>\n<pre><code>long long len = findSmallestString(A[i]);\n</code></pre>\n<p>So is it <code>int</code> or <code>long long</code>? Again, I don't think you are modifying <code>len</code> after this so why isn't it <code>const</code>?</p>\n<hr />\n<p>You seem to be missing all the <code>#include</code> statements, and maybe others, so this won't compile as-posted. Please post complete examples.</p>\n<p>Where does <code>__gcd</code> come from? That is a reserved name, so I suppose some non-standard built-in.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T22:38:51.970", "Id": "260440", "ParentId": "260383", "Score": "-1" } }, { "body": "<h3>As you got TLA, you (probably) need a better algorithm:</h3>\n<ol>\n<li><p>Map from the strings to their periods.</p>\n</li>\n<li><p>Remove duplicates.</p>\n</li>\n<li><p>Map from string-periods to transformation-periods modulo 10<sup>9</sup> + 7.</p>\n</li>\n<li><p>Determine LCM over them modulo 10<sup>9</sup> + 7.</p>\n</li>\n</ol>\n<h3>Regarding implementation efficiency:</h3>\n<p>You allocate memory everywhere, for <code>std::string</code> and <code>std::vector</code>. Both are expensive, and also superfluous.</p>\n<p>For functions expecting a string, see whether <code>std::string_view</code> will fit the deal. If it does it will even beat <code>std::string const&amp;</code>.</p>\n<h3>Regarding standard conformance:</h3>\n<p><code>__gcd()</code> is an implementation detail of your implementation. Just use <code>std::gcd()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T22:00:19.547", "Id": "260473", "ParentId": "260383", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T16:49:37.550", "Id": "260383", "Score": "0", "Tags": [ "c++", "programming-challenge", "strings", "interview-questions" ], "Title": "InterviewBit Problem: Stringoholics" }
260383
<p>The problem is to ask the user to guess a number between 1 to 100 and compare it with a random number of that range. If user guessed number is lesser/greater than the random number print &quot;too low&quot; or &quot;too high&quot; accordingly. Take new input asking the user to guess the correct number again. When the guessed number matches with the random number print &quot;you win&quot; and the number of attempts the user required to guess it.</p> <pre><code>import random u_num = int(input(&quot;guess a number between 1 to 100: &quot;)) w_num = random.randint(1,100) i = 1 while u_num != w_num: if u_num &lt; w_num: print(&quot;too low&quot;) else: print(&quot;too high&quot;) u_num = int(input(&quot;guess again: &quot;)) i += 1 print(f&quot;you win, and you guessed this number in {i} times!&quot;) </code></pre>
[]
[ { "body": "<p>This looks to do the job. I would only change the variable naming to be more meaningful in this context to guess for user guess and answer for the generated number.</p>\n<p>I would also try to handle erroneous input such as strings instead of numbers being passed.</p>\n<p>But besides this is still functionally good :D</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T18:50:48.560", "Id": "260389", "ParentId": "260385", "Score": "3" } }, { "body": "<p>Your variable names are a little impenetrable - best to use whole words.</p>\n<p>Consider adding input validation as a next step to enhancing this program's functionality - what if a user guesses &quot;banana&quot;?</p>\n<p>Pythonic code generally discourages the maintenance of your own loop variables (<code>i</code>). I would move your termination condition into the loop body - where you're already checking the guess anyway - and count in your loop declaration.</p>\n<p>This example code does the above, minus input validation:</p>\n<pre><code>import random\nfrom itertools import count\n\nguess = int(input(&quot;Guess a number between 1 to 100: &quot;))\nsecret = random.randint(1, 100)\n\nfor guesses in count(1):\n if guess &lt; secret:\n print(&quot;Too low&quot;)\n elif guess &gt; secret:\n print(&quot;Too high&quot;)\n else:\n break\n\n guess = int(input(&quot;Guess again: &quot;))\n\nprint(f&quot;You win, and you guessed this number in {guesses} times!&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T10:20:25.903", "Id": "260410", "ParentId": "260385", "Score": "2" } } ]
{ "AcceptedAnswerId": "260410", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T17:14:30.343", "Id": "260385", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "number-guessing-game" ], "Title": "Simple number guessing game in python" }
260385
<p>I have been reading through the rust book. I have made it to chapter 13, at the end of the section called (<a href="https://doc.rust-lang.org/stable/book/ch13-01-closures.html#storing-closures-using-generic-parameters-and-the-fn-traits" rel="nofollow noreferrer">Storing Closures Using Generic Parameters and the Fn Traits</a>) a couple of improvements are described and left as kind of an exercise.</p> <p>The task at hand is to change the cache implementation to support not only u32 but any data type and also allow the results to be stored in a hashmap thus allowing us to memoize multiple queries.</p> <p>I went the route of the everything is copied (since I tried to avoid lifetimes for my first implementation) and I just wanted the feedback from more experienced people on how they would tackle and what pitfall does this version I wrote have.</p> <pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap; use std::cmp::Eq; use std::hash::Hash; struct Cacher&lt;I, O, T&gt; where T: Fn(I) -&gt; O, { calc: T, cache: HashMap&lt;I, O&gt; } impl&lt;I: Eq + Hash + Copy, O, T&gt; Cacher&lt;I, O, T&gt; where T: Fn(I) -&gt; O { fn new(calc: T) -&gt; Cacher&lt;I, O, T&gt; { Cacher { calc, cache: HashMap::new() } } fn get(&amp;mut self, n: &amp;I) -&gt; &amp;O { self.cache.entry(*n).or_insert((self.calc)(*n)) } } fn main() { let mut workout = Cacher::new(|x| x + 1); println!(&quot;{}&quot;, workout.get(&amp;4)); println!(&quot;{}&quot;, workout.get(&amp;5)); println!(&quot;{}&quot;, workout.get(&amp;3)); println!(&quot;{}&quot;, workout.get(&amp;4)); } </code></pre> <p>Another question is where trait are necessary in this case, I realized the compiler doesn't complain if I only put them in the implementation block (but wondered why doesn't it think they are required at the level of the struct since Generic type I has to be both Hashable and Comparable when creating the hashmap right ?)</p>
[]
[ { "body": "<p>Even though I'm relatively new to Rust myself, I'll give this a shot since no one else has responded so far.</p>\n<h2>Is <code>Cacher</code> caching?</h2>\n<p>Let's test that <code>Cacher</code> is working as intended (wouldn't call <code>calc</code> on the same value twice) by adding a log:</p>\n<pre><code>// --snip--\nlet mut workout = Cacher::new(|x| {\n println!(&quot;calc {}&quot;, x);\n x + 1\n});\n// --snip--\n</code></pre>\n<p>The output is:</p>\n<pre><code>calc 4\n5\ncalc 5\n6\ncalc 3\n4\ncalc 4\n5\n</code></pre>\n<p>Why is <code>calc</code> called twice on <code>4</code>? Let's check the implementation of <code>Cacher::get</code>:</p>\n<pre><code>fn get(&amp;mut self, n: &amp;I) -&gt; &amp;O {\n self.cache.entry(*n).or_insert((self.calc)(*n))\n}\n</code></pre>\n<p>The problem is that the expression <code>(self.calc)(*n)</code> is evaluated and the result value given to <code>or_insert</code> whenever <code>Cacher::get</code> is called, even though the result is discarded if the key <code>*n</code> already exists in the hashmap. This can be fixed by using <code>or_insert_with</code>:</p>\n<pre><code>fn get(&amp;mut self, n: &amp;I) -&gt; &amp;O {\n let calc = &amp;self.calc;\n self.cache.entry(*n).or_insert_with(|| calc(*n))\n}\n</code></pre>\n<p>Now the output is as expected:</p>\n<pre><code>calc 4\n5\ncalc 5\n6\ncalc 3\n4\n5\n</code></pre>\n<p>NB: The borrow checker wouldn't let us simply write <code>|| (self.calc)(*n)</code>. The reason is <code>self.cache</code> is borrowed mutably within <code>Cacher::get</code>, and <em>the whole</em> <code>self</code> (implying <code>self.cache</code>) would be borrowed within the closure. That would violate the rule that a mutable borrow is exclusive. We circumvent this by explicitly splitting the borrow outside of the closure. The closure then captures only <code>calc</code>.</p>\n<p>Some links to read up on this:</p>\n<ul>\n<li><a href=\"https://doc.rust-lang.org/nomicon/borrow-splitting.html\" rel=\"noreferrer\">https://doc.rust-lang.org/nomicon/borrow-splitting.html</a></li>\n<li><a href=\"https://stackoverflow.com/questions/61699010/rust-not-allowing-mutable-borrow-when-splitting-properly\">https://stackoverflow.com/questions/61699010/rust-not-allowing-mutable-borrow-when-splitting-properly</a></li>\n<li><a href=\"https://www.reddit.com/r/rust/comments/cufiq7/rust_mutably_borrows_the_whole_struct_even_though/\" rel=\"noreferrer\">https://www.reddit.com/r/rust/comments/cufiq7/rust_mutably_borrows_the_whole_struct_even_though/</a></li>\n</ul>\n<h2>Trait Bounds</h2>\n<p>Let's get to your question on trait bounds. First off, it does make a real difference where we put them:</p>\n<ul>\n<li><p>When the trait bounds are on the <code>struct</code>, then the compiler will not let us instantiate the generic without satisfying the trait bounds, <em>at all</em>.</p>\n</li>\n<li><p>When the trait bounds are on the <code>impl</code> block, then we are allowed to instantiate the generic with types that do not satisfy the trait bounds, but the methods defined in the <code>impl</code> block will be available only to instances where the trait bounds are satisfied.</p>\n</li>\n</ul>\n<p>In fact, if you have a look at <a href=\"https://doc.rust-lang.org/src/std/collections/hash/map.rs.html\" rel=\"noreferrer\">the implementation of <code>HashMap</code></a>, you'll notice that <code>HashMap</code> has trait bounds only on <code>impl</code> blocks for particular sets of methods that require the respective traits. Thus we may create, but not insert into, a HashMap whose key type doesn't satisfy <code>Eq + Hash</code>:</p>\n<pre><code>// This is alright:\nstruct X {}\nlet mut map = HashMap::&lt;X, u32&gt;::new();\n\n// This won't compile:\nmap.insert(X {}, 1);\n</code></pre>\n<p>This being a factual difference, what <em>should</em> we do here? A question on StackOverflow has some interesting answers discussing this question: <a href=\"https://stackoverflow.com/questions/49229332/should-trait-bounds-be-duplicated-in-struct-and-impl\">https://stackoverflow.com/questions/49229332/should-trait-bounds-be-duplicated-in-struct-and-impl</a>. In this case, I'd probably stick with <code>HashMap</code>'s approach and be as specific as possible (see code below).</p>\n<h2>A Note on Tooling</h2>\n<p>Rust's ecosystem brings some nice tools. <a href=\"https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html#more-lints-with-clippy\" rel=\"noreferrer\">Clippy</a> is a linter that does, in fact, hint at the aforementioned bug:</p>\n<pre><code>$ cargo clippy\nwarning: use of `or_insert` followed by a function call\n --&gt; src/main.rs:26:30\n |\n26 | self.cache.entry(*n).or_insert((self.calc)(*n))\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(|| (self.calc)(*n))`\n |\n = note: `#[warn(clippy::or_fun_call)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call\n</code></pre>\n<p>Also, there's <code>cargo fmt</code> to enforce a standard code style. In this case, it sorts the imports, adds a trailing comma in the struct and removes a duplicated blank line.</p>\n<h2>Final Code</h2>\n<p>Here's the code I ended up with, including some further remarks:</p>\n<pre><code>use std::cmp::Eq;\nuse std::collections::HashMap;\nuse std::hash::Hash;\n\n// We may even leave out the trait bound for `T`\n// (Example: Perhaps at some point you want to add another implementation\n// where calculation isn't done via a closure/function,\n// but via some special object. This is general enough to allow that.)\nstruct Cacher&lt;I, O, T&gt; {\n calc: T,\n cache: HashMap&lt;I, O&gt;,\n}\n\n// Here I'm splitting into two `impl` blocks.\n// A `Cacher` may be created without knowing anything about the types.\nimpl&lt;I, O, T&gt; Cacher&lt;I, O, T&gt; {\n fn new(calc: T) -&gt; Cacher&lt;I, O, T&gt; {\n Cacher {\n calc,\n cache: HashMap::new(),\n }\n }\n}\n\n// Now that the hashmap is used, and `calc` is used,\n// the trait bounds are indeed required\nimpl&lt;I, O, T&gt; Cacher&lt;I, O, T&gt;\nwhere\n // For clarity and consistency, I put all trait bounds into the where block\n I: Eq + Hash + Copy,\n T: Fn(I) -&gt; O,\n{\n fn get(&amp;mut self, n: &amp;I) -&gt; &amp;O {\n let calc = &amp;self.calc;\n self.cache.entry(*n).or_insert_with(|| calc(*n))\n }\n}\n\nfn main() {\n let mut workout = Cacher::new(|x| x + 1);\n println!(&quot;{}&quot;, workout.get(&amp;4));\n println!(&quot;{}&quot;, workout.get(&amp;5));\n println!(&quot;{}&quot;, workout.get(&amp;3));\n println!(&quot;{}&quot;, workout.get(&amp;4));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T15:48:15.710", "Id": "514337", "Score": "1", "body": "This is such a thorough answer. I just wanted to say thank you for this. I have learned tons from it. I didn't know about clippy so thanks so much about that tooo. Cheers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T16:06:21.297", "Id": "514340", "Score": "2", "body": "I also uploaded it as a crate since I was learning of doing so with a couple of updates. Check the repo if you would like https://crates.io/crates/closure_cacher" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T13:28:48.533", "Id": "260557", "ParentId": "260386", "Score": "5" } } ]
{ "AcceptedAnswerId": "260557", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T17:25:58.683", "Id": "260386", "Score": "4", "Tags": [ "rust" ], "Title": "Rust Book Ch 13 Closures with Generic Parameters and HashMap for memoization" }
260386
<h1>Quadratic Probing Hash Map</h1> <p>Looking to improve my quadratic probing hash map. Here are some design considerations and questions.</p> <ul> <li><p>Implementation is made such that the hashing function, probing function and load_factor can be changed. Changing them can be done by switching macros in the header for example or just assigning different values to the struct. I'm considering writing functions for several common quadratic ones and linear and then assign the method with a macro upon creating the map. Good idea?</p> </li> <li><p>Is there a clever way to stress test my implementation taking into account any eventualities? That no combination of deleting, adding etc. results in an infinite loop?</p> </li> <li><p>What would be a relevant comparison for testing the speed?</p> </li> <li><p>What would be a set of functions that you would consider fully featured for a hash map implementation with an emphasis on simplicity and ease of use?</p> </li> <li><p>Anything else I have missed?</p> </li> </ul> <p>The implementation is part of a library I'm creating partly as a school project and educational project, but with the intention to make it solid enough for real use. Note that functions in the library might slightly differ from the example since I made the example so that it compiles independently.</p> <p><a href="https://github.com/juliuskoskela/core" rel="nofollow noreferrer">https://github.com/juliuskoskela/core</a></p> <h1>Code</h1> <p>Compilation:</p> <pre><code>gcc -fsanitize=address -Wall -Wextra -Werror -Wpedantic -Wtype-limits -Wunreachable-code -Wpadded -Wshadow map.c -lm -o map_test </code></pre> <p>Source code.</p> <pre class="lang-c prettyprint-override"><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;stdint.h&gt; #include &lt;math.h&gt; #include &lt;string.h&gt; # define MAP_START_CAPACITY 4 # define MAP_LOAD_FACTOR 0.4 # define MAP_HASH map_hash_1 # define MAP_PROBE map_probe_quad_pow2 # define MAP_RESIZE map_resize_pow2 # define MAP_NULL_NODE (t_map_node) {NULL, NULL} # define MAP_NULL (t_map) {NULL, 0, 0, 0.0, NULL, NULL, NULL} typedef struct s_map_node { const char *key; void *data; } t_map_node; typedef struct s_map { t_map_node *node; size_t capacity; size_t count; double load_factor; uint64_t (*hash)(const char *); uint64_t (*probe)(uint64_t); uint64_t (*resize)(uint64_t); } t_map; // Swappable functions uint64_t map_hash_1(const char *key) { uint64_t hash; uint64_t i; uint64_t len; len = strlen(key); hash = 0; i = 0; while (i &lt; len) { hash += key[i]; hash += (hash &lt;&lt; 10); hash ^= (hash &gt;&gt; 6); i++; } hash += (hash &lt;&lt; 3); hash ^= (hash &gt;&gt; 11); hash += (hash &lt;&lt; 15); return (hash); } uint64_t map_probe_quad_pow2(uint64_t x) { return ((pow(x, 2) + x) / 2); } uint64_t map_resize_pow2(uint64_t capacity) { return (pow(2, ceil(log(capacity) / log(2)))); } // Implementation ssize_t map_null_node(t_map_node *n) { if (memcmp(n, &amp;MAP_NULL_NODE, sizeof(t_map_node))) return (0); return (1); } static ssize_t map_grow_add(t_map *dst, void *src, const char *key) { uint64_t hash_key; t_map_node new_node; uint64_t probe; size_t i; new_node.data = src; new_node.key = key; hash_key = dst-&gt;hash(key); probe = 0; i = 0; while (!map_null_node(&amp;dst-&gt;node[(hash_key + probe) % dst-&gt;capacity])) { probe = dst-&gt;probe(i); i++; } dst-&gt;node[(hash_key + probe) % dst-&gt;capacity] = new_node; dst-&gt;count++; return (1); } ssize_t map_grow(t_map *src) { t_map new; size_t i; new.capacity = src-&gt;resize(src-&gt;capacity + 1); new.count = 0; new.hash = src-&gt;hash; new.load_factor = src-&gt;load_factor; new.probe = src-&gt;probe; new.resize = src-&gt;resize; new.node = (t_map_node *)malloc(sizeof(t_map_node) * new.capacity); if (!new.node) return (-1); i = 0; while (i &lt; src-&gt;capacity) { if (!map_null_node(&amp;src-&gt;node[i])) map_grow_add(&amp;new, src-&gt;node[i].data, src-&gt;node[i].key); i++; } free(src-&gt;node); *src = new; return (1); } t_map map_new(void) { t_map m; size_t i; m.capacity = MAP_START_CAPACITY; m.load_factor = MAP_LOAD_FACTOR; m.hash = MAP_HASH; m.probe = MAP_PROBE; m.resize = MAP_RESIZE; m.node = (t_map_node *)malloc(sizeof(t_map_node) * m.capacity); if (!m.node) return (MAP_NULL); i = 0; while (i &lt; m.capacity) { m.node[i] = MAP_NULL_NODE; i++; } m.count = 0; return (m); } ssize_t map_add(t_map *dst, void *val, const char *key) { uint64_t hash_key; double treshold; t_map_node new_node; uint64_t probe; size_t i; new_node.data = val; new_node.key = key; treshold = dst-&gt;load_factor * (double)dst-&gt;capacity - 1; if (dst-&gt;count &gt;= (uint64_t)treshold) map_grow(dst); hash_key = dst-&gt;hash(key); probe = 0; i = 0; while (!map_null_node(&amp;dst-&gt;node[(hash_key + probe) % dst-&gt;capacity])) { if (strcmp(dst-&gt;node-&gt;key, key) == 0) return (0); probe = dst-&gt;probe(i); i++; } dst-&gt;node[(hash_key + probe) % dst-&gt;capacity] = new_node; dst-&gt;count++; return (1); } void *map_get(t_map *src, const char *key) { uint64_t hash_key; uint64_t probe; size_t i; hash_key = src-&gt;hash(key); probe = 0; i = 0; while (i &lt; src-&gt;count) { if (src-&gt;node[(hash_key + probe) % src-&gt;capacity].key &amp;&amp; strcmp(src-&gt;node[(hash_key + probe) % src-&gt;capacity].key, key) == 0) return (src-&gt;node[(hash_key + probe) % src-&gt;capacity].data); probe = src-&gt;probe(i); i++; } return (NULL); } ssize_t map_del(t_map *src, const char *key) { uint64_t hash_key; uint64_t probe; size_t i; hash_key = src-&gt;hash(key); probe = 0; i = 0; while (i &lt; src-&gt;count) { if (src-&gt;node[(hash_key + probe) % src-&gt;capacity].key &amp;&amp; strcmp(src-&gt;node[(hash_key + probe) % src-&gt;capacity].key, key) == 0) { src-&gt;node[(hash_key + probe) % src-&gt;capacity] = MAP_NULL_NODE; return (i); } probe = src-&gt;probe(i); i++; } return (0); } void map_print(t_map *m) { size_t i; i = 0; while (i &lt; m-&gt;capacity) { if (map_null_node(&amp;m-&gt;node[i])) printf(&quot;[EMPTY]\n&quot;); else printf(&quot;%s\n&quot;, m-&gt;node[i].key); i++; } } int main(void) { t_map m; char *course; m = map_new(); course = NULL; map_add(&amp;m, &quot;Quantum Physics 1&quot;, &quot;qp01&quot;); map_add(&amp;m, &quot;Quantum Physics 2&quot;, &quot;qp02&quot;); map_add(&amp;m, &quot;Computer Science 1&quot;, &quot;cs01&quot;); map_add(&amp;m, &quot;Computer Science 2&quot;, &quot;cs02&quot;); map_add(&amp;m, &quot;Computer Science 3&quot;, &quot;cs03&quot;); map_add(&amp;m, &quot;Computer Science 4&quot;, &quot;cs04&quot;); map_add(&amp;m, &quot;Chemistry 1&quot;, &quot;ch01&quot;); map_add(&amp;m, &quot;Chemistry 2&quot;, &quot;ch02&quot;); map_add(&amp;m, &quot;Quantum Chromodynamics&quot;, &quot;qd00&quot;); map_print(&amp;m); course = map_get(&amp;m, &quot;cs01&quot;); printf(&quot;Course: %s\n&quot;, course); map_del(&amp;m, &quot;ch01&quot;); course = map_get(&amp;m, &quot;ch01&quot;); printf(&quot;Course: %s\n&quot;, course); course = map_get(&amp;m, &quot;cs03&quot;); printf(&quot;Course: %s\n&quot;, course); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T18:51:01.687", "Id": "260390", "Score": "0", "Tags": [ "c", "hash-map", "library" ], "Title": "Quadratic Probing Hash Map - questions about implementation and testing" }
260390
<p>I have finished our first version of bin-packing-problem script, but would like to ask you, if there's a better way to organize boxes? Boxes should be organized to save as much space as possible, to make the &quot;main&quot; (blue) box as small as possible.</p> <p>But in some cases boxes do not organize well.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let GrowingPacker = function() { }; GrowingPacker.prototype = { fit: function(blocks) { var n, node, block, len = blocks.length; var w = len &gt; 0 ? blocks[0].w : setFloat(0); var h = len &gt; 0 ? blocks[0].h : setFloat(0); this.root = { x: setFloat(0), y: setFloat(0), w: w, h: h }; for (n = 0; n &lt; len ; n++) { block = blocks[n]; if (node = this.findNode(this.root, block.w, block.h)) { block.fit = this.splitNode(node, block.w, block.h); } else { block.fit = this.growNode(block.w, block.h); } } }, findNode: function(root, w, h) { if (root.used) return this.findNode(root.right, w, h) || this.findNode(root.down, w, h); else if ((w.lessThanOrEqualTo(root.w)) &amp;&amp; (h.lessThanOrEqualTo(root.h))) return root; else return null; }, splitNode: function(node, w, h) { node.used = true; node.down = { x: node.x, y: Decimal.add(node.y, h), w: node.w, h: Decimal.sub(node.h, h) }; node.right = { x: Decimal.add(node.x, w), y: node.y, w: Decimal.sub(node.w, w), h: h }; return node; }, growNode: function(w, h) { var maxWidth = setFloat(limit.area.max.width + limit.milling - (limit.area.border + form.option.panelization[1].padding) * 2); var maxHeight = setFloat(limit.area.max.height + limit.milling - (limit.area.border + form.option.panelization[1].padding) * 2); var possibleGrowDown = Decimal.add(this.root.h, h).lessThanOrEqualTo(maxHeight); var possibleGrowRight = Decimal.add(this.root.w, w).lessThanOrEqualTo(maxWidth); var canGrowDown = possibleGrowDown &amp;&amp; w.lessThanOrEqualTo(this.root.w); var canGrowRight = possibleGrowRight &amp;&amp; h.lessThanOrEqualTo(this.root.h); var shouldGrowDown = canGrowDown &amp;&amp; Decimal.add(this.root.h, h).lessThanOrEqualTo(this.root.w); // attempt to keep square-ish by growing down when width is much greater than height var shouldGrowRight = canGrowRight &amp;&amp; Decimal.add(this.root.w, w).lessThanOrEqualTo(this.root.h); // attempt to keep square-ish by growing right when height is much greater than width if(shouldGrowRight) { return this.growRight(w, h); } else if(shouldGrowDown) { return this.growDown(w, h); } else if(canGrowRight) { return this.growRight(w, h); } else if(canGrowDown) { return this.growDown(w, h); } else{ return this.growDown(w, h); // need to ensure sensible root starting size to avoid this happening } }, growRight: function(w, h) { this.root = { used: true, x: setFloat(0), y: setFloat(0), w: Decimal.add(this.root.w, w), h: this.root.h, down: this.root, right: { x: this.root.w, y: 0, w: w, h: this.root.h } }; var node; if (node = this.findNode(this.root, w, h)) return this.splitNode(node, w, h); else return null; }, growDown: function(w, h) { this.root = { used: true, x: 0, y: 0, w: this.root.w, h: Decimal.add(this.root.h, h), down: { x: 0, y: this.root.h, w: this.root.w, h: h }, right: this.root }; var node; if (node = this.findNode(this.root, w, h)) return this.splitNode(node, w, h); else return null; } } class Line { strokeStyle = '#ddd'; constructor(fX, fY, tX, tY) { this.fX = fX; this.fY = fY; this.tX = tX; this.tY = tY; } get length() { const hL = Math.pow(this.tX - this.fX, 2); const vL = Math.pow(this.tY - this.fY, 2); const l = Math.sqrt(hL + vL); return l; } draw(ctx) { ctx.beginPath(); ctx.moveTo(this.fX, this.fY); ctx.lineTo(this.tX, this.tY); ctx.strokeStyle = this.strokeStyle; ctx.stroke(); } }</code></pre> </div> </div> </p> <p><a href="https://i.stack.imgur.com/tCMaP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tCMaP.png" alt="Preview of the issue" /></a></p> <p>In this case the boxes from the right side should be aligned to the bottom of the blue square to reduce the size of the blue square.</p> <p>Could you help me out, to solve this issue?</p> <p>Thanks in advance.</p>
[]
[ { "body": "<h2>Review Code style &amp; structure</h2>\n<p>I am not going to give a better solution (there are plenty of solutions available online <a href=\"https://en.wikipedia.org/wiki/Bin_packing_problem\" rel=\"nofollow noreferrer\" title=\"Wikipedia article\">Bin packing problem</a>) See Bin Packing under rewrite for some hints.</p>\n<p>This is code review so I will review your code.</p>\n<h3>Low level language style?</h3>\n<p>I get the strong feeling that this code has been lifted from a lower level (language) example.</p>\n<p>Why do I think so? because lower level languages are often strongly typed and can require functions to do basic operations like <code>add</code>, <code>sub</code>, <code>isLessThan</code>, etc..</p>\n<p>When using example from other languages avoid coping type based code as these can have a serious performance penalty in JS</p>\n<p>Functions of concern</p>\n<pre><code> a.lessThanOrEqualTo(b) // replaced with a &lt;= b\n Decimal.add(a, b) // replaced with a + b\n Decimal.sub(a, b) // replaced with a - b *??\n setFloat(a) // replaced with a\n</code></pre>\n<p><code>*</code> You have not included some important information. <code>Decimal.sub(a, b)</code> does not indicate its direction. Is it <code>a - b</code> or <code>b - a</code> ???</p>\n<h3>General style</h3>\n<ul>\n<li><p>A returning statement should not be followed by an <code>else</code> statement. eg <code>if (foo) { return } else { boo = foo }</code> should be <code>if (foo) { return } boo = foo;</code></p>\n</li>\n<li><p>Idiomatic JS has the <code>else</code> on the same line as the closing <code>}</code></p>\n</li>\n<li><p>Always delimit all code blocks. eg <code>if (foo) return</code> should be <code>if (foo) { return }</code></p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> when variables are constants.</p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for...of\">for...of</a> rather then <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> when possible</p>\n</li>\n<li><p>Avoid assignments inside statement clauses. <code>if (foo = boo()) {</code> should be <code>foo = boo(); if (foo) {</code></p>\n</li>\n<li><p>Avoid <code>null</code> and use the default <code>undefined</code> Null does not mean undefined, <code>null</code>'s semantic meaning has been lost in JS but can generally be considered a place holder, though <code>undefined</code> can also be used as such.</p>\n</li>\n<li><p>Avoid accessing global's by passing data to functions.</p>\n<p>Doing so makes the code independent of the scope it exists in, making code more portable.</p>\n<p>For example the function <code>growNode</code> is accessing a higher level scope via <code>limit</code> and <code>form</code>. These objects should be passed to the function, better yet only the values of interest should be passed to the function. See rewrite function <code>growNode</code></p>\n</li>\n</ul>\n<h3>Use modern JS syntax.</h3>\n<ul>\n<li><p>Object property function short cut <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Functions Method definitions\">Functions.Method_definitions</a> when declaring functions for objects. eg <code>fit: function(blocks) {</code> should be <code>fit(blocks) {</code></p>\n</li>\n<li><p>Object property short cut when possible. <code>{x: x, y: y}</code> should be <code>{x, y}</code></p>\n</li>\n<li><p>Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Exponentiation\">** (Exponentiation)</a> operator rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math pow\">Math.pow</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math sqrt\">Math.sqrt</a>, or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cbrt\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math cbrt\">Math.cbrt</a></p>\n<p>On the subject of powers the very common operation of a &quot;line segment length&quot; can be performed using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math hypot\">Math.hypot</a> however <code>Math.hypot</code> is considerably slower than manually calculating the length of a known dimensioned line segment (Most likely because <code>hypot</code> is multi dimensional) .</p>\n<p>From experiment I have found that the quickest way to compute the length of a line segment in JS is as follows</p>\n<pre><code>const dx = x1 - x2, dy = y1 - y2;\nconst length = (dx * dx + dy * dy) ** 0.5;\n</code></pre>\n<p>Note that in many cases you can avoid the root operation is you need only the relative lengths</p>\n<pre><code>const dx = x1 - x2, dy = y1 - y2;\nconst lengthSqr = dx * dx + dy * dy;\n</code></pre>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite covers most of the review points with some additions.</p>\n<ul>\n<li><p>Added Node and NodeEx (Ex for extended) to reduce the code footprint needed to create Nodes.</p>\n</li>\n<li><p>Slight modifications to the line</p>\n<ul>\n<li>Uses a static property for line style</li>\n<li>Changed the way length is calculated</li>\n<li>Just to highlight the after <code>ctx.beginPath</code> the first call to <code>ctx.moveTo</code> is identical to <code>ctx.lineTo</code> .</li>\n</ul>\n</li>\n</ul>\n<p><strong>NOTE:</strong> The rewrite is an example ONLY! It is untested apart from being parsed. Without any tests I can not offer any guarantee that the code actually works.</p>\n<pre><code>const Node = (x, y, w, h) =&gt; ({x, y, w, h});\nconst NodeEx = (x, y, w, h, used = false, down, right) =&gt; ({x, y, w, h, used, down, right});\n\nconst GrowingPacker = function() { };\nGrowingPacker.prototype = {\n fit(blocks) {\n this.root = Node(0, 0, ...(blocks.length ? [blocks[0].w, blocks[0].h] : [0, 0]));\n for (const block of blocks) {\n const node = node = this.findNode(this.root, block.w, block.h);\n block.fit = node ?\n this.splitNode(node, block.w, block.h) :\n this.growNode(block.w, block.h);\n }\n },\n findNode(root, w, h) {\n return root.used ?\n this.findNode(root.right, w, h) || this.findNode(root.down, w, h) :\n (w &lt; root.w &amp;&amp; h &lt;root.h ? root : undefined); \n },\n splitNode(node, w, h) {\n node.used = true;\n node.down = Node(node.x, node.y + h, node.w, node.h - h);\n node.right = Node(node.x + w, node.y, node.w - w, h);\n return node;\n }, \n growNode: function(w, h, maxW, maxH) { // maxWidth and maxHeight passed as maxW and maxH\n const [grownW, grownH] = [this.root.w + w, this.root.h + h];\n const down = grownH &lt;= maxH &amp;&amp; w &lt;= this.root.w;\n const right = grownW &lt;= maxW &amp;&amp; h &lt;= this.root.h;\n \n if (right &amp;&amp; grownW &lt;= this.root.h) { return this.growRight(w, h) }\n if (down &amp;&amp; grownH &lt;= this.root.w) { return this.growDown(w, h) }\n if (right) { return this.growRight(w, h) }\n if (down) { return this.growDown(w, h) }\n return this.growDown(w, h); \n },\n grown(w, h) {\n const node = this.findNode(this.root, w, h);\n if (node) { return this.splitNode(node, w, h) }\n },\n growRight(w, h) {\n this.root = NodeEx(\n 0, 0, this.root.w + w, this.root.h, \n true, this.root, Node(this.root.w, 0, w, this.root.h)\n );\n return grown(w, h);\n },\n growDown(w, h) {\n this.root = NodeEx(\n 0, 0, this.root.w , this.root.h + h, \n true, Node(0, this.root.h, 0, this.root.w, h), this.root\n ); \n return grown(w, h);\n },\n}\n\nclass Line {\n static strokeStyle = &quot;#ddd&quot;;\n constructor(fX, fY, tX, tY, style = Line.strokeStyle) {\n this.fX = fX;\n this.fY = fY;\n this.tX = tX;\n this.tY = tY;\n this.style = style;\n } \n get length() {\n const hL = this.tX - this.fX, vL = this.tY - this.fY;\n return (hL * hL + vL * vL) ** 0.5;\n }\n draw(ctx) {\n ctx.strokeStyle = style;\n ctx.beginPath();\n ctx.lineTo(this.fX, this.fY);\n ctx.lineTo(this.tX, this.tY);\n ctx.stroke();\n }\n}\n</code></pre>\n<h2>Bin Packing</h2>\n<p>Your question.</p>\n<blockquote>\n<p><em>&quot;Bin-packing-problem - is there a way to do it better?&quot;</em></p>\n</blockquote>\n<p>Very likely, but how much better depends on what you are packing into the bin and the nature of the bin.</p>\n<p>The image shows that there are many options for a better solution. (boxes separated by 1 px)</p>\n<p><a href=\"https://i.stack.imgur.com/C4BpT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C4BpT.png\" alt=\"Numbers indicate the bin size\" /></a></p>\n<p><sub>Numbers indicate the bin size</sub></p>\n<p>Problem solving starts with the human approach</p>\n<p>When we humans pack stuff we have the ability to see all the stuff to pack in one glance and as such can formulate a strategy before we start to pack the bins.</p>\n<p>Generally the task is to fit items. If we pack and it turns out that it wont fit, we rearrange the packing by removing items and trying a different arrangement.</p>\n<p>Or we change the bin and start again.</p>\n<p>These are all strategies you can use to address the packing problem.</p>\n<ul>\n<li>Evaluate the objects to be packed.</li>\n<li>Can sub groups be packed highly efficiently. Group them to be packed as a group.</li>\n<li>Compare different combinations of placements.</li>\n<li>Change the bin constraints and start again.</li>\n</ul>\n<p>You say</p>\n<blockquote>\n<p><em><code>But in some cases boxes do not organize well.</code></em></p>\n</blockquote>\n<p>Aesthetics is not a concern unless you are packing a display, however a well pack bin does have a tendency to be aesthetically pleasing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T04:27:15.783", "Id": "260404", "ParentId": "260392", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T19:33:08.057", "Id": "260392", "Score": "0", "Tags": [ "javascript" ], "Title": "Bin-packing-problem - is there a way to do it better?" }
260392
<p>For context, the whole of the project code can be found <a href="https://github.com/gappleto97/job-splitter" rel="nofollow noreferrer">here</a>. This question was created specifically for the <code>progress.py</code> file.</p> <p>The goal behind it is to allow progress of long-running tasks to be reported to a tty terminal. This helps you quickly figure out if your jobs are progressing or stalled. I have not tested this on environments without <code>fork()</code>, so figuring out if this works on Windows (and how to make it do so if it does not) would be incredibly helpful.</p> <p>The only major API change of note is that the function handed to <code>Pool().map()</code> and etc needs to take an extra keyword argument called <code>progress</code>, which is a ProgressReporter instance.</p> <p>If the file is run as a script, it will run through a demo loop</p> <p>File <code>progress.py</code>:</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Implements an extended version of the multiprocessing.Pool object to allow progress reporting. Using several subclasses and wrapper objects, this module injects data into the standard multiprocessing pool. So long as the API for this does not change substantially, this module should work, and does not need to be updated very frequently. &quot;&quot;&quot; from collections import defaultdict from contextlib import contextmanager from enum import IntEnum from functools import partial from itertools import count from multiprocessing import TimeoutError, get_context from multiprocessing.pool import AsyncResult, IMapIterator, Pool, mapstar, starmapstar # type: ignore from time import sleep, time from queue import Queue from sys import stdout from random import random from threading import Thread from typing import Any, Callable, Dict, Generic, Iterable, Iterator, List, Mapping, Optional, Sequence, TypeVar from warnings import warn try: from reprint import output output_not_present = False except Exception: output_not_present = True # TODO: docstrings # TODO: tests # TODO: custom bar format _pool_id_gen = count() _pool_queue_map: Dict[int, Queue] = {} _singleton_map: Dict[str, 'Singleton'] = {} _T = TypeVar(&quot;_T&quot;) _U = TypeVar(&quot;_U&quot;) is_atty = stdout.isatty() @contextmanager def nullcontext(enter_result=None): &quot;&quot;&quot;Backport of contextlib.nullcontext for if output is not usable in a given environment.&quot;&quot;&quot; yield enter_result class Style(IntEnum): LOW_JOB_AND_TOTAL = 0 ACTIVE_JOBS_AND_TOTAL = 1 NON_TTY_SAFE = 2 class Singleton: &quot;&quot;&quot;Stub class that ensures only one instance of an object is ever made. To be used for specific sentinel values. &quot;&quot;&quot; def __new__(cls, name: str) -&gt; 'Singleton': &quot;&quot;&quot;Override __new__ such that it only spawns one instance.&quot;&quot;&quot; if name not in _singleton_map: _singleton_map[name] = super().__new__(cls) return _singleton_map[name] def __init__(self, name: str): self.name = name STOP_THREAD = Singleton(&quot;STOP_THREAD&quot;) class ProgressReporter: &quot;&quot;&quot;Reporter object injected into all calls made by the ProgressPool. Using this object, one can report incremental progress on their compute job back to the main process. &quot;&quot;&quot; def __init__(self, q_id: int, job_id: int): self.q_id = q_id self.job_id = job_id def report(self, progress: float, base: float = 100.0): &quot;&quot;&quot;Report a progress value back to the main process. By default, it is read as a float between 0 and 100, but the base can be overwritten on request. Raises ------ ValueError: if not (0 &lt;= progress &lt;= base) &quot;&quot;&quot; if not (0.0 &lt;= progress &lt;= base): raise ValueError(&quot;progress is outside valid range&quot;) if base != 100.0: progress = progress * 100.0 / base _pool_queue_map[self.q_id].put((self.job_id, progress)) def done(self): &quot;&quot;&quot;Report back to the main process that this task is done.&quot;&quot;&quot; self.report(100) def _initializer( q_id: int, queue: Queue, orig_init: Optional[Callable], initargs: Sequence[Any] = () ): _pool_queue_map[q_id] = queue if orig_init is not None: return orig_init(*initargs) def _wrap_prog(tup, star=False, **kwargs): func, q_id, arg, job_id = tup reporter = ProgressReporter(q_id, job_id) try: if star: ret = func(*arg, progress=reporter, **kwargs) else: ret = func(arg, progress=reporter, **kwargs) return ret finally: reporter.done() class WrappedObject: def __init__(self, obj): self._wrapped_object = obj def __getattr__(self, name: str): if name in self.__dict__: return getattr(self, name) return getattr(self._wrapped_object, name) class ProgressResult(WrappedObject): def __init__(self, result, id_range: Sequence[int]): super().__init__(result) self._pool: ProgressPool self.id_range = id_range self.current = min(id_range) def fix_style(self, style: Style) -&gt; Style: if style != Style.NON_TTY_SAFE: if not is_atty: warn(&quot;Running in a non-tty environment, falling back to one line style&quot;, RuntimeWarning) return Style.NON_TTY_SAFE elif output_not_present: warn(&quot;Running without reprint library, falling back to one line style&quot;, RuntimeWarning) return Style.NON_TTY_SAFE return style def _handle_multiple( self, job_id: int, rel_id: int, max_len: int, style: Style, bar_length: int, fill_char: str, output_lines ) -&gt; Any: if style == Style.LOW_JOB_AND_TOTAL: key = f'Job {str(rel_id).zfill(max_len)} Progress' prog = self._pool.get_progress(job_id) if prog &gt;= 100.0: self.current += 1 if key in output_lines: del output_lines[key] return True cells = int(prog * bar_length / 100.0) output_lines[key] = &quot;[{done}{padding}] {percent:2.02f}%&quot;.format( done=fill_char * cells, padding=&quot; &quot; * (bar_length - cells), percent=prog ) elif style == Style.ACTIVE_JOBS_AND_TOTAL: known_done = set() for rel_id, job_id in enumerate(self.id_range): if job_id in known_done: continue prog = self._pool.get_progress(job_id) if prog: key = f'Job {str(rel_id).zfill(max_len)} Progress' if prog &gt;= 100.0: known_done.add(job_id) if key in output_lines: del output_lines[key] else: cells = int(prog * bar_length / 100.0) output_lines[key] = &quot;[{done}{padding}] {percent:2.02f}%&quot;.format( done=fill_char * cells, padding=&quot; &quot; * (bar_length - cells), percent=prog ) elif style == Style.NON_TTY_SAFE: t_progress = self._pool.get_progress(job_id) cells = int(t_progress * bar_length / 100.0) done: int = output_lines # type: ignore print( &quot;\rJob {id} Progress: [{done}{padding}] {percent:2.02f}% ({i}/{l})&quot;.format( id=str(rel_id).zfill(max_len), done=fill_char * cells, padding=&quot; &quot; * (bar_length - cells), percent=t_progress, i=done, l=len(self.id_range) ), end=&quot;\r&quot; ) def print_info( self, style: Style, bar_length: int, output_lines, max_len: int, fill_char: str = &quot;#&quot;, main_name: str = 'Total Progress' ): # style 0, where the lowest ID'd active job is tracked if style == 0: for rel_id, job_id in enumerate(self.id_range): if job_id != self.current: continue if self._handle_multiple(job_id, rel_id, max_len, style, bar_length, fill_char, output_lines): continue t_progress = sum( self._pool.get_progress(job_id) for job_id in self.id_range ) / len(self.id_range) cells = int(t_progress * bar_length / 100.0) output_lines[main_name] = &quot;[{done}{padding}] {percent:2.02f}% ({i}/{l})&quot;.format( done=fill_char * cells, padding=&quot; &quot; * (bar_length - cells), percent=t_progress, i=rel_id, l=len(self.id_range) ) # style 1, where every active job is tracked, not just the lowest ID'd one elif style == 1: self._handle_multiple(0, 0, max_len, style, bar_length, fill_char, output_lines) t_progress = sum(self._pool.get_progress(job_id) for job_id in self.id_range) / len(self.id_range) cells = int(t_progress * bar_length / 100.0) output_lines[main_name] = &quot;[{done}{padding}] {percent:2.02f}%&quot;.format( done=fill_char * cells, padding=&quot; &quot; * (bar_length - cells), percent=t_progress ) # style 2, where total progress is given in a non-tty-safe manner elif style == 2: progs = [self._pool.get_progress(job_id) for job_id in self.id_range] done = sum(p == 100.0 for p in progs) t_progress = sum(progs) / len(self.id_range) cells = int(t_progress * bar_length / 100.0) length = len(self.id_range) if length &lt;= 1 or (time() % 4) &lt; 2: print( &quot;\r{main_name}: [{done}{padding}] {percent:2.02f}% ({i}/{l})&quot;.format( main_name=main_name, done=fill_char * cells, padding=&quot; &quot; * (bar_length - cells), percent=t_progress, i=done, l=length ), end=&quot;\r&quot; ) else: for rel_id, job_id in enumerate(self.id_range): if self._pool.get_progress(job_id) == 100.0: continue break self._handle_multiple(job_id, rel_id, max_len, style, bar_length, fill_char, done) else: raise ValueError(style) class ProgressImapResult(ProgressResult, Iterable[_T]): def __init__( self, result: IMapIterator, id_range: Sequence[int], style: Style, bar_length: int, fill_char: str, pool: 'ProgressPool', main_name: str = 'Total Progress' ): super().__init__(result, id_range) self.style = style self.bar_length = bar_length self._pool = pool self.fill_char = fill_char self.main_name = main_name def __iter__(self) -&gt; Iterator[_T]: max_len = len(str(len(self.id_range) - 1)) self.current = self.id_range[0] style = self.fix_style(self.style) context = output(output_type='dict') if style != Style.NON_TTY_SAFE else nullcontext({}) with context as output_lines: while True: self.print_info(style, self.bar_length, output_lines, max_len, self.fill_char, self.main_name) try: yield self.next(timeout=0.05) # pylint: disable=not-callable except TimeoutError: pass except StopIteration: break # TODO: maybe make this configurable? # if style == 2: # print() yield from self._wrapped_object class ProgressMapResult(ProgressResult, Generic[_T]): def __init__(self, result: AsyncResult, id_range: Sequence[int]): super().__init__(result, id_range) def get( self, timeout: float = None, style: Style = Style.ACTIVE_JOBS_AND_TOTAL, bar_length: int = 10, fill_char: str = &quot;#&quot;, main_name: str = 'Total Progress' ): if timeout is None: limit = float('inf') else: limit = time() + timeout max_len = len(str(len(self.id_range) - 1)) style = self.fix_style(style) context = output(output_type='dict') if style != Style.NON_TTY_SAFE else nullcontext({}) with context as output_lines: while not self.ready() and time() &lt; limit: self.print_info(style, bar_length, output_lines, max_len, fill_char, main_name) sleep(0.05) # if style == 2: # print() return self._wrapped_object.get(timeout=0) class ProgressAsyncResult(ProgressMapResult, Generic[_T]): def _handle_multiple(self, *args, **kwargs) -&gt; Any: pass class ProgressPool(Pool): &quot;&quot;&quot;Multiprocessing pool modified to keep track of job progress and print it to the console. Note ---- Do not use print statements while you are using a call like map(), map_async().get(), or imap(), as it will mess with progress bar formatting. If you do so, it is advised that you should pad the end of the line with whitespace so the message is more clearly readable. Future versions will provide helper methods to make this easier. TODO: provide helper methods to ensure garbage is not produced when printing, probably by having a lock and a helper method to clear the line. &quot;&quot;&quot; def __init__( self, processes: Optional[int] = None, initializer: Optional[Callable[[], None]] = None, initargs: Sequence[Any] = (), maxtasksperchild: Optional[int] = None, context=None ): context = context or get_context() self._pool_id = next(_pool_id_gen) self._prog_queue: Queue = context.Queue() _pool_queue_map[self._pool_id] = self._prog_queue self._id_generator = count() initializer = partial(_initializer, self._pool_id, self._prog_queue, initializer, initargs) self._active = True self._listener_thread = Thread(target=self._listen, daemon=True) self._listener_thread.start() self._start_job_id = 0 self._end_job_id = 0 self._progress_entries: Mapping[int, float] = defaultdict(int) super().__init__(processes, initializer, (), maxtasksperchild, context) def __del__(self): del _pool_queue_map[self._pool_id] super().__del__() def _listen(self): while self._active: tup = self._prog_queue.get() if tup is STOP_THREAD: return job_id, progress = tup if job_id &gt; self._end_job_id: self._end_job_id = job_id self._progress_entries[job_id] = progress while self._progress_entries[self._start_job_id] &gt;= 100.0: former = self._start_job_id self._start_job_id += 1 del self._progress_entries[former] def get_progress(self, job_id: int) -&gt; float: if job_id &lt; self._start_job_id: return 100.0 elif job_id &gt; self._end_job_id: return 0.0 return self._progress_entries[job_id] def close(self): self._prog_queue.put(STOP_THREAD) super().close() self._listener_thread.join() def apply( # type: ignore[override] self, func: Callable[..., _T], args: Iterable[Any] = (), kwds: Optional[Mapping[str, Any]] = None, callback: Optional[Callable[[_T], None]] = None, error_callback: Optional[Callable[[BaseException], None]] = None, style: Style = Style.ACTIVE_JOBS_AND_TOTAL, bar_length: int = 10, main_name: str = 'Total Progress' ) -&gt; _T: return self.apply_async(func, args, kwds, callback, error_callback).get( None, style, bar_length, main_name ) def apply_async( # type: ignore[override] self, func: Callable[..., _T], args: Iterable[Any] = (), kwds: Optional[Mapping[str, Any]] = None, callback: Optional[Callable[[_T], None]] = None, error_callback: Optional[Callable[[BaseException], None]] = None ) -&gt; ProgressAsyncResult[_T]: if kwds is None: kwds = {} ids = (next(self._id_generator), ) res = super().apply_async( partial(_wrap_prog, star=True), ((func, self._pool_id, args, ids[0]), ), kwds, callback, error_callback ) return ProgressAsyncResult(res, ids) def map( # type: ignore[override] self, func: Callable[[_U, ProgressReporter], _T], iterable: Iterable[_U], chunksize=None, style: Style = Style.ACTIVE_JOBS_AND_TOTAL, bar_length: int = 10, fill_char: str = &quot;#&quot;, main_name: str = 'Total Progress' ) -&gt; List[_T]: return self._map_async( func, iterable, mapstar, chunksize=chunksize ).get( style=style, bar_length=bar_length, fill_char=fill_char, main_name=main_name ) def starmap( self, func: Callable[..., _T], iterable: Iterable[Iterable], chunksize=None, style: Style = Style.ACTIVE_JOBS_AND_TOTAL, bar_length: int = 10, fill_char: str = &quot;#&quot;, main_name: str = 'Total Progress' ) -&gt; List[_T]: return self._map_async( func, iterable, starmapstar, chunksize=chunksize ).get( style=style, bar_length=bar_length, fill_char=fill_char, main_name=main_name ) def _map_async( self, func: Callable[..., _T], iterable, mapper, chunksize: Optional[int] = None, callback: Optional[Callable] = None, error_callback: Optional[Callable] = None ) -&gt; ProgressMapResult[_T]: is_star = (mapper is starmapstar) jobs = tuple(iterable) ids = tuple(next(self._id_generator) for _ in jobs) res = super()._map_async( # type: ignore partial(_wrap_prog, star=is_star), ((func, self._pool_id, t, j_id) for t, j_id in zip(jobs, ids)), mapstar, chunksize, callback, error_callback ) return ProgressMapResult(res, ids) def imap( # type: ignore[override] self, func: Callable[..., _T], iterable, *args, **kwargs ) -&gt; ProgressImapResult[_T]: return self._imap(func, iterable, mapstar, ordered=True, **kwargs) def imap_unordered( # type: ignore[override] self, func: Callable[..., _T], iterable, *args, **kwargs ) -&gt; ProgressImapResult[_T]: return self._imap(func, iterable, mapstar, ordered=False, **kwargs) def istarmap(self, func: Callable[..., _T], iterable, *args, **kwargs) -&gt; ProgressImapResult[_T]: return self._imap(func, iterable, starmapstar, ordered=True, **kwargs) def istarmap_unordered(self, func: Callable[..., _T], iterable, *args, **kwargs) -&gt; ProgressImapResult[_T]: return self._imap(func, iterable, starmapstar, ordered=False, **kwargs) def _imap( self, func: Callable[..., _T], iterable, mapper, *args, ordered: bool = True, style: Style = Style.ACTIVE_JOBS_AND_TOTAL, bar_length: int = 10, fill_char: str = &quot;#&quot;, main_name: str = 'Total Progress', **kwargs ) -&gt; ProgressImapResult[_T]: is_star = (mapper is starmapstar) jobs = tuple(iterable) ids = tuple(next(self._id_generator) for _ in jobs) if ordered: iterator: IMapIterator = super().imap( partial(_wrap_prog, star=is_star), ((func, self._pool_id, t, j_id) for t, j_id in zip(jobs, ids)), *args, **kwargs ) else: iterator = super().imap_unordered( partial(_wrap_prog, star=is_star), ((func, self._pool_id, t, j_id) for t, j_id in zip(jobs, ids)), *args, **kwargs ) return ProgressImapResult(iterator, ids, style, bar_length, fill_char, self, main_name) def demo_sleep(t: float, progress: ProgressReporter): &quot;&quot;&quot;Sleep, but report progress back to the main process.&quot;&quot;&quot; start = time() limit = start + (t or float('inf')) now = time() while now &lt; limit: progress.report((now - start) / t, base=1.0) sleep(1) now = time() if __name__ == '__main__': with ProgressPool() as pool: print(&quot;Let's test it out for each method/style combo!&quot;) for name, style in Style.__members__.items(): print() print(f&quot;apply() style {name}&quot;) pool.apply_async( demo_sleep, (random() * 10, ) ).get( style=style, bar_length=100 ) for map_method in (pool.map, pool.imap, pool.imap_unordered): for name, style in Style.__members__.items(): print() print(f&quot;{map_method.__name__}() style {name}&quot;) tuple(map_method( # type: ignore demo_sleep, (random() * 10 for _ in range(10)), style=style, bar_length=100 )) for starmap_method in (pool.starmap, pool.istarmap, pool.istarmap_unordered): for name, style in Style.__members__.items(): print() print(f&quot;{starmap_method.__name__}() style {name}&quot;) tuple(starmap_method( # type: ignore demo_sleep, ((random() * 10, ) for _ in range(10)), style=style, bar_length=100 )) </code></pre> <p>Edit: do note that it requires the <code>reprint</code> library to work properly</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T01:13:15.367", "Id": "260400", "Score": "4", "Tags": [ "python", "python-3.x", "multiprocessing", "mapreduce" ], "Title": "Subclass of Python's multiprocessing.Pool which allows progress reporting" }
260400
<p>I have a class called <code>CheckUserUltraSecretInformation</code> that is kind of a Use Case in &quot;clean architecture terms&quot;, this class has a dependency that is responsible for retrieving a couple of information from a cache &quot;provider&quot;, such as Redis, this is a crucial business rule for this use case, in order for the user to retrieve its &quot;ultra-secret information&quot; the cached information must exist.</p> <p>since &quot;retrieving the data from the cache&quot; it's a data layer, my first thought was to use the repository pattern, but that implicates that I also have an Entity or a &quot;Domain Model&quot; for this repository, the thing is: although I can picture a &quot;CachedUserInformation&quot; object and its properties I cannot see the <code>CachedUserInformation</code> as an entity, because it's not a &quot;core&quot; object of my application.</p> <p>I feel like this is more of a rule of the use case than an entity, but I cannot just return an array of data from this &quot;repository&quot;.</p> <p>should I just call it <code>CachedUserDataAdapter</code> and return the <code>CachedUserInformation</code> object?</p> <p>what are some good approaches for this scenario?</p> <p>my code:</p> <pre><code>interface CachedUserDataRepository { function findByDocument(string $document): CachedUserInformation; } class CheckUserUltraSecretInformation { public function __construct( private CachedUserDataRepository $cachedDataRepository ) { } public function Check(string $document) { $cachedUserData = $this-&gt;cachedDataRepository-&gt;findByDocument($document); if(empty($cachedUserData)) { throw new Exception('User Cached information not found, cannot proceed'); } } } class CachedUserInformation { private string $id; private string $secretInformation; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T04:32:24.950", "Id": "514043", "Score": "0", "body": "Entity is any data object with an identifier, so I think it's completely valid to call it an entity. On other hand being cached or not is just an implementation detail and thus shouldn't be part of the name, unless it carries the cache related properties as well. But that might be better modelled with composition, ie CacheEntry<TEntity>. But anyway that doesn't seem to be your case..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T04:48:43.040", "Id": "514044", "Score": "0", "body": "what do you mean by \"carries the cache-related properties as well\"? i think my problem with the repository is that I don't have a good name to call the object with only 2 properties, and that it just makes sense in the context of this use case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T05:04:20.567", "Id": "514046", "Score": "1", "body": "I mean things like expiration of the cache entry or so, anything that relates to cache. You could call it `UserSecretInformation` because thats what it seems to carry. It (and any entity really) is and should be completely unaware of its lifespan and persisting strategy, if any exists at all. So what if one day you stop caching theese things? You go and rename it to NonCachedUserInformation or what? If the entity only lives in the domain of the cache, then this may be better communicated by sharing a namespace with the cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T13:23:31.397", "Id": "514065", "Score": "0", "body": "In the end software code has to perform a task, be understandable to humans, and preferably be flexible so it can be altered or expanded. When I read your question, I see a lot of buzzwords, but to be honest, I have no idea what it is actually used for. I cannot test it and the title of your question does not describe what the code does either. What's here to review?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T03:27:51.140", "Id": "260403", "Score": "0", "Tags": [ "php", "repository" ], "Title": "Should my class \"data\" dependency be a repository, adapter or another pattern?" }
260403
<p>I just finished creating my first bash script that helps me to launch documents from terminal using a pdf viewer. This is very helpful and fast (at least I think so) for people who don't use any files manager (and have lots of documents of course); therefore they launch their pdf viewer and documents from terminal.</p> <p>I wish to upload the script on Github so any feedback, review, or tip on how it is or how to improve it before the upload is really appreciated.</p> <p>Here is the script:</p> <h3>rdoc</h3> <pre><code>#!/bin/env bash declare -r CONF_DIR_PATH=~/.config/rdoc declare -r CONF_DOC_DIR=$CONF_DIR_PATH/doc_dir declare -r CONF_PDF_VIEWER=$CONF_DIR_PATH/pdf_viewer declare -r TMP_FILE=/tmp/.rdoc_tmp fn_generate_configs() { local doc_dir_path local pdf_viewer_name mkdir -p $CONF_DIR_PATH echo -n &quot;Please enter your documents directorie's full path: &quot; read doc_dir_path echo $doc_dir_path &gt; $CONF_DOC_DIR echo -ne &quot;\nPlease enter your pdf's viewer name: &quot; read pdf_viewer_name echo $pdf_viewer_name &gt; $CONF_PDF_VIEWER echo echo Your configurations were generated succesfully. } fn_read_configs() { doc_dir=$(cat $CONF_DOC_DIR 2&gt; /dev/null) if [ ! $? -eq 0 ]; then echo Error: one or all of your configuration files are missing. echo Try -h for help. exit -1 fi pdf_viewer=$(cat $CONF_PDF_VIEWER 2&gt; /dev/null) if [ ! $? -eq 0 ]; then echo Error: one or all of your configuration files are missing. echo Try -h for help. exit -1 fi } fn_search_for_book() { local path local grep_opt=&quot;&quot; local string_to_exclude=$1/ if [ $i_status -eq 1 ]; then grep_opt=-i fi if [ $r_status -eq 1 ]; then #Search recursively for path in $1/*; do if [ -d $path ]; then fn_search_for_book $path elif [ -f $path ]; then if echo $path | grep -q $grep_opt $book_name; then echo $path | sed &quot;s|$string_to_exclude||&quot; &gt;&gt; $TMP_FILE fi fi done else for path in $1/*; do if [ -f $path ]; then if echo $path | grep -q $grep_opt $book_name; then echo $path | sed &quot;s|$string_to_exclude||&quot; &gt;&gt; $TMP_FILE fi fi done fi } fn_display_books() { local doc local founded_docs #Make sure a book was founded and TMP_FILE was generated founded_docs=$(cat $TMP_FILE 2&gt; /dev/null) if [ ! $? -eq 0 ]; then echo Error: no document was found with \'$book_name\' in it. exit -1 fi echo -e &quot;These are the documents that were found:\n&quot; #Set output's color to red tput setaf 1 for doc in $founded_docs; do echo $doc done #Reset output's color tput sgr0 } fn_count_books() { local doc local cnt=0 local founded_docs founded_docs=$(cat $TMP_FILE 2&gt; /dev/null) if [ ! $? -eq 0 ]; then echo Error: \'$TMP_FILE\' manipulation while the program is running are disallowed. exit -1 fi for doc in $founded_docs; do (( cnt++ )) done return $cnt } fn_final_book_name() { echo -ne &quot;\nWhich one of them would you like to open: &quot; read book_name } fn_generate_books_paths() { local path if [ $r_status -eq 1 ]; then for path in $1/*; do if [ -d $path ]; then fn_generate_books_paths $path elif [ -f $path ]; then echo $path &gt;&gt; $TMP_FILE fi done else for path in $1/*; do if [ -f $path ]; then echo $path &gt;&gt; $TMP_FILE fi done fi } fn_get_book_path() { local founded_paths local path local grep_opt=&quot;&quot; founded_paths=$(cat $TMP_FILE 2&gt; /dev/null) if [ ! $? -eq 0 ]; then echo Error: \'$TMP_FILE\' manipulation while the program is running are disallowed. exit -1 fi if [ $i_status -eq 1 ]; then grep_opt=-i fi for path in $founded_paths; do if ! echo $path | grep -q $grep_opt $book_name; then continue fi book_path=${path} break done } fn_open_book() { $pdf_viewer $book_path 2&gt; /dev/null if [ ! $? -eq 0 ]; then echo echo Error: \'$book_path\' can\'t be opened. exit -1 fi echo -e &quot;\nOpening: $book_path&quot; } fn_help_message() { echo Usage: rdoc \&lt;options\&gt; [argument] echo echo Available options: echo &quot; -h Display this help message. &quot; echo &quot; -g Generate new configuration files. &quot; echo &quot; -r Allow recursive searching for the document. &quot; echo &quot; -i Ignore case distinctions while searching for the document. &quot; echo &quot; -s Search for the document and display results. &quot; echo &quot; This option takes a document name or a part of it as an argument. &quot; echo &quot; -o Search for the document, display results then open it using your pdf viewer. &quot; echo &quot; This option takes a document name or a part of it as an argument. &quot; echo &quot; (Default) &quot; echo &quot;NOTE: &quot; echo &quot; When using '-s' or '-o' option in a combination of other options like this: &quot; echo &quot; &quot; echo &quot; $ rdoc -ris document_name &quot; echo &quot; &quot; echo &quot; Please make sure that it's the last option; to avoid unexpected behaviour. &quot; } doc_dir=&quot;&quot; pdf_viewer=&quot;&quot; book_path=&quot;&quot; book_name=${BASH_ARGV[0]} #book_name equals to the last arg by defualt so the default option ('-o') will work. #Options status r_status=0 i_status=0 s_status=0 o_status=1 #Make -o the default option #Display help message if no options were passed if [ $# -eq 0 ]; then fn_help_message exit 0 fi while getopts &quot;:hgris:o:&quot; opt; do case $opt in h) fn_help_message exit 0 ;; g) fn_generate_configs o_status=0 ;; r) r_status=1 ;; i) i_status=1 ;; s) book_name=$OPTARG s_status=1 o_status=0 ;; o) book_name=$OPTARG ;; :) echo Error: an argument is required for \'-$OPTARG\' option. echo Try -h for help. exit -1 ;; *) echo Error: unknown option \'-$OPTARG\'. echo Try -h for help. exit -1 ;; esac done if [ $s_status -eq 1 ] || [ $o_status -eq 1 ]; then #Make sure there isn't $TMP_FILE already generated from previous runs. rm $TMP_FILE 2&gt; /dev/null fn_read_configs fi if [ $s_status -eq 1 ]; then fn_search_for_book $doc_dir fn_display_books elif [ $o_status -eq 1 ]; then fn_search_for_book $doc_dir fn_display_books fn_count_books if [ $? -gt 1 ]; then #If more than 1 book were found with $book_name in it fn_final_book_name #Clean any leftovers of $TMP_FILE to search properly rm $TMP_FILE 2&gt; /dev/null #Make sure that the user chose an available document fn_search_for_book $doc_dir if [ ! -f $TMP_FILE ]; then echo echo Error: no document was found with \'$book_name\' in it. exit -1 fi #Make sure that the user is specific enough about the book name fn_count_books if [ $? -gt 1 ]; then echo echo Error: More than 1 book was found with the name \'$book_name\' in it. exit -1 fi fi echo -n &quot;&quot; &gt; $TMP_FILE #Make sure $TMP_FILE is empty so it'll be usable in fn_generate_books_paths fn_generate_books_paths $doc_dir fn_get_book_path fn_open_book fi exit 0 </code></pre> <p>Thanks for your time guys.</p>
[]
[ { "body": "<blockquote>\n<p><code>#!/bin/env bash</code></p>\n</blockquote>\n<p><a href=\"https://stackoverflow.com/a/10383546\">Prefer</a> <code>#!/usr/bin/env bash</code></p>\n<hr />\n<p><code>CONF_DOC_DIR</code> and <code>CONF_PDF_VIEWER</code> can be removed and use <code>$CONF_DIR_PATH/config</code> with contents:</p>\n<pre><code>CONF_DOC_DIR=...\nCONF_PDF_VIEWER=...\n</code></pre>\n<p>Reading the config would become: <code>source $CONF_DIR_PATH/config</code></p>\n<hr />\n<p><code>TMP_FILE</code> should be generated with <code>mktemp</code> so that we are guaranteed that file does not already exist</p>\n<hr />\n<blockquote>\n<p><code>mkdir -p $CONF_DIR_PATH</code></p>\n</blockquote>\n<p>If value of <code>CONF_DIR_PATH</code> has one or more spaces, then multiple directories would be created. Quote the variable to prevent splitting: <code>mkdir -p &quot;$CONF_DIR_PATH&quot;</code></p>\n<hr />\n<blockquote>\n<p>echo -n &quot;Please enter your documents directorie's full path: &quot;</p>\n</blockquote>\n<p>Typo: directories</p>\n<hr />\n<p><code>fn_</code> prefix for function names is not necessary</p>\n<hr />\n<blockquote>\n<p><code>for path in $1/*; do</code></p>\n</blockquote>\n<p><a href=\"https://unix.stackexchange.com/questions/55334/find-and-globbing-and-wildcards\">Prefer</a> <code>find -type f -exec ...</code></p>\n<hr />\n<blockquote>\n<p>echo Error: no document was found with '$book_name' in it.</p>\n</blockquote>\n<p>Quote escaping can be avoided with <code>echo &quot;Error: no document was found with '$book_name' in it. &quot;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T10:08:58.260", "Id": "514183", "Score": "0", "body": "Thank you for the review, I'll fix everything of course and I really appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T04:50:56.823", "Id": "260483", "ParentId": "260412", "Score": "1" } } ]
{ "AcceptedAnswerId": "260483", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T12:22:26.580", "Id": "260412", "Score": "0", "Tags": [ "bash", "linux" ], "Title": "Bash script that helps in opening documents when using terminal" }
260412
<p>So this is my task:</p> <blockquote> <p>You are given an irregular shape on a bitmap. How do you determine if a point is inside or ousdie of the shape?</p> </blockquote> <p>We are allowed to assume that <code>helper functions</code> are already available for us and we don't need to write them as well.</p> <p>So I decided that I can use a function that returns me the status of a given bit on that bitmap.</p> <pre><code>int IsBitIsOn(bitmap_ty *bitmap, size_t x, size_t y); </code></pre> <p><strong>We also can assume that the given point won't be a point on the outline of the shape. Which means the given X,Y coordinates must be either inside or outside the shape and not on one of the outlines.</strong></p> <p>And here is my full code of the task, I wrote it as a bitmap that every <code>ON(==1)</code> bit tells me that I'm on an outline, while <code>0 bit</code> tells me i'm either <code>inside</code> or <code>outside</code> the shape.</p> <pre><code>int IsInTheShape(bitmap_ty *bitmap, size_t x, size_t y) { int IsIn = 0; /* flag of whether the given point is inside the shape */ int ComeFromAbove = 0; int start_sequal = 1; size_t curr_row = y; size_t curr_column = 0; while (x != curr_column) { if (IsBitIsOn(bitmap, curr_column, curr_row)) { IsIn = !IsIn; /* starts a sequal of bits that are ON */ while (IsBitIsOn(bitmap, curr_column + 1, curr_row)) { /* checks the source direction of the first bit in the sequal */ if (start_sequal &amp;&amp; IsBitOn(bitmap, curr_column, curr_row - 1) || isBitOn(bitmap, curr_column - 1, curr_row - 1) || isBitOn(bitmap, curr_column + 1, curr_row - 1)) { ComeFromAbove = 1; start_sequal = 0; } ++curr_column; } /* checks the source direction of the last bit in the sequal, so if it cuts the direction of the first bit, it means the next points are out of the shape */ if (ComeFromAbove) { if (!IsBitOn(bitmap, curr_column, curr_row + 1) &amp;&amp; !isBitOn(bitmap, curr_column - 1, curr_row + 1) &amp;&amp; !isBitOn(bitmap, curr_column + 1, curr_row + 1)) { ComeFromAbove = 0; IsIn = !IsIn; } } } ++curr_column; } return (IsIn); } </code></pre> <p><strong>I draw the following shapes find the problematic points and shapes:</strong></p> <p><a href="https://i.stack.imgur.com/6CPwM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6CPwM.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T17:11:46.367", "Id": "514084", "Score": "2", "body": "I think there are more interesting problematic shapes: what if a shape has a width or height of only 1 pixel? What if two shapes touch each other? What if shapes are not closed (like the M-shape in the image you added, it has a small hole in the bottom left)? What about a 2D donut (a smaller circle inside a bigger one)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T20:03:44.457", "Id": "514101", "Score": "2", "body": "Another problematic shape would be something like the [cardioid](https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Polar_pattern_cardioid.png/1200px-Polar_pattern_cardioid.png)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T04:12:12.880", "Id": "514171", "Score": "1", "body": "Am I missing something or can this be solved with: 1) check if (x,y) is in shape, if it is not, return false, if it is, 2) check all 8 surrounding bits is in shape, if any of them aren't, then return false. Otherwise, return true" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T08:46:35.453", "Id": "514179", "Score": "1", "body": "While this is an interesting problem, Code Review does require working code: https://codereview.stackexchange.com/help/how-to-ask The code presented seems very hypothetical, and won't work as it is (e.g. `IsBitIsOn`, `isBitOn`, `IsBitOn`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T22:34:19.653", "Id": "514220", "Score": "0", "body": "@FromTheStackAndBack How can you check if (x,y) is in shape? This is the whole question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T23:32:18.810", "Id": "514221", "Score": "0", "body": "@NoobCoder see if my answer makes sense" } ]
[ { "body": "<h1>If shape on bitmap is not filled and only one shape present on bitmap:</h1>\n<p>Start at point <code>(x,y)</code>. For each of the four directions (left, right, top, bottom), keep going until either <code>IsBitIsOn</code> is true or a border of the bitmap has been reached. In the former case, point is in shape. Else (if border of bitmap reached), point is not in shape.</p>\n<p>Pseudocode:</p>\n<pre><code>def IsInTheShape(x, y):\n curr_x = x\n curr_y = y\n # Check left\n while curr_x &gt;= -1:\n if (curr_x == -1):\n return false\n if IsBitIsOn(curr_x, y):\n break\n\n curr_x = x\n curr_y = y\n # Check right\n while curr_x &lt;= bitmap.width + 1:\n if (curr_x == bitmap.width + 1):\n return false\n if IsBitIsOn(curr_x, y):\n break\n\n # Check top\n # Check bottom\n\n # All directions hit IsBitIsOn, so must be in shape\n return true\n</code></pre>\n<h1>If shape on bitmap is not filled and one or multiple shapes are present on bitmap:</h1>\n<p>Same as above, but once an outline has been reached, check all connected outline pieces recursively until the starting point has been reached. If the traversal around the outline visits all of the other outlines from the other three directions, then point is inside shape.</p>\n<h1>If shape on bitmap is filled:</h1>\n<p>Suppose that we want to check if <code>(x,y)</code> is in shape. Let <code>(x,y)</code> be cell <code>E</code> in the following grid:</p>\n<pre><code>+---+---+---+\n| A | B | C |\n+---+---+---+\n| D | E | F |\n+---+---+---+\n| G | H | I |\n+---+---+---+\n</code></pre>\n<p>Case 1 (point trivially not in shape):</p>\n<blockquote>\n<p>Point is not in shape if <code>E</code> is off: <code>if not IsBitIsOn(E): return false</code></p>\n</blockquote>\n<p>Case 2 (point not in shape):</p>\n<blockquote>\n<p>Point is not in shape if any of the 8 surrounding bits around <code>E</code> is off:</p>\n</blockquote>\n<pre><code>if not (IsBitIsOn(A) and IsBitIsOn(B) and IsBitIsOn(C) and IsBitIsOn(D) and IsBitIsOn(F) and IsBitIsOn(G) and IsBitIsOn(H) and IsBitIsOn(I)): return false\n</code></pre>\n<p>Case 3 (point in shape):</p>\n<blockquote>\n<p>Point is all of the 8 surrounding bits around <code>E</code> is on:</p>\n</blockquote>\n<pre><code>else: return true\n</code></pre>\n<p>All together, the pseudocode is:</p>\n<pre><code>if not IsBitIsOn(E):\n return false\nelse if not (IsBitIsOn(A) and IsBitIsOn(B) and IsBitIsOn(C) and IsBitIsOn(D) and IsBitIsOn(F) and IsBitIsOn(G) and IsBitIsOn(H) and IsBitIsOn(I)):\n return false\nelse:\n return true\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T23:14:49.300", "Id": "260516", "ParentId": "260413", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T12:34:57.007", "Id": "260413", "Score": "2", "Tags": [ "c", "bitset" ], "Title": "Determine if a point is inside or ouside of an irregular shape on a bitmap" }
260413
<pre><code>#include &lt;vector&gt; std::vector&lt;int&gt; Range(int from, int to, int step = 1) { std::vector&lt;int&gt; range; if (step &gt; 0) { for(int i = from; i &lt; to; i += step) { range.push_back(i); } } else if (step &lt; 0) { for(int i = from; i &gt; to; i += step) { range.push_back(i); } } return range; } </code></pre> <p>I don't like code duplication in my implementation, because I have two almost identical blocks. Is it possible to avoid it?</p>
[]
[ { "body": "<p>I think the easiest way to solve this is to first calculate how many steps it takes to go from <code>from</code> to <code>to</code>, and then just build an array of that many elements. That also has the advantage that you can reserve the right amount of elements in the vector up front. You also have to make sure that <code>step</code> has the correct sign.</p>\n<pre><code>if (from &lt;= to != step &gt; 0)\n step = -step;\n\nsize_t distance = std::abs(to - from);\nsize_t stepsize = std::abs(step);\nsize_t nsteps = (distance + stepsize - 1) / stepsize;\n\nstd::vector&lt;int&gt; range;\nrange.reserve(nsteps);\n\nfor (size_t i = 0; i &lt; nsteps; ++i)\n range.push_back(from + i * step);\n</code></pre>\n<p>You also might want to add some check that <code>step</code> is not zero.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T17:35:36.873", "Id": "514087", "Score": "0", "body": "looks like your solution doesnt work for those tests:\n\nstd::vector<int> expected{-9, -4, 1, 6};\nREQUIRE(expected == Range(-9, 10, 5));\n\nstd::vector<int> expected{7};\nREQUIRE(expected == Range(7, 6, -3));\n\nREQUIRE(Range(3, 7, -1).empty());" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T18:15:17.870", "Id": "514090", "Score": "0", "body": "@IvanPetrushenko I forgot to compensate for step sizes larger than 1. I updated my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T18:36:16.320", "Id": "514094", "Score": "0", "body": "@BlameTheBits `auto rq = std::div(to - from, step); size_t nsteps = rq.quot + !!rq.rem`? It's all ugly at this point :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T18:40:55.503", "Id": "514095", "Score": "0", "body": "Yeah, it really is :D With your descriptive variables it is probably the most clear implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T01:32:28.153", "Id": "514112", "Score": "3", "body": "`to - from` might overflow..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T16:16:22.623", "Id": "260421", "ParentId": "260416", "Score": "5" } }, { "body": "<p>The only difference is the <code>&lt;/&gt;</code> which swaps on multiplication by a negative factor:\n<code>x &lt; y &lt;=&gt; -x &gt; -y</code>. An ugly use would be:</p>\n<pre><code> for (int i = from; signum(step)*i &lt; signum(step)*to; i += step) {\n for (int i = from; signum(i - to) == signum(step); i += step) {\n for (int i = from; (i - to)*signum(step) &lt; 0; i += step) {\n for (int i = from; (i - to)*step &lt; 0; i += step) {\n</code></pre>\n<p>The last choice might seem best, but suffers integer overflow for huge values.</p>\n<p>In fact the code duplication seems fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T20:40:40.787", "Id": "260435", "ParentId": "260416", "Score": "3" } }, { "body": "<p>The <a href=\"https://stackoverflow.com/a/4609795/658087\"><code>signum</code></a> function returns -1, 0, 1 if the argument is negative, zero, or positive.</p>\n<pre><code>int original_diff = signum(to-from);\n</code></pre>\n<p>When <code>signum(to-current)</code> is <em>different</em>, we know the relationship changed, regardless of which direction you were going.</p>\n<pre><code>if (original_diff == 0) return; //do nothing\nfor (int current= from; signum(to-current) != original_diff; current += step)\n</code></pre>\n<p>will do what you want.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T09:39:53.707", "Id": "514180", "Score": "0", "body": "thanks, but it doesn't work for this Range(2, 5, 1) or Range(5, 2, -1)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T13:45:28.247", "Id": "514324", "Score": "0", "body": "original is sgn(5-2) = +1. current=2; current=3 same. current=4 same. current=5 gives sgn(5-5)=0 which != +1 and the loop stops. The count-down example works similarly, with the original sgn(2-5)=-1 eventually becoming sgn(2-2)=0 which stops." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:41:10.083", "Id": "518334", "Score": "1", "body": "@G.Sliepen Sorry, I used the [proper math name](https://en.wikipedia.org/wiki/Sign_function) as did others in comments and answers, but didn't notice that there was no function in the standard library. I've added a link to my post." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T21:41:53.480", "Id": "260438", "ParentId": "260416", "Score": "2" } } ]
{ "AcceptedAnswerId": "260438", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T13:54:10.530", "Id": "260416", "Score": "5", "Tags": [ "c++", "algorithm" ], "Title": "Implementing range from_to with step" }
260416
<p>I want to use <code>TIdTCPClient</code> to connect to Redis from a web server application made with Delphi and <code>TWebModule</code>. Currently on WebModule creation I create a new <code>TIdTCPClient</code> and on web module destroy, I disconnect and free the resource. All works... But this way I create a new connection on every new request and after a lot of time there is a growing number of <code>TIME_WAIT</code> sockets.</p> <p>I would like to implement a global connection pool with a fixed number of connections always open.</p> <p>NB: I have omitted redis logic, in this example is important only TCP connection pool</p> <p><strong>Redis.Pool.pas</strong></p> <pre><code>unit Redis.Pool; interface uses Windows, System.Classes, System.SysUtils, System.SyncObjs, System.Threading, System.DateUtils, IdTCPClient; type EConnPoolException = class(Exception); IRedisConnection = Interface(IInterface) function Connection: TIdTCPClient; function GetRefCount: Integer; function GetLastAccess: TDateTime; function GetIsConnected: boolean; property LastAccess: TDateTime read GetLastAccess; property RefCount: Integer read GetRefCount; property IsConnected: boolean read GetIsConnected; end; // The TRedisConnection class also contains two member fields, // FCriticalSection and FSemaphore. Both of these members are used to point // to a TCriticalSection and a semaphore (a THandle), both of which are // maintained by the TFixedRedisPool class (and are assigned to these // members by the TFixedRedisPool instance when it creates an instance // of the connection module). // The critical section class is used to synchronize access to the internal // reference count of the connection pool instances, and the semaphore // controls access to instances of the TRedisConnection class. This is // shown in the _AddRef and _Release method implementations, shown here. TRedisConnection = class(TInterfacedObject, IRedisConnection) private FConnection: TIdTCPClient; protected FRefCount: Integer; FLastAccess: TDateTime; // When the TRedisConnection is created the // connection pool that creates the object // will assign its critical section to this field. // The object will use this critical section // to synchronize access to its reference count. FCriticalSection: TCriticalSection; // This semaphore points to the FixedConnectionPool's // semaphore. It will be used to call ReleaseSemaphore // from the _Release method of the TRedisConnection. FSemaphore: THandle; // These two static methods are reintroduced // in order to implement lifecycle management // for the interface of this object. // Normally, unlike normal COM objects, Delphi // TComponent descendants are not lifecycle managed // when used in interface references. function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function GetRefCount: Integer; function GetLastAccess: TDateTime; function GetIsConnected: boolean; public constructor Create; overload; destructor Destroy; override; function Connection: TIdTCPClient; end; TCleanupThread = class; TFixedRedisPool = class(TObject) private FPool: array of IRedisConnection; FPoolSize: Integer; FTimeout: Integer; FCleanupThread: TCleanupThread; // This semaphore is used to limit the number of // simultaneous connections. When the nth+1 connection // is requested, it will be blocked until a connection // becomes available. FSemaphore: THandle; // This is the critical section that synchronizes // access to the connection module reference counts FCriticalSection: TCriticalSection; public // This overloaded constructor takes two optional // parameters. These parameters specify the size // of the connection pool, as well as how long idle // connections in the connection pool will be kept. constructor Create(const APoolSize: Integer = 10; const ACleanupDelayMinutes: Integer = 5; const ATimeoutms: Integer = 2000); overload; destructor Destroy; override; // This function returns an object // that implements the IRedisConnection interface. // This object can be a data module, as was //done in this example. function GetConnection: IRedisConnection; end; // This thread class is used by the connection pool // object to cleanup idle connections after a // configurable period of time. TCleanupThread = class(TThread) private FCleanupDelay: Integer; protected // When the thread is created, this critical section // field will be assigned the connection pool's // critical section. This critical section is // used to synchronize access to data module // reference counts. FCriticalSection: TCriticalSection; FFixedConnectionPool: TFixedRedisPool; procedure Execute; override; constructor Create(const ACreateSuspended: Boolean; const ACleanupDelayMinutes: Integer); end; // Global Connection Pool var RedisConnPool: TFixedRedisPool; implementation // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++ TRedisConnection ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ constructor TRedisConnection.Create; begin FConnection := TIdTCPClient.Create; FConnection.Connect('LOCALHOST', 6379); end; destructor TRedisConnection.Destroy; begin FConnection.Disconnect; FConnection.Free; inherited; end; function TRedisConnection._AddRef: Integer; begin // increment the reference count FCriticalSection.Enter; try Inc(FRefCount); Result := FRefCount; finally FCriticalSection.Leave; end; end; function TRedisConnection._Release: Integer; begin // decrement the reference count FCriticalSection.Enter; try Dec(FRefCount); Result := FRefCount; // if not more references, call Destroy if Result = 0 then Destroy else Self.FLastAccess := Now; finally FCriticalSection.Leave; if FRefCount = 1 then ReleaseSemaphore(FSemaphore, 1, nil); end; end; function TRedisConnection.GetRefCount: Integer; begin Result := FRefCount; end; function TRedisConnection.GetLastAccess: TDateTime; begin Result := Self.FLastAccess; end; function TRedisConnection.GetIsConnected: boolean; begin Result := Self.FConnection.Connected; end; function TRedisConnection.Connection: TIdTCPClient; begin Result := Self.FConnection; end; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++ TFixedRedisPool +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ constructor TFixedRedisPool.Create(const APoolSize: Integer = 10; const ACleanupDelayMinutes: Integer = 5; const ATimeoutms: Integer = 2000); begin FPoolSize := APoolSize; FTimeout := ATimeoutms; FSemaphore := CreateSemaphore(nil, APoolSize, APoolSize, ''); FCriticalSection := TCriticalSection.Create; // Set the length of the connection pool SetLength(FPool, APoolSize); // Create and start the cleanup thread FCleanupThread := TCleanupThread.Create(True, ACleanupDelayMinutes); with FCleanupThread do begin FreeOnTerminate := True; Priority := tpLower; FFixedConnectionPool := Self; Start; end; end; function TFixedRedisPool.GetConnection: IRedisConnection; var I: Integer; aRedisConnection: TRedisConnection; aWaitResult: Integer; begin Result := nil; aWaitResult := WaitForSingleObject(FSemaphore, FTimeout); if aWaitResult &lt;&gt; WAIT_OBJECT_0 then raise EConnPoolException.Create('TFixedRedisPool.GetConnection pool timeout.'); FCriticalSection.Enter; try for I := Low(FPool) to High(FPool) do begin // If FPool[i] = nil, the IRedisConnection has // not yet been created. Create it, initialize // it, and return it. If FPool[i] &lt;&gt; nil, then // check to see if its RefCount = 1 (only the pool // is referencing the object). if FPool[I] = nil then begin aRedisConnection := TRedisConnection.Create; aRedisConnection.FCriticalSection := Self.FCriticalSection; aRedisConnection.FSemaphore := Self.FSemaphore; FPool[I] := aRedisConnection; Result := FPool[I]; Exit; end; // if FPool[i].FRefCount = 1 then // the connection is available. Return it. if (FPool[I].RefCount = 1) and FPool[I].IsConnected then begin Result := FPool[I]; Exit; end; end; finally FCriticalSection.Leave; end; end; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++ TCleanupThread ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ constructor TCleanupThread.Create(const ACreateSuspended: Boolean; const ACleanupDelayMinutes: Integer); begin // always create suspended inherited Create(True); FCleanupDelay := ACleanupDelayMinutes; // Start if not created suspended if not(ACreateSuspended) then Start; end; destructor TFixedRedisPool.Destroy; var I: Integer; begin FCleanupThread.Terminate; FCriticalSection.Enter; try for I := Low(FPool) to High(FPool) do FPool[I] := nil; SetLength(FPool,0); finally FCriticalSection.Leave; end; FCriticalSection.Free; CloseHandle(FSemaphore); inherited; end; procedure TCleanupThread.Execute; var I: Integer; begin while True do begin if Terminated then Exit; // Sleep per delay Sleep(FCleanupDelay * 1000 * 60); if Terminated then Exit; FFixedConnectionPool.FCriticalSection.Enter; try for I := Low(FFixedConnectionPool.FPool) to High(FFixedConnectionPool.FPool) do begin if FFixedConnectionPool.FPool[I] = nil then continue; // if the connection exists, has no external reference, // and has not been used lately, release it if not(FFixedConnectionPool.FPool[I].IsConnected) or (FFixedConnectionPool.FPool[I].RefCount = 1) and (MinutesBetween(FFixedConnectionPool.FPool[I].LastAccess, Now) &gt; FCleanupDelay) then begin FFixedConnectionPool.FPool[I] := nil; end; end; finally FFixedConnectionPool.FCriticalSection.Leave; end; end; end; initialization RedisConnPool := TFixedRedisPool.Create(10, 5, 2000); finalization FreeAndNil(RedisConnPool); end. </code></pre> <p>usage</p> <pre><code>uses Redis.Pool; var aConn: IRedisConnection; begin // RedisConnPool is blobal var into Redis.Pool aConn := RedisConnPool.GetConnection; try // I have omitted redis logic in this example is important only TCP connection pool.. // aConn.Connection.GET('REDIS_KEY'); aConn.Connection.IOHandler.Write('HELLO'); finally aConn := nil; end; end; </code></pre> <p>The question is: Is my implementation thread safe in a in a multithread environment like a <code>TWebModule</code> application?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T14:20:53.363", "Id": "260418", "Score": "2", "Tags": [ "tcp", "delphi", "connection-pool" ], "Title": "Delphi TIdTCPClient connection pool in a multithread environment" }
260418
<p>I am thinking about the following problem:</p> <p>Consider a 3-numbers lock, i.e. a lock which has three little number wheels that opens whenever the sum of these three numbers equals 75. I know, this doesn't make sense for a lock, but just imagine this. The number wheels have numbers 3, 15, 17, 35, 40, 25, 5, 13. I am allowed to use numbers multiple times, i.e. in order to reach 75, I could use the combination 25, 25, 25.</p> <p>I want to come up with all possible combinations to solve this puzzle. I have a solution and it works fine for just 3 different number wheels. But since I am using 3 for-loops for this, I know I cannot extend this code to work for, say a 100 number-wheels lock. I don't even know if this was possible (maybe recursively, but I always have troubles understanding recursion). Anyways, I really want to make this code look a little nicer. It is okay for me to leave the number of iterations the same, but I really want to get rid of the 3 for-loops, because I kind of want to extend this code to be a 10-numbers lock and in that case I would have 10 for-loops which looks ridiculous. There should be a way to leave out the for loops, I think</p> <p>So, enough said. Here is my solution:</p> <pre><code>import java.util.ArrayList; import java.util.Collections; import java.util.List; public class TestClass { public static void main(String[] args) { List&lt;List&lt;Integer&gt;&gt; solutions = new ArrayList&lt;&gt;(); List&lt;Integer&gt; combinations = new ArrayList&lt;Integer&gt;(); List&lt;Integer&gt; numbers = new ArrayList&lt;Integer&gt;(); numbers.add(3); numbers.add(15); numbers.add(17); numbers.add(35); numbers.add(40); numbers.add(25); numbers.add(5); numbers.add(13); int target = 75; int var1 = 3; int var2 = 3; int var3 = 3; for (int i = 0; i &lt; numbers.size(); i++) { var1 = numbers.get(i); for (int j = 0; j &lt; numbers.size(); j++) { var2 = numbers.get(j); for (int k = 0; k &lt; numbers.size(); k++) { var3 = numbers.get(k); int sum = var1 + var2 + var3; if (sum == target) { combinations.add(var1); combinations.add(var2); combinations.add(var3); Collections.sort(combinations); if (!solutions.contains(combinations)) { solutions.add(combinations); } combinations = new ArrayList&lt;&gt;(); } } } } for (List&lt;Integer&gt; solution: solutions) { System.out.println(solution); } } } </code></pre> <p>Any ideas, please share them with me :-)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T12:06:01.887", "Id": "514131", "Score": "3", "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-05-07T12:59:58.013", "Id": "514138", "Score": "0", "body": "oh, ok. I didn't know that." } ]
[ { "body": "<p>you need the function</p>\n<pre><code>public static List&lt;Integer&gt; get_next_highest(List&lt;Integer&gt; combinations, List&lt;Integer&gt; numbers) {\n for(int i=0; i &lt; combinations.size(); i++) {\n if(combinations[i]&lt;numbers.size()-1) {\n combinations[i]++;\n return combinations;\n }\n else combinations[i] = 0; \n }\n return null;\n}\n</code></pre>\n<p>here, to simplify I've made combinations have indices (otherwise can't just do combinations[i]++, would need to find the next highest number in numbers)...</p>\n<p>for eg. if <code>numbers=[25 30 60 80]</code> and <code>combinations=[0 0 2 1]</code></p>\n<p>this corresponds to the wheel positions <code>[25 25 60 30]</code></p>\n<p>if you pass the value of combinations <code>[3 3 3 3]</code> the function will return a null so make sure to do a check and stop when it does.</p>\n<p>This will loop you through all possible combinations if you start at <code>[0 0 0 0]</code></p>\n<p>Specifically in the order <code>[0 0 0 0] [1 0 0 0 ] [2 0 0 0] [3 0 0 0] [0 1 0 0] [1 1 0 0] ... [3 3 3 3]</code></p>\n<p>should be fairly easy to sum up numbers[combinations[i]]</p>\n<p>since you specified no for loops here's the recursive version</p>\n<pre><code>public static List&lt;Integer&gt; get_next_highest(List&lt;Integer&gt; combinations, List&lt;Integer&gt; numbers, int i=1) {\n if(i==combinations.size()) return null;\n if(combinations[i]&lt;numbers.size()) {\n combinations[i]++;\n return combinations;\n }\n else {\n combinations[i] = 0;\n return get_next_highest(combinations, numbers, i+1);\n }\n}\n</code></pre>\n<p>it does the same thing</p>\n<pre><code>import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class TestClass {\n\n public static void main(String[] args) {\n \n List&lt;List&lt;Integer&gt;&gt; solutions = new ArrayList&lt;&gt;();\n List&lt;Integer&gt; combinations = new ArrayList&lt;Integer&gt;();\n \n List&lt;Integer&gt; numbers = new ArrayList&lt;Integer&gt;();\n numbers.add(3);\n numbers.add(15);\n numbers.add(17);\n numbers.add(35);\n numbers.add(40);\n numbers.add(25);\n numbers.add(5);\n numbers.add(13);\n \n int target = 75;\n int num_wheels = 3;\n \n for (int i = 0; i &lt; num_wheels; i++) combinations.add(0);\n \n for (; combinations != null; combinations=get_next_highest(combinations, numbers)) {\n int sum = 0;\n for(Integer x : combinations) sum += numbers[x];\n if (sum == target) {\n temp = new ArrayList&lt;&gt;();\n for(Integer x : combinations) temp.add(numbers[x]);\n Collections.sort(temp);\n if (!solutions.contains(temp)) solutions.add(temp);\n }\n }\n \n for (List&lt;Integer&gt; solution: solutions) {\n System.out.println(solution);\n }\n \n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T10:15:37.697", "Id": "514129", "Score": "0", "body": "Hi, thx a lot for your answer! Unfortunately, I don't really understand how to apply this function to my problem. Could you try and integrate it into my example? ... also: I am thinking there might be a neat solution that makes use of streams. I have updated my question a little bit with these thoughts" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T13:34:10.157", "Id": "514140", "Score": "0", "body": "you can replace your triple loop with this function, loop until the get_next_highest returns a null, otherwise it doesn't deviate from the original post much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T13:36:42.003", "Id": "514141", "Score": "0", "body": "oh, and you also have to do sum of numbers[combinations[i]] instead of sum of combinations[i]" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T19:32:16.943", "Id": "260429", "ParentId": "260422", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T16:35:40.737", "Id": "260422", "Score": "4", "Tags": [ "java", "combinatorics" ], "Title": "Find all combinations of numbers of a set that add up to a given target - avoid for loops" }
260422
<p>I have made a function which takes a string which can be any of <code>&quot;triangle&quot;</code>, <code>&quot;square&quot;</code> or <code>&quot;rectangle&quot;</code>.</p> <p>Depending on the string I return a pointer to an instance of class <code>Form</code>. My class <code>Form</code> has subclasses <code>Triangle</code>, <code>Square</code> and <code>Rectangle</code>.</p> <p>My constraints were:</p> <ul> <li>use C++98</li> <li>no STL library (no map, vector etc)</li> <li>no friend, and no <code>using namespace std;</code></li> </ul> <pre><code>#include &lt;iostream&gt; #define NB_FORMS 3 /**/ class Form { public: Form() { } virtual ~Form() { } }; class Square : public Form { public: Square() { std::cout &lt;&lt; &quot;Squareee!&quot; &lt;&lt; std::endl; } static Form *createForm(void) { return (new Square()); } }; class Rectangle : public Form { public: Rectangle() { std::cout &lt;&lt; &quot;Rectangleee!&quot; &lt;&lt; std::endl; } static Form *createForm(void) { return (new Rectangle()); } }; class Triangle : public Form { public: Triangle() { std::cout &lt;&lt; &quot;Triangleee!&quot; &lt;&lt; std::endl; } static Form *createForm(void) { return (new Triangle()); } }; struct s_makeForms { std::string formName; Form *(*makeForm)(); }; /* */ Form *func(std::string name) { struct s_makeForms allForms[3] = { {&quot;triangle&quot;, Triangle::createForm}, {&quot;rectangle&quot;, Rectangle::createForm}, {&quot;square&quot;, Square::createForm} }; for (int i = 0; i &lt; NB_FORMS; i++) { if (name == allForms[i].formName) return (allForms[i].makeForm()); } return (NULL); } int main() { Form *myform; if (!(myform = func(&quot;square&quot;))) { std::cerr &lt;&lt; &quot;wrong name&quot; &lt;&lt; std::endl; } delete myForm; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T13:38:05.150", "Id": "514142", "Score": "5", "body": "It would be better to explain here what problem you are trying to solve instead of making us follow the link to read the question and answer and then come back here." } ]
[ { "body": "<pre><code>Form *func(std::string name)\n{\n std::vector&lt;s_makeForms&gt; allForms =\n {\n {&quot;triangle&quot;, Triangle::createForm}, \n {&quot;rectangle&quot;, Rectangle::createForm},\n {&quot;square&quot;, Square::createForm}\n };\n for (const auto&amp; form : allForms)\n {\n if (name == form.formName)\n return (form.makeForm());\n }\n return nullptr;\n}\n</code></pre>\n<p>since you don't want maps, and whatever other unsaid restrictions you're under... this is all I'll contribute</p>\n<p>some general advice.... modern c++ does not, and should not look like c. The languages are different and have different philosophies. what is good in c is not always good in c++. so try to look out for things like that (eg. avoid raw arrays, use nullptr not NULL, little stuff like that.... to start with... this rabbit hole goes deep)</p>\n<p>PS. I'm looking forward to other people's answers, this promises to be entertaining...</p>\n<p>PPS. Also, take a look at factory design pattern and its variants (abstract factory, etc.) Actually, look up design patterns in general, it's interesting stuff, though YMMV... (edit) nice @indi's got it covered</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T12:48:23.687", "Id": "514136", "Score": "0", "body": "yeah you're right for the nullptr I forgot ^^ I'm not allowed to use vector neither" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T19:46:35.580", "Id": "260430", "ParentId": "260428", "Score": "3" } }, { "body": "<h1>Use all the power of the standard library</h1>\n<p>In your post on StackOverflow, you mentioned that you couldn't use <code>std::map</code> because you were not allowed to use it. Outside of the classroom, you should not limit yourself this way, and instead use the appropriate functions from the standard library that help you write concise and efficient code. The function <code>func()</code> could look like:</p>\n<pre><code>Form *func(std::string_view name)\n{\n static const std::unordered_map&lt;std::string_view, std::function&lt;Form*()&gt;&gt; forms = {\n {&quot;triangle&quot;, []{return new Triangle;}},\n {&quot;rectangle&quot;, []{return new Rectangle;}},\n ...\n };\n\n if (auto found = forms.find(name); found != forms.end()) {\n return found-&gt;second();\n } else {\n return nullptr;\n }\n}\n</code></pre>\n<p>And instead of raw pointers, you should probably return <code>std::unique_ptr&lt;Form&gt;</code>.\nIn the rest of the review I'm going to assume you are limited to what you can use.</p>\n<h1>Prefer using <code>= default</code></h1>\n<p>It's usually best to let the compiler generate default constructors, destructors and other operators. In some cases, you have to explicitly tell it to add one of those, for example when you want to ensure the destructor of <code>Form</code> is <code>virtual</code>. In that case, use <a href=\"https://stackoverflow.com/questions/20828907/the-new-syntax-default-in-c11\"><code>= default</code> instead of <code>{}</code></a>:</p>\n<pre><code>class Form\n{\npublic:\n virtual ~Form() = default;\n};\n</code></pre>\n<h1>Use <code>\\n</code> instead of <code>std::endl</code></h1>\n<p>Prefer using <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>\\n</code> instead of <code>std::endl</code></a>, the latter is equivalent to the former but also forces a flush of the output, which might be bad for performance if you are printing a lot.</p>\n<h1>Avoid unnnecessary parentheses and <code>void</code></h1>\n<p>You can simplify the <code>createForm()</code> functions a bit:</p>\n<pre><code>static Form *createForm()\n{\n return new Square;\n}\n</code></pre>\n<p>The unnecessary parentheses and <code>void</code> in the argument list are just unnecessary distractions here.</p>\n<h1>Move <code>s_makeForms</code> into <code>func()</code></h1>\n<p>You can move the definition of <code>struct s_makeForm</code> into <code>func()</code>, so it doesn't clutter the global namespace. In fact, you don't even have to give this struct a name, you can write:</p>\n<pre><code>Form *func(std::string &amp;name)\n{\n struct {\n std::string name;\n Form *(*createForm)();\n } forms[] = {\n &quot;triangle&quot;, Triangle::createForm},\n ...\n }\n\n ...\n}\n</code></pre>\n<h1>Prefer <code>const std::string &amp;</code> when passing string arguments</h1>\n<p>To avoid unnecessary copying of strings, prefer passing strings as <code>const</code> references:</p>\n<pre><code>Form *func(const std::string &amp;name)\n{\n ...\n}\n</code></pre>\n<h1>Avoid having to <code>#define NB_FORMS</code></h1>\n<p>You can get the size of the array <code>allForms</code> in various ways, the typical trick that works both in C and all versions of C++ is:</p>\n<pre><code>struct ... allForms[] = {...};\nsize_t numForms = sizeof allForms / sizeof *allForms;\n\nfor (size_t i = 0; i &lt; numForms; ++i)\n{\n ...\n}\n</code></pre>\n<p>You can also use a range-based <code>for</code>-loop to iterate over the array:</p>\n<pre><code>struct ... allForms[] = {...};\n\nfor (auto &amp;form: allForms)\n{\n if (name == form.formName)\n return form.makeForm();\n}\n</code></pre>\n<h1>Memory leak</h1>\n<p>There is a memory leak in your program, since you forgot to call <code>delete myform</code>. These kinds of errors can be avoided by using smart pointers, such as <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\"><code>std::unique_ptr</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T22:24:09.767", "Id": "514105", "Score": "3", "body": "Don't use the ancient `sizeof` trick to get an array size. That can malfunction in certain situations. Instead, use template argument deduction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T06:25:17.053", "Id": "514117", "Score": "2", "body": "@JDługosz Sure, we have `std::size()` in [C++17](https://en.cppreference.com/w/cpp/iterator/size) that does exactly what we want. But the `sizeof` trick should work just fine in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T12:42:34.590", "Id": "514133", "Score": "0", "body": "Hello thanks for your review. I'm gonna answer :\nFor the constructor, I must create it, my school asks, (same consrtaint than why I don't use maps)\nFor the std::endl, nice tips thanks !\nFor the void parentheses too ! nice thanks \n\nFor the delete you're right, sorry that was just a test code to show you my problem, and someone asked me to upload it on this site but I didn't pay attention to the leak\nThe struct is a nice trick and the reference for the string is very important yes my bad!\nThank's for you review bro I appreciate, I'm gonna improve my c++ now :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T13:59:04.180", "Id": "514145", "Score": "1", "body": "Ask your teacher to clarify: declaring the constructor using `=default` *is* defining it in the class. See if your teacher even knows about that ... is the textbook pre-2011? Is your instructor familiar with (or even know about) the _Standard Guidelines_ as I showed you in the post of mine you read earlier?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T14:01:28.293", "Id": "514146", "Score": "0", "body": "Did you know C already? If not, many of the things you showed ( like using #define and NULL) you should not even have been taught as a beginner. BTW, from your responses here, I think you will go on to learn C++ well, keep it up!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T23:10:45.493", "Id": "514165", "Score": "2", "body": "@G.Sliepen The problem with the `sizeof` trick is that it will compile just fine if the array has decayed into a pointer, but it will give you the wrong answer. `std::size()` (or a home-rollled version of it) will fail to compile in situations where they aren't correct. While it's fine here, it's good to teach beginners how to do things safely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T23:48:57.877", "Id": "514167", "Score": "1", "body": "@MilesBudnek: Or: `std::array<3, s_makeForms>`?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T19:56:53.780", "Id": "260432", "ParentId": "260428", "Score": "10" } }, { "body": "<h1>Design review</h1>\n<p>I’m not going to bother with a code review, because I see @G-Sliepen has already done an excellent job of that. Instead, I’m going to focus on a high-level design review.</p>\n<p>The name of the pattern you are using is the <strong>Factory</strong> pattern. The Factory pattern uses a single “make” function that takes an argument, and returns a different object type depending on the argument.</p>\n<p>For example:</p>\n<pre><code>class Base\n{\npublic:\n virtual ~Base() = default;\n};\n\nclass A : public Base {};\nclass B : public Base {};\nclass C : public Base {};\n\nenum class object_type\n{\n type_a,\n type_b,\n type_c,\n};\n\nauto factory_function(object_type type) -&gt; std::unique_ptr&lt;Base&gt;\n{\n switch (type)\n {\n case object_type::type_a:\n return std::make_unique&lt;A&gt;();\n case object_type::type_b:\n return std::make_unique&lt;B&gt;();\n case object_type::type_c:\n return std::make_unique&lt;C&gt;();\n }\n}\n</code></pre>\n<p>That’s basically exactly the problem you want to solve, except you don’t want to use <code>if</code> or <code>switch</code>, you want to use a map instead. That’s no problem; it doesn’t really change anything about the basic pattern.</p>\n<p>So the first thing you need to do is make your map. You’ve chosen to use a custom <code>struct</code> and a C array. Okay, first, forget the C array; that’s not just not up to par in modern C++. C arrays are broken in a lot of ways.</p>\n<p>So let’s start instead with your custom <code>struct</code> and a proper C++ array:</p>\n<pre><code>constexpr auto allForms = std::to_array&lt;s_makeForms&gt;({\n {&quot;triangle&quot;, Triangle::createForm},\n {&quot;rectangle&quot;, Rectangle::createForm},\n {&quot;square&quot;, Square::createForm}\n});\n</code></pre>\n<p>Now, the one major annoyance with this design as-is is that if you want to add a new shape, you have to write a boilerplate <code>createForm()</code> function for it. Every shape needs a <code>createForm()</code> function, even though it’s just brainless repetition. Unfortunately, it’s not just tedious, it’s also dangerous. Consider this:</p>\n<pre><code>class Ellipse : public Form\n{\npublic:\n Ellipse() { std::cout &lt;&lt; &quot;Ellipseee!\\n&quot;; }\n\n static auto createForm(void) -&gt; std::unique_ptr&lt;Form&gt;\n {\n return std::make_unique&lt;Ellipse&gt;();\n }\n};\n\nclass Circle : public Ellipse\n{\n Circle() { std::cout &lt;&lt; &quot;A circle is just a special case of ellipse.\\n&quot;; }\n\n // oops! forgot to make the createForm() function!\n}\n\n// ...\n\nconstexpr auto allForms = std::to_array&lt;s_makeForms&gt;({\n // ...\n {&quot;ellipse&quot;, Ellipse::createForm},\n {&quot;circle&quot;, Circle::createForm}\n});\n\n// ...\n\nauto main() -&gt; int\n{\n std::cout &lt;&lt; &quot;making a circle: &quot;;\n auto p_circle = func(&quot;circle&quot;);\n}\n\n// output:\n// making a circle: Ellipseee!\n</code></pre>\n<p>And that’s just one of many, many, many ways you could screw up while having to duplicate the <code>createForm()</code> machinery over and over again.</p>\n<p>There is no reason that every class needs to have a <code>createForm()</code> function. (At least, none that apply to the current code.) The only place that function is needed is in that map, so there’s no need to bog down the creation of new form types with the boilerplate.</p>\n<p>You could do this:</p>\n<pre><code>class Form\n{\npublic:\n virtual ~Form() = default;\n};\n\nclass Rectangle : public Form\n{\npublic:\n // Rectangle needs only the functions necessary to be a rectangle\n Rectangle() { std::cout &lt;&lt; &quot;Rectangleee!\\n&quot;; }\n};\n\nclass Square : public Form\n{\npublic:\n // Square needs only the functions necessary to be a square\n Square() { std::cout &lt;&lt; &quot;Squareee!\\n&quot;; }\n};\n\nclass Triangle : public Form\n{\npublic:\n // ... and so on...\n Triangle() { std::cout &lt;&lt; &quot;Triangleee!\\n&quot;; }\n};\n\nclass Ellipse : public Form\n{\npublic:\n Ellipse() { std::cout &lt;&lt; &quot;Ellipseee!\\n&quot;; }\n};\n\nclass Circle : public Form\n{\npublic:\n Circle() { std::cout &lt;&lt; &quot;Circleee!\\n&quot;; }\n};\n\n// detail namespace to hide implementation details\nnamespace detail_ {\n\nauto create_rectangle() -&gt; std::unique_ptr&lt;Form&gt; { return std::make_unique&lt;Rectangle&gt;(); }\nauto create_square() -&gt; std::unique_ptr&lt;Form&gt; { return std::make_unique&lt;Square&gt;(); }\nauto create_triangle() -&gt; std::unique_ptr&lt;Form&gt; { return std::make_unique&lt;Triangle&gt;(); }\nauto create_ellipse() -&gt; std::unique_ptr&lt;Form&gt; { return std::make_unique&lt;Ellipse&gt;(); }\nauto create_circle() -&gt; std::unique_ptr&lt;Form&gt; { return std::make_unique&lt;Circle&gt;(); }\n\n} // namespace detail_\n\nauto func(std::string_view name) -&gt; std::unique_ptr&lt;Form&gt;\n{\n using create_func_t = auto (*)() -&gt; std::unique_ptr&lt;Form&gt;;\n\n struct value_t\n {\n std::string_view name;\n create_func_t func;\n };\n\n static constexpr auto all_forms = std::to_array&lt;value_t&gt;({\n {&quot;rectangle&quot;, detail_::create_rectangle},\n {&quot;square&quot;, detail_::create_square},\n {&quot;triangle&quot;, detail_::create_triangle},\n {&quot;ellipse&quot;, detail_::create_ellipse},\n {&quot;circle&quot;, detail_::create_circle},\n });\n\n if (auto p = std::ranges::find(all_forms, name, &amp;value_t::name); p != all_forms.end())\n return (p-&gt;func)();\n else\n return nullptr;\n}\n</code></pre>\n<p>But that’s still too much repetition. So rather than using free functions (albeit in a detail namespace), let’s use lambdas:</p>\n<pre><code>class Form\n{\npublic:\n virtual ~Form() = default;\n};\n\nclass Rectangle : public Form\n{\npublic:\n // Rectangle needs only the functions necessary to be a rectangle\n Rectangle() { std::cout &lt;&lt; &quot;Rectangleee!\\n&quot;; }\n};\n\nclass Square : public Form\n{\npublic:\n // Square needs only the functions necessary to be a square\n Square() { std::cout &lt;&lt; &quot;Squareee!\\n&quot;; }\n};\n\nclass Triangle : public Form\n{\npublic:\n // ... and so on...\n Triangle() { std::cout &lt;&lt; &quot;Triangleee!\\n&quot;; }\n};\n\nclass Ellipse : public Form\n{\npublic:\n Ellipse() { std::cout &lt;&lt; &quot;Ellipseee!\\n&quot;; }\n};\n\nclass Circle : public Form\n{\npublic:\n Circle() { std::cout &lt;&lt; &quot;Circleee!\\n&quot;; }\n};\n\nauto func(std::string_view name) -&gt; std::unique_ptr&lt;Form&gt;\n{\n using create_func_t = auto (*)() -&gt; std::unique_ptr&lt;Form&gt;;\n\n struct value_t\n {\n std::string_view name;\n create_func_t func;\n };\n\n static constexpr auto all_forms = std::to_array&lt;value_t&gt;({\n {&quot;rectangle&quot;, [] { return std::unique_ptr&lt;Form&gt;{new Rectangle{}}; }},\n {&quot;square&quot;, [] { return std::unique_ptr&lt;Form&gt;{new Square{}}; }},\n {&quot;triangle&quot;, [] { return std::unique_ptr&lt;Form&gt;{new Triangle{}}; }},\n {&quot;ellipse&quot;, [] { return std::unique_ptr&lt;Form&gt;{new Ellipse{}}; }},\n {&quot;circle&quot;, [] { return std::unique_ptr&lt;Form&gt;{new Circle{}}; }},\n });\n\n if (auto p = std::ranges::find(all_forms, name, &amp;value_t::name); p != all_forms.end())\n return (p-&gt;func)();\n else\n return nullptr;\n}\n</code></pre>\n<p>Adding a new form is now virtually foolproof. Just:</p>\n<ol>\n<li>Create the new class. Be sure to publicly inherit from <code>Form</code>, either directly or indirectly, but that’s all you need to do; there are no other functions you need to implement.</li>\n<li>Add a new line in the <code>all_forms</code> array. Just a string and a simple lambda: <code>[] { return std::unique_ptr&lt;Form&gt;{new CLASS_NAME_HERE{}}; }</code>.</li>\n</ol>\n<p>While I generally abhor macros, you could even make use of one here to make things even simpler:</p>\n<pre><code>#define YOUR_PREFIX_FORM(name, class) {name, [] { return std::unique_ptr&lt;Form&gt;{new class{}}; }}\n\nauto func(std::string_view name) -&gt; std::unique_ptr&lt;Form&gt;\n{\n using create_func_t = auto (*)() -&gt; std::unique_ptr&lt;Form&gt;;\n\n struct value_t\n {\n std::string_view name;\n create_func_t func;\n };\n\n static constexpr auto all_forms = std::to_array&lt;value_t&gt;({\n YOUR_PREFIX_FORM(&quot;rectangle&quot;, Rectangle),\n YOUR_PREFIX_FORM(&quot;square&quot;, Square),\n YOUR_PREFIX_FORM(&quot;triangle&quot;, Triangle),\n YOUR_PREFIX_FORM(&quot;ellipse&quot;, Ellipse),\n YOUR_PREFIX_FORM(&quot;circle&quot;, Circle)\n });\n\n if (auto p = std::ranges::find(all_forms, name, &amp;value_t::name); p != all_forms.end())\n return (p-&gt;func)();\n else\n return nullptr;\n}\n\n#undef YOUR_PREFIX_FORM\n</code></pre>\n<p>Now adding a new form is even more trivial. Just create the class (make sure <code>Form</code> is one of its public bases), then add a new line in the <code>all_forms</code> array that’s just “<code>YOUR_PREFIX_FORM(name, class)</code>”. That’s it.</p>\n<p>If the list of forms got huge, and you wanted to get clever, you could have the <code>all_forms</code> array compile-time sorted, and then use <code>std::ranges::lower_bound()</code> rather than <code>std::ranges_find()</code>. At the same time you’re sorting, you could also do other compile-time checks, like making sure that all the strings are unique. But that’s getting <em>way</em> beyond the scope of things here.</p>\n<p>Let me repeat the code I’ve suggested all together here, just to have it all in one place:</p>\n<pre><code>// base class\nclass Form\n{\npublic:\n virtual ~Form() = default;\n\n // add any other interface functions here as pure virtual functions\n};\n\n// all concrete forms just need to derive from Form, and implement any of the\n// pure virtual functions (there are none now, but there could be some)\n\n// a simple concrete form:\nclass Rectangle : public Form {};\n\n// yes, the above is all you need to create a new concrete form (at least for\n// now, as long as there are no pure virtual functions to implement)\n//\n// but of course, you could add custom constructors, and any other stuff to\n// the concrete form classes that you like\n\n// and this is your factory function:\n#define YOUR_PREFIX_FORM(name, class) {name, [] { return std::unique_ptr&lt;Form&gt;{new class{}}; }}\n\nauto func(std::string_view name) -&gt; std::unique_ptr&lt;Form&gt;\n{\n using create_func_t = auto (*)() -&gt; std::unique_ptr&lt;Form&gt;;\n\n struct value_t\n {\n std::string_view name;\n create_func_t func;\n };\n\n static constexpr auto all_forms = std::to_array&lt;value_t&gt;({\n YOUR_PREFIX_FORM(&quot;rectangle&quot;, Rectangle),\n\n // add as many cases here as you like\n //\n // you could even do stuff like have aliases (like both &quot;square&quot; and\n // &quot;regular quadrilateral&quot; will return a new Square), or other tricks\n // (like &quot;rectangle&quot; and &quot;square&quot; both return new Rectangles...\n // because a square *is* a rectangle... except &quot;square&quot; returns a new\n // Rectangle with all sides equal; you'd need to tweak the macro to do\n // stuff like this, but it's not too challenging to do)\n });\n\n if (auto p = std::ranges::find(all_forms, name, &amp;value_t::name); p != all_forms.end())\n return (p-&gt;func)();\n else\n return nullptr;\n}\n\n// always clean up your macro mess\n#undef YOUR_PREFIX_FORM\n</code></pre>\n<p>Note that the code as I’ve written it uses some C++20 stuff… but it doesn’t really <em>need</em> to. You could implement the whole thing even in C++98, but it would be slower, it wouldn’t work at compile-time, you’d have to reimplement a lot of the stuff yourself, and everything would be much, much more verbose. But you could do it. (You could also do it in C++11, C++14, or C++17, and the more modern the version you use, the less work you’ll have to do.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T22:14:57.493", "Id": "514104", "Score": "0", "body": "I hope your use of right-return syntax doesn't alienate or confuse the OP too much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T12:46:27.830", "Id": "514135", "Score": "0", "body": "Thank you but that was just a simple test code, and not a real code, I appreciate your efforts to show me the factory pattern! thanks bro" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T19:48:40.377", "Id": "514160", "Score": "0", "body": "If you use macros (which I would, too, for this kind of work) you can as well use a map; and create the strings from the class name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T07:27:31.270", "Id": "514176", "Score": "0", "body": "You should usually prefer `std::make_unique<Class>()` to `std::unique_ptr<Class>{new Class}`. (For example, if you have two instances within a single full expression, and there's a possibility one of the constructors could throw an exception, then the latter has a possible memory leak depending on how the compiler orders operations, but the former is safe.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:12:21.233", "Id": "514206", "Score": "1", "body": "@DanielSchepler First, your concern about exception safety is no longer relevant (since C++17); `unique_ptr{new T}` is exactly as safe as `make_unique<T>()`… and the former is faster in some cases (hence `make_unique_for_overwrite<T>()`). Second, look closer. It’s not `unique_ptr<Class>{new Class}` (which would be redundant; you could just do `unique_ptr{new Class}`). It’s `unique_ptr<Base>{new Derived}`. To get consistent deduction with the lambda return, you either have to do that, or `make_unique()` then cast… `unique_ptr<Base>{make_unique<Derived>()}`… which would be silly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T12:40:20.940", "Id": "514540", "Score": "1", "body": "Note that `class Circle : public Ellipse` is a common trap that OO beginners fall into: because \"Circle is-a Ellipse\" in mathematics, they think that means circle should be a subclass of ellipse. But in OO design, the relationship is closer to the other way around (ellipse is a circle with additional behaviour). But neither are a good fit, and being sibling classes is usually best. Geometrical shapes are actually quite a poor teaching aid for class design!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T14:17:14.160", "Id": "514542", "Score": "0", "body": "@indi Can you point to the rule that eliminates the safety concerns that gave rise to `make_unique`? [C.150](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c150-use-make_unique-to-construct-objects-owned-by-unique_ptrs) and [R.23](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-make_unique) are still in the Guidelines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T20:33:49.773", "Id": "514571", "Score": "2", "body": "@JDługosz If you want a standard reference, it’s [[expr.call]/8](https://timsong-cpp.github.io/cppwp/expr.call#8)… but of course it’s standardese, so it’s going to be opaque; you need to understand what “indeterminately sequenced” means. For that, there’s [[intro.execution]/8](https://timsong-cpp.github.io/cppwp/intro.execution#8), which explains in a note: “**cannot overlap**, but either can be executed first”. See [here (“Stricter order of expression evaluation”)](http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0636r0.html) to verify that the change came in C++17." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T20:33:53.797", "Id": "514572", "Score": "0", "body": "@TobySpeight Hm, interesting. Honestly, I’ve never used shapes when teaching OO myself… but then again, I generally haven’t had to teach OO, because most of the people I teach already know it (usually from learning Java). I usually have to spend more time *unteaching* them OO. Your point about how an inheritance relation doesn’t make sense here is actually great teaching point in that direction." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T21:03:02.137", "Id": "260436", "ParentId": "260428", "Score": "7" } }, { "body": "<p>It looks like others already covered everything I noticed, except for the way you position the <code>*</code> in a declaration.</p>\n<p>From the beginning, C++ has used the style of putting the pointer (or ref) mark <em>with the type</em> not with the variable.</p>\n<pre><code>Form* myform;\n</code></pre>\n<p>And looking at the <code>main</code> function where this example came from, notice that it is not being initialized, though it is assigned on the next line. Always initialize variables when they are declared, if you can.</p>\n<pre><code>Form *myform = func(&quot;square&quot;);\nif (!myform)\n{\n std::cerr &lt;&lt; &quot;wrong name\\n&quot;;\n}\n</code></pre>\n<hr />\n<p>The <code>return</code> keyword is not a function call! Don't put parens around the entire return value. This has gone from a matter of style (redundant parens in an expression that don't change the meaning) to a <em>real</em> issue, as the compiler recognises a simple bare local variable and automatically invokes <em>move</em> semantics. So <code>return val;</code> is correct and <code>return (val);</code> defeats this automatic optimization.</p>\n<hr />\n<p>Don't use the C NULL macro. In C++ there is a keyword <code>nullptr</code> as a proper part of the language.</p>\n<p>Look at your function:</p>\n<pre><code>Form *func(std::string name)\n{\n struct s_makeForms allForms[3] =\n {\n {&quot;triangle&quot;, Triangle::createForm}, \n {&quot;rectangle&quot;, Rectangle::createForm},\n {&quot;square&quot;, Square::createForm}\n };\n for (int i = 0; i &lt; NB_FORMS; i++)\n {\n if (name == allForms[i].formName)\n return (allForms[i].makeForm());\n }\n return (NULL);\n}\n</code></pre>\n<p>You are passing in <code>name</code> <em>by value</em> when there is no reason to copy the string! This should be <code>const std::string&amp;</code> as a matter of course! However, you can use <code>string_view</code> for parameters and get greater efficiency for passing arguments of either <code>string</code> or lexical string literals (like <code>&quot;rectangle&quot;</code>) without having to copy that into a <code>string</code> first.</p>\n<pre><code>Form* func(std::string_view name)\n</code></pre>\n<p>You don't need the <code>3</code> when sizing the array. The compiler will count the initializers.\nAlso, the structure should be moved into the function, as it is only used there and has no purpose for any other code. Oh, and you don't need <code>struct</code> in front of the name when using the type! Oh again, the array should be static so you're not making it again on every call, and const since you don't change it, but together you just use <code>constexpr</code>.</p>\n<pre><code> struct s_makeForms\n {\n std::string formName;\n Form* (*makeForm)();\n };\n constexpr s_makeForms allForms[] = {\n {&quot;triangle&quot;, Triangle::createForm}, \n {&quot;rectangle&quot;, Rectangle::createForm},\n {&quot;square&quot;, Square::createForm}\n };\n</code></pre>\n<p>Now you don't need the number of elements in the array for the loop, either:</p>\n<pre><code> for (auto&amp; rec : allForms)\n {\n if (name == rec.formName)\n return rec.makeForm();\n }\n</code></pre>\n<p>Notice that you don't need to repeat the <code>allForms[i]</code> as you do in the original. In general you don't want to repeat the navigation into a collection, though in the case of a primitive array the compiler might optimize it anyway, especially if you had made it <code>const</code>.</p>\n<p>Finally, if you drop out of the loop:</p>\n<pre><code>return nullptr;\n</code></pre>\n<p>no extra parens, and use the built-in keyword, not the ancient C macro.</p>\n<p>These issues can of course be combined with other improvements, such as using lambdas directly in the initializer rather than separate static members for each Form.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T12:52:57.903", "Id": "514137", "Score": "0", "body": "For the place of the pointer, is it different from the C ? I was used to do\nint *a; because we could do int *a, *b, int *c\n\nFor the nullptr, yes you're right thanks !\n\nFor the auto &rec; I didn't know this method that's cool thanks, I'll try to use it in the future, and the const &string, also ! Thanks bro \nI already answered to all the previous posts so I don't have a lot of things to tell to you, but in general thank you for asking me to post my code here, so that I could see all the mistakes !\n\nThank you bro ! see you soon" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T13:50:34.420", "Id": "514143", "Score": "0", "body": "Pointers: don't do that in C++. Write them as separate lines (with initializers). `int* a = foo(); int* b= nullptr; int* c= whatever;` Yes, in the original 1987 book Stroustrup intentionally did it differently than in C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T13:54:11.560", "Id": "514144", "Score": "0", "body": "If you didn't know about `auto` and/or the range-based `for` loop, I suspect your textbook or tutorial you're following is simply too old. You need teaching material made after 2011. C++11 is substantially different and lends itself to different best practices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T12:13:11.793", "Id": "514318", "Score": "0", "body": "i'm currently working on c++98" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T13:40:09.867", "Id": "514323", "Score": "0", "body": "Why are you using a compiler that's at least 10 years old? BTW, the next update to the standard was C++03, so maybe you meant \"pre-2011\" rather than something that didn't get patches and bug fixes since 2003." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T07:38:35.823", "Id": "514525", "Score": "0", "body": "my school asks me to use c++98 in the first projects !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T13:58:50.183", "Id": "514541", "Score": "0", "body": "@sapristi12 ask if you need to turn that in on [Hollerith cards](https://en.wikipedia.org/wiki/Punched_card#The_Hollerith_card). I question the utility of learning things that you will need to un-learn to write real code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T14:16:29.510", "Id": "514612", "Score": "0", "body": "Do you blame people who learn a low-level language when they end up working on javascript?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T14:32:37.807", "Id": "514615", "Score": "0", "body": "I don't understand the remark. Do you want to learn Javascript on I.E. 6 in class, when that's no longer how it's done for real projects?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T22:10:45.623", "Id": "260439", "ParentId": "260428", "Score": "2" } } ]
{ "AcceptedAnswerId": "260432", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T18:43:51.053", "Id": "260428", "Score": "2", "Tags": [ "c++", "object-oriented" ], "Title": "Return correct subclass instance, identified by string" }
260428
<p>Is there any way to reduce this code? It repeats itself, but I cannot find any way to reduce it because it is only repeating inside one elif. Sorry I'm a beginner my code is quite bad It repeats here:</p> <pre><code> onze(joueurs) print(&quot;joueur&quot;, a + 1, &quot;a&quot;, joueurs[a]) time.sleep(1) while sum(joueurs[a]) &lt; 21 or 11 in joueurs[a]: </code></pre> <p>The code :</p> <pre><code>while t: input(&quot;Appuyez sur entrer pour continuer...&quot;) for a in range(nb): while sum(joueurs[a]) &lt; 21 or 11 in joueurs[a]: time.sleep(0.5) print(&quot;main du joueur&quot;, a + 1, &quot;:&quot;, joueurs[a], &quot;Total :&quot;, sum(joueurs[a])) if sum(joueurs[a]) &gt; 21 and 11 in joueurs[a]: onze(joueurs) print(&quot;joueur&quot;, a + 1, &quot;a&quot;, joueurs[a]) ask = input(&quot;Joueur {} voulez vous une carte ?(oui/non)&quot;.format(a + 1)) if ask == &quot;oui&quot;: askoui(joueurs) else: asknon() t = False break if sum(joueurs[a]) == 21: print(&quot;joueur&quot;, a + 1, &quot;a BLACKJACK&quot;) time.sleep(1) elif sum(joueurs[a]) &gt; 21 and 11 in joueurs[a]: onze(joueurs) print(&quot;joueur&quot;, a + 1, &quot;a&quot;, joueurs[a]) time.sleep(1) while sum(joueurs[a]) &lt; 21 or 11 in joueurs[a]: time.sleep(0.5) print(&quot;main du joueur&quot;, a + 1, &quot;:&quot;, joueurs[a], &quot;Total :&quot;, sum(joueurs[a])) if sum(joueurs[a]) &gt; 21 and 11 in joueurs[a]: onze(joueurs) print(&quot;joueur&quot;, a + 1, &quot;a&quot;, joueurs[a]) ask = input(&quot;Joueur {} voulez vous une carte ?(oui/non)&quot;.format(a + 1)) if ask == &quot;oui&quot;: askoui(joueurs) else: asknon() t = False break elif sum(joueurs[a]) &gt; 21: perdu(joueurs) t = False elif sum(joueurs[a]) &gt; 21: perdu(joueurs) t = False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T07:20:01.313", "Id": "514119", "Score": "1", "body": "you can always put code in function and use this function. But for two lines it can be better to keep current version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T14:40:15.853", "Id": "514148", "Score": "0", "body": "Could you share your whole code? That would make it easier to give advice." } ]
[ { "body": "<p>It's &quot;Pythonic&quot; to iterate through items, so assuming that <code>len(joueurs) == nb</code>, your main <code>for</code> loop can be:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for a, joueur in enumerate(joueurs):\n</code></pre>\n<p>which means all your <code>joueurs[a]</code> become <code>joueur</code>. I'm quite surprised that <code>onze</code>, <code>askoui</code> and <code>perdu</code> functions take the whole <code>joueurs</code> list, not just the current player. How does that work?</p>\n<p>I'd guess that the check for possible <code>onze</code> action, which I take it is converting an ace down from 11 points to 1, could more comfortably fit within the <code>askoui</code> function when our current player gets another card, non? Then this main routine could just check against 21, or perhaps even better the <code>askoui</code> function could return a status value.</p>\n<p>Difficult to be more specific without getting into some of these auxiliary functions. Here's my best guess at a reduced code that I think should do the same as you presently have, plus some outstanding issues:</p>\n<pre class=\"lang-py prettyprint-override\"><code>while t:\n input(&quot;Appuyez sur entrer pour continuer...&quot;)\n for ix, jr in enumerate(joueurs):\n jID = ix+1\n while sum(jr) &lt; 21:\n time.sleep(0.5)\n print(&quot;main du joueur&quot;, jID, &quot;:&quot;, jr, &quot;Total :&quot;, sum(jr))\n ask = input(&quot;Joueur {} voulez vous une carte ?(oui/non)&quot;.format(jID))\n if ask == &quot;oui&quot;:\n askoui(joueurs) # why all joueurs?\n if sum(jr) &gt; 21 and 11 in jr:\n onze(joueurs) # why all joueurs?\n else:\n asknon()\n t = False # immediate halt to play for all players?\n break\n if sum(jr) == 21:\n print(&quot;joueur&quot;, jID, &quot;a BLACKJACK&quot;)\n time.sleep(1) # then play continues\n elif sum(jr) &gt; 21:\n perdu(joueurs) # why all joueurs?\n t = False\n # play continues without message if sum(jr)&lt;21 ?\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T19:12:22.587", "Id": "514678", "Score": "0", "body": "Thanks for your time, I couldn't post all my code because Stackexchange lock the amount of code that can be posted. I understood your idea and I think I could make that work. I'll get back to you as soon as I try ! thanks for your answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T00:10:10.727", "Id": "260477", "ParentId": "260431", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T19:55:12.660", "Id": "260431", "Score": "2", "Tags": [ "python", "beginner", "playing-cards" ], "Title": "Main loop for a text-based Blackjack game" }
260431
<p>Apologies for the cryptic title, but the problem really is rather simple.</p> <p>I have a 64 bit integer which I interpret as 16 4 bit nibbles, or a nibble array if you wish, and I needed generate a mask covering the nibbles which are zero, or the inverse.</p> <p>I have already come up with a solution, but it seems to me that there has to be a better way.</p> <pre><code>uint64_t getNonZeroMask( uint64_t b ) { return ( ( ( b &gt;&gt; 2 | b ) &gt;&gt; 1 | ( b &gt;&gt; 2 | b ) ) &amp; 0x1111111111111111 ) * 15; } </code></pre> <p>The above is the most efficient I've found. I've tried numerous approaches, but they pretty much all use the same approach.</p> <p>Just in case there should be any doubt what exactly I'm frying to do, a give value: ex.</p> <pre class="lang-none prettyprint-override"><code>0x010203456000abc0 </code></pre> <p>Should give the mask:</p> <pre class="lang-none prettyprint-override"><code>0x0f0f0ffff000fff0 </code></pre> <p>or the inverse.</p> <p>What I have works, of course, but I do believe it can be done better, and I'd very much like to know how. Preferably it would only involve bitwise operations. Intrinsics from bmi and similar are okay, but I haven't found anything that seems useful. It may be that I'm entirely in the wrong, and this is indeed the way of doing it, in which case I'd very much like to know that too.</p>
[]
[ { "body": "<blockquote>\n<p>Intrinsics from bmi and similar are okay, but I haven't found anything that seems useful.</p>\n</blockquote>\n<p>They're not very useful for this. <code>pdep</code> and <code>pext</code> let you do this in a <em>different</em> way, but it's not better (<em>especially</em> not on AMD Zen1), you shouldn't use this (but maybe it's interesting to think about):</p>\n<pre><code>uint64_t m = 0x1111111111111111;\nuint64_t stacked = _pext_u64(b, m) | _pext_u64(b, m &lt;&lt; 1) |\n _pext_u64(b, m &lt;&lt; 2) | _pext_u64(b, m &lt;&lt; 3);\nreturn _pdep_u64(stacked, m) * 15;\n</code></pre>\n<p>There is a slightly different way to write the original logic in a way that may be easier to read, of course that's subjective but it will be as a straight-line composition of common bitwise idioms, it shouldn't make any difference for a compiler. It's the same thing really, but instead of being a single expression it's linearized into discrete steps, which also creates the opportunity for in-line comments to explain the steps:</p>\n<pre><code>uint64_t getNonZeroMask( uint64_t b )\n{\n // horizontal OR of nibbles in log(bits) steps\n b |= b &gt;&gt; 2;\n b |= b &gt;&gt; 1;\n // remove polluted bits, leaving the results in the lsb of every nibble\n b &amp;= 0x1111111111111111;\n // spread single bit flags into full nibbles\n return b * 15;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T02:52:19.163", "Id": "260442", "ParentId": "260434", "Score": "3" } }, { "body": "<h3>This might be faster than your solution.</h3>\n<pre><code>#include &lt;stdio.h&gt;\n\ntypedef struct __attribute__((__packed__)) {\n unsigned int N0 : 4;\n unsigned int N1 : 4;\n unsigned int N2 : 4;\n unsigned int N3 : 4;\n unsigned int N4 : 4;\n unsigned int N5 : 4;\n unsigned int N6 : 4;\n unsigned int N7 : 4;\n unsigned int N8 : 4;\n unsigned int N9 : 4;\n unsigned int NA : 4;\n unsigned int NB : 4;\n unsigned int NC : 4;\n unsigned int ND : 4;\n unsigned int NE : 4;\n unsigned int NF : 4;\n} SIXTEENNIBBLES;\n\ntypedef union __attribute__((__packed__)) {\n unsigned long QWORD : 64;\n SIXTEENNIBBLES NIBBLE;\n} QWONI; /* QWORD-NIBBLES */\n\nQWONI createmask(QWONI qwoni) {\n QWONI mask;\n mask.QWORD = 0x0000000000000000;\n if(qwoni.NIBBLE.N0) mask.NIBBLE.N0 = 0xF;\n if(qwoni.NIBBLE.N1) mask.NIBBLE.N1 = 0xF;\n if(qwoni.NIBBLE.N2) mask.NIBBLE.N2 = 0xF;\n if(qwoni.NIBBLE.N3) mask.NIBBLE.N3 = 0xF;\n if(qwoni.NIBBLE.N4) mask.NIBBLE.N4 = 0xF;\n if(qwoni.NIBBLE.N5) mask.NIBBLE.N5 = 0xF;\n if(qwoni.NIBBLE.N6) mask.NIBBLE.N6 = 0xF;\n if(qwoni.NIBBLE.N7) mask.NIBBLE.N7 = 0xF;\n if(qwoni.NIBBLE.N8) mask.NIBBLE.N8 = 0xF;\n if(qwoni.NIBBLE.N9) mask.NIBBLE.N9 = 0xF;\n if(qwoni.NIBBLE.NA) mask.NIBBLE.NA = 0xF;\n if(qwoni.NIBBLE.NB) mask.NIBBLE.NB = 0xF;\n if(qwoni.NIBBLE.NC) mask.NIBBLE.NC = 0xF;\n if(qwoni.NIBBLE.ND) mask.NIBBLE.ND = 0xF;\n if(qwoni.NIBBLE.NE) mask.NIBBLE.NE = 0xF;\n if(qwoni.NIBBLE.NF) mask.NIBBLE.NF = 0xF;\n return mask;\n}\n\nint main(int argc, char *argv[]){\n QWONI mynibbles;\n mynibbles.QWORD = 0x010203456000abc0;\n \n printf(&quot;sizeof(mynibbles) = %d\\n&quot;, sizeof(mynibbles));\n printf(&quot;mynibbles.QWORD = %llx\\n&quot;, mynibbles.QWORD);\n printf(&quot;createmask(mynibbles).QWORD = %llx\\n&quot;, createmask(mynibbles).QWORD);\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T17:23:32.950", "Id": "260461", "ParentId": "260434", "Score": "2" } } ]
{ "AcceptedAnswerId": "260442", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T20:39:24.997", "Id": "260434", "Score": "2", "Tags": [ "c", "bitwise" ], "Title": "Generate mask for non zero (or inverse) nibbles in integer" }
260434
<p>Standard code review, tell me what's good, what's bad, and how to improve. Critical suggestions welcomed. This is a content aggregator using bs4 and requests. I did not use any tutorials or help.</p> <pre><code>import requests from bs4 import BeautifulSoup as bs topic = input('Enter the topic: ').lower() print() def getdata(url, headers): r = requests.get(url, headers=headers) return r.text def linesplit(): print('-~'*16, 'COLIN IS MOOCH', '-~'*16, '\n') headers = { 'User-agent': &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582&quot; } google = getdata(f'https://www.google.com/search?q={topic}&amp;oq={topic}&amp;aqs=chrome..69i59j69i57j69i59j69i60l3j69i65j69i60.2666j0j7&amp;sourceid=chrome&amp;ie=UTF-8', headers) soup = bs(google, 'html.parser') links = str(soup.find_all('div', class_='TbwUpd NJjxre')) links = links.replace('&lt;div class=&quot;TbwUpd NJjxre&quot;&gt;&lt;cite class=&quot;iUh30 Zu0yb qLRx3b tjvcx&quot;&gt;', '') links = links.replace('&lt;span class=&quot;dyjrff qzEoUe&quot;&gt;', '') links = links.replace('&lt;/span&gt;&lt;/cite&gt;&lt; /div&gt;', '') links = links.replace('&lt;div class=&quot;TbwUpd NJjxre&quot;&gt;&lt;cite class=&quot;iUh30 Zu0yb tjvcx&quot;&gt;', '') links = links.replace('&lt;/cite&gt;&lt;/div&gt;', '') links = links.replace('&lt;/span&gt;', '') links = links.replace(' › ', '/') links = links.split(', ') links[-1] = links[-1].replace(']', '') links[0] = links[0].replace('[', '') info = [] counter = 0 for x in range(len(links)): try: htmldata = getdata(links[x], headers) newsoup = bs(htmldata, 'html.parser') website = '' for i in newsoup.find_all('p'): website = website + ' ' + i.text info.append(links[x]) info.append(website) counter += 1 except Exception: continue try: for x in range(0, (counter * 2) + 2, 2): if info[x+1] != '': linesplit() print() print('From ', info[x], ':') print() print(info[x+1]) linesplit() except IndexError: pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T21:54:33.720", "Id": "514103", "Score": "0", "body": "Why not use the API?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T22:54:45.113", "Id": "514107", "Score": "0", "body": "Which API? I didn't know there was one." } ]
[ { "body": "<p>Your <code>linesplit</code> is... strange? I'm going to ignore that message and pretend it makes sense.</p>\n<p>Whenever there's an API, prefer it. In this case Google has a Custom Search API that allows you to skip past all of the scraping insanity. You'll need to get an API key and configure an engine instance to search the whole web. The front-end of such an application, without including your second &quot;scrape all of the paragraphs&quot; step, looks like:</p>\n<pre><code>from typing import Iterable\nfrom requests import Session\n\n\n# To set a custom search engine to search the entire web, read\n# https://support.google.com/programmable-search/answer/4513886\nAPI_KEY = '...'\nENGINE_ID = '...'\n\n\ndef api_get(session: Session, query: str) -&gt; Iterable[str]:\n with session.get(\n 'https://customsearch.googleapis.com/customsearch/v1',\n headers={'Accept': 'application/json'},\n params={\n 'key': API_KEY,\n 'cx': ENGINE_ID,\n 'q': query,\n }\n ) as resp:\n resp.raise_for_status()\n body = resp.json()\n\n for item in body['items']:\n yield item['link']\n\n\ndef main():\n topic = input('Enter the topic: ').lower()\n\n with Session() as session:\n urls = api_get(session, topic)\n\n print('\\n'.join(urls))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T01:01:39.863", "Id": "260441", "ParentId": "260437", "Score": "2" } } ]
{ "AcceptedAnswerId": "260441", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T21:12:47.280", "Id": "260437", "Score": "0", "Tags": [ "beginner", "python-3.x", "beautifulsoup" ], "Title": "Content aggregator using bs4 and requests" }
260437
<p>I wrote a fileupload function for my application. Basically the application is a web based folder structure, which has files included.</p> <p>I don't know, but I am not happy with it. Is it too long? Can I do some parts easier? Is the logging ok? So many questions... The FileModel is inerhiting from ParentModel.</p> <pre><code> public ActionResult FileUpload() { int id = Convert.ToInt32(base.Request.Form[&quot;id&quot;]); bool isJson = Convert.ToBoolean(base.Request.Form[&quot;isJson&quot;]); try { if (id &lt; 1) { id = Convert.ToInt32(base.Request.Form[&quot;folderId&quot;]); } if (id &lt; 1) { Logging.LogToFile(&quot;Could not load &quot; + id &quot;.&quot;, 3); base.Response.StatusCode = 500; return Json(new { success = false, errFileUploadMsg = string.Concat(DateTime.Now, &quot; Folder ID &quot;, id, &quot; couldn't load. Please try again.&quot;) }, JsonRequestBehavior.AllowGet); } ParentModel pm = new ParentModel { Files = new Files() }; Files fm = pm.Files; int lastPosition = _mainFolderRepository.GetLastNumberOfFileInFolder(id); int position = ((lastPosition.GetType() != typeof(DBNull)) ? (lastPosition + 1) : 0); for (int i = 0; i &lt; base.Request.Files.Count; i++) { HttpPostedFileBase file = base.Request.Files[i]; Stream str = base.Request.Files[i].InputStream; BinaryReader br = new BinaryReader(str); byte[] FileBytes = br.ReadBytes((int)str.Length); fm.FullTextSearch = &quot;&quot;; fm.File = FileBytes; fm.ContentLength = file.ContentLength; fm.FileName = Path.GetFileName(file.FileName); if (Regex.IsMatch(fm.FileName, &quot;\\d+_\\d+&quot;)) { string[] fileNameSections = Path.GetFileNameWithoutExtension(fm.FileName).Split(' ')[0].Split('_'); if (fileNameSections[0].All(char.IsDigit) &amp;&amp; fileNameSections[1].All(char.IsDigit)) { fm.FileName = fm.FileName.Replace(&quot;_&quot;, &quot;/&quot;); } } if (_mainFolderRepository.IsFileNameInFolder(id, fm.FileName)) { int fileIdForChange = _mainFolderRepository.GetFileId(id, fm.FileName); _mainFolderRepository.UpdateFile(fileIdForChange, fm.File, fm.ContentLength); } else { if (!Helper.CheckIfExtensionStringAllowed(Path.GetExtension(file.FileName).ToLower())) { throw new FileFormatException(fm.Extension); } fm.Extension = Path.GetExtension(file.FileName).ToLower(); if ((fm.Extension == &quot;.pdf&quot; || fm.Extension == &quot;.doc&quot; || fm.Extension == &quot;.docx&quot;) &amp;&amp; fm.File.Length != 0) { fm.VolltextSuche = ConverterController.ConvertFileToText(fm.File, fm.FileName, fm.Extension); } _mainFolderRepository.FileUpload(fm.File, fm.ContentLength, fm.FileName, &quot;&quot;, &quot;&quot;, base.User.Identity.Name, DateTime.Now, isPublic: false, fm.Extension, id, fm.RessortId, position, fm.FullTextSearch, &quot;&quot;); } position++; } } catch (FileFormatException ex) { Logging.LogToFile(ex, 3); if (!isJson) { base.TempData[&quot;Error&quot;] = string.Concat(DateTime.Now, &quot; - Extension &quot;, ex.Message, &quot; not allowed.&quot;); return RedirectToAction(&quot;Index&quot;, &quot;MainFolder&quot;); } base.Response.StatusCode = 500; return Json(new { success = false, errFileUploadMsg = string.Concat(DateTime.Now, &quot; - Extension &quot;, ex.Message, &quot; not allowed.&quot;) }, JsonRequestBehavior.AllowGet); } return RedirectToAction(&quot;Index&quot;, &quot;MainFolder&quot;); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T10:05:19.760", "Id": "514128", "Score": "1", "body": "It is messy because you have put everything into a single method. I would suggest to split this function into smaller chunks where each has a dedicated responsibility and scope." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T13:07:35.957", "Id": "514139", "Score": "0", "body": "Keep controllers and their methods as light as possible, and move as much of the logic as possible to a dedicated class (using https://github.com/jbogard/MediatR for instance). https://codeopinion.com/thin-controllers-cqrs-mediatr/ , https://github.com/pwhe23/MediatrUploader , etc." } ]
[ { "body": "<ul>\n<li>Method has multiple mix responsibilities, it should have one responsibility and clearer scope.</li>\n<li>variable naming doesn't follow naming convention (e.g. <code>id</code> , <code>fm</code>, <code>str</code>) you should always pick a clearer names for your variables.</li>\n<li>when parsing or converting types, you should always validate them or use the appropriate conversions methods such as <code>int.TryParse</code>.</li>\n<li>always work with a copy of the source, don't work with the source directly. this would avoid you a lot of work and mistakes. like the <code>id</code> you're reassigning it with <code>folderId</code> which is confusing, it should be declared separately then switch between them.</li>\n<li>Didn't use the <code>using</code> clause with <code>Disposable</code> object.</li>\n<li><code>ParentModel</code> is misused, you could declare <code>Files</code> without the need of <code>ParentModel</code>.</li>\n<li><code>catch</code> clause, will only catch <code>FileFormatException</code> you should also consider catch other exceptions as will don't catch one and ignore the rest.</li>\n<li>when working with <code>Controller</code> response, it's a good idea to create a method for recurring actions to unify your controllers, and keep things simple and manageable.</li>\n<li>returning status code <code>500</code> for every error is not a good practice, you should return the appropriate status code, for instance, if folder or file does not exist, you can return <code>404</code> status code, if the operation is not allowed then use <code>405</code> status code, and use <code>500</code> code to all unknown exceptions.</li>\n<li>Not using the appropriate <code>built-in</code> status objects such as <code>HttpNotFoundResult</code> ..etc.</li>\n<li>Helper methods or extensions are very helpful, however <code>Helper.CheckIfExtensionStringAllowed</code> does not tell me where it can be used ? which actions can be applied to ?. If is it for a global scope (meaning this extension should be applied on all files) then, it should be implemented inside <code>FileUpload</code> and not used as Helper. but if is it for current scope, then you need to find a clearer naming or implement it else where with a clearer name.</li>\n</ul>\n<p><strong>Create your base Controller</strong>\nusing the base <code>Controller</code> class is fine, but sometimes you need to implement an abstract controller of <code>Controller</code> itself, this abstract would contain the main functions that would be applied to all controllers as a way to unify your work and make your code more manageable.</p>\n<p>For instance. Say that <code>base.Request.Form[&quot;id&quot;]</code> is called in every <code>Action</code>, and also many actions would return <code>Json()</code>. we can implement something like :</p>\n<pre><code>public abstract class BaseController : Controller \n{\n protected int Id =&gt; int.TryParse(base.Request.Form[&quot;id&quot;], out int id) &amp;&amp; id &gt; 0 ? id : -1;\n \n protected bool IsJson =&gt; bool.TryParse(base.Request.Form[&quot;isJson&quot;], out bool isJson) &amp;&amp; isJson;\n\n private ActionResult JsonResponse(HttpStatusCode code, int logId, string message, bool isSuccess)\n {\n Logging.LogToFile(message, logId);\n base.Response.StatusCode = (int) code;\n return Json(new\n {\n success = isSuccess,\n errFileUploadMsg = $&quot;{DateTime.Now} {message}&quot;;\n }, JsonRequestBehavior.AllowGet);\n }\n \n protected ActionResult JsonSuccess()\n {\n return JsonResponse(HttpStatusCode.OK, logId, &quot;success&quot;, true); \n }\n \n protected ActionResult JsonFailed(HttpStatusCode code, int logId, string message)\n {\n return JsonResponse(code, logId, message, false); \n }\n \n protected ActionResult JsonInternalServerError(int logId, string message)\n {\n return JsonResponse(HttpStatusCode.InternalServerError, logId, message, false); \n }\n \n protected ActionResult JsonNotFound(int logId, string message)\n {\n return JsonFailed(HttpStatusCode.NotFound, logId, message);\n }\n\n protected ActionResult JsonNotAllowed(int logId, string message)\n {\n return JsonFailed(HttpStatusCode.MethodNotAllowed, logId, message);\n } \n}\n</code></pre>\n<p>now if you inherit this base class you can do this :</p>\n<pre><code>public class FileController : BaseController\n{\n protected int FolderId =&gt; int.TryParse(base.Request.Form[&quot;folderId&quot;], out int id) &amp;&amp; id &gt; 0 ? id : -1;\n\n protected ActionResult RedirectToMainFolder()\n {\n return RedirectToAction(&quot;Index&quot;, &quot;MainFolder&quot;);\n }\n \n private bool UploadFile(Files file, int folderId, int position)\n {\n // upload file logic\n }\n\n public ActionResult UploadFiles()\n {\n if(!int.TryParse(base.Request.Form[&quot;id&quot;], out int folderId) || folderId &lt; 1) \n {\n return JsonNotFound(3, $&quot;Could not load Folder ID {folderId}, Please try again.&quot;);\n }\n //...\n try\n {\n //... uploading file logic\n \n }\n catch (FileFormatException ex)\n {\n Logging.LogToFile(ex, 3);\n \n var message = $&quot;Extension {ex.Message} not allowed.&quot;;\n \n if (!IsJson)\n {\n base.TempData[&quot;Error&quot;] = message;\n \n return RedirectToMainFolder();\n }\n \n return JsonNotAllowed(3, message);\n }\n catch(Exception ex)\n { \n return JsonInternalServerError(3, ex.Message); \n }\n \n return RedirectToMainFolder();\n}\n</code></pre>\n<p>There are many methods are already exist in the MVC controller that already defined for each <code>HttpStatusCode</code>, such as <code>NotFound()</code>, <code>Forbidden</code> ..etc., which you should use, however, I just want to show you how you can have your custom results which would help you to have a better management to your controllers.</p>\n<p>For the current <code>UploadFiles</code> Action, you will need to extract the file processing into a separate method, and then recall it from inside the action. Something like this :</p>\n<pre><code>private bool UploadFile(Files file, int folderId, int position)\n{\n if(folderId &lt; 1)\n {\n throw new InvalidOperationException(&quot;Folder ID {folderId} couldn't load. Please try again.&quot;);\n }\n \n if(file.File?.Length == 0)\n {\n throw new ArgumentNullException(nameof(file));\n }\n \n if(!Regex.IsMatch(file.FileName, &quot;\\\\d+_\\\\d+&quot;))\n {\n return false;\n }\n \n string[] fileNameSections = Path.GetFileNameWithoutExtension(file.FileName).Split(' '); \n \n if(fileNameSections?.Length == 0)\n {\n throw new Exception(&quot;File name couldn't be read.&quot;);\n }\n\n var sectionParts = fileNameSections[0].Split('_');\n \n if(sectionParts?.Length &gt;= 2 &amp;&amp; sectionParts[0].All(char.IsDigit) &amp;&amp; sectionParts[1].All(char.IsDigit))\n {\n file.FileName = file.FileName.Replace(&quot;_&quot;, &quot;/&quot;);\n }\n \n if (_mainFolderRepository.IsFileNameInFolder(folderId, file.FileName))\n {\n int fileIdForChange = _mainFolderRepository.GetFileId(folderId, file.FileName);\n\n _mainFolderRepository.UpdateFile(fileIdForChange, file.File, file.ContentLength);\n }\n else\n {\n if (!Helper.CheckIfExtensionStringAllowed(Path.GetExtension(file.FileName).ToLower()))\n {\n throw new FileFormatException(file.Extension);\n }\n \n fm.Extension = Path.GetExtension(file.FileName).ToLower();\n\n if ((file.Extension == &quot;.pdf&quot; || file.Extension == &quot;.doc&quot; || file.Extension == &quot;.docx&quot;) &amp;&amp; file.File.Length != 0)\n {\n file.VolltextSuche = ConverterController.ConvertFileToText(file.File, file.FileName, file.Extension);\n }\n \n _mainFolderRepository.FileUpload(file.File, file.ContentLength, file.FileName, &quot;&quot;, &quot;&quot;, base.User.Identity.Name, DateTime.Now, isPublic: false, file.Extension, id, file.RessortId, position, file.FullTextSearch, &quot;&quot;);\n } \n \n return true;\n}\n\npublic ActionResult UploadFiles()\n{\n if(FolderId &lt; 1) \n {\n return JsonNotFound(3, $&quot;Could not load Folder ID {FolderId}, Please try again.&quot;);\n }\n \n try\n {\n Files fileModel = new Files();\n\n int lastPosition = _mainFolderRepository.GetLastNumberOfFileInFolder(id);\n \n int position = ((lastPosition.GetType() != typeof(DBNull)) ? (lastPosition + 1) : 0);\n \n for (int i = 0; i &lt; base.Request.Files.Count; i++)\n {\n HttpPostedFileBase file = base.Request.Files[i];\n \n int fileLength = file.InputStream.Length;\n \n byte[] fileBytes = new byte[fileLength];\n \n using(var stream = new Stream(file.InputStream)) \n {\n stream.Seek(0 , SeekOrigin.Begin);\n stream.Read(fileBytes , 0 , (int) stream.Length);\n }\n\n fileModel.FullTextSearch = &quot;&quot;;\n fileModel.File = fileBytes;\n fileModel.ContentLength = file.ContentLength;\n fileModel.FileName = Path.GetFileName(file.FileName);\n \n var isSuccess = UploadFile(fileModel, FolderId, position++);\n \n if(!isSuccess)\n {\n // do something \n }\n }\n }\n catch (FileFormatException ex)\n {\n Logging.LogToFile(ex, 3);\n \n var message = $&quot;Extension {ex.Message} not allowed.&quot;;\n \n if (!IsJson)\n {\n base.TempData[&quot;Error&quot;] = message;\n \n return RedirectToMainFolder();\n }\n \n return JsonNotAllowed(3, message);\n }\n catch(Exception ex)\n { \n return JsonInternalServerError(3, ex.Message); \n }\n \n return RedirectToMainFolder();\n}\n</code></pre>\n<p>This is just a demonstration on the above points, you should focus on clearing the code, dividing it to chucks based on role and responsibility, make use of other OPP principles such as inheriting's to have a better code experience. Also, make use of pre-existing functions that shipped with the <code>.NET</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T19:23:25.377", "Id": "260467", "ParentId": "260448", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T08:12:23.573", "Id": "260448", "Score": "0", "Tags": [ "c#", "asp.net-mvc" ], "Title": "Use Request with Fileupload in Controller" }
260448
<p>Just want you guys to review my python 3 IRC bot code, it is actually a fork of <a href="https://github.com/Orderchaos/LinuxAcademy-IRC-Bot" rel="nofollow noreferrer">https://github.com/Orderchaos/LinuxAcademy-IRC-Bot</a></p> <p>You can see the <a href="https://github.com/PuneetGopinath/IRCbot/tree/main/bkircbot" rel="nofollow noreferrer">source code at github</a></p> <p>I also have questions:</p> <ol> <li>I really can't find out how to change the ident for the bot, can I change the ident?</li> <li>Can I change the ident by modifying the <a href="https://github.com/PuneetGopinath/IRCbot/blob/main/bkircbot/ircbot.py#L33" rel="nofollow noreferrer">user authentication</a> code?</li> </ol> <p>In addition to answering my question, you can submit a pr at GitHub if you want yourself to be in the contributions list.</p> <p>The ircbot.py file is as below:</p> <pre><code>&quot;&quot;&quot; Copyright (c) 2016 Linux Academy Copyright (c) 2021 BK IRCbot team and contributors Licensed under GNU Lesser General Public License v2.1 See the LICENSE file distributed with the source code OR Visit https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html This project is a fork of https://github.com/Orderchaos/LinuxAcademy-IRC-Bot NOTE This program is distributed in the hope that it will be useful - WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. &quot;&quot;&quot; # socket for irc socket import socket # os for file handling, currently not required # import os # conf from conf import server, port, channel, botnick, adminnick, password, exitcode, filename # Create a socket ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if adminnick == &quot;&quot; or botnick == &quot;&quot;: print(&quot;Notice: BK_IRCbot: adminnick or botnick is empty!&quot;) ircsock.connect((server, port)) # Here we connect to the server # We need to send some info to the server to let the server identify us. # USER &lt;username&gt; &lt;hostname&gt; &lt;servername&gt; :&lt;realname&gt; ircsock.send(bytes( &quot;USER &quot; + botnick + &quot; &quot; + botnick + &quot; &quot; + botnick + &quot; :IRCbot by Linux Academy and Puneet Gopinath.\n&quot;, &quot;UTF-8&quot; )) # user information ircsock.send(bytes( &quot;NICK &quot; + botnick + &quot;\n&quot;, &quot;UTF-8&quot; )) # assign the nick to the bot ircsock.send(bytes( &quot;NickServ identify &quot; + password + &quot;\n&quot;, &quot;UTF-8&quot; )) # login to the botnick's IRC account def joinchan(chan): &quot;&quot;&quot;Join channel(s) Parameters: chan (string): Channel(s) to join. Seperate a channel using a comma, e.g. #chan,#chan2 Returns: null: Returns null. &quot;&quot;&quot; # The ‘bytes’ part and &quot;UTF-8” says to send the message to IRC as UTF-8 encoded bytes. # You will see this on all the lines where we send data to the IRC server. ircsock.send(bytes(&quot;JOIN &quot; + chan + &quot;\n&quot;, &quot;UTF-8&quot;)) # The &quot;\n” at the end of the line denotes to send a new line character. # It tells the server that we’re finished that command. # After sending the join command, we start a loop # To continuously check and receive new info from server # UNTIL we get a message from the server ‘End of /NAMES list.’. # This will indicate we have successfully joined the channel. # The details of how each function works is described in the main function section below. # This is necessary so we don't process the joining message as commands. ircmsg = &quot;&quot; while ircmsg.find(&quot;End of /NAMES list.&quot;) == -1: ircmsg = ircsock.recv(2048).decode(&quot;UTF-8&quot;) ircmsg = ircmsg.strip(&quot;\n\r&quot;) print(ircmsg) def ping(): &quot;&quot;&quot;If the server send a ping to us, respond with a pong. Returns: null: Returns null. &quot;&quot;&quot; ircsock.send(bytes(&quot;PONG :pingis\n&quot;, &quot;UTF-8&quot;)) def sendmsg(msg, target): &quot;&quot;&quot;Send a message to a channel or some nick Parameters: msg (string): The message. target (string): Send message to which channel/nick? Returns: null: Returns null. &quot;&quot;&quot; # Here we are sending a PRIVMSG to the server. # The &quot; :&quot; lets the server separate the target and the message. ircsock.send(bytes(&quot;PRIVMSG &quot; + target + &quot; :&quot; + msg + &quot;\n&quot;, &quot;UTF-8&quot;)) def logger(name, msg): &quot;&quot;&quot;Log message Parameters: name (string): Name to person who sent the message msg (string): The message. Returns: null: Returns null. &quot;&quot;&quot; irclog = open(filename, &quot;r&quot;) content = irclog.readlines() irclog.close() # loop through the content of the chat log and reduce to 100 lines, starting with oldest. # Definitely a better way to do this, needs improvement. irclog = open(filename, &quot;w&quot;) while len(content) &gt; 100: content.remove(content[0]) if len(content) &gt; 0: for i in content: irclog.write(i.strip(&quot;\n\r&quot;) + &quot;\n&quot;) # write newest message to log. irclog.write(name + &quot;:&quot; + msg.strip(&quot;\n\r&quot;) + &quot;\n&quot;) irclog.close() def start(): &quot;&quot;&quot;Start the bot Returns: null: Returns null. &quot;&quot;&quot; # start by joining the channel(s) we defined. chan = &quot;&quot; for x in channel: chan += x + &quot;,&quot; joinchan(chan) # Start infinite loop to keep checking and receive new info from server. # This ensures our connection stays open. # An infinite while loop works better in this case. while 1: # Here we are receiving information from the IRC server. # IRC will send out information encoded in UTF-8 characters # We’re telling our socket to receive up to 2048 bytes and decode it as UTF-8 characters. # We then assign it to the ircmsg variable for processing. ircmsg = ircsock.recv(2048).decode(&quot;UTF-8&quot;) # This part will remove any line break characters from the string. ircmsg = ircmsg.strip(&quot;\n\r&quot;) # This will print the received information to your terminal. # Useful for debugging purposes print(ircmsg) # Here we check if the information we received was a PRIVMSG. # PRIVMSG is standard messages sent to the channel or direct messages sent to the bot. # Most of the processing of messages will be in this section. if ircmsg.find(&quot;PRIVMSG&quot;) != -1: # Messages come from IRC in the format of # &quot;:[Nick]!~[hostname]@[IP Address] PRIVMSG [channel] :[message]&quot; name = ircmsg.split(&quot;!&quot;, 1)[0][1:] # message. message = ircmsg.split(&quot;PRIVMSG&quot;, 1)[1].split(&quot; :&quot;, 1)[1] # To whom (or to which channel) it was sent. sentTo = ircmsg.split(&quot;PRIVMSG&quot;, 1)[1].split(&quot; :&quot;, 1)[0].lstrip() if (sentTo.lower() == botnick.lower()): sendTo = name else: sendTo = sendTo # Log the message logger(name, &quot;(Sent To: &quot; + sentTo + &quot;) :&quot; + message) # We check if the name is less than 17 characters. # Nicks (at least for Freenode) are limited to 16 characters. admin = name.lower() == adminnick.lower() if len(name) &lt; 17: if message.find(&quot;Hi &quot; + botnick) != -1 or message.find(&quot;Who is &quot; + botnick) != -1: sendmsg(&quot;Hello &quot; + name + &quot;!&quot;, sendTo) sendmsg( &quot;I am a bot created by PuneetGopinath, &quot; + &quot;initialy developed by Linux Academy. &quot; + &quot;Credits to Linux Academy and PuneetGopinath. &quot; + &quot;Please report any issues at &quot; + &quot;https://github.com/PuneetGopinath/IRCbot/issues&quot;, sendTo ) if admin and message.rstrip() == &quot;Clear the file, &quot; + botnick: sendmsg(&quot;Ok, will clear the file.&quot;, sendTo) irclog = open(filename, &quot;w&quot;) irclog.write(&quot;&quot;) irclog.close() # Here we add in some code to help us get the bot to stop. # Check whether the name of the person sending the message matches the admin nick. # We make sure the message EXACTLY matches the exit code above. # The only adjustment here is to trim at the right end of the message. if admin and message.rstrip() == exitcode: sendmsg( &quot;Bye... Waiting to see you again!!&quot;, sendTo ) # Send the quit command to the IRC server so it knows we’re leaving. ircsock.send(bytes(&quot;QUIT \n&quot;, &quot;UTF-8&quot;)) # The return command ends the function here # So the bot stops return # If the message is not a PRIVMSG it still might need some response. else: # Check if the info we received was a PING request. # If yes, we call the ping() function so we respond with a PONG to the server. if ircmsg.find(&quot;PING :&quot;) != -1: ping() # The main function is defined, we need to start it. start() </code></pre> <p>And the <code>conf.py</code>:</p> <pre><code>&quot;&quot;&quot; Copyright (c) 2021 BK IRCbot team and contributors Licensed under GNU Lesser General Public License v2.1 See the LICENSE file distributed with the source code OR Visit https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html This project is a fork of https://github.com/Orderchaos/LinuxAcademy-IRC-Bot NOTE This program is distributed in the hope that it will be useful - WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. &quot;&quot;&quot; server = &quot;chat.freenode.net&quot; # Server to connect. port = 6667 # Port to use when connecting channel = [&quot;#chan&quot;] # Array of channels to join. botnick = &quot;&quot; # Your bot's nickname. adminnick = &quot;&quot; # Your IRC nickname. password = &quot;&quot; # Your IRC bot's password. exitcode = &quot;Stop &quot; + botnick # The message we will use to stop the bot if sent by admin. filename = &quot;ircchat.log&quot; # Filename in which messages will be logged. </code></pre>
[]
[ { "body": "<p>This program - and the program it's forked from - have somewhat severe issues. You may want to be more judicious in the repositories you're using to learn.</p>\n<pre><code>ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n</code></pre>\n<p>needs to be protected with a context management <code>with</code> to guarantee closure, and should not be done at global scope. Similar for <code>irclog</code>.</p>\n<pre><code>if adminnick == &quot;&quot; or botnick == &quot;&quot;:\n print(&quot;Notice: BK_IRCbot: adminnick or botnick is empty!&quot;)\n</code></pre>\n<p>seems like something that should hard-<code>raise</code> instead of printing and attempting to continue with execution.</p>\n<p>Your pattern of</p>\n<pre><code>bytes(\n &quot;USER &quot; + botnick + &quot; &quot; + botnick + &quot; &quot; + botnick +\n &quot; :IRCbot by Linux Academy and Puneet Gopinath.\\n&quot;,\n &quot;UTF-8&quot;\n)\n</code></pre>\n<p>is a more awkward way of saying</p>\n<pre><code>(\n f'USER {botnick} {botnick} {botnick} '\n f':IRCbot by Linux Academy and Puneet Gopinath.\\n'\n).encode('UTF-8')\n</code></pre>\n<p>This client is deeply insecure; it transmits your password in plaintext over the wire. Read e.g. <a href=\"https://freenode.net/kb/answer/sasl\" rel=\"nofollow noreferrer\">https://freenode.net/kb/answer/sasl</a> for more information.</p>\n<p><code>joinchan</code> (which would be better named <code>join_channel</code>) would be better off accepting an iterable of strings, and doing <code>','.join</code> on them before sending it off to the server.</p>\n<p>This loop:</p>\n<pre><code> ircmsg = &quot;&quot;\n while ircmsg.find(&quot;End of /NAMES list.&quot;) == -1:\n ircmsg = ircsock.recv(2048).decode(&quot;UTF-8&quot;)\n ircmsg = ircmsg.strip(&quot;\\n\\r&quot;)\n print(ircmsg)\n</code></pre>\n<p>betrays a classic misunderstanding of the way that TCP/IP works that beginners nearly universally stub their toe on. Packets get fragmented. Asking to receive up to 2kB does NOT guarantee:</p>\n<ul>\n<li>that you've received a complete message; or even</li>\n<li>that the message is not fragmented across packet boundaries.</li>\n</ul>\n<p>In other words, there's nothing stopping any of the routers between you and the server from sending</p>\n<pre><code>End of /N\n</code></pre>\n<p>in one packet and</p>\n<pre><code>AMES list.\n</code></pre>\n<p>in the second. For you to gain those guarantees of non-fragmentation you either need to do your own buffering or call into a Python networking abstraction layer that will do it for you.</p>\n<p><code>conf.py</code> is not a great place to store configuration in. Consider making an actual configuration file instead.</p>\n<p>This:</p>\n<pre><code>content = irclog.readlines()\nwhile len(content) &gt; 100:\n content.remove(content[0])\n</code></pre>\n<p>is not efficient, and should be replaced with a single slice operation, probably</p>\n<pre><code>content = irclog.readlines()[:-100]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T06:43:46.713", "Id": "514307", "Score": "0", "body": "What should I use instead of `while ircmsg.find(\"End of /NAMES list.\") == -1:`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T06:59:30.323", "Id": "514308", "Score": "0", "body": "Can you guide me with SASL Client Configuration in the bot, there are guides for clients but not for python bot" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T17:00:27.530", "Id": "514343", "Score": "0", "body": "Re. line buffering - call into https://docs.python.org/3/library/socket.html#socket.socket.makefile and use `readline()` on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T11:20:27.463", "Id": "514454", "Score": "0", "body": "Can I change the ident" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T11:22:15.423", "Id": "514455", "Score": "0", "body": "You said `Consider making an actual configuration file instead.`, Did you mean `.ini` file" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:05:22.573", "Id": "514459", "Score": "0", "body": "Something like that, yes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T15:59:45.357", "Id": "514550", "Score": "0", "body": "Ok. Will deal with that afterwards" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T20:13:04.133", "Id": "260511", "ParentId": "260449", "Score": "2" } } ]
{ "AcceptedAnswerId": "260511", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T10:38:43.270", "Id": "260449", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Python 3 IRCbot (library)" }
260449
<p>I originally wrote a rough C++ wrapper of the sqlite3 c library which did not use prepared statements. This code is my attempt at using prepared statements. I have attempted to make the wrapper as generic as possible so can be used in a wide range of applications.</p> <p>How easy to use do you think this C++ class is? Any bugs? How could this be improved?</p> <p>Here is the header, sqlite.hpp:</p> <pre><code>// sqlite - a thin c++ wrapper of sqlite c library #ifndef SQLITE_HPP_ #define SQLITE_HPP_ // uncomment below to print blob data as hex in ostream overload of column_values // #define PRINT_BLOB_AS_HEX #include &quot;sqlite3.h&quot; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;variant&gt; #include &lt;cstdint&gt; #include &lt;iostream&gt; #include &lt;map&gt; namespace sql { /* sqlite types can be: NULL, INTEGER, REAL, TEXT, BLOB NULL: we don't support this type INTEGER: int REAL: double TEXT: std::string BLOB: std::vector&lt;uint8_t&gt; */ using sqlite_data_type = std::variant&lt;int, double, std::string, std::vector&lt;uint8_t&gt; &gt;; struct column_values { std::string column_name; sqlite_data_type column_value; }; struct where_binding { std::string column_name; sqlite_data_type column_value; }; std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const column_values&amp; v); std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const sqlite_data_type&amp; v); std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const std::map&lt;std::string, sqlite_data_type&gt;&amp; v); class sqlite { public: /* sqlite constructor */ sqlite(); /* cleanup */ ~sqlite(); /* database must be opened before calling an sql operation */ int open(const std::string&amp; filename); /* close database connection */ int close(); /* INSERT INTO (col1, col2) VALUES (:col1, :col2); table_name is table to insert into fields are a list of column name to column value key value pairs */ int insert_into(const std::string&amp; table_name, const std::vector&lt;column_values&gt;&amp; fields); /* returns rowid of last successfully inserted row. If no rows inserted since this database connectioned opened, returns zero. */ int last_insert_rowid(); /* UPDATE contacts SET col1 = value1, col2 = value2, ... WHERE rowid = therowid; table_name is table to update, fields are a list of column name to column value key value pairs to update where_clause is WHERE clause predicate expressed as : parameterised query bindings is the binding of values in the where clause */ int update( const std::string&amp; table_name, const std::vector&lt;column_values&gt;&amp; fields, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings); /* UPDATE contacts SET col1 = value1, col2 = value2, ...; same as update(table_name, fields, where) except no WHERE clause so potential to change EVERY row. USE WITH CAUTION. */ int update(const std::string&amp; table_name, const std::vector&lt;column_values&gt;&amp; fields); /* DELETE FROM table_name WHERE condition; */ int delete_from(const std::string&amp; table_name, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings); /* DELETE FROM table_name; same as delete_from(table_name, where) except no WHERE clause so potential to delete EVERY row. USE WITH CAUTION. */ int delete_from(const std::string&amp; table_name); /* SELECT * FROM table_name WHERE col1 = x; table_name is table to select, where_clause is WHERE clause predicate expressed as : parameterised query bindings is the binding of values in the where clause results is a table of values */ int select_star(const std::string&amp; table_name, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results); /* SELECT * FROM table_name; table_name is table to select, results is a table of values */ int select_star(const std::string&amp; table_name, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results); /* SELECT col1, col2 FROM table_name WHERE col1 = x; table_name is table to select, fields are list of fields in table to select where is list of key value pairs as criterion for select results is a table of values */ int select_columns(const std::string&amp; table_name, const std::vector&lt;std::string&gt;&amp; fields, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results); /* get error text relating to last sqlite error. Call this function whenever an operation returns a sqlite error code */ const std::string get_last_error_description(); private: sqlite3* db_; }; } // itel #endif // SQLITE_HPP_ </code></pre> <p>The implementation, sqlite.cpp:</p> <pre><code>#include &quot;sqlite.hpp&quot; #include &lt;algorithm&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #define EXIT_ON_ERROR(resultcode) \ if (resultcode != SQLITE_OK) \ { \ sqlite3_finalize(stmt); \ return resultcode; \ } namespace { std::string insert_into_helper( const std::string&amp; table_name, const std::vector&lt;sql::column_values&gt;&amp; fields) { std::string sqlfront{ &quot;INSERT INTO &quot; + table_name + &quot; (&quot; }; std::string sqlend{ &quot;) VALUES (&quot; }; std::string separator{ &quot;&quot; }; for (const auto&amp; field : fields) { sqlfront += separator + field.column_name; sqlend += separator + ':' + field.column_name; separator = &quot;,&quot;; } sqlend += &quot;);&quot;; return sqlfront + sqlend; } std::string space_if_required(const std::string&amp; s) { return !s.empty() &amp;&amp; s[0] != ' ' ? &quot; &quot; : &quot;&quot;; } std::string update_helper( const std::string&amp; table_name, const std::vector&lt;sql::column_values&gt;&amp; fields, const std::string&amp; where_clause) { std::string sql{ &quot;UPDATE &quot; + table_name + &quot; SET &quot; }; std::string separator{ &quot;&quot; }; for (const auto&amp; field : fields) { sql += separator + field.column_name + &quot;=:&quot; + field.column_name; separator = &quot;,&quot;; } if (!where_clause.empty()) { sql += space_if_required(where_clause); sql += where_clause; } sql += &quot;;&quot;; return sql; } std::string delete_from_helper( const std::string&amp; table_name, const std::string&amp; where_clause) { std::string sql{ &quot;DELETE FROM &quot; + table_name }; if (!where_clause.empty()) { sql += space_if_required(where_clause); sql += where_clause; } sql += &quot;;&quot;; return sql; } const std::string select_helper( const std::string&amp; table_name, const std::vector&lt;std::string&gt;&amp; fields, const std::string&amp; where_clause) { std::string sql{ &quot;SELECT &quot; }; std::string separator{ &quot;&quot; }; for (const auto&amp; field : fields) { sql += separator + field; separator = &quot;,&quot;; } if (fields.empty()) { sql += &quot;*&quot;; } sql += &quot; FROM &quot; + table_name; if (!where_clause.empty()) { sql += space_if_required(where_clause); sql += where_clause; } sql += &quot;;&quot;; return sql; } int bind_fields(sqlite3_stmt* stmt, const std::vector&lt;sql::column_values&gt;&amp; fields) { int rc = SQLITE_OK; for (const auto&amp; param : fields) { std::string next_param{ ':' + param.column_name }; int idx = sqlite3_bind_parameter_index(stmt, next_param.c_str()); switch (param.column_value.index()) { case 0: rc = sqlite3_bind_int(stmt, idx, std::get&lt;0&gt;(param.column_value)); break; case 1: rc = sqlite3_bind_double(stmt, idx, std::get&lt;1&gt;(param.column_value)); break; case 2: rc = sqlite3_bind_text(stmt, idx, std::get&lt;2&gt;(param.column_value).c_str(), -1, SQLITE_STATIC); break; case 3: rc = sqlite3_bind_blob(stmt, idx, std::get&lt;3&gt;(param.column_value).data(), std::get&lt;3&gt;(param.column_value).size(), SQLITE_STATIC); break; } } return rc; } int bind_where(sqlite3_stmt* stmt, const std::vector&lt;sql::where_binding&gt;&amp; binding) { int rc = SQLITE_OK; for (const auto&amp; param : binding) { std::string next_param{ ':' + param.column_name }; int idx = sqlite3_bind_parameter_index(stmt, next_param.c_str()); switch (param.column_value.index()) { case 0: rc = sqlite3_bind_int(stmt, idx, std::get&lt;0&gt;(param.column_value)); break; case 1: rc = sqlite3_bind_double(stmt, idx, std::get&lt;1&gt;(param.column_value)); break; case 2: rc = sqlite3_bind_text(stmt, idx, std::get&lt;2&gt;(param.column_value).c_str(), -1, SQLITE_STATIC); break; case 3: rc = sqlite3_bind_blob(stmt, idx, std::get&lt;3&gt;(param.column_value).data(), std::get&lt;3&gt;(param.column_value).size(), SQLITE_STATIC); break; } } return rc; } int step_and_finalise(sqlite3_stmt* stmt) { if (stmt == nullptr) { return SQLITE_ERROR; } // whether error or not we must call finalize int rc = sqlite3_step(stmt); // SQLITE_ROW = another row ready - possible to configure to return a value - but we just ignore anything returned // SQLITE_DONE = finished executing // caller is more interested in the result of the step int finalise_rc = sqlite3_finalize(stmt); // de-allocates stmt return rc == SQLITE_DONE ? finalise_rc : rc; } } namespace sql { std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const column_values&amp; v) { os &lt;&lt; &quot;name: &quot; &lt;&lt; v.column_name &lt;&lt; &quot;, value: &quot;; switch (v.column_value.index()) { case 0: os &lt;&lt; std::get&lt;0&gt;(v.column_value) &lt;&lt; &quot; of type int&quot;; break; case 1: os &lt;&lt; std::get&lt;1&gt;(v.column_value) &lt;&lt; &quot; of type double&quot;; break; case 2: os &lt;&lt; std::get&lt;2&gt;(v.column_value) &lt;&lt; &quot; of type string&quot;; break; case 3: { #ifdef PRINT_BLOB_AS_HEX auto previous_flags = os.flags(); std::for_each(std::get&lt;3&gt;(v.column_value).begin(), std::get&lt;3&gt;(v.column_value).end(), [&amp;os](const uint8_t&amp; byte) { os &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; (byte &amp; 0xFF) &lt;&lt; ' '; }); os &lt;&lt; &quot; of type vector&lt;uint8_t&gt;&quot;; os.setf(previous_flags); #else os &lt;&lt; &quot;&lt;blob&gt; of type vector&lt;uint8_t&gt;&quot;; #endif break; } } return os; } #ifdef PRINT_BLOB_AS_HEX std::ostream&amp; operator&lt;&lt;(std::ostream &amp; os, const std::vector&lt;uint8_t&gt;&amp;v) { auto previous_flags = os.flags(); std::for_each(v.begin(), v.end(), [&amp;os](const uint8_t&amp; byte) { os &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; (byte &amp; 0xFF) &lt;&lt; ' '; }); os.setf(previous_flags); #else std::ostream&amp; operator&lt;&lt;(std::ostream &amp; os, const std::vector&lt;uint8_t&gt;&amp; /* v */) { os &lt;&lt; &quot;&lt;blob&gt;&quot;; #endif return os; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const sqlite_data_type&amp; v) { std::visit([&amp;](const auto&amp; element) { os &lt;&lt; element; }, v); return os; } std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const std::map&lt;std::string, sqlite_data_type&gt;&amp; v) { for (const auto&amp; element : v) { os &lt;&lt; element.first &lt;&lt; &quot;: &quot; &lt;&lt; element.second &lt;&lt; '|'; } return os; } sqlite::sqlite() : db_(nullptr) {} sqlite::~sqlite() { close(); } int sqlite::open(const std::string&amp; filename) { return sqlite3_open(filename.c_str(), &amp;db_); } int sqlite::close() { if (db_ == nullptr) { return SQLITE_ERROR; } return sqlite3_close(db_); } int sqlite::insert_into(const std::string&amp; table_name, const std::vector&lt;column_values&gt;&amp; fields) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = insert_into_helper(table_name, fields); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_fields(stmt, fields)); return step_and_finalise(stmt); } int sqlite::last_insert_rowid() { return static_cast&lt;int&gt;(sqlite3_last_insert_rowid(db_)); } int sqlite::update(const std::string&amp; table_name, const std::vector&lt;column_values&gt;&amp; fields, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = update_helper(table_name, fields, where_clause); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_fields(stmt, fields)); EXIT_ON_ERROR(bind_where(stmt, bindings)); return step_and_finalise(stmt); } int sqlite::update(const std::string&amp; table_name, const std::vector&lt;column_values&gt;&amp; fields) { return update(table_name, fields, &quot;&quot;, {}); } int sqlite::delete_from(const std::string&amp; table_name, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = delete_from_helper(table_name, where_clause); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_where(stmt, bindings)); return step_and_finalise(stmt); } int sqlite::delete_from(const std::string&amp; table_name) { return delete_from(table_name, &quot;&quot;, {}); } int sqlite::select_columns(const std::string&amp; table_name, const std::vector&lt;std::string&gt;&amp; fields, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = select_helper(table_name, fields, where_clause); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_where(stmt, bindings)); int num_cols = sqlite3_column_count(stmt); std::vector&lt;std::string&gt; column_names; for (int i = 0; i &lt; num_cols; i++) { const char* colname = sqlite3_column_name(stmt, i); column_names.push_back(colname ? colname : &quot;&quot;); } int rc = 0; while ((rc = sqlite3_step(stmt)) != SQLITE_DONE) { std::map&lt;std::string, sqlite_data_type&gt; row; for (int i = 0; i &lt; num_cols; i++) { switch (sqlite3_column_type(stmt, i)) { case SQLITE3_TEXT: { const unsigned char* value = sqlite3_column_text(stmt, i); int len = sqlite3_column_bytes(stmt, i); row[column_names[i]] = std::string(value, value+len); } break; case SQLITE_INTEGER: { row[column_names[i]] = sqlite3_column_int(stmt, i); } break; case SQLITE_FLOAT: { row[column_names[i]] = sqlite3_column_double(stmt, i); } break; case SQLITE_BLOB: { const uint8_t* value = reinterpret_cast&lt;const uint8_t*&gt;(sqlite3_column_blob(stmt, i)); int len = sqlite3_column_bytes(stmt, i); row[column_names[i]] = std::vector&lt;uint8_t&gt;(value, value + len); } break; case SQLITE_NULL: { row[column_names[i]] = &quot;null&quot;; } break; default: break; } } results.push_back(row); } return sqlite3_finalize(stmt); } int sqlite::select_star(const std::string&amp; table_name, const std::string&amp; where_clause, const std::vector&lt;where_binding&gt;&amp; bindings, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results) { return select_columns(table_name, {}, where_clause, bindings, results); } int sqlite::select_star(const std::string&amp; table_name, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results) { return select_star(table_name, &quot;&quot;, {}, results); } const std::string sqlite::get_last_error_description() { if (db_ == nullptr) { return &quot;&quot;; } const char* error = sqlite3_errmsg(db_); std::string s(error ? error : &quot;&quot;); return s; } } // sql </code></pre> <p>main.cpp example:</p> <pre><code>/* This example assumes you have created a database as follows: sqlite3.exe mydb.db CREATE TABLE test (name TEXT, age INTEGER, photo BLOB); */ #include &quot;sqlite.hpp&quot; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; using namespace sql; int main() { sql::sqlite db; int rc = db.open(&quot;mydb.db&quot;); std::cout &lt;&lt; &quot;db.open returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // picture from https://en.wikipedia.org/wiki/Mickey_Mouse std::ifstream f(&quot;Mickey_Mouse.png&quot;, std::ios::binary); if (!f.good()) { std::cout &lt;&lt; &quot;failed to open Mickey Mouse bitmap file\n&quot;; return 1; } std::vector&lt;uint8_t&gt; buffer(std::istreambuf_iterator&lt;char&gt;(f), {}); std::vector&lt;sql::column_values&gt; params { {&quot;name&quot;, &quot;Mickey Mouse&quot;}, {&quot;age&quot;, 12}, {&quot;photo&quot;, buffer} }; for (const auto&amp; param : params) { std::cout &lt;&lt; &quot;inserting param: &quot; &lt;&lt; param &lt;&lt; std::endl; } rc = db.insert_into(&quot;test&quot;, params); std::cout &lt;&lt; &quot;db.insert_into(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; int lastrowid = 0; if (rc == SQLITE_OK) { lastrowid = db.last_insert_rowid(); std::cout &lt;&lt; &quot;inserted into rowid: &quot; &lt;&lt; lastrowid &lt;&lt; std::endl; } // let us now update this record std::vector&lt;sql::column_values&gt; updated_params{ {&quot;name&quot;, &quot;Donald Duck&quot;}, {&quot;age&quot;, 23} }; const std::vector&lt;where_binding&gt;&amp; bindings{ {&quot;rowid&quot;, lastrowid} }; rc = db.update(&quot;test&quot;, updated_params, &quot;WHERE rowid=:rowid&quot;, bindings); std::cout &lt;&lt; &quot;db.update(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // try SELECT std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; // simplest way //rc = db.select_star(&quot;test&quot;, results); // using select_column to specifically display sqlite table rowid //rc = db.select_columns(&quot;test&quot;, { &quot;rowid&quot;, &quot;name&quot;, &quot;age&quot;, &quot;photo&quot; }, {}, results); // Or pass in rowid and * to display rowid and all other columns //rc = db.select_columns(&quot;test&quot;, { &quot;rowid&quot;, &quot;*&quot; }, {}, results); const std::vector&lt;where_binding&gt;&amp; select_bindings{ {&quot;name&quot;, &quot;Don%&quot;} }; rc = db.select_columns(&quot;test&quot;, { &quot;rowid&quot;, &quot;*&quot; }, &quot;WHERE name LIKE :name&quot;, select_bindings, results); std::cout &lt;&lt; &quot;db.select_columns(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // print rows int i = 0; for (const auto&amp; row : results) { std::cout &lt;&lt; &quot;row&quot; &lt;&lt; ++i &lt;&lt; &quot;: &quot; &lt;&lt; row &lt;&lt; std::endl; } // finally delete row added const std::vector&lt;where_binding&gt;&amp; delete_bindings { {&quot;rowid&quot;, lastrowid} }; rc = db.delete_from(&quot;test&quot;, &quot;WHERE rowid=:rowid&quot;, delete_bindings); std::cout &lt;&lt; &quot;db.delete_from(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // code below inserts into data into a table that does not exist // test to insert into an invalid column std::vector&lt;sql::column_values&gt; bad_params{ {&quot;nave&quot;, &quot;Tanner&quot;}, {&quot;address8&quot;, &quot;3 The Avenue&quot;}, {&quot;postcoode&quot;, &quot;GU17 0TR&quot;} }; rc = db.insert_into(&quot;contacts&quot;, bad_params); std::cout &lt;&lt; &quot;db.insert_into(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; if (rc != SQLITE_OK) { std::cout &lt;&lt; db.get_last_error_description() &lt;&lt; std::endl; } } </code></pre> <p>And some tests:</p> <pre><code>#include &quot;sqlite.hpp&quot; #include &quot;sqlite3.h&quot; // required for db_initial_setup #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;cstdio&gt; #include &lt;sstream&gt; #include &lt;cstdio&gt; #include &lt;filesystem&gt; #include &lt;algorithm&gt; #include &quot;gtest/gtest.h&quot; using namespace sql; namespace { void db_initial_setup() { if (remove(&quot;contacts.db&quot;) != 0) { perror(&quot;Error deleting contacts.db&quot;); } // we create using c library so not using any of the code to exercise sqlite3* db; char* err_msg = 0; int rc = sqlite3_open(&quot;contacts.db&quot;, &amp;db); if (rc != SQLITE_OK) { fprintf(stderr, &quot;Cannot open database: %s\n&quot;, sqlite3_errmsg(db)); sqlite3_close(db); FAIL() &lt;&lt; &quot;Cannot open database for testing\n&quot;; return; } const char* sql[] = { &quot;DROP TABLE IF EXISTS contacts;&quot; &quot;CREATE TABLE contacts (name TEXT, company TEXT, mobile TEXT, ddi TEXT, switchboard TEXT, address1 TEXT, address2 TEXT, address3 TEXT, address4 TEXT, postcode TEXT, email TEXT, url TEXT, category TEXT, notes TEXT);&quot; &quot;CREATE INDEX idx_mobile ON contacts (mobile);&quot; &quot;CREATE INDEX idx_switchboard ON contacts (switchboard);&quot; &quot;CREATE INDEX idx_ddi ON contacts (ddi);&quot;, &quot;CREATE TABLE calls(timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, callerid TEXT, contactid INTEGER);&quot;, &quot;INSERT INTO contacts (name, mobile, switchboard, address1, address2, address3, postcode, email, url, category) VALUES(\&quot;Test Person\&quot;, \&quot;07788111222\&quot;, \&quot;02088884444\&quot;, \&quot;House of Commons\&quot;, \&quot;Westminster\&quot;, \&quot;London\&quot;, \&quot;SW1A 0AA\&quot;, \&quot;test@house.co.uk\&quot;, \&quot;www.house.com\&quot;, \&quot;Supplier\&quot;);&quot;, &quot;INSERT INTO calls (callerid, contactid) VALUES(\&quot;07788111222\&quot;, 1);&quot; }; size_t num_commands = sizeof(sql) / sizeof(char*); for (size_t i = 0; i &lt; num_commands; ++i) { rc = sqlite3_exec(db, sql[i], 0, 0, &amp;err_msg); if (rc != SQLITE_OK) { fprintf(stderr, &quot;SQL error: %s\n&quot;, err_msg); sqlite3_free(err_msg); sqlite3_close(db); } } sqlite3_close(db); } const std::string filename(&quot;contacts.db&quot;); std::vector&lt;std::string&gt; tables{ &quot;contacts&quot;, &quot;calls&quot; }; } class sqlite_cpp_tester : public ::testing::Test { public: void SetUp() { db_initial_setup(); } }; TEST_F(sqlite_cpp_tester, given_a_valid_db_file_open_close_return_success) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); EXPECT_EQ(db.close(), SQLITE_OK); } TEST_F(sqlite_cpp_tester, given_a_valid_insert_select_returns_same_as_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); std::vector&lt;sql::column_values&gt; fields { {&quot;name&quot;, &quot;Mickey Mouse&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755123456&quot;}, {&quot;ddi&quot;, &quot;01222333333&quot;}, {&quot;switchboard&quot;, &quot;01222444444&quot;}, {&quot;address1&quot;, &quot;1 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;mickey@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;delightful mouse&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields), SQLITE_OK); int lastrowid = db.last_insert_rowid(); const std::vector&lt;sql::where_binding&gt;&amp; bindings { {&quot;rowid&quot;, lastrowid} }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_star(&quot;contacts&quot;, &quot;WHERE rowid=:rowid&quot;, bindings, results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], fields[13].column_value); } TEST_F(sqlite_cpp_tester, given_a_valid_insert_then_update_select_returns_same_as_updated) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); std::vector&lt;sql::column_values&gt; fields{ {&quot;name&quot;, &quot;Mickey Mouse&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755123456&quot;}, {&quot;ddi&quot;, &quot;01222333333&quot;}, {&quot;switchboard&quot;, &quot;01222444444&quot;}, {&quot;address1&quot;, &quot;1 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;mickey@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;delightful mouse&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields), SQLITE_OK); int lastrowid = db.last_insert_rowid(); // UPDATE std::vector&lt;sql::column_values&gt; updated_fields{ {&quot;name&quot;, &quot;Donald Duck&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755654321&quot;}, {&quot;ddi&quot;, &quot;01222444444&quot;}, {&quot;switchboard&quot;, &quot;01222555555&quot;}, {&quot;address1&quot;, &quot;2 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;donald@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;quackers&quot;} }; const std::vector&lt;where_binding&gt;&amp; update_bindings{ {&quot;rowid&quot;, lastrowid} }; const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; EXPECT_EQ(db.update(&quot;contacts&quot;, updated_fields, where_clause, update_bindings), SQLITE_OK); std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;contacts&quot;, { &quot;rowid&quot;, &quot;*&quot; }, &quot;WHERE rowid=:rowid&quot;, update_bindings, results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], updated_fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], updated_fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], updated_fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], updated_fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], updated_fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], updated_fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], updated_fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], updated_fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], updated_fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], updated_fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], updated_fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], updated_fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], updated_fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], updated_fields[13].column_value); } TEST_F(sqlite_cpp_tester, given_a_single_quote_in_notes_field_select_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); std::vector&lt;sql::column_values&gt; fields{ {&quot;name&quot;, &quot;Sean O'Hennessey&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755123456&quot;}, {&quot;ddi&quot;, &quot;01222333333&quot;}, {&quot;switchboard&quot;, &quot;01222444444&quot;}, {&quot;address1&quot;, &quot;1 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;mickey@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;single quote symbol is '&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields), SQLITE_OK); int lastrowid = db.last_insert_rowid(); const std::vector&lt;where_binding&gt;&amp; update_bindings{ {&quot;rowid&quot;, lastrowid} }; const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;contacts&quot;, { &quot;rowid&quot;, &quot;*&quot; }, &quot;WHERE rowid=:rowid&quot;, update_bindings, results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], fields[13].column_value); } TEST_F(sqlite_cpp_tester, given_non_alphanumeric_characters_inserted_select_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); std::vector&lt;sql::column_values&gt; fields{ {&quot;name&quot;, &quot;&lt;----------------------&gt;'&quot;}, {&quot;company&quot;, &quot;D\nisne y&quot;}, {&quot;mobile&quot;, &quot;!!!\&quot;0775512345'''6&quot;}, {&quot;ddi&quot;, &quot;{}====================&quot;}, {&quot;switchboard&quot;, &quot;++++++++++++++++++++++++&quot;}, {&quot;address1&quot;, &quot;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&quot;}, {&quot;address2&quot;, &quot;``````````¬|&quot;}, {&quot;address3&quot;, &quot;;'#:@~&quot;}, {&quot;address4&quot;, &quot;'''''''''''''''''''&quot;}, {&quot;postcode&quot;, &quot;!\&quot;£$%^&amp;*()_+&quot;}, {&quot;email&quot;, &quot;***************************&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;1\n2\n3\n4\n5\n&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields), SQLITE_OK); int lastrowid = db.last_insert_rowid(); const std::vector&lt;where_binding&gt;&amp; update_bindings{ {&quot;rowid&quot;, lastrowid} }; const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;contacts&quot;, { &quot;rowid&quot;, &quot;*&quot; }, &quot;WHERE rowid=:rowid&quot;, update_bindings, results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], fields[13].column_value); } TEST_F(sqlite_cpp_tester, add_integer_value_select_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); std::vector&lt;sql::column_values&gt; fields{ {&quot;callerid&quot;, &quot;0775512345&quot;}, {&quot;contactid&quot;, 2} }; EXPECT_EQ(db.insert_into(&quot;calls&quot;, fields), SQLITE_OK); const std::vector&lt;where_binding&gt;&amp; bindings{ {&quot;contactid&quot;, 2} }; const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;calls&quot;, { &quot;timestamp&quot;, &quot;callerid&quot;, &quot;contactid&quot; }, &quot;WHERE contactid=:contactid&quot;, bindings, results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;callerid&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;contactid&quot;], fields[1].column_value); // get 3 columns back EXPECT_EQ(results[0].size(), 3u); } // SELECT (using LIKE) TEST_F(sqlite_cpp_tester, add_integer_value_select_like_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); std::vector&lt;sql::column_values&gt; fields{ {&quot;callerid&quot;, &quot;0775512345&quot;}, {&quot;contactid&quot;, 2} }; EXPECT_EQ(db.insert_into(&quot;calls&quot;, fields), SQLITE_OK); const std::vector&lt;where_binding&gt;&amp; bindings{ {&quot;callerid&quot;, &quot;077%&quot;} }; const std::string where_clause{ &quot;WHERE callerid LIKE :callerid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;calls&quot;, { &quot;timestamp&quot;, &quot;callerid&quot;, &quot;contactid&quot; }, where_clause, bindings, results), SQLITE_OK); EXPECT_EQ(results.size(), 2u); EXPECT_EQ(std::get&lt;std::string&gt;(results[0][&quot;callerid&quot;]), &quot;07788111222&quot;); EXPECT_EQ(std::get&lt;int&gt;(results[0][&quot;contactid&quot;]), 1); EXPECT_EQ(results[1][&quot;callerid&quot;], fields[0].column_value); EXPECT_EQ(results[1][&quot;contactid&quot;], fields[1].column_value); // get 3 columns back EXPECT_EQ(results[0].size(), 3u); } // GETCALLS TEST_F(sqlite_cpp_tester, join_returning_data_from_two_tables_returns_correct_data) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const std::vector&lt;std::string&gt;&amp; fields { &quot;calls.timestamp&quot;, &quot;contacts.name&quot;, &quot;calls.callerid&quot;, &quot;contacts.url&quot; }; const std::string where_clause{ &quot;LEFT JOIN contacts ON calls.contactid = contacts.rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;calls&quot;, fields, where_clause, {}, results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(std::get&lt;2&gt;(results[0][&quot;callerid&quot;]), &quot;07788111222&quot;); EXPECT_EQ(std::get&lt;2&gt;(results[0][&quot;name&quot;]), &quot;Test Person&quot;); EXPECT_EQ(std::get&lt;2&gt;(results[0][&quot;url&quot;]), &quot;www.house.com&quot;); EXPECT_NE(std::get&lt;2&gt;(results[0][&quot;timestamp&quot;]), &quot;&quot;); } int main(int argc, char **argv) { testing::InitGoogleTest(&amp;argc, argv); return RUN_ALL_TESTS(); } </code></pre>
[]
[ { "body": "<p>Just a few quick observations:</p>\n<pre><code>/* sqlite constructor */\n</code></pre>\n<p>Duh. Keep comments useful and meaningful. You don't need to explain that the ctor and dtor are those things.</p>\n<pre><code>(const std::string&amp; table_name, \n</code></pre>\n<p>Suggest you use <code>std::string_view</code> (by value) for parameters instead. This is more optimal if you pass a lexical string literal, as it doesn't have to copy the data into a <code>std::string</code> first! And it's just as fast when passed existing <code>std::string</code> instances.</p>\n<p>All the functions return <code>int</code> — what does that mean? I suppose it is passing through the underlying sqlite function results. I suggest you define a &quot;strong type&quot; for that, e.g. <code>enum class sqlite_result : int {};</code></p>\n<p>Don't use <code>endl</code>, as explained many times on this board.</p>\n<p>Why do you use <code>fprintf</code> in some places and ostreams in others? You know that <code>cerr</code> exists, right?</p>\n<pre><code>std::vector&lt;sql::column_values&gt; params {\n {&quot;name&quot;, &quot;Mickey Mouse&quot;},\n {&quot;age&quot;, 12},\n {&quot;photo&quot;, buffer}\n };\n</code></pre>\n<p>Should be at least <code>const</code>, can be <code>constexpr</code> in this case. You might think that test code is not important, but people will use it as an exemplar and copy it to use as a starting point in real uses, so it should be fully robust and illustrative of best practices.</p>\n<p>You're requiring a <code>std::vector</code> for the fields. You should instead make it a template that takes a pair of iterators, or if you are using C++20 or otherwise have ranges3 available, use a range view. Then you can pass it, for example, a plain C array in your examples and not need to construct a vector in dynamic memory, use vectors with non-default allocators, <code>std::pmr::vector</code>, Boost containers, etc.</p>\n<pre><code>const std::vector&lt;where_binding&gt;&amp; bindings{\n {&quot;rowid&quot;, lastrowid}\n };\n</code></pre>\n<p>What does the <code>&amp;</code> do here?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T14:42:09.640", "Id": "260456", "ParentId": "260450", "Score": "2" } } ]
{ "AcceptedAnswerId": "260456", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T11:56:09.423", "Id": "260450", "Score": "2", "Tags": [ "c++", "sqlite", "wrapper" ], "Title": "Thin C++ wrapper for sqlite3 C library" }
260450
<p><strong>Hello everyone!</strong></p> <p>In this task I had to create docstring generator. I'm just wondering how you see this problem, I have to &quot;take data&quot; from the dictionary</p> <pre><code>{'Args': None, 'Returns': None, 'Raises': None, 'Attributes': None, 'Summary': None, 'Description': None} </code></pre> <p>and then generate docstring in the correct order.</p> <p>This is my solution:</p> <pre><code>import textwrap def gendoc(config): docstring = [] if (&quot;Summary&quot; in config) and (config[&quot;Summary&quot;] is not None): docstring.append(config[&quot;Summary&quot;]) if (&quot;Args&quot; in config) and (config[&quot;Args&quot;] is not None): args = [&quot;Args:&quot;] + [f&quot;\t{arg}: Function argument&quot; for arg in config[&quot;Args&quot;]] docstring += args if (&quot;Attributes&quot; in config) and (config[&quot;Attributes&quot;] is not None): attr = [&quot;Attributes:&quot;] + [f&quot;\t{attr}: Information about parameter {attr}&quot; for attr in config[&quot;Attributes&quot;]] docstring += attr if (&quot;Raises&quot; in config) and (config[&quot;Raises&quot;] is not None): raises = [&quot;Raises: &quot;] + [f&quot;\t {config.get('Raises')}&quot;] docstring += raises if (&quot;Returns&quot; in config) and (config[&quot;Returns&quot;] is not None): returns = [&quot;Returns: &quot;] + [f&quot;\t {config.get('Returns')}&quot;] docstring += returns if (&quot;Description&quot; in config) and (config[&quot;Description&quot;] is not None): value = config.get('Description') wrapper=textwrap.TextWrapper(subsequent_indent= '\t', width = 120) description = [&quot;Description: &quot;] + [f&quot;\t{wrapper.fill(value)}&quot;] docstring += description if (&quot;Todo&quot; in config) and (config[&quot;Todo&quot;] is not None): star = &quot;*&quot; todo = [&quot;Todo:&quot;] + [f&quot;\t{star} {todo}&quot; for todo in config[&quot;Todo&quot;]] docstring += todo docstring = &quot;\n\n&quot;.join(docstring) return docstring </code></pre> <p>My output:</p> <pre><code>The Pear object describes the properties of pears. Args: a: Function argument b: Function argument Attributes: a: Information about parameter a b: Information about parameter b Raises: AttributeError: The ``Raises`` section is a list of all exceptions that are relevant to the interface. Returns: The return value. True for success, False otherwise. Description: The description may span multiple lines. Following lines should be indented. The type is optional. The description may span multiple lines. Following lines should be indented. The type is optional.The description may span multiple lines. Following lines should be indented. The type is optional.The description may span multiple lines. Following lines should be indented. The type is optional. Todo: * Do something * Something else </code></pre> <p>Any tips how to make this SHORTER and more neat, closer to a advanced or just better solution will be definitely on point. Thanks in advance!</p> <p><strong>Have a great day!</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T12:44:45.493", "Id": "514134", "Score": "3", "body": "Welcome to the Code Review Community, I hope you get some good answers." } ]
[ { "body": "<ul>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>if (&quot;Summary&quot; in config) and (config[&quot;Summary&quot;] is not None):\n</code></pre>\n</blockquote>\n<p>Can be simplified to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if config.get(&quot;summary&quot;) is not None:\n</code></pre>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>args = [&quot;Args:&quot;] + [f&quot;\\t{arg}: Function argument&quot; for arg in config[&quot;Args&quot;]]\nattr = [&quot;Attributes:&quot;] + [f&quot;\\t{attr}: Information about parameter {attr}&quot; for attr in config[&quot;Attributes&quot;]]\ntodo = [&quot;Todo:&quot;] + [f&quot;\\t{star} {todo}&quot; for todo in config[&quot;Todo&quot;]]\n</code></pre>\n</blockquote>\n<p>Can all be moved into a function.</p>\n<ul>\n<li>You always add <code>f&quot;{Name}:&quot;</code>,</li>\n<li>You always iterate through <code>config[Name]</code>, and</li>\n<li>You always format the value. Which can be provided as a format string (not an f-string).</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def format_values(config, name, fmt):\n return [f&quot;{name}:&quot;] + [fmt.format(value) for value in config[name]]\n\nformat_values(config, &quot;Args&quot;, &quot;\\t{}: Function argument&quot;)\n</code></pre>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>docstring.append(config[&quot;Summary&quot;])\nraises = [&quot;Raises: &quot;] + [f&quot;\\t {config.get('Raises')}&quot;]\nreturns = [&quot;Returns: &quot;] + [f&quot;\\t {config.get('Returns')}&quot;]\n</code></pre>\n</blockquote>\n<p>Can all be moved into a function.</p>\n<ul>\n<li>You add <code>f&quot;{Name}: &quot;</code> except for Summary,</li>\n<li>You always add <code>config[Name]</code>, and</li>\n<li>You always format the value. (Summary would be <code>&quot;{}&quot;</code>)</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def format_value(config, name, fmt, head=True):\n return ([f&quot;{name}: &quot;] if head else []) + [fmt.format(config[name])]\n\nformat_value(config, &quot;Summary&quot;, &quot;{}&quot;, False)\n</code></pre>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>value = config.get('Description')\nwrapper=textwrap.TextWrapper(subsequent_indent= '\\t', width = 120)\ndescription = [&quot;Description: &quot;] + [f&quot;\\t{wrapper.fill(value)}&quot;]\ndocstring += description\n</code></pre>\n</blockquote>\n<p>To be able to handle Description we can change <code>format_value</code> (and optionally <code>format_values</code> for consistency) to take a <code>lambda</code> to decide how to display the value.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def format_value(config, name, fmt, head=True):\n return ([f&quot;{name}: &quot;] if head else []) + [fmt(config[name])]\n\nwrapper = textwrap.TextWrapper(subsequent_indent='\\t', width=120)\ndocstring += format_value(config, &quot;Description&quot;, lambda value: f&quot;\\t{wrapper.fill(value)}&quot;)\n</code></pre>\n</li>\n</ul>\n<p>Lets look at how the code looks now:</p>\n<pre><code>import textwrap\n\n\ndef format_value(config, name, fmt, head=True):\n return ([f&quot;{name}: &quot;] if head else []) + [fmt(config[name])]\n\n\ndef format_values(config, name, fmt):\n return [f&quot;{name}:&quot;] + [fmt(value) for value in config[name]]\n\n\ndef gendoc(config):\n docstring = []\n if None is not config.get(&quot;Summary&quot;):\n docstring += format_value(config, &quot;Summary&quot;, lambda summary: summary, False)\n if None is not config.get(&quot;Args&quot;):\n docstring += format_values(config, &quot;Args&quot;, lambda arg: f&quot;\\t{arg}: Function argument&quot;)\n if None is not config.get(&quot;Attributes&quot;):\n docstring += format_values(config, &quot;Attributes&quot;, lambda attr: f&quot;\\t{arg}: Information about parameter {arg}&quot;)\n if None is not config.get(&quot;Raises&quot;):\n docstring += format_value(config, &quot;Raises&quot;, lambda raises: f&quot;\\t {raises}&quot;)\n if None is not config.get(&quot;Returns&quot;):\n docstring += format_value(config, &quot;Returns&quot;, lambda returns: f&quot;\\t {returns}&quot;)\n if None is not config.get(&quot;Description&quot;):\n wrapper = textwrap.TextWrapper(subsequent_indent='\\t', width=120)\n docstring += format_value(config, &quot;Description&quot;, lambda value: f&quot;\\t{wrapper.fill(value)}&quot;)\n if None is not config.get(&quot;Todo&quot;):\n star = &quot;*&quot;\n docstring += format_values(config, &quot;Todo&quot;, lambda todo: f&quot;\\t{star} {todo}&quot;)\n\n docstring = &quot;\\n\\n&quot;.join(docstring)\n return docstring\n</code></pre>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>if None is not config.get({name}):\n docstring += format_value(config, {name}, ...)\n</code></pre>\n</blockquote>\n<p>We can see we are duplicating the above pseudocode.\nLets ignore the <code>fmt</code> and <code>head</code> arguments to <code>format_value</code> and <code>format_values</code>.</p>\n<p>We could change the code to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>docstring = []\nfor name, fn in ...:\n if config.get(name) is not None:\n docstring += fn(config, name)\n</code></pre>\n<p>We can change <code>format_value</code> and <code>format_values</code> so we provide the <code>fmt</code> and <code>head</code>.\nWe then return another function which takes <code>config</code> and <code>name</code> to call in the loop.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def format_value(fmt, head=True):\n def inner(config, name):\n return ([f&quot;{name}: &quot;] if head else []) + [fmt(config[name])]\n return inner\n\nformat_value(&quot;{}&quot;)(config, &quot;Summary&quot;)\n</code></pre>\n<p>Next we can define a dictionary to store the result of the first call to <code>format_value</code> and <code>format_values</code>.\nAnd then change the code to iterate over the dictionary.</p>\n<p>Final code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import textwrap\n\n\ndef format_value(fmt, head=True):\n def inner(config, name):\n return ([f&quot;{name}: &quot;] if head else []) + [fmt(config[name])]\n return inner\n\n\ndef format_values(fmt):\n def inner(config, name):\n return [f&quot;{name}:&quot;] + [fmt(value) for value in config[name]]\n return inner\n\n\nwrapper = textwrap.TextWrapper(subsequent_indent='\\t', width=120)\nstar = &quot;*&quot;\n\nFORMATS = {\n &quot;Summary&quot;: format_value(lambda summary: f&quot;{summary}&quot;, False),\n &quot;Args&quot;: format_values(lambda arg: f&quot;\\t{arg}: Function argument&quot;),\n &quot;Attributes&quot;: format_values(lambda attr: f&quot;\\t{arg}: Information about parameter {arg}&quot;),\n &quot;Raises&quot;: format_value(lambda raises: f&quot;\\t {raises}&quot;),\n &quot;Returns&quot;: format_value(lambda returns: f&quot;\\t {returns}&quot;),\n &quot;Description&quot;: format_value(lambda value: f&quot;\\t{wrapper.fill(value)}&quot;),\n &quot;Todo&quot;: format_values(lambda todo: f&quot;\\t{star} {todo}&quot;),\n}\n\n\ndef gendoc(config):\n docstring = []\n for name, fn in FORMATS.items():\n if config.get(name) is not None:\n docstring += fn(config, name)\n return &quot;\\n\\n&quot;.join(docstring)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T18:35:24.843", "Id": "514158", "Score": "4", "body": "As an alternative to the \"format\" lambdas, you could use `string.format`, e.g., `\"Args\": format_values(\"\\t{}: Function argument\".format)`. I leave it to the reader to decide which is clearer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T16:59:28.183", "Id": "260460", "ParentId": "260451", "Score": "5" } }, { "body": "<ul>\n<li>Avoid representing internal data as dictionaries if possible. As @RootTwo indicates, it's trivial to initialize a dataclass from a dict via the <code>**</code> kwarg-splatting operator if that's needed.</li>\n<li>Would be nice to support output to string, stdout or a file through wrappers. <code>StringIO</code> makes this easy.</li>\n<li>Avoid <code>\\t</code> - it has medium-dependent indentation; better to have space rendering with a user-configurable indentation level.</li>\n<li>You should wrap everything, not just your description.</li>\n<li>This is a matter of opinion, but I disagree with double-newlines on the inside of your sections; reserving double-newlines for section breaks makes things clearer.</li>\n</ul>\n<h2>Example code</h2>\n<pre><code>from dataclasses import dataclass\nfrom io import StringIO\nfrom sys import stdout\nfrom textwrap import TextWrapper\nfrom typing import Optional, Tuple, Sequence, TextIO\n\nPair = Tuple[str, str]\nPairSeq = Sequence[Pair]\n\n\n@dataclass\nclass Documentation:\n summary: Optional[str] = None\n args: Optional[PairSeq] = None\n attrs: Optional[PairSeq] = None\n raises: Optional[PairSeq] = None\n returns: Optional[str] = None\n desc: Optional[str] = None\n todo: Optional[Sequence[str]] = None\n indent: int = 4\n wrap: int = 80\n\n def __post_init__(self):\n self.wrap_outer = TextWrapper(width=self.wrap).fill\n indent = ' ' * self.indent\n self.wrap_inner = TextWrapper(\n width=self.wrap,\n initial_indent=indent,\n subsequent_indent=indent,\n ).fill\n\n def __str__(self) -&gt; str:\n with StringIO() as f:\n self.to_file(f)\n return f.getvalue()\n\n def print(self) -&gt; None:\n self.to_file(stdout)\n\n def write_section(self, title: str, content: str, f: TextIO) -&gt; None:\n if content:\n f.write(f'\\n{title}:\\n')\n f.write(self.wrap_inner(content) + '\\n')\n\n def write_pairs(self, title: str, pairs: PairSeq, f: TextIO) -&gt; None:\n if pairs:\n f.write(f'\\n{title}:\\n')\n f.writelines(\n self.wrap_inner(f'{name}: {desc}') + '\\n'\n for name, desc in pairs\n )\n\n def to_file(self, f: TextIO) -&gt; None:\n if self.summary:\n f.write(self.wrap_outer(self.summary))\n\n self.write_pairs('Arguments', self.args, f)\n self.write_pairs('Attributes', self.attrs, f)\n self.write_pairs('Raises', self.raises, f)\n self.write_section('Returns', self.returns, f)\n self.write_section('Description', self.desc, f)\n\n if self.todo:\n f.write(f'\\nTodo:\\n')\n f.writelines(\n self.wrap_inner(f'* {todo}') + '\\n'\n for todo in self.todo\n )\n\n\ndef test():\n Documentation(\n summary='The Pear object describes the properties of pears.',\n args=(\n ('a', 'Function argument'),\n ('b', 'Function argument'),\n ),\n attrs=(\n ('a', 'Information about parameter a'),\n ('b',\n 'Information about parameter b. '\n 'Information about parameter b. '\n 'Information about parameter b. '\n 'Information about parameter b. '\n ),\n ),\n raises=(\n ('AttributeError',\n 'The ``Raises`` section is a list of all exceptions that are '\n 'relevant to the interface.'),\n ),\n returns='The return value. True for success, False otherwise.',\n desc='The description may span multiple lines. Following lines should '\n 'be indented. The type is optional. '\n 'The description may span multiple lines. Following lines should '\n 'be indented. The type is optional. '\n 'The description may span multiple lines. Following lines should '\n 'be indented. The type is optional. '\n 'The description may span multiple lines. Following lines should '\n 'be indented. The type is optional.',\n todo=('Do Something', 'Something else'),\n ).print()\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2>Output</h2>\n<pre><code>The Pear object describes the properties of pears.\nArguments:\n a: Function argument\n b: Function argument\n\nAttributes:\n a: Information about parameter a\n b: Information about parameter b. Information about parameter b. Information\n about parameter b. Information about parameter b.\n\nRaises:\n AttributeError: The ``Raises`` section is a list of all exceptions that are\n relevant to the interface.\n\nReturns:\n The return value. True for success, False otherwise.\n\nDescription:\n The description may span multiple lines. Following lines should be indented.\n The type is optional. The description may span multiple lines. Following\n lines should be indented. The type is optional. The description may span\n multiple lines. Following lines should be indented. The type is optional.\n The description may span multiple lines. Following lines should be indented.\n The type is optional.\n\nTodo:\n * Do Something\n * Something else\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T21:19:55.407", "Id": "514162", "Score": "2", "body": "@Daro, from the problem description, it sounds like the docstring configuration is provided as a dictionary. Fortunately, the Documentation dataclass can be initialized from a dictionary like so: `Documentation(**config)`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T17:57:06.543", "Id": "260463", "ParentId": "260451", "Score": "5" } } ]
{ "AcceptedAnswerId": "260460", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T12:06:05.070", "Id": "260451", "Score": "6", "Tags": [ "python", "generator" ], "Title": "Docstring generator in Google type" }
260451
<p>I'm feeling this code is messy and also repeats between all components that needs to handle backend data. Any comment is appreciated.</p> <pre><code>//the stored version localVersion = undefined; //injecting the redux service and the backend service(in case there is no version defined in reduxService) constructor( private reduxService: ReduxService, private backendService: BackendService) { } ngOnInit(): void { this.getVersion().subscribe(v =&gt; { this.localVersion = {...v}; }); this.setlocalVersion().subscribe(v =&gt; { this.localVersion = {...v}; }); } private getlocalVersion(): Observable&lt;localVersionResponseModel&gt; { //this is made to get the first value for the localId. const id = this.reduxService.getValue&lt;IlocalVersionStateData&gt;(LabelsEnum.version); //maybe the id is not set in reduxService. return (id) ? this.backendService.getlocalVersion(id.localVersionId) : of(undefined); } private setlocalVersion(): Observable&lt;localVersionResponseModel&gt; { return this.reduxService.getObservableValue&lt;IlocalVersionStateData&gt;(LabelsEnum.version) .pipe( takeUntil(this.Unsubscribe), //switchMap in case of backend service response. switchMap(vStateData =&gt; { return this.backendService.getlocalVersion(vStateData.localVersionId); }) ); } //removes the subscription when component is destroyed ngOnDestroy(): void { this.Unsubscribe.next(); this.Unsubscribe.complete(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T14:08:11.023", "Id": "260452", "Score": "0", "Tags": [ "javascript", "typescript", "angular-2+", "redux" ], "Title": "Handling the first value for a variable, with Redux and the Backend service. Angular, Redux" }
260452
<p>What do you think about this read only table design, regarding performance?</p> <p><strong>package jsql</strong></p> <p><code>Main.java</code></p> <pre><code>package jsql; public class Main { public static void main(String[] args) { Record head = new Record(&quot;given name&quot;, &quot;family name&quot;, &quot;street&quot;, &quot;postal code&quot;, &quot;city&quot;); Record jimmy = new Record(&quot;James&quot;, &quot;Blunt&quot;, &quot;Rochesterfield 1&quot;, &quot;1234&quot;, &quot;Bloomville&quot;); Record joey = new Record(&quot;John&quot;, &quot;Smith&quot;, &quot;Green Way 5&quot;, &quot;5678&quot;, &quot;Harrisburg&quot;); Table friends = new Table(head, jimmy, joey); if(friends.isValid) { System.out.println(friends.toString()); } else { System.err.println(&quot;Error: Invalid table with hash code: &quot; + friends.hashCode()); } } } </code></pre> <p><code>Record.java</code></p> <pre><code>package jsql; class Record { final String entry[]; private static final String SEPARATOR = &quot;\t&quot;; public String toString() { String temp = this.entry[0]; for(int i = 1; i &lt; this.entry.length; i++) { temp = temp.concat(SEPARATOR); temp = temp.concat(this.entry[i]); } return temp; } Record(String...entry) { this.entry = entry; } } </code></pre> <p><code>Table.java</code></p> <pre><code>package jsql; class Table { final Record record[]; final boolean isValid; private static final String NEWLINE = &quot;\n&quot;; public String toString() { String temp = this.record[0].toString(); for(int i = 1; i &lt; this.record.length; i++) { temp = temp.concat(NEWLINE); temp = temp.concat(this.record[i].toString()); } return temp; } static boolean validate(Table t) { for(int i = 1; i &lt; t.record.length; i++) { if(t.record[0].entry.length != t.record[i].entry.length) { return false; } } return true; } Table(Record...record) { this.record = record; this.isValid = validate(this); } } </code></pre>
[]
[ { "body": "<p>You should use exceptions to indicate that something fails, rather than just printing something somewhere that might very easily get ignored, while the program goes on with invalid data. Classes should have the responsibility of ensuring valid state (not additional methods or auxiliary attributes).</p>\n<p>Basically do the validate in the constructor, and then:</p>\n<pre><code>try {\n Table friends = new Table(head, jimmy, joey);\n} catch(InvalidRecordLength e) {\n // Do something. This allows you to just print if you don't care about validity too much, but will stop other users from unknowingly continuing with invalid state\n}\n</code></pre>\n<p>The header should be stored ideally in a different class (you might want to store constraints on columns, like types), and more importantly in a different place than records[0]. This is because the header is not a record. This will save you from a lot of confusing logic like the one you have in validate(), which would get repeated for every method reading the table.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T16:51:17.900", "Id": "260459", "ParentId": "260453", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T14:16:29.060", "Id": "260453", "Score": "-1", "Tags": [ "java" ], "Title": "What do you think about this read only table design, regarding performance?" }
260453
<p>I have the following code that makes a call to an external API, processes the response and returns a string. The problem is it is taking a very long time to process. I can't do anything to the API, but I was just wondering if there is a better way of doing the rest of the code.</p> <pre><code>foreach(var item in products) { item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink); } </code></pre> <p>And the GetSiteLink method in a different class.</p> <pre><code>public async Task&lt;string&gt; GetSiteLink(int itemId, string baseLink) { var encodedUrl = HttpUtility.UrlEncode(baseLink); var response = await _client.GetAsync($&quot;apilink/{itemId}/?ulp={encodedUrl}&quot;); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); var parsedResponse = JsonConvert.DeserializeObject&lt;string[]&gt;(responseContent); return HttpUtility.UrlDecode(parsedResponse[0]); } return &quot;&quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T21:35:01.833", "Id": "514163", "Score": "0", "body": "`IDisposable`: `using var response = await ...`. It would allow to reuse the opened server connections faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T21:40:26.553", "Id": "514164", "Score": "0", "body": "Also answers in [this question](https://stackoverflow.com/q/17096201/12888024) might be useful." } ]
[ { "body": "<p>one way of solving this would be using <code>Task.WhenAll</code> the idea is to add all tasks into a list of tasks then we call <code>Task.WhenAll</code> and await the final results.</p>\n<p>Here is an example of it :</p>\n<pre><code>private async Task&lt;ProductItem&gt; SetSiteLink(ProductItem item)\n{ \n item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink); \n \n return Task.FromResult(item); \n}\n</code></pre>\n<p>then call it like this :</p>\n<pre><code>var tasks = new List&lt;Task&lt;ProductItem&gt;&gt;();\n\nforeach (var item in products)\n{\n tasks.Add(SetSiteLink(item));\n}\n\nvar results = await Task.WhenAll(tasks);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T07:14:20.680", "Id": "514309", "Score": "0", "body": "Depending on the size of the `products` and overloadness of the downstream system this approach could make the situation even worse. Instead of issuing a single request against a service which is already struggling you issue N requests. The chance of failure (or timeout) might increase with this approach. I would suggest this approach only with throttling." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T20:18:40.037", "Id": "260468", "ParentId": "260454", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T14:32:11.490", "Id": "260454", "Score": "1", "Tags": [ "c#", "api" ], "Title": "How can I optimise a foreach calling an API? The code calls an API and returns the first string reponse" }
260454
<p>I've made a <code>splitString()</code> function which receives a character and a string and returns a <code>vector&lt;string&gt;</code> containing all the string split by a character in the input string:</p> <pre><code>vector&lt;string&gt; splitString(string input, char separator) { size_t pos; vector&lt;string&gt; text; while (!input.empty()) { pos = input.find(separator); //find separator character position if (pos == string::npos) { text.push_back(input); break; } text.push_back(input.substr(0, pos)); input = input.substr(pos + 1); } return text; //returns a vector with all the strings } </code></pre> <p>Example Input(.csv):</p> <pre class="lang-none prettyprint-override"><code>name;surname;age </code></pre> <p>Output would be:</p> <pre><code>vector&lt;string&gt; contains {name, surname, age} </code></pre> <p><em>Is there any efficient way of doing this?</em></p> <p>As you can see, the <code>;</code> was deleted separating the strings.<br /> I was wondering if there is any way of adding an option to NOT delete the <code>separator</code> character, including it in the split strings.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T15:46:38.277", "Id": "514152", "Score": "0", "body": "Welcome to the Code Review Community, we can provide a better code review if you provide a unit test program that you have written the tests the function." } ]
[ { "body": "<p>If you don't want to modify the original string, you can use a <code>stringstream</code>:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;sstream&gt;\n\nstd::vector&lt;std::string&gt; splitString(const std::string input, const char&amp; delimiter) {\n\n std::vector&lt;std::string&gt; elements;\n std::stringstream stream(input);\n std::string element;\n\n while (getline(stream, element, delimiter)) {\n elements.push_back(element);\n }\n\n return elements;\n\n}\n</code></pre>\n<p>This has the added benefit of not modifying the input string. Because <code>std::stringstream</code> is an input stream, we can use <code>getline</code> to append characters to the <code>element</code> string until the delimiter is reached. This is repeated until the end of the input string.</p>\n<p>I also noticed that you're using <code>using namespace std</code>. For smaller projects like this, that's fine. But as you begin to develop bigger applications and programs, you should stick to writing <code>std::</code>, as <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">namespace collisions</a> can happen if you're using the same function names.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T16:15:29.767", "Id": "514199", "Score": "0", "body": "Your answer is a more inefficient solution when more efficiency is asked for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T22:31:13.450", "Id": "260474", "ParentId": "260457", "Score": "0" } }, { "body": "<p>What are the expensive operations you do?</p>\n<ol>\n<li><p>Allocating memory for the copy of a <code>std::string</code> passed into <code>splitString()</code>.</p>\n<p>This can be fixed by accepting a <code>std::string_view</code> instead, or at least a constant reference instead of a copy.</p>\n<p>See <a href=\"//stackoverflow.com/questions/40127965/how-exactly-is-stdstring-view-faster-than-const-stdstring\">How exactly is std::string_view faster than const std::string&amp;?</a> and <a href=\"//stackoverflow.com/questions/20803826/what-is-string-view\">What is string_view?</a> for details.</p>\n</li>\n<li><p>Allocating memory for the <code>std::string</code>s stored in the result-vector.</p>\n<p>Those might be replacable with <code>std::string_view</code> if the argument is changed, but no guarantees. This would be a significant usage change.</p>\n</li>\n<li><p>Repeatedly shuffling all the rest of the string to the front when removing a match.</p>\n<p>Just find the target and copy / reference from there.</p>\n</li>\n<li><p>Constructing the result-elements in-place using <code>.emplace_back()</code> can also save some effort.</p>\n</li>\n</ol>\n<p>Adding the option to not remove the separator would only really make sense if you allow multiple separators.</p>\n<p>Regarding your code, I'm not sure whether you use the dreaded <code>using namespace std;</code>, or the far more benign <code>using std::string; using std::vector;</code>.<br />\nIf the former, see <a href=\"//stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a>.</p>\n<p>One behavioral point I changed: You ignore the last entry if empty. I decided to preserve it always, thus even an empty string gets at least one result.</p>\n<pre><code>auto splitString(std::string_view in, char sep) {\n std::vector&lt;std::string_view&gt; r;\n r.reserve(std::count(in.begin(), in.end(), sep) + 1); // optional\n for (auto p = in.begin();; ++p) {\n auto q = p;\n p = std::find(p, in.end(), sep);\n r.emplace_back(q, p);\n if (p == in.end())\n return r;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T20:58:49.777", "Id": "514212", "Score": "0", "body": "Good code :) Minor issue: The algorithm in the question returns an empty vector if the input string is empty. In this answer, a vector with a single empty string is returned instead. However, this can be fixed easily." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:01:37.203", "Id": "514213", "Score": "0", "body": "@pschill Good for seeing that. I took the naming more seriously... Imho, treating the last entry as non-existent if empty is a defect. But I should have written that down." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:09:09.277", "Id": "514215", "Score": "0", "body": "I agree. This version is more consistent." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T16:44:51.497", "Id": "260499", "ParentId": "260457", "Score": "4" } }, { "body": "<p>I mean no offense but this is one of the worst implementations and least efficient implementations of split.</p>\n<p>Think what this operation does <code>input = input.substr(pos + 1);</code>. It copies all data past <code>pos</code> and store it in another instance of a string. Basically, if input had <code>N</code> strings each of size <code>K</code> then this algo would take <code>O(N^2 K)</code> operations which is too much. It shouldn't be over <code>O(NK)</code> the total number of elements.</p>\n<p>Have you heard of GTA V bug that caused loading times to be several minutes for a dumb reasons? See this link <a href=\"https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/\" rel=\"nofollow noreferrer\">GTA V fix</a>. It turns out that it spent the whole time loading a 12mb json file - for a dumb reason. Something similar to what you have only more C-like.</p>\n<p>@Deduplicator wrote a decent fix to the implementation. While @Linny used a <code>stringstream</code> for this purpose... it is more semantic but such text streams are generally considered outdated and better proposals are coming in. Also Deduplicator's implementation is more efficient.</p>\n<p>Although, in general, <code>split</code> is fundamentally wrong function to use.\nIt's not an efficient parsing tool. Normally, for efficient parsing one iterates parsing algo on each element instead of running split.</p>\n<p>Say, you have a simple algorithm - you convert each string element into a double and expect a <code>vector&lt;double&gt;</code> as output. Is it efficient to first create <code>vector&lt;string&gt;</code> and then convert it to <code>vector&lt;double&gt;</code> or it's preferable to run conversion in-place and return the end result?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T18:34:29.400", "Id": "260506", "ParentId": "260457", "Score": "0" } }, { "body": "<p>I have an efficient function that splits a string based on a single character delimiter, and it does not need to allocate memory and copy the substrings, at all!</p>\n<p>First, it returns a collection of <code>string_view</code> so it just points to the locations within the original string.</p>\n<p>Second, it returns them as a <code>std::array</code> rather than a <code>vector</code> so it doesn't need to allocate memory. Instead, the <code>array</code> is allocated on the stack by the caller, and NVRO prevents the whole thing from being copied when it is returned.</p>\n<p>The downside is that you need to give the number of elements expected as a template argument. For my use case (mainly CSV files and multi-part fields such as dates) I know the number of fields expected to split into. Note that in Perl you can give <code>split</code> an optional argument that specifies the number of fields and this acts as a maximum; it stops looking for delimiters after that. Since the <code>array</code> is a fixed size, if it's actually a maximum then you'd have empty <code>string_view</code> items padding the end.</p>\n<p>If you can't handle fixed-size at all, then you can split the difference and return a dynamic collection, but still use <code>string_view</code> in it. You can also use a non-standard collection, or <code>vector</code> with an Allocator, so it allocates a certain size on the stack and only has to dynamically allocate on the heap if it exceeds that.</p>\n<pre><code>template &lt;size_t N&gt;\nauto split (char separator, std::string_view input)\n{\n std::array&lt;std::string_view, N&gt; results; \n auto current = input.begin();\n const auto End = input.end();\n for (auto&amp; part : results)\n {\n if (current == End) {\n const bool is_last_part = &amp;part == &amp;(results.back());\n if (!is_last_part) throw std::invalid_argument (&quot;not enough parts to split&quot;);\n }\n auto delim = std::find (current, End, separator);\n part = { &amp;*current, size_t(delim-current) };\n current = delim;\n if (delim != End) ++current;\n }\n if (current != End) throw std::invalid_argument (&quot;too many parts to split&quot;);\n return results;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:31:02.290", "Id": "260563", "ParentId": "260457", "Score": "0" } } ]
{ "AcceptedAnswerId": "260499", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T15:28:09.417", "Id": "260457", "Score": "4", "Tags": [ "c++", "strings", "vectors" ], "Title": "Efficiently splitting a string in C++" }
260457
<p>So I have recently written a bubble sort in java and was wondering if the code is correct and if there was any way to make it even more efficient.</p> <p>Here is my code:</p> <pre><code>void bubbleSort(int array[], int num){ if(num == 1) return; for(int i = 0; i &lt; num - 1; i++){ if(array[i] &gt; array[i+1]){ int num2 = array[i]; array[i] = array[i+1]; array[i+1] = num2; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T17:48:30.813", "Id": "514157", "Score": "0", "body": "What's the point of `num`? Did you translate this code from C or something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T23:17:13.710", "Id": "514166", "Score": "0", "body": "Generally the correct advice here is \"don't write sort routines\", except for instructional purposes. Use built-in sort methods if at all possible. I confess to having ignored this advice in the past." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T13:27:04.620", "Id": "514189", "Score": "1", "body": "It is almost a bubble sort, it is missing the outer loop." } ]
[ { "body": "<p>The first question you should ask is why implement Bubble Sort in Java? Java has sorting built-in. So you could replace calls to your <code>bubbleSort(data, num)</code> with <code>Arrays.sort(data, 0, num)</code> to get a sorted array. Or if you just want to sort the whole thing, <code>Arrays.sort(data)</code>. You can even take advantage of parallelism with <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#parallelSort(int%5B%5D)\" rel=\"nofollow noreferrer\"><code>Arrays.parallelSort(data)</code></a>.</p>\n<p>The main reason to implement a Bubble Sort is that it can be built to verify that an array is already sorted and efficiently sort an almost sorted array. But your code does not do that. In fact, your code does not actually sort unless the data is almost sorted already.</p>\n<p>Consider an input of <code>{ 4, 3, 2, 1 }</code>. Your code will go through the following steps</p>\n<pre><code>{ 3, 4, 2, 1 }\n{ 3, 2, 4, 1 }\n{ 3, 2, 1, 4 }\n</code></pre>\n<p>Now the loop ends. You have successfully moved the <code>4</code> into the correct position (and the <code>2</code> happens to be in the right position). But the <code>3</code> and <code>1</code> are out of position. You've essentially done a quarter of the work. You would need to run that function twice more to finish the sort. And you'd generally run it a third time to verify that you are finished.</p>\n<pre><code>class BubbleSort {\n\n public boolean bubble(int[] data, int top) {\n boolean swapped = false;\n for (int i = 1; i &lt; top; i++) {\n if (data[i - 1] &gt; data[i]) {\n int temp = data[i - 1];\n data[i - 1] = data[i];\n data[i] = temp;\n swapped = true;\n }\n }\n\n return swapped;\n }\n\n}\n</code></pre>\n<p>Prefer verb names for methods. I would call it <code>sort</code>, except that this doesn't sort. It just bubbles the largest item to the last position. So I simply call it <code>bubble</code>.</p>\n<p>I prefer names like <code>data</code> to names like <code>array</code>.</p>\n<p>I removed your initial check. The <code>for</code> loop will not run in that case, having the same effect. So you don't need the initial check.</p>\n<p>This version returns a <code>boolean</code> to say whether the method did anything. How would we know that it was sorted? Then the data would be in order and we'd make no swaps. So this tracks whether it swapped or not. If it did not, it's sorted. If it did swap, it's not sorted.</p>\n<p>I don't check it, but <code>top</code> has to be less than or equal to <code>data.length</code>. If greater, you will get an array out of bounds exception (unless <code>top</code> is <code>1</code> and the array is empty, in which case it is sorted and will just return).</p>\n<p>You could write a Bubble Sort using this method. Note that if you want to bubble the entire array, you don't need <code>top</code>. Just use <code>data.length</code>. But there is a reason to have a separate <code>top</code> if you're calling this inside a Bubble Sort. Hint: note that the <code>4</code> is in the correct position (last) after the first pass.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T22:38:18.800", "Id": "260475", "ParentId": "260462", "Score": "1" } } ]
{ "AcceptedAnswerId": "260475", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T17:31:45.240", "Id": "260462", "Score": "-2", "Tags": [ "java" ], "Title": "What is the most best way to write a bubble sort in java?" }
260462
<p>Im writing this simple program for school and using NumberFormat on all the variables seems very repetitive (Note that we were asked to use the <code>NumberFormat</code> method). Is there any way to clean this code so it doesn't look so cluttered?</p> <pre><code>import java.util.Scanner; import java.text.NumberFormat; public class CarPrice { public static void main(String[] args) { double priceInitial; double HST; double PDI_CHARGE = 0.02; String makeModel; Scanner scan = new Scanner(System.in); System.out.print(&quot;makeModel?: &quot;); makeModel = scan.nextLine().toUpperCase(); do { System.out.print(&quot;Price?: &quot;); priceInitial = scan.nextDouble(); if (priceInitial &lt; 0) { System.out.println(&quot;Enter A Value Above 0&quot;); } else { System.out.println(priceInitial); break; } } while (true); do { System.out.print(&quot;HST?: &quot;); HST = scan.nextDouble(); if (HST &lt; 0) { System.out.println(&quot;Enter A Value Above 0&quot;); } else { System.out.println(HST); break; } } while (true); double tax = priceInitial * (HST / 100) + priceInitial; double PDI = (tax + priceInitial) * PDI_CHARGE; double AfterPDI = PDI + tax; String PDI_Print = NumberFormat.getCurrencyInstance().format(PDI); String tax_Print = NumberFormat.getCurrencyInstance().format(tax); String priceInitial_Print = NumberFormat.getCurrencyInstance().format(priceInitial); String tax_Amount = NumberFormat.getPercentInstance().format(HST / 100); String AfterPDI_Print = NumberFormat.getCurrencyInstance().format(AfterPDI); System.out.println(&quot;Congrats! Your &quot; + makeModel + &quot; is &quot; + priceInitial_Print + &quot;\n Your total after &quot; + tax_Amount + &quot; HST is &quot; + tax_Print + &quot;\n with a PDI fee of &quot; + PDI_Print + &quot;\n making your total &quot; + AfterPDI_Print); } } </code></pre>
[]
[ { "body": "<p>The most important approach to reduce duplicated code is to put the repetitive code into a <em>parameterized method</em>. In case you use an <em>integrated Development Environment</em> (IDE) like eclipse, IntelliJ or alike they have an <em>automated Refactoring</em> to assist you with that. (lookup your IDEs online help how to invoke it).</p>\n<h3>Here is how I do this step by step</h3>\n<p>The initial step is to identify the duplicated parts. In your case the two <code>while/do</code> loops are the first candidates. They are <em>similar</em> that means that there are variables and literals that differ. We need to make them looking <em>the same</em> so that we can replace all of them with the call to the new method to be created.</p>\n<ol>\n<li><p>To be able to do that we need to provide a unique variable scope for both parts. This is done by enclosing each of the loop in braces <code>{}</code></p>\n<pre><code> {\n do {\n System.out.print(&quot;Price?: &quot;);\n priceInitial = scan.nextDouble();\n if (priceInitial &lt; 0) {\n System.out.println(&quot;Enter A Value Above 0&quot;);\n } else {\n System.out.println(priceInitial);\n break;\n }\n } while (true);\n }\n {\n do {\n System.out.print(&quot;HST?: &quot;);\n HST = scan.nextDouble();\n if (HST &lt; 0) {\n System.out.println(&quot;Enter A Value Above 0&quot;);\n } else {\n System.out.println(HST);\n break;\n }\n } while (true);\n }\n</code></pre>\n</li>\n<li><p>Inside this braces we declare and use new variables, that have the same names in both places <em>(it is important that the new variables are <strong>declared</strong> in each block individually and not reused in the lower block!)</em>:</p>\n<pre><code> {\n String message = &quot;Price?: &quot;;\n double userInput = 0;\n do {\n System.out.print(message);\n userInput = scan.nextDouble();\n if (userInput &lt; 0) {\n System.out.println(&quot;Enter A Value Above 0&quot;);\n } else {\n System.out.println(userInput);\n break;\n }\n } while (true);\n priceInitial = userInput;\n }\n {\n String message = &quot;HST?: &quot;;\n double userInput = 0;\n do {\n System.out.print(message);\n userInput = scan.nextDouble();\n if (userInput &lt; 0) {\n System.out.println(&quot;Enter A Value Above 0&quot;);\n } else {\n System.out.println(userInput);\n break;\n }\n } while (true);\n HST = userInput;\n }\n</code></pre>\n</li>\n<li><p>Now we select all the lines in the first part that look exactly the same as in the second part. Then you can apply the <em>extract method</em> refactoring of the IDE. The result should look like this:</p>\n<pre><code> {\n String message = &quot;Price?: &quot;;\n // replaces by the IDE\n double userInput = extracted(scan, message);\n priceInitial = userInput;\n }\n\n\n // new method created by the IDE behind main()\n private static double extracted(Scanner scan, String message) {\n double userInput = 0;\n do {\n System.out.print(message);\n userInput = scan.nextDouble();\n if (userInput &lt; 0) {\n System.out.println(&quot;Enter A Value Above 0&quot;);\n } else {\n System.out.println(userInput);\n break;\n }\n } while (true);\n return userInput;\n }\n</code></pre>\n<p>Of cause you should give it a better name then what the IDE suggested.</p>\n<ul>\n<li><p>In case your IDE did not replace the other occurrence of the selected code itself you copy the method call from the first block the other one and delete the obsolete code:</p>\n<pre><code> {\n String message = &quot;Price?: &quot;;\n double userInput = extracted(scan, message);\n priceInitial = userInput;\n }\n {\n String message = &quot;HST?: &quot;;\n double userInput = extracted(scan, message);\n HST = userInput;\n }\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>Then inline the new variables in both blocks</p>\n<pre><code> {\n priceInitial = extracted(scan, &quot;Price?: &quot;);\n }\n {\n HST = extracted(scan, &quot;HST?: &quot;);\n }\n</code></pre>\n</li>\n<li><p>And finally remove the blocks too.</p>\n<pre><code> priceInitial = extracted(scan, &quot;Price?: &quot;);\n HST = extracted(scan, &quot;HST?: &quot;);\n</code></pre>\n</li>\n</ol>\n<h3>Why do I suggest this rather complicated approach?</h3>\n<ul>\n<li>Each single step is a very small change to your code.</li>\n<li>You don't need to think about the signature of the new method beside giving it a good name.</li>\n<li>After each step you can compile and run the code to check if it still does what it should. (having <em>Unittest</em> will be handy...)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T23:34:30.767", "Id": "260476", "ParentId": "260464", "Score": "2" } } ]
{ "AcceptedAnswerId": "260476", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T18:20:18.357", "Id": "260464", "Score": "1", "Tags": [ "java", "formatting", "homework", "calculator" ], "Title": "Car price calculator" }
260464
<p>I am working on the improvement of the bash-awk workflow designed for the analysis of data in multiple-colums format. The script uses AWK code (which extract numbers from selected columns of the input.csv as well as does some basic stat calculations) integrated into bash script (which operates with the input files located in different folders):</p> <pre><code>#!/bin/bash home=&quot;$PWD&quot; # folder with the outputs rescore=&quot;${home}&quot;/rescore # folder with the folders to analyse storage=&quot;${home}&quot;/results csv_pattern='*_filt.csv' str_name='output.csv' while read -r d; do #awk -F, ' # set field separator to comma awk -F &quot;, *&quot; ' # set field separator to comma, followed by 0 or more whitespaces FNR==1 { if (n) { # calculate the results of previous file m = s / n # mean var = s2 / n - m * m # variance if (var &lt; 0) var = 0 # avoid an exception due to round-off error mean[suffix] = m # store the mean in an array rmsd[suffix] = sqrt(var) lowest[suffix] = min # lowest dG highest[suffix] = fourth # dG in cluster with highest pop } prefix=suffix=FILENAME sub(/_.*/, &quot;&quot;, prefix) sub(/\/[^\/]+$/, &quot;&quot;, suffix) sub(/^.*_/, &quot;&quot;, suffix) s = 0 # sum of $3 s2 = 0 # sum of $3 ** 2 n = 0 # count of samples min = 0 # lowest value of $3 (assuming all $3 &lt; 0) max = 0 # highest value of $2 (assuming all $2 &gt; 0) } FNR &gt; 1 { s += $3 s2 += $3 * $3 ++n if ($3 &lt; min) min = $3 # update the lowest value if ($2 &gt; max) { max = $2 # update popMAX fourth = $3 # update the value of dG corresponded to topPOP } } END { if (n) { # just to avoid division by zero m = s / n var = s2 / n - m * m if (var &lt; 0) var = 0 mean[suffix] = m rmsd[suffix] = sqrt(var) lowest[suffix] = min # most negative dG highest[suffix] = fourth # dG in a cluster with pop(MAX) } print &quot;Lig(CNE)&quot;, &quot;dG(&quot; prefix &quot;)&quot;, &quot;dG(popMAX)&quot; for (i in mean) printf &quot;%s %.2f %.2f\n&quot;, i, lowest[i], highest[i] }' &quot;${d}_&quot;*/${str} &gt; &quot;${rescore}/${str_name}/&quot;${d%%_*}&quot;.csv&quot; done &lt; &lt;(find . -maxdepth 1 -type d -name '*_*_*' | awk -F '[_/]' '!seen[$2]++ {print $2}') </code></pre> <p>Basically, the script operates with input.csv (shown below), extracting numbers from the third column (dG): i) detecting the minimal value in the third column (dG(min) which always corresponds to the line with ID=1), as well as the number of the dG corresponded to the maximal number in the second column (POPmax):</p> <pre><code># input *_filt.csv located in the folder 10V1_cne_lig12 ID, POP, dG 1, 142, -5.6500 # this is dG min to be extracted 2, 10, -5.5000 3, 2, -4.9500 4, 150, -4.1200 # this is dG corresponded to pop(MAX) to be extracted </code></pre> <p>finally it saves the results in another multi-column output file, contained a part of the name of each processed CSV (with corresponded prefix used as the ID of the line), as well as information regarding its dG(min) and dG(popMAX). For 5 processed input.csvs it will countain 5 lines and 3 columns with name of the initial file, dG(min) as well as dG(corresponded to popMAX):</p> <pre><code># output.csv Lig(CNE) dG(min) dG(popMAX) lig12 -5.65 -4.12 # this line from the input.csv shown above ! lig40 -5.52 -5.52 lig199 -4.81 -4.81 lig211 -5.28 -5.28 lig278 -5.76 -5.76 </code></pre> <p>I need to modify the AWK part of my script in order to add two additional columns to the output.csv contained information regarding POP (the number from the second column of the inout.csv) for each of the corresponded dG value (the has been taken from the 3rd column of the same log). So the same log should be like this</p> <pre><code># output.csv Lig(CNE). dG(min) POP(min) dG(popMAX) POP(max) lig12 -5.65 (142) -4.12 (150) # this is both dG and POP from input.csv lig40 -5.52 (30) -5.52 (34) lig199 -4.81 (111) -4.81 (300) lig211 -5.28 (4) -5.28 (12) lig278 -5.76 (132) -5.76 (150) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T14:32:17.890", "Id": "514254", "Score": "2", "body": "Just a reminder that this is Code Review, we review working code to help you improve that code. We can't help you add new features such as 2 new columns to the output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T14:35:11.713", "Id": "514256", "Score": "0", "body": "Right thank you! In fact this code is fully OK but as it can be seen it was written focusing primarily on the operations mame on the third column. So the problem is to adapt it for multi-column tasks .." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T14:05:37.007", "Id": "515321", "Score": "0", "body": "Code Review isn't about helping you modify your code for new requirements, it is about helping you to see better logic. We Review code here, Code that is already written and fulfilling all requirements." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T18:59:20.230", "Id": "260466", "Score": "2", "Tags": [ "bash", "awk" ], "Title": "bash / awk workflow operating on multi-column files" }
260466
<p>After quite some time away from Haskell I am trying to brush up. To do so I am writing some basic linear regression functionality.</p> <p>The code produces the output expected. In essence I am trying to duplicate the functionality of R's lm() function using matrix algebra in Haskell. I appreciate that there is much more to do, but before going further I would appreciate any comments/guidance etc on what I have here so far.</p> <pre><code>import Data.List import Text.Printf type Vector = [Double] type Matrix = [Vector] -- number of rows of a Matrix nrow :: Matrix -&gt; Int nrow = length -- number of columns of a Matrix ncol :: Matrix -&gt; Int ncol = length . head -- the product of a Vector multiplied by a scalar vectorScalarProduct :: Double -&gt; Vector -&gt; Vector vectorScalarProduct n vec = [ n * x | x &lt;- vec ] -- the prodict of a Matrix multiplied by a scalar matrixScalarProduct :: Double -&gt; Matrix -&gt; Matrix matrixScalarProduct n m = [ vectorScalarProduct n row | row &lt;- m ] -- the sum of two vectors vectorSum :: Vector -&gt; Vector -&gt; Vector vectorSum = zipWith (+) -- negate a Vector negV :: Vector -&gt; Vector negV = map negate -- the dot product of two vectors dotProduct :: Vector -&gt; Vector -&gt; Double dotProduct v w | length v /= length w = error &quot;dotProduct: Vectors should be of equal length&quot; | otherwise = sum ( zipWith (*) v w ) -- product of matrix and vector m %*% v mvProduct :: Matrix -&gt; Vector -&gt; Vector mvProduct m v | ncol m /= length v = error &quot;mvProduct: incompatible dimensions&quot; | otherwise = [ dotProduct row v | row &lt;- m] -- matrix multiplication matrixProduct :: Matrix -&gt; Matrix -&gt; Matrix matrixProduct m n | ncol m /= nrow n = error &quot;matrixProduct: incompatible dimensions&quot; | otherwise = [ map (dotProduct row) (transpose n) | row &lt;- m ] -- diagnonal entries of a square matrix diag :: Matrix -&gt; Vector diag m | nrow m /= ncol m = error &quot;diag: undefined for a non-square Matrox&quot; | otherwise = (zipWith (!!) m [0..]) -- cut out an element of a Vector or a row of a Matrix cut :: [a] -&gt; Int -&gt; [a] cut [] n = [] cut xs n | n &lt; 1 || n &gt; (length xs) = xs | otherwise = (take (n-1) xs) ++ drop n xs -- remove all entries in the same row and column as the i,j the entry remove :: Matrix -&gt; Int -&gt; Int -&gt; Matrix remove m i j | m == [] || i &lt; 1 || i &gt; nrow m || j &lt; 1 || j &gt; ncol m = error &quot;remove: (i,j) out of range&quot; | otherwise = transpose $ cut (transpose $ cut m i ) j -- determinant of a square matrix det :: Matrix -&gt; Double det [] = error &quot;det: determinant not defined for a 0 matrix&quot; det [[n]] = n det m = sum [ (-1)^ (j+1) * (head m)!!(j-1) * det (remove m 1 j) | j &lt;- [1..(ncol m) ] ] -- Cofactor i,j cofactor :: Matrix -&gt; Int -&gt; Int -&gt; Double cofactor m i j = (-1.0)^ (i+j) * det (remove m i j) -- Cofactor Matrix cofactorMatrix :: Matrix -&gt; Matrix cofactorMatrix m = [ [ (cofactor m i j) | j &lt;- [1..n] ] | i &lt;- [1..n] ] where n = length m -- inverse of a square Matrix inverse :: Matrix -&gt; Matrix inverse m = transpose [ [ x / (det m) | x &lt;- cofm ] | cofm &lt;- (cofactorMatrix m) ] -- Statistical functions -- sample mean mean :: Vector -&gt; Double mean [] = error &quot;mean of empty Vector is not defined&quot; mean xs = sum xs / fromIntegral (length xs) -- sample variance var :: Vector -&gt; Double var [] = error &quot;variance of empty Vector is not defined&quot; var xs = sum (map (^2) (map (subtract (mean xs)) xs)) / fromIntegral (length xs - 1) -- multiple regression toy data. -- Here, x should be a valid model matrix, typically consisting of -- one column of 1s for the intercept, and then further columns -- of data representing the covariates, by convention. x :: Matrix x = [[1, -0.6264538, -0.8204684], [1, 0.1836433, 0.4874291], [1, -0.8356286, 0.7383247], [1, 1.5952808, 0.5757814], [1, 0.3295078, -0.3053884]] y :: Vector y = [0.06485897, 1.06091561, -0.71854449, -0.04363773, 1.14905030] n = nrow x p = ncol x - 1 -- inverse of XX' needed for the hat matrix inverse_X_X' = inverse $ matrixProduct (transpose x) x -- the hat hatrix hat = matrixProduct inverse_X_X' (transpose x) -- the regression coefficient estimates betas = mvProduct hat y -- fitted values fitted = mvProduct x betas -- residuals res = vectorSum y $ negV fitted -- Total sum of squares ssto = sum $ map (^2) $ map (subtract $ mean y) y -- Sum of squared errors sse = sum $ map (^2) res -- Regression sum of squares ssr = ssto - sse -- mean squared error mse = sse / fromIntegral (n - p - 1) -- regression mean square msr = ssr / fromIntegral (p) -- F statistic for the regression f = msr / mse -- on p and n-p-1 degrees of freedom -- standard error of regression coefficients se_coef = map (sqrt) $ diag $ matrixScalarProduct mse inverse_X_X' -- r-squared r2 = 1 - (sse / ssto) -- adjusted r-squared r2_adj = 1 - (mse / var y) -- helper function for output vector_to_string :: Vector -&gt; String vector_to_string xs = unwords $ printf &quot;%.3f&quot; &lt;$&gt; xs lm :: IO() lm = putStr (&quot;Estimates: &quot; ++ (vector_to_string betas) ++ &quot;\n&quot; ++ &quot;Std. Error: &quot; ++ (vector_to_string se_coef )++ &quot;\n&quot; ++ &quot;R-squared: &quot; ++ printf &quot;%.3f&quot; r2 ++ &quot; Adj R-sq: &quot; ++ printf &quot;%.3f&quot; r2_adj ++ &quot;\n&quot; ++ &quot;F Statistic: &quot; ++ printf &quot;%.3f&quot; f ++ &quot; on &quot; ++ show p ++ &quot; and &quot; ++ show (n - p - 1) ++ &quot; degrees of freedom&quot; ++ &quot;\n&quot;) </code></pre> <p>Output:</p> <pre><code>Estimates: 0.327 0.331 -0.494 Std. Error: 0.449 0.529 0.759 R-squared: 0.242 Adj R-sq: -0.516 F Statistic: 0.319 on 2 and 2 degrees of freedom </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T03:48:12.083", "Id": "514170", "Score": "1", "body": "It all looks pretty good to me! If you were pretending this were a library you could write Haddock-styled comments. I'd also switch to using `Data.Array` for the underlying data structure, you should see some small algorithmic improvements at least." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T11:44:10.980", "Id": "514186", "Score": "0", "body": "@bisserlis thank you for the feedback :)" } ]
[ { "body": "<p>Looks good, matrix operations have been kind of a sore spot for Haskell, but this is example is easy to follow along.\nI would definitely do is get rid of all the calls to <code>error</code>. Instead, you can wrap a lot of things with <code>Either SomeFailure &lt;Success&gt;</code>, where SomeFailure could just be a string to describe how things failed. Then, you could run your computation within a an <a href=\"https://hackage.haskell.org/package/base-4.15.0.0/docs/Data-Either.html#t:Either\" rel=\"nofollow noreferrer\"><code>Either</code> monad</a>:</p>\n<p>This would give you:</p>\n<pre><code>dotProduct :: Vector -&gt; Vector -&gt; Either String Double\ndotProduct v w\n | length v /= length w = Left &quot;dotProduct: Vectors should be of equal length&quot;\n | otherwise = Right . sum $ zipWith (*) v w \n</code></pre>\n<p>For performance, I would look into using the <a href=\"https://hackage.haskell.org/package/vector-0.12.3.0/docs/Data-Vector.html\" rel=\"nofollow noreferrer\"><code>vector</code> library</a>, which is a more efficient representation than using lists.</p>\n<p>Finally, a lot of the comparisons you're making at runtime are on the length of the vectors, (<code>vectorSum</code> has a bug, it will return the shorter length argument of two differently sized args), and instead it would be nice to track the length of the vector/array at the type level, making your calculation &quot;safe&quot;. An example of this approach your be the <a href=\"https://hackage.haskell.org/package/vector-sized-1.4.3.1/docs/Data-Vector-Generic-Mutable-Sized.html\" rel=\"nofollow noreferrer\">vector-sized</a> library, and this might be a good exercise.</p>\n<p>Overall, keep up the good work!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-21T23:05:34.183", "Id": "515140", "Score": "0", "body": "Thank you. This was very helpful !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T05:28:38.673", "Id": "260687", "ParentId": "260469", "Score": "2" } } ]
{ "AcceptedAnswerId": "260687", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T20:27:39.103", "Id": "260469", "Score": "6", "Tags": [ "haskell", "statistics" ], "Title": "Linear Regression in Haskell" }
260469
<p>I've been playing with TypeORM and I wanted to create proper tests for my EventSubscriber. I also wanted those test to be independent from database connection. I believe I managed to achieve my goal. Here is my code:</p> <p>UserSubscriber.ts:</p> <pre class="lang-js prettyprint-override"><code>@EventSubscriber() export class UserSubscriber implements EntitySubscriberInterface&lt;User&gt; { private readonly passwordHasher: PasswordHasher; constructor(passwordHasher: PasswordHasher) { this.passwordHasher = passwordHasher; } listenTo() { return User; } async beforeUpdate({ entity: user, updatedColumns }: UpdateEvent&lt;User&gt;) { await this.handleUpdate( user, updatedColumns.map((value: ColumnMetadata) =&gt; value.propertyName) ); } async handleUpdate(user: User, updatedFields: string[]) { UserValidator.validate(user, updatedFields); if (updatedFields.includes(&quot;password&quot;)) { user.password = await this.passwordHasher.hash(user.password); } } async beforeInsert({ entity: user }: InsertEvent&lt;User&gt;) { await this.handleInsert(user); } async handleInsert(user: User) { UserValidator.validate(user); user.password = await this.passwordHasher.hash(user.password); } } </code></pre> <p>UserSubscriber.test.ts</p> <pre class="lang-js prettyprint-override"><code>describe(&quot;UserSubscriber&quot;, () =&gt; { const passwordHasher = new ArgonPasswordHasher(); const userSubscriber = new UserSubscriber(passwordHasher); describe(&quot;listenTo&quot;, () =&gt; { it(&quot;should return User class&quot;, () =&gt; { expect(userSubscriber.listenTo()).toBe(User); }); }); describe(&quot;handleInput&quot;, () =&gt; { const user = createValidUser(); it.each` description | value ${&quot;is empty&quot;} | ${emptyUsername} ${&quot;is shorter than 2 characters&quot;} | ${tooShortUsername} ${&quot;is longer than 255 characters&quot;} | ${tooLongUsername} `(&quot;should throw an error when user username $description&quot;, async ({ value }) =&gt; { user.username = value; await expectToThrow(() =&gt; userSubscriber.handleInsert(user)); }); it.each` description | value ${&quot;is empty&quot;} | ${empytEmail} ${&quot;is not an email&quot;} | ${notAnEmail} ${&quot;is longer than 255 characters&quot;} | ${tooLongEmail} `(&quot;should throw an error when user email $description&quot;, async ({ value }) =&gt; { user.email = value; await expectToThrow(() =&gt; userSubscriber.handleInsert(user)); }); it.each` description | value ${&quot;is empty&quot;} | ${emptyPassword} ${&quot;is shorter than 8 characters&quot;} | ${tooShortPassword} ${&quot;is longer than 32 characters&quot;} | ${tooLongPassword} ${&quot;contains no lowercase characters&quot;} | ${passwordWithoutLowercase} ${&quot;contains no uppercase characters&quot;} | ${passwordWithoutUppercase} ${&quot;contains no number characters&quot;} | ${passwordWithoutNumber} ${&quot;contains no special characters&quot;} | ${passwordWithoutSpecialCharacter} `(&quot;should throw an error when user password $description&quot;, async ({ value }) =&gt; { user.password = value; await expectToThrow(() =&gt; userSubscriber.handleInsert(user)); }); it(&quot;should not throw an error when all user fields are valid&quot;, async () =&gt; { user.username = anotherValidUsername; user.email = anotherValidEmail; user.password = anotherValidPassword; await expectNotToThrow(() =&gt; userSubscriber.handleInsert(user)); }); it(&quot;should replace user password with hash verifiable by ArgonPasswordHasher&quot;, async () =&gt; { user.password = anotherValidPassword; await userSubscriber.handleInsert(user); expect(user.password).not.toBe(anotherValidPassword); expect(await passwordHasher.verify(anotherValidPassword, user.password)).toBe(true); }); }); describe(&quot;handleUpdate&quot;, () =&gt; { const user = createInvalidUser(); const throwAnErrorDescription = &quot;should throw an error when user $field $description and $field is passed as updated field&quot;; it.each` description | value | field ${&quot;is empty&quot;} | ${emptyUsername} | ${&quot;username&quot;} ${&quot;is shorter than 2 characters&quot;} | ${tooShortUsername} | ${&quot;username&quot;} ${&quot;is longer than 255 characters&quot;} | ${tooLongUsername} | ${&quot;username&quot;} `(throwAnErrorDescription, async ({ value, field }) =&gt; { user.username = value; await expectToThrow(() =&gt; userSubscriber.handleUpdate(user, [field])); }); it.each` description | value | field ${&quot;is empty&quot;} | ${empytEmail} | ${&quot;email&quot;} ${&quot;is not an email&quot;} | ${notAnEmail} | ${&quot;email&quot;} ${&quot;is longer than 255 characters&quot;} | ${tooLongEmail} | ${&quot;email&quot;} `(throwAnErrorDescription, async ({ value, field }) =&gt; { user.email = value; await expectToThrow(() =&gt; userSubscriber.handleUpdate(user, [field])); }); it.each` description | value | field ${&quot;is empty&quot;} | ${emptyPassword} | ${&quot;password&quot;} ${&quot;is shorter than 8 characters&quot;} | ${tooShortPassword} | ${&quot;password&quot;} ${&quot;is longer than 32 characters&quot;} | ${tooLongPassword} | ${&quot;password&quot;} ${&quot;contains no lowercase characters&quot;} | ${passwordWithoutLowercase} | ${&quot;password&quot;} ${&quot;contains no uppercase characters&quot;} | ${passwordWithoutUppercase} | ${&quot;password&quot;} ${&quot;contains no number characters&quot;} | ${passwordWithoutNumber} | ${&quot;password&quot;} ${&quot;contains no special characters&quot;} | ${passwordWithoutSpecialCharacter} | ${&quot;password&quot;} `(throwAnErrorDescription, async ({ value, field }) =&gt; { user.password = value; await expectToThrow(() =&gt; userSubscriber.handleUpdate(user, [field])); }); it(&quot;should not throw an error when all user fields are valid and all fields are passed as updated fields&quot;, async () =&gt; { user.username = anotherValidUsername; user.email = anotherValidEmail; user.password = anotherValidPassword; await expectNotToThrow(() =&gt; userSubscriber.handleUpdate(user, Object.getOwnPropertyNames(user))); }); it(&quot;should replace user password with hash verifiable by ArgonPasswordHasher when password is valid and password is passed as updated field&quot;, async () =&gt; { user.password = anotherValidPassword; await userSubscriber.handleUpdate(user, [&quot;password&quot;]); expect(user.password).not.toBe(anotherValidPassword); expect(await passwordHasher.verify(anotherValidPassword, user.password)).toBe(true); }); }); }); </code></pre> <p>What do you folks think about my solution? One thing I worry about is that TypeORM doesn't use my handle functions directly and I don't test that.</p> <p><a href="https://github.com/ostojan/shopping-list-server/commit/c0f6e537ca6b5ce17264cd9d34d44d6b6e1b73cf" rel="nofollow noreferrer">Here is commit with my changes.</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T20:53:48.163", "Id": "260471", "Score": "0", "Tags": [ "javascript", "unit-testing", "typescript" ], "Title": "TypeORM EventSubscriber unit testing" }
260471
<p>The rationale behind this code is to implement a runtime-safe number conversions in situations when precision loss is possible, but is not expected. Example: passing a <code>size_t</code> value from a 64-bit code to a library (filesystem, database, etc.) which uses 32-bit type for size, assuming you will never pass more than 4Gb of data. Safety here means cast result would have an <em>exactly same</em> <strong>numeric</strong> (not binary) value (i.e. any rounding, value wrapping, sign re-interpretation, etc. would be treated as casting failure). At the same time, simple check-free implicit casting between compatible types for maximum performance is highly desired. This is especially useful for template classes, which usually assumed to have no special treatment to the types they operate on. Since it would be used in many places of my code, I'm wondering if I've overlooked something.</p> <p>Here's the code (<em>note that &quot;to&quot;-template argument goes before &quot;from&quot;-argument for automatic argument deduction in real-world usage</em>):</p> <pre><code>#include &lt;limits&gt; #include &lt;type_traits&gt; #include &lt;stdexcept&gt; #include &lt;typeinfo&gt; class SafeNumericCast { public: template &lt;typename TFrom&gt; class AutoCast { private: const TFrom _value; public: constexpr AutoCast(TFrom value) : _value(value) { } template &lt;typename TTo&gt; constexpr operator TTo() const { return cast&lt;TTo&gt;(_value); } }; protected: enum class NumberClass { UNSIGNED_INTEGER, SIGNED_INTEGER, IEEE754 }; protected: template &lt;typename T&gt; static constexpr NumberClass resolveNumberClass() { static_assert(std::numeric_limits&lt;T&gt;::radix == 2, &quot;Safe numeric casts can only be performed on binary number formats!&quot;); if constexpr (std::numeric_limits&lt;T&gt;::is_integer) { if constexpr (!std::is_same&lt;T, bool&gt;::value) { // NOTE Boolean is conceptually not a number (while it is technically backed by one) return std::numeric_limits&lt;T&gt;::is_signed ? NumberClass::SIGNED_INTEGER : NumberClass::UNSIGNED_INTEGER; } } else if constexpr (std::numeric_limits&lt;T&gt;::is_iec559) { return NumberClass::IEEE754; } throw std::logic_error(&quot;SafeNumericCast &gt; Unsupported numeric type!&quot;); } public: template &lt;typename TTo, typename TFrom&gt; static constexpr bool isSafelyCastable() { if constexpr (!std::is_same&lt;TTo, TFrom&gt;::value) { const NumberClass toNumberClass = resolveNumberClass&lt;TTo&gt;(); const NumberClass fromNumberClass = resolveNumberClass&lt;TFrom&gt;(); if constexpr (toNumberClass == NumberClass::UNSIGNED_INTEGER) { if constexpr (fromNumberClass == NumberClass::UNSIGNED_INTEGER) { return std::numeric_limits&lt;TTo&gt;::digits &gt;= std::numeric_limits&lt;TFrom&gt;::digits; } } else if constexpr (toNumberClass == NumberClass::SIGNED_INTEGER) { if constexpr ((fromNumberClass == NumberClass::UNSIGNED_INTEGER) || (fromNumberClass == NumberClass::SIGNED_INTEGER)) { return std::numeric_limits&lt;TTo&gt;::digits &gt;= std::numeric_limits&lt;TFrom&gt;::digits; } } else if constexpr (toNumberClass == NumberClass::IEEE754) { if constexpr ((fromNumberClass == NumberClass::UNSIGNED_INTEGER) || (fromNumberClass == NumberClass::SIGNED_INTEGER) || (fromNumberClass == NumberClass::IEEE754)) { return std::numeric_limits&lt;TTo&gt;::digits &gt;= std::numeric_limits&lt;TFrom&gt;::digits; } } return false; } return true; } template &lt;typename TTo, typename TFrom&gt; static constexpr TTo cast(TFrom value) { static_assert(isSafelyCastable&lt;TTo, TFrom&gt;()); return value; } template &lt;typename TFrom&gt; static constexpr AutoCast&lt;TFrom&gt; autocast(TFrom value) { return AutoCast&lt;TFrom&gt;(value); } }; class SafeRuntimeNumericCast : public SafeNumericCast { public: template &lt;typename TFrom&gt; class AutoCast { private: const TFrom _value; public: constexpr AutoCast(TFrom value) : _value(value) { } template &lt;typename TTo&gt; constexpr operator TTo() const { return cast&lt;TTo&gt;(_value); } }; private: template &lt;typename TTo, typename TFrom&gt; static constexpr bool isRuntimeCastable(TFrom value, TTo casted) { static_assert(!SafeNumericCast::isSafelyCastable&lt;TTo, TFrom&gt;()); const NumberClass toNumberClass = resolveNumberClass&lt;TTo&gt;(); const NumberClass fromNumberClass = resolveNumberClass&lt;TFrom&gt;(); if constexpr (toNumberClass == NumberClass::UNSIGNED_INTEGER) { if constexpr (fromNumberClass == NumberClass::UNSIGNED_INTEGER) { return value &lt;= std::numeric_limits&lt;TTo&gt;::max(); } else if constexpr (fromNumberClass == NumberClass::SIGNED_INTEGER) { if (value &gt;= 0) { return value &lt;= std::numeric_limits&lt;TTo&gt;::max(); } } else if constexpr (fromNumberClass == NumberClass::IEEE754) { return casted == value; } } else if constexpr (toNumberClass == NumberClass::SIGNED_INTEGER) { if constexpr (fromNumberClass == NumberClass::UNSIGNED_INTEGER) { return value &lt;= std::numeric_limits&lt;TTo&gt;::max(); } else if constexpr (fromNumberClass == NumberClass::SIGNED_INTEGER) { return ((value &gt;= std::numeric_limits&lt;TTo&gt;::min()) &amp;&amp;(value &lt;= std::numeric_limits&lt;TTo&gt;::max())); } else if constexpr (fromNumberClass == NumberClass::IEEE754) { return casted == value; } } else if constexpr (toNumberClass == NumberClass::IEEE754) { if constexpr (fromNumberClass == NumberClass::UNSIGNED_INTEGER) { return value &lt;= (1ULL &lt;&lt; std::numeric_limits&lt;TTo&gt;::digits); // NOTE Can't do &quot;casted == value&quot; check because of int-&gt; float promotion } else if constexpr (fromNumberClass == NumberClass::SIGNED_INTEGER) { return static_cast&lt;TFrom&gt;(casted) == value; // NOTE Presumable faster than doing abs(value) } else if constexpr (fromNumberClass == NumberClass::IEEE754) { return (casted == value) || (value != value); } } return false; } public: using SafeNumericCast::isSafelyCastable; template &lt;typename TTo, typename TFrom&gt; static constexpr bool isSafelyCastable(TFrom value) { if constexpr (!SafeNumericCast::isSafelyCastable&lt;TTo, TFrom&gt;()) { return isRuntimeCastable&lt;TTo&gt;(value, static_cast&lt;TTo&gt;(value)); } return true; } template &lt;typename TTo, typename TFrom&gt; static constexpr TTo cast(TFrom value) { if constexpr (!SafeNumericCast::isSafelyCastable&lt;TTo, TFrom&gt;()) { TTo casted = static_cast&lt;TTo&gt;(value); if (isRuntimeCastable&lt;TTo&gt;(value, casted)) { return casted; } throw std::bad_cast(); } return value; } template &lt;typename TFrom&gt; static constexpr AutoCast&lt;TFrom&gt; autocast(TFrom value) { return AutoCast&lt;TFrom&gt;(value); } }; </code></pre> <p>The usage is simple:</p> <pre><code>SafeNumericCast::cast&lt;uint64_t&gt;(42); // Statically check for possible precision loss SafeRuntimeNumericCast::cast&lt;float&gt;(1ULL); // Dynamically check for precision loss SafeNumericCast::isSafelyCastable&lt;uint64_t, uint32_t&gt;(); // Non-throwing static check SafeRuntimeNumericCast::isSafelyCastable&lt;float&gt;(1ULL); // Non-throwing dynamic check </code></pre> <p>Here are the assumptions the code is based on:</p> <ul> <li>The code is working only with built-in &quot;fundamental&quot; binary numeric types - this is intended for now.</li> <li>Any unsigned integer can be exactly represented by another signed or unsigned integer as long as it has enough digit capacity, otherwise a runtime value check against max value is required.</li> <li>Any signed integer can be exactly represented by another signed integer as long as it has enough digit capacity, otherwise a runtime value check against min and max values is required.</li> <li>Signed integer can't be generally represented by an unsigned integer, so a runtime value check is required. We can't simply compare by value due to sign re-interpretation during signed/unsigned promotion, so we have to separately check for negative sign and positive value against possible max value</li> <li>Integers can be represented by an IEEE 754 float as long as it has enough digit capacity, otherwise a runtime value check is required. We can't simply compare by value due to possible rounding during integer/float promotion, so we have to manually check against maximum representable integer.</li> <li>IEEE 754 floats can't be generally represented by an integer, so we have to check at runtime by simply comparing original and cast values. This should also cover NaN/Infinity/etc cases. The only problematic case is negative zero, and without constexpr <code>std::signbit()</code> we don't have much to do to help here, apart from turning the whole thing non-constexpr, which, IMO, is a way bigger no-no than letting negative zeroes slip through the cast.</li> <li>Any IEEE 754 float can be exactly represented by another IEEE 754 float as long as it has same or bigger size (that is, double simply has more capacity for both mantissa and exponent, thus any float is exactly representable by a double). Otherwise, a simple runtime value comparison is required. The only corner case is NaN and <code>std::isnan()</code> is, unfortunately is not constexpr, but we can work it around by checking <code>value != value</code>.</li> </ul> <p><strong>Update.</strong> Added &quot;auto-casting&quot; functionality to allow automatic deduction of return/target type and get rid of that ugly explicit template parameter specifications:</p> <pre><code>double dvalue = SafeNumericCast::autocast(0.0f); int ivalue = SafeRuntimeNumericCast::autocast(0.0f); </code></pre> <p>...or even:</p> <pre><code>auto value = SafeNumericCast::autocast(0.0f); // Hence the namesake double dvalue = value; int ivalue = value; </code></pre>
[]
[ { "body": "<p><strong>Use non-member functions where possible</strong>:</p>\n<p>The cast functions are all static, and there is no member data in <code>SafeNumericCast</code> and <code>SafeRuntimeNumericCast</code>, so these the classes don't need to exist.</p>\n<p>We could use namespaces, or plain non-member functions instead.</p>\n<hr />\n<p><strong>Unnecessary inheritance</strong>:</p>\n<p>Inheritance seems unnecessary and confusing here. <code>SafeRuntimeNumericCast</code> hides all of the names in <code>SafeNumericCast</code> anyway. There's a <code>using SafeNumericCast::isSafelyCastable;</code>, but we immediately define another <code>isSafelyCastable</code> function?</p>\n<p>We could put <code>NumberClass</code> and <code>resolveNumberClass()</code> into a <code>namespace Detail { ... }</code> so that we don't need to use inheritance.</p>\n<hr />\n<p><strong>SafeNumericCast</strong>:</p>\n<p><code>SafeNumericCast</code> is more or less equivalent to using C++ braced initialization, which already disallows narrowing casts:</p>\n<pre><code>auto i = 54;\nauto u = std::uint8_t{ i }; // error\nauto u = SafeNumericCast::cast&lt;std::uint8_t&gt;(i); // error\n</code></pre>\n<p>Technically the braced initialization only has to issue a warning in such cases, so I guess there's nothing wrong with making the intent explicit and forcing a definite error.</p>\n<p>However, checking whether we can cast an integer to floating point without losing any precision seems like rather different functionality, and maybe deserves a different name (e.g. <code>LosslessFloatCast</code> or something).</p>\n<hr />\n<p><strong>SafeRuntimeNumericCast</strong>:</p>\n<p>The name <code>SafeRuntimeNumericCast</code>, is a bit confusing, because we're doing the opposite of what <code>SafeNumericCast</code> did above. <code>SafeRuntimeNumericCast</code> allows us to do an &quot;unsafe&quot; cast, and then check that we got a meaningful result. So maybe <code>CheckedNumericCast</code> would be a better name?</p>\n<hr />\n<p><strong>Autocast</strong>:</p>\n<p><code>Autocast&lt;From&gt;</code> is really just a <code>From</code> that we pass around until we decide to actually cast it. If we want to save typing, then better names would probably help more than anything:</p>\n<pre><code>auto i = safeCast&lt;int&gt;(u);\nauto f = safeLosslessCast&lt;float&gt;(i);\nauto d = checkedCast&lt;double&gt;(x);\n</code></pre>\n<hr />\n<p><strong>Readability</strong>:</p>\n<p>Perhaps the nested if-statements would be more readable if they were flattened out:</p>\n<pre><code> if constexpr (a == NumberClass::UNSIGNED_INTEGER &amp;&amp; b == NumberClass::UNSIGNED_INTEGER) {\n return value &lt;= std::numeric_limits&lt;TTo&gt;::max();\n }\n else if constexpr (a == NumberClass::UNSIGNED_INTEGER &amp;&amp; b == NumberClass::SIGNED_INTEGER) {\n return value &lt;= std::numeric_limits&lt;TTo&gt;::max();\n }\n else if constexpr (a == NumberClass::UNSIGNED_INTEGER &amp;&amp; b == NumberClass::IEEE754) {\n return casted == value;\n }\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T12:06:12.777", "Id": "260554", "ParentId": "260472", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T21:47:47.103", "Id": "260472", "Score": "2", "Tags": [ "c++", "c++17", "integer", "floating-point", "casting" ], "Title": "Safe runtime numeric casts" }
260472
<p>My C++20 N-dimensional matrix project now supports basic linear algebra operations: <a href="https://github.com/frozenca/Ndim-Matrix" rel="nofollow noreferrer">https://github.com/frozenca/Ndim-Matrix</a></p> <p>Today I want to get some reviews on computing eigenvalues and eigenvectors. In particular, I don't like so much duplicate codes. I think other parts are okay.. (hope?)</p> <p>There are two functions: Computes eigenvalues only, and computes both eigenvalues and corresponding eigenvectors. These two functions share so much code, I want to know how to fix nicely..</p> <p>Full code: <a href="https://github.com/frozenca/Ndim-Matrix/blob/main/LinalgOps.h#L956" rel="nofollow noreferrer">https://github.com/frozenca/Ndim-Matrix/blob/main/LinalgOps.h#L956</a></p> <pre><code>constexpr float tolerance_soft = 1e-6; constexpr float tolerance_hard = 1e-10; constexpr std::size_t max_iter = 100; constexpr std::size_t local_iter = 15; template &lt;isScalar T&gt; decltype(auto) getSign (const T&amp; t) { if constexpr (isComplex&lt;T&gt;) { if (std::abs(t) &lt; tolerance_soft) { return static_cast&lt;T&gt;(1.0f); } return t / std::abs(t); } else { return std::signbit(t) ? -1.0f : +1.0f; } }; template &lt;typename Derived, isScalar T&gt; Vec&lt;T&gt; normalize(const MatrixBase&lt;Derived, T, 1&gt;&amp; vec) { Vec&lt;T&gt; u = vec; auto u_norm = norm(u); if (u_norm &lt; tolerance_hard) { return u; } else { u /= u_norm; return u; } } template &lt;typename Derived, isScalar T&gt; bool isSubdiagonalNeglegible(MatrixBase&lt;Derived, T, 2&gt;&amp; M, std::size_t idx) { if (std::abs(M[{idx + 1, idx}]) &lt; tolerance_soft * (std::abs(M[{idx, idx}]) + std::abs(M[{idx + 1, idx + 1}]))) { M[{idx + 1, idx}] = T{0}; return true; } return false; } template &lt;isScalar T&gt; T computeShift(const T&amp; a, const T&amp; b, const T&amp; c, const T&amp; d) { auto tr = a + d; auto det = a * d - b * c; auto disc = std::sqrt(tr * tr - 4.0f * det); auto root1 = (tr + disc) / 2.0f; auto root2 = (tr - disc) / 2.0f; if (std::abs(root1 - d) &lt; std::abs(root2 - d)) { return root1; } else { return root2; } } template &lt;isScalar T, isReal U = RealTypeT&lt;T&gt;&gt; std::tuple&lt;T, T, U&gt; givensRotation(const T&amp; a, const T&amp; b) { if (b == T{0}) { return {getSign(a), 0, std::abs(a)}; } else if (a == T{0}) { return {0, getSign(b), std::abs(b)}; } else if (std::abs(a) &gt; std::abs(b)) { auto t = b / a; auto u = getSign(a) * std::sqrt(1.0f + t * t); return {1.0f / u, t / u, std::abs(a * u)}; } else { auto t = a / b; auto u = getSign(b) * std::sqrt(1.0f + t * t); return {t / u, 1.0f / u, std::abs(b * u)}; } } // QR algorithm used in eigendecomposition. // not to be confused with QR decomposition template &lt;typename Derived, isScalar U, isScalar T = CmpTypeT&lt;U&gt;&gt; requires CmpTypeTo&lt;U, T&gt; std::vector&lt;T&gt; QRIteration(const MatrixBase&lt;Derived, U, 2&gt;&amp; mat) { std::size_t iter = 0; std::size_t total_iter = 0; std::size_t n = mat.dims(0); auto conjif = [&amp;](const auto&amp; v) { if constexpr (isComplex&lt;U&gt;) { return conj(v); } else { return v; } }; Mat&lt;T&gt; M = mat; std::size_t p = n - 1; while (true) { while (p &gt; 0) { if (!isSubdiagonalNeglegible(M, p - 1)) { break; } iter = 0; --p; } if (p == 0) { break; } if (++iter &gt; local_iter) { break; } if (++total_iter &gt; max_iter) { break; } std::size_t top = p - 1; while (top &gt; 0 &amp;&amp; !isSubdiagonalNeglegible(M, top - 1)) { --top; } auto shift = computeShift(M[{p - 1, p - 1}], M[{p - 1, p}], M[{p, p - 1}], M[{p, p}]); // initial Givens rotation auto x = M[{top, top}] - shift; auto y = M[{top + 1, top}]; auto [c, s, r] = givensRotation(x, y); Mat&lt;T&gt; R {{c, -s}, {s, c}}; Mat&lt;T&gt; RT{{c, s}, {-s, c}}; if (r &gt; tolerance_hard) { auto Sub1 = M.submatrix({top, top}, {top + 2, n}); Sub1 = dot(conjif(RT), Sub1); std::size_t bottom = std::min(top + 3, p + 1); auto Sub2 = M.submatrix({0, top}, {bottom, top + 2}); Sub2 = dot(Sub2, R); } for (std::size_t k = top + 1; k &lt; p; ++k) { x = M[{k, k - 1}]; y = M[{k + 1, k - 1}]; std::tie(c, s, r) = givensRotation(x, y); if (r &gt; tolerance_hard) { M[{k, k - 1}] = r; M[{k + 1, k - 1}] = T{0}; R[{0, 0}] = RT[{0, 0}] = R[{1, 1}] = RT[{1, 1}] = c; R[{0, 1}] = RT[{1, 0}] = -s; R[{1, 0}] = RT[{0, 1}] = s; auto Sub1 = M.submatrix({k, k}, {k + 2, n}); Sub1 = dot(conjif(RT), Sub1); std::size_t bottom = std::min(k + 3, p + 1); auto Sub2 = M.submatrix({0, k}, {bottom, k + 2}); Sub2 = dot(Sub2, R); } } } std::vector&lt;T&gt; res; for (std::size_t k = 0; k &lt; n; ++k) { res.push_back(M[{k, k}]); } return res; } template &lt;typename Derived, typename Derived2, isScalar T&gt; Mat&lt;T&gt; computeEigenvectors(const MatrixBase&lt;Derived, T, 2&gt;&amp; M, const MatrixBase&lt;Derived2, T, 2&gt;&amp; Q) { std::size_t n = M.dims(0); Mat&lt;T&gt; X = identity&lt;T&gt;(n); for (std::size_t k = n - 1; k &lt; n; --k) { for (std::size_t i = k - 1; i &lt; n; --i) { X[{i, k}] -= M[{i, k}]; if (k - i &gt; 1 &amp;&amp; k - i - 1 &lt; n) { auto row_vec = M.row(i).submatrix(i + 1, k); auto col_vec = X.col(k).submatrix(i + 1, k); X[{i, k}] -= dot(row_vec, col_vec); } auto z = M[{i, i}] - M[{k, k}]; if (z == T{0}) { z = static_cast&lt;T&gt;(tolerance_hard); } X[{i, k}] /= z; } } return dot(Q, X); } // QR algorithm used in eigendecomposition. // not to be confused with QR decomposition template &lt;typename Derived, typename Derived2, isScalar U, isScalar T = CmpTypeT&lt;U&gt;&gt; requires CmpTypeTo&lt;U, T&gt; std::vector&lt;std::pair&lt;T, Vec&lt;T&gt;&gt;&gt; QRIterationWithVec(const MatrixBase&lt;Derived, U, 2&gt;&amp; mat, const MatrixBase&lt;Derived2, U, 2&gt;&amp; V) { std::size_t iter = 0; std::size_t total_iter = 0; std::size_t n = mat.dims(0); auto conjif = [&amp;](const auto&amp; v) { if constexpr (isComplex&lt;U&gt;) { return conj(v); } else { return v; } }; Mat&lt;T&gt; M = mat; std::size_t p = n - 1; Mat&lt;T&gt; Q = V; while (true) { while (p &gt; 0) { if (!isSubdiagonalNeglegible(M, p - 1)) { break; } iter = 0; --p; } if (p == 0) { break; } if (++iter &gt; 20) { break; } if (++total_iter &gt; max_iter) { break; } std::size_t top = p - 1; while (top &gt; 0 &amp;&amp; !isSubdiagonalNeglegible(M, top - 1)) { --top; } auto shift = computeShift(M[{p - 1, p - 1}], M[{p - 1, p}], M[{p, p - 1}], M[{p, p}]); // initial Givens rotation auto x = M[{top, top}] - shift; auto y = M[{top + 1, top}]; auto [c, s, r] = givensRotation(x, y); Mat&lt;T&gt; R {{c, -s}, {s, c}}; Mat&lt;T&gt; RT{{c, s}, {-s, c}}; if (r &gt; tolerance_hard) { auto Sub1 = M.submatrix({top, top}, {top + 2, n}); Sub1 = dot(conjif(RT), Sub1); std::size_t bottom = std::min(top + 3, p + 1); auto Sub2 = M.submatrix({0, top}, {bottom, top + 2}); Sub2 = dot(Sub2, R); auto QSub2 = Q.submatrix({0, top}, {n, top + 2}); QSub2 = dot(QSub2, R); } for (std::size_t k = top + 1; k &lt; p; ++k) { x = M[{k, k - 1}]; y = M[{k + 1, k - 1}]; std::tie(c, s, r) = givensRotation(x, y); if (r &gt; tolerance_hard) { M[{k, k - 1}] = r; M[{k + 1, k - 1}] = T{0}; R[{0, 0}] = RT[{0, 0}] = R[{1, 1}] = RT[{1, 1}] = c; R[{0, 1}] = RT[{1, 0}] = -s; R[{1, 0}] = RT[{0, 1}] = s; auto Sub1 = M.submatrix({k, k}, {k + 2, n}); Sub1 = dot(conjif(RT), Sub1); std::size_t bottom = std::min(k + 3, p + 1); auto Sub2 = M.submatrix({0, k}, {bottom, k + 2}); Sub2 = dot(Sub2, R); auto QSub2 = Q.submatrix({0, k}, {n, k + 2}); QSub2 = dot(QSub2, R); } } } std::vector&lt;std::pair&lt;T, Vec&lt;T&gt;&gt;&gt; res; auto eV = computeEigenvectors(M, Q); for (std::size_t k = 0; k &lt; n; ++k) { res.emplace_back(M[{k, k}], normalize(eV.col(k))); } return res; } } // anonymous namespace template &lt;typename Derived, isScalar U, isScalar T = CmpTypeT&lt;U&gt;&gt; requires CmpTypeTo&lt;U, T&gt; std::vector&lt;T&gt; eigenval(const MatrixBase&lt;Derived, U, 2&gt;&amp; M) { std::size_t n = M.dims(0); std::size_t C = M.dims(1); if (n != C) { throw std::invalid_argument(&quot;Not a square Matrix, cannot compute eigenvalues&quot;); } if (n == 1) { // 1 x 1 return {M[{0, 0}]}; } else if (n == 2) { // 2 x 2 return eigenTwo(M); } else if (n == 3) { // 3 x 3 return eigenThree(M); } else { // for 4 x 4 we need advanced algorithm auto H = Hessenberg(M); return QRIteration(H); } } template &lt;typename Derived, isScalar U, isScalar T = CmpTypeT&lt;U&gt;&gt; requires CmpTypeTo&lt;U, T&gt; std::vector&lt;std::pair&lt;T, Vec&lt;T&gt;&gt;&gt; eigenvec(const MatrixBase&lt;Derived, U, 2&gt;&amp; M) { std::size_t n = M.dims(0); std::size_t C = M.dims(1); if (n != C) { throw std::invalid_argument(&quot;Not a square Matrix, cannot compute eigenvalues&quot;); } if (n == 1) { // 1 x 1 auto val = M[{0, 0}]; Vec&lt;T&gt; vec {T{1}}; return {{val, vec}}; } else if (n == 2) { // 2 x 2 return eigenVecTwo(M); } else if (n == 3) { // 3 x 3 return eigenVecThree(M); } else { // for 4 x 4 we need advanced algorithm auto [H, V] = HessenbergWithVec(M); return QRIterationWithVec(H, V); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T02:28:09.390", "Id": "514168", "Score": "0", "body": "Can you edit your question to include the headers necessary for this to compile?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T02:45:20.657", "Id": "514169", "Score": "0", "body": "@1201ProgramAlarm Very sorry, there are too many dependencies... to compile, you should ```git clone https://github.com/frozenca/Ndim-Matrix.git``` and add ```#include \"Matrix.h\"```. The ```test.cpp``` shows the usage of the code I posted." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T00:55:19.683", "Id": "260478", "Score": "1", "Tags": [ "c++", "matrix", "c++20" ], "Title": "C++20 Ndim matrix, computing eigenvalues and eigenvectors" }
260478
<h2>Description</h2> <p>This is a simple (and hopefully) RESTful API in Golang that uses Redis. I have next to no prior experience in Golang and absolutely no prior experience with Redis. The API is a simple counter service with the feature of disabling &quot;public&quot; updates (cannot create new counter, and cannot increment existing counter)</p> <p>The original idea was taken from <a href="https://countapi.xyz/" rel="nofollow noreferrer">CountAPI</a> [external website]</p> <h2>API reference</h2> <ul> <li><code>/api/{key}</code> (namespace defaults to <code>default</code>)</li> <li><code>/api/{namespace}/{key}</code></li> </ul> <p><code>{namespace}</code> and <code>{key}</code> match the regex <code>[a-zA-Z0-9_]+</code></p> <p>The following methods are supported on the endpoints:</p> <ul> <li><code>GET</code>: get view count</li> <li><code>POST</code>: increment view count</li> <li><code>PATCH</code>: update namespace settings</li> </ul> <h2>Example usage</h2> <p><code>test.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from copy import deepcopy from requests import get, patch, post def test_expected(method, url, expected, ignored_fields = [], headers = {}, data = {}): response = method(url, headers=headers, data=data).json() original_response = deepcopy(response) print(f'{method.__name__.upper()} {url}') print(f' {response}\n') for ignored_field in ignored_fields: try: response.pop(ignored_field) except KeyError: pass try: expected.pop(ignored_field) except KeyError: pass assert response == expected, f'got {response}, expected {expected}' return original_response if __name__ == '__main__': # Get view count test_expected(get, 'http://localhost:8080/api/default/key', {'success': True, 'data': 0}) test_expected(get, 'http://localhost:8080/api/namespace/key', {'success': True, 'data': 0}) test_expected(get, 'http://localhost:8080/api/default_namespace_key', {'success': True, 'data': 0}) # Create new key (&quot;default/key&quot;) in namespace that is public (is_public == true) test_expected(post, 'http://localhost:8080/api/default/key', {'success': True, 'data': 1, 'isNewNamespace': False}) # Create new key in non-existent namespace response = test_expected(post, 'http://localhost:8080/api/namespace/key', {'success': True, 'data': 1, 'isNewNamespace': True}, ignored_fields=['overrideKey']) key = response.get('overrideKey') # Check that namespace is not public by default test_expected(post, 'http://localhost:8080/api/namespace/key', {'success': False, 'error': 'No permission to update namespace/key'}) # Check that key in private namespace can be accessed with override key test_expected(post, 'http://localhost:8080/api/namespace/key', {'success': True, 'data': 2, 'isNewNamespace': False}, headers={'X-Override-Key': key}) test_expected(patch, 'http://localhost:8080/api/namespace/key', {'success': False, 'error': 'Incorrect override key'}) test_expected(patch, 'http://localhost:8080/api/namespace/key', {'success': False, 'error': 'Incorrect override key'}, headers={'X-Override-Key': 'foobar'}) test_expected(patch, 'http://localhost:8080/api/namespace/key', {'success': False, 'error': 'Field to update does not exist'}, headers={'X-Override-Key': key}) test_expected(patch, 'http://localhost:8080/api/namespace/key', {'success': True}, headers={'X-Override-Key': key}, data={'field': 'is_public', 'newValue': 'true', 'valueType': 'bool'}) # Check that everything still works as expected test_expected(get, 'http://localhost:8080/api/namespace/key', {'success': True, 'data': 2}) test_expected(post, 'http://localhost:8080/api/namespace/key', {'success': True, 'data': 3, 'isNewNamespace': False}) test_expected(patch, 'http://localhost:8080/api/namespace/key', {'success': True}, headers={'X-Override-Key': key}, data={'field': 'is_public', 'newValue': 'false', 'valueType': 'bool'}) test_expected(get, 'http://localhost:8080/api/namespace/key', {'success': True, 'data': 3}) test_expected(post, 'http://localhost:8080/api/namespace/key', {'success': False, 'error': 'No permission to update namespace/key'}) print('All tests passed') </code></pre> <p><code>test.py</code> output:</p> <pre><code>GET http://localhost:8080/api/default/key {'success': True, 'data': 0} GET http://localhost:8080/api/namespace/key {'success': True, 'data': 0} GET http://localhost:8080/api/default_namespace_key {'success': True, 'data': 0} POST http://localhost:8080/api/default/key {'success': True, 'data': 1, 'isNewNamespace': False} POST http://localhost:8080/api/namespace/key {'success': True, 'data': 1, 'isNewNamespace': True, 'overrideKey': '+2yubkGY1GwgfIJA'} POST http://localhost:8080/api/namespace/key {'success': False, 'error': 'No permission to update namespace/key'} POST http://localhost:8080/api/namespace/key {'success': True, 'data': 2, 'isNewNamespace': False} PATCH http://localhost:8080/api/namespace/key {'success': False, 'error': 'Incorrect override key'} PATCH http://localhost:8080/api/namespace/key {'success': False, 'error': 'Incorrect override key'} PATCH http://localhost:8080/api/namespace/key {'success': False, 'error': 'Field to update does not exist'} PATCH http://localhost:8080/api/namespace/key {'success': True} GET http://localhost:8080/api/namespace/key {'success': True, 'data': 2} POST http://localhost:8080/api/namespace/key {'success': True, 'data': 3, 'isNewNamespace': False} PATCH http://localhost:8080/api/namespace/key {'success': True} GET http://localhost:8080/api/namespace/key {'success': True, 'data': 3} POST http://localhost:8080/api/namespace/key {'success': False, 'error': 'No permission to update namespace/key'} All tests passed </code></pre> <h2>Code</h2> <p><em>WARNING</em>: Redis database running on <code>localhost:6379</code> will be modified</p> <p><code>main.go</code>:</p> <pre class="lang-golang prettyprint-override"><code>package main import ( &quot;encoding/json&quot; &quot;log&quot; &quot;math/rand&quot; &quot;net/http&quot; &quot;strconv&quot; &quot;strings&quot; &quot;time&quot; &quot;github.com/gomodule/redigo/redis&quot; &quot;github.com/gorilla/mux&quot; ) var ( c redis.Conn err error ) const defaultNamespace = &quot;default&quot; func apiMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Print(strings.Join([]string{r.RemoteAddr, r.Method, r.URL.Path}, &quot; &quot;)) w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;) next.ServeHTTP(w, r) }) } func mainErrorHandler(w http.ResponseWriter, r *http.Request) { const page = `&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;title&gt;Not Found&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Not Found&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt;` w.Write([]byte(page)) } func getNamespaceAndKey(m map[string]string) (string, string) { namespace := m[&quot;namespace&quot;] if namespace == &quot;&quot; { namespace = defaultNamespace } key := m[&quot;key&quot;] return namespace, key } func incrementViewCount(namespace string, key string) int { val, err := c.Do(&quot;INCR&quot;, namespace+&quot;:&quot;+key) if err != nil { log.Fatal(err) } n, err := redis.Int(val, err) if err != nil { log.Fatal(err) } return n } func getViewCount(namespace string, key string) int { val, err := c.Do(&quot;GET&quot;, namespace+&quot;:&quot;+key) if err != nil { log.Fatal(err) } if val == nil { return 0 } n, err := redis.Int(val, err) if err != nil { log.Fatal(err) } return n } func apiErrorHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;) type Response struct { Success bool `json:&quot;success&quot;` Error string `json:&quot;error&quot;` } res := Response{Success: false, Error: &quot;Invalid route&quot;} json.NewEncoder(w).Encode(res) } func apiGetNumViewsHandler(w http.ResponseWriter, r *http.Request) { type Response struct { Success bool `json:&quot;success&quot;` Data int `json:&quot;data&quot;` } vars := mux.Vars(r) namespace, key := getNamespaceAndKey(vars) n := getViewCount(namespace, key) res := Response{Success: true, Data: n} json.NewEncoder(w).Encode(res) } func namespaceExists(namespace string) bool { namespaceExists, err := redis.Bool(c.Do(&quot;EXISTS&quot;, namespace)) if err != nil { log.Fatal(err) } return namespaceExists } func allowedToUpdateKey(namespace string, key string, userOverrideKey string) bool { if !namespaceExists(namespace) { return true } overrideKey, err := redis.String(c.Do(&quot;HGET&quot;, namespace, &quot;override_key&quot;)) if err != nil { log.Fatal(err) } if userOverrideKey == overrideKey { return true } namespacePublic, err := redis.Bool(c.Do(&quot;HGET&quot;, namespace, &quot;is_public&quot;)) if err != nil { log.Fatal(err) } return namespacePublic } var letters = []rune(&quot;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+&quot;) // From https://stackoverflow.com/a/22892986 func randomOverrideKey(n int) string { b := make([]rune, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return string(b) } func createNamespace(namespace string) string { overrideKey := randomOverrideKey(16) _, err := redis.Int(c.Do(&quot;HSET&quot;, namespace, &quot;is_public&quot;, false, &quot;override_key&quot;, overrideKey)) if err != nil { log.Fatal(err) } return overrideKey } func apiPingHandler(w http.ResponseWriter, r *http.Request) { type Response struct { Success bool `json:&quot;success&quot;` Data int `json:&quot;data&quot;` NewNamespace bool `json:&quot;isNewNamespace&quot;` OverrideKey string `json:&quot;overrideKey,omitempty&quot;` } type ErrorResponse struct { Success bool `json:&quot;success&quot;` Error string `json:&quot;error&quot;` } vars := mux.Vars(r) namespace, key := getNamespaceAndKey(vars) userOverrideKey := r.Header.Get(&quot;X-Override-Key&quot;) if !allowedToUpdateKey(namespace, key, userOverrideKey) { res := ErrorResponse{Success: false, Error: &quot;No permission to update &quot; + namespace + &quot;/&quot; + key} json.NewEncoder(w).Encode(res) return } isNewNamespace := !namespaceExists(namespace) var overrideKey string if isNewNamespace { overrideKey = createNamespace(namespace) } else { overrideKey = &quot;&quot; } n := incrementViewCount(namespace, key) res := Response{Success: true, Data: n, NewNamespace: isNewNamespace, OverrideKey: overrideKey} json.NewEncoder(w).Encode(res) } func convertValueType(value string, valueType string) interface{} { var convertedValue interface{} // Other types at https://pkg.go.dev/github.com/gomodule/redigo/redis#pkg-index // Conversion at https://github.com/gomodule/redigo/blob/72af8129e040d6f962772a8c582e5e9f22085788/redis/reply.go switch valueType { case &quot;string&quot;: convertedValue, err = redis.String(value, err) if err != nil { log.Fatalf(`Could not convert &quot;%v&quot; to type &quot;%v&quot; (invalid value): %v`, value, valueType, err) } case &quot;bool&quot;: convertedValue, err = redis.Bool([]byte(value), err) if err != nil { log.Fatalf(`Could not convert &quot;%v&quot; to type &quot;%v&quot; (invalid value): %v`, value, valueType, err) } case &quot;int&quot;: convertedValue, err = redis.Int([]byte(value), err) if err != nil { log.Fatalf(`Could not convert &quot;%v&quot; to type &quot;%v&quot; (invalid value): %v`, value, valueType, err) } default: log.Fatalf(`Could not convert &quot;%v&quot; to type &quot;%v&quot; (unknown type)`, value, valueType) } return convertedValue } func apiUpdateHandler(w http.ResponseWriter, r *http.Request) { userOverrideKey := r.Header.Get(&quot;X-Override-Key&quot;) vars := mux.Vars(r) namespace, _ := getNamespaceAndKey(vars) overrideKey, err := redis.String(c.Do(&quot;HGET&quot;, namespace, &quot;override_key&quot;)) if err != nil { log.Fatal(err) } type Response struct { Success bool `json:&quot;success&quot;` } type ErrorResponse struct { Success bool `json:&quot;success&quot;` Error string `json:&quot;error&quot;` } if userOverrideKey != overrideKey { res := ErrorResponse{Success: false, Error: &quot;Incorrect override key&quot;} json.NewEncoder(w).Encode(res) return } field := r.FormValue(&quot;field&quot;) value := r.FormValue(&quot;newValue&quot;) valueType := r.FormValue(&quot;valueType&quot;) exists, err := redis.Int(c.Do(&quot;HEXISTS&quot;, namespace, field)) if err != nil { log.Fatal(err) } if exists == 0 { res := ErrorResponse{Success: false, Error: &quot;Field to update does not exist&quot;} json.NewEncoder(w).Encode(res) return } convertedValue := convertValueType(value, valueType) _, err = redis.Int(c.Do(&quot;HSET&quot;, namespace, field, convertedValue)) if err != nil { log.Fatal(err) } res := Response{Success: true} json.NewEncoder(w).Encode(res) } func init() { c, err = redis.Dial(&quot;tcp&quot;, &quot;:6379&quot;) if err != nil { log.Fatal(err) } log.Print(&quot;Connected to database&quot;) s := time.Now().UnixNano() rand.Seed(s) log.Print(&quot;Seeded with &quot; + strings.ToUpper(strconv.FormatInt(s, 16))) createNamespace(defaultNamespace) _, err = c.Do(&quot;HSET&quot;, defaultNamespace, &quot;is_public&quot;, convertValueType(&quot;true&quot;, &quot;bool&quot;)) if err != nil { log.Fatal(err) } } func main() { defer c.Close() r := mux.NewRouter() r.NotFoundHandler = http.HandlerFunc(mainErrorHandler) s := r.PathPrefix(&quot;/api/&quot;).Subrouter() s.Use(apiMiddleware) allowedCharsRegex := &quot;[a-zA-Z0-9_]+&quot; s.Path(&quot;/{key:&quot; + allowedCharsRegex + &quot;}&quot;).HandlerFunc(apiGetNumViewsHandler).Methods(&quot;GET&quot;) s.Path(&quot;/{namespace:&quot; + allowedCharsRegex + &quot;}/{key:&quot; + allowedCharsRegex + &quot;}&quot;).HandlerFunc(apiGetNumViewsHandler).Methods(&quot;GET&quot;) s.Path(&quot;/{key:&quot; + allowedCharsRegex + &quot;}&quot;).HandlerFunc(apiPingHandler).Methods(&quot;POST&quot;) s.Path(&quot;/{namespace:&quot; + allowedCharsRegex + &quot;}/{key:&quot; + allowedCharsRegex + &quot;}&quot;).HandlerFunc(apiPingHandler).Methods(&quot;POST&quot;) s.Path(&quot;/{key:&quot; + allowedCharsRegex + &quot;}&quot;).HandlerFunc(apiUpdateHandler).Methods(&quot;PATCH&quot;) s.Path(&quot;/{namespace:&quot; + allowedCharsRegex + &quot;}/{key:&quot; + allowedCharsRegex + &quot;}&quot;).HandlerFunc(apiUpdateHandler).Methods(&quot;PATCH&quot;) s.NotFoundHandler = http.HandlerFunc(apiErrorHandler) log.Print(&quot;Routes set up successfully&quot;) http.ListenAndServe(&quot;:8080&quot;, r) } </code></pre> <p><code>go.mod</code>:</p> <pre><code>module hit-counter go 1.16 require ( github.com/gomodule/redigo v1.8.4 github.com/gorilla/mux v1.8.0 ) </code></pre> <p><code>go.sum</code>:</p> <pre><code>github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gomodule/redigo v1.8.4 h1:Z5JUg94HMTR1XpwBaSH4vq3+PNSIykBLxMdglbw10gg= github.com/gomodule/redigo v1.8.4/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0= github.com/gomodule/redigo/redis v0.0.0-do-not-use h1:J7XIp6Kau0WoyT4JtXHT3Ei0gA1KkSc6bc87j9v9WIo= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T03:41:30.627", "Id": "260480", "Score": "4", "Tags": [ "beginner", "go", "http", "rest", "server" ], "Title": "Simple RESTful counting API in Golang" }
260480
<p>I have created the following function which filters a linked list in place (here it removes all instances of the element k), but it could easily be modified to take a function pointer as an argument and filter on something else.</p> <p>Any ideas on how to improve the code?</p> <pre><code>typedef struct list_integer { type value; struct list_integer *next; } list_integer; list_integer *removeKFromList(list_integer * l, int k) { if (!l) return l; while (l &amp;&amp; l-&gt;value == k) l = l-&gt;next; if (!l) return l; list_integer *p = l; list_integer *q = l-&gt;next; scan_in: if (q) { if (q-&gt;value != k) { list_integer *t = q; q = q-&gt;next; p = t; goto scan_in; } else { goto scan_out; } } scan_out: if (q) { if (q-&gt;value != k) { p-&gt;next = q; p = q; q = q-&gt;next; goto scan_in; } else { q = q-&gt;next; goto scan_out; } } else { p-&gt;next = q; } return l; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T06:31:35.807", "Id": "514174", "Score": "1", "body": "Is the indentation in your question the same as in your original code?" } ]
[ { "body": "<h1>Table of contents (in no particular order)</h1>\n<p>Indent your code properly!</p>\n<p>Don't use goto for something so routine. Unless you're writing a c compiler and intend to compete with gcc or clang or you're Andrei Alexandrescu... don't use goto at all!</p>\n<p>while loop/for loop can be used to accomplish what you need instead of goto.</p>\n<p>Fix memory leaks. If you're in place modifying a linked list, the nodes that are removed from the list have to have their memory free'd. (In general, this is the assumption going off solely your function prototype. It's possible that all the nodes are statically allocated and it's not this function's responsibility to free them but I'm assuming the more usual case.)</p>\n<p>Use comments to explain what you're doing. Although this isn't super complicated, since it's pretty low level, comments are a good idea.</p>\n<p>Checking for NULL, IMO it's better to do an explicit check with <code>== NULL</code> rather than <code>!l</code>. Although it is the same and is a popular choice among C programmers (I used to do it too, it made me feel smart)... it's hard to read and is not a good idea. Personally, I only use <code>!l</code> to check for bool's. Others may disagree.</p>\n<p>Better variable names. This can cut down on the amount of stuff that has to be explained in comments. Renamed p to previous and q to current. (If you really don't wanna type so much -- prev and cur)</p>\n<pre><code>typedef struct list_integer {\n type value;\n struct list_integer *next;\n} list_integer;\n\nlist_integer *removeKFromList(list_integer * l, int k)\n{\n\n if (l == NULL) return NULL; // empty list becomes empty list\n\n // remove the occurrences of k at the beginning\n while (l != NULL &amp;&amp; l-&gt;value == k) { \n list_integer* temp = l;\n l = l-&gt;next;\n free(temp); // deallocate memory\n }\n\n if (l == NULL) return NULL; // list of only k's becomes empty list\n\n // already checked in the while loop. l-&gt;value != k\n list_integer *previous = l;\n list_integer *current = l-&gt;next;\n\n while (current != NULL) {\n if (current-&gt;value != k) {\n previous = current;\n current = current-&gt;next;\n } else {\n while (l != NULL &amp;&amp; l-&gt;value == k) { // remove continuous occurrences of k\n list_integer* temp = current;\n current = current-&gt;next;\n free(temp); // deallocate memory\n }\n previous-&gt;next = current;\n if(current != NULL) {\n previous = current;\n current = current-&gt;next;\n } \n }\n }\n\n return l;\n}\n</code></pre>\n<p>The version above keep's the OP's optimisation of not modifying the next pointer (ie p-&gt;next) multiple times if there are multiple continuous k's.</p>\n<p>Version without this optimisation is a bit simpler</p>\n<pre><code>typedef struct list_integer {\n type value;\n struct list_integer *next;\n} list_integer;\n\nlist_integer *removeKFromList(list_integer * l, int k)\n{\n\n if (l == NULL) return NULL; // empty list becomes empty list\n\n // remove the occurrences of k at the beginning\n while (l != NULL &amp;&amp; l-&gt;value == k) { \n list_integer* temp = l;\n l = l-&gt;next;\n free(temp); // deallocate memory\n }\n\n if (l == NULL) return NULL; // list of only k's becomes empty list\n\n // already checked in the while loop. l-&gt;value != k\n list_integer *previous = l;\n list_integer *current = l-&gt;next;\n\n while (current != NULL) {\n if (current-&gt;value != k) {\n previous = current;\n current = current-&gt;next;\n } else {\n list_integer* temp = current;\n current = current-&gt;next;\n previous-&gt;next = current;\n free(temp); // deallocate memory\n }\n }\n\n return l;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T07:06:33.473", "Id": "514175", "Score": "0", "body": "Calling it table of contents was a joke... don't overthink it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T15:20:44.603", "Id": "514194", "Score": "0", "body": "Being more verbose or more similar to other more verbose languages is not something to strive for. Anyway, the problem is the name `l` or was it `1` or ???" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T15:31:28.827", "Id": "514195", "Score": "0", "body": "As an aside, you like OP prefer the rare over the common case. The latter being that there are more nodes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:01:42.137", "Id": "514202", "Score": "0", "body": "I mean... for each node, the overhead is two condition checks for a zero in a memory location that's probably hot in cache (if not already in a register)... vs a memory read+write" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:08:00.100", "Id": "514204", "Score": "0", "body": "Yes, `l` should be in a register. But the options are letting the common case run, which only writes if needed, vs. testing for the end, and then sometimes letting the common case run. That extra-check is not needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:09:13.430", "Id": "514205", "Score": "0", "body": "too many asides.... removed the bonus, it was wrong... not worth fixing, beyond scope of question" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T07:05:53.710", "Id": "260484", "ParentId": "260481", "Score": "1" } }, { "body": "<p>Congratulations on hitting on the idea that modifying pointers, even by setting them to their current value, has a cost. That cost is not necessarily insignificant either, as cache-unsharing and marking a page as dirty has immediate and follow-on costs.</p>\n<p>Also kudos for adding a typedef-name, and making it match the tag-name.</p>\n<p>Still there are multiple issues with your code:</p>\n<ol>\n<li><p><strong>Proper indentation is crucial for maintainability</strong>. Take care of it while programming to support your own understanding, and fix any warts before subjecting anyone else to it. If that's too tedious for you, it's easily automated.</p>\n</li>\n<li><p><strong><code>goto</code> is rarely the solution</strong>. It might be preferable over pushing the control-flow into flags, but there is nearly always a better structured way to go.</p>\n</li>\n<li><p>You test for an empty list twice for a quick exit. That's a optimizing the rare case to the detriment of the common case. Also, it's more code.</p>\n</li>\n<li><p>I'm hard pressed to think of a worse name than <code>l</code>. It's easily confused with other symbols. Also, its scope is too big for most single-letter names.</p>\n</li>\n<li><p>You just drop unneeded nodes. If that is actually the right thing to do, it deserves a comment to assert that was intended: <code>/* dropping node here */</code>.<br />\nFar more likely, you just forgot to <code>free()</code> it.</p>\n</li>\n<li><p>Personally, I prefer putting the links at the beginning of the node. If double-linked, they even get their own struct.</p>\n</li>\n</ol>\n<pre><code>typedef struct list_integer {\n struct list_integer *next;\n int value;\n} list_integer;\n\nlist_integer *removeKFromList(list_integer *head, int k) {\n list_integer* r;\n list_integer** insert = &amp;r;\n do {\n while (head &amp;&amp; head-&gt;value == k) {\n list_integer* p = head;\n head = head-&gt;next;\n free(p);\n }\n *insert = head;\n while (*insert &amp;&amp; (*insert)-&gt;value != k)\n insert = &amp;(*insert)-&gt;next;\n head = *insert;\n } while (head);\n return r;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T16:08:32.500", "Id": "260498", "ParentId": "260481", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T04:16:35.943", "Id": "260481", "Score": "1", "Tags": [ "c", "linked-list" ], "Title": "Filter a Linked List in Place in C" }
260481
<p>I recently decided to learn how to multithread Java programs, so I made a small program to compare the performance of serial and multithreaded programs that perform the same task.</p> <p>I created a serial program that calculates the number of primes from 1 to 10 million, and timed it 50 times using a test program. Here's the code for the serial program:</p> <pre><code>import java.util.Locale; import java.text.NumberFormat; /** * A serial program that calculates the number of primes less than a * certain number (which is hard coded). Used as a basis for * benchmarking the multi-threaded programs that do the same thing. * * @author Tirthankar Mazumder * @version 1.2 * @date 2nd May, 2021 */ public class PrimalityTestSerial { public static final long max = 10_000_000; public static void main(String[] args) { final long startTime = System.currentTimeMillis(); long num_primes = primeCalculator(); final long endTime = System.currentTimeMillis(); NumberFormat nf = NumberFormat.getInstance(Locale.US); System.out.println(&quot;Number of primes less than &quot; + nf.format(max) + &quot;: &quot; + num_primes); System.out.println(&quot;Took &quot; + (endTime - startTime) + &quot; ms.&quot;); System.out.println(); } private static boolean isPrime(long l) { long upper_bound = (long) Math.floor(Math.sqrt(l)); for (long i = 2; i &lt;= upper_bound; i++) { if (l % i == 0) return false; } return true; } public static long primeCalculator() { long num_primes = 0; for (long i = 2; i &lt;= max; i++) { if (isPrime(i)) num_primes++; } return num_primes; } } </code></pre> <p>Here's the code for the worker class used in the multithreaded version:</p> <pre><code>/** * A worker class for calculating the number of primes from start to end, * which are private member variables. Instances of this class are used * in the multithreaded version of PrimalityTestSerial. * * @author Tirthankar Mazumder * @version 1.2 * @date 3rd May, 2021 */ public class PrimalityTestWorker1 implements Runnable { //Member variables public static long totalPrimeCount = 0; private final long start; private final long end; public PrimalityTestWorker1(long start, long end) { this.start = start; this.end = end; } private synchronized void increment(long num) { totalPrimeCount += num; } private static boolean isPrime(long l) { long upper_bound = (long) Math.floor(Math.sqrt(l)); for (long i = 2; i &lt;= upper_bound; i++) { if (l % i == 0) return false; } return true; } private void numPrimes() { long primeCount = 0; for (long i = start; i &lt;= end; i++) { if (isPrime(i)) primeCount++; } increment(primeCount); } public void run() { numPrimes(); Thread.yield(); } } </code></pre> <p>Here's the main program which uses instances of PrimalityTest1Worker as threads:</p> <pre><code>import java.util.Locale; import java.text.NumberFormat; /** * The master program for the multithreaded primality test that creates * objects of the PrimalityTestWorker1 to make threads, and then collates * the results and prints them to stdout. * * @author Tirthankar Mazumder * @version 1.0=2 * @date 3rd May, 2021 */ public class PrimalityTestParallel1Runner { public static final int cores = Runtime.getRuntime().availableProcessors(); //We will spawn as many threads as there are cores on the system, and not //more than that because we are not I/O bound here. public static final long max = PrimalityTestSerial.max; //For consistency. public static void main(String[] args) { long startTime = System.currentTimeMillis(); primeCalculator(); long endTime = System.currentTimeMillis(); NumberFormat nf = NumberFormat.getInstance(Locale.US); System.out.println(&quot;Number of primes less than &quot; + nf.format(max) + &quot;: &quot; + PrimalityTestWorker1.totalPrimeCount); System.out.println(&quot;Took &quot; + (endTime - startTime) + &quot; ms.&quot;); System.out.println(); } public static void primeCalculator() { Thread arrThreads[] = new Thread[cores]; long chunk = max / cores; long threadStart = 2; long threadEnd = threadStart + chunk; for (int i = 0; i &lt; cores; i++) { Thread t = new Thread(new PrimalityTestWorker1(threadStart, threadEnd)); t.start(); arrThreads[i] = t; threadStart = threadEnd + 1; threadEnd = (threadEnd + chunk &gt; max) ? max : threadEnd + chunk; } for (int i = 0; i &lt; cores; i++) { try { arrThreads[i].join(); } catch (InterruptedException e) { System.out.println(&quot;Was interrupted.&quot;); return; } } } } </code></pre> <p>Finally, here's the code for the testing program, which runs each program 50 times and then calculates the average runtimes:</p> <pre><code>import java.util.Arrays; /** * A wrapper class that handles benchmarking the performances of * PrimalityTestSerial and PrimalityTestParallel1Runner and then * prints information about the results to stdout. * * @author Tirthankar Mazumder * @version 1.0 * @date 8th May, 2021 */ public class PrimalityTestSuite { public static final int n = 50; //Number of test runs to perform public static void main(String[] args) { long totalSerialTime = 0; long totalParallelTime = 0; long serialTimes[] = new long[n]; double avgSerialTime = 0; double avgParallelTime = 0; System.out.println(&quot;Starting Serial runs...&quot;); long startTime = System.currentTimeMillis(); for (int i = 0; i &lt; n; i++) { PrimalityTestSerial.primeCalculator(); serialTimes[i] = System.currentTimeMillis(); } for (int i = 0; i &lt; n; i++) { serialTimes[i] -= startTime; for (int j = 0; j &lt; i; j++) { serialTimes[i] -= serialTimes[j]; //to get rid of the time taken by the previous runs } avgSerialTime += serialTimes[i]; } avgSerialTime /= n; long parallelTimes[] = new long[n]; System.out.println(&quot;Starting parallel runs...&quot;); startTime = System.currentTimeMillis(); for (int i = 0; i &lt; n; i++) { PrimalityTestParallel1Runner.primeCalculator(); parallelTimes[i] = System.currentTimeMillis(); } for (int i = 0; i &lt; n; i++) { parallelTimes[i] -= startTime; for (int j = 0; j &lt; i; j++) { parallelTimes[i] -= parallelTimes[j]; //to get rid of the time taken by the previous runs } avgParallelTime += parallelTimes[i]; } avgParallelTime /= n; Arrays.sort(serialTimes); Arrays.sort(parallelTimes); double bestThreeSerialAvg = (serialTimes[0] + serialTimes[1] + serialTimes[2]) / 3; double bestThreeParallelAvg = (parallelTimes[0] + parallelTimes[1] + parallelTimes[2]) / 3; System.out.println(); System.out.println(&quot;Results:&quot;); System.out.println(&quot;Average of &quot; + n + &quot; Serial Runs: &quot; + avgSerialTime + &quot; ms.&quot;); System.out.println(&quot;Average of &quot; + n + &quot; Parallel Runs: &quot; + avgParallelTime + &quot; ms.&quot;); System.out.println(); System.out.println(&quot;Average speed-up: &quot; + avgSerialTime / avgParallelTime + &quot;x&quot;); System.out.println(); System.out.println(&quot;Average of best 3 Serial Runs: &quot; + bestThreeSerialAvg + &quot; ms.&quot;); System.out.println(&quot;Average of best 3 Parallel Runs: &quot; + bestThreeParallelAvg + &quot; ms.&quot;); System.out.println(); System.out.println(&quot;Average speed-up (w.r.t. best run times): &quot; + bestThreeSerialAvg / bestThreeParallelAvg + &quot;x&quot;); System.out.println(); } } </code></pre> <p>Here are the results from the test program:</p> <pre><code>Starting Serial runs... Starting parallel runs... Results: Average of 50 Serial Runs: 4378.92 ms. Average of 50 Parallel Runs: 1529.2 ms. Average speed-up: 2.8635364896678x Average of best 3 Serial Runs: 4328.0 ms. Average of best 3 Parallel Runs: 1297.0 ms. Average speed-up (w.r.t. best run times): 3.3369313801079414x </code></pre> <p>From here, it is obvious that the average speed-up is simply around 3x. However, this is surprising because I expect the multi-threaded program to run 7 to 8 times faster (because the serial program uses just 1 core, whereas the multi-threaded program should use all 8 cores on my system.)</p> <p>So my question is, <strong>why is the multi-threaded program not as fast as I expect it to be?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T06:10:01.540", "Id": "514229", "Score": "6", "body": "Every time I see a prime-counting function program I feel obligated to tell you there are much faster algorithms that run in sub-linear time using https://en.wikipedia.org/wiki/Meissel%E2%80%93Lehmer_algorithm My pure python implementation runs in 0.01 sec." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T09:15:21.110", "Id": "514241", "Score": "2", "body": "@qwr Thanks, I didn't know about this algorithm. But even if I did, I wouldn't have used it here, because my objective was to make the threads do some nontrivial work so that I can measure my performance gains. But for tasks where prime-counting is necessary and performance is required, I will most definitely use that algorithm from now on :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T19:23:22.200", "Id": "514284", "Score": "0", "body": "@qwr: That's still way too much work. I use `1e7 / math.log(1e7)` as an approximation and get a result in 7ns. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T19:47:17.927", "Id": "514290", "Score": "0", "body": "Yes, the PNT provides a very good approximation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T05:14:21.063", "Id": "514306", "Score": "3", "body": "The dynamic programming algorithm for finding primes, known as the Sieve of Eratosthenes, is a very good exercise in principles of HPC if you want to up-level your skills. Parallel tasks must synchronize access to a common array of bits. You'll need a queue of tasks (each task is to strike every Nth number), then dispatch them to threads, decide when it's cheaper to lump tasks (every 2nd runs a long time, every 1E6th is fast). And how to optimize it: find first 1E4 primes then schedule tasks only for prime N<1E4 up to 1E6, rinse&repeat. Try 1E11, it needs only a 5G array, as primes>2 are odd." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:36:19.213", "Id": "514330", "Score": "0", "body": "@kkm: Oh right, interesting. To avoid copying the bit-array for each thread and ANDing or ORing after independent work (or using atomic RMWs or an optimistic approach that [reads back a chunk after a memory barrier to detect stepped-on writes](https://stackoverflow.com/questions/45556086/how-to-set-bits-of-a-bit-vector-efficiently-in-parallel/45994685#45994685)), most likely you'd want to divide up regions of the array between threads, so each thread gets the same list of numbers to mark off, but does it in disjoint parts of the array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:41:48.753", "Id": "514331", "Score": "0", "body": "(And further, [cache-block](https://en.wikipedia.org/wiki/Loop_nest_optimization) within each thread, to mark out multiple strides in each ~128k (half L2 cache sized) chunk while it's still hot in cache, before moving on. Especially for the early primes (less than 64*8 = 512 bits in one cache line) where every cache line in the region will be touched for each marking-off. This takes advantage of each core's L2 cache in parallel.)" } ]
[ { "body": "<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>threadEnd = (threadEnd + chunk &gt; max) ? max : threadEnd + chunk;\n</code></pre>\n</blockquote>\n<p>Your <code>primeCalculator</code>'s <em>equally sized</em> chunks run in <em>unequal time</em>. The calls to <code>primeCalculator</code> for, say, 1-20 are going to be significantly faster than the calls to <code>primeCalculator</code> for, say, 10000-10020. When 1-20 is done 10000-10020 will still be running, hence performance isn't cut to an 1/8.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T07:49:25.993", "Id": "260486", "ParentId": "260485", "Score": "14" } }, { "body": "<p>Following on from <a href=\"/a/260486\">Peilonrayz' answer</a>, to counteract that problem as much as possible, you can do multiple &quot;chunks&quot; per thread, making each such chunk smaller, and spreading them out across the values.</p>\n<p>In the extreme, the chunks are of size 1. If you know how many threads there will be (we see you have <code>cores</code> threads), then this is fairly simple to implement: tell each thread <code>t</code> the total number of threads <code>n</code> and an initial value <code>x</code> to check for primality, then add <code>n</code> after each check. That is, instead of providing a <code>threadStart</code> and <code>threadEnd</code> value, provide a <code>threadStart</code> value between <code>1</code> and <code>n</code>, and a <code>threadIncrement</code> value (that is just <code>n</code>; alternatively, you could make that <code>n</code> a global variable that all threads can see so that you don't need to pass it into the worker constructor). In each thread, you then do something like this:</p>\n<pre><code>x = threadStart;\n\nwhile (x &lt; max) {\n if (isPrime(x)) {\n // ...\n }\n x += n;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T19:17:44.367", "Id": "514282", "Score": "0", "body": "Note that every even number is composite (except 2), and will leave the division loop right away, on the first divisor. Dividing up the *odd* numbers between threads is a very good idea, though, with `x += nthreads`, but if you do this naively then half your threads will exit much sooner than the others. (Which is maybe ok on a CPU with 2 logical cores per physical core, otherwise you're wasting half your available cores.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T19:43:22.447", "Id": "514287", "Score": "0", "body": "@PeterCordes Of course there are more efficient ways to do this, even much more efficient that what you have stated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T19:55:29.953", "Id": "514291", "Score": "0", "body": "My point wasn't primarily about making it more *efficient* (that's a side benefit), but making the work done in each thread actually about *equal*. So you can use static scheduling with 8 equal chunks, and not have some threads still working long after others exit, assuming they all had a CPU core to run on the whole time. But that problem would happen if some threads are only checking even numbers, and some are only checking odd. (e.g. starting at 2 vs. starting at 3, and incrementing by 8. Every even number has `n % i == 0` for i=2 so they exit on the first iteration.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:01:35.750", "Id": "514292", "Score": "1", "body": "@PeterCordes, ah, yes, this is actually a good point. If the number of threads *n* is not prime, then those threads whose index is a factor of *n* will finish very quickly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:13:25.163", "Id": "514293", "Score": "0", "body": "Oh yes, I was assuming an even number of threads, so you could add `nthreads` and always get odd numbers. Or even if you had a setup with 6 cores for example (e.g. Coffee Lake without hyperthreading), a thread that started with n=3 would get all multiples of 3. So yeah, there's a possible problem for any non-power-of-2 number of threads, I think. (It's not nthreads being non-prime that's the issue, e.g. nt=7 would make the thread starting with n=7 a problem)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:15:18.797", "Id": "514294", "Score": "0", "body": "And BTW, using `n` for number of threads seems like an unclear choice. My expectation would be that `n` would be used for the problem size, i.e. 10 million. If you want a one-letter var name for number of threads, `t` might be a good choice." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T16:58:48.313", "Id": "260501", "ParentId": "260485", "Score": "8" } }, { "body": "<p>Many modern CPUs can run at a higher clock speed when only one core is active, vs. when all cores are active. This ratio between one-core vs. all-core max turbo / boost-clock depends entirely on the CPU model. (It can be higher in laptops, where thermal constraints are a bigger deal, for the similar reasons to <a href=\"https://stackoverflow.com/questions/36363613/why-cant-my-ultraportable-laptop-cpu-maintain-peak-performance-in-hpc\">max turbo vs. sustained frequency being a higher ratio in laptops</a>.)</p>\n<hr />\n<p>Also:</p>\n<p>If your CPU has <a href=\"https://en.wikipedia.org/wiki/Simultaneous_multithreading\" rel=\"nofollow noreferrer\">SMT (e.g. Intel Hyper Threading)</a>, one thread per physical core is probably mostly maxing out the integer-division throughput. (Composite numbers with small prime factors will mean you break out of the loop relatively often, letting SMT do its job by letting the other thread get more done while this thread is recovering from a branch misprediction.)</p>\n<p>But still, with SMT, best-case speedup may only scale with number of physical cores, not the number you detect with <code>availableProcessors</code>. E.g. 4x on a 4c8t (4 core 8 thread) CPU like i7-6700k which the OS will detect as having 8 logical cores, but has 4 physical.</p>\n<p>(Division is a very slow operation, and not fully pipelined even in modern high-end x86 CPUs. I.e. it can't start a new division every clock cycle, the way it can for multiply, let alone do multiple per clock cycle like with add/sub. For example, Intel Skylake has throughput of one <code>idiv r32</code> per 6 cycles (<a href=\"https://uops.info/\" rel=\"nofollow noreferrer\">https://uops.info/</a> / <a href=\"https://agner.org/optimize/\" rel=\"nofollow noreferrer\">https://agner.org/optimize/</a>). It's microcoded as 10 uops, but in 6 cycles the 4-wide front-end can issue 24 uops, so there's plenty of room for loop overhead of a test/jcc and inc / cmp/jcc in that simple loop that's just running idiv repeatedly to do signed integer division.)</p>\n<p>This may be why your unequal work distribution <a href=\"https://codereview.stackexchange.com/a/260486/50567\">identified by @Peilonrayz</a> doesn't hurt as much as it could: once the &quot;easy&quot; thread finishes, whichever thread has a physical core all to itself can make faster progress.</p>\n<p><strong>This dependency on thread-scheduling may also be why your best-3 average (3.33x) is significantly better than your mean of 2.86x speedup.</strong> The best case only happens when the last (most work-intensive) thread shares a core with the first thread (finishes first). I'm guessing you <em>do</em> have a CPU with SMT. (But I'm not at all confident in this prediction.)</p>\n<p>BTW, uneven chunk costs are what OpenMP <code>schedule(dynamic)</code> is for, when using C with OpenMP to auto-parallelize a loop. (<a href=\"https://stackoverflow.com/questions/10850155/whats-the-difference-between-static-and-dynamic-schedule-in-openmp\">https://stackoverflow.com/questions/10850155/whats-the-difference-between-static-and-dynamic-schedule-in-openmp</a>). Break the problem up into more smaller chunks, and have a worker thread start a new one every time you finish one.</p>\n<p>@Jivan Pal's suggestion to interleave the numbers you check across threads is an alternative way to make the work uniform, as long as you skip even numbers! Every even number above 2 is composite. (OTOH, if you insist on brute-force checking every one, then ideally the OS would schedule threads checking even numbers to the same cores as the real work so they don't compete as much. Or at least those 4 threads would exit much sooner than the rest, leaving 4 odd-number checking threads.)</p>\n<hr />\n<p>BTW, this is fine as an experiment / benchmark for multi-threading, but if you actually wanted to count primes fast, you'd certainly want to improve the algorithm each thread is running. There's a trivial factor of 2 here, by only checking the odd numbers as divisors: <code>for(int i=3 ; i &lt; rootn ; i+=2)</code>. And by only considering odd numbers as candidate primes in the outer loop. On the plus side, you do only go up to sqrt(n) which means you're doing vastly less work than even more naive <code>i &lt; n</code> brute-force loops.</p>\n<p>Or the much better option, use a <a href=\"/questions/tagged/sieve-of-eratosthenes\" class=\"post-tag\" title=\"show questions tagged &#39;sieve-of-eratosthenes&#39;\" rel=\"tag\">sieve-of-eratosthenes</a>, and yes CodeReview.SE has a whole tag for it. (But that's harder to parallelize.) Of course it doesn't matter how inefficient your algorithm is when you're just comparing relative speedups.</p>\n<p>In general, throwing more threads / cores at a problem is sometimes easy to do (for embarrassingly parallel problems like brute-force checking), but making each thread more efficient is also very valuable. (And costs less total CPU cycles / energy.) For this problem specifically, sieving on one core should be faster than brute-forcing on all cores, even with a big Xeon or maybe even a cluster.</p>\n<p>Or <a href=\"https://codereview.stackexchange.com/questions/260485/finding-number-of-primes-less-than-10-million-using-a-multithreaded-program/260537#comment514229_260485\">as @qwr comments</a>, even more specific math for primes (<a href=\"https://en.wikipedia.org/wiki/Meissel%E2%80%93Lehmer_algorithm\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Meissel%E2%80%93Lehmer_algorithm</a>) allows <em>counting</em> them without <em>finding</em> them. Prime numbers are kind of a special case, compared to other real-world problems, given how much clever math has been done on them - the algorithmic optimizations are even huger than what's often possible.</p>\n<hr />\n<p>For primes, the amount of work scales with <span class=\"math-container\">\\$O(\\sqrt{n})\\$</span>, the number of trial divisions. OTOH primes are less frequent the larger the numbers are: most numbers have some smaller factors, so you aren't frequently going all the way to <span class=\"math-container\">\\$\\sqrt{n}\\$</span> iterations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T19:44:54.490", "Id": "514289", "Score": "2", "body": "you should try https://codegolf.stackexchange.com/questions/74269/calculate-the-number-of-primes-up-to-n/74372?r=SearchResults#74372 but for even bigger inputs. the best published algorithms are almost O(n^2/3) time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T06:31:55.550", "Id": "514389", "Score": "1", "body": "@PeterCordes Thank you for this extremely informative answer, I learned a lot from this. And I'm amazed that you managed to actually infer that I have a SMT processor from just looking at the mean and best 3 speed-ups! I _do_ have an Intel SMT processor. I'm on a laptop which has an Intel i5-1135G7. It has 4 physical cores and 8 logical cores. Moreover, as you mentioned, the OS does indeed recognize it as having 8 cores. (I've checked by printing the result of `Runtime.getRuntime().availableProcessors()` to stdout, and by running `cat /proc/cpuinfo` on the terminal in Ubuntu.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T17:03:48.990", "Id": "514416", "Score": "1", "body": "@wermos: Part of my guesswork was that 4c8t CPUs are very common, but 8c8t CPUs aren't, and I knew you had 8 threads. (Even rarer than I thought; maybe just [Intel Coffee Lake-refresh i7 desktop](//en.wikipedia.org/wiki/Coffee_Lake#Desktop_processors) - I think all AMDs ship with SMT enabled. Or I guess ancient dual-socket Core2Quad Xeon systems.) But even without that, the fact that the best was significantly better than the average hinted that there was some inter-thread competition, and SMT is the only plausible mechanism if your system was mostly idle for benchmarking. Not mem or cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T17:08:12.583", "Id": "514417", "Score": "1", "body": "So the choice between 4c8t or 8c8t was fairly solid once I consider the rarity of 8c8t; most people don't disable HT / SMT in the BIOS. But if I'd had to consider geometries like 5c8t (e.g. a VM exposing 8 cores across 5 physical cores), I wouldn't have been able to estimate the right number of physical cores, just that it was less than #threads." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T17:12:27.420", "Id": "514418", "Score": "1", "body": "@wermos: Fun fact: Your Ice Lake / Tiger Lake introduced a new [improved integer divide unit](https://stackoverflow.com/questions/58422171/do-fp-and-integer-division-compete-for-the-same-throughput-resources-on-x86-cpus) that no longer competes with FP division, but it's still 6c throughput. Fewer uops for the front-end (just 4, no longer indirecting to the microcode sequencer). https://uops.info/table.html?search=div%20r32&cb_lat=on&cb_tp=on&cb_uops=on&cb_ports=on&cb_SKL=on&cb_TGL=on&cb_measurements=on&cb_doc=on&cb_base=on. So naive brute-force trial division still sucks just as much :/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T18:29:19.367", "Id": "260537", "ParentId": "260485", "Score": "3" } } ]
{ "AcceptedAnswerId": "260486", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T07:41:22.023", "Id": "260485", "Score": "9", "Tags": [ "java", "multithreading" ], "Title": "Finding number of primes less than 10 million using a multithreaded program" }
260485
<p>I have this function called error, which estimates value based on previous value and rewards in trials. The difference between the estimated value and true value is then calculated, giving the error. I need to run this code 1000 times with different lists of trials, but currently it runs too slowly. How would I optimize this code?</p> <p>Additional information: alpha is a parameter. Reward and true_value are lists. Value always starts at 0.5, but I remove this starting number before calculating error</p> <pre><code>def loopfunction(alpha, reward, true_value): difference = [] value = [0.5] for index, lr in enumerate(reward): value.append(lever_update(alpha, value[-1], reward[index])) value.pop(0) zip_object = zip(value, true_value) for value_i, true_value_i in zip_object: difference.append(value_i-true_value) absdiff = [abs(number) for number in difference] return absdiff </code></pre> <p>The lever_update function, which calculates value is here:</p> <pre><code>def lever_update(alpha, value, reward): value += alpha * (reward - value) return(value) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T10:26:19.727", "Id": "514184", "Score": "1", "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 [ask] for examples, and revise the title accordingly." } ]
[ { "body": "<ol>\n<li><p>Using list comprehensions instead of numerous <code>.append</code> calls is\noften times faster and more readable.</p>\n</li>\n<li><p>A list of rewards should be called <code>rewards</code> instead of <code>reward</code>. Same goes for <code>values</code> and <code>true_values</code>.</p>\n</li>\n<li><p>We don't need to <code>enumerate</code> rewards, since we don't need the index itself. We can simply iterate over <code>rewards</code>.</p>\n<pre><code>def loopfunction(alpha, rewards, true_values):\n\n values = [0.5]\n for reward in rewards:\n values.append(lever_update(alpha, values[-1], reward))\n\n values.pop(0)\n\n return [abs(value - true_value) for value, true_value in zip(values, true_values)]\n</code></pre>\n</li>\n</ol>\n<p>I sadly can't test performance right now, but I would assume the first <code>for</code> loop takes up most of your runtime. This is what I'd focus on for further improvements. In general, making code more concise and readable also allows for easier refactoring / performance improvements in the future.</p>\n<hr />\n<p>We can also make <code>lever_update</code> more concise:</p>\n<pre><code>def lever_update(alpha, value, reward):\n return value + alpha * (reward - value)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T10:40:59.090", "Id": "260490", "ParentId": "260488", "Score": "1" } } ]
{ "AcceptedAnswerId": "260490", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T10:11:36.320", "Id": "260488", "Score": "3", "Tags": [ "python", "performance", "functional-programming" ], "Title": "Finding the difference between the estimated value and the true value in a reward task" }
260488
<p>We have a large set of projects at work. It's very important we keep track of those and every so often we need to run a full back-up that's unrelated to the 'normal' back-ups IT is running (snapshots every day, week, month, etc.). Recently we had a big migration on all of the older projects. To make sure nothing is irreparably damaged during the migration (basically a version upgrade), everything is backed-up twice before the upgrade.</p> <p>There are network drives and slow computers involved (so everything is IO-bound), which makes CPU usage largely irrelevant.</p> <p>Current speed:</p> <ul> <li>under a minute/GB (local-to-local)</li> <li>around 3 minutes/GB (local-to-network)</li> <li>around 4 minutes/GB (network -&gt; local)</li> <li>under 2 minutes/GB (network -&gt; network)</li> </ul> <p>We're talking 60+ GB for the source directory, spread over 7k folders and 180k files. If we could somehow read/write differently to make it easier on the disks and the network, that would be great.</p> <p>I'm working on an application that eventually does 3 things:</p> <ul> <li>backup</li> <li>set a secondary program loose on the original data for the migration</li> <li>clean-up</li> </ul> <p>This question is purely concerned about the first part of that process, the rest of the story is purely to explain the context and motivation. It can be used stand-alone just fine, so it's ready for review.</p> <p>This program will perform some basic sanity checks on the directories involved, verify the required space is available and perform a backup to as many locations as you like. At the end it prints how many bytes were written, for a quick visual check whether anything went wrong. It's important that meta-data like the dates of creation and last modification are kept intact.</p> <p>I've split the code into somewhat sensible functions. Some are doing the heavy lifting, others are just helpers to avoid repeating myself. I'm not happy about how I've implemented the directory validation, the reporting and exception handling is shoddy at best and I'm sure other functions can be improved in terms of re-usability.</p> <p>I've tried doing some fancy things on the directory checking so I could recursively determine the validity without any care whether I passed a string, a WindowsPath or a dictionary. Which failed horribly. I feel like I'm not optimally using <code>pathlib</code>, but considering I'm legacy tools (I was running into fairly odd <code>PermissionError</code> trouble with <code>shutil</code> while <code>xcopy</code> &quot;just works&quot;) I'm not entirely sure that can be helped. I think all the readouts and at least part of the validation could be done with decorators, <a href="https://codereview.stackexchange.com/a/235960/52915">like here</a> but that's still fairly magical to me.</p> <p>I'm fairly sure it shouldn't all be in one file either, but considering I'd just take everything except <code>main</code> and put it in a <code>utils.py</code>, I hadn't gone that route yet. I'm open to ideas. Honestly I'm surprised my code still works, it doesn't look like it should. I've attempted (not shown) to prettify it with wrappers and decorators, but it seems like it would require a rewrite before that's going to work. As long as the data gets copied in a cleanly matter, the rest of the code can still be changed any which way. The spec isn't set in stone.</p> <pre><code># -*- coding: utf-8 -*- &quot;&quot;&quot; Created on Wed May 5 13:10:37 2021 @author: Mast Notes: # xcopy &amp; psutil don't seem to handle pathlib.WindowsPath too well, # converting to string conveniently turns / into \\ # shutil kept running into PermissionError where xcopy has no trouble &quot;&quot;&quot; import os import sys import subprocess import psutil import time from datetime import datetime from pathlib import Path PROJECTS_SOURCE = Path('Z:/EPLAN_DATA/Gegevens/Projecten/') BACKUP_DIRECTORIES = { 'local': Path('C:/backups/eplanprojects'), 'network': Path('N:/BackupsEplan') } XCOPY_ARGS = &quot;/e /h /i /q /s /z&quot; MAX_BACKUPS = 3 SLEEP_TIME = 60 FORCE = True def to_megabytes(size): &quot;&quot;&quot; Parameters ---------- size : int Returns ------- str Turn Bytes into rounded MegaBytes. &quot;&quot;&quot; return &quot;{0} MB&quot;.format(round(size / 1000000.0, 2)) def get_directory_size(directory): &quot;&quot;&quot; Parameters ---------- directory : pathlib.WindowsPath Returns ------- int Size of the contents of the directory in Bytes. &quot;&quot;&quot; print(&quot;Calculating size of {0}&quot;.format(directory)) size = 0 for path, _, files in os.walk(directory): for file in files: file_path = os.path.join(path, file) size += os.path.getsize(file_path) print(to_megabytes(size)) return size def free_space(directory): &quot;&quot;&quot; Parameters ---------- directory : pathlib.WindowsPath Returns ------- int Free space available on partition the directory belongs to. &quot;&quot;&quot; return psutil.disk_usage(str(directory)).free def terminate_program(additional_info=&quot;&quot;): &quot;&quot;&quot; Parameters ---------- additional_info : str (OPTIONAL) Print additional_info, wait &amp; exit. &quot;&quot;&quot; print(&quot;Program terminated before completion.&quot;) if additional_info: print(additional_info) time.sleep(SLEEP_TIME) sys.exit() def validate_directory(directory): &quot;&quot;&quot; Parameters ---------- directory : pathlib.WindowsPath Raise FileNotFoundError if directory does not exist. &quot;&quot;&quot; if not directory.exists(): print(&quot;Invalid directory: {0}&quot;.format(directory)) raise FileNotFoundError def verify_available_backup_space(source_size, backup_directories): &quot;&quot;&quot; Parameters ---------- source_size : int backup_directories : dict of pathlib.WindowsPath Validate backup directories exist and are big enough to hold source. Terminate on failure. &quot;&quot;&quot; for backup_directory in backup_directories.values(): validate_directory(backup_directory) backup_space_available = free_space(backup_directory) if source_size &gt; backup_space_available: # WARNING: If multiple back-up locations are on the SAME partition, # this check is insufficient print(&quot;That's not going to fit.\nTarget: {0} available.\nSource: {1}&quot;.format( backup_space_available, source_size)) terminate_program() def backup_projects(source, backup_directories): &quot;&quot;&quot; Parameters ---------- source : pathlib.WindowsPath backup_directories : dict of pathlib.WindowsPath Returns ------- list of int : bytes_written Perform backup of source directory to (multiple) backup directories. &quot;&quot;&quot; bytes_written = [] for backup_directory in backup_directories: if len([f.path for f in os.scandir(backup_directories.get(backup_directory)) if f.is_dir()]) &gt;= MAX_BACKUPS: print(&quot;Amount of immediate subdirectories in ({0}) is higher or equal to maximum amount of backups ({1}) configured.&quot;.format( backup_directory, MAX_BACKUPS)) if not FORCE: terminate_program() else: print(&quot;Backup forced. Continuing.&quot;) print(backup_directories[backup_directory]) start_time = datetime.now() print(&quot;Start copy {0}&quot;.format(start_time)) try: subfolder = &quot;_{}&quot;.format(start_time).replace( ':', '-').replace(' ', '_').split('.')[0] print(subfolder) syscall = &quot;xcopy {source} {destination}\\{subfolder} {args}&quot;.format( source=str(source), destination=str(backup_directories[backup_directory]), subfolder=subfolder, args=XCOPY_ARGS) print(syscall) subprocess.run(syscall, check=True) except PermissionError: print(&quot;Permission denied: {0}&quot;.format(syscall)) terminate_program() end_time = datetime.now() print(&quot;Started: {0}\nFinished: {1}\nExecution time {2}&quot;.format( start_time, end_time, end_time - start_time) ) bytes_written.append(get_directory_size( str(backup_directories[backup_directory]) + '\\' + subfolder)) for value in bytes_written: print(to_megabytes(value)) def main(): validate_directory(PROJECTS_SOURCE) projects_source_size = get_directory_size(PROJECTS_SOURCE) verify_available_backup_space(projects_source_size, BACKUP_DIRECTORIES) backup_projects(PROJECTS_SOURCE, BACKUP_DIRECTORIES) if __name__ == &quot;__main__&quot;: main() print(&quot;Press any key...&quot;) input() </code></pre> <p>Real output:</p> <pre class="lang-none prettyprint-override"><code>Calculating size of Z:\EPLAN_DATA\Gegevens\Projecten 60585.67 MB C:\backups\eplanprojects Start copy 2021-05-07 17:21:57.007150 _2021-05-07_17-21-57 xcopy Z:\EPLAN_DATA\Gegevens\Projecten C:\backups\eplanprojects\_2021-05-07_17-21-57 /e /h /i /q /s /z 178642 File(s) copied Started: 2021-05-07 17:21:57.007150 Finished: 2021-05-07 21:41:52.366467 Execution time 4:19:55.359317 Calculating size of C:\backups\eplanprojects\_2021-05-07_17-21-57 60585.67 MB N:\BackupsEplan Start copy 2021-05-07 21:43:31.600948 _2021-05-07_21-43-31 xcopy Z:\EPLAN_DATA\Gegevens\Projecten N:\BackupsEplan\_2021-05-07_21-43-31 /e /h /i /q /s /z 178642 File(s) copied Started: 2021-05-07 21:43:31.600948 Finished: 2021-05-07 23:31:07.970629 Execution time 1:47:36.369681 Calculating size of N:\BackupsEplan\_2021-05-07_21-43-31 60585.67 MB 60585.67 MB 60585.67 MB Press any key... </code></pre> <p>Anything and everything is up for review. Nitpick away.</p> <p>Python 3.8.5 on Windows 10 x64, no limitations on libraries this time and no need to be cross-platform.</p>
[]
[ { "body": "<p>You can use f-strings instead of <code>.format()</code>. It makes the code more readable, and is also faster (see <a href=\"https://stackoverflow.com/questions/43123408/f-strings-vs-str-format\">here</a>, and even on my system, f-strings are about 4.4 times faster than <code>.format()</code> on my Windows machine, and about 3.5 times faster on WSL2 with Ubuntu 20.04 LTS), though the speed difference is negligible in most cases.</p>\n<p>For example, in <code>get_directory_size</code>, you can write <code>print(f&quot;Calculating size of {directory}&quot;)</code>.</p>\n<p>Similarly, in <code>to_megabytes</code>, you can write <code>return f&quot;{round(size / 1_000_000.0, 2)} MB&quot;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T15:38:01.047", "Id": "514196", "Score": "1", "body": "f-strings have the side-effect of handling backslashes a little differently like I do in `\"Started: {0}\\nFinished: {1}\\nExecution time {2}\".format(`, but apparently [there are workarounds](https://stackoverflow.com/a/44780467/1014587)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T09:41:15.970", "Id": "514243", "Score": "0", "body": "@Mast Yes, it is true that you cannot use backslashes inside the curly brackets in f-strings (thanks for pointing that out, I actually didn't know about that), but the example you posted is perfectly legal, even with f-strings. But you are correct: There are most definitely use-cases where it is better to use `.format` and stay away from f-strings." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T15:28:42.847", "Id": "260496", "ParentId": "260491", "Score": "2" } }, { "body": "<h1>Function Level Review</h1>\n<ul>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>`# -*- coding: utf-8 -*-`\n</code></pre>\n</blockquote>\n<p>In Python 3 the default encoding is UTF-8.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>&quot;{0} MB&quot;.format(round(size / 1000000.0, 2))\n</code></pre>\n</blockquote>\n<p>Division in Python 3 is float division, which functions like casting the numerator and/or denominator to floats before dividing.\nAs such you don't need to make the divisor a float.<br />\nNote: If you ever need Python 2 style division you can use <code>//</code>.</p>\n</li>\n<li>\n<blockquote>\n<p>1000000</p>\n</blockquote>\n<p>I'm struggling to read the number.\nWe have two options on how to make the number easier to read.</p>\n<ol>\n<li><p>We can use, in my opinion, ugly scientific notation.<br />\n1e6</p>\n</li>\n<li><p>We can use <code>_</code> as a thousands separator.<br />\n1_000_000</p>\n</li>\n</ol>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>&quot;{0} MB&quot;.format(round(size / 1000000.0, 2))\n</code></pre>\n</blockquote>\n<p>We can round to two decimal places using <code>format</code> rather than calling round.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&quot;{:.2f} MB&quot;.format(size / 1_000_000)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>f&quot;{size / 1_000_000:.2f} MB&quot;\n</code></pre>\n<p><strong>Note</strong>: <code>round</code> and <code>.2f</code> <em>act differently</em>. <code>round</code> can show 1-2 decimal places, where <code>.2f</code> <em>always</em> shows 2 dp.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; f&quot;{round(1.0, 2)}&quot;\n'1.0'\n&gt;&gt;&gt; f&quot;{1.0:.2f}&quot;\n'1.00'\n</code></pre>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-markdown prettyprint-override\"><code>Parameters\n----------\ndirectory : pathlib.WindowsPath\n</code></pre>\n</blockquote>\n<p>If we ran a type checker over your documentation on my OS your code would result in type errors.\nOnly specify the OS specific implementation <em>if you need</em> the OS specific implementation.</p>\n<p>An example of needing an OS specific path is if we are parsing a URL and we convert the URL path to a <code>PurePosixPath</code>.\nAs using a <code>PureWindowsPath</code> would make the output <em>invalid</em>.\nFor the code to be correct the type has to be the POSIX one.</p>\n</li>\n<li><p>Printing inside of <code>get_directory_size</code> makes the code less reusable.\nWhat if you want to get the size of a directory later, but you don't want to print the information?</p>\n<p>You can add an 'echo' flag to the function later to duct-tape a fix.\nHowever isn't a good solution.\nI find thinking of code as either 'library code' or 'application code' to make the most sense.\nLibrary code is code which is devoid of business requirements, like interacting with a user.\nWhere application code is the duct-tape holding together a bunch of library code to make the application your user interacts with.\nHowever by not having a clear separation between library code and application code you're making everything application code, which is harder to reuse later.</p>\n<p>I personally put library code into separate files or packages (which could make good pip packages).\nHowever with the amount of code you have, you'd just have added complexity for no benefit.</p>\n</li>\n<li><p>Your function <code>get_directory_size</code> looks good. If we ignore the SRP violation mentioned previously.</p>\n<p>I'd personally use a comprehension and <code>sum</code>.\nAs the code would be far more dense, and compact in a way I find easier to read.</p>\n<p>However, neither is better.</p>\n</li>\n<li><p>Your naming is pretty good.\nSo much so, I think most of your docstrings aren't needed.</p>\n<p>I think the docstrings are quite monotonous.\nWhich is absolutely fine for <code>to_megabytes</code> and <code>get_directory_size</code>.\nHowever has spilled over into <code>terminate_program</code> which I think could really do with a bit more explanation.<br />\nWhy is the code sleeping?\nWhy does the code take extra information to print?\nWhat is the goal of the code?\nWhy are you not using standard Python exceptions?</p>\n<p>As such I'd recommend identifying and paying special attention to the functions which shouldn't be monotonous.\nIf you write documentation after the code I'd recommend writing the special documentation first.\nAs I tend to find my documentation's quality tends to drop off toward the end.\nAnd, in all situations, I'd recommend having a think of what are the special functions after the first time you've written documentation.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def terminate_program(additional_info=&quot;&quot;):\nif additional_info:\n</code></pre>\n</blockquote>\n<p>I'd recommend using <code>None</code>, rather than a truthy test, to check if any additional information has been passed.\nFor example <code>terminate_program(False)</code> and <code>terminate_program(&quot;False&quot;)</code> output different information.\nAdditionally <code>None</code> is the standard 'do nothing' singleton.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>print(&quot;Program terminated before completion.&quot;)\nsys.exit()\n</code></pre>\n</blockquote>\n<p><code>sys.exit</code> defaults the status code to 0 - meaning the program ran successfully.\nHowever the message indicates the program exited abruptly and wasn't a successful run.\nWhich should be a non-zero status code.\nWhilst I can appreciate you probably have no use for the status code, if you ever change workflow having a correctly set status code will be a help.</p>\n<p>For example many Linux shell prompts display whether the previous command ran successfully from the status code.</p>\n<p><a href=\"https://i.stack.imgur.com/VGJ5B.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VGJ5B.png\" alt=\"Example of my shell showing a command which failed.\" /></a></p>\n<p>Status codes can be used by shells for control flow.\nFor example lets say I want to know if a program ran successfully.\nIn Fish I'd use:</p>\n<pre><code>if python -m &quot;print('doing something'); raise SystemExit(1)&quot;\n echo &quot;successful&quot;\nelse\n echo &quot;unsuccessful&quot;\nend\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>doing something\nunsuccessful\n</code></pre>\n<p>Again you're probably not invoking from the CLI otherwise you wouldn't be using the <code>input</code> on exit 'pattern'.\nSo kind of useless right now.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>print(&quot;Invalid directory: {0}&quot;.format(directory))\nraise FileNotFoundError\n</code></pre>\n</blockquote>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n validate_directory(PROJECTS_SOURCE)\n projects_source_size = get_directory_size(PROJECTS_SOURCE)\n\n verify_available_backup_space(projects_source_size, BACKUP_DIRECTORIES)\n</code></pre>\n</blockquote>\n<p>We can see you've opted to not use your custom <code>terminate_program</code>.\n<em>And</em> you're not putting the error message in the exception.\nAs such I think we've highlighted an issue with the error handling.</p>\n<p>Why is <code>terminate_program</code> insufficient here?\nWhat can we do to allow you to rely on one way to handle errors?</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>print(&quot;Amount of immediate subdirectories in ({0}) is higher or equal to maximum amount of backups ({1}) configured.&quot;.format(\nbackup_directory, MAX_BACKUPS))\n</code></pre>\n</blockquote>\n<p>I think your format string is too long.\nAs I can't see <code>{1}</code> and <code>MAX_BACKUPS</code> at the same time.\nUsing an f-string here would resolve the length issue.</p>\n<p>As such, one of the things I dislike about linters is the stringent adherence to a max character length.\nSplitting the f-string up into separate chunks would hurt readability.\nBut would pass some dumb <code>len</code> check.\nI think keeping the print and string on one line is good.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>if len([f.path for f in os.scandir(backup_directories.get(backup_directory)) if f.is_dir()]) &gt;= MAX_BACKUPS:\n</code></pre>\n</blockquote>\n<p>I personally have two styles for <code>a &gt;= b</code>.</p>\n<ol>\n<li><p>When an expression is on a single line always have a preference for the smaller expression on the left hand side of the line.</p>\n<p>I tend to notice long lines of code tend to have one thing which is long, and everything else tends to be short.\nFor example your long thing is &quot;<code>os.scandir(backup_directories.get(backup_directory))</code>&quot;, which is really easy to read and is quite simple.\nIf we ignore the fact you're using a comprehension for a moment.\nHaving the short, but important parts, on the left-hand side of the editor means we don't accidentally skip over important information in the right hand side.\nLike noticing the check is <code>len(...) &lt;= MAX_BACKUPS</code> not <code>len([... if f.is_dir() &lt;= MAX_BACKUPS])</code>.\nSkimming lines can cause some silly misreadings.</p>\n</li>\n<li><p>Always have a preference for <code>&lt;</code> over <code>&gt;</code>.<br />\nHaving a preference for one over the other means you can focus less on the minute detail and more on reading.\nA friend challenged me to complete a test where I was asked a bunch of <code>&lt;</code>/<code>&gt;</code> questions.\nThe challenge wasn't reading the text, or knowing what <code>&lt;</code> or <code>&gt;</code> are.\nThe challenge was not being tripped up by the questionnaire constantly flipping between the two.</p>\n<p>I've picked <code>&lt;</code>, over <code>&gt;</code>, as ordering the smallest to largest, left to right and top to bottom are most common.\nIf you have a sorted list of numbers which would you commonly say:</p>\n<ul>\n<li>\n<blockquote>\n<p>0, 5, 231, 1342</p>\n</blockquote>\n</li>\n<li>\n<blockquote>\n<p>1342, 231, 5, 0</p>\n</blockquote>\n</li>\n</ul>\n</li>\n</ol>\n<p>A simple rearrange would get us:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if MAX_BACKUPS &lt;= len([f.path for f in os.scandir(backup_directories.get(backup_directory)) if f.is_dir()]):\n</code></pre>\n<p>However <code>if f.is_dir()</code> is still on the right hand side of your space taker, <code>os.scandir(...)</code>.\nSo I'd split the comprehension over multiple lines.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if (MAX_BACKUPS\n &lt;= len([\n f.path\n for f in os.scandir(backup_directories.get(backup_directory))\n if f.is_dir()\n ])\n):\n</code></pre>\n<p>And you should be able to see here is a pretty good example where you have one big space filler, and everything else is small.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>for backup_directory in backup_directories:\n</code></pre>\n</blockquote>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>backup_directories.get(backup_directory)\n</code></pre>\n</blockquote>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>print(backup_directories[backup_directory])\n</code></pre>\n</blockquote>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>destination=str(backup_directories[backup_directory]),\n</code></pre>\n</blockquote>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>str(backup_directories[backup_directory]) + '\\\\' + subfolder))\n</code></pre>\n</blockquote>\n<p>You should either make a variable or iterate over the items.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for backup_directory, destination in backup_directories.items():\n</code></pre>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>start_time = datetime.now()\n&quot;_{}&quot;.format(start_time).replace(':', '-').replace(' ', '_').split('.')[0]\n</code></pre>\n</blockquote>\n<p>I think formatting the <code>datetime</code> would make the code much easier to understand.</p>\n<pre class=\"lang-py prettyprint-override\"><code>f&quot;_{start_time:%Y-%m-%d_%H-%M-%S}&quot;\n</code></pre>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>str(backup_directories[backup_directory]) + &quot;\\\\&quot; + subfolder\n</code></pre>\n</blockquote>\n<p>I think the best part of <code>pathlib</code> is being able to use <code>/</code> to join path segments.\nYou should use <code>/</code> for cross platform compatibility.\nAnd, <code>/</code> is much cleaner than <code>+ &quot;\\\\&quot; +</code> or <code>+ os.path.sep +</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>str(backup_directories[backup_directory] / subfolder)\n</code></pre>\n</li>\n</ul>\n<p><strong>Note</strong>: Docstrings removed for brevity.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport sys\nimport subprocess\nimport psutil\nimport time\n\nfrom datetime import datetime\nfrom pathlib import Path\n\n\nPROJECTS_SOURCE = Path('Z:/EPLAN_DATA/Gegevens/Projecten/')\nBACKUP_DIRECTORIES = {\n 'local': Path('C:/backups/eplanprojects'),\n 'network': Path('N:/BackupsEplan')\n}\n\nXCOPY_ARGS = &quot;/e /h /i /q /s /z&quot;\nMAX_BACKUPS = 3\nSLEEP_TIME = 60\nFORCE = True\n\n\ndef to_megabytes(size):\n return f&quot;{size / 1_000_000:.2f}&quot;\n\n\ndef _get_directory_size(directory):\n return sum(\n os.path.getsize(os.path.join(path, file))\n for path, _, files in os.walk(directory)\n for file in files\n )\n\n\ndef get_directory_size(directory):\n print(&quot;Calculating size of {0}&quot;.format(directory))\n size = _get_directory_size(directory)\n print(to_megabytes(size))\n return size\n\n\ndef free_space(directory):\n return psutil.disk_usage(str(directory)).free\n\n\ndef terminate_program(additional_info=&quot;&quot;):\n print(&quot;Program terminated before completion.&quot;)\n if additional_info:\n print(additional_info)\n time.sleep(SLEEP_TIME)\n sys.exit()\n\n\ndef validate_directory(directory):\n if not directory.exists():\n print(&quot;Invalid directory: {0}&quot;.format(directory))\n raise FileNotFoundError\n\n\ndef verify_available_backup_space(source_size, backup_directories):\n for backup_directory in backup_directories.values():\n validate_directory(backup_directory)\n backup_space_available = free_space(backup_directory)\n if source_size &gt; backup_space_available:\n # WARNING: If multiple back-up locations are on the SAME partition,\n # this check is insufficient\n print(&quot;That's not going to fit.\\nTarget: {0} available.\\nSource: {1}&quot;.format(\n backup_space_available, source_size))\n terminate_program()\n\n\ndef backup_projects(source, backup_directories):\n bytes_written = []\n for backup_directory in backup_directories:\n if (MAX_BACKUPS\n &lt;= len([\n f.path\n for f in os.scandir(backup_directories.get(backup_directory))\n if f.is_dir()\n ])\n ):\n print(&quot;Amount of immediate subdirectories in ({0}) is higher or equal to maximum amount of backups ({1}) configured.&quot;.format(\n backup_directory, MAX_BACKUPS))\n if not FORCE:\n terminate_program()\n else:\n print(&quot;Backup forced. Continuing.&quot;)\n print(backup_directories[backup_directory])\n\n start_time = datetime.now()\n print(&quot;Start copy {0}&quot;.format(start_time))\n try:\n subfolder = &quot;_{}&quot;.format(start_time).replace(':', '-').replace(' ', '_').split('.')[0]\n print(subfolder)\n syscall = &quot;xcopy {source} {destination}\\\\{subfolder} {args}&quot;.format(\n source=str(source),\n destination=str(backup_directories[backup_directory]),\n subfolder=subfolder,\n args=XCOPY_ARGS\n )\n print(syscall)\n subprocess.run(syscall, check=True)\n except PermissionError:\n print(&quot;Permission denied: {0}&quot;.format(syscall))\n terminate_program()\n end_time = datetime.now()\n print(&quot;Started: {0}\\nFinished: {1}\\nExecution time {2}&quot;.format(\n start_time,\n end_time,\n end_time - start_time\n ))\n bytes_written.append(get_directory_size(\n str(backup_directories[backup_directory] / subfolder)\n ))\n for value in bytes_written:\n print(to_megabytes(value))\n\n\ndef main():\n validate_directory(PROJECTS_SOURCE)\n projects_source_size = get_directory_size(PROJECTS_SOURCE)\n verify_available_backup_space(projects_source_size, BACKUP_DIRECTORIES)\n backup_projects(PROJECTS_SOURCE, BACKUP_DIRECTORIES)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n print(&quot;Press any key...&quot;)\n input()\n</code></pre>\n<h1>Design Level Review</h1>\n<ul>\n<li><p>As touched on earlier; lets redesign your <code>terminate_program</code> and <code>main</code> functions.<br />\nUsing exceptions for control flow is <em>very, very</em> common in Python.\nSo using one/ones here seems more than reasonable.\nRather than calling into <code>terminate_program</code>, we can raise a custom exception, <code>Terminate</code>, or any exception <a href=\"https://docs.python.org/3/library/exceptions.html#exception-hierarchy\" rel=\"nofollow noreferrer\">under, say, <code>Exception</code></a>.\nBecause we'll be raising exceptions we'll need to change <code>main</code> to integrate <code>terminate_program</code>.</p>\n<p>We then have a choice of options for how to handle the exceptions.\nWe can print full tracebacks with the <code>traceback</code> library.\nWe can print the message of the exception with <code>print</code>.\nOr we can just not print anything.</p>\n<p>Because I commonly use setuptools entrypoints I have two mains.\nOne to handle exceptions, and one to be the 'real' main.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _main():\n validate_directory(PROJECTS_SOURCE)\n projects_source_size = get_directory_size(PROJECTS_SOURCE)\n verify_available_backup_space(projects_source_size, BACKUP_DIRECTORIES)\n backup_projects(PROJECTS_SOURCE, BACKUP_DIRECTORIES)\n\n\ndef main():\n try:\n _main()\n except Exception as e:\n print(&quot;Program terminated before completion.&quot;)\n message = str(e)\n if message:\n print(message)\n time.sleep(SLEEP_TIME)\n raise SystemExit(1) from None\n else:\n input(&quot;Press any key...\\n&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n</li>\n<li><p>I think building a <code>Backup</code> class would improve the readability and reusability of your code.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>if (MAX_BACKUPS\n &lt;= len([\n f.path\n for f in os.scandir(destination)\n if f.is_dir()\n ])\n):\n</code></pre>\n</blockquote>\n<p>Could become a single line with a call to a method <code>count_child_dirs</code>.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>f&quot;_{datetime.datetime.now():%Y-%m-%d_%H-%M-%S}&quot;\n</code></pre>\n</blockquote>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>syscall = f&quot;xcopy {source} {destination / subfolder} {XCOPY_ARGS}&quot;\nprint(syscall)\nsubprocess.run(syscall, check=True)\n</code></pre>\n</blockquote>\n<p>Both can be hidden behind a method.</p>\n</li>\n<li><p>I think using <code>logging</code> rather than <code>print</code> would be a good idea.\nThe line between when <code>logging</code> is good and when <code>print</code> is good isn't always clear.\nHowever here your prints seem more like a log of what happened, rather than, say, IO between the user and a game.\nBy using logging too you could log to a file so you no longer need <code>input</code> or to be around when the script is running in case an error occurs.</p>\n<p><strong>Note</strong>: I've not implemented logging and I've deleted some <code>print</code>s.\nPlease ignore.</p>\n</li>\n</ul>\n<p>Here is a rewrite to show my train of thoughts.<br />\n<strong>Note</strong>: Documentation removed for brevity.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\nimport datetime\nimport os\nimport pathlib\nimport subprocess\nimport time\nfrom typing import Sequence, Union\n\nimport psutil\n\nPROJECTS_SOURCE = pathlib.Path('Z:/EPLAN_DATA/Gegevens/Projecten/')\nBACKUP_DIRECTORIES = {\n 'local': pathlib.Path('C:/backups/eplanprojects'),\n 'network': pathlib.Path('N:/BackupsEplan')\n}\n\nXCOPY_ARGS = &quot;/e /h /i /q /s /z&quot;\nMAX_BACKUPS = 3\nSLEEP_TIME = 60\nFORCE = True\n\nAPath = Union[str, pathlib.PurePath]\n\n\ndef bytes_to_megabytes(size):\n return f&quot;{size / 1_000_000:.2f}&quot;\n\n\ndef get_directory_size(directory: APath) -&gt; int:\n return sum(\n os.path.getsize(os.path.join(path, file))\n for path, _, files in os.walk(directory)\n for file in files\n )\n\n\ndef get_free_space(directory: APath) -&gt; int:\n return psutil.disk_usage(str(directory)).free\n\n\nclass Backup:\n def __init__(self, path: pathlib.Path) -&gt; None:\n self.path = path.resolve()\n \n def exists(self) -&gt; bool:\n return self.path.exists()\n \n def count_child_dirs(self) -&gt; int:\n return sum(\n 1\n for f in os.scandir(self.path)\n if f.is_dir()\n )\n \n def disk(self) -&gt; pathlib.Path:\n return pathlib.Path(self.path.drive)\n \n @staticmethod\n def backup_name(date: datetime.datetime) -&gt; str:\n return f&quot;_{date:%Y-%m-%d_%H-%M-%S}&quot;\n \n def copy_from(self, source: APath, date: datetime.datetime) -&gt; None:\n dir = self.path / self.backup_name(date)\n try:\n syscall = f&quot;xcopy {source} {dir} {XCOPY_ARGS}&quot;\n subprocess.run(syscall, check=True)\n return dir\n except PermissionError:\n raise ValueError(f&quot;Permission denied: {syscall}&quot;)\n\n\ndef validate_backups(source_size: int, backups: Sequence[Backup]) -&gt; None:\n disks = collections.defaultdict(int)\n for backup in backups:\n disks[backup.disk()] += 1\n if not backup.exists():\n raise FileNotFoundError(f&quot;Invalid directory: {backup}&quot;)\n if not FORCE and MAX_BACKUPS &lt;= backup.count_child_dirs():\n raise ValueError(f&quot;Amount of immediate subdirectories in ({backup}) is higher or equal to maximum amount of backups ({MAX_BACKUPS}) configured.&quot;)\n for disk, amount in disks.items():\n if amount * get_free_space(disk) &lt; source_size:\n raise ValueError(f&quot;That's not going to fit.\\nTarget: {disk} available.\\nSource: {source_size}&quot;)\n\n\ndef backup_projects(source: APath, backups: Sequence[Backup]) -&gt; None:\n bytes_written = []\n for backup in backups:\n print(backup)\n start_time = datetime.datetime.now()\n print(f&quot;Start copy {start_time}&quot;)\n dir = backup.copy_from(source)\n end_time = datetime.datetime.now()\n print(f&quot;Started: {start_time}\\nFinished: {end_time}\\nExecution time {end_time - start_time}&quot;)\n print(f&quot;Calculating size of {dir}&quot;)\n size = get_directory_size(dir)\n print(bytes_to_megabytes(size))\n bytes_written.append(size)\n for value in bytes_written:\n print(bytes_to_megabytes(value))\n\n\ndef _main():\n if not PROJECTS_SOURCE.exists():\n raise FileNotFoundError(f&quot;Invalid directory: {PROJECTS_SOURCE}&quot;)\n print(f&quot;Calculating size of {PROJECTS_SOURCE}&quot;)\n projects_source_size = get_directory_size(PROJECTS_SOURCE)\n print(bytes_to_megabytes(projects_source_size))\n backups = [Backup(b) for b in BACKUP_DIRECTORIES.values()]\n validate_backups(projects_source_size, backups)\n backup_projects(PROJECTS_SOURCE, backups)\n\n\ndef main():\n try:\n _main()\n except Exception as e:\n print(&quot;Program terminated before completion.&quot;)\n message = str(e)\n if message:\n print(message)\n time.sleep(SLEEP_TIME)\n raise SystemExit(1) from None\n else:\n input(&quot;Press any key...\\n&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T23:19:29.310", "Id": "519053", "Score": "0", "body": "Great answer! Just a quick comment, is there a reason you are using `os.walk` instead of doing something like `sum(f.stat().st_size for f in path.rglob(\"*\") if f.exists())`? Cheers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T23:29:41.407", "Id": "519056", "Score": "2", "body": "@N3buchadnezzar in `get_directory_size`? The simple answer is because Mast was already used `os.walk`. The longer answer is because I prefer using `os.walk` when I have to recursively descend and I only want directories or files. Having to figure out which of `f.is_dir()`, `f.is_file()`, `f.is_symlink()`, etc I want isn't how I want to spend my time. I also don't really want to figure out if `rglob` walks symlinks, and if `rglob` does how can I stop walking symlinks? `os.walk` is good enough" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T23:34:03.743", "Id": "519057", "Score": "0", "body": "Makes sense =) If I am already importing`pathlib` I try to get the most out of it before importing `os`, I guess that is just a bad habit of mine. Using `subprocess` with `pathlib` usually gets the job done. Speedwise I think they are much the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T01:12:37.403", "Id": "519063", "Score": "1", "body": "@N3buchadnezzar I confess when I first used `pathlib` I did the same :) Everything and everything was `pathlib`, `os.path` no more. But I now try to use the best tool for the job rather than being a 'purist'. For example, [`os.path.commonprefix`](https://docs.python.org/3/library/os.path.html#os.path.commonprefix) is pretty handy at times. Not necessarily when I'm interacting with paths mind you ;)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T21:32:50.127", "Id": "262955", "ParentId": "260491", "Score": "4" } } ]
{ "AcceptedAnswerId": "262955", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T11:09:41.910", "Id": "260491", "Score": "7", "Tags": [ "python", "python-3.x", "network-file-transfer" ], "Title": "Multi-site backup utility with basic sanity checks" }
260491
<p>I have tried to embody some basic ATM operations in a Object Oriented manner for practice. Would love some review pointers from structure, Object Oriented principles point of view. Also what should be my next steps in order to get good at OO design(I would like to read more code not books/videos, have pushed my mind out of 5 years of Tutorial Hell).</p> <p>Assumptions - My ATM implementation includes creating a user and open a bank account from an ATM.</p> <p>ATM Operations-</p> <p>Account Class</p> <ol> <li>Open Account</li> <li>Check Balance</li> <li>Withdraw</li> <li>PIN Change</li> <li>Mini Statement</li> </ol> <pre><code>package templates; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Account { private long accountBalance; private List&lt;String&gt; miniStatement; private boolean accountStatus; private String accountPIN; public Account() { this.accountBalance = 10000; this.accountStatus = true; this.accountPIN = &quot;1111&quot;; this.miniStatement = new ArrayList&lt;&gt;(); } public String doWithdraw(long amount) { if(this.accountStatus) { if(getBalance() &gt; 0.00 &amp;&amp; amount &gt; 0.00 &amp;&amp; getBalance() &gt;= amount) { this.accountBalance -= amount; String str = &quot;Account debited with $&quot;+amount; this.miniStatement.add(str); return str; }else return &quot;Amount entered is high, please enter less amount !!! &quot;; }else return &quot;Account is already closed&quot;; } public double getBalance() { if(checkAccountStatus()) return this.accountBalance; return -1.00; } public boolean changePIN(String newPin) { if(checkAccountStatus()) { this.accountPIN = newPin; return true; } return false; } private boolean checkAccountStatus() { return this.accountStatus; } public String closeAccount() { if(checkAccountStatus()) { String str = &quot;Please collect $&quot;+ getBalance(); this.accountStatus = false; return str+&quot;. Account is now closed&quot;; } return &quot;Account is already closed&quot;; } public Iterator&lt;String&gt; printMiniStatement() { return this.miniStatement.iterator(); } } </code></pre> <p>User Class</p> <ol> <li>Create User</li> <li>Set First Name</li> <li>Get First Name</li> <li>Set Last Name</li> <li>Get Last Name</li> <li>Set User Address</li> <li>Get User Address</li> <li>Set Phone Number</li> <li>Get Phone Number</li> </ol> <pre><code>package templates; public class User { private String firstName; private String lastName; private String address; private String phoneNumber; public User(String firstName,String lastName,String address,String phoneNumber) { this.firstName = firstName; this.lastName = lastName; this.address = address; this.phoneNumber = phoneNumber; } public void setFirstName(String fname) { this.firstName = fname; } public String getFirstName() { return this.firstName; } public void setLastName(String lname) { this.lastName = lname; } public String getLastName() { return this.lastName; } public void setAddress(String addr) { this.address = addr; } public String getAddress() { return this.address; } public void setPhoneNumer(String phonenum) { this.phoneNumber = phonenum; } public String getPhoneNumber() { return this.phoneNumber; } } </code></pre> <p>Main/Test Class</p> <pre><code>package test; import java.util.Iterator; import templates.*; public class ATMTest { public static void main(String[] args) { Account savings = new Account(); User user1 = new User(&quot;Dummy&quot;,&quot;Name&quot;,&quot;27, First Floor, Suok-I&quot;,&quot;8888888888&quot;); System.out.printf(&quot;%s%n&quot;, &quot;Account Balance is $&quot;+savings.getBalance()); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(50)); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(5540)); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(3350)); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(1090)); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(90)); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(966)); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, &quot;Account Balance is $&quot;+savings.getBalance()); System.out.println(&quot;-------------------------------------&quot;); savings.changePIN(&quot;1611&quot;); Iterator&lt;String&gt; itr = savings.printMiniStatement(); System.out.printf(&quot;%20s%n&quot;, &quot;MINI STATEMENT&quot;); while(itr.hasNext()) { System.out.printf(&quot;%s%n&quot;, itr.next()); } System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, user1.getFirstName()); System.out.printf(&quot;%s%n&quot;, user1.getLastName()); System.out.printf(&quot;%s%n&quot;, user1.getAddress()); System.out.printf(&quot;%s%n&quot;, user1.getPhoneNumber()); System.out.println(&quot;-------------------------------------&quot;); user1.setFirstName(&quot;Rain&quot;); user1.setLastName(&quot;Man&quot;); user1.setAddress(&quot;32, Second Floor, Suok-I&quot;); user1.setPhoneNumer(&quot;9999999999&quot;); System.out.printf(&quot;%s%n&quot;, user1.getFirstName()); System.out.printf(&quot;%s%n&quot;, user1.getLastName()); System.out.printf(&quot;%s%n&quot;, user1.getAddress()); System.out.printf(&quot;%s%n&quot;, user1.getPhoneNumber()); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.closeAccount()); System.out.println(&quot;-------------------------------------&quot;); System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(1111)); System.out.println(&quot;-------------------------------------&quot;); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T13:40:07.373", "Id": "514191", "Score": "0", "body": "Your User setter methods should not be doing any error checking. Error checking is done when the information is input and can be corrected. A real financial system would have a separate Transaction class for all of the user transactions. The transaction file is called an accounting journal. Your Account class methods should return String rather than use System.out.println statements. The accountBalance field should be an int or a long and hold pennies. Floating-point arithmetic will drop pennies somewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:06:34.550", "Id": "514203", "Score": "0", "body": "@GilbertLeBlanc I have implemented suggested changes. Can you clarify how to deal with decimal values(pennies) ? Also please suggest some good code to grasp the idea of OOP. Thank you for the review as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:36:20.263", "Id": "514207", "Score": "0", "body": "int pennies = (double) amount * 100.0; double amount = 0.01 * pennies; I'm not sure what else you need to know about pennies and dollars. As far as good examples, here's a link to my [GitHub](https://github.com/ggleblanc2). Pick any Java application that looks interesting to you." } ]
[ { "body": "<h2>Only submit compilable code to review</h2>\n<p>There is an type-issue in your ATMTest.\nThe <code>printMiniStatement</code>-Method in <code>Iterator&lt;String&gt; itr = savings.printMiniStatement();</code>\nhas return type void, but the variable is expecting an Iterator.\nHence, the code can't be compiled.</p>\n<h2>Logic &amp; Design</h2>\n<p>You should introduce some relation between User and Account since they are obviously connected.\nFor example:</p>\n<ul>\n<li>A User may have several Accounts: You can add a field <code>List&lt;Account&gt; accounts</code> to <code>User</code></li>\n<li>An Account has exactly one User: You can add a field <code>User user</code> to <code>Account</code></li>\n</ul>\n<p>You should add an <code>ATM</code>-Class which is responsible for doing the withdrawal.\nThis should not be done by the Account itself. Take a look at the Single-Responsibility-Principle\nfor more information(link below). You should also add a field <code>String id</code> to Account.\nIt can be used in combination with the <code>accountPin</code>-field\nto allow an ATM-Instance to conduct some authentication.</p>\n<p>As Gilbert pointed out: Don't use floating point when representing money.\nFloating point representation isn't 100% accurate so you will lose/add a few cents at times.\nUse an integer/long instead. They don't suffer from precision errors and won't\ncause these types of bugs that are hard to pin down(link below).</p>\n<p>And why does the Account-Class only have a no argument constructor that assigns arbitrary\nvalues?</p>\n<p><strong>Further reading:</strong></p>\n<ul>\n<li>Single-Responsibility-Principle: <a href=\"https://stackify.com/solid-design-principles/\" rel=\"nofollow noreferrer\">https://stackify.com/solid-design-principles/</a></li>\n<li>Floating point precision error: <a href=\"https://www.simplexacode.ch/en/blog/2018/07/using-bigdecimal-as-an-accurate-replacement-for-floating-point-numbers/\" rel=\"nofollow noreferrer\">https://www.simplexacode.ch/en/blog/2018/07/using-bigdecimal-as-an-accurate-replacement-for-floating-point-numbers/</a></li>\n</ul>\n<h2>toString-Method</h2>\n<p>You can override a class' <code>toString</code>-Method so <code>System.out.println(...)</code> can infer a string representation of its instances.\nTake the following scenario: Creating a new User and immediately printing out\nthe assigned values. You did just that in your <code>ATMTest</code>-class by repeatedly calling different getters.\nBy overriding the User's &quot;toString&quot;-Method, this can be abbreviated to: <code>System.out.println(new User(...))</code></p>\n<p><strong>Further reading:</strong></p>\n<ul>\n<li><a href=\"https://www.baeldung.com/java-tostring\" rel=\"nofollow noreferrer\">https://www.baeldung.com/java-tostring</a></li>\n</ul>\n<h2>this-keyword</h2>\n<p>Only use <code>this</code> when you have to avoid shadowing/ambiguity.\nOtherwise, it makes your code harder to read.</p>\n<p><strong>Further reading:</strong></p>\n<ul>\n<li>When to use <code>this</code>: <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html</a></li>\n<li>Tutorial on shadowing: <a href=\"https://javabeginnerstutorial.com/core-java-tutorial/variable-shadowing/\" rel=\"nofollow noreferrer\">https://javabeginnerstutorial.com/core-java-tutorial/variable-shadowing/</a></li>\n</ul>\n<h2>Whitespace</h2>\n<p>Use whitespaces to your advantage.\nVisual gaps created by whitespace are a necessary guide when reading someone's code.\nThey provide additional structure and hence increase readability.</p>\n<p><strong>Further reading:</strong></p>\n<ul>\n<li>Code-conventions: <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-whitespace.html\" rel=\"nofollow noreferrer\">https://www.oracle.com/java/technologies/javase/codeconventions-whitespace.html</a></li>\n</ul>\n<h2>Wildcard-Import</h2>\n<p>Statements like <code>import templates.*;</code> import all the classes in the <code>templates</code>-package.\nAvoid wildcard-imports as they may lead to cumbersome errors when compiling due to naming conflicts.</p>\n<p><strong>Further reading:</strong></p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad\">https://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad</a></li>\n</ul>\n<hr />\n<p>I only added a few comments to your code marking spots where the above points can be implemented. It's running just the way it used to!<br />\n<strong>Account Class</strong></p>\n<pre><code>package templates;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class Account {\n /*\n &quot;accountBalance&quot; can be renamed to &quot;balance&quot; since &quot;accountBalance&quot; always belongs to an instance of &quot;Account&quot;.\n Preceding &quot;Balance&quot; by &quot;account&quot; doesn't add any information\n */\n private double accountBalance;\n private List&lt;String&gt; miniStatement;\n /*\n &quot;accountStatus&quot; is an extremly broad term and may lead to confusion. If your goal was to mark an account as closed\n consider renaming &quot;accountStatus&quot; to &quot;isClosed&quot;\n */\n private boolean accountStatus;\n private String accountPIN;\n\n public Account() {\n /*\n the &quot;this&quot;-keyword is only required if you need to avoid ambiguity (this applies to most of your getters/setters as well!!)\n take a look at your &quot;User&quot;-Constructor for more information (I left another comment over there :) )\n */\n\n this.accountBalance = 10000.0;\n this.accountStatus = true;\n this.accountPIN = &quot;1111&quot;;\n this.miniStatement = new ArrayList&lt;&gt;();\n\n }\n\n\n public String doWithdraw(double amount) {\n // Consistency! use either &quot;this.accountStatus&quot; or &quot;checkAccountStatus()&quot;\n if(this.accountStatus) {\n if(getBalance() &gt; 0.00 &amp;&amp; amount &gt; 0.00 &amp;&amp; getBalance() &gt;= amount) {\n\n this.accountBalance -= amount;\n // use meaningful names e.g. &quot;substatement&quot;\n String str = &quot;Account debited with $&quot;+amount;\n this.miniStatement.add(str);\n return str;\n\n }else\n return &quot;Amount entered is high, please enter less amount !!! &quot;;\n }else\n return &quot;Account is already closed&quot;;\n\n }\n\n public double getBalance() {\n\n if(checkAccountStatus())\n return this.accountBalance;\n\n // why should the balance of an disabled account be -1??\n return -1.00;\n }\n\n // replace &quot;changePIN&quot; by &quot;setPIN&quot;. The terms getter/setter are commonly in OOP. They make your code more readable to other programmers\n public boolean changePIN(String newPin) {\n if(checkAccountStatus()) {\n this.accountPIN = newPin;\n return true;\n }\n return false;\n }\n\n // replace &quot;checkAccountStatus&quot; by &quot;getAccountStatus&quot;\n private boolean checkAccountStatus() {\n return this.accountStatus;\n }\n\n public String closeAccount() {\n\n if(checkAccountStatus()) {\n System.out.printf(&quot;%s&quot;,&quot;Please collect $&quot;+ getBalance());\n\n this.accountStatus = false;\n\n return &quot;. Account is now closed&quot;;\n }\n return &quot;Account is already closed&quot;;\n\n }\n\n public void printMiniStatement() {\n\n if(checkAccountStatus()) {\n Iterator&lt;String&gt; itr = this.miniStatement.iterator();\n\n System.out.printf(&quot;%20s%n&quot;, &quot;MINI STATEMENT&quot;);\n\n while(itr.hasNext()) {\n\n System.out.printf(&quot;%s%n&quot;, itr.next());\n\n }\n }\n\n }\n\n}\n</code></pre>\n<p><strong>User Class</strong></p>\n<pre><code>package templates;\n\npublic class User {\n\n private String firstName;\n private String lastName;\n private String address;\n private String phoneNumber;\n\n /*\n Here, the &quot;this&quot;-keyword was necessary. Otherwise method parameters will shadow the field you want to assign a value to.\n */\n public User(String firstName,String lastName,String address,String phoneNumber) {\n\n this.firstName = firstName;\n this.lastName = lastName;\n this.address = address;\n this.phoneNumber = phoneNumber;\n\n }\n\n /* why abbreviate &quot;firstName&quot; to &quot;fname&quot;? Simply use &quot;firstName&quot; as your method parameter.\n This way you can avoid unnecessary confusion for other programmers. Keep the &quot;this&quot;-keyword to avoid ambiguity\n */\n public boolean setFirstName(String fname) {\n\n if(!fname.isEmpty()) {\n this.firstName = fname;\n\n return true;\n }\n\n return false;\n\n }\n\n public String getFirstName() {\n return this.firstName;\n }\n\n public boolean setLastName(String lname) {\n\n if(!lname.isEmpty()) {\n this.lastName = lname;\n\n return true;\n }\n\n return false;\n\n }\n\n public String getLastName() {\n return this.lastName;\n }\n\n\n public boolean setAddress(String addr) {\n\n if(!addr.isEmpty()) {\n this.address = addr;\n\n return true;\n }\n\n return false;\n\n }\n\n public String getAddress() {\n return this.address;\n }\n\n public boolean setPhoneNumer(String phonenum) {\n\n if(phonenum.length() == 10) {\n this.phoneNumber = phonenum;\n\n return true;\n }\n\n return false;\n\n }\n\n public String getPhoneNumber() {\n return this.phoneNumber;\n }\n}\n</code></pre>\n<p><strong>ATMTest Class</strong></p>\n<pre><code>package test;\n\nimport java.util.Iterator;\n\n// avoid wildcard imports\nimport templates.*;\n\npublic class ATMTest {\n\n public static void main(String[] args) {\n\n Account savings = new Account();\n\n User user1 = new User(&quot;Dummy&quot;,&quot;Name&quot;,&quot;27, First Floor, Suok-I&quot;,&quot;8888888888&quot;);\n\n System.out.printf(&quot;%s%n&quot;, &quot;Account Balance is $&quot;+savings.getBalance());\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(50));\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(5540));\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(3350));\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(1090));\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(90));\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(966));\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, &quot;Account Balance is $&quot;+savings.getBalance());\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n savings.changePIN(&quot;1611&quot;);\n\n /*\n // the following line can't be compiled -&gt; incompatible types\n Iterator&lt;String&gt; itr = savings.printMiniStatement();\n\n System.out.printf(&quot;%20s%n&quot;, &quot;MINI STATEMENT&quot;);\n\n while(itr.hasNext()) {\n\n System.out.printf(&quot;%s%n&quot;, itr.next());\n\n }\n */\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n // use the &quot;toString&quot;-Method here to print &quot;user1&quot;\n System.out.printf(&quot;%s%n&quot;, user1.getFirstName());\n\n System.out.printf(&quot;%s%n&quot;, user1.getLastName());\n\n System.out.printf(&quot;%s%n&quot;, user1.getAddress());\n\n System.out.printf(&quot;%s%n&quot;, user1.getPhoneNumber());\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n user1.setFirstName(&quot;Rain&quot;);\n\n user1.setLastName(&quot;Man&quot;);\n\n user1.setAddress(&quot;32, Second Floor, Suok-I&quot;);\n\n user1.setPhoneNumer(&quot;9999999999&quot;);\n\n System.out.printf(&quot;%s%n&quot;, user1.getFirstName());\n\n System.out.printf(&quot;%s%n&quot;, user1.getLastName());\n\n System.out.printf(&quot;%s%n&quot;, user1.getAddress());\n\n System.out.printf(&quot;%s%n&quot;, user1.getPhoneNumber());\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.closeAccount());\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n System.out.printf(&quot;%s%n&quot;, savings.doWithdraw(1111));\n\n System.out.println(&quot;-------------------------------------&quot;);\n\n }\n\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T18:05:53.843", "Id": "260618", "ParentId": "260493", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T12:36:29.140", "Id": "260493", "Score": "0", "Tags": [ "java", "object-oriented" ], "Title": "OOP ATM Implementation" }
260493
<p>Inspired by <a href="https://codereview.stackexchange.com/questions/260413/determine-if-a-point-is-inside-or-ouside-of-an-irregular-shape-on-a-bitmap">this question</a>, here's some C code to check if a point is &quot;inside&quot; of a shape on a simple black and white bitmap.</p> <p>For this exercise:</p> <ul> <li>Set bits form the &quot;outlines&quot; of a shape (and are never inside).</li> <li>Unset bits may be inside or outside of a shape.</li> <li>Unset bits with a path to the edge of the bitmap are &quot;outside&quot;.</li> <li>Unset bits with no path to the edge of the bitmap are &quot;inside&quot;.</li> <li>Paths may step diagonally between set bits.</li> </ul> <hr /> <pre><code> #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; void die() { __debugbreak(); } void die_if(bool condition) { if (condition) die(); } struct bitmap { size_t m_w; size_t m_h; bool* m_pixels; }; struct bitmap bitmap_from_string(size_t width, size_t height, char const* str) { die_if(!str); die_if(strlen(str) != width * height); bool* pixels = malloc(sizeof(bool) * width * height); die_if(!pixels); char const* src = str; bool* dst = pixels; char const set = '#'; for (size_t i = 0; i != width * height; ++i) *dst++ = (*src++ == set ? true : false); return (struct bitmap){ width, height, pixels }; } bool bitmap_is_in_bounds(struct bitmap* bmp, size_t x, size_t y) { die_if(!bmp); return (x &lt; bmp-&gt;m_w) &amp;&amp; (y &lt; bmp-&gt;m_h); } bool bitmap_at(struct bitmap* bmp, size_t x, size_t y) { die_if(!bmp); die_if(!bitmap_is_in_bounds(bmp, x, y)); return bmp-&gt;m_pixels[y * bmp-&gt;m_w + x]; } bool bitmap_is_at_edge(struct bitmap* bmp, size_t x, size_t y) { die_if(!bmp); die_if(!bitmap_is_in_bounds(bmp, x, y)); return (x == 0 || y == 0 || x == (bmp-&gt;m_w - 1) || y == (bmp-&gt;m_h - 1)); } void bitmap_free(struct bitmap* bmp) { die_if(!bmp); free(bmp-&gt;m_pixels); bmp-&gt;m_pixels = NULL; } /* bitmap_is_in_shape * A &quot;shape&quot; is composed of unset bits, fully enclosed (on axes and * diagonally) by set bits (so there should not exist a path of unset bits from * the start point to the edge of the bitmap). * Start points on set bits are not considered to be &quot;inside&quot; a shape. */ bool bitmap_is_in_shape(struct bitmap* bmp, size_t x, size_t y) { die_if(!bmp); die_if(!bitmap_is_in_bounds(bmp, x, y)); /* trivial rejection */ if (bitmap_at(bmp, x, y)) return false; /* on outline */ if (bitmap_is_at_edge(bmp, x, y)) return false; /* at edge */ /* depth first search */ struct coords { size_t x, y; }; size_t stack_size = 0; struct coords* stack = malloc(sizeof(struct coords) * bmp-&gt;m_w * bmp-&gt;m_h); /* coords to visit next */ die_if(!stack); bool* visited = calloc(bmp-&gt;m_w * bmp-&gt;m_h, sizeof(bool)); /* points added to stack - indexed the same as bitmap pixels */ die_if(!visited); visited[y * bmp-&gt;m_w + x] = true; /* start point already visited */ /* for each neighbour... */ #define N(c_x, c_y) \ X(c_x, c_y, -1, -1) \ X(c_x, c_y, -1, 0) \ X(c_x, c_y, -1, +1) \ X(c_x, c_y, 0, -1) \ X(c_x, c_y, 0, +1) \ X(c_x, c_y, +1, -1) \ X(c_x, c_y, +1, 0) \ X(c_x, c_y, +1, +1) /* check visited list and push to stack */ #define X(c_x, c_y, o_x, o_y) \ if (!visited[(size_t)(c_y + o_y) * bmp-&gt;m_w + (size_t)(c_x + o_x)]) \ { \ visited[(size_t)(c_y + o_y) * bmp-&gt;m_w + (size_t)(c_x + o_x)] = true; \ stack[stack_size++] = (struct coords){ (size_t)(c_x + o_x), (size_t)(c_y + o_y) }; \ } N(x, y); /* add neighbours */ bool result = true; while (stack_size != 0) { struct coords c = stack[--stack_size]; /* pop */ if (bitmap_at(bmp, c.x, c.y)) continue; /* on outline */ if (bitmap_is_at_edge(bmp, c.x, c.y)) { result = false; break; } /* at edge */ N(c.x, c.y); /* add neighbours */ } #undef X #undef N free(stack); free(visited); return result; } void test(bool expected, bool actual, char const* name) { printf(&quot;%s: %s\n&quot;, name, (expected == actual ? &quot;pass&quot; : &quot;FAIL&quot;)); } int main() { { struct bitmap bmp = bitmap_from_string(1, 1, &quot;#&quot;); test(false, bitmap_is_in_shape(&amp;bmp, 0, 0), &quot;one pixel - set&quot;); bitmap_free(&amp;bmp); } { struct bitmap bmp = bitmap_from_string(1, 1, &quot; &quot;); test(false, bitmap_is_in_shape(&amp;bmp, 0, 0), &quot;one pixel - unset&quot;); bitmap_free(&amp;bmp); } { struct bitmap bmp = bitmap_from_string(3, 3, &quot;###&quot; &quot;# #&quot; &quot;###&quot;); test(false, bitmap_is_in_shape(&amp;bmp, 0, 1), &quot;three pixel - on outline&quot;); test(true, bitmap_is_in_shape(&amp;bmp, 1, 1), &quot;three pixel - bounded&quot;); bitmap_free(&amp;bmp); } { struct bitmap bmp = bitmap_from_string(3, 3, &quot;###&quot; &quot;# #&quot; &quot;## &quot;); test(false, bitmap_is_in_shape(&amp;bmp, 0, 1), &quot;three pixel - on outline&quot;); test(false, bitmap_is_in_shape(&amp;bmp, 1, 1), &quot;three pixel - middle w/ outlet&quot;); bitmap_free(&amp;bmp); } { struct bitmap bmp = bitmap_from_string(8, 4, &quot;########&quot; &quot;###### #&quot; &quot;# #&quot; &quot;########&quot;); test(true, bitmap_is_in_shape(&amp;bmp, 1, 2), &quot;corridor - start&quot;); test(true, bitmap_is_in_shape(&amp;bmp, 6, 1), &quot;corridor - end&quot;); test(false, bitmap_is_in_shape(&amp;bmp, 3, 1), &quot;corridor - on outline&quot;); bitmap_free(&amp;bmp); } { struct bitmap bmp = bitmap_from_string(8, 4, &quot;##### ##&quot; &quot;###### #&quot; &quot;# # #&quot; &quot;########&quot;); test(true, bitmap_is_in_shape(&amp;bmp, 1, 2), &quot;corridor - room&quot;); test(false, bitmap_is_in_shape(&amp;bmp, 3, 2), &quot;corridor - start&quot;); test(false, bitmap_is_in_shape(&amp;bmp, 6, 1), &quot;corridor - end&quot;); test(false, bitmap_is_in_shape(&amp;bmp, 3, 1), &quot;corridor - on outline&quot;); bitmap_free(&amp;bmp); } } </code></pre> <p>Some things:</p> <ul> <li><p>The X macro was fun to use... but feels a little messy. Especially adding the offset to the coordinates.</p> </li> <li><p>I like to use assert-type checks (<code>die_if()</code>) everywhere... but is it too much? Often there's a check in a higher-level function (e.g. <code>bitmap_is_in_shape()</code> checks that the bitmap isn't null) that makes all the following lower-level checks redundant (e.g. in <code>bitmap_at()</code> checks it again).</p> <p>Would having two versions of lower-level access functions (e.g. <code>bitmap_at()</code> and <code>bitmap_at_unsafe()</code>) be silly?</p> </li> <li><p>Any other C-ish things (especially more modern stuff) that's missing?</p> </li> </ul> <p>Any other feedback welcome. :)</p>
[]
[ { "body": "<p>This looks like a very reasonable attempt at solving the problem. You are using a flood fill instead of counting the number of shape edges crossed, and that avoids a whole lot of issues, although it therefore won't be very fast.</p>\n<h1>Unnecessary conversion from string to bitmap?</h1>\n<p>Converting the input string to an array of <code>bool</code> is not doing anything useful. Why not just let your algorithm work on the original string? You can do this easily by writing:</p>\n<pre><code>struct bitmap {\n size_t m_w;\n size_t m_h;\n char const* m_pixels;\n};\n\nbool bitmap_at(struct bitmap* bmp, size_t x, size_t y)\n{\n return bmp-&gt;m_pixels[y * bmp-&gt;m_w + x] == '#';\n}\n</code></pre>\n<p>Also note that a <a href=\"https://en.wikipedia.org/wiki/Bitmap\" rel=\"nofollow noreferrer\">bitmap</a> is usually understood to use only one bit per pixel, and that would reduce the amount of storage necessary by a factor 8.</p>\n<h1>Consider pre-processing the bitmap</h1>\n<p>It should not be very hard to modify your code to pre-process the bitmap once, so that it stores for every pixel whether it is in a shape or outside it. For example, you can use the algorithm you have, but have it flood-fill from the edge. At the end, all the visited pixels should be outside the shapes, the unvisited pixels are inside shapes.</p>\n<h1>Make functions that should not be public <code>static</code></h1>\n<p>Helper functions that should not be called from other source files should be made <code>static</code>. This can help the compiler generate more optimal code, and will avoid possible linking errors if other parts of the program want to use the same function or variable name.</p>\n<h1>Use <code>assert()</code></h1>\n<p>Instead of writing your own function like <code>die()</code> and <code>die_if()</code>, just use the standard function <a href=\"https://en.cppreference.com/w/c/error/assert\" rel=\"nofollow noreferrer\"><code>assert()</code></a>. Debuggers should be able to break when that function is called.</p>\n<p>Another nice thing of <code>assert()</code> is that it is a macro that will do nothing if <code>NDEBUG</code> is defined, so you can use that to make a release build that does not have the overhead of the checks everywhere. That also means it's OK to use <code>assert()</code> a lot, as this will help find bugs faster during development.</p>\n<p>However, don't use <code>assert()</code> for things that should always be checked, even in optimized release builds. For example, when checking whether <code>malloc()</code> succeeded. In those cases, I'd recommend writing an explicit check, and think a bit more about what action to take in case of failure. Do you really need to abort the program in such a case, or can you recover gracefully?</p>\n<h1>Useless ternary</h1>\n<p>In this line:</p>\n<pre><code>*dst++ = (*src++ == set ? true : false);\n</code></pre>\n<p>The ternary expression is totally useless. You are checking something that is already either <code>true</code> or <code>false</code>, so you can just write:</p>\n<pre><code>*dst++ = *src++ == set;\n</code></pre>\n<h1>Avoid macros</h1>\n<p>The X-macro is not necessary. You can create an array with all the 8 offsets, and just use a regular <code>for</code>-loop to call the code that needs to be repeated. For example:</p>\n<pre><code>static const struct {\n int x;\n int y;\n} offsets[8] = {\n {-1, -1},\n {-1, 0},\n ...\n};\n\nfor (int i = 0; i &lt; 8; i++) {\n int x = c_x + offsets[i].x;\n int y = c_y + offsets[i].y;\n size_t idx = y * bmp-&gt;m_w + x;\n\n if (!visited[idx]) {\n visited[idx] = true;\n stack[stack_size++] = (struct coords){x, y};\n }\n}\n</code></pre>\n<h1>Consider using recursion</h1>\n<p>Whenever you create a stack manually, ask yourself if you need to do it. Your computer is already managing a stack for you when you run the program, so maybe you can just use that? Split off the part of <code>bitmap_is_in_shape()</code> that recursively call itself:</p>\n<pre><code>static bool recurse(struct bitmap* bmp, bool* visited, size_t x, size_t y)\n{\n if (bitmap_is_at_edge(bmp, x, y))\n return false;\n\n size_t idx = bmp-&gt;m_w * y + x;\n\n if (visited[idx] || bitmap_at(bmp, x, y))\n return true;\n else\n visited[idx] = true;\n\n static const struct {...} offsets[8] = {...};\n\n for (int i = 0; i &lt; 8; i++) {\n // Recursively check neighbors, but exit as soon as we have reached the edge.\n if (!recurse(bmp, visited, x + offsets[i].x, y + offsets[i].y))\n return false;\n }\n\n return true;\n}\n\nbool bitmap_is_in_shape(struct bitmap* bmp, size_t x, size_t y)\n{\n ...\n bool* visited = calloc(bmp-&gt;m_w * bmp-&gt;m_h, sizeof(bool));\n bool result = recurse(bmp, visited, x, y);\n free(visited);\n return result;\n}\n</code></pre>\n<p>The drawback is that you could exceed the amount of stack space available, on the other hand it will probably use much less memory than you did when reserving an array of <code>m_w * m_h</code> elements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:56:44.620", "Id": "514217", "Score": "0", "body": "Good review. Still found more and a slightly different approach to the neighbors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T07:25:52.600", "Id": "514230", "Score": "1", "body": "Thanks for the review. I was under the impression it was a good thing to have checks with the same behavior in both debug and release builds. (Otherwise I won't catch issues like failed memory allocation in release builds. Perhaps there's not much difference between `die()` and just crashing, but it's a lot easier to reason about what happens)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T07:55:53.957", "Id": "514234", "Score": "1", "body": "@user673679 You are right, you shouldn't use `assert()` in those cases. I've updated the answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T19:55:08.680", "Id": "260509", "ParentId": "260494", "Score": "4" } }, { "body": "<p><a href=\"/u/129343\">@G.Sliepen</a> already gave quite a few points to consider.<br />\nStill, there is a bit more, some points to elaborate, and some with a different interesting solution:</p>\n<ol>\n<li><p>As he said, your <code>die()</code> is equivalent to <code>assert(0)</code>, and <code>die_if(!expr)</code> is equivalent to <code>assert(expr)</code> unless <code>NDEBUG</code> is defined.</p>\n<p>The diagnostic is probably not as nice, and the code is not removed in release-mode.</p>\n<p>While most of the checks should be replaced by <code>assert()</code>, a few don't indicate a programming error, and thus should always kill the program, but never break into the debugger. Which I would expect <code>die()</code> to do, after giving an appropriate error-message.</p>\n</li>\n<li><p>Avoid <code>sizeof(TYPE)</code>. Nearly always, you can use <code>sizeof *pointer</code> instead, which avoids repeating information and possibly getting it wrong. Or not getting it changed everywhere at once should that become necessary.</p>\n</li>\n<li><p>Decide whether you want to pass your <code>struct bitmap</code> by value or by reference. Currently, there is no upside to passing it by reference, though you still do so sometimes.</p>\n</li>\n<li><p>You could work with a single linear coordinate for most of your algorithm. It wouldn't change anything but free up resources and simplify some computations.</p>\n</li>\n<li><p>If you put the start-point on the open stack, you don't have to mark its neighbors. One macro eliminated. Simplicity!</p>\n</li>\n<li><p>Managing your open stack would be simpler if you used two pointers (stack and top) instead of (stack and size).</p>\n</li>\n<li><p>A simple loop is much better than using macros to repeat the same code over and over.</p>\n<p>The other answer has one option using a lookup-table. Considering only 8 very short integers (they fit a nibble each) are needed, one (or two) 64-bit value and some bit-shifting lead to another quite performant solution.</p>\n</li>\n<li><p>I'm sad to say but many of your comments are obvious.</p>\n<p>The problem is that they neither describe why you do something, nor summarize a bigger part of the picture. A single line, or even a few if they are that uncomplicated, are trivially understood without a comment which can be stale.</p>\n</li>\n<li><p>While I understand that in C++ when member-functions grow too big, a prefix or suffix for member-variables can at least alleviate the confusion, importing that wart into C which only has free functions is needless clutter displacing more useful naming. Even in C++, the proper remedy is extracting functions and other refactorings leading to smaller functions.</p>\n</li>\n</ol>\n<p>Below just the modified core function, assuming all others accept <code>struct bitmap</code> by value. If you want to follow the suggestion of pre-processing and / or directly working with the source, feel free to start from here.</p>\n<pre><code>void die(const char* p) {\n if (p) fprintf(stderr, &quot;Fatal Error: %s\\n&quot;, p)\n exit(1);\n}\nbool bitmap_is_in_shape(struct bitmap bmp, size_t x, size_t y) {\n assert(bitmap_is_in_bounds(bmp, x, y));\n\n if (bitmap_at(bmp, x, y) || bitmap_is_at_edge(bmp, x, y)) return false;\n size_t* const stack = malloc(sizeof *stack * bmp.m_h * bmp.m_w);\n stack || die(&quot;Failed to allocate memory.&quot;);\n size_t* top = stack;\n\n bool *visited = calloc(bmp.m_h * bmp.m_w, sizeof *visited);\n visited || die(&quot;Failed to allocate memory.&quot;);\n\n *top++ = y * bmp.m_w + x;\n visited[y * bmp.m_w + x] = true;\n\n bool result = true;\n\n while (stack != top) {\n size_t linear = *--top;\n if (bitmap_is_at_edge(bmp, linear % bmp.m_w, linear / bmp.m_w)) {\n result = false;\n break;\n }\n#if 1\n for (uint64_t which = 0x01011e021e0101ff; which; which &gt;&gt;= 8) {\n linear += (signed char)(which &amp; 0xf0) / 16;\n linear += (signed char)((which &lt;&lt; 4) &amp; 0xf0) / 16 * bmp.m_w;\n#else\n for (uint64_t x = 0x00000100010000ff, y = 0x0101fe02fe0101ff; y; x &gt;&gt;= 8, y &gt;&gt;= 8) {\n linear += (signed char)x;\n linear += (signed char)y * bmp.m_w;\n#endif\n if (!visited[linear]) {\n visited[linear] = true;\n *top++ = linear;\n }\n }\n }\n\n free(stack);\n free(visited);\n\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T07:32:55.733", "Id": "514231", "Score": "0", "body": "Thanks for the review. `__debugbreak()` does actually kill the program if not running under a debugger." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T07:45:31.053", "Id": "514232", "Score": "0", "body": "Re. comments... yeah, I tend to find C fiddly enough that I want to summarize in English what each part of the code does. But maybe it's obvious to someone who's competent at C. :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T07:49:53.840", "Id": "514233", "Score": "1", "body": "@user673679 I think it's OK to add a comment describing what a larger section of code does, but comments that just describe what a one-liner does, like `c = stack[--stack_size]; /* pop */`, are often redundant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T15:57:23.300", "Id": "514264", "Score": "1", "body": "@user673679 Still kills it in the wrong way, as it implies a detected programming-error, instead of a somewhat expected lack of resources." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:55:58.183", "Id": "260515", "ParentId": "260494", "Score": "4" } } ]
{ "AcceptedAnswerId": "260509", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T12:59:48.867", "Id": "260494", "Score": "3", "Tags": [ "c", "depth-first-search" ], "Title": "Check if point is inside a bitmap shape" }
260494
<p>I would be grateful for a code review of my first &quot;real&quot; C# project (<a href="https://github.com/michaeljsiena/RockPaperScissors" rel="nofollow noreferrer">https://github.com/michaeljsiena/RockPaperScissors</a>). It's a basic rock, paper, scissors console game. It's probably quite over-engineered for what it is, but I wanted to try applying some aspects of object-oriented design I've been learing in a simple console app.</p> <p>I would especially appreciate comments on how I could further separate concerns in many of my methods. I also noticed much of the code involved in handling inputs is repeated so was hoping for some tips on how to reduce this.</p> <p>Edit: I've already implemented theVBE-it'srightforme suggestion - thanks again!</p> <p><strong>Program</strong></p> <pre><code>using System; namespace RockPaperScissors { class Program { static void Main(string[] args) { Console.Title = &quot;ROCK, PAPER, SCISSORS, LIZARD, SPOCK&quot;; var gameManager = GameManager.Instance; gameManager.PlayGame(); } } } </code></pre> <p><strong>GameManager</strong></p> <pre><code>using System; namespace RockPaperScissors { // Uses a singleton pattern public sealed class GameManager { private GameMode gameMode; private IPlayer player1, player2; private readonly ScoreManager scoreManager = ScoreManager.Instance; private static GameManager _instance = null; public static GameManager Instance { get =&gt; _instance ??= new GameManager(); } public void PlayGame() { // game loop do { // set up game gameMode = SetGameMode(); InitialisePlayers(gameMode, ref player1, ref player2); scoreManager.SetWinningScore(); // play game int round = 1; while (player1.Score &lt; scoreManager.WinningScore &amp;&amp; player2.Score &lt; scoreManager.WinningScore) { ConsoleHelper.PrintColorTextLine($&quot;\nROUND {round}&quot;, ConsoleColor.Blue); Rules.ShowMoveOutcomes(); // make moves player1.MakeMove(); player2.MakeMove(); // update and showround information scoreManager.UpdateGameScore(player1, player2); scoreManager.ShowGameScore(player1, player2); round++; } // show end of game information scoreManager.ShowWinner(player1, player2); scoreManager.ShowGameScore(player1, player2); } while (WillPlayAgain()); static GameMode SetGameMode() { ConsoleHelper.PrintColorText(&quot;GAME MODE ('1' = vs Computer, '2' = Simulation)?: &quot;, ConsoleColor.Blue); int playerInput; while (!int.TryParse(Console.ReadLine(), out playerInput) || !(playerInput == 1 || playerInput == 2)) { ConsoleHelper.PrintColorTextLine(&quot;Invalid input, try again...&quot;, ConsoleColor.Red); } return (GameMode)playerInput; } static void InitialisePlayers(GameMode gameMode, ref IPlayer player1, ref IPlayer player2) { switch (gameMode) { case GameMode.HumanVsComputer: // get player name ConsoleHelper.PrintColorText(&quot;PLAYER NAME: &quot;, ConsoleColor.Blue); string playerName = Console.ReadLine(); player1 = new HumanPlayer(playerName); player2 = new ComputerPlayer(&quot;HAL 9000&quot;); break; case GameMode.ComputerVsComputer: player1 = new ComputerPlayer(&quot;Skynet&quot;); player2 = new ComputerPlayer(&quot;HAL 9000&quot;); break; } } static bool WillPlayAgain() { ConsoleHelper.PrintColorText(&quot;\nPLAY AGAIN ('1' = yes, '2' = no)?: &quot;, ConsoleColor.Blue); int playerInput; while (!int.TryParse(Console.ReadLine(), out playerInput) || !(playerInput == 1 || playerInput == 2)) { ConsoleHelper.PrintColorTextLine(&quot;Invalid input, try again...&quot;, ConsoleColor.Red); } return playerInput == 1; } } } } </code></pre> <p><strong>ScoreManager</strong></p> <pre><code>using System; using System.Collections.Generic; namespace RockPaperScissors { // Uses a singleton pattern public sealed class ScoreManager { private static ScoreManager _instance = null; public static ScoreManager Instance { get =&gt; _instance ??= new ScoreManager(); } private ScoreManager() { } public int WinningScore { get; private set; } public int PlayerScore { get; private set; } public int ComputerScore { get; private set; } public void SetWinningScore() { ConsoleHelper.PrintColorText(&quot;WINNING SCORE: &quot;, ConsoleColor.Green); int winningScore; while (!int.TryParse(Console.ReadLine(), out winningScore) || winningScore &lt; 1) { ConsoleHelper.PrintColorTextLine(&quot;Invalid input, must be a positive whole number...&quot;, ConsoleColor.Red); } WinningScore = winningScore; } public void UpdateGameScore(IPlayer player1, IPlayer player2) { if (player1.Move == player2.Move) { player1.Score += 1; player2.Score += 1; } else if (player2.Move == Rules.MoveOutcomes[player1.Move].losingMove1 || player2.Move == Rules.MoveOutcomes[player1.Move].losingMove2) { player1.Score += 1; } else { player2.Score += 1; } } public void ShowGameScore(IPlayer player1, IPlayer player2) { ConsoleHelper.PrintColorTextLine($&quot;{player1.Name}'s Score: {player1.Score}\n{player2.Name}'s Score: {player2.Score}&quot;, ConsoleColor.Green); } public void ShowWinner(IPlayer player1, IPlayer player2) { string message = (player1.Score == player2.Score) ? $&quot;{player1.Name} and {player2.Name} tie!&quot; : $&quot;{(player1.Score &gt; player2.Score ? player1.Name : player2.Name)} wins!&quot;; ConsoleHelper.PrintColorTextLine(&quot;\n&quot; + new string('*', message.Length), ConsoleColor.Green); ConsoleHelper.PrintColorTextLine(message, ConsoleColor.Green); ConsoleHelper.PrintColorTextLine(new string('*', message.Length), ConsoleColor.Green); } } } </code></pre> <p><strong>IPlayer</strong></p> <pre><code>namespace RockPaperScissors { public interface IPlayer { public string Name { get; } public Move Move { get; } public int Score { get; set; } public void MakeMove(); } } </code></pre> <p><strong>Player</strong></p> <pre><code>namespace RockPaperScissors { public abstract class Player : IPlayer { public string Name { get; private set; } public Move Move { get; protected set; } public int Score { get; set; } protected Player(string name) =&gt; Name = name; public abstract void MakeMove(); } } </code></pre> <p><strong>HumanPlayer</strong></p> <pre><code>using System; namespace RockPaperScissors { public sealed class HumanPlayer : Player { public HumanPlayer(string name) : base(name) { } public override void MakeMove() { ConsoleHelper.PrintColorText($&quot;{this.Name}'s move: &quot;, ConsoleColor.White); int playerInput; while (!int.TryParse(Console.ReadLine(), out playerInput) || !Enum.IsDefined(typeof(Move), playerInput)) { ConsoleHelper.PrintColorTextLine(&quot;Invalid input, please try again...&quot;, ConsoleColor.Red); } Move = (Move)playerInput; } } } </code></pre> <p><strong>ComputerPlayer</strong></p> <pre><code>using System; namespace RockPaperScissors { public sealed class ComputerPlayer : Player { public ComputerPlayer(string name) : base(name) { } public override void MakeMove() { Move = RandomMoveGenerator.GenerateRandomMove(); Console.WriteLine($&quot;{this.Name} made a {this.Move}&quot;); } } } </code></pre> <p><strong>RandomMoveGenerator</strong></p> <pre><code>using System; using System.Linq; namespace RockPaperScissors { public static class RandomMoveGenerator { private readonly static Random random = new Random(); private static readonly Move[] moves = Enum.GetValues(typeof(Move)) .Cast&lt;Move&gt;() .ToArray(); public static Move GenerateRandomMove() =&gt; moves[random.Next(moves.Length)]; } } </code></pre> <p><strong>ConsoleHelper</strong></p> <pre><code>using System; // Made this to eliminate some of the clutter in GameManager.PlayGame() namespace RockPaperScissors { public static class ConsoleHelper { public static void PrintColorText(string text, ConsoleColor color) { Console.ForegroundColor = color; Console.Write(text); Console.ResetColor(); } public static void PrintColorTextLine(string text, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(text); Console.ResetColor(); } } } </code></pre> <p><strong>GameMode</strong></p> <pre><code>namespace RockPaperScissors { public enum GameMode { HumanVsComputer = 1, ComputerVsComputer // simulation, mainly for testing } } </code></pre> <p><strong>Move</strong></p> <pre><code>namespace RockPaperScissors { public enum Move { Rock = 1, Paper, Scissors, Lizard, Spock, } } </code></pre> <p><strong>Rules</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Text; namespace RockPaperScissors { public static class Rules { private static readonly Dictionary&lt;Move, (Move losingMove1, Move losingMove2)&gt; _moveOutcomes = new Dictionary&lt;Move, (Move, Move)&gt; { { Move.Rock, (Move.Scissors, Move.Lizard)}, { Move.Paper, (Move.Rock, Move.Spock)}, { Move.Scissors, (Move.Paper, Move.Lizard)}, { Move.Lizard, (Move.Paper, Move.Spock)}, { Move.Spock, (Move.Rock, Move.Scissors)}, }; public static Dictionary&lt;Move, (Move losingMove1, Move losingMove2)&gt; MoveOutcomes { get =&gt; _moveOutcomes; } public static void ShowMoveOutcomes() { ConsoleHelper.PrintColorTextLine(&quot;\nMOVES&quot;, ConsoleColor.Blue); foreach (KeyValuePair&lt;Move, (Move losingMove1, Move losingMove2)&gt; moveOutcome in Rules.MoveOutcomes) { ConsoleHelper.PrintColorTextLine($&quot;{moveOutcome.Key} (key: '{(int)moveOutcome.Key}') beats {moveOutcome.Value.losingMove1} and {moveOutcome.Value.losingMove2}&quot;, ConsoleColor.DarkGray); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T12:42:17.713", "Id": "514249", "Score": "1", "body": "I don't have expertise for a proper review but I am almost certain you should be using an interface for the `Player` subclasses rather than holding references to them using the base class. The point of abstract base class is to implement common functionality while interface is to represent object confirming to an expected set of functionality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T13:14:54.923", "Id": "514250", "Score": "1", "body": "@theVBE-it'srightforme Thanks for your comments. I used an abstract Player base class because I wanted derived classes to (1) have the same basic properites and behaviour and (2) be interchangeable in my GameManager and ScoreManager classes (since both you and the computer can play the game). Therefore, I'm not sure I fully understand the advantage of using a Player interface in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T13:47:28.787", "Id": "514251", "Score": "1", "body": "Interface defines the set of methods/features/whatever that client code (eg GameManager and ScoreManager) can expect an object to conform to, so it more purely achieves the interchangeability aspect. In the conceptual framework of separating concerns, the concern of the interface would be to define what the object looks like externally, while the concern of the abstract base class would be to contain the common properties/functionality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T13:50:47.510", "Id": "514252", "Score": "2", "body": "Naturally this means they can be used together; in your case just declare `public interface IPlayer` with same set of methods in `Player`, have `Player : IPlayer`, and change the references in the client classes from `Player` to `IPlayer`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T10:42:54.817", "Id": "514396", "Score": "1", "body": "honestly on second thought I can probably be of at least some help trying to review it so will make attempt tomorrow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T21:03:20.660", "Id": "514428", "Score": "0", "body": "@theVBE-it'srightforme That would really be appreciated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T22:56:45.447", "Id": "514581", "Score": "0", "body": "Well I don't need to embarrass myself trying a full review but can still go through and see if I notice anything he might have missed." } ]
[ { "body": "<p>Overall a very good first attempt at a &quot;real&quot; project.</p>\n<ul>\n<li><p><strong>Drop &quot;Manager&quot; class name suffix</strong> — Consider renaming GameManager to simply Game. Similarly rename ScoreManager to something like GameScore. I see the &quot;Manager&quot; suffix frequently applied to classes that do not really manage something. Read <a href=\"https://blog.codinghorror.com/i-shall-call-it-somethingmanager/\" rel=\"nofollow noreferrer\">I shall call it... Something manager</a> for more information about why the &quot;Manager&quot; suffix isn't the greatest.</p>\n</li>\n<li><p><strong>Unnecessary use of singletons</strong> — there is no need to restrict then number of instances for GameManager and ScoreManager. If you need one and only one, consider using dependency injection or <code>new</code>ing up a ScoreManager in the constructor of GameManager. Sometimes objects only need to be singletons within a certain scope, and restricting classes to a single instance using a private constructor gains you nothing.</p>\n</li>\n<li><p><strong>Refactor nested ternary expression</strong> — the code to set the game winning message is impossible to read because a ternary expression is embedded in another ternary expression. It becomes a jumbled blob of text. Either Refactor into an if-else block or move this logic into its own method.</p>\n</li>\n<li><p><strong>Decouple writing to console</strong> — since static classes are used to write to the console, you cannot isolate the critical classes in your game for unit testing. Consider defining an interface with the methods and properties required in order to interact with the console.</p>\n</li>\n<li><p><strong>Define a class for moves</strong> — Believe it or not there is <em>some</em> behavior associated with a move. The logic of comparing moves to see which ones win belongs in its own class. It's funny that my second suggestion was to not use singletons, but a Move class is honestly a good use case for singletons. As a bonus, this implementation also lets you practice using <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors\" rel=\"nofollow noreferrer\">static constructors</a>.</p>\n<pre><code>public class Move\n{\n public static readonly Move Rock = new Move(&quot;Rock&quot;);\n public static readonly Move Paper = new Move(&quot;Paper&quot;);\n public static readonly Move Scissors = new Move(&quot;Scissors&quot;);\n public static readonly Move Spock = new Move(&quot;Spock&quot;);\n public static readonly Move Lizzard = new Move(&quot;Lizzard&quot;);\n\n public string Name { get; }\n private List&lt;Move&gt; defeatedMoves { get; }\n\n public IEnumerable&lt;Move&gt; DefeatedMoves =&gt; defeatedMoves;\n\n private Move(string name)\n {\n Name = name;\n defeatedMoves = new List&lt;Move&gt;();\n }\n\n static Move()\n {\n Rock.WinsAgainst(Scissors, Lizzard);\n Paper.WinsAgainst(Rock, Spock);\n Scissors.WinsAgainst(Paper, Lizzard);\n Lizzard.WinsAgainst(Paper, Spock);\n Spock.WinsAgainst(Rock, Scissors)\n }\n\n private void WinsAgainst(params Move[] defeatedMoves)\n {\n this.defeatedMoves.AddRange(defeatedMoves);\n }\n\n public bool Beats(Move opponentMove)\n {\n return defeatedMoves.Contains(opponentMove);\n }\n}\n</code></pre>\n<p>The line beginning <code>static Move() { ... }</code> is a static constructor. This gets invoked the first time a static member of the Move class gets accessed. This constructor wires together the moves that defeat each other. By using access modifiers, singletons and a static constructor the compiler restricts who defeats who.</p>\n<p>Notice that the <code>WinsAgainst</code> method is private, yet the static constructor in this class is still able to call this instance method, because the static constructor is a member of the Move class. More bonus points for practice using a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params\" rel=\"nofollow noreferrer\"><code>params</code> argument</a>.</p>\n<p>Lastly, the <code>bool Beats(Move)</code> method makes your <code>ScoreManager.UpdateGameScore</code> method much easier to read. No more parsing through a Dictionary object trying to infer the logic. The code reads exactly what it does:</p>\n<pre><code>public void UpdateGameScore(IPlayer player1, IPlayer player2)\n{\n if (player1.Move == player2.Move)\n {\n player1.Score += 1;\n player2.Score += 1;\n }\n// else if (player2.Move == Rules.MoveOutcomes[player1.Move].losingMove1 || player2.Move == Rules.MoveOutcomes[player1.Move].losingMove2)\n else if (player1.Move.Beats(player2.Move))\n {\n player1.Score += 1;\n }\n else\n {\n player2.Score += 1;\n }\n}\n</code></pre>\n<p>This leaves very little need for the <code>Rules</code> class. Any logic in that class could be moved in to GameManager or ScoreManager.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T09:35:15.957", "Id": "514533", "Score": "0", "body": "Thanks, Greg. A lot of good suggestions here - I agree coupling is definitely something I need to work on reducing. Static constructors also seem very handy! Why do you have a getter on what looks like a private field, defeatedMoves?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T11:37:18.993", "Id": "514537", "Score": "0", "body": "@ImNotThatCSharp: The getter returns an `IEnumerable<Move>` which does not allow you to add items to the collection. This is in case you want to loop over the moves that this move defeats. The private field is a `List<Move>`, which allows you to add or remove items from the collection. We want to restrict who can decide which moves are defeated to enforce the business rules of your game (rock beats scissors and lizzard)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T22:54:01.313", "Id": "514580", "Score": "0", "body": "Reading the link about naming classes with \"Manager\" suffix I think it would be fair to say it that it is still acceptable to do so as a placeholder while someone is in the earlier stages of the project? I mean if it serves some useful purpose for them making sense of what they are trying to do they shouldn't obsess about finding a better name at that moment because they know they aren't \"supposed\" to name things that way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T23:20:18.060", "Id": "514584", "Score": "1", "body": "@theVBE-it'srightforme: The earlier stages of a project are where names and coding idioms are established, and these features spread throughout the code. If you cannot come up with a good name, it might indicate a design problem with the class, or a need to understand the problem domain better. To be fair, this is a stage we all go through, but this should not be a stage we keep going through. [Temporary code becomes permanent all too often](https://github.com/chrislgarry/Apollo-11/blob/a49d8e792c71d957e67db05b50fc7d3fa3b5750b/Luminary099/LUNAR_LANDING_GUIDANCE_EQUATIONS.agc#L179)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T23:23:35.670", "Id": "514585", "Score": "1", "body": "If you're curious, that link in my previous comment was to the Apollo 11 lunar landing module code. The comment on that line of code reads `# TEMPORARY, I HOPE HOPE HOPE` and here we are 60 years later reading a \"temporary\" line of code. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T02:10:29.297", "Id": "514588", "Score": "0", "body": "Yeah, but how you do know they didn't refactor it for Apollo 12? :-p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T04:16:04.697", "Id": "514590", "Score": "0", "body": "I do get the principle of course. I just have noticed that worrying about a class or function name not being correct can stall my flow and thought it more efficient to get down something and keep going." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T18:08:46.480", "Id": "260665", "ParentId": "260502", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:10:11.547", "Id": "260502", "Score": "6", "Tags": [ "c#", "rock-paper-scissors" ], "Title": "Rock, Paper, Scissors - Applying OOP Principles" }
260502
<p>I have a <code>dataframe</code> with a column composed by <code>date</code> object and a column composed by <code>time</code> object. I have to merge the two columns.</p> <p>Personally, I think it is so ugly the following solution. Why I have to cast to <code>str</code>? I crafted my solution based <a href="https://stackoverflow.com/a/49668702/6290211">on this answer</a></p> <pre><code>#importing all the necessary libraries import pandas as pd import datetime #I have only to create a Minimal Reproducible Example time1 = datetime.time(3,45,12) time2 = datetime.time(3,49,12) date1 = datetime.datetime(2020, 5, 17) date2 = datetime.datetime(2021, 5, 17) date_dict= {&quot;time1&quot;:[time1,time2],&quot;date1&quot;:[date1,date2]} df=pd.DataFrame(date_dict) df[&quot;TimeMerge&quot;] = pd.to_datetime(df.date1.astype(str)+' '+df.time1.astype(str)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T03:32:39.717", "Id": "514442", "Score": "1", "body": "i agree it would be nice if they overloaded `+` for `date` and `time`, but your current `str`/`to_datetime()` code is the fastest way to do it (even if it looks uglier)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T03:38:49.850", "Id": "514443", "Score": "1", "body": "if your real data is coming from a csv, [`pd.read_csv(..., parse_dates=[['date1','time1']])`](https://stackoverflow.com/a/44920602/13138364) would probably be the \"prettiest\" and fastest option" } ]
[ { "body": "<p>We can let pandas handle this for us and use <code>DataFrame.apply</code> and <code>datetime.datetime.combine</code> like this:</p>\n<pre><code>df[&quot;TimeMerge&quot;] = df.apply(lambda row: datetime.datetime.combine(row.date1, row.time1), axis=1)\n</code></pre>\n<hr />\n<p>Although the following approach is more explicit and might therefore be more readable if you're not familiar with <code>DataFrame.apply</code>, I would strongly recommend the first approach.</p>\n<p>You could also manually map <code>datetime.datetime.combine</code> over a zip object of <code>date1</code> and <code>time1</code>:</p>\n<pre><code>def combine_date_time(d_t: tuple) -&gt; datetime.datetime:\n return datetime.datetime.combine(*d_t)\n\ndf[&quot;TimeMerge&quot;] = pd.Series(map(combine_date_time, zip(df.date1, df.time1)))\n</code></pre>\n<p>You can also inline it as an anonymous lambda function:</p>\n<pre><code>df[&quot;TimeMerge&quot;] = pd.Series(map(lambda d_t: datetime.datetime.combine(*d_t), zip(df.date1, df.time1)))\n</code></pre>\n<p>This is handy for simple operations, but I would advise against this one-liner in this case.</p>\n<hr />\n<p>By the way, <a href=\"https://stackoverflow.com/a/39474812/9173379\">the answer your were looking for</a> can also be found under <a href=\"https://stackoverflow.com/q/17978092/9173379\">the question you linked</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T03:28:49.800", "Id": "514441", "Score": "1", "body": "\"can and should\" seems too conclusive though. `apply(axis=1)` is usually the slowest option. in this case, it's 2x slower than `pd.to_datetime()` at 200 rows, 3x slower at 2K rows, 3.5x slower at 2M rows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T10:21:20.890", "Id": "514452", "Score": "0", "body": "Thank you for the input, I was expecting `df.apply` to be faster than that. I reduced it to *\"can\"*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T06:40:12.827", "Id": "514816", "Score": "0", "body": "Thank you @riskypenguin I missed the specific answer :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:48:17.013", "Id": "260504", "ParentId": "260503", "Score": "2" } } ]
{ "AcceptedAnswerId": "260504", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:19:09.717", "Id": "260503", "Score": "1", "Tags": [ "python", "datetime", "pandas" ], "Title": "Pandas merge a \"%Y%M%D\" date column with a \"%H:%M:%S\" time column" }
260503
<p>I previously posted a question for codereview:</p> <p><a href="https://codereview.stackexchange.com/questions/259824/python-autoclicker">Python Autoclicker</a></p> <p>And I received some great feedback and changes to do in the code.</p> <p>I have done many of the changes mentioned in the answers and here is the final code:</p> <pre><code>from pynput.keyboard import Controller from time import sleep def auto_click(key: str, n_clicks: int, delay: float): keyboard = Controller() for _ in range(n_clicks): keyboard.tap(key) sleep(delay) def main(): key = input(&quot;Key to be autopressed: &quot;) try: n_clicks = int(input(&quot;Number of autopresses (integer): &quot;)) except ValueError: print(&quot;\n The number of autopresses should be an integer value, defaulting to 1. \n&quot;) n_clicks = 1 try: delay = float(input(&quot;Delay between each autopress in seconds (integer/float): &quot;)) except ValueError: print(&quot;\n The delay between each autoclick should be an integer or a decimal value, defaulting to 1 (second). \n&quot;) delay = 1 auto_click(key, n_clicks, delay) if __name__ == '__main__': main() </code></pre> <p>What is it that you think should be made better in this code? Any feedback and suggestions would be much appreciated.</p> <p>Here's the github repo:</p> <p><a href="https://github.com/SannanOfficial/AutoKeyPython" rel="nofollow noreferrer">https://github.com/SannanOfficial/AutoKeyPython</a></p>
[]
[ { "body": "<p>Your code is generally fine. I suspect you are not doing enough validation (for\nexample, to forbid negative values or multi-character keys). Also, if you want\nto expand your toolkit, you can think about eliminating the duplication in your\ncode by generalizing the input collection process.</p>\n<p>Collecting user input involves a few common elements: an input prompt, a\nfunction to convert the string to a value, a function to validate that value,\nan error message in the event of bad input, and possibly some other stuff (max\nallowed attempts, fallback/default value in the event of bad input). If we\nfocus on just the basics, we end up with a function along the lines of this\nsketch:</p>\n<pre><code>def get_input(convert, validate, prompt, errmsg):\n while True:\n try:\n x = convert(input(prompt + ': '))\n if validate(x):\n return x\n else:\n print(errmsg)\n except ValueError:\n print(errmsg)\n</code></pre>\n<p>With that in hand, all of the algorithmic detail will reside in that single\nfunction, and your <code>main()</code> will be little more than straightforward,\nstep-by-step orchestration code.</p>\n<pre><code>def main():\n key = get_input(\n str.strip,\n lambda s: len(s) == 1,\n 'Key to be autopressed',\n 'Invalid, must be single character',\n )\n n_clicks = get_input(\n int,\n lambda n: n &gt; 0,\n 'Number of autopresses',\n 'Invalid, must be positive integer',\n )\n delay = get_input(\n float,\n lambda n: n &gt; 0,\n 'Delay between autopresses',\n 'Invalid, must be positive float',\n )\n auto_click(key, n_clicks, delay)\n</code></pre>\n<p>As shown in that sketch, I would also encourage you to favor a more compact\nstyle in messages to users. Brevity usually scales better across a variety of\ncontexts than verbosity: it's easier to maintain; it's easier to make\nconsistent across an entire application; and most people don't appreciate\nhaving to slog through long messages when an equally clear short one\nis possible.</p>\n<p>Finally, you might also consider whether <code>input()</code> is the best\nmechanism to get this information from the user. In my experience,\nit is almost always preferable to take such values from the\ncommand-line, either from <code>sys.argv</code> directly or, more commonly,\nusing a library like <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a>. The advantages\nto this approach are numerous.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T15:00:57.117", "Id": "514258", "Score": "0", "body": "Thank you so much for the answer, mate. All of your suggestions make sense to me and I'll try to implement all of them If I can." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:33:06.157", "Id": "260514", "ParentId": "260505", "Score": "4" } }, { "body": "<p>If <code>n_clicks</code> and <code>delay</code> have default values, you can put them directly in the signature of your <code>auto_click</code> function so that you can call it with the <code>key</code> parameter only. (I would also rename rename <code>n_clicks</code> to <code>clicks</code>, but that's a personal preference really:))</p>\n<pre class=\"lang-py prettyprint-override\"><code>def auto_click(key: str, n_clicks: int = 1, delay: float = 1):\n keyboard = Controller()\n for _ in range(n_clicks):\n keyboard.tap(key)\n sleep(delay)\n</code></pre>\n<p>As @FMc mentionned, we don't usually use <code>input()</code> to take user input, but rather execute the program from the command line. There is an amazing library made by Google called <code>fire</code> (<code>pip install fire</code>) that generates the necessary code for you based on your function's signature:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import fire\nfrom time import sleep\nfrom pynput.keyboard import Controller\n\n\ndef auto_click(key: str, n_clicks: int = 1, delay: float = 1):\n keyboard = Controller()\n for _ in range(n_clicks):\n keyboard.tap(key)\n sleep(delay)\n\n\nif __name__ == &quot;__main__&quot;:\n fire.Fire(auto_click)\n</code></pre>\n<p>Now you can call your script from the command line like so:</p>\n<pre><code>python myscript.py --key A --n_clicks 5 --delay 1\n</code></pre>\n<p>Or, since you have default parameters:</p>\n<pre><code>python myscript.py --key A\n</code></pre>\n<p>Hope this helps :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T03:41:40.650", "Id": "514814", "Score": "0", "body": "Thanks for the answer. I'll try to implement whatever I can that you suggested." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:46:56.233", "Id": "260651", "ParentId": "260505", "Score": "2" } } ]
{ "AcceptedAnswerId": "260514", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T18:32:36.063", "Id": "260505", "Score": "4", "Tags": [ "python", "python-3.x", "automation" ], "Title": "\"Python AutoClicker\" Part 2" }
260505
<p>I recently needed to detect agents within a certain-field of view and came across <a href="https://gamedev.stackexchange.com/questions/118675/need-help-with-a-field-of-view-like-collision-detector">this</a> question in gamedev stack exchange. To learn how it works, I followed the first answer's guidance and decided to make a program that demonstrates how a &quot;a field of view like collision detection&quot; is done. But throughout the process, I struggled a lot with how to structure the program. Here is the code.</p> <pre><code>#define OLC_PGE_APPLICATION #include &quot;olcPixelGameEngine.h&quot; #define PI 3.14159f #define MAX(a, b) a &gt; b ? a : b #define MIN(a, b) a &gt; b ? b : a struct Point { Point() { } Point(olc::vf2d _position, float _directionAngle, float _rotationAngle) : position(_position), directionAngle(_directionAngle), rotationAngle(_rotationAngle) { } olc::vf2d position = { 0.0f, 0.0f }; float directionAngle = 0.0f; float rotationAngle = 0.0f; bool withinSensoryRange = false; olc::Pixel color; }; struct Triangle { Triangle() { } Triangle(olc::vf2d _p1, olc::vf2d _p2, olc::vf2d _p3) : p1(_p1), p2(_p2), p3(_p3) { } olc::vf2d p1 = { 0.0f, -7.0f }; olc::vf2d p2 = { -5.0f, 5.0f }; olc::vf2d p3 = { 5.0f, 5.0f }; Triangle TranslateAndRotate(const float rotationAngle, olc::vf2d offset) { Triangle tri; tri.p1.x = cosf(rotationAngle) * p1.x - sinf(rotationAngle) * p1.y + offset.x; tri.p1.y = sinf(rotationAngle) * p1.x + cosf(rotationAngle) * p1.y + offset.y; tri.p2.x = cosf(rotationAngle) * p2.x - sinf(rotationAngle) * p2.y + offset.x; tri.p2.y = sinf(rotationAngle) * p2.x + cosf(rotationAngle) * p2.y + offset.y; tri.p3.x = cosf(rotationAngle) * p3.x - sinf(rotationAngle) * p3.y + offset.x; tri.p3.y = sinf(rotationAngle) * p3.x + cosf(rotationAngle) * p3.y + offset.y; return tri; } }; class PlayGround : public olc::PixelGameEngine { public: PlayGround() { sAppName = &quot;PlayGround&quot;; } private: bool debug = true; private: Triangle agent1; float rotationAngle1 = 0.0f; float sensoryRadius1 = 50.0f; float fov1 = PI; float agent1Speed = 120.0f; float directionPointDistance1 = 60.0f; olc::vf2d position1 = { 300.0f, 150.0f }; private: olc::Pixel offWhite = olc::Pixel(200, 200, 200); private: float pointsSpeed = 10.0f; int nPoints = 1000; std::vector&lt;std::unique_ptr&lt;Point&gt;&gt; points; private: float GetDistance(float x1, float y1, float x2, float y2) { return sqrtf((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } float DirectionAngle(float rotationAngle) { return rotationAngle - (PI / 2.0f); } private: bool OnUserCreate() override { for (int i = 0; i &lt; nPoints; i++) { //4 random floats between 0 and 1 for initializing x, y and rotation angle and direction angle for point float rx = static_cast &lt;float&gt; (rand()) / static_cast &lt;float&gt; (RAND_MAX); float ry = static_cast &lt;float&gt; (rand()) / static_cast &lt;float&gt; (RAND_MAX); float rra = static_cast &lt;float&gt; (rand()) / static_cast &lt;float&gt; (RAND_MAX); float rda = static_cast &lt;float&gt; (rand()) / static_cast &lt;float&gt; (RAND_MAX); std::unique_ptr&lt;Point&gt; point = std::make_unique&lt;Point&gt;(olc::vf2d(rx * 600, ry * 300), rda * (PI * 2), rra * (PI * 2)); points.push_back(std::move(point)); } return true; } bool OnUserUpdate(float elapsedTime) override { //USER CONTROLS if (GetKey(olc::UP).bHeld) { position1.x += cosf(DirectionAngle(rotationAngle1)) * elapsedTime * agent1Speed; position1.y += sinf(DirectionAngle(rotationAngle1)) * elapsedTime * agent1Speed; } if (GetKey(olc::RIGHT).bHeld) rotationAngle1 += 3.0f * elapsedTime; if (GetKey(olc::LEFT).bHeld) rotationAngle1 -= 3.0f * elapsedTime; if (GetKey(olc::Q).bHeld) fov1 -= 3.0f * elapsedTime; if (GetKey(olc::W).bHeld) fov1 += 3.0f * elapsedTime; if (GetKey(olc::A).bHeld) sensoryRadius1 -= 50.0f * elapsedTime; if (GetKey(olc::S).bHeld) sensoryRadius1 += 50.0f * elapsedTime; if (GetKey(olc::D).bPressed) debug = !debug; fov1 = MAX(MIN(fov1, PI), 0); sensoryRadius1 = MAX(MIN(sensoryRadius1, 200), 0); //TRANSFORMATIONS FOR TRIANGLE Triangle transformedAgent1 = agent1.TranslateAndRotate(rotationAngle1, position1); //points that connects to the triangle to show the directiom vector olc::vf2d direction1; direction1.x = (cosf(DirectionAngle(rotationAngle1)) * directionPointDistance1) + position1.x; direction1.y = (sinf(DirectionAngle(rotationAngle1)) * directionPointDistance1) + position1.y; //these are the two field of view points one at angle + fov and other at angle - fov olc::vf2d fovPoints11; olc::vf2d fovPoints12; //calculating position based on the position of triangle, fov and the sensory range fovPoints11.x = (cosf(DirectionAngle(rotationAngle1 + fov1)) * sensoryRadius1) + position1.x; fovPoints11.y = (sinf(DirectionAngle(rotationAngle1 + fov1)) * sensoryRadius1) + position1.y; fovPoints12.x = (cosf(DirectionAngle(rotationAngle1 - fov1)) * sensoryRadius1) + position1.x; fovPoints12.y = (sinf(DirectionAngle(rotationAngle1 - fov1)) * sensoryRadius1) + position1.y; //COLLISION DETECTION //within the sensory radius for (auto&amp; point : points) { float distance = GetDistance(point-&gt;position.x, point-&gt;position.y, position1.x, position1.y); if (distance &lt; sensoryRadius1) point-&gt;withinSensoryRange = true; else { point-&gt;color = olc::BLACK; point-&gt;withinSensoryRange = false; } } //within the field of view for (auto&amp; point : points) { if (point-&gt;withinSensoryRange) { olc::vf2d normalizedForwardVector = (direction1 - position1).norm(); olc::vf2d normalizedPointCentreVector = (point-&gt;position - position1).norm(); float dot = normalizedPointCentreVector.dot(normalizedForwardVector); if (dot &gt;= cosf(fov1)) debug ? point-&gt;color = olc::RED : point-&gt;color = olc::WHITE; else debug ? point-&gt;color = olc::GREEN : point-&gt;color = olc::BLACK; } } //RENDERING Clear(olc::Pixel(52, 55, 54)); if (debug) { //draw control instructions DrawString(2, 40, &quot;This is a toy program made to demonstrate how collision\ndetection within &quot; &quot;a field of view works. Black flies represent the\npoints that are comletely out &quot; &quot;of range. In debug mode,\nGreen ones represent the ones that are within the sensory\nraidus. The &quot; &quot;ones in the sensory radius are tested to\nsee if they are in the field of view, and &quot; &quot;if they\nare,they appear red.\n\nWhen debug mode is off, white flies\nrepresent the flies that can &quot; &quot;be seen&quot;, offWhite); DrawString(2, 10, &quot;Press up, right and left keys for movement.\n&quot; &quot;Press w to increase FOV and q to reduce it.\n&quot; &quot;Press s to increase sensory range and a to decrease it.&quot;, offWhite); } DrawString(2, 290, &quot;Press d to toggle text and geometric debug data.&quot;, olc::Pixel(200, 250, 200)); //display info std::ostringstream fovValue; fovValue &lt;&lt; &quot;FOV: &quot; &lt;&lt; round(fov1 * 2.0f * (180 / PI)) &lt;&lt; &quot; degrees&quot;; DrawString(440, 280, fovValue.str(), offWhite); std::ostringstream sensoryRangeValue; sensoryRangeValue &lt;&lt; &quot;Sensory Range: &quot; &lt;&lt; round(sensoryRadius1); DrawString(440, 265, sensoryRangeValue.str(), offWhite); //transform (wobble while moving forward) and draw all the points for (auto&amp; point : points) { point-&gt;rotationAngle += 0.05f; point-&gt;directionAngle -= 0.05f; point-&gt;position.x += cosf(point-&gt;directionAngle) * sinf(point-&gt;rotationAngle) * elapsedTime * pointsSpeed; point-&gt;position.y += sinf(point-&gt;directionAngle) * sinf(point-&gt;rotationAngle) * elapsedTime * pointsSpeed; if (point-&gt;rotationAngle &gt; PI * 2) point-&gt;rotationAngle = 0; if (point-&gt;rotationAngle &lt; 0) point-&gt;rotationAngle = PI * 2; if (point-&gt;directionAngle &gt; PI * 2) point-&gt;directionAngle = 0; if (point-&gt;directionAngle &lt; 0) point-&gt;directionAngle = PI * 2; if (point-&gt;position.x &gt; 600) point-&gt;position.x = 0; if (point-&gt;position.x &lt; 0) point-&gt;position.x = 600; if (point-&gt;position.y &gt; 300) point-&gt;position.y = 0; if (point-&gt;position.y &lt; 0) point-&gt;position.y = 300; Draw((int)point-&gt;position.x, (int)point-&gt;position.y, point-&gt;color); } if (debug) { //lines from centre of triangle to fov points DrawLine((int)position1.x, (int)position1.y, (int)fovPoints11.x, (int)fovPoints11.y, olc::RED); DrawLine((int)position1.x, (int)position1.y, (int)fovPoints12.x, (int)fovPoints12.y, olc::RED); //field of view points FillCircle((int)fovPoints11.x, (int)fovPoints11.y, 2, olc::RED); FillCircle((int)fovPoints12.x, (int)fovPoints12.y, 2, olc::RED); //color the points between the two fov points in red float tempAngle = DirectionAngle(rotationAngle1 + fov1); while (tempAngle &gt; DirectionAngle(rotationAngle1 - fov1)) { for (int i = 0; i &lt; 3; i++) Draw((int)(cosf(tempAngle) * (sensoryRadius1 + i)) + position1.x, (int)(sinf(tempAngle) * (sensoryRadius1 + i)) + position1.y, olc::RED); tempAngle -= 0.01f; } //draw sensory radius DrawCircle((int)position1.x, (int)position1.y, sensoryRadius1, olc::GREEN); //the straingt line signifying direction DrawLine((int)position1.x, (int)position1.y, (int)direction1.x, (int)direction1.y, offWhite); } //Draw the main triangle body FillTriangle( (int)transformedAgent1.p1.x, (int)transformedAgent1.p1.y, (int)transformedAgent1.p2.x, (int)transformedAgent1.p2.y, (int)transformedAgent1.p3.x, (int)transformedAgent1.p3.y, offWhite); return true; } }; int main() { PlayGround playGround; if (playGround.Construct(600, 300, 2, 2)) playGround.Start(); } </code></pre> <p>I am sure its bad and tons of optimizations can be made, but for this particular question, I want to focus on how I could have structured it better. Thank you.</p> <p>It is made using pixel game engine, so if you wish to test it out, it needs <a href="https://github.com/OneLoneCoder/olcPixelGameEngine" rel="nofollow noreferrer">this</a>. Its a single file library, so easy to set up.</p>
[]
[ { "body": "<h1>Avoid using macros</h1>\n<p>Try to avoid macros where possible; usually a better solution is available. For constants, prefer using <code>constexpr</code>:</p>\n<pre><code>static constexpr float PI = 3.14159...f;\n</code></pre>\n<p>Instead of <code>MIN</code> and <code>MAX</code>, just use <a href=\"https://en.cppreference.com/w/cpp/algorithm/min\" rel=\"nofollow noreferrer\"><code>std::min()</code></a> and <a href=\"https://en.cppreference.com/w/cpp/algorithm/max\" rel=\"nofollow noreferrer\"><code>std::max()</code></a>. Or if you can use C++17, use <a href=\"https://en.cppreference.com/w/cpp/algorithm/clamp\" rel=\"nofollow noreferrer\"><code>std::clamp()</code></a>.</p>\n<h1>Constructors and member initialization</h1>\n<p>If you need to explicitly add a default constructor, prefer doing that using <a href=\"https://stackoverflow.com/questions/20828907/the-new-syntax-default-in-c11\"><code>= default</code></a>.</p>\n<p>When initializing members to zero, you can do that very concisely using <a href=\"https://en.cppreference.com/w/cpp/language/value_initialization\" rel=\"nofollow noreferrer\">value initialization</a>, which looks like this:</p>\n<pre><code>olc::vf2d position{};\n</code></pre>\n<h1>Separate translation and rotation</h1>\n<p>Instead of having a <code>TranslateAndRotate()</code> function, consider splitting that up into a separate <code>Translate()</code> and <code>Rotate()</code>. This is more flexible, and it also removes an ambiguity: does your function translate first and then rotate, or the other way around? You can also greatly simplify these functions, especially when using a little helper to rotate single <code>Point</code>s:</p>\n<pre><code>Triangle Translate(olc::vf2d offset)\n{\n return {p1 + offset, p2 + offset, p3 + offset};\n}\n\nTriangle Rotate(float angle)\n{\n static const auto rotate = [](olc::vf2d p, float angle) -&gt; olc::vf2d {\n return {\n p.x * std::cos(angle) - p.y * std::sin(angle),\n p.x * std::sin(angle) + p.y * std::cos(angle)\n };\n };\n\n return {rotate(p1, angle), rotate(p2, angle), rotate(p3, angle)};\n}\n</code></pre>\n<p>I used a lambda here, but you could also write that as a regular function. You can now use this as follows:</p>\n<pre><code>Triangle transformedAgent1 = agent1.Rotate(rotationAngle1).Translate(position1);\n</code></pre>\n<h1>Avoid using smart pointers unnecessarily</h1>\n<p>There is no reason to use <code>std::unique_ptr</code> to store <code>Point</code>s in a vector. Instead just write:</p>\n<pre><code>std::vector&lt;Point&gt; points;\n</code></pre>\n<p>When adding points to this class, you can write:</p>\n<pre><code>for (int i = 0; i &lt; nPoints; i++)\n{\n float rx = ...;\n float ry = ...;\n float rra = ...;\n float rrd = ...;\n points.emplace_back(olc::vf2d{rx * 600, ry * 600}, rda * PI * 2, rra * PI * 2);\n}\n</code></pre>\n<h1>Use proper random number generators</h1>\n<p>Since C++11 there are proper <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">random number generator functions</a>, there is no need to use the rather ugly <code>rand()</code>.</p>\n<h1>Use <code>std::</code></h1>\n<p>Teach yourself to use <code>std::</code> consistently when using functions from the standard library, and <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">avoid relying on <code>using namespace std</code></a>. Also note that using math functions from <code>std::</code> has the benefit of automatically using the right overload. For example, instead of <code>sinf(...)</code>, write <a href=\"https://en.cppreference.com/w/cpp/numeric/math/sin\" rel=\"nofollow noreferrer\"><code>std::sin(...)</code></a>, if the argument is a <code>float</code> it will pick the overload for <code>float</code>s. That's one less thing to worry about.</p>\n<h1>Be consistent using <code>olc::vf2d</code></h1>\n<p>If you have a proper type for 2D vectors, you rarely have to pass coordinates in separate <code>float</code>s anymore. For example, <code>GetDistance</code> can be rewritten to:</p>\n<pre><code>float GetDistance(olc::vf2d p1, olc::vf2d p2)\n{\n return std::hypot(p2.x - p1.x, p2.y - p1.y);\n}\n</code></pre>\n<p>And use it like so in <code>OnUserUpdate()</code>:</p>\n<pre><code>float distance = GetDistance(point.position, position1);\n</code></pre>\n<h1>Avoid repetition</h1>\n<p>Avoid repeating yourself where possible, even if it's small things, like the ternaries in <code>OnUserUpdate()</code>:</p>\n<pre><code>if (dot &gt;= cosf(fov1))\n debug ? point.color = olc::RED : point.color = olc::WHITE;\n</code></pre>\n<p>This can be rewritten to:</p>\n<pre><code>if (dot &gt;= std::cos(fov1))\n point.color = debug ? olc::RED : olc::WHITE;\n</code></pre>\n<h1>Split the code into more functions</h1>\n<p>The function <code>OnUserUpdate()</code> is quite long. Consider splitting it up into multiple functions, so that <code>OnUserUpdate()</code> just gives you a high-level overview of what it is doing:</p>\n<pre><code>bool OnUserUpdate(float elapsedTime) override\n{\n HandleInput(elapsedTime);\n UpdateState(elapsedTime);\n DrawScreen();\n\n return true;\n}\n</code></pre>\n<p>Each of these functions could be split into multiple parts as well if necessary, for example updating the state could look like:</p>\n<pre><code>void UpdateState(float elapsedTime)\n{\n CollisionDetection();\n WobblePoints(elapsedTime);\n}\n</code></pre>\n<p>And drawing could look like:</p>\n<pre><code>void DrawScreen()\n{\n Clear({52, 55, 54});\n\n if (debug)\n DrawDebugInformation();\n\n DrawInformation();\n DrawPoints();\n DrawBody();\n}\n</code></pre>\n<h1>Wrapping values</h1>\n<p>If you wnat to clamp a variable between a low and high value, you can use the <code>std::max</code>+<code>std::min()</code> trick, or C++17's <code>std::clamp()</code>. However, you also have a few variables that you want to let wrap. You are doing this four times, so already you should have created a function to do this that will reduce code duplication.</p>\n<p>Your code also checks if a value is larger than, say, <code>PI * 2</code>, and if so you reset it to zero. However, suppose the value was actually <code>PI * 2 + 0.1</code>, then ideally after wrapping the result should be <code>0.1</code>, not <code>0</code>. You could change your code to subtract <code>PI * 2</code> until it is in range, but we can avoid <code>if</code> and <code>while</code> statement altogether by making use of <a href=\"https://en.cppreference.com/w/cpp/numeric/math/floor\" rel=\"nofollow noreferrer\"><code>std::floor</code></a>, like so:</p>\n<pre><code>float wrap(float value, float max)\n{\n value /= max;\n value -= std::floor(value); // value is now in the range [0, 1)\n value *= max;\n return value;\n}\n</code></pre>\n<p>And with this you can write:</p>\n<pre><code>point.rotationAngle = wrap(point.rotationAngle, PI * 2);\npoint.directionAngle = wrap(point.directionAngle, PI * 2);\npoint.position.x = wrap(point.position.x, 600);\npoint.position.y = wrap(point.position.y, 300);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T11:40:40.963", "Id": "514245", "Score": "0", "body": "Hello, Thanks for the answer. You see the for loop below the comment `//transform (wobble while moving forward) and draw all the points`. I am doing all the transformations and drawings in the same loop. I was struggling with how to separate those two out. What would be your advice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T14:59:41.387", "Id": "514257", "Score": "1", "body": "I would indeed separate the code. Make one function that updates the state, and another one that draw everything. I've updated the answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T10:56:34.093", "Id": "260526", "ParentId": "260510", "Score": "1" } } ]
{ "AcceptedAnswerId": "260526", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T20:09:15.557", "Id": "260510", "Score": "1", "Tags": [ "c++" ], "Title": "Structuring the program that demonstrates collision detection within a field of view" }
260510
<p>I'm working on an implementation of <strong>Monte Carlo Tree Search</strong> in <strong>Swift</strong>.</p> <p>It's not bad, but it could be better! I'm principally interested in making my algorithm:</p> <ol> <li>faster (more iterations/second)</li> <li>prioritize moves that prevent instant losses (you'll see...)</li> </ol> <p>Here is the <strong>main driver</strong>:</p> <pre class="lang-swift prettyprint-override"><code>final class MonteCarloTreeSearch { var player: Player var timeBudget: Double var maxDepth: Int var explorationConstant: Double var root: Node? var iterations: Int init(for player: Player, timeBudget: Double = 5, maxDepth: Int = 5, explorationConstant: Double = sqrt(2)) { self.player = player self.timeBudget = timeBudget self.maxDepth = maxDepth self.explorationConstant = explorationConstant self.iterations = 0 } func update(with game: Game) { if let newRoot = findNode(for: game) { newRoot.parent = nil newRoot.move = nil root = newRoot } else { root = Node(game: game) } } func findMove(for game: Game? = nil) -&gt; Move? { iterations = 0 let start = CFAbsoluteTimeGetCurrent() if let game = game { update(with: game) } while CFAbsoluteTimeGetCurrent() - start &lt; timeBudget { refine() iterations += 1 } print(&quot;Iterations: \(iterations)&quot;) return bestMove } private func refine() { let leafNode = root!.select(explorationConstant) let value = rollout(leafNode) leafNode.backpropogate(value) } private func rollout(_ node: Node) -&gt; Double { var depth = 0 var game = node.game while !game.isFinished { if depth &gt;= maxDepth { break } guard let move = game.randomMove() else { break } game = game.update(move) depth += 1 } let value = game.evaluate(for: player).value return value } private var bestMove: Move? { root?.selectChildWithMaxUcb(0)?.move } private func findNode(for game: Game) -&gt; Node? { guard let root = root else { return nil } var queue = [root] while !queue.isEmpty { let head = queue.removeFirst() if head.game == game { return head } for child in head.children { queue.append(child) } } return nil } } </code></pre> <p>I built this driver with a <code>maxDepth</code> argument because playouts/rollouts in my <em>real</em> game are fairly long and I have a access to a decent static evaluation function. Also, the BFS <code>findNode</code> method is so that I can reuse parts of the tree.</p> <p>Here's what a <strong>node</strong> in the driver looks like:</p> <pre class="lang-swift prettyprint-override"><code>final class Node { weak var parent: Node? var move: Move? var game: Game var untriedMoves: [Move] var children: [Node] var cumulativeValueFor: Double var cumulativeValueAgainst: Double var visits: Double init(parent: Node? = nil, move: Move? = nil, game: Game) { self.parent = parent self.move = move self.game = game self.children = [] self.untriedMoves = game.availableMoves() self.cumulativeValueFor = 0 self.cumulativeValueAgainst = 0 self.visits = 0 } var isFullyExpanded: Bool { untriedMoves.isEmpty } lazy var isTerminal: Bool = { game.isFinished }() func select(_ c: Double) -&gt; Node { var leafNode = self while !leafNode.isTerminal { if !leafNode.isFullyExpanded { return leafNode.expand() } else { leafNode = leafNode.selectChildWithMaxUcb(c)! } } return leafNode } func expand() -&gt; Node { let move = untriedMoves.popLast()! let nextGame = game.update(move) let childNode = Node(parent: self, move: move, game: nextGame) children.append(childNode) return childNode } func backpropogate(_ value: Double) { visits += 1 cumulativeValueFor += value if let parent = parent { parent.backpropogate(value) } } func selectChildWithMaxUcb(_ c: Double) -&gt; Node? { children.max { $0.ucb(c) &lt; $1.ucb(c) } } func ucb(_ c: Double) -&gt; Double { q + c * u } private var q: Double { let value = cumulativeValueFor - cumulativeValueAgainst return value / visits } private var u: Double { sqrt(log(parent!.visits) / visits) } } extension Node: CustomStringConvertible { var description: String { guard let move = move else { return &quot;&quot; } return &quot;\(move) (\(cumulativeValueFor)/\(visits))&quot; } } </code></pre> <p>I don't think there's anything extraordinary about my node object? (I am hoping, though, that I can do something to/about <code>q</code> so that I might prevent an &quot;instant&quot; loss in my <em>test</em> game...</p> <hr /> <p>I've been testing this implementation of MCTS on a 1-D variant of &quot;Connect 4&quot;.</p> <p>Here's the game and all of it's primitives:</p> <pre class="lang-swift prettyprint-override"><code>enum Player: Int { case one = 1 case two = 2 var opposite: Self { switch self { case .one: return .two case .two: return .one } } } extension Player: CustomStringConvertible { var description: String { &quot;\(rawValue)&quot; } } typealias Move = Int enum Evaluation { case win case loss case draw case ongoing(Double) var value: Double { switch self { case .win: return 1 case .loss: return 0 case .draw: return 0.5 case .ongoing(let v): return v } } } struct Game { var array: Array&lt;Int&gt; var currentPlayer: Player init(length: Int = 10, currentPlayer: Player = .one) { self.array = Array.init(repeating: 0, count: length) self.currentPlayer = currentPlayer } var isFinished: Bool { switch evaluate() { case .ongoing: return false default: return true } } func availableMoves() -&gt; [Move] { array .enumerated() .compactMap { $0.element == 0 ? Move($0.offset) : nil} } func update(_ move: Move) -&gt; Self { var copy = self copy.array[move] = currentPlayer.rawValue copy.currentPlayer = currentPlayer.opposite return copy } func evaluate(for player: Player) -&gt; Evaluation { let player3 = three(for: player) let oppo3 = three(for: player.opposite) let remaining0 = array.contains(0) switch (player3, oppo3, remaining0) { case (true, true, _): return .draw case (true, false, _): return .win case (false, true, _): return .loss case (false, false, false): return .draw default: return .ongoing(0.5) } } private func three(for player: Player) -&gt; Bool { var count = 0 for slot in array { if slot == player.rawValue { count += 1 } else { count = 0 } if count == 3 { return true } } return false } } extension Game { func evaluate() -&gt; Evaluation { evaluate(for: currentPlayer) } func randomMove() -&gt; Move? { availableMoves().randomElement() } } extension Game: CustomStringConvertible { var description: String { return array.reduce(into: &quot;&quot;) { result, i in result += String(i) } } } extension Game: Equatable {} </code></pre> <p>While there are definitely efficiencies to be gained in optimizing the <code>evaluate</code>/<code>three(for:)</code> scoring methods, I'm more concerned about improving the performance of the driver and the node as this &quot;1d-connect-3&quot; game isn't my <em>real</em> game. That said, if there's a huge mistake here and a simple fix I'll take it!</p> <p>Another note: I am actually using <code>ongoing(Double)</code> in my <em>real</em> game (I've got a static evaluation function that can reliably score a player as 1-99% likely to win).</p> <hr /> <p>A bit of Playground code:</p> <pre class="lang-swift prettyprint-override"><code>var mcts = MonteCarloTreeSearch(for: .two, timeBudget: 5, maxDepth: 3) var game = Game(length: 10) // 0000000000 game = game.update(0) // player 1 // 1000000000 game = game.update(8) // player 2 // 1000000020 game = game.update(1) // player 1 // 1100000020 let move1 = mcts.findMove(for: game)! // usually 7 or 9... and not 2 print(mcts.root!.children) game = game.update(move1) // player 2 mcts.update(with: game) game = game.update(4) // player 1 mcts.update(with: game) let move2 = mcts.findMove()! </code></pre> <p>Unfortunately, <code>move1</code> in this sample &quot;playthru&quot; doesn't try and prevent the instant win-condition on the next turn for player 1?! (I know that orthodox Monte Carlo Tree Search is in the business of maximizing winning not minimizing losing, but not picking <code>2</code> here is unfortunate).</p> <p>So yeah, any help in making all this faster (perhaps through parallelization), and fixing the &quot;instant-loss&quot; business would be swell!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T09:14:45.813", "Id": "514392", "Score": "0", "body": "Performance tests must be done in a compiled project, not in a Playground." } ]
[ { "body": "<p>I've been mulling this over and have some preliminary answers! (But would still appreciate some help!!)</p>\n<hr />\n<p><a href=\"https://hal.inria.fr/file/index/docid/495078/filename/cig2010.pdf\" rel=\"nofollow noreferrer\">F. Teytaud and O. Teytaud (2010)</a> inspired a solution to the &quot;loss prevention&quot; problem. The paper recommends selecting the decisive or anti-decisive (win for opponent) move if it exists, else <code>select</code> as normal:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>// final class Node {\n// ...\n func select(_ c: Double) -&gt; Node {\n var leafNode = self\n if let decisiveNode = selectDecisiveChild() {\n return decisiveNode\n }\n while !leafNode.isTerminal {\n if !leafNode.isFullyExpanded {\n return leafNode.expand()\n } else {\n leafNode = leafNode.selectChildWithMaxUcb(c)!\n }\n }\n return leafNode\n }\n\n private func selectDecisiveChild() -&gt; Node? {\n children.filter { $0.game.isFinished }.randomElement()\n }\n// ...\n// }\n</code></pre>\n<hr />\n<p>To squeeze out more iterations per second, I've implemented &quot;leaf parallelization&quot; as defined in <a href=\"https://dke.maastrichtuniversity.nl/m.winands/documents/multithreadedMCTS2.pdf\" rel=\"nofollow noreferrer\">G. M. J.-B. Chaslot, M. H. M. Winands, and H. J. van den Herik (2008)</a>. While other methods of parallelization look more promising, this method seemed easiest:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>// final class MonteCarloTreeSearch {\n// ...\n\n private let activeProcessors = ProcessInfo.processInfo.activeProcessorCount\n private let dispatchGroup = DispatchGroup()\n\n// ...\n\n private func refine() {\n let leafNode = root!.select(explorationConstant)\n var values = Array&lt;Double&gt;(repeating: 0, count: activeProcessors)\n var mutex = os_unfair_lock()\n for i in 0..&lt;activeProcessors {\n DispatchQueue.global(qos: .userInitiated).async(group: dispatchGroup) {\n let value = self.rollout(leafNode)\n os_unfair_lock_lock(&amp;mutex)\n values[i] = value\n self.iterations += 1\n os_unfair_lock_unlock(&amp;mutex)\n }\n }\n _ = dispatchGroup.wait(timeout: .distantFuture)\n for value in values {\n leafNode.backpropagate(value)\n }\n }\n\n// ...\n// }\n</code></pre>\n<p>I'm still a novice of <code>DispatchQueue</code>. So if I'm using the locks incorrectly, I'd love to know... but it seems to work!</p>\n<hr />\n<p>Looking forward to reviewing other answers~</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:40:51.560", "Id": "260565", "ParentId": "260512", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T20:19:59.000", "Id": "260512", "Score": "2", "Tags": [ "performance", "tree", "swift" ], "Title": "Monte Carlo Tree Search Optimization and Loss Prevention" }
260512
<p>I've been learning React for about a month now. I wrote a small <a href="https://calc-solver.com/twin-paradox-under-special-relativity-calculator" rel="nofollow noreferrer">interactive calculator</a> to show the effects of time dilation under special relativity. It's Node/React/Razzle(for SSR)/Typescript/Javascript.</p> <p>Here are the issues I have run into and would like help with:</p> <ol> <li><p>I feel like I'm abusing state. You change one parameter and it cascades through other dependent values which then trigger a recalculation; but because state updates are asynchronous, I have to set awkward artificial callbacks to force a timely update.</p> </li> <li><p>Bootstrap prepend and append on input forms take up a lot of space and cause certain calculators to render poorly on mobile... Should I consider using Material UI, or can I &quot;prettify&quot; and resize the input fields appropriately with custom CSS / bootstrap?</p> </li> <li><p>Scalability - Currently there are only ~13 components but intend to make a lot more pages and calculators, and I'm wondering if there's any room for refactoring to take advantage of recurring patterns: it feels like I could be writing a lot less code. Also, routes - the file containing routes could get huge - will that become a problem in the future?</p> </li> </ol> <pre><code>import React, { useEffect, Component } from &quot;react&quot;; import { ThreeColumnContainer } from &quot;../Layout/ThreeColumnContainer&quot;; import { TextControl } from &quot;../controls/Input&quot;; import { Helmet } from &quot;react-helmet&quot;; const c = 299792.458; //km/s export class TwinParadoxUnderSpecialRelativity extends Component&lt;{}, { [key: string]: number }&gt; { constructor(props) { super(props); this.state = { velocityAsPercentageOfC: 0, lorentzFactor: 1, velocityInKph: 0, velocityInMph: 0, contractedElapsedTime: 1, dilatedElapsedTime: 1 }; this.calculateLorentzFactor = this.calculateLorentzFactor.bind(this); this.updateVelocity = this.updateVelocity.bind(this); this.updateLorentzFactor = this.updateLorentzFactor.bind(this); this.calculateVelocityAsPercentageOfC = this.calculateVelocityAsPercentageOfC.bind(this); this.calculateTimeDilation = this.calculateTimeDilation.bind(this); this.updateElapsedTime = this.updateElapsedTime.bind(this); this.updateTravelerElapsedTime = this.updateTravelerElapsedTime.bind(this); this.calculateTimeContraction = this.calculateTimeContraction.bind(this); } updateVelocity(e) { var velocityAsPctOfC = e.target.value; var lorentzF = this.calculateLorentzFactor(velocityAsPctOfC); var kph = this.convertToKmh(velocityAsPctOfC); var mph = this.convertToMph(kph) //var dilatedTime = this.setState({ velocityAsPercentageOfC: velocityAsPctOfC, lorentzFactor: lorentzF, velocityInKph: kph, velocityInMph: mph}, () =&gt; this.setState({dilatedElapsedTime: this.calculateTimeDilation(this.state.contractedElapsedTime, lorentzF)})); } updateLorentzFactor(e) { var lorentzF = e.target.value; var velocityAsPctOfC = this.calculateVelocityAsPercentageOfC(lorentzF); var kph = this.convertToKmh(velocityAsPctOfC); var mph = this.convertToMph(kph) //var dilatedTime = this.calculateTimeDilation(this.state.elapsedTime); this.setState({ velocityAsPercentageOfC: velocityAsPctOfC, lorentzFactor: lorentzF, velocityInKph: kph, velocityInMph: mph}, () =&gt; this.setState({dilatedElapsedTime: this.calculateTimeDilation(this.state.contractedElapsedTime, lorentzF)})); } updateTravelerElapsedTime(e) { var elapsed = e.target.value; this.setState({contractedElapsedTime: elapsed}, () =&gt; this.setState({dilatedElapsedTime: this.calculateTimeDilation(this.state.contractedElapsedTime, this.state.lorentzFactor)})); } updateElapsedTime(e) { var dilatedTime = e.target.value; this.setState({ dilatedElapsedTime: dilatedTime }, () =&gt; this.setState({contractedElapsedTime: this.calculateTimeContraction(this.state.dilatedElapsedTime, this.state.lorentzFactor)})); } calculateLorentzFactor(velocityAsPercentageOfC: number) { return 1 / Math.sqrt( 1 - ( Math.pow( velocityAsPercentageOfC / 100, 2) ) ); } calculateVelocityAsPercentageOfC(lorentzFactor: number) { return Math.sqrt(-1 * (Math.pow(1/lorentzFactor, 2) -1)) * 100; } convertToKmh(velocityAsPercentageOfC: number){ return velocityAsPercentageOfC * c; } convertToMph(kilometersPerHour: number) { return kilometersPerHour * 0.621371; } calculateTimeContraction(contractedElapsedTime: number, lorentzFactor: number) { return contractedElapsedTime / lorentzFactor; } calculateTimeDilation(dilatedElapsedTime: number, lorentzFactor: number) { return dilatedElapsedTime * lorentzFactor; } roundNumber = (num: number, dec: number) =&gt; { return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); } renderLeft() { return ( &lt;div&gt; &lt;h1&gt;Twin Paradox (Time Dilation under SR) Calculator&lt;/h1&gt; &lt;p/&gt; &lt;TextControl prepend=&quot;Relative velocity as % of c&quot; type=&quot;number&quot; value={this.state.velocityAsPercentageOfC} append=&quot;v&quot; onChange={this.updateVelocity} /&gt; &lt;TextControl prepend=&quot;Lorentz Factor&quot; type=&quot;number&quot; value={this.state.lorentzFactor} append=&quot;gamma&quot; onChange={this.updateLorentzFactor} /&gt; &lt;TextControl prepend=&quot;Velocity in kph&quot; type=&quot;number&quot; value={this.state.velocityInKph} append=&quot;kph&quot; readonly=&quot;true&quot; /&gt; &lt;TextControl prepend=&quot;Velocity in mph&quot; type=&quot;number&quot; value={this.state.velocityInMph} append=&quot;mph&quot; readonly=&quot;true&quot; /&gt; &lt;TextControl prepend=&quot;Earth Observer Elapsed Time&quot; type=&quot;number&quot; value={this.state.dilatedElapsedTime} append=&quot;Tb&quot; onChange={this.updateElapsedTime} /&gt; &lt;TextControl prepend=&quot;Spaceship Traveler Elapsed Time&quot; type=&quot;number&quot; value={this.state.contractedElapsedTime} append=&quot;Ta&quot; onChange={this.updateTravelerElapsedTime}/&gt; &lt;p&gt;&lt;/p&gt; &lt;h4&gt;Explanation&lt;/h4&gt; &lt;p&gt;At {this.roundNumber(this.state.velocityAsPercentageOfC,0)}% of the speed of light (c), the lorentz factor or gamma is {this.roundNumber(this.state.lorentzFactor,4)}. That means a twin traveling through space will age at {this.roundNumber(1 / this.state.lorentzFactor * 100,4)}% the rate of its twin at relative rest on earth. If {this.roundNumber(this.state.dilatedElapsedTime,4)} units of time have passed on earth, {this.roundNumber(this.state.contractedElapsedTime,2)} units of time will pass for the space twin. For this to be realistic, the space twin needs to travel at {this.roundNumber(this.state.velocityInMph/1000,0)}K miles per hour ({this.roundNumber(this.state.velocityInKph/1000,0)}K kilometers per hour).&lt;/p&gt; &lt;p&gt;Interestingly, the spaceship - and everything in it - will also contract in length to {this.roundNumber(1 / this.state.lorentzFactor * 100,2)}% of its original length.&lt;/p&gt; &lt;/div &gt; ); } renderMiddle() { return ( &lt;div&gt; &lt;Helmet&gt; &lt;title&gt;Time Dilation Calculator (Twin Paradox)&lt;/title&gt; &lt;meta name='description' content='Calculate the Lorenz factor based on given velocity or percentage of the speed of light to measure time dilation in special relativity.' /&gt; &lt;/Helmet&gt; &lt;h3&gt;Calculate Time Dilation (SR)&lt;/h3&gt; &lt;p&gt;Time Dilation is the time difference between two clocks or observers moving relative to each other. Time Dilation has practical consequences at very fast relative speeds, in particular for GPS and other satelites. The formula to calculate time dilation is Sqrt(1 - v^2 / c^2) where v is relative velocity and c is the speed of light. The result is called the Lorenz factor.&lt;/p&gt; &lt;p&gt;Time Dilation means that someone traveling at very high speeds will &quot;experience&quot; time at a slower rate than someone in a frame at rest. So at speeds approaching the speed of light a traveler will age more slowly than someone observing from earth. The closer the traveler gets to the speed of light, the more dramatic the effect, so the traveler could experience and age only a year while everyone on earth ages and experiences eight years.&lt;/p&gt; &lt;/div&gt; ); } render() { return ( &lt;div&gt; &lt;ThreeColumnContainer left={this.renderLeft()} middle={this.renderMiddle()}&gt;&lt;/ThreeColumnContainer&gt; &lt;/div &gt; ); } } </code></pre> <pre><code>//ThreeColumnContainer.js import React from 'react'; const designsThatWillAwe = require(&quot;../../images/WebsiteDesignsThatWillAwe.png&quot;); export function ThreeColumnContainer(props) { return ( &lt;div className=&quot;row&quot;&gt; &lt;div className=&quot;col-6&quot; id=&quot;left&quot;&gt; {props.left} &lt;/div&gt; &lt;div className=&quot;col-sm&quot; id=&quot;middle&quot;&gt; {props.middle} &lt;/div&gt; &lt;div className=&quot;col-sm&quot; id=&quot;right&quot;&gt; &lt;img src={designsThatWillAwe} alt=&quot;Fractal Flame Swirls - Designs That Will Awe&quot;/&gt; &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <pre><code>//TextControl.js import React from 'react'; function inputControl(props) { if (props &amp;&amp; props.onChange) { return (&lt;input className=&quot;form-control&quot; type={props.type} value={props.value} onChange={props.onChange} readonly={props.readonly}/&gt;); } else{ return (&lt;input className=&quot;form-control&quot; type={props.type} value={props.value} onChange={()=&gt;{}} readonly={props.readonly}/&gt;); } } export function TextControl(props) { return ( &lt;div className=&quot;input-group&quot;&gt; {props.prepend &amp;&amp; &lt;div className=&quot;input-group-prepend&quot;&gt; &lt;span className=&quot;input-group-text&quot;&gt;{props.prepend}&lt;/span&gt; &lt;/div&gt; } {inputControl(props)} {props.append &amp;&amp; &lt;div className=&quot;input-group-append&quot;&gt; &lt;span className=&quot;input-group-text&quot;&gt;{props.append}&lt;/span&gt; &lt;/div&gt; } &lt;/div&gt; ); } </code></pre>
[]
[ { "body": "<p>Let me say first that I haven't actually tried the code or proposed changes, mostly because I don't have the imported files <code>ThreeColumnContainer</code> and <code>TextControl</code>.</p>\n<p>I begin with what I think is the main challenge.</p>\n<hr />\n<p>There are some interdependent values, and whenever one of them is changed by the user, all others should be updated instantaneously. This doesn't seem to be as straightforward as one may think in clean TypeScript/React.</p>\n<ul>\n<li><p>Currently, the code is storing and processing <em>strings</em> of the input values, because <code>e.target.value</code> is a string. This implicitly relies on JavaScript's auto-conversion between strings and numbers, and is hidden by the fact that the <code>e</code> parameters implicitly have type <code>any</code>. If you give <code>e</code> an appropriate type (I guess <code>e: React.ChangeEvent&lt;HTMLInputElement&gt;</code>), then <code>tsc</code> will probably start complaining about <code>string</code>/<code>number</code> type mismatches.</p>\n</li>\n<li><p>As an alternative, one might actually store and process <em>numbers</em>, either by using <code>e.target.valueAsNumber</code> (which should work because the inputs have <code>type=&quot;number&quot;</code>), or by explicitly parsing with <code>parseFloat(e.target.value)</code>. That, however, may lead to strange behavior of the input fields. For example, we would probably not be able to append a decimal point at the end, because <code>&quot;123.&quot;</code> would immediately be converted to and rendered as <code>123</code>.</p>\n</li>\n</ul>\n<p>I see a couple of options to deal with this:</p>\n<ol>\n<li><p>Continue to store strings; adopt the component's state type (e.g. <code>{ [key: string]: string | number }</code>) and add <code>parseFloat</code>s where necessary.</p>\n</li>\n<li><p>Store numbers, and <em>additionally</em> store the actual string value of the last-edited input field. On rendering, use the numeric value by default, or have that overridden by the stored string for one input field.</p>\n</li>\n<li><p>Write an input component that doesn't cascade the values instantaneously, but only after the user &quot;submits&quot; the value (e.g., by pressing <kbd>Return</kbd>).</p>\n</li>\n<li><p>Write an input component that <em>does</em> cascade the values instantaneously, but keeps an internal state of its value, which is updated from props only when not focused.</p>\n</li>\n</ol>\n<p>In a word: Set <code>noImplicitAny</code> to <code>true</code> in your <code>tsconfig.json</code>, and play around with these options to fix the new errors.</p>\n<hr />\n<p>Some more fine-grained suggestions:</p>\n<ul>\n<li><p>Use <code>let</code> or <code>const</code> instead of <code>var</code>.</p>\n</li>\n<li><p>Be more specific about the type of your component's state. For example:</p>\n<pre><code>type State = {\n velocityAsPercentageOfC: number;\n lorentzFactor: number;\n velocityInKph: number;\n velocityInMph: number;\n contractedElapsedTime: number;\n dilatedElapsedTime: number;\n};\n\n// Or, saving on space:\ntype State = {\n [X in &quot;velocityAsPercentageOfC&quot; | &quot;lorentzFactor&quot; | /* etc. */]: number;\n};\n\nexport class TwinParadoxUnderSpecialRelativity extends Component&lt;{}, State&gt; {\n // ...\n}\n</code></pre>\n</li>\n<li><p>Keep state minimal, and keep values in state orthogonal to each other. So instead of storing <code>4+2</code> interdependent values, try to store only <code>1+1</code> values and calculate all other values in the render methods. That shouldn't be a problem performance-wise here as the computations aren't too expensive. If they were, we could use memoization.</p>\n</li>\n<li><p>On your first question: React allows to give a callback to <code>setState</code>, the first parameter of which will be previous state. This lets us update state based on the current state without worrying about timing.</p>\n<pre><code>updateVelocity = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {\n // ...\n\n this.setState(prevState =&gt; ({\n velocityAsPercentageOfC: velocityAsPctOfC,\n lorentzFactor: lorentzF,\n velocityInKph: kph,\n velocityInMph: mph,\n // NOTE: Here contractedElapsedTime of previous state is used\n dilatedElapsedTime: this.calculateTimeDilation(prevState.contractedElapsedTime, lorentzF),\n }));\n}\n</code></pre>\n<p>More on this can be found in <a href=\"https://reactjs.org/docs/react-component.html#setstate\" rel=\"nofollow noreferrer\">the documentation</a>.</p>\n</li>\n<li><p>For the purpose of formatting it isn't optimal to round the numbers. For example, <code>Math.round(1.005 * Math.pow(10, 2)) / Math.pow(10, 2) == 1</code> (thanks <a href=\"https://stackoverflow.com/a/12830454\">https://stackoverflow.com/a/12830454</a> for the example), and there may be other artifacts of floating point representation. Instead, just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString\" rel=\"nofollow noreferrer\"><code>toLocaleString</code></a>:</p>\n<pre><code>roundNumber(num: number, dec: number) {\n return num.toLocaleString(undefined, { maximumFractionDigits: dec });\n}\n</code></pre>\n<p>If wanted, you may also specify <code>minimumFractionDigits</code>.</p>\n</li>\n</ul>\n<hr />\n<ul>\n<li><p>Consider using class properties instead of calls to <code>.bind()</code> (some of which are needless anyways). Then you may even dissolve the constructor.</p>\n<pre><code>export class TwinParadoxUnderSpecialRelativity extends Component&lt;{}, State&gt; {\n readonly state: State = {\n // ...\n };\n\n updateVelocity = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {\n // ...\n }\n}\n</code></pre>\n<p>Some pros and cons of class properties are discussed in <a href=\"https://stackoverflow.com/questions/50375440/binding-vs-arrow-function-for-react-onclick-event\">https://stackoverflow.com/questions/50375440/binding-vs-arrow-function-for-react-onclick-event</a>.</p>\n</li>\n<li><p>In TypeScript (and modern JavaScript), instead of <code>Math.pow</code> you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation\" rel=\"nofollow noreferrer\">exponentiation operator</a> <code>**</code>:</p>\n<pre><code>calculateLorentzFactor(velocityAsPercentageOfC: number) {\n return 1 / Math.sqrt(1 - (velocityAsPercentageOfC / 100) ** 2);\n}\n</code></pre>\n</li>\n<li><p>The utility functions (<code>calculateLorentzFactor</code> etc.) <a href=\"https://eslint.org/docs/rules/class-methods-use-this\" rel=\"nofollow noreferrer\">do not use <code>this</code></a>, so move them out of the class. Perhaps even move them to another file so that they may be reused more easily. The same may be done with <code>const c</code>. Also, I'd put the comment <code>km/s</code> into a JSDoc comment, so that in suited IDEs it appears on hover:</p>\n<pre><code>/**\n* Speed of light in km/s.\n*/\nconst c = 299792.458;\n</code></pre>\n</li>\n<li><p>Personally I'd use even more descriptive names in some cases. For instance, in <em>code</em> (as opposed to formulas), I'd write something like <code>SPEED_OF_LIGHT</code> instead of <code>c</code>, and <code>kphToMph</code> instead of <code>convertToMph</code>. Oh, and I find it useful to prefix names of event handlers with &quot;handle&quot;, e.g. <code>handleUpdateVelocity</code> instead of <code>updateVelocity</code>.</p>\n</li>\n<li><p>Especially if you work with others, please follow a code style. Auto-formatters may help. In the code sample, there are some superfluous blank lines, inconsistent brace styles, and inconsistent and sometimes confusing spacing. Also, you may consider breaking up long lines:</p>\n<pre><code>renderLeft() {\n return (\n &lt;div&gt;\n &lt;h1&gt;Twin Paradox (Time Dilation under SR) Calculator&lt;/h1&gt;\n\n &lt;p /&gt;\n\n &lt;TextControl\n prepend=&quot;Relative velocity as % of c&quot;\n type=&quot;number&quot;\n value={this.state.velocityAsPercentageOfC}\n append=&quot;v&quot;\n onChange={this.updateVelocity}\n /&gt;\n\n {/* etc. */}\n\n &lt;p&gt;\n At {this.roundNumber(this.state.velocityAsPercentageOfC, 0)}% of the speed of light (c),\n the lorentz factor or gamma is {this.roundNumber(this.state.lorentzFactor, 4)}.\n\n {/* etc. */}\n &lt;/p&gt;\n\n {/* etc. */}\n &lt;/div&gt;\n );\n}\n</code></pre>\n</li>\n<li><p>If a JSX tag doesn't have children, use auto-closing:</p>\n<pre><code>render() {\n return (\n &lt;div&gt;\n &lt;ThreeColumnContainer\n left={this.renderLeft()}\n middle={this.renderMiddle()}\n /&gt;\n &lt;/div&gt;\n );\n}\n</code></pre>\n</li>\n<li><p>You write <code>readonly=&quot;true&quot;</code>. I don't know about the interface of <code>TextControl</code>, but if it's accepting booleans, then <code>readonly</code> should be enough.</p>\n</li>\n<li><p>Perhaps it's because of some omitted code, but there's an unused import of <code>useEffect</code>.</p>\n</li>\n<li><p>As an aside, there's the <code>&lt;sup&gt;</code> tag for prettier rendering of superscripts/exponentiation.</p>\n</li>\n</ul>\n<hr />\n<p>And finally to your questions:</p>\n<ol>\n<li>(Should be answered above.)</li>\n<li>I can't fully answer that because I have never used Material UI. Anyways, perhaps you could try to use just forms and labels instead of prepend/append, or to shorten the prepend text (e.g. &quot;kph&quot; instead of &quot;Velocity in kph&quot;). In general, if don't use it already, you may find <a href=\"https://react-bootstrap.github.io/\" rel=\"nofollow noreferrer\">React Bootstrap</a> to be a useful library.</li>\n<li>I don't see much to extract in your code sample. One thing perhaps, if you plan on using numeric inputs more often, is to write a component specifically for that, so that you can avoid repeating <code>type=&quot;number&quot;</code>, and so that the <code>onChange</code> handler tells you the new value parsed as <code>number</code> (= you don't have to deal with <code>e.target.value</code> all the time). On the issue of routes, it's hard to tell without seeing code, but I think it's not unusual that route files become somewhat large. As long as you keep that clean and focussed, it shouldn't be a problem.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-17T14:45:24.533", "Id": "514763", "Score": "0", "body": "I wrote an alt implementation in pure JS/HTML as an exercise, and this review hits all of the points I ran into and more! Such an excellent review I hope it gets many upvotes!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T23:13:24.333", "Id": "260681", "ParentId": "260517", "Score": "2" } } ]
{ "AcceptedAnswerId": "260681", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T00:10:22.240", "Id": "260517", "Score": "0", "Tags": [ "javascript", "node.js", "react.js", "typescript", "jsx" ], "Title": "This code renders a time dilation calculator" }
260517
<p>I am trying to learn how to correctly implement an iterator (and its corresponding const variant) using a single template, so I would appreciate any criticism to the following code. It's an forward iterator for a cv::Mat wrapper (a class from OpenCV that stores an image).</p> <p>Edit: Its behavior must be equivalent to a pair of nested fors like <code>for(row in rows) for(colum in columns)</code></p> <p>I have already tested it, however I am not familiar with the traditional C++ idioms and patterns so I am not sure that I have properly tested it.</p> <pre><code>class Image { public: using value_type = double_t; using coord_t = int32_t; static const int value_type_opencv_code = CV_64FC1; template &lt;bool isConst&gt; class ImageIterator { public: using iterator_category = std::forward_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = Image::value_type; using pointer = std::conditional_t&lt;isConst, value_type const*, value_type*&gt;; using reference = std::conditional_t&lt;isConst, value_type const&amp;, value_type&amp;&gt;; ImageIterator(const ImageIterator&amp;) = default; template &lt;bool _isConst = isConst, class = std::enable_if_t&lt;_isConst&gt;&gt; ImageIterator(const ImageIterator&lt;false&gt;&amp; other) : data(other.data), index(other.index) {} ImageIterator(cv::Mat data, size_t initial_index) : data(data), index(initial_index) {} // There is definitely some code re usage opportunity here template &lt;bool _isConst = isConst, class = std::enable_if_t&lt;_isConst&gt;&gt; reference operator*() const { return data.at&lt;value_type&gt;(index_to_row(index), index_to_col(index)); } template &lt;bool _isConst = isConst, class = std::enable_if_t&lt;!_isConst&gt;&gt; reference operator*() { return data.at&lt;value_type&gt;(index_to_row(index), index_to_col(index)); } template&lt;bool _isConst = isConst, class = std::enable_if_t&lt;_isConst&gt;&gt; pointer operator-&gt;() const { return data.ptr&lt;value_type&gt;(index_to_row(index)) + index_to_col(index); } template&lt;bool _isConst = isConst, class = std::enable_if_t&lt;!_isConst&gt;&gt; pointer operator-&gt;() { return data.ptr&lt;value_type&gt;(index_to_row(index)) + index_to_col(index); } ImageIterator&lt;isConst&gt;&amp; operator++() { ++index; return *this; } ImageIterator&lt;isConst&gt; operator++(int) { ImageIterator&lt;isConst&gt; other(*this); ++(*this); return other; } // Not sure if this is acceptable, maybe with friendly free functions Image::coord_t getRow() const { return index_to_row(index); } Image::coord_t getColumn() const { return index_to_col(index); } auto getCoordinates() const { return std::make_pair(getRow(), getColumn()); } friend bool operator==(const ImageIterator&lt;isConst&gt;&amp; a, const ImageIterator&lt;isConst&gt;&amp; b) { return a.index == b.index; } friend bool operator!=(const ImageIterator&lt;isConst&gt;&amp; a, const ImageIterator&lt;isConst&gt;&amp; b) { return a.index != b.index; } // To allow const_iterator access to iterator's data. friend ImageIterator&lt;true&gt;; private: cv::Mat data; // Maybe add const, if isConst == true size_t index; // ... [some helper functions] ... } private: cv::Mat data; public: Image(cv::Mat&amp; data) : data(data) {}; Image(coord_t rows, coord_t columns) : data(cv::Mat::zeros(cv::Size((int)columns, (int)rows), value_type_opencv_code)) {} Image(std::pair&lt;coord_t, coord_t&gt; shape) : Image(shape.second, shape.first) {} coord_t rows() const { return data.rows; } coord_t columns() const { return data.cols; } auto shape() const { return std::make_pair(rows(), columns()); } value_type at(const coord_t row, const coord_t column) const { return std::as_const(data).at&lt;double_t&gt;((int)row, (int)column); } value_type&amp; at(const coord_t row, const coord_t column) { return data.at&lt;double_t&gt;((int)row, (int)column); } using iterator = ImageIterator&lt;false&gt;; using const_iterator = ImageIterator&lt;true&gt;; const_iterator begin() const { return const_iterator(data, 0); } const_iterator end() const { return const_iterator(data, (size_t)rows() * columns()); } iterator begin() { return iterator(data, 0); } iterator end() { return iterator(data, (size_t)rows() * columns()); } // ... [more irrelevant member functions] ... const cv::Mat&amp; toMat() const { return data; } }; </code></pre> <p>Tests:</p> <pre><code>// Access using const_iterator Image::coord_t i{ 0 }; Image::coord_t j{ 0 }; for (const auto&amp; e : std::as_const(image)) { EXPECT_EQ(e, generator(i, j)); // ... [update i and j] ... } </code></pre> <pre><code>// Assignment using iterator double_t i{ 0.0 }; for (auto&amp; e : image) e = generator(i++); </code></pre> <pre><code>// const_iterator and iterator construction from iterator Image::iterator iter = std::begin(image); Image::iterator iter2 = iter; Image::const_iterator citer3 = iter; while (iter != std::end(image)) { EXPECT_EQ(*iter, *iter2); EXPECT_EQ(*iter, *citer3); ++iter; ++iter2; ++citer3; } </code></pre> <p>I have implemented more tests, however these are the most critical ones. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:03:57.760", "Id": "514325", "Score": "1", "body": "Try using [Boost.Iterator](https://www.boost.org/doc/libs/1_76_0/libs/iterator/doc/index.html), specifically the `iterator_facade` template." } ]
[ { "body": "<pre><code>template &lt;bool isConst&gt;\nclass ImageIterator\n{\npublic:\n ImageIterator(cv::Mat data, size_t initial_index) : data(data), index(initial_index) {}\n ...\nprivate:\n cv::Mat data;\n size_t index;\n ...\n};\n</code></pre>\n<p>It looks like <code>cv::Mat</code> is a reference-counted handle type, so copying a <code>cv::Mat</code> doesn't copy the actual data.</p>\n<p>However, this also implies that <code>ImageIterator</code> has shared ownership of the data, which would be very unusual in C++. Generally the container (<code>Image</code>) would be the sole owner of the underlying data. An iterator is just a pointer into that data, and keeping one around shouldn't extend the lifetime of the container resources.</p>\n<p>So perhaps we should store a pointer to the <code>cv::Mat</code> (or a pointer to the <code>Image</code> class) in the <code>ImageIterator</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T23:08:11.143", "Id": "514372", "Score": "0", "body": "You're right, it makes no sense for an iterator to own a resource. I did not notice that. I guess I'll go with a pointer (or a reference) to cv::Mat. High cohesiveness isn't a problem between a container and its iterator." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T08:45:43.820", "Id": "260551", "ParentId": "260519", "Score": "1" } } ]
{ "AcceptedAnswerId": "260551", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T08:03:56.150", "Id": "260519", "Score": "3", "Tags": [ "c++", "beginner", "c++17", "iterator", "opencv" ], "Title": "Image (Const) Iterator using C++17" }
260519
<p>I am writng a JUnit test case for the below methods :</p> <pre><code>public final class LoggerService implements ILoggerService { private Logger logger; private &lt;T&gt; LoggerService(T type){ logger = LoggerFactory.getLogger((Class&lt;?&gt;) type); } public static &lt;T&gt; LoggerService getLoggerService(T type){ return new LoggerService(type); } @Override public Long startTimeFrame() { return new Date().getTime(); } @Override public Long stopTimeFrame(Long startTimeFrame) { return new Date().getTime() - startTimeFrame; } } } </code></pre> <p>The simple JUnit test is :</p> <pre><code> @Test public void testStartTimeFrame(){ LoggerService loggerService = LoggerService.getLoggerService(LoggerServiceTest.class); assertEquals(new Date().getTime(), loggerService.startTimeFrame()); } </code></pre> <p>Is this an efficient test case ? Is there any chance that this test could fail sometimes ? Please suggest how I can improve this</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T08:22:09.643", "Id": "514237", "Score": "3", "body": "You could create one timestamp before the call to tested method, and another after the call. Then check that the tested method returned value between those two (inclusive)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T08:24:56.707", "Id": "514238", "Score": "4", "body": "Another option is to introduce a clock interface with method returning current time and use that in your class instead of instantiating a Date directly. And in the test supply a mock implementation and check that the tested method returned whatever the mock returns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T09:56:40.463", "Id": "514244", "Score": "3", "body": "Your stop method refers to a variable startTimeFrame which doesn't appear to exist. Please post all of the relevant code..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T12:16:15.363", "Id": "514247", "Score": "0", "body": "Hi I have corrected the code" } ]
[ { "body": "<p>The problem here is the call to the <code>new</code> operator inside your <em>code under test</em> (cut). So the way to go is to <em>inject</em> this <em>dependency</em> into your cut. Of cause the (failed) implementation of the <em>Java Singelton Pattern</em> is a <a href=\"https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/\" rel=\"noreferrer\">problem</a> too.</p>\n<p>By looking at the API of the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html\" rel=\"noreferrer\"><code>Date</code></a> class we find that it is <em>mutable</em> (which raised lots of discussions when it was introduced). This gives us the opportunity to define a <em>member variable</em> of type <code>Date</code> and reuse is in all the methods of the cut. Of cause in each method <code>Date.setTime(milliseconds)</code> needs to be called where we pass in <code>System.currentTimeMillis()</code>.</p>\n<p>Of cause this is a new <em>requirement</em> to our cut that needs its own UnnitTest methods.</p>\n<pre><code> class InjectDateTest {\n\n static class LoggerService {\n\n private Date date;\n\n public LoggerService(Date date) {\n this.date = date;\n }\n\n public Long startTimeFrame() {\n date.setTime(System.currentTimeMillis());\n return date.getTime();\n }\n\n }\n\n private LoggerService loggerService;\n private Date loggerDate = new Date();\n\n @BeforeEach\n void setUp() throws Exception {\n loggerService = new LoggerService(loggerDate);\n }\n\n @Test\n public void shouldSetTimeAfterCall() throws InterruptedException {\n long creationTime = loggerDate.getTime(); \n Thread.sleep(200, 0);\n loggerService.startTimeFrame();\n assertTrue(creationTime &lt; loggerDate.getTime(),\n String.format(&quot;time in date object %s &lt; %s&quot;, creationTime, loggerDate.getTime())\n );\n }\n\n @Test\n public void testStartTimeFrame() {\n Long startTimeFrame = loggerService.startTimeFrame();\n assertEquals(loggerDate.getTime(), startTimeFrame);\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T12:41:14.823", "Id": "514248", "Score": "0", "body": "So here are we not instantiating the \"LoggerService\" object from the Java Module ( Not the inner static class inside Test Class) . I'm little confused as both the names are same - 'LoggerService'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T17:08:35.867", "Id": "514266", "Score": "0", "body": "@user3254725: I simply wanted to provide a [SSCCE](http://sscce.org/) that you can directly paste to your IDE in one shot." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T09:56:37.620", "Id": "260523", "ParentId": "260520", "Score": "5" } }, { "body": "<h2>Test-ability</h2>\n<p>@Timothy Truckle and @slepic have both given you some good suggestions about how you can improve your test and the test-ability of your class. There are various other ways that could be used to make the class more testable, however the thing that struck me was that the <code>LoggerService</code> didn't seem to make a lot of sense.</p>\n<h2>A Logging Service?</h2>\n<p>There's three public methods <code>getLoggerService</code>, <code>startTimeFrame</code> and <code>stopTimeFrame</code>. The <code>getLoggerService</code> creates a new instance, fine, but start/stop time frame don't feel like they belong in a logger class. Start returns an actual start time, whereas stop returns a delta from a time that the client has to supply. To me this behaviour feels wrong, and because we can't see the client it's unclear why it would be structured this way. Both methods feel like they belong more in a stopwatch (or similar) class rather than a logger. The <code>@Override</code> suggests these methods are coming from <code>ILoggerService</code>, is this a class you own, or does it come from a library somewhere?</p>\n<p>I also find it particularly weird that a <code>LoggerService</code> class doesn't appear to provide any way to access the <code>logger</code> it creates, or in fact do any logging related activity at all.</p>\n<h2>Boxing</h2>\n<p>As an aside, <code>getTime()</code> returns a <code>long</code>. If you do own the interface, is there a reason why start and stop are boxing the parameters/return values, rather than using the primitive types?</p>\n<h2>JUnit</h2>\n<p>You related <a href=\"https://stackoverflow.com/q/67455244/592182\">question on stackoverflow</a> suggests that you're using JUnit 5. If this is the case, you no longer need to declare you test methods as <code>public</code>, annotating them with <code>@Test</code> is sufficient for the framework to find them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T00:09:22.617", "Id": "260545", "ParentId": "260520", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T08:14:35.200", "Id": "260520", "Score": "0", "Tags": [ "java", "unit-testing", "junit" ], "Title": "Need Feedback on JUnit test comparing two timestamps" }
260520
<p>I've built a login panel, which will submit an email and password via fetch/POST. And I wanted to know the best way to handle network status errors?</p> <p>Reason being, as I want to inject error messages into my login panel for each state/status code.</p> <p>I've written the code below, which works. But I wondered if there is a better way to write this? For example, should my status code handling go in the catch() etc?</p> <pre><code>let url = 'www.MYAPI.com/xyz'; // post body data let data = { &quot;Username&quot;: emailAddress, &quot;Password&quot;: Password, } // create request object let request = new Request(url, { &quot;method&quot;: 'POST', &quot;mode&quot;: 'cors', &quot;credentials&quot;: 'include', &quot;body&quot;: JSON.stringify(data), &quot;referrerPolicy&quot;: &quot;strict-origin-when-cross-origin&quot;, &quot;headers&quot;: { &quot;accept&quot;: &quot;application/json, text/plain, */*&quot;, &quot;content-type&quot;: &quot;application/json;charset=UTF-8&quot;, &quot;sec-fetch-mode&quot;: &quot;cors&quot;, &quot;sec-fetch-site&quot;: &quot;same-origin&quot;, &quot;x-requested-with&quot;: &quot;XMLHttpRequest&quot; } }); fetch(request) .then( async (response) =&gt; { let data = await response.json(); if(response.status === 200){ // LOGIN SUCCESSFUL HERE; console.log(&quot;Successful log in - status: &quot;, data); document.getElementById(&quot;id01&quot;).style.display = &quot;none&quot;; // HIDE LOGIN PANEL } else{ // Rest of status codes (400,500,303), can be handled here appropriately // IF EMAIL ADDRESS ERROR / STATUS 502 if (data.KnownErrorDescription === &quot;MemberEmailDoesNotExist&quot;) { document.getElementById(&quot;email-error&quot;).innerHTML = &quot;Please enter a valid email address to sign in&quot;; }; // IF PASSWORD IS EMPTY / STATUS 400 if (data.Message === &quot;The request is invalid.&quot;) { document.getElementById(&quot;password-error&quot;).innerHTML = data.ModelState[&quot;request.Password&quot;][0]; } // // IF ACCOUNT LOCKED / 502 if (data.KnownErrorDescription === &quot;MemberAccountLocked&quot;) { document.getElementById(&quot;failed-sign-in-error&quot;).innerHTML = &quot;You need to reset your password&quot;; document.getElementById(&quot;password-reset&quot;).style.display = &quot;block&quot;; } }; }) .catch((err) =&gt; { console.log(err); }) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T11:47:28.637", "Id": "514246", "Score": "0", "body": "Welcome to the Code Review Community. The title of the question should be an introduction into what the code does, not your concerns about the code. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T03:36:23.097", "Id": "514975", "Score": "1", "body": "The way you're handling the errors looks just fine to me. Because the fetch() API doesn't throw on bad status codes, there's no good way to handle the errors in the catch block, unless you threw them from your .then() handler, which is an option, but it's not needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T14:41:37.607", "Id": "515031", "Score": "0", "body": "@ScottyJamison - Thank you for the feedback! Appreciate!" } ]
[ { "body": "<p>I personally think that You can easily handle part of the error handling logic in the <code>catch</code> block however at the moment You are listening for the specific response status do specify what went wrong during the API connection process.</p>\n<p>MDN says:</p>\n<blockquote>\n<p>You can use a catch block to handle all exceptions that may be generated in the try block.</p>\n</blockquote>\n<p><code>try/catch</code> works in a way that if anything fails on the try block, then the rest of the code (in the <code>try</code> block) is ignored and the script execution goes to the catch block. If something goes wrong then the error object is created and passed to the <code>catch block</code> as a parameter <code>.catch(err)</code>. From this object You might be able to handle part of the error handling logic. Take a look at the below links:</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch</a>\n<a href=\"https://javascript.info/try-catch\" rel=\"nofollow noreferrer\">https://javascript.info/try-catch</a></p>\n<p>Moreover:</p>\n<ul>\n<li>data variable can be a <code>const</code></li>\n<li>Instead of writing <code>.style.display = &quot;none&quot;;</code> use <code>YourElement.classList.add('YourNewSexyClass')</code> and use CSS for styling :)</li>\n<li><code>innerHTML</code> is not a good practice. Take a look here -&gt; <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations</a></li>\n<li><code>url</code> variable should a <code>const</code></li>\n<li><code>data</code> variable should be a <code>const</code></li>\n</ul>\n<blockquote>\n<pre><code>let data = {\n &quot;Username&quot;: emailAddress,\n &quot;Password&quot;: Password,\n }\n</code></pre>\n</blockquote>\n<p>can be changed like so (get rid of capital letters here)</p>\n<pre><code>let data = {\n username: emailAddress,\n password: password\n }\n</code></pre>\n<p>so that You can change it to</p>\n<pre><code>let data = {\n username: emailAddress,\n password\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T11:57:40.143", "Id": "515008", "Score": "0", "body": "Hey @AdamKniec, sorry for the delay in coming back to you and I appreciate your feedback! I'm just wrapping up a project and I shall come back to you in the next day or two. I appreciate your feedback. I have a couple of questions but not urgent, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T14:43:06.580", "Id": "515032", "Score": "0", "body": "Hey @AdamKniec - thank you for the feedback? I wondered why the `url` and `data` variable should be a const? Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T14:44:53.980", "Id": "515033", "Score": "1", "body": "@ReenaVerma because values assigned to those variables does not change. In that case its a good prsctice to use a const. It uses less memory in the CPU" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T15:39:23.233", "Id": "515039", "Score": "0", "body": "Thank you! Really helpful note on its impact on CPU. I had no idea that was the case." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T16:10:12.003", "Id": "260532", "ParentId": "260524", "Score": "1" } } ]
{ "AcceptedAnswerId": "260532", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T10:19:07.797", "Id": "260524", "Score": "1", "Tags": [ "javascript", "api", "ajax" ], "Title": "Posting data via fetch and handling network errors" }
260524
<p>A few days ago I posted a previous version of my first bash script here to get few tips and reviews so I could improve it. So now it is improved a bit. I also shellchecked it and fixed the warnings. I would love to hear more tips from you guys.</p> <p>Here is the code:</p> <pre><code>#!/usr/bin/env bash declare -r CONF_DIR_PATH=&quot;$HOME/.config/rdoc&quot; declare -r TMP_FILE=&quot;/tmp/rdoc_tmp.$$&quot; #Trap the following signals and do cleanup before exiting trap 'rm -f &quot;$TMP_FILE&quot; 2&gt; /dev/null &amp;&amp; exit 0' EXIT trap 'rm -f &quot;$TMP_FILE&quot; 2&gt; /dev/null &amp;&amp; echo &amp;&amp; exit 1' SIGINT fn_generate_configs() { local doc_dir_path local pdf_viewer_name mkdir -p &quot;$CONF_DIR_PATH&quot; printf &quot;Please enter your documents directory full path: &quot; read -r doc_dir_path echo &quot;$doc_dir_path&quot; &gt; &quot;$CONF_DIR_PATH/doc_dir&quot; printf &quot;\nPlease enter your pdf's viewer name: &quot; read -r pdf_viewer_name echo &quot;$pdf_viewer_name&quot; &gt; &quot;$CONF_DIR_PATH/pdf_viewer&quot; printf &quot;\nYour configurations were generated succesfully.\n&quot; } fn_read_configs() { if ! doc_dir=$(cat &quot;$CONF_DIR_PATH/doc_dir&quot; 2&gt; /dev/null); then echo Error: one or all of your configuration files are missing. echo Try -h for help. exit 1 fi if ! pdf_viewer=$(cat &quot;$CONF_DIR_PATH/pdf_viewer&quot; 2&gt; /dev/null); then echo Error: one or all of your configuration files are missing. echo Try -h for help. exit 1 fi } fn_search_for_book() { local path local grep_opt=&quot;-q&quot; local string_to_exclude=&quot;$1/&quot; if [ &quot;$i_status&quot; -eq 1 ]; then grep_opt=&quot;-qi&quot; fi if [ &quot;$r_status&quot; -eq 1 ]; then #Search recursively for path in &quot;$1&quot;/*; do if [ -d &quot;$path&quot; ]; then fn_search_for_book &quot;$path&quot; elif [ -f &quot;$path&quot; ]; then #Redirect grep help message if book_name has the program's options value. #This would happen if the user called the program with the defualt behaviour, #plus with one of the available options but he/she omitted to pass the doc_name #so book_name will get the value of the passed options wich will trhow the grep help message. if echo &quot;$path&quot; | grep $grep_opt &quot;$book_name&quot; 2&gt; /dev/null; then echo &quot;${path//&quot;$string_to_exclude&quot;/}&quot; &gt;&gt; &quot;$TMP_FILE&quot; fi fi done else for path in &quot;$1&quot;/*; do if [ -f &quot;$path&quot; ]; then #Redirect grep help message for the same reasons as above if echo &quot;$path&quot; | grep $grep_opt &quot;$book_name&quot; 2&gt; /dev/null; then echo &quot;${path//&quot;$string_to_exclude&quot;/}&quot; &gt;&gt; &quot;$TMP_FILE&quot; fi fi done fi } fn_display_books() { local doc local founded_docs #Make sure a book was founded and TMP_FILE was generated if ! founded_docs=$(cat &quot;$TMP_FILE&quot; 2&gt; /dev/null); then printf &quot;Error: no document was found with \'%s\' in it.\n&quot; &quot;$book_name&quot; exit 1 fi printf &quot;These are the documents that were found:\n\n&quot; #Set output's color to red tput setaf 1 for doc in $founded_docs; do echo &quot;$doc&quot; done #Reset output's color tput sgr0 } fn_count_books() { local doc local founded_docs local cnt=0 if ! founded_docs=$(cat &quot;$TMP_FILE&quot; 2&gt; /dev/null); then printf &quot;\nError: \'%s\' manipulation while the program is running are disallowed.\n&quot; &quot;$TMP_FILE&quot; exit 1 fi for doc in $founded_docs; do (( cnt++ )) done return &quot;$cnt&quot; } fn_final_book_name() { printf &quot;\nWhich one of them would you like to open: &quot; read -r book_name } fn_generate_books_paths() { local path if [ &quot;$r_status&quot; -eq 1 ]; then for path in &quot;$1&quot;/*; do if [ -d &quot;$path&quot; ]; then fn_generate_books_paths &quot;$path&quot; elif [ -f &quot;$path&quot; ]; then echo &quot;$path&quot; &gt;&gt; &quot;$TMP_FILE&quot; fi done else for path in &quot;$1&quot;/*; do if [ -f &quot;$path&quot; ]; then echo &quot;$path&quot; &gt;&gt; &quot;$TMP_FILE&quot; fi done fi } fn_get_book_path() { local founded_paths local path local grep_opt=&quot;-q&quot; if ! founded_paths=$(cat &quot;$TMP_FILE&quot; 2&gt; /dev/null); then printf &quot;\nError: \'%s\' manipulation while the program is running are disallowed.\n&quot; &quot;$TMP_FILE&quot; exit 1 fi if [ &quot;$i_status&quot; -eq 1 ]; then grep_opt=&quot;-qi&quot; fi for path in $founded_paths; do if ! echo &quot;$path&quot; | grep $grep_opt &quot;$book_name&quot;; then continue fi book_path=&quot;$path&quot; break done } fn_open_book() { if ! &quot;$pdf_viewer&quot; &quot;$book_path&quot; 2&gt; /dev/null; then printf &quot;\nError: %s can\'t be opened.\n&quot; &quot;$book_path&quot; exit 1 fi printf &quot;\nOpening: %s\n&quot; &quot;$book_path&quot; } fn_help_message() { printf &quot;Usage: rdoc &lt;options&gt; [argument] Available options: -h Display this help message. -g Generate new configuration files. -r Allow recursive searching for the document. -i Ignore case distinctions while searching for the document. -s Search for the document and display results. This option takes a document name or a part of it as an argument. -o Search for the document, display results then open it using your pdf viewer. This option takes a document name or a part of it as an argument. (Default) NOTE: When using '-s' or '-o' option in a combination of other options like this: $ rdoc -ris document_name Please make sure that it's the last option; to avoid unexpected behaviour. &quot; } doc_dir=&quot;&quot; pdf_viewer=&quot;&quot; book_path=&quot;&quot; book_name=${!#} #book_name equals to the last arg by defualt so the default option ('-o') will work. #Options status r_status=0 i_status=0 s_status=0 o_status=1 #Make -o the default option #Display help message if no options were passed if [ $# -eq 0 ]; then fn_help_message exit 0 fi while getopts &quot;:hgris:o:&quot; opt; do case $opt in h) fn_help_message exit 0 ;; g) fn_generate_configs o_status=0 ;; r) r_status=1 ;; i) i_status=1 ;; s) book_name=&quot;$OPTARG&quot; s_status=1 o_status=0 ;; o) book_name=&quot;$OPTARG&quot; ;; :) printf &quot;Error: an argument is required for \'-%s\' option.\n&quot; &quot;$OPTARG&quot; echo Try -h for help. exit 1 ;; *) printf &quot;Error: unknown option \'-%s\'.\n&quot; &quot;$OPTARG&quot; echo Try -h for help. exit 1 ;; esac done if [ &quot;$s_status&quot; -eq 1 ]; then fn_read_configs fn_search_for_book &quot;$doc_dir&quot; fn_display_books elif [ &quot;$o_status&quot; -eq 1 ]; then fn_read_configs fn_search_for_book &quot;$doc_dir&quot; fn_display_books fn_count_books if [ $? -gt 1 ]; then #If more than 1 book were found with $book_name in it fn_final_book_name #Clean any leftovers of $TMP_FILE to search properly rm &quot;$TMP_FILE&quot; 2&gt; /dev/null #Make sure that the user chose an available document fn_search_for_book &quot;$doc_dir&quot; if [ ! -f &quot;$TMP_FILE&quot; ]; then printf &quot;\nError: no document was found with \'%s\' in it.\n&quot; &quot;$book_name&quot; exit 1 fi #Make sure that the user is specific enough about the book name fn_count_books if [ $? -gt 1 ]; then printf &quot;\nError: More than 1 book was found with the name \'%s\' in it.\n&quot; &quot;$book_name&quot; exit 1 fi fi : &gt; &quot;$TMP_FILE&quot; #Make sure $TMP_FILE is empty so it'll be usable in fn_generate_books_paths fn_generate_books_paths &quot;$doc_dir&quot; fn_get_book_path fn_open_book fi exit 0 </code></pre> <p>Here is a link to the repo on github for the ones who would prefer to review it there: <a href="https://github.com/yankh764/rdoc" rel="nofollow noreferrer">https://github.com/yankh764/rdoc</a></p> <p>Thanks guys.</p>
[]
[ { "body": "<h1>Good</h1>\n<ul>\n<li>nice indentation</li>\n<li>good docs for the options</li>\n<li>good variable names</li>\n<li>a reasonable amount of inline comments</li>\n<li>yay for being on top of the shellcheck already</li>\n</ul>\n<h1>Suggestions</h1>\n<ul>\n<li>For conditionals it is safer to use double square brackets. Some folks on here discourage the double square brackets for portability, but bash/zsh/ksh all support the more modern syntax.</li>\n<li>Put your config into the format of a script and then <a href=\"https://superuser.com/a/46146/358509\">source it</a>.</li>\n<li>Put your usage function near the top and include a line that says what the\ngist of the command is.</li>\n</ul>\n<h1>Nits</h1>\n<p>These are minor issues that are more matters of taste.</p>\n<ul>\n<li>I wouldn't proceed every function with the same <code>fn_</code>, but I can see that might make it easier to keep a script of this size straight in your head.</li>\n<li>Putting a space after the hash in a comment will make it easier to read.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T19:56:06.737", "Id": "514362", "Score": "0", "body": "Thank you for such a great review. I was surprised that you also included the good things alongside to the tips and suggestions which is really nice and encouraging, so I appreciate it. Lastly I will of course learn from your tips and modify my script to improve it :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T02:35:51.683", "Id": "260547", "ParentId": "260525", "Score": "1" } } ]
{ "AcceptedAnswerId": "260547", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T10:21:56.560", "Id": "260525", "Score": "1", "Tags": [ "bash", "linux" ], "Title": "Rdoc - a command-line tool for launching documents (improved)" }
260525
<p>I recently put up my C++ class to wrap the sqlite3 c library here:</p> <p><a href="https://codereview.stackexchange.com/questions/260450/thin-c-wrapper-for-sqlite3-c-library">Thin C++ wrapper for sqlite3 C library</a></p> <p>One of the suggestions was rather than to specify a vector for arguments to functions instead specify iterators so users can use whatever collection they see fit.</p> <p>Not being that familiar with adding such iterator functionality, please review this aspect of the class.</p> <p>And indeed any other comments you would like to make.</p> <p>Here is the header, sqlite.hpp:</p> <pre><code>/* sqlite - a thin c++ wrapper of sqlite c library */ #ifndef SQLITE_HPP_ #define SQLITE_HPP_ // uncomment below to print blob data as hex in ostream overload of column_values // #define PRINT_BLOB_AS_HEX #include &quot;sqlite3.h&quot; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;variant&gt; #include &lt;cstdint&gt; #include &lt;iostream&gt; #include &lt;map&gt; #define EXIT_ON_ERROR(resultcode) \ if (resultcode != SQLITE_OK) \ { \ sqlite3_finalize(stmt); \ return resultcode; \ } namespace sql { /* sqlite types can be: NULL, INTEGER, REAL, TEXT, BLOB NULL: we don't support this type INTEGER: int REAL: double TEXT: std::string BLOB: std::vector&lt;uint8_t&gt; */ using sqlite_data_type = std::variant&lt;int, double, std::string, std::vector&lt;uint8_t&gt; &gt;; struct column_values { std::string column_name; sqlite_data_type column_value; }; struct where_binding { std::string column_name; sqlite_data_type column_value; }; std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const column_values&amp; v); std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const sqlite_data_type&amp; v); std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const std::map&lt;std::string, sqlite_data_type&gt;&amp; v); class sqlite { public: sqlite(); ~sqlite(); /* database must be opened before calling an sql operation */ int open(const std::string&amp; filename); /* close database connection */ int close(); /* INSERT INTO (col1, col2) VALUES (:col1, :col2); table_name is table to insert into begin and end are iterators to a collection of column name -&gt; value key value pairs */ template &lt;typename columns_iterator&gt; int insert_into(const std::string&amp; table_name, columns_iterator begin, columns_iterator end); /* returns rowid of last successfully inserted row. If no rows inserted since this database connectioned opened, returns zero. */ int last_insert_rowid(); /* UPDATE contacts SET col1 = value1, col2 = value2, ... WHERE rowid = therowid; table_name is table to update, columns_begin and columns_end are iterators to a collection of column name -&gt; value key value pairs where_clause is WHERE clause predicate expressed as : parameterised query where_bindings_begin and end are iterators to a collection of where bindings used in the where clause */ template &lt;typename columns_iterator, typename where_bindings_iterator&gt; int update( const std::string&amp; table_name, columns_iterator columns_begin, columns_iterator columns_end, const std::string&amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end); /* UPDATE contacts SET col1 = value1, col2 = value2, ...; same as update(table_name, begin, end, where) except no WHERE clause so potential to change EVERY row. USE WITH CAUTION. */ template &lt;typename columns_iterator&gt; int update(const std::string&amp; table_name, columns_iterator begin, columns_iterator end); /* DELETE FROM table_name WHERE condition; */ template &lt;typename where_bindings_iterator&gt; int delete_from(const std::string&amp; table_name, const std::string&amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end); /* DELETE FROM table_name; same as delete_from(table_name, where) except no WHERE clause so potential to delete EVERY row. USE WITH CAUTION. */ int delete_from(const std::string&amp; table_name); /* SELECT * FROM table_name WHERE col1 = x; table_name is table to select, where_clause is WHERE clause predicate expressed as : parameterised query where_bindings_begin and end are iterators to a collection of where bindings used in the where clause results is a table of values */ template &lt;typename where_bindings_iterator&gt; int select_star(const std::string&amp; table_name, const std::string&amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results); /* SELECT * FROM table_name; table_name is table to select, results is a table of values */ int select_star(const std::string&amp; table_name, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results); /* SELECT col1, col2 FROM table_name WHERE col1 = x; table_name is table to select, name_begin and end are iterators to a collection of column name strings in table to select where_clause is the sql WHERE clause where_bindings_begin and end are iterators to a collection of where bindings used in the where clause results is a table of values */ template &lt;typename column_names_iterator, typename where_bindings_iterator&gt; int select_columns(const std::string&amp; table_name, column_names_iterator name_begin, column_names_iterator name_end, const std::string&amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results); /* get error text relating to last sqlite error. Call this function whenever an operation returns a sqlite error code */ const std::string get_last_error_description(); private: sqlite3* db_; template &lt;typename columns_iterator&gt; int bind_fields(sqlite3_stmt* stmt, columns_iterator begin, columns_iterator end); template &lt;typename columns_iterator&gt; std::string insert_into_helper(const std::string&amp; table_name, columns_iterator begin, columns_iterator end); template &lt;typename columns_iterator&gt; std::string update_helper( const std::string&amp; table_name, columns_iterator begin, columns_iterator end, const std::string&amp; where_clause); template &lt;typename where_binding_iterator&gt; int bind_where(sqlite3_stmt* stmt, where_binding_iterator begin, where_binding_iterator end); int step_and_finalise(sqlite3_stmt* stmt); std::string space_if_required(const std::string&amp; s); std::string delete_from_helper( const std::string&amp; table_name, const std::string&amp; where_clause); template &lt;typename column_names_iterator&gt; const std::string select_helper( const std::string&amp; table_name, column_names_iterator name_begin, column_names_iterator name_end, const std::string&amp; where_clause); }; template &lt;typename columns_iterator&gt; int sqlite::bind_fields(sqlite3_stmt* stmt, columns_iterator begin, columns_iterator end) { int rc = SQLITE_OK; for (auto it = begin; it != end; ++it) { std::string next_param{ ':' + it-&gt;column_name }; int idx = sqlite3_bind_parameter_index(stmt, next_param.c_str()); switch (it-&gt;column_value.index()) { case 0: rc = sqlite3_bind_int(stmt, idx, std::get&lt;0&gt;(it-&gt;column_value)); break; case 1: rc = sqlite3_bind_double(stmt, idx, std::get&lt;1&gt;(it-&gt;column_value)); break; case 2: rc = sqlite3_bind_text(stmt, idx, std::get&lt;2&gt;(it-&gt;column_value).c_str(), -1, SQLITE_STATIC); break; case 3: rc = sqlite3_bind_blob(stmt, idx, std::get&lt;3&gt;(it-&gt;column_value).data(), static_cast&lt;int&gt;(std::get&lt;3&gt;(it-&gt;column_value).size()), SQLITE_STATIC); break; } } return rc; } template &lt;typename columns_iterator&gt; int sqlite::insert_into(const std::string&amp; table_name, columns_iterator begin, columns_iterator end) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = insert_into_helper(table_name, begin, end); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_fields(stmt, begin, end)); return step_and_finalise(stmt); } template &lt;typename columns_iterator, typename where_bindings_iterator&gt; int sqlite::update( const std::string &amp; table_name, columns_iterator columns_begin, columns_iterator columns_end, const std::string &amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = update_helper(table_name, columns_begin, columns_end, where_clause); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_fields(stmt, columns_begin, columns_end)); EXIT_ON_ERROR(bind_where(stmt, where_bindings_begin, where_bindings_end)); return step_and_finalise(stmt); } template &lt;typename columns_iterator&gt; int sqlite::update(const std::string&amp; table_name, columns_iterator begin, columns_iterator end) { return update(table_name, begin, end, &quot;&quot;, {}); } template &lt;typename columns_iterator&gt; std::string sqlite::insert_into_helper(const std::string&amp; table_name, columns_iterator begin, columns_iterator end) { std::string sqlfront{ &quot;INSERT INTO &quot; + table_name + &quot; (&quot; }; std::string sqlend{ &quot;) VALUES (&quot; }; std::string separator{ &quot;&quot; }; for (auto field = begin; field != end; ++field) { sqlfront += separator + field-&gt;column_name; sqlend += separator + ':' + field-&gt;column_name; separator = &quot;,&quot;; } sqlend += &quot;);&quot;; return sqlfront + sqlend; } template &lt;typename columns_iterator&gt; std::string sqlite::update_helper( const std::string&amp; table_name, columns_iterator begin, columns_iterator end, const std::string&amp; where_clause) { std::string sql{ &quot;UPDATE &quot; + table_name + &quot; SET &quot; }; std::string separator{ &quot;&quot; }; for (auto field = begin; field != end; ++field) { sql += separator + field-&gt;column_name + &quot;=:&quot; + field-&gt;column_name; separator = &quot;,&quot;; } if (!where_clause.empty()) { sql += space_if_required(where_clause); sql += where_clause; } sql += &quot;;&quot;; return sql; } template &lt;typename where_binding_iterator&gt; int sqlite::bind_where(sqlite3_stmt* stmt, where_binding_iterator begin, where_binding_iterator end) { //const std::vector&lt;sql::where_binding&gt;&amp; binding) { int rc = SQLITE_OK; for (auto param = begin; param != end; ++param) { std::string next_param{ ':' + param-&gt;column_name }; int idx = sqlite3_bind_parameter_index(stmt, next_param.c_str()); switch (param-&gt;column_value.index()) { case 0: rc = sqlite3_bind_int(stmt, idx, std::get&lt;0&gt;(param-&gt;column_value)); break; case 1: rc = sqlite3_bind_double(stmt, idx, std::get&lt;1&gt;(param-&gt;column_value)); break; case 2: rc = sqlite3_bind_text(stmt, idx, std::get&lt;2&gt;(param-&gt;column_value).c_str(), -1, SQLITE_STATIC); break; case 3: rc = sqlite3_bind_blob(stmt, idx, std::get&lt;3&gt;(param-&gt;column_value).data(), static_cast&lt;int&gt;(std::get&lt;3&gt;(param-&gt;column_value).size()), SQLITE_STATIC); break; } } return rc; } template &lt;typename column_names_iterator, typename where_bindings_iterator&gt; int sqlite::select_columns(const std::string&amp; table_name, column_names_iterator name_begin, column_names_iterator name_end, const std::string&amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = select_helper(table_name, name_begin, name_end, where_clause); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_where(stmt, where_bindings_begin, where_bindings_end)); int num_cols = sqlite3_column_count(stmt); std::vector&lt;std::string&gt; column_names; for (int i = 0; i &lt; num_cols; i++) { const char* colname = sqlite3_column_name(stmt, i); column_names.push_back(colname ? colname : &quot;&quot;); } int rc = 0; while ((rc = sqlite3_step(stmt)) != SQLITE_DONE) { std::map&lt;std::string, sqlite_data_type&gt; row; for (int i = 0; i &lt; num_cols; i++) { switch (sqlite3_column_type(stmt, i)) { case SQLITE3_TEXT: { const unsigned char* value = sqlite3_column_text(stmt, i); int len = sqlite3_column_bytes(stmt, i); row[column_names[i]] = std::string(value, value + len); } break; case SQLITE_INTEGER: { row[column_names[i]] = sqlite3_column_int(stmt, i); } break; case SQLITE_FLOAT: { row[column_names[i]] = sqlite3_column_double(stmt, i); } break; case SQLITE_BLOB: { const uint8_t* value = reinterpret_cast&lt;const uint8_t*&gt;(sqlite3_column_blob(stmt, i)); int len = sqlite3_column_bytes(stmt, i); row[column_names[i]] = std::vector&lt;uint8_t&gt;(value, value + len); } break; case SQLITE_NULL: { row[column_names[i]] = &quot;null&quot;; } break; default: break; } } results.push_back(row); } return sqlite3_finalize(stmt); } template &lt;typename column_names_iterator&gt; const std::string sqlite::select_helper( const std::string&amp; table_name, column_names_iterator name_begin, column_names_iterator name_end, const std::string&amp; where_clause) { std::string sql{ &quot;SELECT &quot; }; std::string separator{ &quot;&quot; }; for (auto field = name_begin; field != name_end; ++field) { sql += separator + *field; separator = &quot;,&quot;; } if (name_begin == name_end) { sql += &quot;*&quot;; } sql += &quot; FROM &quot; + table_name; if (!where_clause.empty()) { sql += space_if_required(where_clause); sql += where_clause; } sql += &quot;;&quot;; return sql; } template &lt;typename where_bindings_iterator&gt; int sqlite::delete_from(const std::string&amp; table_name, const std::string&amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end) { if (db_ == nullptr) { return SQLITE_ERROR; } const std::string sql = delete_from_helper(table_name, where_clause); sqlite3_stmt* stmt = NULL; EXIT_ON_ERROR(sqlite3_prepare_v2(db_, sql.c_str(), -1, &amp;stmt, NULL)); EXIT_ON_ERROR(bind_where(stmt, where_bindings_begin, where_bindings_end)); return step_and_finalise(stmt); } template &lt;typename where_bindings_iterator&gt; int sqlite::select_star(const std::string&amp; table_name, const std::string&amp; where_clause, where_bindings_iterator where_bindings_begin, where_bindings_iterator where_bindings_end, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results) { std::string empty; return select_columns(table_name, empty.begin(), empty.end(), where_clause, where_bindings_begin, where_bindings_end, results); } } // itel #endif // SQLITE_HPP_ </code></pre> <p>Implementation file, sqlite.cpp:</p> <pre><code>#include &quot;sqlite.hpp&quot; #include &lt;algorithm&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; namespace sql { std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const column_values&amp; v) { os &lt;&lt; &quot;name: &quot; &lt;&lt; v.column_name &lt;&lt; &quot;, value: &quot;; switch (v.column_value.index()) { case 0: os &lt;&lt; std::get&lt;0&gt;(v.column_value) &lt;&lt; &quot; of type int&quot;; break; case 1: os &lt;&lt; std::get&lt;1&gt;(v.column_value) &lt;&lt; &quot; of type double&quot;; break; case 2: os &lt;&lt; std::get&lt;2&gt;(v.column_value) &lt;&lt; &quot; of type string&quot;; break; case 3: { #ifdef PRINT_BLOB_AS_HEX auto previous_flags = os.flags(); std::for_each(std::get&lt;3&gt;(v.column_value).begin(), std::get&lt;3&gt;(v.column_value).end(), [&amp;os](const uint8_t&amp; byte) { os &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; (byte &amp; 0xFF) &lt;&lt; ' '; }); os &lt;&lt; &quot; of type vector&lt;uint8_t&gt;&quot;; os.setf(previous_flags); #else os &lt;&lt; &quot;&lt;blob&gt; of type vector&lt;uint8_t&gt;&quot;; #endif break; } } return os; } #ifdef PRINT_BLOB_AS_HEX std::ostream&amp; operator&lt;&lt;(std::ostream &amp; os, const std::vector&lt;uint8_t&gt;&amp;v) { auto previous_flags = os.flags(); std::for_each(v.begin(), v.end(), [&amp;os](const uint8_t&amp; byte) { os &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; (byte &amp; 0xFF) &lt;&lt; ' '; }); os.setf(previous_flags); #else std::ostream&amp; operator&lt;&lt;(std::ostream &amp; os, const std::vector&lt;uint8_t&gt;&amp; /* v */) { os &lt;&lt; &quot;&lt;blob&gt;&quot;; #endif return os; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const sqlite_data_type&amp; v) { std::visit([&amp;](const auto&amp; element) { os &lt;&lt; element; }, v); return os; } std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const std::map&lt;std::string, sqlite_data_type&gt;&amp; v) { for (const auto&amp; element : v) { os &lt;&lt; element.first &lt;&lt; &quot;: &quot; &lt;&lt; element.second &lt;&lt; '|'; } return os; } sqlite::sqlite() : db_(nullptr) {} sqlite::~sqlite() { close(); } int sqlite::open(const std::string&amp; filename) { return sqlite3_open(filename.c_str(), &amp;db_); } int sqlite::close() { if (db_ == nullptr) { return SQLITE_ERROR; } return sqlite3_close(db_); } int sqlite::last_insert_rowid() { return static_cast&lt;int&gt;(sqlite3_last_insert_rowid(db_)); } int sqlite::delete_from(const std::string&amp; table_name) { std::vector&lt;where_binding&gt; empty; return delete_from(table_name, &quot;&quot;, empty.begin(), empty.end()); } int sqlite::select_star(const std::string&amp; table_name, std::vector&lt;std::map&lt;std::string, sqlite_data_type&gt;&gt;&amp; results) { std::vector&lt;where_binding&gt; empty; return select_star(table_name, &quot;&quot;, empty.begin(), empty.end(), results); } const std::string sqlite::get_last_error_description() { if (db_ == nullptr) { return &quot;&quot;; } const char* error = sqlite3_errmsg(db_); std::string s(error ? error : &quot;&quot;); return s; } int sqlite::step_and_finalise(sqlite3_stmt* stmt) { if (stmt == nullptr) { return SQLITE_ERROR; } // whether error or not we must call finalize int rc = sqlite3_step(stmt); // SQLITE_ROW = another row ready - possible to configure to return a value - but we just ignore anything returned // SQLITE_DONE = finished executing // caller is more interested in the result of the step int finalise_rc = sqlite3_finalize(stmt); // de-allocates stmt return rc == SQLITE_DONE ? finalise_rc : rc; } std::string sqlite::space_if_required(const std::string&amp; s) { return !s.empty() &amp;&amp; s[0] != ' ' ? &quot; &quot; : &quot;&quot;; } std::string sqlite::delete_from_helper( const std::string&amp; table_name, const std::string&amp; where_clause) { std::string sql{ &quot;DELETE FROM &quot; + table_name }; if (!where_clause.empty()) { sql += space_if_required(where_clause); sql += where_clause; } sql += &quot;;&quot;; return sql; } } // sql </code></pre> <p>Example main.cpp:</p> <pre><code>/* This example assumes you have created a database as follows: sqlite3.exe mydb.db CREATE TABLE test (name TEXT, age INTEGER, photo BLOB); */ #include &quot;sqlite.hpp&quot; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; using namespace sql; int main() { sql::sqlite db; int rc = db.open(&quot;mydb.db&quot;); std::cout &lt;&lt; &quot;db.open returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // picture from https://en.wikipedia.org/wiki/Mickey_Mouse std::ifstream f(&quot;Mickey_Mouse.png&quot;, std::ios::binary); if (!f.good()) { std::cout &lt;&lt; &quot;failed to open Mickey Mouse bitmap file\n&quot;; return 1; } std::vector&lt;uint8_t&gt; buffer(std::istreambuf_iterator&lt;char&gt;(f), {}); std::vector&lt;sql::column_values&gt; params { {&quot;name&quot;, &quot;Mickey Mouse&quot;}, {&quot;age&quot;, 12}, {&quot;photo&quot;, buffer} }; for (const auto&amp; param : params) { std::cout &lt;&lt; &quot;inserting param: &quot; &lt;&lt; param &lt;&lt; std::endl; } rc = db.insert_into(&quot;test&quot;, params.begin(), params.end()); std::cout &lt;&lt; &quot;db.insert_into(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; int lastrowid = 0; if (rc == SQLITE_OK) { lastrowid = db.last_insert_rowid(); std::cout &lt;&lt; &quot;inserted into rowid: &quot; &lt;&lt; lastrowid &lt;&lt; std::endl; } // let us now update this record std::vector&lt;sql::column_values&gt; updated_params{ {&quot;name&quot;, &quot;Donald Duck&quot;}, {&quot;age&quot;, 23} }; const std::vector&lt;where_binding&gt;&amp; bindings{ {&quot;rowid&quot;, lastrowid} }; rc = db.update(&quot;test&quot;, updated_params.begin(), updated_params.end(), &quot;WHERE rowid=:rowid&quot;, bindings.begin(), bindings.end()); std::cout &lt;&lt; &quot;db.update(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // try SELECT std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; // simplest way //rc = db.select_star(&quot;test&quot;, results); // using select_column to specifically display sqlite table rowid //rc = db.select_columns(&quot;test&quot;, { &quot;rowid&quot;, &quot;name&quot;, &quot;age&quot;, &quot;photo&quot; }, {}, results); // Or pass in rowid and * to display rowid and all other columns //rc = db.select_columns(&quot;test&quot;, { &quot;rowid&quot;, &quot;*&quot; }, {}, results); const std::vector&lt;where_binding&gt;&amp; select_bindings{ {&quot;name&quot;, &quot;Don%&quot;} }; std::vector&lt;std::string&gt; cols{ &quot;rowid&quot;, &quot;*&quot; }; rc = db.select_columns(&quot;test&quot;, cols.begin(), cols.end(), &quot;WHERE name LIKE :name&quot;, select_bindings.begin(), select_bindings.end(), results); std::cout &lt;&lt; &quot;db.select_columns(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // print rows int i = 0; for (const auto&amp; row : results) { std::cout &lt;&lt; &quot;row&quot; &lt;&lt; ++i &lt;&lt; &quot;: &quot; &lt;&lt; row &lt;&lt; std::endl; } // finally delete row added const std::vector&lt;where_binding&gt;&amp; delete_bindings { {&quot;rowid&quot;, lastrowid} }; rc = db.delete_from(&quot;test&quot;, &quot;WHERE rowid=:rowid&quot;, delete_bindings.begin(), delete_bindings.end()); std::cout &lt;&lt; &quot;db.delete_from(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; // code below inserts into data into a table that does not exist // test to insert into an invalid column std::vector&lt;sql::column_values&gt; bad_params{ {&quot;nave&quot;, &quot;Tanner&quot;}, {&quot;address8&quot;, &quot;3 The Avenue&quot;}, {&quot;postcoode&quot;, &quot;GU17 0TR&quot;} }; rc = db.insert_into(&quot;contacts&quot;, bad_params.begin(), bad_params.end()); std::cout &lt;&lt; &quot;db.insert_into(...) returned: &quot; &lt;&lt; rc &lt;&lt; std::endl; if (rc != SQLITE_OK) { std::cout &lt;&lt; db.get_last_error_description() &lt;&lt; std::endl; } } </code></pre> <p>test.cpp:</p> <pre><code>#include &quot;sqlite.hpp&quot; #include &quot;sqlite3.h&quot; // required for db_initial_setup #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;cstdio&gt; #include &lt;sstream&gt; #include &lt;cstdio&gt; #include &lt;filesystem&gt; #include &lt;algorithm&gt; #include &quot;gtest/gtest.h&quot; using namespace sql; namespace { void db_initial_setup() { if (remove(&quot;contacts.db&quot;) != 0) { perror(&quot;Error deleting contacts.db&quot;); } // we create using c library so not using any of the code to exercise sqlite3* db; char* err_msg = 0; int rc = sqlite3_open(&quot;contacts.db&quot;, &amp;db); if (rc != SQLITE_OK) { std::cerr &lt;&lt; &quot;Cannot open database: &quot; &lt;&lt; sqlite3_errmsg(db) &lt;&lt; std::endl; sqlite3_close(db); FAIL() &lt;&lt; &quot;Cannot open database for testing\n&quot;; return; } const char* sql[] = { &quot;DROP TABLE IF EXISTS contacts;&quot; &quot;CREATE TABLE contacts (name TEXT, company TEXT, mobile TEXT, ddi TEXT, switchboard TEXT, address1 TEXT, address2 TEXT, address3 TEXT, address4 TEXT, postcode TEXT, email TEXT, url TEXT, category TEXT, notes TEXT);&quot; &quot;CREATE INDEX idx_mobile ON contacts (mobile);&quot; &quot;CREATE INDEX idx_switchboard ON contacts (switchboard);&quot; &quot;CREATE INDEX idx_ddi ON contacts (ddi);&quot;, &quot;CREATE TABLE calls(timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, callerid TEXT, contactid INTEGER);&quot;, &quot;INSERT INTO contacts (name, mobile, switchboard, address1, address2, address3, postcode, email, url, category) VALUES(\&quot;Test Person\&quot;, \&quot;07788111222\&quot;, \&quot;02088884444\&quot;, \&quot;House of Commons\&quot;, \&quot;Westminster\&quot;, \&quot;London\&quot;, \&quot;SW1A 0AA\&quot;, \&quot;test@house.co.uk\&quot;, \&quot;www.house.com\&quot;, \&quot;Supplier\&quot;);&quot;, &quot;INSERT INTO calls (callerid, contactid) VALUES(\&quot;07788111222\&quot;, 1);&quot; }; size_t num_commands = sizeof(sql) / sizeof(char*); for (size_t i = 0; i &lt; num_commands; ++i) { rc = sqlite3_exec(db, sql[i], 0, 0, &amp;err_msg); if (rc != SQLITE_OK) { std::cerr &lt;&lt; &quot;SQL error: &quot; &lt;&lt; err_msg &lt;&lt; std::endl; sqlite3_free(err_msg); sqlite3_close(db); } } sqlite3_close(db); } const std::string filename(&quot;contacts.db&quot;); std::vector&lt;std::string&gt; tables{ &quot;contacts&quot;, &quot;calls&quot; }; } class sqlite_cpp_tester : public ::testing::Test { public: void SetUp() { db_initial_setup(); } }; TEST_F(sqlite_cpp_tester, given_a_valid_db_file_open_close_return_success) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); EXPECT_EQ(db.close(), SQLITE_OK); } TEST_F(sqlite_cpp_tester, given_a_valid_insert_select_returns_same_as_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const std::vector&lt;sql::column_values&gt; fields { {&quot;name&quot;, &quot;Mickey Mouse&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755123456&quot;}, {&quot;ddi&quot;, &quot;01222333333&quot;}, {&quot;switchboard&quot;, &quot;01222444444&quot;}, {&quot;address1&quot;, &quot;1 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;mickey@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;delightful mouse&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields.begin(), fields.end()), SQLITE_OK); int lastrowid = db.last_insert_rowid(); const std::vector&lt;sql::where_binding&gt;&amp; bindings { {&quot;rowid&quot;, lastrowid} }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_star(&quot;contacts&quot;, &quot;WHERE rowid=:rowid&quot;, bindings.begin(), bindings.end(), results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], fields[13].column_value); } TEST_F(sqlite_cpp_tester, given_a_valid_insert_then_update_select_returns_same_as_updated) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const std::vector&lt;sql::column_values&gt; fields{ {&quot;name&quot;, &quot;Mickey Mouse&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755123456&quot;}, {&quot;ddi&quot;, &quot;01222333333&quot;}, {&quot;switchboard&quot;, &quot;01222444444&quot;}, {&quot;address1&quot;, &quot;1 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;mickey@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;delightful mouse&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields.begin(), fields.end()), SQLITE_OK); int lastrowid = db.last_insert_rowid(); // UPDATE const std::vector&lt;sql::column_values&gt; updated_fields{ {&quot;name&quot;, &quot;Donald Duck&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755654321&quot;}, {&quot;ddi&quot;, &quot;01222444444&quot;}, {&quot;switchboard&quot;, &quot;01222555555&quot;}, {&quot;address1&quot;, &quot;2 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;donald@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;quackers&quot;} }; const std::vector&lt;where_binding&gt;&amp; update_bindings{ {&quot;rowid&quot;, lastrowid} }; const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; EXPECT_EQ(db.update(&quot;contacts&quot;, updated_fields.begin(), updated_fields.end(), where_clause, update_bindings.begin(), update_bindings.end()), SQLITE_OK); std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; std::vector&lt;std::string&gt; cols { &quot;rowid&quot;, &quot;*&quot; }; EXPECT_EQ(db.select_columns(&quot;contacts&quot;, cols.begin(), cols.end(), &quot;WHERE rowid=:rowid&quot;, update_bindings.begin(), update_bindings.end(), results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], updated_fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], updated_fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], updated_fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], updated_fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], updated_fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], updated_fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], updated_fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], updated_fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], updated_fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], updated_fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], updated_fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], updated_fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], updated_fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], updated_fields[13].column_value); } TEST_F(sqlite_cpp_tester, given_a_single_quote_in_notes_field_select_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const std::vector&lt;sql::column_values&gt; fields{ {&quot;name&quot;, &quot;Sean O'Hennessey&quot;}, {&quot;company&quot;, &quot;Disney&quot;}, {&quot;mobile&quot;, &quot;07755123456&quot;}, {&quot;ddi&quot;, &quot;01222333333&quot;}, {&quot;switchboard&quot;, &quot;01222444444&quot;}, {&quot;address1&quot;, &quot;1 The Avenue&quot;}, {&quot;address2&quot;, &quot;Greystoke&quot;}, {&quot;address3&quot;, &quot;Lower Wirmwood&quot;}, {&quot;address4&quot;, &quot;Baffleshire&quot;}, {&quot;postcode&quot;, &quot;PO21 4RR&quot;}, {&quot;email&quot;, &quot;mickey@disney.com&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;single quote symbol is '&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields.begin(), fields.end()), SQLITE_OK); int lastrowid = db.last_insert_rowid(); const std::vector&lt;where_binding&gt;&amp; update_bindings{ {&quot;rowid&quot;, lastrowid} }; std::vector&lt;std::string&gt; cols{ &quot;rowid&quot;, &quot;*&quot; }; const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;contacts&quot;, cols.begin(), cols.end(), &quot;WHERE rowid=:rowid&quot;, update_bindings.begin(), update_bindings.end(), results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], fields[13].column_value); } TEST_F(sqlite_cpp_tester, given_non_alphanumeric_characters_inserted_select_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const std::vector&lt;sql::column_values&gt; fields{ {&quot;name&quot;, &quot;&lt;----------------------&gt;'&quot;}, {&quot;company&quot;, &quot;D\nisne y&quot;}, {&quot;mobile&quot;, &quot;!!!\&quot;0775512345'''6&quot;}, {&quot;ddi&quot;, &quot;{}====================&quot;}, {&quot;switchboard&quot;, &quot;++++++++++++++++++++++++&quot;}, {&quot;address1&quot;, &quot;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&quot;}, {&quot;address2&quot;, &quot;``````````¬|&quot;}, {&quot;address3&quot;, &quot;;'#:@~&quot;}, {&quot;address4&quot;, &quot;'''''''''''''''''''&quot;}, {&quot;postcode&quot;, &quot;!\&quot;£$%^&amp;*()_+&quot;}, {&quot;email&quot;, &quot;***************************&quot;}, {&quot;url&quot;, &quot;disney.com&quot;}, {&quot;category&quot;, &quot;cartoonist&quot;}, {&quot;notes&quot;, &quot;1\n2\n3\n4\n5\n&quot;} }; EXPECT_EQ(db.insert_into(&quot;contacts&quot;, fields.begin(), fields.end()), SQLITE_OK); int lastrowid = db.last_insert_rowid(); const std::vector&lt;where_binding&gt;&amp; update_bindings{ {&quot;rowid&quot;, lastrowid} }; std::vector&lt;std::string&gt; cols{ &quot;rowid&quot;, &quot;*&quot; }; const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;contacts&quot;, cols.begin(), cols.end(), &quot;WHERE rowid=:rowid&quot;, update_bindings.begin(), update_bindings.end(), results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;name&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;company&quot;], fields[1].column_value); EXPECT_EQ(results[0][&quot;mobile&quot;], fields[2].column_value); EXPECT_EQ(results[0][&quot;ddi&quot;], fields[3].column_value); EXPECT_EQ(results[0][&quot;switchboard&quot;], fields[4].column_value); EXPECT_EQ(results[0][&quot;address1&quot;], fields[5].column_value); EXPECT_EQ(results[0][&quot;address2&quot;], fields[6].column_value); EXPECT_EQ(results[0][&quot;address3&quot;], fields[7].column_value); EXPECT_EQ(results[0][&quot;address4&quot;], fields[8].column_value); EXPECT_EQ(results[0][&quot;postcode&quot;], fields[9].column_value); EXPECT_EQ(results[0][&quot;email&quot;], fields[10].column_value); EXPECT_EQ(results[0][&quot;url&quot;], fields[11].column_value); EXPECT_EQ(results[0][&quot;category&quot;], fields[12].column_value); EXPECT_EQ(results[0][&quot;notes&quot;], fields[13].column_value); } TEST_F(sqlite_cpp_tester, add_integer_value_select_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const std::vector&lt;sql::column_values&gt; fields{ {&quot;callerid&quot;, &quot;0775512345&quot;}, {&quot;contactid&quot;, 2} }; EXPECT_EQ(db.insert_into(&quot;calls&quot;, fields.begin(), fields.end()), SQLITE_OK); const std::vector&lt;where_binding&gt; bindings{ {&quot;contactid&quot;, 2} }; const char* result_cols[] { &quot;timestamp&quot;, &quot;callerid&quot;, &quot;contactid&quot; }; size_t cols_len = sizeof(result_cols) / sizeof(result_cols[0]); const std::string where_clause{ &quot;WHERE rowid=:rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;calls&quot;, result_cols, result_cols+cols_len, &quot;WHERE contactid=:contactid&quot;, bindings.begin(), bindings.end(), results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(results[0][&quot;callerid&quot;], fields[0].column_value); EXPECT_EQ(results[0][&quot;contactid&quot;], fields[1].column_value); // get 3 columns back EXPECT_EQ(results[0].size(), 3u); } // SELECT (using LIKE) TEST_F(sqlite_cpp_tester, add_integer_value_select_like_returns_same_value_inserted) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const sql::column_values fields[] { {&quot;callerid&quot;, &quot;0775512345&quot;}, {&quot;contactid&quot;, 2} }; size_t len = sizeof(fields) / sizeof(fields[0]); EXPECT_EQ(db.insert_into(&quot;calls&quot;, fields, fields + len), SQLITE_OK); const std::vector&lt;where_binding&gt; bindings{ {&quot;callerid&quot;, &quot;077%&quot;} }; std::vector&lt;std::string&gt; cols { &quot;timestamp&quot;, &quot;callerid&quot;, &quot;contactid&quot; }; const std::string where_clause{ &quot;WHERE callerid LIKE :callerid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; EXPECT_EQ(db.select_columns(&quot;calls&quot;, cols.begin(), cols.end(), where_clause, bindings.begin(), bindings.end(), results), SQLITE_OK); EXPECT_EQ(results.size(), 2u); EXPECT_EQ(std::get&lt;std::string&gt;(results[0][&quot;callerid&quot;]), &quot;07788111222&quot;); EXPECT_EQ(std::get&lt;int&gt;(results[0][&quot;contactid&quot;]), 1); EXPECT_EQ(results[1][&quot;callerid&quot;], fields[0].column_value); EXPECT_EQ(results[1][&quot;contactid&quot;], fields[1].column_value); // get 3 columns back EXPECT_EQ(results[0].size(), 3u); } // GETCALLS TEST_F(sqlite_cpp_tester, join_returning_data_from_two_tables_returns_correct_data) { sql::sqlite db; EXPECT_EQ(db.open(&quot;contacts.db&quot;), SQLITE_OK); const std::vector&lt;std::string&gt; fields { &quot;calls.timestamp&quot;, &quot;contacts.name&quot;, &quot;calls.callerid&quot;, &quot;contacts.url&quot; }; const std::string where_clause{ &quot;LEFT JOIN contacts ON calls.contactid = contacts.rowid&quot; }; std::vector&lt;std::map&lt;std::string, sql::sqlite_data_type&gt;&gt; results; const std::vector&lt;where_binding&gt; bindings {}; // none required EXPECT_EQ(db.select_columns(&quot;calls&quot;, fields.begin(), fields.end(), where_clause, bindings.begin(), bindings.end(), results), SQLITE_OK); EXPECT_EQ(results.size(), 1u); EXPECT_EQ(std::get&lt;2&gt;(results[0][&quot;callerid&quot;]), &quot;07788111222&quot;); EXPECT_EQ(std::get&lt;2&gt;(results[0][&quot;name&quot;]), &quot;Test Person&quot;); EXPECT_EQ(std::get&lt;2&gt;(results[0][&quot;url&quot;]), &quot;www.house.com&quot;); EXPECT_NE(std::get&lt;2&gt;(results[0][&quot;timestamp&quot;]), &quot;&quot;); } int main(int argc, char **argv) { testing::InitGoogleTest(&amp;argc, argv); return RUN_ALL_TESTS(); } </code></pre>
[]
[ { "body": "<p>Just a quick note: the begin and end iterator might be different types, as a recent improvement in STL provides for <code>end</code> to be a special &quot;sentinel&quot; type that's different from the normal iterator.</p>\n<p>If you're using C++20, you can use Concepts to declare the template arguments, to ensure that they are iterators (and sentinels, respectively) <em>to</em> the proper type of element and having the required feature set (e.g. forward iterators OK, or do you need random access iterators? Single pass iteration OK? There is a hierarchy of iterator categories.)</p>\n<p>Your tests still use <code>std::vector</code> for all the examples. Change one of them to use a plain array. Change another to use <code>std::deque</code> or a Boost container, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:16:49.433", "Id": "260561", "ParentId": "260527", "Score": "1" } } ]
{ "AcceptedAnswerId": "260561", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T10:56:54.273", "Id": "260527", "Score": "2", "Tags": [ "c++", "iterator", "sqlite" ], "Title": "Adding iterators to C++ sqlite wrapper class" }
260527
<p>I read some answers here on stack exchange, but none really &quot;hits the nail on the head&quot; about where to throw exceptions, where I shouldn't and where to catch them.</p> <p>the idea that an exception should be thrown in exceptional cases is very vague, for example, if I can't find a user in my data source (repository) I can't continue the flow of my code, can this be considered exceptional?</p> <p>I also understand that there are caveats about flow control with exceptions, for me it does not seem right to use try/catch within the service, to catch all the exceptions that a repository/adapter/whatever may throw to control what to do next.</p> <p>based on this, a code example with a &quot;service&quot; and a controller calling the service and catching all of the service exceptions:</p> <p><strong>Service:</strong></p> <pre><code>class CheckUserUltraSecretInformation { public function __construct( private CachedUserDataRepository $cachedDataRepository, ) { } public function handle(string $document) { $cachedUserData = $this-&gt;cachedDataRepository-&gt;findByDocument($document); if (empty($cachedUserData)) { throw new CachedUserDataNotFoundException('User Cached information not found, cannot proceed'); } if ($cachedUserData-&gt;hasExpired()) { throw new CachedUserDataHasExpiredException('Cached user data is expired'); } // return ultra secret information } } </code></pre> <p><strong>Controller:</strong></p> <pre><code>class UserSecretInformationController { public function __construct( private CheckUserUltraSecretInformation $checkUserUltraSecretInformation) { } public function checkUserInformation(Request $request) { $document = $request-&gt;input('document'); try { $userUltraSecretInformation = $this-&gt;checkUserUltraSecretInformation-&gt;handle($document); } catch (CachedUserDataNotFoundException $exception) { // return json response with http code 400 } catch (CachedUserDataExpiredException $exception) { //returns json response with http code 500 } } } </code></pre> <ul> <li><p>Is it &quot;correct&quot; that my repository does not throw exceptions, and only returns <code>null/false</code> when it cannot return an entity? if not, what is the problem?</p> </li> <li><p>if my repository throws exceptions, should my service capture them and re-launch them as service exceptions? is this considered flow control?</p> </li> <li><p>Are the outer layers the &quot;most correct&quot; to capture and handle exceptions? in my example the controller is used, can It know the name of the services/use-cases exceptions?</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T15:04:13.247", "Id": "518776", "Score": "2", "body": "We don't do general \"best-practice\" questions or example code on Code Review. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709) and [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:19:08.380", "Id": "531463", "Score": "0", "body": "This is my view on the matter, maybe it helps: **Point 1)** All errors and exceptions thrown by the system in case of a failure (for ex. in case of \"db connection could not be established\" - see [PDO's Errors/Exceptions](https://www.php.net/manual/en/pdo.construct.php#refsect1-pdo.construct-errors)) should be let to propagate to the entry point of your application. Only at this level should they be handled, like this:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:19:24.177", "Id": "531465", "Score": "0", "body": "**1.a)** In a _\"production\"_ application environment, only a general, user-friendly message should be displayed to the user: \"An error occurred during your request. Please try again later\". At the same time the detailed error or exception should be logged, for later debug purposes. Recommendation for PHP 7+: Any raised [Error](https://www.php.net/manual/en/class.error.php) should be transformed to [ErrorException](https://www.php.net/manual/en/class.errorexception.php) prior to handling it as previously said." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:20:08.427", "Id": "531466", "Score": "0", "body": "**1.b)** In a _\"development\"_ application environment, the detailed error or exception should be both displayed to the user and logged, for later debug purposes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:21:19.233", "Id": "531467", "Score": "0", "body": "Recommendation: Use the error handling functions, as following: **a)** Use [register_shutdown_function](https://www.php.net/manual/en/function.register-shutdown-function.php) for handling all fatal errors ([here](https://exceptionshub.com/how-do-i-catch-a-php-fatal-error-2.html) are some examples). Fatal errors are those error types which can not be handled with a user-defined function (like \"set_error_handler\"). The list of fatal errors is presented [here](https://www.php.net/manual/en/function.set-error-handler.php#refsect1-function.set-error-handler-description)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:21:51.320", "Id": "531468", "Score": "0", "body": "and [here](https://www.php.net/manual/en/errorfunc.constants.php). **b)** Use [set_error_handler](https://www.php.net/manual/en/function.set-error-handler.php) for handling all errors, except the fatal ones. Here takes place the transformation of _Error_'s to _ErrorException_'s, e.g. _set_error_handler_ only throws an _ErrorException_. **c)** Use [set_exception_handler](https://www.php.net/manual/en/function.set-exception-handler.php) for handling all exceptions (including the _ErrorException_'s thrown by _set_error_handler_). Instead of _set_exception_handler_ you could use" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:22:33.637", "Id": "531469", "Score": "0", "body": "a _try/catch_ block at the entry point of your application, in order to catch and handle all exceptions which arrive at this level." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:23:02.733", "Id": "531470", "Score": "0", "body": "**Point 2)** In the course of developing your application code, you, as developer, will throw exceptions in situations where certain conditions imposed by the code structure/programming rules/configuration are not met. Such cases imply that the exception details should not be known by the application user, but only by you, the developer. So, such exceptions should be handled as presented at point 1) above, as well. For such cases you can use both [Predefined Exceptions](https://www.php.net/manual/en/reserved.exceptions.php)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:23:28.570", "Id": "531471", "Score": "0", "body": "and [SPL Exceptions](https://www.php.net/manual/en/spl.exceptions.php). For example, when you create a Route object (in order to add it to a predefined list of routes), but you forget to assign a controller name to the route handler:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:23:51.497", "Id": "531472", "Score": "0", "body": "`private function resolveController(RouteInterface $route): string|array|object { $handler = $route->getHandler(); $controller = array_key_exists('controller', $handler) ? $handler['controller'] : null; if (!isset($controller)) { throw new \\UnexpectedValueException('The route handler of the route \"' . $route->getPattern() . '\" must have a key \"controller\" and a value of type string, array, or object assigned to it.'); } return $controller; }`. Another example: You, the developer, want to render a template file (in a controller, for example - as most web frameworks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:24:04.440", "Id": "531473", "Score": "0", "body": "are doing it, unfortunately), but forget to create it. The code of the template renderer of your choice will/should check this and raise a corresponding exception: `private function validateTemplateFile(string $filename): static { if (!file_exists($filename)) { throw new \\RuntimeException('The template file \"' . $filename . '\" could not be found.'); } }`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:24:15.887", "Id": "531474", "Score": "0", "body": "**Point 3)** Certain errors need to be shown to the user of the application: \"book not found\" (on searching a book in a collection), \"user already exists\" (when adding a new user), \"not a valid e-mail address\" (in a login form), etc. These errors are thrown in form of _custom exceptions_ and are handled in the presentation layer of the application (controller & view) - as you did in your codes from the Code Review question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:24:52.563", "Id": "531475", "Score": "0", "body": "To _\"I also understand [...] to control what to do next\"_ and to _\"Is it \"correct\" that my repository does not throw exceptions [...]?\"_: A [repository](https://www.martinfowler.com/eaaCatalog/repository.html) or a [data mapper](https://www.martinfowler.com/eaaCatalog/dataMapper.html) should not throw any custom exceptions. Therefore it will throw only system failure errors or exceptions, which will be handled as presented at point 1) above. The codes presented by you in the CR questions are correct: the service throws custom exceptions, dependent on the results returned by the repository" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:25:02.537", "Id": "531476", "Score": "0", "body": "(null, false, true, etc), and the controller (in your case) catches them, in order to present them to the user (in your case as json encoded data)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:25:12.743", "Id": "531477", "Score": "0", "body": "To _\"Are the outer layers the \"most correct\" to capture and handle exceptions?\"_: only in the cases 1) and 2) above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T09:25:28.610", "Id": "531478", "Score": "0", "body": "To _\"in my example the controller is used, can It know the name of the services/use-cases exceptions?\"_: Of course, because it wants to present them to the user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T12:11:43.270", "Id": "531710", "Score": "0", "body": "In regard of error reporting in PHP I recommend [this article](https://phpdelusions.net/articles/error_reporting)." } ]
[ { "body": "<blockquote>\n<p>the idea that an exception should be thrown in exceptional cases is very vague, for example, if I can't find a user in my data source (repository) I can't continue the flow of my code, can this be considered exceptional?</p>\n</blockquote>\n<p>My personal approach is to raise an exception if I encounter a scenario where I make a <code>truthy</code> assumption during code execution, but that assumption turns out to be <code>falsey</code>. So in your example, if you can't continue the expected code execution path without a valid <code>user</code> object returned from the repository, throw an exception at the point where having a <code>user</code> assumption turns out to be <code>false</code>.</p>\n<p>Where to initially throw an exception and where to catch depends on the use case. The rule of thumb I tend to follow is to throw an exception as soon as I can't continue or recover the desired code execution path, then allow that exception to propagate back up the stack to a place that understands how to handle that exception. Don't catch an exception if all you're going to do is re-throw.</p>\n<blockquote>\n<p>Is it &quot;correct&quot; that my repository does not throw exceptions, and only returns null/false when it cannot return an entity? if not, what is the problem?</p>\n</blockquote>\n<p>I would say this is acceptable. Occasionally, a <code>falsey</code> response from your repository is not exceptional and is perfectly acceptable. I would also argue it's not the responsibility of the repository to decide if a <code>falsey</code> response is acceptable or not (for example when checking the existence of a record).</p>\n<blockquote>\n<p>if my repository throws exceptions, should my service capture them and re-launch them as service exceptions? is this considered flow control?</p>\n</blockquote>\n<p>Catch an exception where you intend to handle that exception. Sometimes, it makes sense to catch and re-throw an exception, such as in cases where you want to add information to the exception or cast it to a more meaningful exception for the caller above.</p>\n<blockquote>\n<p>Are the outer layers the &quot;most correct&quot; to capture and handle exceptions? in my example the controller is used, can It know the name of the services/use-cases exceptions?</p>\n</blockquote>\n<p>Catch and handle where it makes sense. In your case, it makes sense as the controller is the last caller before returning a response to the client and it's not the responsibility of your service to format an error response for the caller.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T14:42:05.233", "Id": "260739", "ParentId": "260529", "Score": "5" } }, { "body": "<p>Throw an exception when your code can't proceed the happy path without some information, or prerequisites. For example, in a hypothetical method <code>makeSale(int $userId)</code> you would throw an exception if there is no matching record for the given ID. You can't return a meaningful value or perform the required action, so you need to throw. If the ID comes from user input, then the user input should be validated before to make sure that it is a real user.</p>\n<p>In your example, it looks like you are trying to perform validations for user input. Exceptions are not a good way to do it, although possible. Validations should return boolean true or false to the controller, and then the controller returns a response to the user with an explanatory message. Don't return code 500 for validations; that code is meant for server errors, not user errors. When a user provides wrong information then they need to see an explanatory message.</p>\n<p>Expired document or invalid document number are validation errors due to invalid input from the user. This is not a server error. Your controller needs to call the right validation methods that will tell you whether the input is correct or not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:22:38.980", "Id": "262799", "ParentId": "260529", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T13:45:37.830", "Id": "260529", "Score": "4", "Tags": [ "php", "object-oriented", "error-handling", "repository" ], "Title": "Should i throw exceptions in the service layer or repository, and catch it on the controller?" }
260529
<p>I wanted to write a program in python which it scans the RAM of a computer, by displaying the services and the executables.</p> <pre><code>import psutil import wmi from time import sleep from progress.bar import Bar # Connecting c = wmi.WMI() # stock here Process Id proc = [] # function to get the Size def get_size(bytes, suffix=&quot;B&quot;): factor = 1028 for unit in[&quot;&quot;,&quot;K&quot;,&quot;M&quot;,&quot;G&quot;,&quot;T&quot;,&quot;P&quot;]: if bytes &lt; factor: return f&quot;{bytes:.2f} {unit}{suffix}&quot; bytes /= factor # End print(&quot;Scanning RAM: \n&quot;) print(&quot;system virtual memory: \n&quot;) # Return statistics about system memory usage with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar: for i in range(100): sleep(0.02) svmem = psutil.virtual_memory() # physical memory usage bar.next() # to calculate percentage of available memory avmem = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total prcntg = '{:.1f} %'.format(avmem) bar.finish() # put the object in a dictionary mem = {'Total': get_size(svmem.total), 'Percentage-available': prcntg, 'Available': get_size(svmem.available), 'Percentage-used': f'{svmem.percent} %', 'Used': get_size(svmem.used), 'Free': get_size(svmem.free)} print(mem) # End print(&quot;\n&quot;) print(&quot;system swap memory: \n&quot;) # Return system swap memory statistics as a named tuple including the following fields with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar: for i in range(100): sleep(0.02) swap = psutil.swap_memory() # the percentage usage calculated as (total - available) / total * 100 bar.next() bar.finish() mem2 = {'Total': get_size(swap.total), 'Used': get_size(swap.used), 'Free': get_size(swap.free), 'Percentage': f'{swap.percent} %'} print(mem2) # End ''' # Return an iterator yielding a WindowsService class instance for all Windows services installed. # Get a Windows service by name, returning a WindowsService instance. with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar: for i in range(100): sleep(0.02) winserv = list(psutil.win_service_iter()) s = psutil.win_service_get('alg') # windows service by name bar.next() bar.finish() print(winserv) print(&quot;\n&quot;) print(s.as_dict()) # End ''' print(&quot;\n&quot;) print(&quot;Services: \n&quot;) # Get all Windows services using the WMI module with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar: for i in range(100): sleep(0.02) bar.next() print(&quot;ID: Name:\n&quot;) for process in c.Win32_Process (): print (f&quot;{process.ProcessId} {process.Name}&quot;) bar.finish() # Get get a specific Windows service for process in c.Win32_Process (name=&quot;notepad.exe&quot;): print (f&quot;{process.ProcessId} {process.Name}&quot;) # End # calculate how much Processes are runnig for process in c.Win32_Process(): proc.append(process.ProcessId) print(f&quot;{len(proc)} Processes are running in your Device.&quot;) # End </code></pre> <p>is it correct?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T15:00:29.547", "Id": "260530", "Score": "1", "Tags": [ "python" ], "Title": "scan the RAM of a computer, displaying the services and executables" }
260530
<p>I want to have dynamic continuous block of memory for different types, that inherit from single base class. I've written structure for that purpose. I know I play with a fire here, but I would like to know how dangerous it is to use this structure. Each element stored in DynamicPool must inherit from Base to support copying. I store additional vector of size_t , it stores offsets in memory of elements to support indexing.</p> <p>This is header file:</p> <pre><code>class DynamicPool { public: struct Base { virtual ~Base() = default; virtual void OnCopy(uint8_t* buffer) = 0; }; public: DynamicPool(uint32_t capacity = 0); DynamicPool(const DynamicPool&amp; other); DynamicPool(DynamicPool&amp;&amp; other) noexcept; ~DynamicPool(); template &lt;typename T&gt; void Push(const T&amp; elem) { static_assert(std::is_base_of&lt;Base, T&gt;::value, &quot;BaseType is not base type of type T&quot;); if (m_Size + sizeof(T) &gt; m_Capacity) reallocate(sizeof(T)); new(&amp;m_Data[m_Size])T(elem); m_Handles.push_back(m_Size); m_Size += sizeof(T); } template &lt;typename T, typename ...Args&gt; void Emplace(Args&amp;&amp; ...args) { static_assert(std::is_base_of&lt;Base, T&gt;::value, &quot;BaseType is not base type of type T&quot;); if (m_Size + sizeof(T) &gt; m_Capacity) reallocate(sizeof(T)); new(&amp;m_Data[m_Size])T(std::forward&lt;Args&gt;(args)...); m_Handles.push_back(m_Size); m_Size += sizeof(T); } void Erase(size_t index); template &lt;typename T&gt; T&amp; Get(size_t index) { static_assert(std::is_base_of&lt;Base, T&gt;::value, &quot;BaseType is not base type of type T&quot;); return *reinterpret_cast&lt;T*&gt;(&amp;m_Data[m_Handles[index]]); } template &lt;typename T&gt; const T&amp; Get(size_t index) const { static_assert(std::is_base_of&lt;Base, T&gt;::value, &quot;BaseType is not base type of type T&quot;); return *reinterpret_cast&lt;T*&gt;(&amp;m_Data[m_Handles[index]]); } Base&amp; Back(); const Base&amp; Back() const; size_t Size() const { return m_Handles.size(); } Base&amp; operator[](size_t index); const Base&amp; operator[](size_t index) const; private: void destroy(); void reallocate(size_t minSize); private: size_t m_Size; size_t m_Capacity; uint8_t* m_Data; std::vector&lt;size_t&gt; m_Handles; static constexpr size_t sc_CapacityMultiplier = 2; }; </code></pre> <p>This is cpp:</p> <pre><code>DynamicPool::DynamicPool(uint32_t capacity) : m_Size(0), m_Capacity(capacity) { m_Data = nullptr; if (m_Capacity) m_Data = new uint8_t[m_Capacity]; } DynamicPool::DynamicPool(const DynamicPool&amp; other) : m_Size(other.m_Size), m_Capacity(other.m_Capacity) { destroy(); m_Handles = other.m_Handles; m_Data = new uint8_t[m_Capacity]; for (size_t handle : m_Handles) { Base* base = reinterpret_cast&lt;Base*&gt;(&amp;other.m_Data[m_Capacity]); base-&gt;OnCopy(&amp;m_Data[handle]); } } DynamicPool::DynamicPool(DynamicPool&amp;&amp; other) noexcept : m_Size(other.m_Size), m_Capacity(other.m_Capacity) { destroy(); m_Handles = std::move(other.m_Handles); m_Data = other.m_Data; other.m_Data = nullptr; other.m_Size = 0; other.m_Capacity = 0; } DynamicPool::~DynamicPool() { destroy(); } void DynamicPool::Erase(size_t index) { size_t handle = m_Handles[index]; Base* base = reinterpret_cast&lt;Base*&gt;(&amp;m_Data[handle]); base-&gt;~Base(); if (index + 1 &lt; m_Handles.size()) { size_t elementSize = m_Handles[index + 1] - handle; m_Size -= elementSize; for (size_t i = index + 1; i &lt; m_Handles.size(); ++i) { size_t nextHandle = m_Handles[i]; m_Handles[i] -= elementSize; Base* next = reinterpret_cast&lt;Base*&gt;(&amp;m_Data[nextHandle]); next-&gt;OnCopy(&amp;m_Data[handle]); handle = nextHandle; } } m_Handles.erase(m_Handles.begin() + index); } DynamicPool::Base&amp; DynamicPool::Back() { return *reinterpret_cast&lt;Base*&gt;(&amp;m_Data[m_Handles.back()]); } const DynamicPool::Base&amp; DynamicPool::Back() const { return *reinterpret_cast&lt;Base*&gt;(&amp;m_Data[m_Handles.back()]); } DynamicPool::Base&amp; DynamicPool::operator[](size_t index) { return *reinterpret_cast&lt;Base*&gt;(&amp;m_Data[m_Handles[index]]); } const DynamicPool::Base&amp; DynamicPool::operator[](size_t index) const { return *reinterpret_cast&lt;Base*&gt;(&amp;m_Data[m_Handles[index]]); } void DynamicPool::destroy() { if (m_Data) { for (size_t handle : m_Handles) { Base* base = reinterpret_cast&lt;Base*&gt;(&amp;m_Data[handle]); base-&gt;~Base(); } delete[]m_Data; } } void DynamicPool::reallocate(size_t minSize) { m_Capacity = minSize + (m_Capacity * sc_CapacityMultiplier); uint8_t* tmp = new uint8_t[m_Capacity]; if (m_Data) { for (size_t handle : m_Handles) { Base* base = reinterpret_cast&lt;Base*&gt;(&amp;m_Data[handle]); base-&gt;OnCopy(&amp;tmp[handle]); } delete[] m_Data; } m_Data = tmp; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:09:24.197", "Id": "514326", "Score": "0", "body": "Just a quick comment: use `std::byte` instead of `uint8_t`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T18:18:36.703", "Id": "260536", "Score": "2", "Tags": [ "c++", "memory-management", "memory-optimization" ], "Title": "Dynamic heterogeneous container" }
260536
<p>I was working on an Limit Order Book structure in JS and came up with this algorithm. I am pretty sure this must have already been implemented but couldn't even find a clue over the web.</p> <p>The thing is, it's very fast especially when you have an array of many duplicate items. However the real beauty is, after inserting <code>k</code> new items into an array of already sorted <code>n</code> items the pseudo sort (explained below) takes only <code>O(k)</code> and sort takes only <code>O(n+k)</code>. To achieve this i keep a pseudo sorted array of <code>m</code> items in a sparse array where <code>m</code> is the number of unique items.</p> <p>Take for instance we need to sort <code>[42,1,31,17,1453,5,17,0,5]</code> where <code>n</code> is 9 and then we just use values as keys and construct a sparse array (Pseudo Sorted) like;</p> <pre><code>Value: 1 1 2 2 1 1 1 Index: 0 1 5 17 31 42 1453 </code></pre> <p>Where <code>Value</code> keeps the repeat count. I think now you start to see where I am getting at. JS have a fantastic ability. In JS accessing the sparse array keys can be very fast by jumping over the non existent ones. To achieve this you either use a <code>for in</code> loop of <code>Object.keys()</code>.</p> <p>So you can keep your sparse (pseudo sorted) array to insert new items and they will always be kept in pseudo sorted state having all insertions and deletions done in <code>O(1)</code>. Whenever you need a real sorted array just construct it in <code>O(n)</code>. Now this is very important in a Limit Order Book implementation because say you have to respond to your clients with the top 100 bids and bottom 100 asks in every 500ms over a web socket connection, now you no longer need to sort the whole order book list again even if it gets updated with many new bids and asks continuously.</p> <p>So here is <code>sparseSort</code> code which could possibly be trimmed up by employing <code>for</code> loops instead of <code>.reduce</code>s etc. Still beats Radix and <code>Array.prototype.sort()</code>.</p> <pre><code>function sparseSort(arr){ var tmp = arr.reduce((t,r) =&gt; t[r] ? (t[r]++,t) : (t[r]=1,t),[]); return Object.keys(tmp) .reduce((a,k) =&gt; { for (var i = 0; i &lt; tmp[k]; i++) a.push(+k); return a; },[]); } </code></pre> <p><a href="https://jsben.ch/s6Ld2" rel="nofollow noreferrer">Here you can see a bench against <code>Array.prototype.sort()</code> and <code>radixSort</code></a>. I just would like to know if this is reasonable and what might be the handicaps involved.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:19:14.447", "Id": "514328", "Score": "2", "body": "The radix sort in https://jsben.ch/s6Ld2 is very poorly written. This https://jsben.ch/96YZc bench has a better (not best) example of a radix sort" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T17:08:49.997", "Id": "514344", "Score": "0", "body": "@Blindman67 Yes that seems to make difference however there many curious things in play (Chrome or new Edge). You may test `radixSort` against `sparseSort` on dev tools snippets with `performance.now()` and try `data = $setOf(12500, () => $randI(12500))` and`data = $setOf(13000, () => $randI(13000))` to notice a huge difference. Apart from such breaking points Radix Sort and Sparse Sort give very close results however when you enforce duplicates like `data = $setOf(12500, () => $randI(125))` then it suddenly becomes a different game." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T17:51:11.247", "Id": "514351", "Score": "0", "body": "I'm afraid this is a modification of the counting sort" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T18:01:29.743", "Id": "514353", "Score": "0", "body": "@Norhther Well it is and it is not. It seems to be a union of Radix Sort and Count Sort. You may read more in my self answer. Especially the last paragraph." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T18:06:22.203", "Id": "514354", "Score": "0", "body": "@Redu I don't think this is Radix (I mean the algorithm, not the actual implementation). I think this is just the natural improvement of Counting Sort, just storing the actual elements and not the full range" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T18:10:01.347", "Id": "514356", "Score": "0", "body": "@Norhther The code that you see has nothing to do with Radix sort but the real question is, under the hood how exactly the sparse array indices end up being served in an orderly fashion. This... most possibly turns out to be Radix Sort implementation of V8 engine that kick in when things happen. You may read my self answer below for more information." } ]
[ { "body": "<p>I think you re-invented <a href=\"https://www.geeksforgeeks.org/counting-sort/\" rel=\"noreferrer\">counting sort</a>, but with some small differences. Also you probably need to sort your sparse array keys before iterating over them so that's O(k log k) at least unless your possible range of values is small (let's call it N) so you can just try all N values and it will be O( N ).</p>\n<p>Performance wise, it's hard to beat if you have a small range of value N.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:15:20.830", "Id": "514295", "Score": "0", "body": "Iterating over the sparse array keys in JS make them come in a sorted manner as string values so i do `+k`. However we best care there are no other properties than indices in order to prevent an unexpected failure. So i think the sparse array must be kept private, totally in our control, away from prying eyes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:17:30.037", "Id": "514296", "Score": "3", "body": "Ok well, I'm not familiar with JavaScript, but if it's already sorted, somebody already did the sort for you at some point (the language). It means that inserting into the array probably cost at least O( log k ) (more if they shift stuff around) and you do it k times so it ends up costing O (k log k). After that I agree that reading the list cost only O ( k )." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:24:48.187", "Id": "514297", "Score": "0", "body": "Just checked [counting sort](https://www.geeksforgeeks.org/counting-sort/) and yes that seems basically the same idea but there is a big difference. We have a sparse array here. So no indices among non existent elements. I mean `1453` is **right** after `42` here. That's why it is fast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T22:30:46.580", "Id": "514298", "Score": "2", "body": "It's not necessarily faster, actually it's slower in many cases. They just made a different trade-off. If your counting array is sorted.. You paid that price. There is no free lunch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T22:35:30.763", "Id": "514299", "Score": "1", "body": "Let me break it down a little. If we look at this logically, without even knowing how JavaScript does it under the hood, we can still see why. In your code you start by counting and placing the count in a \"sparse array\" here : \"var tmp = arr.reduce((t,r) => t[r] ? (t[r]++,t) : (t[r]=1,t),[]);\". If you print that array, you'll see that it's already sorted. It means that something sorted it for you. Optimistic worst case, you are looking at O ( k log k ).. but I suspect it's actually O ( k ^ 2 ) with all the shifting around needed to insert the new elements in the right position." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T22:36:55.977", "Id": "514300", "Score": "1", "body": "Meanwhile for counting sort, they just insert it into their array at O( 1 ) cost, and then they go through their array at O ( N ) cost. Overall, it's probably always better to use traditional counting sort unless you have a very big range ( N ) and not a lot of elements ( k )." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T10:43:49.943", "Id": "514312", "Score": "0", "body": "I think there is kind of free lunch, well at least in this particular case. However it will be very hard to explain how this is possible in a comment so i will post a self answer once i have free time later this afternoon. It's very interesting though." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:02:19.657", "Id": "260540", "ParentId": "260538", "Score": "5" } }, { "body": "<p>So to me this seems to be a really efficient sorting algorithm at least for a very particular case as follows;</p>\n<ol>\n<li>Sorting positive integers only or negative integers only (zero included).</li>\n<li>Works much more efficient if you have duplicates</li>\n<li>Works much more efficient when elements are discontinuous (sparse)</li>\n</ol>\n<p>The Array structure in JS is complicated and in time has been optimized greatly. You may like to <a href=\"https://youtu.be/m9cTaYI95Zc\" rel=\"nofollow noreferrer\">watch this</a> before proceeding any further but i will try to summarize. Depending on their structures there are basically 6 types of arrays.</p>\n<p><a href=\"https://i.stack.imgur.com/KXhds.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KXhds.png\" alt=\"enter image description here\" /></a></p>\n<pre><code>PACKED_SMI_ELEMENTS : [1,2,3]\nPACKED_DOUBLE_ELEMENTS: [1.1,2,3]\nPACKED_ELEMENTS : [1,2,&quot;c&quot;]\n</code></pre>\n<p>These are dense arrays and there are three separate optimization layers for them. Then we have three more types coming with their own optimization layers.</p>\n<pre><code>HOLEY_SMI_ELEMENTS : [1,,3]\nHOLEY_DOUBLE ELEMENTS : [1.1,,3]\nHOLEY_ELEMENTS : [1,,&quot;c&quot;]\n</code></pre>\n<p>In our case we <em>may</em> have a <code>HOLEY_SMI_ELEMENTS</code> type of array at hand. But i think not all <code>HOLEY_SMI_ELEMENTS</code> type arrays are the same. I guess if the gap between the elements are big enough we end up with a <code>NumberDictionary</code> type where the elements are now of <code>DICTIONARY_ELEMENTS</code>. Now most probably we are here. Normally this is very inefficient compared to normal arrays when normal array operations are performed but in this very particular case it shines. <a href=\"https://itnext.io/v8-deep-dives-understanding-array-internals-5b17d7a28ecc\" rel=\"nofollow noreferrer\">Further reading here</a>.</p>\n<p>Now what i couldn't find is, how exactly the number keys (indices) are stored in a <code>NumberDictionary</code> type array. Perhaps balanced BST or Heap with O(log n) access</p>\n<p>OK then can we not use a map to start with..? Perhaps we can but it wont be a <code>NumberDictionary</code> and possibly the map keys are not handled like in <code>NumberDictionary</code>. For example In Haskell there is the Map data type which takes two types like <code>Ord k =&gt; Map k v</code> which says <code>k</code> type is requried to be a member or <code>Ord</code> type class so that we can apply operations like <code>&lt;</code> or <code>&gt;</code> on <code>k</code> type. Map is implemented on Balanced BST. However there is also an IntMap type where keys have to be Integers. This is how it is explained in Data.IntMap reference.</p>\n<blockquote>\n<p>The implementation is based on big-endian patricia trees. This data\nstructure performs especially well on binary operations like union and\nintersection. However, my benchmarks show that it is also (much)\nfaster on insertions and deletions when compared to a generic\nsize-balanced map implementation.</p>\n</blockquote>\n<p>It turns out the mentioned <a href=\"https://en.wikipedia.org/wiki/Radix_tree\" rel=\"nofollow noreferrer\">big-endian patricia trees</a> are in fact Radix Trees. I think once you end up with a <code>NumberDictionary</code> your keys are stored in a Radix Tree. So in this very algorthm, having duplicates in the array enforce you do Radix sort on keys and count sort on values at the same time. This way of sorting in some particular cases in JS might be reasonable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T12:30:23.020", "Id": "260556", "ParentId": "260538", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T18:40:28.113", "Id": "260538", "Score": "3", "Tags": [ "javascript", "sorting", "radix-sort" ], "Title": "Sorting an array of positive integers including 0 much faster than Radix Sort" }
260538
<p>Hello I don't have any specific problem but I'm just interested how someone who is experienced in JavaScript would write this small toy program. it's a simple Todo List app, there are many approaches to writing something like this but I'm not sure if the way I wrote it is the most optimal. I want to see how others would write this, and maybe learn something new.</p> <p>I'm not very experienced programmer so any criticism is welcome :)</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 TodoList = document.getElementById("TodoList"); const AddTodo = document.getElementById("AddTodo"); let ToggleBtns = []; let RemoveBtns = []; let MyTodos = [ {todoText: "hello world", Completed: true}, {todoText: "hello world", Completed: false}, {todoText: "hello world", Completed: false} ]; function CreateItems(text, index){ const TodoItem = document.createElement("li"); const ToggleButton = document.createElement("button"); const TodoText = document.createElement("p"); const RemoveButton = document.createElement("button"); TodoItem.className = "TodoItem"; ToggleButton.className = "ToggleButton"; TodoText.ClassName = "TodoText"; RemoveButton.className = "RemoveButton"; TodoText.innerText = text; TodoText.style.textDecoration = (MyTodos[index].Completed === true ? "line-through" : "none"); TodoItem.appendChild(ToggleButton); TodoItem.appendChild(TodoText); TodoItem.appendChild(RemoveButton); TodoList.appendChild(TodoItem); ToggleBtns.push(ToggleButton); RemoveBtns.push(RemoveButton); }; for (i in MyTodos) { CreateItems(MyTodos[i].todoText, i); } AddTodo.addEventListener("keypress", function(e){ if(e.keyCode === 13){ MyTodos.push({todoText: AddTodo.value, Completed: false}); CreateItems(MyTodos[MyTodos.length -1].todoText, (MyTodos.length -1)) } }); document.addEventListener("click", function(e){ if(e.target.className === "ToggleButton"){ ToggleIndex = ToggleBtns.indexOf(e.target); MyTodos[ToggleIndex].Completed = (MyTodos[ToggleIndex].Completed === true ? false : true); e.target.parentElement.children[1].style.textDecoration = (MyTodos[ToggleIndex].Completed === true ? "line-through" : "none"); } else if (e.target.className === "RemoveButton"){ RemoveIndex = RemoveBtns.indexOf(e.target); if(RemoveIndex !== 0){ MyTodos.splice(RemoveIndex, RemoveIndex); ToggleBtns.splice(RemoveIndex, RemoveIndex); RemoveBtns.splice(RemoveIndex, RemoveIndex); } else { MyTodos.splice(0, 1); ToggleBtns.splice(0, 1); RemoveBtns.splice(0, 1); } e.target.parentElement.remove(); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code> #TodoList { display: flex; flex-direction: column; padding: 0 ; } .TodoItem { display: flex; flex-direction: row; } .TodoItem button { width: 50px; } .TodoItem p { width: 300px; text-align: center; } #Todos { display: table; margin: 0 auto; } #AddTodo { display: table; height:35px; width: 70%; padding: 0 20px; margin: 0 auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="Todos"&gt; &lt;input type="text" name="" id="AddTodo"&gt; &lt;ul id="TodoList"&gt;&lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>If you had not written this code but were trying to use it, how would you know that the square on either side was a button or what the function of that button was? Buttons need labels and they are generally oval shaped.</p>\n<p>When you design or write code for the web you need to consider the user and how they will be using the tool. Even a toy application should follow some basic standards.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T02:16:49.140", "Id": "514377", "Score": "0", "body": "I was looking for criticism just coding wise, obviously the UX design is bad" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:49:56.190", "Id": "260566", "ParentId": "260541", "Score": "1" } }, { "body": "<p>Your code works, so congratulations for that and for the effort!</p>\n<p>I'm not that experienced myself but after a quick look at your code I notice two important things:</p>\n<ul>\n<li>naming you variables/functions can be improved. Trust me, this is usually a lot harder than it seems.</li>\n<li>casing. In javascript we normally use <code>camelCasing</code>, example: <code>helloWorld, stackOverflow, myTodos, youNameIt</code></li>\n<li>your code is too complicated. Simplifying code is harder than it seems.</li>\n</ul>\n<p>Fortunately both things require just experience and patience.</p>\n<p>I took the freedom to name some of the variable and to restructure the code a bit and I came up with this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>// here we keep a reference to our DOM elements\nconst app = document.getElementById('app');\nconst todoList = document.getElementById('todoList');\nconst newTodo = document.getElementById('newTodo');\n\nlet myTodos = [\n {todoText: &quot;hello world&quot;, Completed: true},\n {todoText: &quot;hello world&quot;, Completed: false},\n {todoText: &quot;hello world&quot;, Completed: false}\n];\n\n// this renders the todo items\n\nnewTodo.addEventListener('keypress', onKeyPress)\n\nfunction onKeyPress(e) {\n if(newTodo.value &amp;&amp; e.code === 'Enter') {\n const brandNewTodo = { \n todoText: newTodo.value, \n Completed: false\n }\n createTodoElement(brandNewTodo);\n newTodo.value = '';\n }\n}\n\n\nfunction createTodoElement(todo) {\n const todoContainer = document.createElement('li');\n // it makes more sense to have a checkbox for a todo\n const todoCheckInput = document.createElement('input');\n const todoDeleteBtn = document.createElement('button');\n const todoText = document.createElement('span');\n todoText.innerText = todo.todoText;\n \n todoContainer.className = 'todo-item ';\n todoCheckInput.className = 'btn-check';\n todoCheckInput.setAttribute('type', 'checkbox');\n // initial checkbox state\n todoCheckInput.checked = todo.Completed;\n // if initial state of the todo is Completed then we add the css\n // class completed\n todoText.className =`${todo.Completed &amp;&amp; 'completed'}`;\n todoDeleteBtn.className = 'btn-delete';\n todoDeleteBtn.innerText = 'delete';\n\n // on click event listener to the checkbox\n todoCheckInput.addEventListener('click', (e) =&gt; {\n todo.Completed = !todo.Completed;\n todoText.classList.toggle('completed');\n })\n // on click event listener for removing the todo\n todoDeleteBtn.addEventListener('click', (e) =&gt; {\n e.currentTarget.parentNode.remove();\n })\n\n todoContainer.appendChild(todoCheckInput);\n todoContainer.appendChild(todoText);\n todoContainer.appendChild(todoDeleteBtn);\n\n todoList.appendChild(todoContainer);\n}\n</code></pre>\n<p>That's it for the js.\nAs you can see, there are no big changes but I think it's easier to read and maintain.</p>\n<p>Here is the html:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div id=&quot;app&quot;&gt;\n &lt;input type=&quot;text&quot; name=&quot;newTodo&quot; id=&quot;newTodo&quot; placeholder=&quot;create new todo and press ENTER&quot; class=&quot;new-todo&quot;&gt;\n &lt;ul id=&quot;todoList&quot; class=&quot;todo-list&quot;&gt;&lt;/ul&gt;\n &lt;/div&gt;\n &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;\n</code></pre>\n<p>and here is the CSS:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#app {\n max-width: 600px;\n}\n.new-todo {\n width: 100%;\n}\n.todo-list {\n width: 100%;\n padding: 0;\n}\n\n.todo-item {\n display: flex;\n justify-content: space-between;\n padding-bottom: 0.3rem;\n}\n.completed {\n text-decoration: line-through;\n}\n</code></pre>\n<p>Good luck and keep up the good work!\nHere is a js fiddle link: <a href=\"https://jsfiddle.net/c103nvf7/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/c103nvf7/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T18:42:22.507", "Id": "514635", "Score": "1", "body": "This could be improved by explaining why you made some of the changes (e.g. different names, different casing on variables, etc). Also feel free to post your code in a new question with a link to this question and the tag [rags-to-riches](https://codereview.stackexchange.com/tags/rags-to-riches/info) (among others)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T11:13:32.373", "Id": "514660", "Score": "0", "body": "Yes, I agree with you. My answer might need more clarification. The reason why I do code reviews is because that makes me a better coder and I know that with each review I am better at it. However sometimes I have not enough time and my review might be considered hurried but I still think some people will benefit from it. Someone else submitted a lot better answer and I was not asked for further clarification for my code. What’s the rags-to-riches?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T18:26:42.900", "Id": "514676", "Score": "0", "body": "Naming property like this: `Completed` is not a good way. You even mentioned it in your post, but didn't change it (\"In javascript we normally use camelCasing\")." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T18:58:58.317", "Id": "514677", "Score": "0", "body": "You are correct" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T12:07:17.650", "Id": "260602", "ParentId": "260541", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T20:47:14.263", "Id": "260541", "Score": "2", "Tags": [ "javascript", "beginner", "to-do-list" ], "Title": "What is the optimal way to write this small Todo List app" }
260541
<p>I have an IoT device with accelerating and gyroscope sensors. before my device can be used it needs to be calibrated.</p> <p>Basically, it means that I do measures for XYZ axes and for the gyro movements and save the findings in JSON file.</p> <p>With this script, I want to assure the calibration process has occurred and that the values I got are in reasonable tolerance.</p> <p>The axes' values divided between positive and negative and revolve around the value of 9.81 for the positive and -9.81 for the negative. When I say revolve I mean they should be in a certain tolerance.</p> <p>The gyroscope values revolve around 0 with the same tolerance.</p> <p>The default JSON file before it is being calibrated looks like this:</p> <p><code>{&quot;acc_x_max&quot;: 9.81, &quot;acc_x_min&quot;: -9.81, &quot;acc_y_max&quot;: 9.81, &quot;acc_y_min&quot;: -9.81, &quot;acc_z_max&quot;: 9.81, &quot;acc_z_min&quot;: -9.81, &quot;gyro_x_offset&quot;: 0, &quot;gyro_y_offset&quot;: 0, &quot;gyro_z_offset&quot;: 0}</code></p> <p>I would like to have your great feedback about the most pythonic way and best practices for this script:</p> <pre><code>import logging import sys # Defining logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('%(levelname)s - %(message)s') handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) logger.addHandler(handler) # Defining constants G = 9.81 TOLERANCE = 2.0 AXES_ARGS = ['acc_x_max', 'acc_y_max', 'acc_z_max', 'acc_x_min', 'acc_y_min', 'acc_z_min'] GYRO_OFFSETS = ['gyro_x_offset', 'gyro_y_offset', 'gyro_z_offset'] PATH_TO_CALIBRATION_FILE = '/home/pi/Desktop/device/IMU_calibration.json' FIXING_CALIBRATION_MSG = 'please calibrated by running &quot;sudo sh IoT/calibration.sh&quot; ' \ 'from /home/pi/Desktop/device directory ' CALIBRATION_ARGS = AXES_ARGS + GYRO_OFFSETS def main(): calib_dict = get_calibration_dictionary(PATH_TO_CALIBRATION_FILE) checking_if_calibration_file_has_been_changed(calib_dict) verify_calibration_in_tolerance_range() logger.info('Device is calibrated !!! :)') def is_calibration_in_tolerance(data: str, tolerance: float, g_force: float): &quot;&quot;&quot; This function takes a value and assesses if it stands in the calibration standards. @param g_force: float @param data: str - acc axes key or gyro offset key @param tolerance: the range which defines valid results in calibration accuracy. @return: None &quot;&quot;&quot; calib_dict = get_calibration_dictionary(PATH_TO_CALIBRATION_FILE) if not abs(calib_dict[data] - g_force) &lt;= tolerance: logger.error(data + f' seems out of calibration\n {FIXING_CALIBRATION_MSG}') exit(1) def get_calibration_dictionary(path_to_calibration_file) -&gt; dict: &quot;&quot;&quot; This function verifying if the calibration file exists in the path and if it does; it returns the calibration data as a python dictionary. @param path_to_calibration_file: str - path to the calibration file. @return: python dictionary &quot;&quot;&quot; try: with open(path_to_calibration_file) as f: return json.load(f) except FileNotFoundError: raise FileNotFoundError(f'cant find calibration file at: {path_to_calibration_file}') def checking_if_calibration_file_has_been_changed(calib_dict: dict) -&gt; None: calibration_file_did_not_change_error_msg = f'This Device hasn\'t been calibrated\n {FIXING_CALIBRATION_MSG}' # Checking if axes have been calibrated or they still hold their default values for axis in AXES_ARGS: if 'max' in axis and calib_dict[axis] == G: logger.error(calibration_file_did_not_change_error_msg) exit(1) if 'min' in axis and calib_dict[axis] == -G: logger.error(calibration_file_did_not_change_error_msg) exit(1) # Checking if gyro offsets have been calibrated or they still hold their default values for gyro_offset in GYRO_OFFSETS: if calib_dict[gyro_offset] == 0: logger.error(gyro_offset + calibration_file_did_not_change_error_msg) exit(1) def verify_calibration_in_tolerance_range() -&gt; None: &quot;&quot;&quot; This function checks if the calibration values are in the tolerance range. It differentiates the input data according to its key and supplies &quot;is_calibration_in_tolerance&quot; function with suitable arguments. If the tested value does no meet the criteria it will exit with the return value of 1. If all the values meet the standard it returns None. @return: None &quot;&quot;&quot; # verifying axes calibration in tolerance range for calib_key in CALIBRATION_ARGS: if 'max' in calib_key: is_calibration_in_tolerance(calib_key, TOLERANCE, G) elif 'min' in calib_key: is_calibration_in_tolerance(calib_key, TOLERANCE, -G) elif 'gyro' in calib_key: is_calibration_in_tolerance(calib_key, TOLERANCE, 0.0) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T20:14:27.340", "Id": "514364", "Score": "0", "body": "This is not complete - you're missing at least one import" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T21:56:27.523", "Id": "514368", "Score": "0", "body": "Could you specify them? I must have missed that and can't figure out which ones?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T21:59:52.460", "Id": "514369", "Score": "1", "body": "i see the JSON import :)" } ]
[ { "body": "<p>You're using logging - great! You should encapsulate your logging setup so that you don't pollute the global namespace, something like</p>\n<pre><code>def make_logger():\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter('%(levelname)s - %(message)s')\n handler = logging.StreamHandler(sys.stdout)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n\nlogger = make_logger()\n</code></pre>\n<p>The <a href=\"https://en.wikipedia.org/wiki/Gravitational_acceleration\" rel=\"nofollow noreferrer\">standard value of gravitational acceleration</a> at sea level is not 9.81 - it's 9.80665.</p>\n<p><code>AXES_ARGS</code> and <code>GYRO_OFFSETS</code> should be tuples instead of lists due to them being immutable.</p>\n<p><code>PATH_TO_CALIBRATION_FILE</code> is fine to take a value in <code>/home</code> <em>if the user provides that value in interactive mode</em>. But defaulting to something in <code>/home</code> is a bad idea. Since this seems like a permanent service on an IOT device, make an actual (non-<code>pi</code>) service user and pay attention to the recommendations for standard Unix file layout. Depending on a few things, your calibration file - if centralized - would be better in a permissions-restricted subdirectory of <code>/usr/share</code> or <code>/usr/local/share</code>, or maybe <code>/etc/</code> if it's considered &quot;static configuration&quot;; or maybe <code>/var/</code> if it's considered &quot;runtime data&quot;. If it's not centralized and requires an interactive user (which seems unlikely), then you should just be accepting this path on the command line.</p>\n<p>Grammar: <code>please calibrated</code> -&gt; <code>please calibrate</code></p>\n<p>Asking that the user run <code>calibration.sh</code> under <code>sudo</code> is awful. Please don't contribute to the stereotype that IOT is a vast wasteland of insecurity - your user model needs to be cleaned up. Nothing in your calibration code should require root access.</p>\n<p>This is basically a no-op:</p>\n<pre><code> except FileNotFoundError:\n raise FileNotFoundError(f'cant find calibration file at: {path_to_calibration_file}')\n</code></pre>\n<p>so delete it and just let the original exception fall through.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T22:47:18.033", "Id": "514371", "Score": "1", "body": "This is extremely valuable THX" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T20:34:04.810", "Id": "260580", "ParentId": "260542", "Score": "3" } } ]
{ "AcceptedAnswerId": "260580", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T21:55:47.640", "Id": "260542", "Score": "3", "Tags": [ "python" ], "Title": "Verifying calibration process on IoT device, python script" }
260542
<p>There are things that I am not 100% sure. Is it possible that dangling references can be create in <em>add_task</em> method? Is it possible that this implementation will deadlock? I had to use <em>shared_ptr</em> in order to store <em>packaged_task</em> in the queue. Is there a better way to do it?</p> <pre><code>class ThreadPool { public: ThreadPool(int number_of_workers) { for (int i=0; i&lt;number_of_workers; ++i) { worker_threads.push_back(std::thread{std::bind(&amp;ThreadPool::thread_func, this)}); } } ~ThreadPool() = default; ThreadPool(const ThreadPool&amp;) = delete; ThreadPool(ThreadPool&amp;&amp;) = delete; ThreadPool&amp; operator=(const ThreadPool&amp;) = delete; ThreadPool&amp; operator=(ThreadPool&amp;&amp;) = delete; template&lt;typename Func, typename... Args&gt; decltype(auto) add_task(Func&amp;&amp; func, Args... args) { using ReturnType = decltype(func(args...)); auto ptask = std::make_shared&lt;std::packaged_task&lt;ReturnType()&gt;&gt;( std::bind(std::forward&lt;Func&gt;(func), std::forward&lt;Args&gt;(args)...)); auto fut = ptask-&gt;get_future(); { std::unique_lock lk{pool_mutex}; task_queue.push([pt = std::move(ptask)]() { (*pt)(); }); } cond.notify_one(); return fut; } void stop() { { std::unique_lock lk{pool_mutex}; stopped = true; } cond.notify_all(); for (auto&amp; th : worker_threads) { if (th.joinable()) { th.join(); } } } private: void thread_func() { while(true) { std::unique_lock lk{pool_mutex}; if (task_queue.empty() &amp;&amp; stopped) { break; } if (task_queue.empty()) { cond.wait(lk, [this]() { return !task_queue.empty() || stopped; }); } if (!task_queue.empty()) { auto callable = std::move(task_queue.front()); task_queue.pop(); lk.unlock(); callable(); } else if (stopped) { break; } } } private: std::mutex pool_mutex; std::vector&lt;std::thread&gt; worker_threads; bool stopped = false; std::condition_variable cond; std::queue&lt;std::function&lt;void()&gt;&gt; task_queue; }; </code></pre> <p>Note, that <em>add_task</em> returns a future that can be used to wait for a specific task to complete.</p>
[]
[ { "body": "<pre><code>~ThreadPool() = default;\n</code></pre>\n<p>We need to call <code>stop()</code> in the destructor!</p>\n<hr />\n<pre><code>template&lt;typename Func, typename... Args&gt;\ndecltype(auto) add_task(Func&amp;&amp; func, Args... args) {\n using ReturnType = decltype(func(args...));\n</code></pre>\n<p>For perfect forwarding we need to use <code>&amp;&amp;</code> for args:</p>\n<pre><code>template&lt;typename Func, typename... Args&gt;\ndecltype(auto) add_task(Func&amp;&amp; func, Args&amp;&amp;... args) {\n using ReturnType = decltype(func(std::forward&lt;Args&gt;(args)...));\n</code></pre>\n<hr />\n<pre><code>ThreadPool(int number_of_workers) {\n</code></pre>\n<p>We need to check that this number is greater than zero. Also it might be better to use an <code>unsigned int</code> to match the result of <code>std::thread::hardware_concurrency()</code>.</p>\n<hr />\n<pre><code>void thread_func() {\n while(true) {\n std::unique_lock lk{pool_mutex};\n if (task_queue.empty() &amp;&amp; stopped) {\n break;\n }\n ...\n</code></pre>\n<p>I'm not sure that we should wait for the <code>task_queue</code> to be empty before stopping. I'd suggest that <code>stop()</code> should prevent threads taking any more tasks from the queue (i.e. provide a way to &quot;cancel&quot; tasks that haven't started executing yet).</p>\n<p>If we wait for the queue to be empty when calling <code>stop()</code>, we're waiting for all the tasks to complete, so calling <code>stop()</code> doesn't really do much. (The calling code is already in control of whether or not it adds more tasks and waits for futures).</p>\n<pre><code> if (task_queue.empty()) {\n cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });\n }\n</code></pre>\n<p>We don't really need to put <code>cond.wait()</code> in an <code>if</code> statement. It will check the condition before waiting.</p>\n<p>I'd probably go for something more like:</p>\n<pre><code>void thread_func() {\n while(true) {\n \n std::unique_lock lk{pool_mutex};\n cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });\n \n if (stopped)\n break;\n\n assert(!task_queue.empty());\n \n auto callable = std::move(task_queue.front());\n task_queue.pop();\n \n lk.unlock();\n \n callable();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T11:54:55.657", "Id": "514317", "Score": "0", "body": "I agree with your critique. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T08:16:35.030", "Id": "260550", "ParentId": "260544", "Score": "1" } } ]
{ "AcceptedAnswerId": "260550", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T22:35:09.730", "Id": "260544", "Score": "2", "Tags": [ "c++", "c++17" ], "Title": "Is this thread pool implementation OK?" }
260544
<p>I have a Direct3D 11 application and recently I've started to implement a new feature on it, the UI(User Interface).</p> <p>It seems to work well, but I'm having one problem with optimization when it comes to moving stuff on my window, currently I can create a 2D square with textures and a 300x300 resolution.I can drag it around my screen by calling a function that updates the square position on my screen.</p> <pre><code>bool Model::UpdateModel2D(ID3D11DeviceContext* pDeviceContext, short NewX, short NewY) { if ((m_PreviousX == NewX) || (m_PreviousY == NewY)) // detects if the UI position is the same as before return true; D3D11_MAPPED_SUBRESOURCE ms; ModelData* pNewData; ZeroMemory(&amp;ms, sizeof(D3D11_MAPPED_SUBRESOURCE)); ModelData pData[6]; //Builds two triangles in order to form a square. pData[0].VertexData = XMFLOAT3(NewX, NewY, 0.0f); pData[0].TextureCoords = XMFLOAT2(0.0f, 0.0f); pData[1].VertexData = XMFLOAT3(NewX + 300.0f, NewY + 300.0f, 0.0f); pData[1].TextureCoords = XMFLOAT2(1.0f, 1.0f); pData[2].VertexData = XMFLOAT3(NewX, NewY + 300, 0.0f); pData[2].TextureCoords = XMFLOAT2(0.0f, 1.0f); pData[3].VertexData = XMFLOAT3(NewX, NewY, 0.0f); pData[3].TextureCoords = XMFLOAT2(0.0f, 0.0f); pData[4].VertexData = XMFLOAT3(NewX + 300.0f, NewY, 0.0f); pData[4].TextureCoords = XMFLOAT2(1.0f, 0.0f); pData[5].VertexData = XMFLOAT3(NewX + 300.0f, NewY + 300.0f, 0.0f); pData[5].TextureCoords = XMFLOAT2(1.0f, 1.0f); hr = pDeviceContext-&gt;Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &amp;ms); if (FAILED(hr)) return false; pNewData = (ModelData*)ms.pData; memcpy(pNewData, pData, sizeof(ModelData) * m_NumVertices); //updates the position of the 2D square pDeviceContext-&gt;Unmap(m_pVertexBuffer, 0); return true; } </code></pre> <p>To drag this square I have to left click on it and move my mouse, but this is an issue because my application gets too slow, and it looks like the longer I hold it on my mouse, the slower the application gets, until it gets released. If someone knows how to improve updating my buffers, please help me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T13:07:06.373", "Id": "514319", "Score": "3", "body": "This question is more suited towards the [Computer Graphics](https://computergraphics.stackexchange.com/) or [Gamedev](https://gamedev.stackexchange.com) stackexchanges. Anyway, it may be possible that your app is reading the subresource data while it's being mapped. [See here](https://docs.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-map#remarks) (\"Don't read from a subresource mapped for writing\")" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T00:24:13.693", "Id": "514376", "Score": "0", "body": "Oh, looks like it was actually an issue. I've changed the part where I'm reading the previous buffer data before updating and now I'm instead copying the new data directly over the old buffer, the performance increased pretty much by doing so. If you want, you can post here your answer and I'll give you the best answer. And thanks for providing these links, I'll use them if I have a related question in the future." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T00:26:27.353", "Id": "260546", "Score": "0", "Tags": [ "c++", "graphics" ], "Title": "How can I make my resource mapping faster?" }
260546
<p>I'm new to Go and I completed the first challenge from Gophercises. Any feedback would be highly appreciated.</p> <p>There are some things that I am unsure of if they are made in an optimal way.</p> <p><a href="https://github.com/anthonygedeon/gophercises/tree/main/quiz-master" rel="nofollow noreferrer">Github repo</a></p> <ol> <li><p>Goroutines and channels in the <code>quizList</code> loop</p> </li> <li><p>Better error logging for the cli portion</p> </li> <li><p>The <code>Shuffle</code> function only works for string, how can I make it work for other types as well?</p> </li> <li><p>How should I approach writing test cases?</p> </li> <li><p>How should the folder structure be structured?</p> <pre><code> package main import ( &quot;encoding/csv&quot; &quot;flag&quot; &quot;fmt&quot; &quot;log&quot; &quot;math/rand&quot; &quot;os&quot; &quot;strings&quot; &quot;time&quot; ) type question struct { prompt, answer string } func main() { var ( csvFile = flag.String(&quot;csv&quot;, &quot;problems.csv&quot;, &quot;a csv file in the format of 'question,answer'&quot;) timeLimit = flag.Int(&quot;limit&quot;, 3, &quot;the time limit for the quiz in seconds&quot;) isShuffle = flag.Bool(&quot;shuffle&quot;, false, &quot;shuffle the quiz order each time it is run&quot;) ) flag.Parse() if *csvFile == &quot;&quot; { fmt.Printf(&quot;%s does not exist, please choose another file&quot;, *csvFile) } if *timeLimit == 0 { fmt.Printf(&quot;Not a valid limit, please choose another limit&quot;) } score := 0 file, err := os.Open(*csvFile) if err != nil { log.Fatal(err) } r := csv.NewReader(file) problems, err := r.ReadAll() if err != nil { log.Fatal(err) } if *isShuffle { Shuffle(problems) } quizList := populateQuiz(problems) timer := time.NewTimer(time.Duration(*timeLimit) * time.Second) isTimerDone := true ch := make(chan string) for _, quiz := range quizList { fmt.Printf(quiz.prompt) var recipientAnswer string go func() { fmt.Scanln(&amp;recipientAnswer) ch &lt;-recipientAnswer }() if isTimerDone { select { case &lt;-ch: if recipientAnswer == quiz.answer { score += 1 } case &lt;-timer.C: isTimerDone = false fmt.Println() return } } else { break } } fmt.Printf(&quot;\nYou scored %d out of %d.\n&quot;, score, len(problems)) } func Shuffle(l [][]string) { rand.Seed(time.Now().UnixNano()) rand.Shuffle(len(l), func(i, j int) { l[i], l[j] = l[j], l[i] }) } func populateQuiz(problems [][]string) []question { var questions []question for index, record := range problems { prompt := fmt.Sprintf(&quot;Problem: #%d: %s = &quot;, index + 1, record[0]) answer := record[1] questions = append(questions, question{ prompt: prompt, answer: strings.TrimSpace(answer), }) } return questions } </code></pre> </li> </ol>
[]
[ { "body": "<p>from what I saw there are a few changes that could be done to the program</p>\n<ol>\n<li><p>while parsing command-line arguments I think it's better to put them inside a function cause it makes the code look clean and simple and as it is returned as a pointer you would have to keep getting the value as * but you could return it as the specific type and have a simpler handling</p>\n<pre><code> csvFile, timeLimit, isShuffle := parseCMD() \n\n func parseCMD() (string, int, bool) {\n csvFile := flag.String(&quot;csv&quot;, &quot;problems.csv&quot;, &quot;a csv file in the format of 'question,answer'&quot;)\n timeLimit := flag.Int(&quot;limit&quot;, 3, &quot;the time limit for the quiz in seconds&quot;)\n isShuffle := flag.Bool(&quot;shuffle&quot;, false, &quot;shuffle the quiz order each time it is run&quot;)\n flag.Parse()\n return *csvFile, *timeLimit, *isShuffle\n</code></pre>\n<p>}</p>\n</li>\n<li><p>var (\ncsvFile = flag.String(&quot;csv&quot;, &quot;problems.csv&quot;, &quot;a csv file in the format of 'question,answer'&quot;)\ntimeLimit = flag.Int(&quot;limit&quot;, 3, &quot;the time limit for the quiz in seconds&quot;)\nisShuffle = flag.Bool(&quot;shuffle&quot;, false, &quot;shuffle the quiz order each time it is run&quot;)\n)\nvar can be used on a variable that doesn't have any initialization or if it's gonna be a global score or... if in a case outside an if statement or a for loop (a situation where:= won't work).. as these are being declared inside a function and have a default value a short variable declaration would be a more golang kinda way. (there is not a lot of difference between using var and:= in your code but in a situation like this:= would be more golang-ish)\n<a href=\"https://stackoverflow.com/questions/53404305/when-to-use-var-or-in-go/53404332\">https://stackoverflow.com/questions/53404305/when-to-use-var-or-in-go/53404332</a>\n<a href=\"https://stackoverflow.com/questions/21657446/var-vs-in-go\">https://stackoverflow.com/questions/21657446/var-vs-in-go</a></p>\n</li>\n</ol>\n<ol start=\"3\">\n<li>\n<pre><code> timer := time.NewTimer(time.Duration(*timeLimit) * time.Second)\n</code></pre>\n<p>while defining a ticker add a &quot;defer ticker.stop()&quot; to release any resource related to as it wont be garbage collected (<a href=\"https://golang.org/src/time/tick.go\" rel=\"nofollow noreferrer\">https://golang.org/src/time/tick.go</a>)</p>\n</li>\n<li><p>if isTimerDone {\nselect {\ncase &lt;-ch:\nif recipientAnswer == quiz.answer {\nscore += 1\n}\ncase &lt;-timer.C:\nisTimerDone = false\nfmt.Println()\nreturn\n}\n} else {\nbreak\n}</p>\n</li>\n</ol>\n<p>In the above case the if check (isTimerDone) won't actually hit as by flow you always go into the select case and if you get an answer you continue the loop and if the timer hits you return.. so a better way to write it would be to remove the IF-ELSE check..</p>\n<p>from what I understand yours is a score counting program so assuming you don't answer and the timer hit.. you could continue the loop and score based on the total answer or break the loop if he doesn't answer (this is just a suggestion :) )</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T17:10:26.897", "Id": "260661", "ParentId": "260548", "Score": "1" } }, { "body": "<p>A well-written program has a well-organized structure.</p>\n<p>In Go, interfaces describe behavior, and are a key abstraction. A primary Go abstraction for a stream of data is the io.Reader interface. It allows us to substitute any type that satisfies the io.Reader interface, for example, os.File, bytes.Buffer, bytes.Reader, strings.Reader, bufio.Reader, and so on.</p>\n<p>Consider reading the Gophercises Quiz Game problems.csv.</p>\n<p>A problem is</p>\n<pre><code>type problem struct {\n question, answer string\n}\n</code></pre>\n<p>For the io.Reader interface we have</p>\n<pre><code>func readProblems(r io.Reader) ([]problem, error) {\n rv := csv.NewReader(r)\n rv.FieldsPerRecord = 2\n rv.ReuseRecord = true\n\n var problems []problem\n for {\n rec, err := rv.Read()\n if err != nil {\n if err == io.EOF {\n break\n }\n return nil, err\n }\n problems = append(problems,\n problem{\n question: rec[0],\n answer: rec[1],\n },\n )\n }\n return problems[:len(problems):len(problems)], nil\n}\n</code></pre>\n<p>For reading a file, we use os.File to satisfy the io.Reader interface.</p>\n<pre><code>func loadProblems(filename string) ([]problem, error) {\n f, err := os.Open(filename)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n\n problems, err := readProblems(f)\n if err != nil {\n return nil, err\n }\n return problems, nil\n}\n</code></pre>\n<p>For testing, we use bytes.Reader to satisfy the io.Reader interface.</p>\n<pre><code>var readProblemsTests = []struct {\n line string\n want problem\n}{\n {\n line: &quot;5+5,10\\n&quot;,\n want: problem{question: &quot;5+5&quot;, answer: &quot;10&quot;},\n },\n // ...\n}\n\nfunc TestReadProblems(t *testing.T) {\n var file []byte\n for _, tt := range readProblemsTests {\n file = append(file, tt.line...)\n }\n r := bytes.NewReader(file)\n\n got, err := readProblems(r)\n if err != nil {\n t.Errorf(&quot;readProblems: got %v, want %v&quot;, err, nil)\n }\n\n // ...\n}\n</code></pre>\n<p>The following are sample data, program, and test to illustrate the usage of the readProblems function for the Gophercises Quiz Game.</p>\n<p><code>readcsv.csv</code>:</p>\n<pre><code>5+5,10\n1+1,2\n8+3,11\n1+2,3\n8+6,14\n3+1,4\n1+4,5\n</code></pre>\n<p><code>readcsv.go</code>:</p>\n<pre><code>package main\n\nimport (\n &quot;encoding/csv&quot;\n &quot;fmt&quot;\n &quot;io&quot;\n &quot;log&quot;\n &quot;math/rand&quot;\n &quot;os&quot;\n &quot;time&quot;\n)\n\ntype problem struct {\n question, answer string\n}\n\nfunc (p problem) String() string {\n return fmt.Sprintf(\n &quot;{question: %q, answer: %q}&quot;,\n p.question, p.answer,\n )\n}\n\nfunc readProblems(r io.Reader) ([]problem, error) {\n rv := csv.NewReader(r)\n rv.FieldsPerRecord = 2\n rv.ReuseRecord = true\n\n var problems []problem\n for {\n rec, err := rv.Read()\n if err != nil {\n if err == io.EOF {\n break\n }\n return nil, err\n }\n problems = append(problems,\n problem{\n question: rec[0],\n answer: rec[1],\n },\n )\n }\n return problems[:len(problems):len(problems)], nil\n}\n\nfunc loadProblems(filename string) ([]problem, error) {\n f, err := os.Open(filename)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n\n problems, err := readProblems(f)\n if err != nil {\n return nil, err\n }\n return problems, nil\n}\n\nfunc shuffleProblems(l []problem) {\n rand.Seed(time.Now().UnixNano())\n rand.Shuffle(len(l),\n func(i, j int) {\n l[i], l[j] = l[j], l[i]\n },\n )\n}\n\nfunc printProblems(problems []problem) {\n fmt.Println(len(problems), &quot;problems&quot;)\n for _, p := range problems {\n fmt.Println(p.String())\n }\n}\n\nfunc main() {\n // TODO: use flag\n filename := `readcsv.csv`\n\n problems, err := loadProblems(filename)\n if err != nil {\n log.Fatal(err)\n }\n\n // TODO: use flag\n shuffle := true\n if shuffle {\n shuffleProblems(problems)\n }\n\n printProblems(problems)\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>$ go run readcsv.go\n7 problems\n{question: &quot;1+4&quot;, answer: &quot;5&quot;}\n{question: &quot;5+5&quot;, answer: &quot;10&quot;}\n{question: &quot;8+6&quot;, answer: &quot;14&quot;}\n{question: &quot;1+1&quot;, answer: &quot;2&quot;}\n{question: &quot;3+1&quot;, answer: &quot;4&quot;}\n{question: &quot;1+2&quot;, answer: &quot;3&quot;}\n{question: &quot;8+3&quot;, answer: &quot;11&quot;}\n$ \n</code></pre>\n<p><code>readcsv_test.go</code>:</p>\n<pre><code>package main\n\nimport (\n &quot;bytes&quot;\n &quot;testing&quot;\n)\n\nvar readProblemsTests = []struct {\n line string\n want problem\n}{\n {\n line: &quot;5+5,10\\n&quot;,\n want: problem{question: &quot;5+5&quot;, answer: &quot;10&quot;},\n },\n {\n line: &quot;1+1,2\\n&quot;,\n want: problem{question: &quot;1+1&quot;, answer: &quot;2&quot;},\n },\n}\n\nfunc TestReadProblems(t *testing.T) {\n var file []byte\n for _, tt := range readProblemsTests {\n file = append(file, tt.line...)\n }\n r := bytes.NewReader(file)\n\n got, err := readProblems(r)\n if err != nil {\n t.Errorf(&quot;readProblems: got %v, want %v&quot;, err, nil)\n }\n if len(got) != len(readProblemsTests) {\n t.Errorf(&quot;problems: got %v, want %v&quot;, len(got), len(readProblemsTests))\n }\n for i, tt := range readProblemsTests {\n if got[i] != tt.want {\n t.Errorf(&quot;problem: got %v, want %v&quot;, got[i], tt.want)\n }\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>$ go test readcsv_test.go readcsv.go -v\n=== RUN TestReadProblems\n--- PASS: TestReadProblems (0.00s)\nPASS\n$\n</code></pre>\n<hr />\n<p><strong>ADDENDUM</strong></p>\n<blockquote>\n<p>Comment: Regarding the readcsv.go file, in the readProblems function\nwhy did you return problems[:len(problems):len(problems)] instead of\nproblems? Also, when closing the file in the loadProblems function,\ndoes the defer wait until the loadProblems function has returned or\nuntil the main function is done? – Anthony Gedeon</p>\n</blockquote>\n<hr />\n<blockquote>\n<p><a href=\"https://golang.org/ref/spec\" rel=\"nofollow noreferrer\">The Go Programming Language\nSpecification</a></p>\n<p><a href=\"https://golang.org/ref/spec#Appending_and_copying_slices\" rel=\"nofollow noreferrer\">Appending to and copying\nslices</a></p>\n<p>The variadic function append appends zero or more values x to s of\ntype S, which must be a slice type, and returns the resulting slice,\nalso of type S.</p>\n<p>If the capacity of s is not large enough to fit the additional values,\nappend allocates a new, sufficiently large underlying array that fits\nboth the existing slice elements and the additional values. Otherwise,\nappend re-uses the underlying array.</p>\n<p><a href=\"https://golang.org/ref/spec#Slice_expressions\" rel=\"nofollow noreferrer\">Slice expressions</a></p>\n<p>Full slice expressions</p>\n<p>For an array, pointer to array, or slice a (but not a string), the\nprimary expression</p>\n<pre><code>a[low : high : max]\n</code></pre>\n<p>constructs a slice of the same type, and with the same length and\nelements as the simple slice expression a[low : high]. Additionally,\nit controls the resulting slice's capacity by setting it to max - low.\nOnly the first index may be omitted; it defaults to 0.</p>\n</blockquote>\n<hr />\n<blockquote>\n<p><a href=\"https://www.hyrumslaw.com/\" rel=\"nofollow noreferrer\">Hyrum's Law</a></p>\n<p>An observation on Software Engineering</p>\n<p>Put succinctly, the observation is this:</p>\n<pre><code>With a sufficient number of users of an API,\nit does not matter what you promise in the contract:\nall observable behaviors of your system\nwill be depended on by somebody. \n</code></pre>\n<p>Obligatory XKCD: <a href=\"https://xkcd.com/1172/\" rel=\"nofollow noreferrer\">https://xkcd.com/1172/</a></p>\n</blockquote>\n<hr />\n<p>We should avoid exposing a particular API (function or method) implementation. This particular implementation of readProblems uses the append built-in function, which may create excess capacity. Other implementations may return the exact capacity. By Hyrum's Law, we ensure that this implementation, like other implementations, returns the exact capacity:</p>\n<pre><code>problems[:len(problems):len(problems)]\n</code></pre>\n<hr />\n<blockquote>\n<p><a href=\"https://golang.org/ref/spec\" rel=\"nofollow noreferrer\">The Go Programming Language\nSpecification</a></p>\n<p><a href=\"https://golang.org/ref/spec#Defer_statements\" rel=\"nofollow noreferrer\">Defer statements</a></p>\n<p>A &quot;defer&quot; statement invokes a function whose execution is deferred to\nthe moment the surrounding function returns, either because the\nsurrounding function executed a return statement, reached the end of\nits function body, or because the corresponding goroutine is\npanicking.</p>\n</blockquote>\n<hr />\n<p>It's important to ensure that scarce resources, like file handles, are released as soon as they are no longer needed. The defer statement to close the file in the loadProblems function is deferred to the moment the loadProblems function returns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T22:25:07.727", "Id": "514646", "Score": "0", "body": "Regarding the readcsv.go file, in the readProblems function why did you return problems[:len(problems):len(problems)] instead of problems? Also, when closing the file in the loadProblems function, does the defer wait until the loadProblems function has returned or until the main function is done?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T03:40:10.340", "Id": "514651", "Score": "1", "body": "@AnthonyGedeon: See the addendum in my revised answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T14:14:32.230", "Id": "260708", "ParentId": "260548", "Score": "1" } } ]
{ "AcceptedAnswerId": "260708", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T03:02:36.050", "Id": "260548", "Score": "1", "Tags": [ "programming-challenge", "go" ], "Title": "Improving my solution to the Quiz project from Gophercises in Golang" }
260548
<p>I am trying to optimise my remove-erase functions by using some attributes of C++ containers. This function should delete all indices defined in std::set form given vector. I am pretty sure that algorithm is functionality-wise working, but every time I see STL implementation or any code using STL I see a lot of checks around which I cannot come up when I am writing my own code.</p> <p>I decided to practise by trying so I hope for some tips or tricks on how to improve my code-writing skills.</p> <p>The algorithm is trying to prevent unnecessary copies. So it is copying just the elements that are supposed to survive. It goes by two iterators. One for a destination where the next element should be copied and second the next element that should &quot;survive&quot;. When it arrives at the end of the vector minus the number of deleted elements it stops and leaves the rest for <code>erase()</code> function.</p> <pre class="lang-cpp prettyprint-override"><code>//================================================================================= // Deletes all indexes defined in set from vector. Leverages the advantage of set being // sorted from the smallest to the highest number and continuity of vector storage. template &lt;class T, class IdxT&gt; typename std::vector&lt;T&gt;::iterator remove_indices(std::vector&lt;T&gt;&amp; vector, const std::set&lt;IdxT&gt;&amp; set) { if (set.empty()) { return vector.end(); } auto nextDelete = set.begin(); const auto destinationIndex = *nextDelete; auto destination = vector.begin(); auto source = vector.begin(); std::advance(destination, destinationIndex); std::advance(source, destinationIndex + 1); ++nextDelete; auto sourceIndex = destinationIndex + 1; while (destination != vector.end() - set.size()) { while (nextDelete != set.end()) { if (sourceIndex == *nextDelete) { ++source; ++nextDelete; ++sourceIndex; } } *destination = std::move(*source); ++destination; ++source; ++sourceIndex; } return destination; } </code></pre>
[]
[ { "body": "<p>There are a few things I would improve:</p>\n<ul>\n<li>Clearly separate the three distinct phases:\n<ol>\n<li>Skip until the first index in the set</li>\n<li>Copy/delete until we reached the last index</li>\n<li>Copy the remainder until the end of the container is reached.</li>\n</ol>\n</li>\n<li>Have an <em>outer</em> loop that loops over the entries of <code>set</code>.</li>\n<li>Use <code>*foo++</code> syntax.</li>\n<li>Use <code>auto</code> return type deduction.</li>\n<li>Name things after their purpose, not what type they are. So instead of <code>set</code>, name it <code>indices</code>.</li>\n</ul>\n<p>With this, the code would look like:</p>\n<pre><code>template &lt;class T, class IdxT&gt; \nauto remove_indices(std::vector&lt;T&gt;&amp; container, const std::set&lt;IdxT&gt;&amp; indices)\n{\n // Exit early if there is nothing to do.\n if (indices.empty())\n return container.end();\n\n auto destination = container.begin();\n auto source = container.begin();\n auto idx_it = indices.begin();\n\n // Skip until we reach the first index.\n std::advance(destination, *idx_it);\n std::advance(source, *idx_it + 1);\n\n // Delete all the elements at the given indices.\n while(++idx_it != indices.end()) {\n auto nextDelete = container.begin() + *idx_it;\n while(source &lt; nextDelete)\n *destination++ = std::move(*source++);\n source++;\n }\n\n // Copy the remainder until the end of the container.\n while (source != container.end())\n *destination++ = std::move(*source++);\n\n return destination;\n}\n</code></pre>\n<p>Also consider adding a test suite. And you might want to generalize this further to remove elements from other random access container types (for example, <code>std::deque</code>), and have it take the indices in other container types as well, as a <code>std::set</code> is quite an inefficient way to store a few integers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T13:30:16.997", "Id": "260558", "ParentId": "260553", "Score": "4" } } ]
{ "AcceptedAnswerId": "260558", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T11:11:13.147", "Id": "260553", "Score": "3", "Tags": [ "c++", "stl" ], "Title": "Remove indicies from vector" }
260553
<p>For the real time control software I need square root calculation. I have heard that the sqrt function from the standard library isn't good choice due to the unpredictable number of iterations used during calculation. Based on that information I have decided to implement the sqrt function in my own based on the Newton tangent method. So I have exploited the iteration formula</p> <p><span class="math-container">$$x_{k+1} = -\frac{f(x_k)}{f'(x_k)} + x_k,$$</span> where <span class="math-container">$$f(x) = x^2 - a$$</span> and <span class="math-container">$$a\in\mathbb R_0^+, a_{min} = 0.1, a_{max} = 400.0$$</span>.</p> <p>Based on the above mentioned formulas I have</p> <p><span class="math-container">$$x_{k+1} = \frac{1}{2}\cdot\left(x_k + \frac{a}{x_k}\right)$$</span></p> <p>I have chosen <span class="math-container">$$x(0) = 2$$</span> and based on my observations four iterations give good results in comparison with the <code>sqrt</code> from the standard library.</p> <pre><code>#define ITERATIONS 4 double squareRoot(double a) { double xk = 2.0; // x(k) uint8_t k; for(k = 0; k &lt; ITERATIONS; k++) { xk = 0.5*(xk + a/xk); } return xk; } </code></pre> <p>Despite that fact I have some doubts regarding the choice of the initial value and number of iterations.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T21:36:14.017", "Id": "514429", "Score": "2", "body": "For what values of `a` do you expect to get? Negatives? Small positives? Integers? What is min and max value? What is the error threshold?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T23:28:52.080", "Id": "514435", "Score": "4", "body": "What hardware is this running on? _I have heard_ seems like dangerous justification to make a design decision like this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-02T12:32:40.717", "Id": "520639", "Score": "0", "body": "What are you looking for from a code review, it remains unclear to me." } ]
[ { "body": "<blockquote>\n<p>I have heard that the sqrt function from the standard library isn't good choice due to the unpredictable number of iterations used during calculation.</p>\n</blockquote>\n<p>The goal of standard functions do not generally include a uniform time requirement.</p>\n<p>Far more often, a precise and correct as able solution is sought. Speed is of secondary concern.</p>\n<hr />\n<blockquote>\n<p>my observations four iterations give good results</p>\n</blockquote>\n<p>Below is a test harness.</p>\n<p>I found the numeric results disappointing for general <code>double</code> usage. Notice the &quot;relative difference&quot; of 1.0 (very bad).</p>\n<pre><code>#include &lt;float.h&gt;\n#include &lt;math.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n// Insert OP's code here\n\nvoid test(double x) {\n double y0 = sqrt(x);\n double y1 = squareRoot(x);\n if (y0 != y1) {\n double diff = y1 - y0;\n double rel = diff / (y1 + y0);\n printf(\n &quot;x:%13g sqrt(x):%23.17g squareRoo(x):%23.17g relative difference:%13g\\n&quot;,\n x, y0, y1, rel);\n }\n}\n\nint main() {\n double a[] = {0.0, 1.0, 2.0, 42, DBL_TRUE_MIN, DBL_MIN, sqrt(DBL_MIN), sqrt(\n DBL_MAX), DBL_MAX};\n size_t n = sizeof a / sizeof a[0];\n for (size_t i = 0; i &lt; n; i++) {\n test(a[i]);\n\n }\n puts(&quot;Done&quot;);\n}\n</code></pre>\n<p>Output</p>\n<pre><code>x: 0 sqrt(x): 0 squareRoo(x): 0.125 relative difference: 1\nx: 1 sqrt(x): 1 squareRoo(x): 1.0000000464611474 relative difference: 2.32306e-08\nx: 2 sqrt(x): 1.4142135623730951 squareRoo(x): 1.4142135623746899 relative difference: 5.6382e-13\nx: 42 sqrt(x): 6.4807406984078604 squareRoo(x): 6.4812185874674091 relative difference: 3.68686e-05\nx: 4.94066e-324 sqrt(x):2.2227587494850775e-162 squareRoo(x): 0.125 relative difference: 1\nx: 2.22507e-308 sqrt(x):1.4916681462400413e-154 squareRoo(x): 0.125 relative difference: 1\nx: 1.49167e-154 sqrt(x): 1.221338669755462e-77 squareRoo(x): 0.125 relative difference: 1\nx: 1.34078e+154 sqrt(x): 1.1579208923731618e+77 squareRoo(x):4.1899399781070611e+152 relative difference: 1\nx: 1.79769e+308 sqrt(x):1.3407807929942596e+154 squareRoo(x):5.6177910464447366e+306 relative difference: 1\nDone\n</code></pre>\n<hr />\n<p><strong>Design problem</strong></p>\n<p><em>Newton tangent method</em> rapidly converges to a good answer once it is is <em>near</em> the correct result. Trouble with OP's approach is the <strong>slow</strong> convergence when the result is not near 2.0.</p>\n<p>Instead, better to first get the result exponent in range.</p>\n<p>Below, with exponent halving and 1 more iteration that OP's, give very good result for all <code>double &gt; 0</code>. Notice the &quot;relative difference&quot; of 1e-16 (very good).</p>\n<pre><code>double squareRoot_improved(double a) {\n int expo;\n frexp(a, &amp;expo);\n double xk = ldexp(1, expo/2);\n\n uint8_t k;\n for (k = 0; k &lt; 5; k++) {\n xk = 0.5 * (xk + a / xk);\n }\n\n return xk;\n}\n</code></pre>\n<p>Results</p>\n<pre><code>x: 0 sqrt(x): 0 squareRoo(x): 0.03125 relative difference: 1\nx: 2 sqrt(x): 1.4142135623730951 squareRoo(x): 1.4142135623730949 relative difference: -7.85046e-17\nx: 4.94066e-324 sqrt(x):2.2227587494850775e-162 squareRoo(x): 2.22275874948508e-162 relative difference: 5.55112e-16\nx: 2.22507e-308 sqrt(x):1.4916681462400413e-154 squareRoo(x): 1.491668146240043e-154 relative difference: 5.55112e-16\nx: 1.49167e-154 sqrt(x): 1.221338669755462e-77 squareRoo(x): 1.2213386697554618e-77 relative difference: -7.85046e-17\nx: 1.34078e+154 sqrt(x): 1.1579208923731618e+77 squareRoo(x): 1.157920892373162e+77 relative difference: 5.55112e-17\nx: 1.79769e+308 sqrt(x):1.3407807929942596e+154 squareRoo(x):1.3407807929942597e+154 relative difference: 5.55112e-17\nDone\n</code></pre>\n<hr />\n<p>See also <a href=\"https://en.wikipedia.org/wiki/Fast_inverse_square_root\" rel=\"nofollow noreferrer\">Fast inverse square root</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-16T10:22:51.493", "Id": "266098", "ParentId": "260559", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T13:43:41.773", "Id": "260559", "Score": "2", "Tags": [ "algorithm", "c", "mathematics", "signal-processing" ], "Title": "Implementation of the square root for real time application" }
260559
<p>I am learning C from <em>C Primer Plus</em>, and am still a beginner. I have been introduced to only two functions for input, <code>scanf()</code> and <code>getchar()</code>.</p> <p>According to me, when <code>stdin</code> is associated with input from a keyboard, there are 4 possibilities for user input in this program:</p> <ol> <li>User provides valid input and presses <kbd>enter</kbd>.</li> <li>User provides valid input and triggers EOF.</li> <li>User provides invalid input (including no input) and presses <kbd>enter</kbd>.</li> <li>User provides invalid input (including no input) and triggers EOF.</li> </ol> <p>For (1) and (2), I want the program to continue normally. For (3), I want the program to keep asking the user for valid input. For (4), I want the program to abort.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #define PROMPT &quot;Enter a non-negative number: &quot; double get_valid_input(void); bool flush(void); int main(void) { double inputNum = get_valid_input(); printf(&quot;Your input = %.2f\n&quot;, inputNum); return 0; } double get_valid_input(void) { double inputNum; bool endOfFile; int a; while ((printf(PROMPT), (a = scanf(&quot;%lf&quot;, &amp;inputNum)) != 1) || ((a == 1) &amp;&amp; (inputNum &lt; 0.0))) { a = 0; endOfFile = flush(); if (endOfFile == true) break; } if (a == 0) exit(EXIT_FAILURE); else endOfFile = flush(); return inputNum; } bool flush(void) { int f; while ((f = getchar()) != '\n' &amp;&amp; f != EOF) continue; if (f == EOF) { printf(&quot;\n&quot;); return true; } else return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T22:08:03.880", "Id": "514370", "Score": "2", "body": "I believe your `(a == 1)` check is redundant, since it is in the 2nd part of an `||` expression. (This comment is redundant, given @Reinderein's reply below, but I include it for completeness.) Also, if you make the `PROMPT`, the `scanf` format string, and a validation function into parameters, you could have the start of a generic input validation module." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T14:53:24.647", "Id": "514547", "Score": "1", "body": "BTW, I learned from that same book, but the original 1984 edition." } ]
[ { "body": "<h1>General Observations</h1>\n<ul>\n<li>The code is quite readable.</li>\n<li>Using void in the function declarations is good.</li>\n<li>Using stdlib.h for <code>EXIT_FAILURE</code> is good, but the <code>return</code> from <code>main()</code> should be <code>return EXIT_SUCCESS;</code></li>\n</ul>\n<h1>Avoid Global References of Any Form</h1>\n<p>There are good reasons to use <code>#define CONSTANT</code> to define constants used throughout programs, but doing this for prompt strings probably isn't a good idea. If the program being developed needs to communicate with users in multiple languages it is better to pass the C equivalent of a string <code>char *str</code> into a function instead. It would be better to define <code>prompt</code> as a local variable in main and pass it by reference into the function <code>get_valid_input()</code>.</p>\n<h1>Function Prototypes</h1>\n<p>In a small program such as this it is better to put the functions in the proper order to reduce the amount of code to be written. Reducing the amount of code necessary is better because if the function declarations need to change they only need to be changed in one place rather than multiple places. Function prototypes are best when linking multiple code files together, then the prototypes are in a header file associated with the source file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T15:56:26.710", "Id": "260571", "ParentId": "260562", "Score": "8" } }, { "body": "<h2>Non-exported functions</h2>\n<p>Declare <code>get_valid_input</code> and <code>flush</code> as <code>static</code> since you're in a single translation unit.</p>\n<h2>Foot-cannon one-liners</h2>\n<pre><code>while ((printf(PROMPT), (a = scanf(&quot;%lf&quot;, &amp;inputNum)) != 1)\n</code></pre>\n<p>takes the common C antipattern of in-condition assignment even further: it's an entire code-block in a condition. Please consider rewriting this to</p>\n<pre><code>while (true) {\n printf(PROMPT);\n a = scanf(&quot;%lf&quot;, &amp;inputNum);\n if (a == 1 &amp;&amp; inputNum &gt;= 0)\n break;\n // ...\n</code></pre>\n<h2>scanf</h2>\n<p>It's a mess. It pollutes the input buffer on failure, among other nasty surprise behaviours. Any serious attempt at comprehensive input validation ends up ditching <code>scanf</code> in favour of <code>sscanf</code>. Read <a href=\"http://c-faq.com/stdio/scanfprobs.html\" rel=\"noreferrer\">http://c-faq.com/stdio/scanfprobs.html</a> and <a href=\"http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html\" rel=\"noreferrer\">http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html</a> for flavour.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T20:46:12.897", "Id": "260581", "ParentId": "260562", "Score": "9" } }, { "body": "<p><strong>Bug</strong></p>\n<p>&quot;User provides ... no input and presses enter.&quot;. <code>scanf(&quot;%lf&quot;, &amp;inputNum)</code> does not return in that case. Waits for non-white-space input.</p>\n<p><strong>Beware % in the prompt</strong></p>\n<p><code>printf(PROMPT)</code> can lead to undefined behavior (UB) with when <code>PROMPT</code> has a <code>'%'</code> in it. Use <code>fputs()</code></p>\n<pre><code>// printf(PROMPT)\nfputs(PROMPT, stdout)\n</code></pre>\n<p><strong>Bug</strong></p>\n<p>&quot;Enter a non-negative number&quot; --&gt; Rejecting values with <code>inputNum &lt; 0.0</code> still allows input like <code>&quot;-0.0&quot;</code> and <code>&quot;NaN&quot;</code>.</p>\n<p><code>inputNum &lt; 0.0</code> --&gt; <code>(signbit(inputNum) || isnan(inputNum))</code>or the like.</p>\n<p><strong>Bug</strong></p>\n<p><code>scanf(&quot;%lf&quot;, &amp;inputNum)</code> allows an input line like <code>&quot;123.4xyz\\n&quot;</code> as <code>scanf(&quot;%lf&quot;...</code> does not work with a <em>line</em> of input.</p>\n<p><strong>Debug with <code>%g</code></strong></p>\n<p><code>&quot;%g&quot;</code> is more informative with small values and less noise with large ones.</p>\n<pre><code>// printf(&quot;Your input = %.2f\\n&quot;, inputNum);\nprintf(&quot;Your input = %.2g\\n&quot;, inputNum);\n</code></pre>\n<hr />\n<p><strong>Pedantic: <code>stdin</code> error not handled clearly</strong></p>\n<p>Code fails to distinguish between end-of-file and rare <code>stdin</code> error. <code>stdin</code> error is different than textual input error.</p>\n<p><strong>Pedantic: <code>flush()</code> may consume good data</strong></p>\n<p>Rare: <code>scanf(&quot;%lf&quot;, &amp;inputNum)</code> returns <code>EOF</code> due to a transient input error. The following <code>flush()</code> then may consume good input.</p>\n<hr />\n<p><strong>Alternative</strong></p>\n<p>Some unchecked sample code to explore other ideas.</p>\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;float.h&gt;\n#include &lt;math.h&gt;\n#include &lt;stdio.h&gt;\n\n// Reasonable input perhaps as long as DBL_MAX in non-exponential notation.\n#define GET_POSITIVE_LINE_N DBL_MAX_10_EXP\n\ndouble get_postive_double(const char *prompt) {\n // Readily handle inputs up to 2x reasonable length.\n // More code needed to detect nefarious super long inputs.\n char buf[GET_POSITIVE_LINE_N * 2];\n\n // Possible to construct other loop styles.\n // I find the below clear.\n while (1) {\n if (prompt) {\n fputs(prompt, stdout);\n }\n\n if (fgets(buf, sizeof buf, stdin) == NULL) {\n // Suggest some note about early exit and where\n fprintf(stderr, &quot;%s:%u end-of-file&quot;, __FILE__, __LINE__);\n exit(EXIT_FAILURE);\n }\n\n // As reasonable, declare objects when needed\n char *endptr;\n errno = 0; // See note below\n double inputNum = strtod(buf, &amp;endptr);\n\n // No conversion\n if (buf == endptr) {\n continue;\n }\n\n // Look for trailing non-white-space junk\n while (isspace(*(unsigned char* )endptr)) {\n endptr++;\n }\n if (*endptr) {\n continue;\n }\n\n // Allow only positive values\n if (signbit(inputNum) || isnan(inputNum)) {\n continue;\n }\n\n return inputNum;\n }\n\n // Code never reaches this point\n}\n</code></pre>\n<p><code>strtod()</code> could first use a <code>errno==0</code> to later detect various errors. I find the default handling sufficient and detailed handling of <code>errno</code>, especially with tiny values not that portable, so left that pedantic corner out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T16:41:22.887", "Id": "514553", "Score": "0", "body": "I'll definitely incorporate all of these wonderful ideas once I'm done with the book :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T00:22:18.593", "Id": "260683", "ParentId": "260562", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:19:28.223", "Id": "260562", "Score": "7", "Tags": [ "c", "validation", "io" ], "Title": "Input validation" }
260562
<p>This is intended as a simple layout for an auto showroom site:</p> <p><strong>Disclaimer</strong> <em>Details changed from original for privacy</em></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-family: Helvetica, sans-serif; background-color: #B2BEB5; } b { font-family: Helvetica, sans-serif; } h1, h2, h3, h4, h5, h6 { font-family: Helvetica, sans-serif; } header.brandname { background-color: #333; color: #FFF; padding: 20px; } .dublin-ac1 { background-color: #FFF; font-family: Verdana, sans-serif; color: red; } .flex-container { font-family: Arial, sans-serif; font-size: 14px; line-height: 16px; } .flex-container h2, h3, h4 { font-family: Arial, sans-serif; } .flex-container { color: #333; display: flex; flex-direction: row; width: 880px; padding: 20px; } .flex-left { width: 195%; padding: 10px; margin-top: -30px; } .flex-right { width: 95%; text-align: right; padding: 10px; margin-top: -30px; } .flex-left1 { width: 50%; margin-top: -50px; } .flex-left1 img { max-width:100%; max-height:100%; } .flex-right1 { width: 90%; margin-left: 10px; margin-top: -70px; margin-bottom: auto; } .az2 { background-color: #FFFFFF; margin: 30px; margin-bottom: 20px; margin-right: 130px; width: 920px; border: 2px solid; height: auto; } .price { font-weight: 700; } section.dublinvehicles { background-color: #FFF; margin-left: 20px; height: auto; padding: 15px; } /* div.image-card-thumbnails { display: flex; position: relative; flex-direction: column; flex-grow: 1; max-width: 60%; } */ div.image-card-thumbnails { width: 300px; display: flex; flex-direction: column; align-items: flex-start; max-width: 34%; } .image-card-thumbnails img { max-width: 90%; max-height: 33%; } div.image-card-thumbnails-1 { display: flex; flex-direction: row; max-width: 34%; object-fit: contain; } .image-card-thumbnails-1 img { max-width: 90%; max-height: 33%; } .aw1 { width: 230px; object-fit: cover; position: absolute; bottom: -10px; margin-left: -320px; margin-bottom: 80px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header class="brandname"&gt; &lt;h1&gt;NEW DUBLIN CAR SALES&lt;/h1&gt; &lt;/header&gt; &lt;article class="dublin-ac1"&gt; &lt;h3&gt;26 North Belfast Road, Dublin 11&lt;/h3&gt; &lt;h3&gt;Tel: 086 000 0000&lt;/h3&gt; &lt;/article&gt; &lt;section class="dublinvehicles"&gt; &lt;h3&gt;20 minutes from Dublin town centre&lt;/h3&gt; &lt;article class="az2"&gt; &lt;div class="flex-container"&gt; &lt;div class="flex-left"&gt; &lt;h3&gt;2021 TOYOTA RAV4 2.5 HYBRID PREMIUM 5dr&lt;/h3&gt; &lt;/div&gt; &lt;div class="flex-right price"&gt; &lt;h3&gt;€38,000 / £30,400&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="flex-container"&gt; &lt;div class="flex-left1"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/2019_Toyota_RAV4_Excel_HEV_CVT_2.5_Front.jpg/1280px-2019_Toyota_RAV4_Excel_HEV_CVT_2.5_Front.jpg"&gt; &lt;div class="image-card-thumbnails"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/2019_Toyota_RAV4_Hybrid_01.jpg/1024px-2019_Toyota_RAV4_Hybrid_01.jpg"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/2019_Toyota_RAV4_hybrid_in_Taiwan_taxi_service.jpg/1024px-2019_Toyota_RAV4_hybrid_in_Taiwan_taxi_service.jpg"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2020_Toyota_Rav4_XLE%2C_Front_Left%2C_09-30-2020.jpg/1280px-2020_Toyota_Rav4_XLE%2C_Front_Left%2C_09-30-2020.jpg"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="flex-right1"&gt; &lt;p&gt;5 door, choice of colours, well-equipped, ONLY 20 LEFT&lt;/p&gt; &lt;/div&gt; &lt;/article&gt; &lt;article class="az2"&gt; &lt;div class="flex-container"&gt; &lt;div class="flex-left"&gt; &lt;h3&gt;2012 PEUGEOT 207 1.4 VTi COMFORT 4dr&lt;/h3&gt; &lt;/div&gt; &lt;div class="flex-right price"&gt; &lt;h3&gt;€1,744/£1,395&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="flex-container"&gt; &lt;div class="flex-left1"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/74/Peugeot_207_CN_sedan_2_China_2012-05-13.jpg/1024px-Peugeot_207_CN_sedan_2_China_2012-05-13.jpg"&gt; &lt;/div&gt; &lt;div class="flex-right1"&gt; &lt;p&gt;4 door, maroon, 120,000 km, NCT, good condition&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;article class="az2"&gt; &lt;div class="flex-container"&gt; &lt;div class="flex-left"&gt; &lt;h3&gt;1991/1992/1993 TOYOTA HIACE 3.0 DIESEL VAN&lt;/h3&gt; &lt;/div&gt; &lt;div class="flex-right price"&gt; &lt;h3&gt;€1,800 / £1,440&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="flex-container"&gt; &lt;div class="flex-left1"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/1998-2004_Toyota_HiAce_%28RZH103R%29_van_%282011-11-04%29.jpg/180px-1998-2004_Toyota_HiAce_%28RZH103R%29_van_%282011-11-04%29.jpg"&gt; &lt;/div&gt; &lt;div class="flex-right1"&gt; &lt;p&gt;white, choice of models&lt;/p&gt; &lt;div class="aw1"&gt; &lt;div class="image-card-thumbnails-1"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/GE-RZH125B-Kanachu-a13-Yumebus.jpg/800px-GE-RZH125B-Kanachu-a13-Yumebus.jpg"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/KingTaxi_saga_44.jpg/1280px-KingTaxi_saga_44.jpg"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/1999_Toyota_HiAce_%28RZH103R%29_van_%2824567060179%29.jpg/1024px-1999_Toyota_HiAce_%28RZH103R%29_van_%2824567060179%29.jpg"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Toyota_Hiace_%2825153414567%29.jpg/800px-Toyota_Hiace_%2825153414567%29.jpg"&gt; &lt;/div&gt; &lt;div class="image-card-thumbnails-1"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Toyota_Hiace_100_long_van_001.JPG/1024px-Toyota_Hiace_100_long_van_001.JPG"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Toyota_Hiace_100_long_van_001.JPG/1024px-Toyota_Hiace_100_long_van_001.JPG"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Toyota_Hiace_in_Ayutthaya.jpg/1024px-Toyota_Hiace_in_Ayutthaya.jpg"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/%2790-%2791_Toyota_HiAce.JPG/1024px-%2790-%2791_Toyota_HiAce.JPG"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;/section&gt;</code></pre> </div> </div> </p> <p>What I am looking for is constructive criticism on how to improve this code which is entirely written by hand, and is not copied from elsewhere. It's taken inspiration from real-life car sales sites but is currently HTML-only, although it may be adapted for PHP MVCs model-view controllers.</p> <p>Influence was taken from <a href="https://www.autotrader.co.uk/dealers/hertfordshire/waltham-cross/allwood-automobiles-361/stock?sort=price-asc&amp;page=1&amp;dealer=361&amp;onesearchad=Used&amp;onesearchad=Nearly%20New&amp;onesearchad=New&amp;advertising-location=at_cars&amp;advertising-location=at_profile_cars" rel="nofollow noreferrer">this design on autotrader.co.uk</a> (but with my own coding).</p> <p>I want to try and make a variant of my flexbox code that displays the photos (with a javascript to enlarge them) along the bottom and remains at the bottom even if div class=flex-right-1 extends due to a large amount of text in the box</p> <p>So far, I'm just concentrating on the HTML side of things.</p> <p>I am looking for any constructive criticism on this.</p>
[]
[ { "body": "<p>I think u can use ul tag after <code>&lt;h3&gt;20 minutes from Dublin town centre&lt;/h3&gt;</code> and then use li tag instead of article tag, becuase you have the list of cars in this page, and for list we should use ul and li tag which html is provide for us. <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul\" rel=\"nofollow noreferrer\">you can visit this link for list in html</a></p>\n<p>Then, after this code\n<code>&lt;section class=&quot;dublinvehicles&quot;&gt; &lt;h3&gt;20 minutes from Dublin town centre&lt;/h3&gt;</code>, you should add ul tag and replace all of article of tag by li tag and append to ul tag</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T13:57:26.940", "Id": "260605", "ParentId": "260574", "Score": "1" } }, { "body": "<p>I think you can improve semantics by using the <code>&lt;main&gt;</code> element:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;header&gt;\n...\n&lt;/header&gt;\n\n&lt;main&gt;\n &lt;section&gt;, &lt;article&gt;, &lt;div&gt;, etc...\n&lt;/main&gt;\n</code></pre>\n<p>And instead of a <code>&lt;h3&gt;</code> to write an address, you can simply use the <code>&lt;address&gt;</code> element as follows:</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-css lang-css prettyprint-override\"><code>a[href^=\"tel\"]::before {\n content: \" \";\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;article class=\"dublin-ac1\"&gt;\n &lt;address&gt;\n 26 North Belfast Road, Dublin 11&lt;br&gt;\n &lt;a href=\"tel:+10860000000\"&gt;Tel: 086 000 0000&lt;/a&gt;\n &lt;/address&gt;\n&lt;/article&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Of course, you also can use both <code>&lt;address&gt;</code> and <code>&lt;h3&gt;</code> elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T00:27:03.947", "Id": "260724", "ParentId": "260574", "Score": "0" } } ]
{ "AcceptedAnswerId": "260605", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T16:17:16.320", "Id": "260574", "Score": "2", "Tags": [ "html", "css" ], "Title": "Code for car sales platform designed with flexbox in HTML5" }
260574
<p>I am attempting to build an Android APP with the ability to connect specified FTP server in Java. The connection operation has been performed in <code>FTPconnection</code> class and the network call of FTP has been separated from main thread via <code>java.util.concurrent.Executors</code>.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p>Project name: FTPConnectionTest</p> </li> <li><p><code>FTPconnection</code> class implementation</p> <pre><code>package com.example.ftpconnectiontest; import android.util.Log; import java.io.IOException; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import org.apache.commons.net.SocketClient; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPconnection { private native String getHostname(); private native String getUsername(); private native String getPassword(); private static String FTPHostName = &quot;&quot;; private static final int FTPPort = 21; private static String FTPUsername = &quot;&quot;; private static String FTPPassword = &quot;&quot;; public FTPconnection() { FTPHostName = getHostname(); FTPUsername = getUsername(); FTPPassword = getPassword(); } public FTPClient connectftp() { // Reference: https://stackoverflow.com/a/8761268/6667035 FTPClient ftp = new FTPClient(); try { // Reference: https://stackoverflow.com/a/55950845/6667035 // The argument of `FTPClient.connect` method is hostname, not URL. ftp.connect(FTPHostName, FTPPort); boolean status = ftp.login(FTPUsername, FTPPassword); if (status) { ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.sendCommand(&quot;OPTS UTF8 ON&quot;); } System.out.println(&quot;status : &quot; + ftp.getStatus()); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (SocketException en) { en.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ftp; } } </code></pre> </li> <li><p><code>ftpconnectiontest.cpp</code>: The place where store the authorization information. I am wondering is the design safe enough in general FTP connection application.</p> <pre><code>#include &lt;jni.h&gt; #include &lt;string&gt; extern &quot;C&quot; JNIEXPORT jstring JNICALL Java_com_example_ftpconnectiontest_FTPconnection_getHostname(JNIEnv *env, jobject thiz) { std::string output = &quot;Hostname&quot;; return env-&gt;NewStringUTF(output.c_str()); } extern &quot;C&quot; JNIEXPORT jstring JNICALL Java_com_example_ftpconnectiontest_FTPconnection_getUsername(JNIEnv *env, jobject thiz) { std::string output = &quot;Username&quot;; return env-&gt;NewStringUTF(output.c_str()); } extern &quot;C&quot; JNIEXPORT jstring JNICALL Java_com_example_ftpconnectiontest_FTPconnection_getPassword(JNIEnv *env, jobject thiz) { std::string output = &quot;Password&quot;; return env-&gt;NewStringUTF(output.c_str()); } </code></pre> </li> <li><p><code>java.util.concurrent.Executors</code> class implementation</p> <pre><code>ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -&gt; { String threadName = Thread.currentThread().getName(); showToast(threadName, Toast.LENGTH_SHORT); FTPconnection ftpConnect = new FTPconnection(); FTPClient ftpClient = ftpConnect.connectftp(); final String LOG_TAG = &quot;executor&quot;; try { Log.v(LOG_TAG, Boolean.toString(ftpClient.isConnected())); showToast(Boolean.toString(ftpClient.isConnected()), Toast.LENGTH_SHORT); } catch (Exception ex) { ex.printStackTrace(); } }); </code></pre> </li> <li><p>User permission setting</p> <pre><code>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot; /&gt; </code></pre> </li> <li><p><code>AndroidManifest.xml</code></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.example.ftpconnectiontest&quot;&gt; &lt;application android:allowBackup=&quot;true&quot; android:icon=&quot;@mipmap/ic_launcher&quot; android:label=&quot;@string/app_name&quot; android:roundIcon=&quot;@mipmap/ic_launcher_round&quot; android:supportsRtl=&quot;true&quot; android:theme=&quot;@style/Theme.FTPConnectionTest&quot;&gt; &lt;activity android:name=&quot;.MainActivity&quot; android:exported=&quot;true&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot; /&gt; &lt;/manifest&gt; </code></pre> </li> <li><p><code>build.gradle</code></p> <pre><code>plugins { id 'com.android.application' } android { compileSdk 31 defaultConfig { applicationId &quot;com.example.ftpconnectiontest&quot; minSdk 26 targetSdk 31 versionCode 1 versionName &quot;1.0&quot; testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot; externalNativeBuild { cmake { cppFlags '' } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_11 targetCompatibility JavaVersion.VERSION_11 } externalNativeBuild { cmake { path file('src/main/cpp/CMakeLists.txt') version '3.18.1' } } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') // https://mvnrepository.com/artifact/commons-net/commons-net implementation group: 'commons-net', name: 'commons-net', version: '20030805.205232' implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.1' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' } </code></pre> </li> </ul> <p><strong>Full Testing Code</strong></p> <p><code>MainActivity.java</code> implementation:</p> <pre><code>package com.example.ftpconnectiontest; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import org.apache.commons.net.ftp.FTPClient; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MainActivity extends AppCompatActivity { private static final int ACCESS_NETWORK_STATE_CODE = 1; static { System.loadLibrary(&quot;ftpconnectiontest&quot;); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkPermission(Manifest.permission.ACCESS_NETWORK_STATE, ACCESS_NETWORK_STATE_CODE); FTPConnectionTest(); } private void FTPConnectionTest() { ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -&gt; { if (BuildConfig.DEBUG) { String threadName = Thread.currentThread().getName(); showToast(threadName, Toast.LENGTH_SHORT); } FTPconnection ftpConnect = new FTPconnection(); FTPClient ftpClient = ftpConnect.connectftp(); final String LOG_TAG = &quot;executor&quot;; try { Log.v(LOG_TAG, Boolean.toString(ftpClient.isConnected())); showToast(Boolean.toString(ftpClient.isConnected()), Toast.LENGTH_SHORT); } catch (Exception ex) { ex.printStackTrace(); } }); } private void showToast(@StringRes int res, int duration) { showToast(getResources().getString(res), duration); return; } private void showToast(String textInput, int duration) { Context context = getApplicationContext(); CharSequence text = textInput; // Reference: https://stackoverflow.com/a/12897386/6667035 runOnUiThread(() -&gt; Toast.makeText(context, text, duration).show()); } // Function to check and request permission. public void checkPermission(@NonNull String permission, int requestCode) { if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { if (BuildConfig.DEBUG) { showToast(&quot;Permission already granted&quot;, Toast.LENGTH_SHORT); } } } } </code></pre> <p>If there is any possible improvement, please let me know.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T17:13:52.360", "Id": "260576", "Score": "3", "Tags": [ "java", "multithreading", "android", "networking", "ftp" ], "Title": "Android APP connect to FTP server in Java" }
260576
<p>I want to use only one for Loop for this code. Is this possible? If not then how can I optimise my code further?</p> <p>It works well for the constraint 1 ≤ T ≤ 10, 2 ≤ N ≤ 10^3, 1 ≤ M ≤ 10^5, but I am getting time limit exceeded for 1 ≤ T ≤ 100, 2 ≤ N ≤ 10^5, 1 ≤ M ≤ 10^5.</p> <pre><code>#include &lt;iostream&gt; using namespace std; #include &lt;vector&gt; #include &lt;bits/stdc++.h&gt; #include &lt;iterator&gt; #include &lt;utility&gt; #include &lt;boost/multiprecision/cpp_int.hpp&gt; using boost::multiprecision::cpp_int; using namespace std; int main() { // your code goes here ios_base::sync_with_stdio(false); cin.tie(NULL); cpp_int t,ans; std::cin &gt;&gt; t; while(t--&gt;0) { cpp_int n; std::cin &gt;&gt; n; cpp_int m; std::cin &gt;&gt; m; cpp_int count=0; for(int a=1;a&lt;=n;++a) { for(int b=1;b&lt;=n;++b) { if(a&lt;b) { if( ((m%a)%b) == ((m%b)%a) ) count++; } } } cout &lt;&lt; count &lt;&lt; &quot;\n&quot;; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T17:45:20.670", "Id": "514349", "Score": "6", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T18:15:06.730", "Id": "514357", "Score": "3", "body": "This looks like a programming challenge, could you please include the text of the question and a link to the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T03:33:05.087", "Id": "514378", "Score": "0", "body": "[link](https://www.codechef.com/MAY21C/problems/MODEQ)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T06:40:51.127", "Id": "514390", "Score": "0", "body": "Do you need to use `boost::multiprecision::cpp_int` or can you work with a regular integer type? The latter would likely be faster." } ]
[ { "body": "<p>I'm sure the puzzle intends you to use more math and less brute force. But here's a 2x speedup right away: Any loop of the form</p>\n<pre><code>for (int a=1; a &lt;= n; ++a) {\n for (int b = 1; b &lt;= n; ++b) {\n if (a &lt; b) {\n do something\n }\n }\n}\n</code></pre>\n<p>can obviously be replaced with a loop of the form</p>\n<pre><code>for (int a=1; a &lt;= n; ++a) {\n for (int b = a+1; b &lt;= n; ++b) {\n assert(a &lt; b); // compile with -DNDEBUG for speed\n do something\n }\n}\n</code></pre>\n<p>(Also, notice my indentation and whitespace style changes. Adopt them in all the code you write.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T02:49:44.423", "Id": "260591", "ParentId": "260577", "Score": "2" } }, { "body": "<p>Starting from <a href=\"https://codereview.stackexchange.com/a/260591/56343\">Quuxplusone's answer</a>, let's get rid of some more operations.</p>\n<pre><code>for(int a = 1; a &lt;= n; ++a)\n{\n for(int b = a + 1; b &lt;= n; ++b)\n {\n if( ((m%a)%b) == ((m%b)%a) )\n count++;\n }\n}\n</code></pre>\n<p>One thing to notice is that the quantity <code>m%a</code> never changes during the inner loop. So, we can move it to the outer loop.</p>\n<pre><code>for(int a = 1; a &lt;= n; ++a)\n{\n int ma = m%a;\n for(int b = a + 1; b &lt;= n; ++b)\n {\n if( (ma%b) == ((m%b)%a) )\n count++;\n }\n}\n</code></pre>\n<p>The next transformation relies on two facts:</p>\n<ol>\n<li><code>x % y &lt; y</code> for all positive integers <code>x</code> and <code>y</code>.</li>\n<li><code>x % y == x</code> for all positive integers <code>x</code> and <code>y</code> if <code>x</code> &lt; <code>y</code>.</li>\n</ol>\n<p>So, since <code>a &lt; b</code>, <code>(m%a)%b == m%a</code>. This allows us to write <code>ma%b</code> as just <code>ma</code>.</p>\n<pre><code>for(int a = 1; a &lt;= n; ++a) \n{\n int ma = m%a;\n for(int b = a + 1; b &lt;= n; ++b)\n {\n if( ma == ((m%b)%a) )\n count++;\n }\n}\n</code></pre>\n<p>Now, we've reduced the number of modulo operations by nearly half. This comes after the reducing by half in the linked answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T05:17:56.177", "Id": "514381", "Score": "0", "body": "Thanks for your suggestion. But still time limit exceed is coming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T09:15:45.787", "Id": "514393", "Score": "1", "body": "What happens if you replace `cpp_int` with `int`? None of the numbers are big enough to require an arbitrary-precision integer type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T09:39:13.027", "Id": "514394", "Score": "0", "body": "@jerry00 See above question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T04:32:37.573", "Id": "260594", "ParentId": "260577", "Score": "1" } }, { "body": "<p>Don't write <code>using namespace std;</code>. You certainly don't need to write it twice!!</p>\n<p><code>// your code goes here</code> along with the duplicated <code>using</code> declaration makes me think that you did not really proof-read your own code first. Pay attention to what you're writing! It will go a long way to finding improvements and silly mistakes.</p>\n<p><code>#include &lt;bits/stdc++.h&gt;</code> is not a standard header. Some kind of implementation-specific header? Or is it internal details you are not supposed to use directly? Looking it up on Google, I see it's supposed to include all the standard headers... so why are you including others directly as well, and if it's supposed to be a precompiled header it needs to go first. Again, it looks like you're just pasting things together and not understanding or reviewing what you wrote.</p>\n<p><code>cin.tie(NULL);</code>\nDon't use the C macro <code>NULL</code>. C++ has a keyword <code>nullptr</code> now.</p>\n<p><code>cpp_int t,ans;</code>\n<code>ans</code> doesn't seem to be used anywhere, so why are you declaring it? See comments above. In general, don't define things ahead of their use, though the nature of <code>cin&gt;&gt;</code> I see why you are not initializing <code>t</code>. Generally don't declare more than one thing at a time.</p>\n<pre><code>std::cin &gt;&gt; t;\n while(t--&gt;0)\n</code></pre>\n<p>So you loop counting down <code>t</code> until it reaches 0. You need <code>t</code> to be a arbitrary precision int because 64 bits isn't big enough?? If you are looping 2 to the 64 times, that would indeed take a long time. That's 1.8e19, and if each iteration took one nanosecond that's still on the order of ten billion seconds, or 317 years. So I seriously question your need to make <code>t</code> an extended precision integer and not a plain built-in 32-bit or 64-bit integer.</p>\n<p>Likewise for <code>count</code> where you are counting up. Does your program run for hundreds of years? If not, 64 bit integers is enough!</p>\n<p>Note for performance that <code>%</code> is a very slow operation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T15:06:04.730", "Id": "260612", "ParentId": "260577", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T17:30:08.760", "Id": "260577", "Score": "-3", "Tags": [ "c++", "performance", "time-limit-exceeded" ], "Title": "Is there any way to use a single for Loop for this code?" }
260577
<p>I've added some methods to a basic BST implementation for integers - if anyone can point out some ways that this could be written in a more efficient or clean manner, please let me know.</p> <pre><code>public class BST { /* * 1) Node inner class */ private class Node { int data; Node leftChild, rightChild; public Node(int num, Node left, Node right) { this.data = num; this.leftChild = left; this.rightChild = right; } } // 2) Variables private Node root = null; // every binary search tree object will be assigned a root node = null private int nodeCount = 0; // 3) Methods: size public int size() { return nodeCount; } // 4) Methods: isEmpty public boolean isEmpty() { return (root == null); // if the root of the BST is null (we haven't added any nodes) then the BST is empty } // 5) Methods: contains (recursive), SEARCH public boolean treeContains(int info) { return treeContains(root, info); } public boolean treeContains(Node node, int info) { if (node == null) return false; // corner case: if tree is null, but also BASE CASE // SEARCHING, but looking for a number so we can use O log(n) time if (info &gt; node.data) { // go to the right return treeContains(node.rightChild, info); } else if (info &lt; node.data) { return treeContains(node.leftChild, info); } else { // either node has bigger or smaller data or this case: it is equal return true; } } // 6) Methods: add public boolean add(int newData) { if (treeContains(newData)) return false; else { root = add(root, newData); // NOTE: this works but why can't it just be add(root,newdata) without the &quot;root = &quot; ? nodeCount++; return true; } } public Node add(Node node, int newData) { if (node == null) { node = new Node(newData, null, null); // NOTE: how does this add a node? it doesn't place it anywhere? it just exists somewhere? i mean i understand that by then we're pointing to a space that is null but still } else if (newData &gt; node.data) { node.rightChild = add(node.rightChild, newData); } else { // else if newData is less or equal to node data node.leftChild = add(node.leftChild, newData); } return node; } // 7) Methods: remove // look up node to be removed, set it to null, recursive public boolean remove(int newData) { if (!treeContains(newData)) return false; // will null BST's fall under this ??? else { root = remove(root,newData); // NOTE: why do we need to have root = remove(root, newData) ??? instead of just remove.. nodeCount--; return true; } } public Node remove(Node node, int newData) { if (node.data == newData) { // if we find the node we want to delete // 3 SCENARIOS - the node can be a leaf, can have 1 or 2 children // leaf node if (node.leftChild==null &amp;&amp; node.rightChild== null) { node = null; } // node has left child only else if (node.leftChild !=null &amp;&amp; node.rightChild == null) { node.data = node.leftChild.data; // left child is now node node.leftChild = null; } // node has right child only else if (node.leftChild==null &amp;&amp; node.rightChild!=null) { Node temp = node.rightChild; // trying another way of switching nodes &amp; deleting node.rightChild = null; node.data = temp.data; } // node has both children else { Node temp = findMin(node.rightChild); node.data = temp.data; // switch data node.rightChild = remove(node.rightChild, temp.data); // remove the findMin node, originally node.RC = remove... } } else if (newData &lt; node.data) { node.leftChild = remove (node.leftChild, newData); } else { // if newData &gt; node.data node.rightChild = remove(node.rightChild, newData); } return node; } // Helper method to find the leftmost node (which has the smallest value) private Node findMin(Node node) { while (node.leftChild != null) node = node.leftChild; return node; } // 8) Methods: In order tree traversal public void traverseInOrder(Node node) { if (node == null) return; traverseInOrder(node.leftChild); System.out.print(node.data + &quot; &quot;); traverseInOrder(node.rightChild); } // 9) Methods: Pre order tree traversal public void traversePreOrder(Node node) { if (node == null) return; System.out.print(node.data + &quot; &quot;); traversePreOrder(node.leftChild); traversePreOrder(node.rightChild); } // 10) Methods: Post order tree traversal public void traversePostOrder(Node node) { if (node == null) return; traversePostOrder(node.leftChild); traversePostOrder(node.rightChild); System.out.print(node.data + &quot; &quot;); } // RUN METHODS public static void main(String[] args) { BST tree1 = new BST(); tree1.add(10); tree1.add(7); tree1.add(5); tree1.add(8); tree1.add(20); tree1.add(15); tree1.add(25); tree1.traverseInOrder(tree1.root); System.out.println( &quot;\nSize of tree is: &quot; + tree1.size() ); System.out.println( &quot;Root of tree is: &quot; + tree1.root.data ); System.out.println( &quot;Min num of tree is: &quot; + tree1.findMin(tree1.root).data ); System.out.println( &quot;Does the tree contain the #5 ? &quot; + tree1.treeContains(5) ); tree1.remove(8); tree1.remove(20); tree1.traverseInOrder(tree1.root); System.out.println( &quot;\nSize of tree is: &quot; + tree1.size() ); } } </code></pre> <p>Thank you!!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T12:13:28.700", "Id": "514403", "Score": "0", "body": "You're looking to optimize, is the code too slow right now? Have you done any profiling? It's a very common fallacy for new coders to want to optimize the ever living daylight out of everything but in general it's much better to make something that works and is complete first and then optimize the final product, this prevents you spending 90% of your time improving performance by 1% as opposed to spending 10% of your time improving performance by 90% once you know what to focus on." } ]
[ { "body": "<p>I am not a Java devloper, so take review with a grain of salt.</p>\n<hr />\n<p>There are a lot of unncessary comments:</p>\n<blockquote>\n<p><code>3) Methods: size</code></p>\n<p><code>4) Methods: isEmpty</code></p>\n</blockquote>\n<p>We can already see that it is a method and what it's name is by looking at the code. Adding a docstring is optional for such short methods.</p>\n<hr />\n<pre><code>public Node(int num, Node left, Node right) {\n this.data = num;\n ...\n}\n</code></pre>\n<p>Why is the argument named <code>num</code>, but assigned to <code>data</code>? Later on in code, you call <code>num</code> as <code>newData</code>, which is more appropriate.</p>\n<hr />\n<pre><code>if (treeContains(newData)) return false;\n else {\n root = add(root, newData);\n nodeCount++;\n return true; \n }\n</code></pre>\n<p>This looks really awkward to me and I would rewrite as:</p>\n<pre><code>if (treeContains(newData)) return false;\n\nroot = add(root, newData);\nnodeCount++;\nreturn true;\n</code></pre>\n<hr />\n<blockquote>\n<p><code>// NOTE: this works but why can't it just be add(root,newdata) without the &quot;root = &quot; ?</code></p>\n</blockquote>\n<p>This is because <code>root</code>, defined as class instance <code>private Node root = null</code> is updated</p>\n<hr />\n<blockquote>\n<p><code>else if (node.leftChild !=null &amp;&amp; node.rightChild == null)</code></p>\n<p><code>else if (node.leftChild==null &amp;&amp; node.rightChild!=null)</code></p>\n</blockquote>\n<p>Spacing is all over the place. Prefer spaces around the equality operator. For example, <code>node.leftChild == null</code></p>\n<hr />\n<blockquote>\n<p><code>System.out.println( &quot;Root of tree is: &quot; + tree1.root.data );</code></p>\n</blockquote>\n<p>New public methods should be created (<code>getRoot()</code> and <code>getValue()</code>) for encapsulation.</p>\n<hr />\n<blockquote>\n<p><code>public boolean add(int newData)</code></p>\n</blockquote>\n<p>Method signature looks odd to me. What is the meaning of the <code>boolean</code> that is returned? (add to documentation)</p>\n<p>Why is same-valued nodes not allowed?</p>\n<hr />\n<blockquote>\n<p><code>nodeCount++;</code></p>\n<p><code>nodeCount--;</code></p>\n</blockquote>\n<p>In this case, it does not matter much if pre- or post-increment/decrement is used. Pre-increment should be used when old value does not matter</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T05:27:07.900", "Id": "514382", "Score": "0", "body": "Thank you!! This was super helpful! One quick question though, when you say that \"This is because root, defined as class instance private Node root = null is updated\" do you mean that the subtrees of the root node are updated? or that the root node itself is occasionally updated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T17:44:22.257", "Id": "514419", "Score": "0", "body": "In this case, it is both. I think the confusion comes from the odd method signatures. If I'm correct, the `root = ` part of `root = add(...)` is only needed when `root == null` (and not in the general case). Try `if (root == null) { root = add(root, newData); } else { add(root, newData); }` and see if it makes sense" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T17:46:18.237", "Id": "514420", "Score": "0", "body": "This should also answer your question in the comments: `// NOTE: how does this add a node? it doesn't place it anywhere? it just exists somewhere? i mean i understand that by then we're pointing to a space that is null but still`. The node is assigned to `root` in the first case, and the subtree in the others" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T23:38:15.860", "Id": "260587", "ParentId": "260579", "Score": "2" } }, { "body": "<blockquote>\n<pre><code> if (!treeContains(newData)) return false; // will null BST's fall under this ???\n \n else {\n</code></pre>\n</blockquote>\n<p>Please don't do this. It is a pain to read and can cause bugs as separating the <code>else</code> from the <code>if</code> makes it so that it is quite possible that the <code>if</code> is on one screen and the <code>else</code> is off the bottom. People know to check for an <code>else</code> on the next line. Making us continue to check past that is just cruel.</p>\n<p>It's also unnecessary in this case. You are returning from the initial clause. So the rest of the method will only run if the check fails. Therefore, you don't need to use an <code>else</code> at all. Just the <code>if</code> is sufficient.</p>\n<p>As a general rule, try to avoid mixing the statement and block forms in the same control structure. It adds cognitive load unnecessarily when someone reads the code. And in general, people read code more than they write it. Because most development work is changing existing code rather than writing new code.</p>\n<p>There is a school of thought that you should never use the statement form of control structures, as it leads to a number of opportunities for weird, hard-to-find bugs. For example, compare</p>\n<pre><code> if (!treeContains(newData)) //return false;\n\n doSomething();\n</code></pre>\n<p>to</p>\n<pre><code> if (!treeContains(newData)) {\n //return false;\n }\n\n doSomething();\n</code></pre>\n<p>At first glance, these might seem to do the same thing. But in actuality, they are quite different. Particularly if <code>doSomething</code> has important side effects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T11:17:48.740", "Id": "260600", "ParentId": "260579", "Score": "1" } } ]
{ "AcceptedAnswerId": "260587", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T19:44:30.030", "Id": "260579", "Score": "1", "Tags": [ "java", "performance", "object-oriented", "binary-search", "binary-tree" ], "Title": "How can I optimize this Binary Search Tree?" }
260579
<p>I was given a spreadsheet of data that I turned into a CSV file and then converted it into a JSON file.</p> <p>I threw it into my application and I am processing it in the following manner:</p> <pre><code>const fs = require(&quot;fs&quot;); class DataRepository { constructor(filename) { if (!filename) { throw new Error(&quot;Creating a repository requires a filename&quot;); } this.filename = filename; try { fs.accessSync(this.filename); } catch (error) { console.error(&quot;data does not exist&quot;); } } async getAll() { // Open the file called this.filename return JSON.parse( await fs.promises.readFile(this.filename, { encoding: &quot;utf-8&quot;, }) ); } async getOneBy(filters) { const records = await this.getAll(); for (let record of records) { let found = true; for (let key in filters) { if (record[key] !== filters[key]) { found = false; } } if (found) { return record; } } } } module.exports = new DataRepository(&quot;cales_data.json&quot;); </code></pre> <p>With this approach, will I later be able to create some JavaScript classes to access values inside of it like so:</p> <pre><code>export class Address { constructor() { this.Address = repo.Address; } } </code></pre>
[]
[ { "body": "<p>Some issues:</p>\n<ol>\n<li><p>The constructor recognizes an error if the file doesn't exist but, after logging, just behaves as if nothing is wrong. It does not communicate back an error. Probably, you should just let the exception go back to the caller or don't test it at all in the constructor and let the operation that actually uses the file get the error and communicate that error back to the caller then.</p>\n</li>\n<li><p>You're using a mix of synchronous and asynchronous file access. That's usually a wrong choice because if you are in a programming situation where synchronous access is fine (like startup code or a single user script), then it's just simpler to use synchronous access everywhere. If not (like in a server environment) and you should be using asynchronous access everywhere, then you should be using asynchronous access everywhere.</p>\n</li>\n<li><p>If you're doing this synchronously in nodejs, then <code>require()</code> of a filename with a <code>.json</code> file extension will automatically read and parse the file for you.</p>\n</li>\n<li><p>It's not clear why any of this involves methods on an instantiated object. These are all stand-alone functions. While you do access <code>this.filename</code>, that is not required if you just pass the filename to <code>getAll()</code>.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T23:48:19.777", "Id": "514373", "Score": "0", "body": "I don't care for its methods at this point. I just want to be able to access the contents of `this.filename = \"cales_data.json\";`. Would you recommend a different approach? Perhaps just converting the data to a CSV file and working with that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T23:57:56.977", "Id": "514374", "Score": "0", "body": "@Daniel - Since you aren't storing or caching any data in an instance of the class, the class really seems to have no purpose so I would just create a single function called `getFilteredData(filename, filters = null)` that does what this does. If `filters` is `null`, then it would return a promise that resolves to the whole object like `getAll()` does. If `filters` has a value, then it would work like `getOneBy()`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T23:33:24.307", "Id": "260586", "ParentId": "260582", "Score": "2" } } ]
{ "AcceptedAnswerId": "260586", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T20:49:42.487", "Id": "260582", "Score": "1", "Tags": [ "javascript", "node.js" ], "Title": "Is this file a good starting point for accessing data inside this json file via javascript classes?" }
260582
<p>I'm starting out with Rust and decided to implement a game of Hangman. Can you please provide general feedback on the code?</p> <p>I've already identified some lines (see comments <code>[A]</code>, <code>[B]</code>, <code>[C]</code>) where I cannot find a better way; feedback regarding these would be much appreciated as well.</p> <pre class="lang-rust prettyprint-override"><code>use rand::seq::SliceRandom; use std::io::stdin; const MAX_ALLOWED_ERRORS: i32 = 7; fn main() { println!(&quot;\nWelcome to Hangman!\n&quot;); let to_guess = generate_word(); let mut display = str::repeat(&quot;_ &quot;, to_guess.len()); println!(&quot;{}&quot;, display); let mut nb_errors = 0; loop { let mut user_input = String::new(); stdin().read_line(&amp;mut user_input).expect(&quot;Could not read user input&quot;); match extract_and_capitalize_first_letter(&amp;user_input) { Ok(user_guess) =&gt; { println!(&quot;You guessed: {}&quot;, user_guess); let (is_error, is_full, new_display) = compute_displayed_word( &amp;to_guess, &amp;Some(display), &amp;user_guess, ); // [A] Is there a way to avoid this? Ideally, I would like // to use the same variable for storing the result as // the one passed as the argument display = new_display; if is_error { nb_errors += 1; } if is_full { println!(&quot;You win!&quot;); break; } } Err(_) =&gt; { println!(&quot;Could not process your input&quot;); nb_errors += 1; } } println!(&quot;Error counter: {}&quot;, nb_errors); // maybe later print a real hangman if nb_errors &gt; MAX_ALLOWED_ERRORS { println!(&quot;You lose! The word was: {}&quot;, to_guess); break; } println!(&quot;{}&quot;, display); } } // return the string to display along with 2 booleans: // 1. indicating if an error should be counted // 2. indicating if the word is fully guessed fn compute_displayed_word( word: &amp;String, current_display: &amp;Option&lt;String&gt;, guess: &amp;char, ) -&gt; (bool, bool, String) { let mut is_error = true; let mut is_full = true; // [B] Should I work with a Vec&lt;char&gt;, or is a mutable String ok? let mut new_display = &quot;&quot;.to_string(); for (i, letter) in word.chars().enumerate() { if letter.to_ascii_uppercase().eq(guess) { is_error = false; new_display.push(*guess); } else { let letter_to_display = match current_display { // [C] I couldn't find a way to not do the .chars().collect() // at each iteration, apparently this is due to the // absence of Copy implementation in Vec&lt;char&gt; Some(d) =&gt; d.chars().collect::&lt;Vec&lt;char&gt;&gt;()[i * 2], _ =&gt; '_' }; if letter_to_display.eq(&amp;'_') { is_full = false; } new_display.push(letter_to_display); } new_display.push(' '); } (is_error, is_full, new_display) } fn generate_word() -&gt; String { let all_words = vec![&quot;test&quot;, &quot;cat&quot;, &quot;dog&quot;, &quot;controller&quot;, &quot;operation&quot;, &quot;jazz&quot;]; let chosen_word = all_words.choose(&amp;mut rand::thread_rng()); match chosen_word { Some(&amp;s) =&gt; { return s.to_string(); } None =&gt; panic!(&quot;Could not choose a word!&quot;) } } fn extract_and_capitalize_first_letter(s: &amp;String) -&gt; Result&lt;char, String&gt; { return match s.chars().nth(0) { Some(c) =&gt; { if !c.is_ascii_alphabetic() { return Err(&quot;Only alphabetic characters allowed&quot;.to_string()); } Ok(c.to_ascii_uppercase()) } None =&gt; Err(&quot;Empty string&quot;.to_string()), }; } </code></pre>
[]
[ { "body": "<p>The biggest improvement that you can make is to not store your state in a String. You'll find things much easier if you store your state in appropriate data structures.</p>\n<p>It'll also be easier to understand you code if you organize the current state of the game into a struct rather then across a collection of local variables.</p>\n<p>Here I'd do something like:</p>\n<pre><code>struct Game {\n word_to_guess: String,\n guesses: HashSet&lt;char&gt;\n}\n\nimpl Game {\n fn display(&amp;self) -&gt; String {\n // return the f _ _ _ _ t string you want\n }\n\n fn errors(&amp;self) -&gt; usize {\n // count the number of guesses that aren't contained in the word\n }\n\n fn is_full(&amp;self) -&gt; bool {\n // return true if all the chars in the word are in guesses\n }\n}\n</code></pre>\n<p>You could also use a <code>Vec&lt;bool&gt;</code> to represent which letters are uncovered.</p>\n<blockquote>\n<pre><code> // [A] Is there a way to avoid this? Ideally, I would like\n // to use the same variable for storing the result as\n // the one passed as the argument\n</code></pre>\n</blockquote>\n<p>If you want the function to essentially modify the <code>display</code> variable, you should pass it via a <code>&amp;mut</code> parameter.</p>\n<blockquote>\n<pre><code>// [B] Should I work with a Vec&lt;char&gt;, or is a mutable String ok?\n</code></pre>\n</blockquote>\n<p>As explained above, you should do neither, but choose an appropriate data structure to represent the logical state of the game.</p>\n<blockquote>\n<p>// [C] I couldn't find a way to not do the .chars().collect()\n// at each iteration, apparently this is due to the\n// absence of Copy implementation in Vec</p>\n</blockquote>\n<p>Rust doesn't provide indexing into strings. That's a deliberate choice because indexing into unicode strings is almost always the wrong thing to do. This is rather another reason to store the state in appropriate data structures rather then trying to read your state into and out of a String.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T07:46:20.640", "Id": "515149", "Score": "0", "body": "This is a great answer! I'll give all these suggestions a try. On a purely theoretical view, will the implementation of those `Game` functions not be computationally worse? I only needed to read the String once per guess. Either way, the improvement in readability is so big with your idea!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-23T05:59:28.733", "Id": "515220", "Score": "1", "body": "@BusyAnt, yes, there is some performance lost in my approach. But in the case that the loss is big enough to care about, you can add cached/precomputed values to the Game struct and get that back. However, its best to avoid adding such optimizations until they are needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-21T05:06:24.297", "Id": "261016", "ParentId": "260583", "Score": "3" } } ]
{ "AcceptedAnswerId": "261016", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T20:53:28.700", "Id": "260583", "Score": "1", "Tags": [ "beginner", "rust", "hangman" ], "Title": "Simple Hangman implementation in Rust" }
260583
<p>I have made an AVL tree in C and coded the basic functionality of insertion, deletion, and search. I would love some criticism on my implementation especially on the insertion and deletion section of the code. Furthermore I think I could have used one less variable in the Node structure as you do not need a height for both the left and the right sub-tree instead you just need to know their balance, but for now the implementation contains the height for the left and right sub-tree.</p> <p>TLDR - Criticism on my implementation of the AVL Tree especially the insertion and deletion section of the code.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #define MAX(x, y) (x &lt; y ? y : x) struct Node { void *data; int32_t max_height_left; struct Node *left; int32_t max_height_right; struct Node *right; }; struct AVL_Tree { struct Node *root; size_t size_of_data; int32_t (*compare)(const void *, const void *); void (*print)(const void *); }; int32_t create_tree(struct AVL_Tree **tree, const size_t size_of_data, int32_t (*compare)(const void *, const void *), void (*print)(const void *)) { *tree = malloc(sizeof(**tree)); if(*tree == NULL) { return -1; } (*tree)-&gt;size_of_data = size_of_data; (*tree)-&gt;compare = compare; (*tree)-&gt;print = print; return 0; } static struct Node * left_rotate(struct Node *node) { struct Node *temp; temp = node-&gt;right; node-&gt;right = temp-&gt;left; node-&gt;max_height_right = temp-&gt;max_height_left; temp-&gt;left = node; temp-&gt;max_height_left = MAX(node-&gt;max_height_left, node-&gt;max_height_right) + 1; return temp; } static struct Node * right_rotate(struct Node *node) { struct Node *temp; temp = node-&gt;left; node-&gt;left = temp-&gt;right; node-&gt;max_height_left = temp-&gt;max_height_right; temp-&gt;right = node; temp-&gt;max_height_right = MAX(node-&gt;max_height_left, node-&gt;max_height_right) + 1; return temp; } static struct Node * insert_data_helper(struct Node *node, const void *data, int32_t (*compare)(const void *, const void *), const size_t size_of_data) { struct Node *temp; int32_t results; if(node == NULL) { /*allocate all the memory*/ temp = malloc(sizeof(*temp)); if(temp == NULL) { return NULL; } temp-&gt;data = malloc(size_of_data); if(temp-&gt;data == NULL) { free(temp); return NULL; } /*set all the vars*/ memcpy(temp-&gt;data, data, size_of_data); temp-&gt;left = temp-&gt;right = NULL; temp-&gt;max_height_left = temp-&gt;max_height_right = 0; return temp; } results = compare(data, node-&gt;data); if(results &lt; 0) { node-&gt;left = insert_data_helper(node-&gt;left, data, compare, size_of_data); /*get the greater of the two heights from the left sub tree*/ node-&gt;max_height_left = MAX(node-&gt;left-&gt;max_height_left, node-&gt;left-&gt;max_height_right) + 1; if(node-&gt;max_height_left - node-&gt;max_height_right &gt; 1) { if(node-&gt;left-&gt;max_height_left - node-&gt;left-&gt;max_height_right &lt;= -1) { node-&gt;left = left_rotate(node-&gt;left); } node = right_rotate(node); } } else if(results &gt; 0) { node-&gt;right = insert_data_helper(node-&gt;right, data, compare, size_of_data); /*get the greater of the two heights from the right sub tree*/ node-&gt;max_height_right = MAX(node-&gt;right-&gt;max_height_left, node-&gt;right-&gt;max_height_right) + 1; if(node-&gt;max_height_left - node-&gt;max_height_right &lt; -1) { if(node-&gt;right-&gt;max_height_left - node-&gt;right-&gt;max_height_right &gt;= 1) { node-&gt;right = right_rotate(node-&gt;right); } node = left_rotate(node); } } return node; } void insert_data(struct AVL_Tree *tree, const void *data) { tree-&gt;root = insert_data_helper(tree-&gt;root, data, tree-&gt;compare, tree-&gt;size_of_data); } static struct Node * get_lowest_value_node(struct Node *node) { if(node == NULL) { return NULL; } else if(node-&gt;left == NULL) { return node; } return get_lowest_value_node(node-&gt;left); } /*delete data*/ static struct Node * delete_data_helper(struct Node *node, const void *data, int32_t (*compare)(const void *, const void *), const size_t size_of_data) { struct Node *temp; int32_t results; if(node == NULL) { return NULL; } results = compare(data, node-&gt;data); if(results &lt; 0) { node-&gt;left = delete_data_helper(node-&gt;left, data, compare, size_of_data); node-&gt;max_height_left = node-&gt;left == NULL ? 0 : MAX(node-&gt;left-&gt;max_height_left, node-&gt;left-&gt;max_height_right) + 1; if(node-&gt;max_height_left - node-&gt;max_height_right &lt; -1) { if(node-&gt;right != NULL &amp;&amp; node-&gt;right-&gt;max_height_left - node-&gt;right-&gt;max_height_right &gt;= 1) { node-&gt;right = right_rotate(node-&gt;right); } node = left_rotate(node); } } else if(results &gt; 0) { node-&gt;right = delete_data_helper(node-&gt;right, data, compare, size_of_data); node-&gt;max_height_right = node-&gt;right == NULL ? 0 : MAX(node-&gt;right-&gt;max_height_left, node-&gt;right-&gt;max_height_right) + 1; if(node-&gt;max_height_left - node-&gt;max_height_right &gt; 1) { if(node-&gt;left != NULL &amp;&amp; node-&gt;left-&gt;max_height_left - node-&gt;left-&gt;max_height_right &lt;= -1) { node-&gt;left = left_rotate(node-&gt;left); } node = right_rotate(node); } } else { if(node-&gt;left == NULL) { temp = node-&gt;right; free(node-&gt;data); free(node); return temp; } else if(node-&gt;right == NULL) { temp = node-&gt;left; free(node-&gt;data); free(node); return temp; } else { /*has two branches. get the lowest value from the right branch*/ temp = get_lowest_value_node(node-&gt;right); memcpy(node-&gt;data, temp-&gt;data, size_of_data); /*now delete the value that was copies from the right branch*/ node-&gt;right = delete_data_helper(node-&gt;right, temp-&gt;data, compare, size_of_data); node-&gt;max_height_right = node-&gt;right == NULL ? 0 : MAX(node-&gt;right-&gt;max_height_left, node-&gt;right-&gt;max_height_right) + 1; if(node-&gt;max_height_left - node-&gt;max_height_right &gt; 1) { if(node-&gt;left != NULL &amp;&amp; node-&gt;left-&gt;max_height_left - node-&gt;left-&gt;max_height_right &lt;= -1) { node-&gt;left = left_rotate(node-&gt;left); } node = right_rotate(node); } } } return node; } void delete_data(struct AVL_Tree *tree, const void *data) { tree-&gt;root = delete_data_helper(tree-&gt;root, data, tree-&gt;compare, tree-&gt;size_of_data); } static int8_t contains_data_helper(struct Node *node, const void *data, int32_t (*compare)(const void *, const void *)) { int32_t results; if(node == NULL) { return -1; } results = compare(data, node-&gt;data); if(results &lt; 0) { return contains_data_helper(node-&gt;left, data, compare); } else if(results &gt; 0) { return contains_data_helper(node-&gt;right, data, compare); } return 0; } int8_t contains_data(struct AVL_Tree *tree, const void *data) { return contains_data_helper(tree-&gt;root, data, tree-&gt;compare); } static void free_tree_helper(struct Node *node) { if(node == NULL) { return; } free_tree_helper(node-&gt;left); free_tree_helper(node-&gt;right); free(node-&gt;data); free(node); } void free_tree(struct AVL_Tree *tree) { free_tree_helper(tree-&gt;root); } static void pre_order_helper(struct Node *node, void (*print)(const void *)) { if(node == NULL) { return; } print(node-&gt;data); printf(&quot;(left = %d, right = %d, balance = %d)\n&quot;, node-&gt;max_height_left, node-&gt;max_height_right, node-&gt;max_height_left - node-&gt;max_height_right); pre_order_helper(node-&gt;left, print); pre_order_helper(node-&gt;right, print); } void pre_order(struct AVL_Tree *tree) { pre_order_helper(tree-&gt;root, tree-&gt;print); } static void in_order_helper(struct Node *node, void (*print)(const void *)) { if(node == NULL) { return; } in_order_helper(node-&gt;left, print); print(node-&gt;data); printf(&quot;(left = %d, right = %d, balance = %d)\n&quot;, node-&gt;max_height_left, node-&gt;max_height_right, node-&gt;max_height_left - node-&gt;max_height_right); in_order_helper(node-&gt;right, print); } void in_order(struct AVL_Tree *tree) { in_order_helper(tree-&gt;root, tree-&gt;print); } static void post_order_helper(struct Node *node, void (*print)(const void *)) { if(node == NULL) { return; } post_order_helper(node-&gt;left, print); post_order_helper(node-&gt;right, print); print(node-&gt;data); printf(&quot;(left = %d, right = %d, balance = %d)\n&quot;, node-&gt;max_height_left, node-&gt;max_height_right, node-&gt;max_height_left - node-&gt;max_height_right); } void post_order(struct AVL_Tree *tree) { post_order_helper(tree-&gt;root, tree-&gt;print); } /*user code*/ void print_data(const void *ptr) { const int *ptr_temp = ptr; printf(&quot;%d &quot;, *ptr_temp); } int compare(const void *ptr1, const void *ptr2) { const int *ptr1_temp, *ptr2_temp; ptr1_temp = ptr1; ptr2_temp = ptr2; if(*ptr1_temp &lt; *ptr2_temp) { return -1; } else if(*ptr1_temp &gt; *ptr2_temp) { return 1; } return 0; } int main(void) { struct AVL_Tree *tree; int i; /*array is used to insert data into the tree*/ int array[] = {1, 2, 3}; create_tree(&amp;tree, sizeof(array[0]), &amp;compare, &amp;print_data); for(i = 0; i &lt; sizeof(array) / sizeof(array[0]); i++) { insert_data(tree, (array + i)); } pre_order(tree); printf(&quot;\n\n\n&quot;); i = 3; delete_data(tree, &amp;i); pre_order(tree); i = 1; printf(&quot;\n(Contains the value %d) = %d(0 == yes, -1 == no)\n&quot;, i, contains_data(tree, &amp;i)); free_tree(tree); return 0; } </code></pre> <p>This is the make file I use</p> <pre><code>program: BBST.o gcc *.o -o program BBST.o: BBST.c gcc -g -c -Wall -pedantic BBST.c clean: rm *.o program </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T00:17:16.110", "Id": "514375", "Score": "1", "body": "I would look at a way to rename the functions a little bit - all your main functions are calling a corresponding `helper` function, which feels too generic and vague. Helping with what? Also, why have these helpers if the main functions are going to be one-liners?" } ]
[ { "body": "<p><strong>Height</strong></p>\n<p>The usually AVL tree needs to only record the height difference or <a href=\"https://en.wikipedia.org/wiki/AVL_tree#Balance_factor\" rel=\"nofollow noreferrer\">balance factor</a>: [-1, 0, 1]. Instead of 2 <code>int32_t</code>. A <code>signed char</code> will do. Given <code>struct</code> alignment issue, might as well use a single <code>int</code>.</p>\n<p><strong>Naming</strong></p>\n<p>Instead of global names all over the name space as with:</p>\n<pre><code>struct Node\nstruct AVL_Tree\ncreate_tree()\ninsert_data()\ndelete_data()\nfree_tree()\n...\n</code></pre>\n<p>How about a uniform style and prefix?</p>\n<pre><code>struct AVL_Node\nstruct AVL_Tree\nAVL_create()\nAVL_insert()\nAVL_delete()\nAVL_free()\nAVL_...\n</code></pre>\n<p><strong>AVL.h</strong></p>\n<p>I'd really like to see <code>AVL.c, AVL.h, main.c</code> for a clear demarcation of what is seen by the public and what is private.</p>\n<p><strong>Fixed width types</strong></p>\n<p>Rather than <code>int32_t</code>, consider an <code>int</code>. <code>int32_t</code> is excessively wide for small applications.</p>\n<p><strong>C2X ordering</strong></p>\n<p>Consider <a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\">the order of parameters in function declarations should be arranged such that the size of an array appears before the array</a>.<br />\nWrap long lines.</p>\n<pre><code>// static struct Node * insert_data_helper(struct Node *node, const void *data, int32_t (*compare)(const void *, const void *), const size_t size_of_data);\nstatic struct Node *insert_data_helper(size_t size, struct Node *node, void *data, \n int32_t (*compare)(const void *, const void *));\n</code></pre>\n<p><strong>Allocate to the referenced object</strong></p>\n<p>Good use of <code>*tree = malloc(sizeof(**tree));</code></p>\n<p><strong>Minor: Unneeded <code>else</code></strong></p>\n<pre><code>if (node == NULL) {\n return NULL;\n}\n// else if(node-&gt;left == NULL) {\nif (node-&gt;left == NULL) {\n return node;\n}\n</code></pre>\n<p>Also in <code>contains_data_helper()</code>.</p>\n<p><strong>Good to tolerate <code>delete_data_helper(NULL, ...)</code></strong></p>\n<p>Also <code>free_tree_helper(NULL)</code>.</p>\n<p><strong>Consider a return value on the helper function</strong></p>\n<p>Instead of <code>void (*f)(const void *)</code>, how about <code>int (*f)(const void *)</code> that returns early when the return value is non-zero.</p>\n<pre><code>static int helper(struct Node *node, int (*foo)(const void *)) {\n if(node == NULL) {\n return 0;\n }\n int retval = helper(node-&gt;left, print);\n if (retval) {\n return retval;\n }\n retval = foo(node-&gt;data);\n if (retval) {\n return retval;\n }\n return helper(node-&gt;right, foo);\n}\n</code></pre>\n<p>I'd even consider passing in a <code>state</code>.</p>\n<pre><code>static int helper(struct Node *node, \n int (*foo)(void * state, const void *), void *state);\n</code></pre>\n<hr />\n<blockquote>\n<p>Criticism on my implementation of the AVL Tree especially the insertion and deletion section of the code.</p>\n</blockquote>\n<p>A better than usual AVL code.<br />\nGood to properly <code>free(temp);</code> on insertion failure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T01:55:49.693", "Id": "260878", "ParentId": "260584", "Score": "1" } } ]
{ "AcceptedAnswerId": "260878", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T21:01:58.373", "Id": "260584", "Score": "3", "Tags": [ "c", "tree", "binary-tree", "binary-search-tree" ], "Title": "AVL Tree in C Criticism" }
260584
<p>This is my implementation of an AStar-like algorithm for maze solving.</p> <p>A quick summary of the problem I am trying to solve with my algorithm might be:</p> <blockquote> <p>A simple binary maze is given to you to solve, you may only go in the standard cardinal directions: north, east, west and south. There is a twist, however: You may also break only one wall. Create a function solution(maze) which determines the minimal number of steps to reach the end defined at point (width-1, height-1) from the start point (0, 0).</p> </blockquote> <pre><code>class AStar: def __init__(self, maze): self.queue = [] self.visited = set() self.maze = maze self.end = len(self.maze)-1, len(self.maze[0])-1 def forward(self): self.queue.append((0, 0, False, 0, 0, None)) while self.queue: self.queue = sorted(self.queue, key=lambda x: x[-3]+x[-4]) #Might be suboptimal to sort every time... node = self.queue.pop(0) if node[0:2] == self.end: return node self.visited.add(node[0:2]) new_nodes = self.rulebook(node) self.queue.extend(new_nodes) def rulebook(self, node): x, y, broken, cost, heuristic, _ = node new_nodes = [] #------RULES &amp; ACTIONS-----# for direction in [[0, 1], [1, 0], [-1, 0], [0, -1]]: x_dir, y_dir = direction x_pdir = x + x_dir y_pdir = y + y_dir distance = self.distance((x_pdir, y_pdir), self.end) if (x_pdir, y_pdir) not in self.visited: if (x_pdir,y_pdir) not in self.visited: if (x_pdir &lt; len(self.maze) and y_pdir &lt; len(self.maze[0])): if (x_pdir &gt;= 0 and y_pdir &gt;= 0): if self.maze[x_pdir][y_pdir] == 1: if not broken: new_nodes.append((x_pdir, y_pdir, True, cost+1, \ distance, node)) elif self.maze[x_pdir][y_pdir] == 0: new_nodes.append((x_pdir, y_pdir, False, cost+1, \ distance, node)) return new_nodes def distance(self, node, end): #Chose the Taxicab Metric as it is more of a fit for the problem, #as you cannot go diagonally in the problem statement. x = node[0] y = node[1] end_x = end[0] end_y = end[1] return abs(x - end_x) + abs(y - end_y) def backward(self, node): steps = 0 while node != None: steps += 1 node = node[-1] return steps def solution(maze): astar = AStar(maze) end_node = astar.forward() steps = astar.backward(end_node) return steps </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T22:01:33.707", "Id": "260585", "Score": "2", "Tags": [ "python", "performance", "pathfinding" ], "Title": "AStar Implementation and Efficiency" }
260585
<p>This is a fully functional PowerShell script I wrote not long ago that converts data (numerical data) among 4 data formats: binary, decimal, hexadecimal and ipv4.</p> <p>It supports 12 conversions, it can convert number from each type to the other three type, it can convert:</p> <pre class="lang-powershell prettyprint-override"><code>binary to decimal | binary to hexadecimal | binary to ipv4 decimal to binary | decimal to hexadecimal | decimal to ipv4 hexadecimal to binary | hexadecimal to decimal | hexadecimal to ipv4 ipv4 to binary | ipv4 to decimal | ipv4 to hexadecimal </code></pre> <p>And I have tested the script numerous times and confirmed it gives right answers, I wrote the script all by myself without any help from anyone and without using the inbuilt methods of PowerShell, of course I know these .Net methods and I just don't use them in my script because that wouldn't be a programming challenge and won't help me improve my skills, though of course I have checked the results of my script against those of the built-in methods and found no discrepancies.</p> <p>So here is the script:</p> <pre class="lang-powershell prettyprint-override"><code>function NumConversion { param( [parameter(valuefrompipeline=$true, mandatory=$true, position=0)] [ValidateNotNull()] [string] $data, [parameter(valuefrompipeline=$true, mandatory=$true, position=1)] [ValidateNotNull()] [string] $task ) begin { $binhex = @{ '0000' = '0' '0001' = '1' '0010' = '2' '0011' = '3' '0100' = '4' '0101' = '5' '0110' = '6' '0111' = '7' '1000' = '8' '1001' = '9' '1010' = 'a' '1011' = 'b' '1100' = 'c' '1101' = 'd' '1110' = 'e' '1111' = 'f' } $dechex = @{ '0' = '0' '1' = '1' '2' = '2' '3' = '3' '4' = '4' '5' = '5' '6' = '6' '7' = '7' '8' = '8' '9' = '9' '10' = 'a' '11' = 'b' '12' = 'c' '13' = 'd' '14' = 'e' '15' = 'f' } } process { $bin2dec = { param($bin) $power = 1 $dec = 0 [int[]]$bits = $bin -split &quot;(0|1)&quot; | where {$_ -ne &quot;&quot;} for ($i = $bits.count - 1; $i -ge 0; $i--) { $bit = $bits[$i] $dec += $bit * $power $power *= 2 } $dec } $bin2hex = { param($bin) $i = 0 if ($bin.Length % 4 -ne 0) { while ($i -lt $bin.Length) {$i += 4} $bin = '0' * ($i - $bin.Length) + $bin } $bin = $bin -split '([01]{4})' | where {$_ -ne ''} $hex = ($bin | % { $binhex.$_ }) -join '' $hex } $bin2ip = { param($bin) if ($bin.length -lt 32) { $bin = '0' * (32 - $bin.length) + $bin } [array]$bin = $bin -split '([01]{8})' | where {$_ -ne ''} [array]$ip = foreach($seg in $bin) { &amp;$bin2dec -bin $seg } $ip = $ip -join '.' $ip } $dec2bin = { param($dec) [array]$bits = for ($i = 1; $i -le $dec; $i*=2) {$i} [string[]]$bin = for($i = $bits.count - 1; $i -ge 0; $i--) { $bit = $bits[$i] if ($dec -ge [double]$bit) {1; $dec -= $bit} else {0} } [string]$bin = $bin -join '' $bin } $dec2hex = { param($dec) [array]$bits = for ($i = 1; $i -le $dec; $i *= 16) {$i} [string[]]$hex = for ($i = $bits.count - 1; $i -ge 0; $i--) { $bit = $bits[$i] if ($dec -ge $bit) { $num = [math]::floor($dec / $bit) $dec = $dec % $bit $dechex.([string]$num) } else {0} } [string]$hex = $hex -join &quot;&quot; $hex } $dec2ip = { param($dec) [array]$ip = for ($i = 0; $i -le 3; $i++) { $seg = $dec % 256 $dec = ($dec - $seg) / 256 $seg } $ip = for ($i = 3; $i -ge 0; $i--) { $ip[$i] } $ip = $ip -join '.' $ip } $hex2bin = { param($hex) [array]$hexa = $hex -split '(\w{1})' | where {$_ -ne ''} $bin = for ($i = 0; $i -lt $hexa.count; $i++) { $binhex.keys | where {$binhex.$_ -eq $hexa[$i]} } $bin = $bin -join '' $bin } $hex2dec = { param($hex) [array]$bits = for($i = 0; $i -lt $hex.length; $i++){[math]::pow(16, $i)} $dec = 0 $hexa = $hex -split '(\w{1})' | where {$_ -ne ''} for (($i = 0), ($j = $hexa.count - 1); $i -lt $hexa.count; $i++, $j--) { $num = [double]($dechex.keys | where {$dechex.$_ -eq $hexa[$j]}) $bit = $bits[$i] $dec = $dec + $num * $bit } $dec } $hex2ip = { param($hex) if ($hex.length -lt 8) {$hex = '0' * (8 - $hex.length) + $hex } [array]$hexa = $hex -split '(\w{2})' | where {$_ -ne ''} [array]$ip = foreach($seg in $hexa) { &amp;$hex2dec -hex $seg } $ip = $ip -join '.' $ip } $ip2bin = { param($ip) $ip = $ip.split('.') [array]$bin = foreach ($seg in $ip) { [int]$num = $seg [array]$bits = for ($i = 128; $i -ge 1; $i /= 2) {$i} $bits = $bits | % { if ($num -ge [int64]$_) {1; $num -= $_} else {0} } [string]$bits = $bits -join &quot;&quot; $bits } $bin = $bin -join '' $bin } $ip2dec = { param($ip) $ip = $ip.split('.') $dec = 0 $base = 16777216 foreach ($seg in $ip) { $dec += [int]$seg * $base $base = $base / 256 } $dec } $ip2hex = { param($ip) $ip = $ip.split('.') [string[]]$hex = foreach ($seg in $ip) { $byte = &amp;$dec2hex -dec $seg if ($byte.length -lt 2) { $byte = '0' + $byte } $byte } $hex = $hex -join '' $hex } switch ($task) { 'bd' { [string]$bin = $data; &amp;$bin2dec -bin $bin } 'bh' { [string]$bin = $data; &amp;$bin2hex -bin $bin } 'bi' { [string]$bin = $data; &amp;$bin2ip -bin $bin } 'db' { [double]$dec = $data; &amp;$dec2bin -dec $dec } 'dh' { [double]$dec = $data; &amp;$dec2hex -dec $dec } 'di' { [double]$dec = $data; &amp;$dec2ip -dec $dec } 'hb' { [string]$hex = $data; &amp;$hex2bin -hex $hex } 'hd' { [string]$hex = $data; &amp;$hex2dec -hex $hex } 'hi' { [string]$hex = $data; &amp;$hex2ip -hex $hex } 'ib' { [string]$ip = $data; &amp;$ip2bin -ip $ip } 'id' { [string]$ip = $data; &amp;$ip2dec -ip $ip } 'ih' { [string]$ip = $data; &amp;$ip2hex -ip $ip } } } } $data = $Args[0] $task = $Args[1] NumConversion $data $task </code></pre> <p>I came up with the logics and the algorithms all by myself;</p> <p>Usage:</p> <p>Save the script as <code>.\NumConversion.ps1</code>, it uses 12 keywords to identify which process to carry out, the 12 switches are (in the order of the table shown above):</p> <pre class="lang-powershell prettyprint-override"><code>bd | bh | bi db | dh | di hb | hd | hi ib | id | ih </code></pre> <p>Now if you want to convert something you just give it two arguments, the data as the first argument and the keyword as the second argument, for example, if you want to convert the ipv4 address <code>127.0.0.1</code> to binary:</p> <pre class="lang-powershell prettyprint-override"><code>.\NumConversion.ps1 127.0.0.1 ib </code></pre> <p>And it will return:</p> <pre class="lang-powershell prettyprint-override"><code>01111111000000000000000000000001 </code></pre> <p>I want your thoughts on my script, can it be more performant, how can it be improved? Can it be shorter and still be clear? Can the code be simplified? I am still very new to all these programming thing, and I want to know how my skills can be improved. Thank you.</p> <hr /> <p>I will briefly explain the logic I use in these algorithms.</p> <p>I found 4 binary bits equal to 1 hexadecimal bit, namely 4 binary bits can represent numbers from 0 to 15, or 2^4 - 1, and integers from 0 to 15 can be represented by 1 hexadecimal bit, and there can be one to one correspondence between every four binary bits and one hexadecimal bit, and binary numbers can be just split into chunks of four (if the string is padded into multiples of four) and translated into hexadecimal bits, because every 4 binary bits segment has the base unit 16 times the previous unit, exactly like 1 hexadecimal bit.</p> <p>And I think IPv4 is sort of base-256, because from left to right, each consecutive segment has the base 256 times of the previous segment, I understand IPv4 is a 4-byte number and 1 byte equals to 8 binary bits and 2 hexadecimal bits, because 8 binary bits can represent integers 0 - 255 (2^8 - 1), and 2 hexadecimal bits can also represent integers 0 - 255 (16^2 - 1), so there is a one-one correspondence among 1 byte of ipv4 and 2 bits of hexadecimal and 8 bits of binary, and I can just split the string (if it is padded first) and translate the value.</p> <p>I mainly use split and padding, I split the binary/hexadecimal/ipv4 string into chunks of appropriate size and store the values in an array, then translate the segments one by one and join strings.</p> <p>The codes to convert binary, hexadecimal and ipv4 are similar, I wonder if I can use one script block to achieve the conversion processes and use a parameter to determine which conversion to run.</p> <p>I wonder if I can use less code to get the same results using the same logic.</p> <hr /> <p>Update: Yeah, thanks for JosefZ's feedback, the two problem are now solved in my new edit.</p> <p>About the first issue, that was unexpected and unintended, and that was definitely a bug, and I was able to fix it by explicitly declare the data type of the variable <code>$dec</code> to appropriate data type; Now I have improved the type casting of all the variables, the bug is fixed.</p> <p>And about the second issue, that was definitely not a bug, however I definitely haven't intended for it to even give an output, it was working as it should be.</p> <p>You all know that saying: garbage in, garbage out; you inputted wrong data, data that the algorithm isn't designed to process, you must expect it to give wrong result.</p> <p>I thought everyone that will be using my script will be in their clear minds and won't input the wrong data to the script, so I didn't implement exception handling functions.</p> <p>I was lazy, now I have fixed it, the script will now through out 7 error messages depending on 7 possible situations, the process won't run if you don't input correctly formatted data in one of the four data types possible respective to the process;</p> <p>And if you use one of the three functions that converts data into IPv4, and the value exceeds the maximum possible value (11111111111111111111111111111111 for binary, 4294967295 for decimal and ffffffff for hexadecimal), the process won't run.</p> <p>Now everything is definitely working as intended, but there are even more duplicate lines of code that can be improved, but I am working on other projects now and I don't have time to improve the code.</p> <p>The updated code:</p> <pre class="lang-powershell prettyprint-override"><code>function NumConversion { param( [parameter(valuefrompipeline=$true, mandatory=$true, position=0)] [ValidateNotNull()] [string] $data, [parameter(valuefrompipeline=$true, mandatory=$true, position=1)] [ValidateNotNull()] [string] $task ) begin { $binhex = @{ '0000' = '0' '0001' = '1' '0010' = '2' '0011' = '3' '0100' = '4' '0101' = '5' '0110' = '6' '0111' = '7' '1000' = '8' '1001' = '9' '1010' = 'a' '1011' = 'b' '1100' = 'c' '1101' = 'd' '1110' = 'e' '1111' = 'f' } $dechex = @{ '0' = '0' '1' = '1' '2' = '2' '3' = '3' '4' = '4' '5' = '5' '6' = '6' '7' = '7' '8' = '8' '9' = '9' '10' = 'a' '11' = 'b' '12' = 'c' '13' = 'd' '14' = 'e' '15' = 'f' } } process { $bin2dec = { param($bin) [string]$bin = $bin if ($bin -match &quot;[01]{$($bin.length)}&quot;) { $power = 1 $dec = 0 [int[]]$bits = $bin -split &quot;(0|1)&quot; | where {$_ -ne &quot;&quot;} for ($i = $bits.count - 1; $i -ge 0; $i--) { $bit = $bits[$i] $dec += $bit * $power $power *= 2 } $dec } else { write-error -message &quot;InvalidData: The inputted string isn't a valid binary string, process will now stop.&quot; -Category InvalidData; break } } $bin2hex = { param($bin) [string]$bin = $bin if ($bin -match &quot;[01]{$($bin.length)}&quot;) { $i = 0 if ($bin.Length % 4 -ne 0) { while ($i -lt $bin.Length) {$i += 4} $bin = '0' * ($i - $bin.Length) + $bin } [array]$bin = $bin -split '([01]{4})' | where {$_ -ne ''} $hex = ($bin | % { $binhex.$_ }) -join '' $hex } else { write-error -message &quot;InvalidData: The inputted string isn't a valid binary string, process will now stop.&quot; -Category InvalidData; break } } $bin2ip = { param($bin) [string]$bin = $bin if ($bin -match &quot;[01]{$($bin.length)}&quot;) { if ($bin -eq ($bin | select-string -pattern &quot;[01]{1,32}&quot;).matches.value) { if ($bin.length -lt 32) { $bin = '0' * (32 - $bin.length) + $bin } [array]$bin = $bin -split '([01]{8})' | where {$_ -ne ''} [array]$ip = foreach($seg in $bin) { &amp;$bin2dec -bin $seg } $ip = $ip -join '.' $ip } else { write-error -message &quot;LimitsExceeded: The value of the inputted binary string exceeds the maximum IPv4 value possible, process will now stop.(maximum value allowed: 11111111111111111111111111111111)&quot; -Category LimitsExceeded; break } } else { write-error -message &quot;InvalidData: The inputted string isn't a valid binary string, process will now stop.&quot; -Category InvalidData; break } } $dec2bin = { param($dec) if ([string]$dec -match &quot;[0-9]{$($([string]$dec).Length)}&quot;) { [double]$dec = $dec [array]$bits = for ($i = 1; $i -le $dec; $i*=2) {$i} [string[]]$bin = for($i = $bits.count - 1; $i -ge 0; $i--) { $bit = $bits[$i] if ($dec -ge [double]$bit) {1; $dec -= $bit} else {0} } [string]$bin = $bin -join '' $bin } else { write-error -message &quot;InvalidData: The inputted string isn't a valid binary string, process will now stop.&quot; -Category InvalidData; break } } $dec2hex = { param($dec) if ([string]$dec -match &quot;[0-9]{$($([string]$dec).Length)}&quot;) { [double]$dec = $dec [array]$bits = for ($i = 1; $i -le $dec; $i *= 16) {$i} [string[]]$hex = for ($i = $bits.count - 1; $i -ge 0; $i--) { $bit = $bits[$i] if ($dec -ge $bit) { $num = [math]::floor($dec / $bit) $dec = $dec % $bit $dechex.([string]$num) } else {0} } [string]$hex = $hex -join &quot;&quot; $hex } else { write-error -message &quot;InvalidData: The inputted string isn't a valid decimal natural number, process will now stop.&quot; -Category InvalidData; break } } $dec2ip = { param($dec) if ([string]$dec -match &quot;[0-9]{$($([string]$dec).Length)}&quot;) { [int64]$dec = $dec if ($dec -le 4294967295) { [array]$ip = for ($i = 0; $i -le 3; $i++) { $seg = $dec % 256 $dec = ($dec - $seg) / 256 $seg } $ip = for ($i = 3; $i -ge 0; $i--) { $ip[$i] } $ip = $ip -join '.' $ip } else { write-error -message &quot;LimitsExceeded: The value of the inputted decimal natural number exceeds the maximum IPv4 value possible, process will now stop. (maximum value allowed: 4294967295)&quot; -Category LimitsExceeded; break } } else { write-error -message &quot;InvalidData: The inputted string isn't a valid decimal natural number, process will now stop.&quot; -Category InvalidData; break } } $hex2bin = { param($hex) [string]$hex = $hex if ($hex -match &quot;[0-9a-f]{$($hex.length)}&quot;) { [array]$hexa = $hex -split '(\w{1})' | where {$_ -ne ''} $bin = for ($i = 0; $i -lt $hexa.count; $i++) { $binhex.keys | where {$binhex.$_ -eq $hexa[$i]} } $bin = $bin -join '' $bin } else { write-error -message &quot;InvalidData: The inputted string isn't a valid hexadecimal number, process will now stop.&quot; -Category InvalidData; break } } $hex2dec = { param($hex) [string]$hex = $hex if ($hex -match &quot;[0-9a-f]{$($hex.length)}&quot;) { [array]$bits = for($i = 0; $i -lt $hex.length; $i++){[math]::pow(16, $i)} $dec = 0 [array]$hexa = $hex -split '(\w{1})' | where {$_ -ne ''} for (($i = 0), ($j = $hexa.count - 1); $i -lt $hexa.count; $i++, $j--) { $num = [double]($dechex.keys | where {$dechex.$_ -eq $hexa[$j]}) $bit = $bits[$i] $dec = $dec + $num * $bit } $dec } else { write-error -message &quot;InvalidData: The inputted string isn't a valid hexadecimal number, process will now stop.&quot; -Category InvalidData; break } } $hex2ip = { param($hex) [string]$hex = $hex if ($hex -match &quot;[0-9a-f]{$($hex.length)}&quot;) { if ($hex -eq ($hex | select-string -pattern &quot;[0-9a-f]{1,8}&quot;).matches.value) { if ($hex.length -lt 8) {$hex = '0' * (8 - $hex.length) + $hex } [array]$hexa = $hex -split '(\w{2})' | where {$_ -ne ''} [array]$ip = foreach($seg in $hexa) { &amp;$hex2dec -hex $seg } $ip = $ip -join '.' $ip } else { write-error -message &quot;LimitsExceeded: The value of the inputted hexadecimal number exceeds the maximum IPv4 value possible, process will now stop. (maximum value allowed: ffffffff)&quot; -Category LimitsExceeded; break } } else { write-error -message &quot;InvalidData: The inputted string isn't a valid hexadecimal number, process will now stop.&quot; -Category InvalidData; break } } $ip2bin = { param($ip) [string]$ip = $ip if ($ip -match '((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)') { [array]$ip = $ip.split('.') [array]$bin = foreach ($seg in $ip) { [int]$num = $seg [array]$bits = for ($i = 128; $i -ge 1; $i /= 2) {$i} $bits = $bits | % { if ($num -ge [int64]$_) {1; $num -= $_} else {0} } [string]$bits = $bits -join &quot;&quot; $bits } $bin = $bin -join '' $bin } else { write-error -message &quot;InvalidData: The inputted string isn't a valid IPv4 string, process will now stop.&quot; -Category InvalidData; break } } $ip2dec = { param($ip) [string]$ip = $ip if ($ip -match '((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)') { [array]$ip = $ip.split('.') $dec = 0 $base = 16777216 foreach ($seg in $ip) { $dec += [int]$seg * $base $base = $base / 256 } $dec } else { write-error -message &quot;InvalidData: The inputted string isn't a valid IPv4 string, process will now stop.&quot; -Category InvalidData; break } } $ip2hex = { param($ip) [string]$ip = $ip if ($ip -match '((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)') { [array]$ip = $ip.split('.') [string[]]$hex = foreach ($seg in $ip) { $byte = &amp;$dec2hex -dec $seg if ($byte.length -lt 2) { $byte = '0' + $byte } $byte } $hex = $hex -join '' $hex } else { write-error -message &quot;InvalidData: The inputted string isn't a valid IPv4 string, process will now stop.&quot; -Category InvalidData; break } } switch ($task) { 'bd' { $bin = $data; &amp;$bin2dec -bin $bin } 'bh' { $bin = $data; &amp;$bin2hex -bin $bin } 'bi' { $bin = $data; &amp;$bin2ip -bin $bin } 'db' { $dec = $data; &amp;$dec2bin -dec $dec } 'dh' { $dec = $data; &amp;$dec2hex -dec $dec } 'di' { $dec = $data; &amp;$dec2ip -dec $dec } 'hb' { $hex = $data; &amp;$hex2bin -hex $hex } 'hd' { $hex = $data; &amp;$hex2dec -hex $hex } 'hi' { $hex = $data; &amp;$hex2ip -hex $hex } 'ib' { $ip = $data; &amp;$ip2bin -ip $ip } 'id' { $ip = $data; &amp;$ip2dec -ip $ip } 'ih' { $ip = $data; &amp;$ip2hex -ip $ip } default {write-error -message &quot;InvalidOperation: The operation specified is undefined, process will now stop.&quot; -Category InvalidOperation} } } } $data = $Args[0] $task = $Args[1] NumConversion $data $task </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T06:11:57.637", "Id": "514387", "Score": "2", "body": "you state that you want to avoid all the optimized methods available in PoSh and in dotnet ... and then ask for optimization help. that does not make sense to me. [*grin*]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T19:39:43.450", "Id": "514682", "Score": "0", "body": "An intriguing project, but… _A fully functional Posh script_? Try `NumConversion 1 hd` or `NumConversion 127.0.0.1 ih`. And compare _edge_ examples (here I agree that `1` isn't an IP-like string…) `NumConversion 1 ih` versus `NumConversion 1 id`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T20:04:05.257", "Id": "514686", "Score": "0", "body": "To elaborate the _edge_ case: `NumConversion (NumConversion 1 ih) hi` returns `0.0.0.1` while `NumConversion (NumConversion 1 id) di` yields `1.0.0.0`. It's an inconsistency, isn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-11T02:35:01.323", "Id": "530316", "Score": "0", "body": "One thing to consider with binary IP addresses is that you need to decide if you want host byte order (which is typically little-endian) or network order (which is always big-endian). That's why `System.Net.IPAddress` has both `HostToNetworkOrder()` and `NetworkToHostOrder()`." } ]
[ { "body": "<p>I don't have enough score to comment, so i'll write an answer instead:</p>\n<p>Its a interesting idea. I'm suprised there isn't any command that does this already?</p>\n<ol>\n<li>Function should always be <code>verb-job</code>. To get a list of approved verbs, do <code>get-verb</code> in the console. Might i suggest something hing like <code>Invoke-BitConvert</code>?</li>\n<li>when asking for one of several 'static' values please use <code>[Validateset('possible,'values')]</code> on the parameter\n<ol>\n<li>on the notion of the task argument, it would be more benefitial to the user if you used the full conversion names (IE <code>binaryToDecimal</code> instead of <code>bd</code>). You could still add in the shortnames aswell, but if you read a script that has this its much more clear what the intention of the parameter is</li>\n</ol>\n</li>\n<li>Add <code>[CmdletBinding()]</code> above the <code>param()</code> block to get support for -verbose, -debug, -erroraction etc.</li>\n<li>Try to figure out if you can used some dotnet features to help you along with the conversion. they are faster and most likely better tested:\n<ol>\n<li>Convert from binary -&gt; dec -&gt; hex: <code>[Convert]::ToInt32($bin,2).tostring(&quot;X&quot;)</code></li>\n<li>IP check:<code>[ipaddress]::TryParse($ip,[ref]$null)</code> this would return a boolean, making you get rid of that regex.</li>\n<li><code>[system.convert]</code> have many features that convert to and from different types. but they convert ususally to byte array or from byte array</li>\n</ol>\n</li>\n<li>I would advice you to find a intermidiate step between all of these values to convert to and from (mabye decimal?). This would do 2 things:\n<ol>\n<li>For each conversion you only need to define how to convert your current &quot;startvalue&quot; to the intermidiate value and how to convert it back.</li>\n<li>Any future conversion you choose to add, would also automatically be supported for all current conversions aswell.</li>\n</ol>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T00:10:45.780", "Id": "261397", "ParentId": "260592", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T02:54:15.340", "Id": "260592", "Score": "3", "Tags": [ "performance", "beginner", "programming-challenge", "converting", "powershell" ], "Title": "PowerShell script binary-decimal-hexadecimal-ipv4 convertor" }
260592
<p>Here's the Rabin-Karp implementation that I've written in Python:</p> <pre class="lang-py prettyprint-override"><code>from functools import lru_cache from itertools import islice from typing import List, Optional BASE = 139 MOD = 2 ** 31 - 1 @lru_cache(maxsize=None) def char_to_int(c: str) -&gt; int: return ord(c) + 1 def calculate_hash(s: str, length: Optional[int] = None) -&gt; int: ret_hash = 0 if length is not None: s = islice(s, 0, length) power = len(s) - 1 if length is None else length - 1 for i, c in enumerate(s): ret_hash += char_to_int(c) * BASE ** power power -= 1 return ret_hash % MOD def roll_hash(prev_hash: int, prev_char: int, next_char: str, length: int) -&gt; int: new_hash = ((prev_hash - char_to_int(prev_char) * BASE ** (length - 1)) * BASE) % MOD new_hash += char_to_int(next_char) return new_hash % MOD def rabin_karp(text: str, pattern: str) -&gt; List[int]: &quot;&quot;&quot; Returns a list of indices where each entry corresponds to the starting index of a substring of `text` that exactly matches `pattern` &quot;&quot;&quot; p_hash = calculate_hash(pattern) n = len(pattern) curr_hash = calculate_hash(text, n) indices = [] if p_hash == curr_hash: indices.append(0) for i in range(1, len(text) - n + 1): curr_hash = roll_hash( curr_hash, text[i - 1], text[i + n - 1], n ) if p_hash == curr_hash: indices.append(i) return indices if __name__ == &quot;__main__&quot;: with open(&quot;lorem_ipsum.txt&quot;, &quot;r&quot;) as f: text = f.read() pattern = &quot;lorem&quot; indices = rabin_karp(text, pattern) print(f&quot;indices: {indices}&quot;) </code></pre> <p>I'm trying to optimize the code as much as possible, so I've tried to do some dynamic code analysis to better understand bottlenecks. I used <code>cProfile</code> to understand the function calls and made changes to the code accordingly to arrive at the above code. Here is the final output from <code>cProfile</code>:</p> <pre><code>Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 60301 0.091 0.000 0.091 0.000 rabin_karp.py:25(roll_hash) 1 0.035 0.035 0.126 0.126 rabin_karp.py:30(rabin_karp) 42 0.000 0.000 0.000 0.000 rabin_karp.py:11(char_to_int) 2 0.000 0.000 0.000 0.000 rabin_karp.py:15(calculate_hash) 57 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 42 0.000 0.000 0.000 0.000 {built-in method builtins.ord} 3 0.000 0.000 0.000 0.000 {built-in method builtins.len} </code></pre> <p>Are there any other ways I could further optimize the code? Another interesting thing of note is that adding <code>@lru_cache</code> actually increases execution time as measured by <code>timeit</code> despite the caching mechanism reducing the number of functions calls to <code>char_to_int()</code> (from 120612 to 42).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T10:39:11.477", "Id": "514395", "Score": "1", "body": "pow() is quite slow operation ... dunno if you can find good enough pow() approximation for the job..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T11:04:44.203", "Id": "514398", "Score": "1", "body": "FYI the same task can be done with `[m.start(0) for m in re.finditer(pattern, text)]`. It runs in milliseconds over a file of 100K lines, while it takes seconds using your `rabin_karp`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T04:38:31.587", "Id": "514445", "Score": "0", "body": "@Marc I appreciate your suggestion, but I wanted to implement Rabin Karp from scratch for the purpose of understanding the algorithm from first principles as well as to refresh my code optimization skills!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:37:00.207", "Id": "514466", "Score": "0", "body": "Pow() LUT didn't give much speedup ... even it was just an \"direct access\" array[1, 139, 19321, 2685619, etc]... ." } ]
[ { "body": "<p>Disclaimer: I did not get any noticeable performance improvements but here are a few ideas nonetheless. Also, your code looks really good to me and there is not much to improve.</p>\n<p>In <code>calculate_hash</code>, you compute a power in the body of the loop. Based on the way the exponents is computed, we can tell that the different values will be: <code>BASE ** (length - 1)</code>, <code>BASE ** (length - 2)</code>, etc. A different option could be to compute the initial value with the '**' and then update the power using division by BASE.</p>\n<p>We could get something like:</p>\n<pre><code>def calculate_hash(s: str, length: Optional[int] = None) -&gt; int:\n if length is not None:\n s = islice(s, 0, length)\n else:\n length = len(s)\n power = BASE ** (length - 1)\n ret_hash = 0\n for c in s:\n ret_hash += char_to_int(c) * power\n power /= BASE\n return ret_hash % MOD\n</code></pre>\n<p>In <code>roll_hash</code>, the computation is split across different lines as the first line is getting too big. In order to keep the expressions easier to read, it may be useful to define additional local variables such as: <code>prev_int, next_int = char_to_int(prev_char), char_to_int(next_char)</code>.</p>\n<p>Then, a few things can be spotted:</p>\n<ul>\n<li>we compute <code>m = (val1 % MOD)</code> and then <code>(m + val2) % MOD</code>: we could perform the modulo operation just once</li>\n<li>the <code>((prev_hash - char_to_int(prev_char) * BASE ** (length - 1)) * BASE)</code> expression can be slightly simplified by expanding it, we get: <code>prev_hash * BASE - char_to_int(prev_char) * BASE ** length</code>. It is much easier to read and should be just as efficient (if not more).</li>\n</ul>\n<p>At the end, the whole function becomes:</p>\n<pre><code>def roll_hash(prev_hash: int, prev_char: int, next_char: str, length: int) -&gt; int:\n prev_int, next_int = char_to_int(prev_char), char_to_int(next_char)\n return (next_int + prev_hash * BASE - prev_int * BASE ** length) % MOD\n</code></pre>\n<p>As mentionned in the comment, the power operation is quite expensive. Maybe we could try to compute it just once and provide it to the <code>roll_hash</code> function.</p>\n<p>Also, we could try to take this chance to use an unknown part of the <a href=\"https://docs.python.org/3/library/functions.html#pow\" rel=\"nofollow noreferrer\"><code>pow</code> builtin</a>: the mod parameter. Here, we may as well compute <code>BASE ** length % MOD</code> so that we get to handle smaller values later on (this is an improvements when the length of the pattern is bigger than 4).</p>\n<p>At this stage, we get:</p>\n<pre><code>def roll_hash(prev_hash: int, prev_char: int, next_char: str, base_pow_length: int) -&gt; int:\n prev_int, next_int = char_to_int(prev_char), char_to_int(next_char)\n return (next_int + prev_hash * BASE - prev_int * base_pow_length) % MOD\n\n\n\ndef rabin_karp(text: str, pattern: str) -&gt; List[int]:\n &quot;&quot;&quot;\n Returns a list of indices where each entry corresponds to the starting index of a\n substring of `text` that exactly matches `pattern`\n &quot;&quot;&quot;\n p_hash = calculate_hash(pattern)\n n = len(pattern)\n curr_hash = calculate_hash(text, n)\n indices = []\n if p_hash == curr_hash:\n indices.append(0)\n base_pow_length = pow(BASE, n, MOD)\n for i in range(1, len(text) - n + 1):\n curr_hash = roll_hash(\n curr_hash, text[i - 1], text[i + n - 1], base_pow_length\n )\n if p_hash == curr_hash:\n indices.append(i)\n return indices\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T04:33:33.067", "Id": "514444", "Score": "0", "body": "You raise some great points! I did try storing the power operation and it didn't seem to make any noticeable performance changes, but thanks to you TIL that there is a mod parameter in the power function!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:53:14.870", "Id": "260609", "ParentId": "260595", "Score": "1" } } ]
{ "AcceptedAnswerId": "260609", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T05:05:17.903", "Id": "260595", "Score": "1", "Tags": [ "performance", "python-3.x" ], "Title": "Python Rabin-Karp Code Optimization" }
260595
<p>I want to improve performance for api. I design cache in dao layer. I use caffine cache. Basic code is:</p> <p>CacheConfig.java</p> <pre><code>@Configuration public class CacheConfig { @Autowired private AppDao appDao; @Bean(value = &quot;appCache&quot;) public LoadingCache&lt;String, App&gt; appCache() { return Caffeine.newBuilder() .maximumSize(1000) .refreshAfterWrite(5, TimeUnit.MINUTES) .build(key -&gt; appDao.getByKeyFromDB(key)); } } </code></pre> <p>AppDao.java</p> <pre><code>@Repository public class AppDao { @Autowired @Qualifier(value = &quot;appCache&quot;) private LoadingCache&lt;String, App&gt; appCache; @Autowired private AppMapper appMapper; // service call getByAppKey public App getByKey(String appKey) { App app = appCache.get(appKey); return app; } // appCache load data by getByKey public App getByKeyFromDB(String appKey) { LambdaQueryWrapper&lt;App&gt; queryWrapper = Wrappers.lambdaQuery(); queryWrapper.eq(App::getAppKey, appKey); return appMapper.selectOne(queryWrapper); } } </code></pre> <p>I maybe divide getByKey and getByKeyFromDB to two file, but I have no idea. How do I divide getByKey and getByKeyFromDB to different modules?</p>
[]
[ { "body": "<p>Well if you want to distinct classes, you should create two classes:</p>\n<pre><code>class CahedDao {\n AppCache cache;\n getByKey(String)\n} \n\nclass DbDao {\n getByKeyFromDb(String)\n}\n</code></pre>\n<p>Notes:</p>\n<p><strong>A.</strong> Codereview is to review working code, if you want to solve a problem you should better ask on stackexchange.</p>\n<p><strong>B.</strong> There are some issues in your code. Thanks to the DI and (bad) field injection you did not got them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T10:57:28.007", "Id": "514397", "Score": "0", "body": "Thank you! What is the issues?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T11:30:52.910", "Id": "514400", "Score": "0", "body": "You have a dependency loop, `CacheConfig` needs an `AppDao` to produce `appCache` and `AppDao` needs and `appCache`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T12:18:24.813", "Id": "514404", "Score": "0", "body": "Thanks! I got it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T10:33:38.970", "Id": "260599", "ParentId": "260596", "Score": "0" } } ]
{ "AcceptedAnswerId": "260599", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T07:00:11.920", "Id": "260596", "Score": "0", "Tags": [ "java", "cache", "spring", "framework" ], "Title": "How do I divide Dao and Dao-Cache into different modules?" }
260596
<p>I wrote two template functions to serialize and deserialize structs representing messages to be sent and received via a TCP socket:</p> <pre class="lang-cpp prettyprint-override"><code>/* * Convert a byte string into a packet. */ template &lt;typename PacketType&gt; PacketType deserialize(std::string &amp;buf, bool partialProcessing = false) { PacketType packet; size_t bufSize = buf.length(); size_t packetSize = sizeof packet; if (packetSize &gt; bufSize) std::cerr &lt;&lt; &quot;Packet larger than buffer size. Partial read: &quot; &lt;&lt; (packetSize - bufSize) &lt;&lt; std::endl; if (packetSize &lt; bufSize &amp;&amp; !partialProcessing) std::cerr &lt;&lt; &quot;Packet smaller than buffer size. Bytes unprocessed: &quot; &lt;&lt; (bufSize - packetSize) &lt;&lt; std::endl; auto ptr = reinterpret_cast&lt;char*&gt;(&amp;buf[0]); memcpy(&amp;packet, ptr, (packetSize &lt; bufSize) ? packetSize : bufSize); return packet; } /* * Convert a packet into a byte string. */ template &lt;typename PacketType&gt; std::string serialize(PacketType &amp;packet) { auto ptr = reinterpret_cast&lt;char*&gt;(&amp;packet); return std::string(ptr, ptr + sizeof packet); } </code></pre> <p>The code currently works within a larger project quite well, but I am unsure as to whether it might produce memory leaks due to my usage of pointers and memcpy.</p> <p>How can I improve this code?</p> <p><strong>Addendum</strong> Since some of the (great) answers seem to need more context, this is but an excerpt of <a href="https://github.com/Programmieren-2/battleship/blob/5d25e151a102d06262db982b4fc83539ba746075/src/proto/Packets.h" rel="nofollow noreferrer">this revision</a> of a header file within the respective project. The template functions are used internally only i.e. do not constitute an external API.</p>
[]
[ { "body": "<p>Your code produces no memory leaks since you're not manually allocating and deleting memory.</p>\n<hr />\n<h2>Include all headers</h2>\n<p>Always include all the headers. In this case, you need <code>&lt;iostream&gt;</code>, <code>string</code>, and <code>cstring</code>.</p>\n<hr />\n<h2>Pass by const reference</h2>\n<p>You should pass your objects by const reference. For example, <code>const std::string&amp; buf</code> and <code>const PacketType&amp; packet</code>. You can use <code>reinterpret_cast&lt;const char*&gt;</code>.</p>\n<hr />\n<h2>Use <code>std::memcpy</code> instead of <code>memcpy</code></h2>\n<p>If you're including <code>&lt;cstring&gt;</code> (which you should be since you're using C++), you should qualify your C function calls with the <code>std</code> namespace.</p>\n<blockquote>\n<p>Including the C++-style header () guarantees that the entities will be found in namespace std and perhaps in the global namespace.</p>\n</blockquote>\n<hr />\n<h2>Compile time checks for POD structs</h2>\n<p><code>std::memcpy</code> only does a shallow copy, so it only works on POD structs (i.e. C-style structs).</p>\n<blockquote>\n<p>A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.</p>\n</blockquote>\n<p>For example,</p>\n<pre><code>struct Example\n{\n int a;\n std::string b;\n};\n</code></pre>\n<p>is a non-POD struct since <code>std::string</code> is a non-POD type (has a non trivial copy constructor, non-trivial destructor).</p>\n<p>You should make sure that <code>PacketType</code> is a POD struct. You can do this with a compile time check using <code>static_assert</code>.</p>\n<p>You can check whether a type is POD, using <code>is_pod</code> type trait (deprecated in C++20) or using <code>is_trivial &amp;&amp; is_standard_layout</code>. <a href=\"https://docs.microsoft.com/en-us/cpp/cpp/trivial-standard-layout-and-pod-types?view=msvc-160\" rel=\"noreferrer\">Here is a good description of what these terms mean and how they relate to POD types.</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T12:19:33.750", "Id": "260603", "ParentId": "260597", "Score": "7" } }, { "body": "<p>Adding to what Rish wrote, don't use <code>std::endl</code>. Just use <code>\\n</code> in the string to indicate a newline.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T19:07:24.340", "Id": "514422", "Score": "0", "body": "I've come across this tip repeatedly now. From other sources I learned to use `std::endl` to indicate the end of a line. What I understand from the [official docs](https://en.cppreference.com/w/cpp/io/manip/endl) is that `endl` executes an extra flush on the data stream, which may cost time and resources unnecessarily. Is this the reason behind your tip, or are there other/more issues with using `endl`? Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T22:53:05.583", "Id": "514431", "Score": "1", "body": "That's the reason: it's unnecessary since flushing is done automatically anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T00:22:31.970", "Id": "514439", "Score": "0", "body": "For error logging purposes the extra flush can be beneficial as messages get written immediately. This is rather helpful for debugging as on a crash buffers might not get flushed. For other output, especially in tight loops, I'd also recommend using `\\n`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T17:10:22.160", "Id": "514482", "Score": "0", "body": "@JDługosz Flushing is done automatically if it's line-buffered. If you want to flush if, and only if, the stream is line buffered and you need to send a newline anyway, there is no point in calling a flushing function. First, that will flush unconditionally and you only wanted to flush if it's line buffered. Second, if it's line buffered, you just output a line, so you just flushed. So why are you calling a flushing function right after you flushed?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T13:41:52.477", "Id": "260604", "ParentId": "260597", "Score": "3" } }, { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Use all required <code>#include</code>s</h2>\n<p>Part of the interface is the <code>#include</code> files that are required, so those should be included here.</p>\n<h2>Make your code hard to abuse</h2>\n<p>Right now we're playing fast and loose with the assumption that <code>memcpy</code> will do the right thing, <em>no matter what type is used for the template</em>. That's a very dangerous assumption, and is easy to get wrong. The fact that you were unsure about its implication could be an indicator that perhaps something is not quite right.</p>\n<h2>Use return values or exceptions rather than printing</h2>\n<p>Printing to <code>std::cerr</code> is fine for debugging, but for production code, I'd probably prefer that either an exception is thrown or that a return value indicates the necessary information. At the very least, a parameter to turn printing on or off would be useful.</p>\n<h2>Let objects be expert about themselves</h2>\n<p>The <code>PacketType</code> class, I assume, is a placeholder for one of several types of specific <code>Packet</code> classes. The point to <code>serialize</code> is to &quot;convert a byte string into a packet&quot; according to the comment. It seems to me that creating a <code>Packet</code> would be the job of a <code>Packet</code> constructor. In this case, I'd suggest something like this:</p>\n<pre><code>class BigPacket {\npublic:\n BigPacket() { std::fill(data, data + size(), 0); }\n BigPacket(std::string&amp; buf);\n explicit operator std::string() const;\n constexpr std::size_t size() const { return sizeof data; }\nprivate:\n uint8_t data[79];\n};\n</code></pre>\n<p>Now instead of writing code like this:</p>\n<pre><code>auto pkt = deserialize&lt;BigPacket&gt;(testvalue, true);\n</code></pre>\n<p>You can just write this:</p>\n<pre><code>auto pkt3 = BigPacket(testvalue);\n</code></pre>\n<p>All of the functionality is easily transferred into the constructor:</p>\n<pre><code>BigPacket::BigPacket(std::string&amp; buf) {\n auto end{std::min(sizeof data, buf.size())};\n std::copy(buf.begin(), buf.begin() + end, data);\n if (buf.size() &lt; sizeof data) {\n std::fill(&amp;data[buf.size()], data + sizeof data, 0);\n }\n}\n</code></pre>\n<p>Note that this follows the previous suggestion and printing is gone. If the caller wants to check for the stated conditions, all of the information is available to do those checks and printing if needed. It also explicitly sets each byte in the packet which is a useful security measure.</p>\n<h2>Use a conversion operator</h2>\n<p>You may have noticed the line:</p>\n<pre><code>explicit operator std::string() const;\n</code></pre>\n<p>Here's one way to implement it:</p>\n<pre><code>BigPacket::operator std::string() const {\n return std::string(reinterpret_cast&lt;const char *&gt;(&amp;data[0]), sizeof data);\n}\n</code></pre>\n<p>Now the <code>serialize</code> and <code>deserialize</code> are completely replaced by constructors and conversion operators:</p>\n<pre><code>std::string testvalue{&quot;abcdefghijklmnopqrstuvwxyz&quot;};\nauto pkt = BigPacket(testvalue);\n#if VERBOSE_LOGGING\nif (pkt.size() &gt; testvalue.size()) {\n std::cerr &lt;&lt; &quot;Packet larger than buffer size. Partial read: &quot; &lt;&lt; (pkt.size() - testvalue.size()) &lt;&lt; '\\n';\n}\n#endif\nauto str = static_cast&lt;std::string&gt;(pkt);\nstd::cout &lt;&lt; str &lt;&lt; '\\n';\n</code></pre>\n<p>Not only is this nice and neat, but it also means that more complex <code>Packet</code> types (such as those using shared pointers or dynamically sized buffers) can be accommodated with confidence and accuracy and a clean programming interface.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T12:20:26.730", "Id": "514457", "Score": "0", "body": "+1 for \"Let objects be expert about themselves\". Use of the OOP paradigm make code much more clean, robust and easier to extend later." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:53:00.627", "Id": "260608", "ParentId": "260597", "Score": "7" } } ]
{ "AcceptedAnswerId": "260603", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T08:36:26.327", "Id": "260597", "Score": "4", "Tags": [ "c++", "c++17", "pointers", "serialization", "template-meta-programming" ], "Title": "De-/Serialization of structs representing TCP messages" }
260597
<p>I need to iterate over a list of IP addresses, to check if the elements inside are subnets/supernets between them, for this I use the <a href="https://docs.python.org/3/library/ipaddress.html#module-ipaddress" rel="nofollow noreferrer">IP-address</a> library.</p> <p>Currently I have the following problem: my second iterator (which I use to iterate over the rest of the list) always starts at 0 and therefore compares each element of the list twice (which I think can be avoided).</p> <p>Here is part of the txt file from which I create the list:</p> <pre><code>Name 10.104.181.0/23 10.104.180.0/24 10.132.83.112/32 10.104.183.0/24 10.104.185.0/24 10.104.185.32/24 174.28.164.30/24 178.38.233.0/24 10.104.186.0/24 10.132.208.0/24 10.104.185.42/24 10.130.217.88/32 10.104.24.108/24 10.134.213.84/32 10.134.205.18/32 10.104.182.145/32 10.123.232.95/32 10.130.236.0/24 10.105.26.245/32 10.134.65.250/32 10.134.222.120/32 10.104.184.62/32 10.104.184.61/32 10.105.121.0/24 </code></pre> <p>And here is my python code:</p> <pre><code>import ipaddress import sys fileobj=open(&quot;test.txt&quot;) for line in fileobj: lines.append(line.strip())#create the list from the txt file lines.pop(0)#remove line &quot;name&quot; for line in lines: for j in range(1,len(lines)): if(line==lines[j]):#problem here: j start always at 1 print('comparing same line.... skipping') pass elif(ipaddress.ip_network(line,False).subnet_of(ipaddress.ip_network(lines[j],False))):#check if subnet print(line+' is subnet of network'+lines[j]) elif(ipaddress.ip_network(line,False).supernet_of(ipaddress.ip_network(lines[j],False))):#check if supernet print(line+' is super of network'+lines[j]) </code></pre> <p>What I'm looking for:</p> <ol> <li>How to solve the problem of my second iterator.</li> <li>Any other improvement (whatever it is, formatting, algorithm,...) is appreciated.</li> </ol>
[]
[ { "body": "<p>This section:</p>\n<pre><code>fileobj=open(&quot;test.txt&quot;)\nfor line in fileobj:\n lines.append(line.strip())#create the list from the txt file\nlines.pop(0)#remove line &quot;name&quot;\n</code></pre>\n<p>has an alternate representation as an iterator-adjustment to skip one line:</p>\n<pre><code>with open('test.txt') as fileobj:\n next(fileobj)\n lines = [line.strip() for line in fileobj]\n</code></pre>\n<p>Also note use of a list comprehension and a context manager.</p>\n<p>Your separate supernet/subnet checks are redundant. If A is a subnet of B, B is a supernet of A; so it's not even worth doing the second.</p>\n<p>Algorithmically: if your list is very, very long you may want to consider moving away from your current nested loop. Your current loop is O(n^2) in time and I don't immediately see a way to avoid this . Consider doing something like - roughly -</p>\n<ol>\n<li>Populate a list of tuples of start and end IP address integers and IP objects; the packed integer representation can be obtained by casting an <code>ipaddress</code> object to <code>int</code></li>\n<li>Sort this list; a naive <code>.sort()</code> should work</li>\n<li>On your outer loop, iterate over all entries for subnet selection</li>\n<li>Prune away any potential supernets whose end is so low that they will never match again</li>\n<li>On your inner loop, iterate from the beginning of the list up to the current entry and then quit.</li>\n</ol>\n<p>This sortation and early-bail should improve your performance a little.</p>\n<h2>Example</h2>\n<p>Edit: &quot;a little&quot; seems to be a (vast) understatement; comparing the two:</p>\n<pre><code>from collections import OrderedDict\nfrom functools import partial\nfrom ipaddress import IPv4Network\nfrom random import randrange, randbytes, seed\nfrom timeit import timeit\nfrom typing import Iterable, Tuple, Sequence\n\nNetRow = Tuple[int, int, str]\nIndexRow = Tuple[int, int]\n\n\ndef parse_addresses(filename: str) -&gt; Iterable[NetRow]:\n with open(filename) as f:\n next(f)\n for line in f:\n net_str = line.strip()\n net = IPv4Network(net_str, strict=False)\n yield int(net.network_address), int(net.broadcast_address), net_str\n\n\ndef end_indices(nets: Sequence[NetRow]) -&gt; Iterable[IndexRow]:\n for i, (start, end, net) in enumerate(nets):\n yield end, i\n\n\ndef new(filename: str):\n # Start and end integers and network objects ordered by start\n subnets = sorted(parse_addresses(filename))\n\n # Supernet dictionary by index from subnets; in same order as subnets\n supernets = OrderedDict(enumerate(subnets))\n\n # List of tuples of subnet end to subnet index, used for pruning\n ends = sorted(end_indices(subnets))\n\n for sub_start, sub_end, subnet in subnets:\n\n # If there are any supernets whose end occurs before the current start,\n # they need to be pruned because they will never match\n for n_to_drop, (end, index) in enumerate(ends):\n if end &gt;= sub_start:\n break\n supernets.pop(index)\n del ends[:n_to_drop]\n\n for super_start, super_end, supernet in supernets.values():\n # Skip comparison to self\n if subnet is supernet:\n continue\n\n # If the current supernet start is after the current subnet start,\n # there will not be any more supernets that encompass this subnet\n if super_start &gt; sub_start:\n break\n\n # The supernet start occurs at or before the current subnet start.\n # If the supernet end occurs at or after the current subnet end,\n # then the supernet encompasses the subnet.\n if super_end &gt;= sub_end:\n # assert subnet.subnet_of(supernet)\n print(f'{subnet} is subnet of {supernet}')\n\n\ndef old(filename: str):\n lines = []\n fileobj = open(filename)\n for line in fileobj:\n lines.append(line.strip()) # create the list from the txt file\n lines.pop(0) # remove line &quot;name&quot;\n for line in lines:\n for j in range(1, len(lines)):\n if (line == lines[j]): # problem here: j start always at 1\n # print('comparing same line.... skipping')\n pass\n elif (IPv4Network(line, False).subnet_of(\n IPv4Network(lines[j], False))): # check if subnet\n print(line\n + ' is subnet of network ' + lines[j])\n #elif (IPv4Network(line, False).supernet_of(\n # IPv4Network(lines[j], False))): # check if supernet\n # print(line\n # + ' is super of network ' + lines[j])\n\n\ndef generate_test(filename: str, min_mask: int, rows: int):\n seed(0) # for repeatability\n with open(filename, 'w') as f:\n f.write('Name\\n')\n for _ in range(rows):\n addr = '.'.join(str(b) for b in randbytes(4))\n mask = randrange(min_mask, 31)\n f.write(f'{addr}/{mask}\\n')\n\n\nif __name__ == '__main__':\n generate_test('bigtest.txt', min_mask=14, rows=1_000)\n\n for method, title in (\n (new, 'New'),\n (old, 'Old'),\n ):\n print(f'{title} method:')\n t = timeit(partial(method, 'bigtest.txt'), number=1)\n print(f'{t:.3f}s\\n')\n</code></pre>\n<h2>Output</h2>\n<pre><code>New method:\n50.100.190.198/30 is subnet of 50.100.216.175/16\n68.143.197.241/26 is subnet of 68.142.21.93/15\n87.88.133.166/17 is subnet of 87.88.222.120/17\n87.88.222.120/17 is subnet of 87.88.133.166/17\n101.186.112.235/19 is subnet of 101.186.155.104/14\n106.183.253.213/22 is subnet of 106.180.121.90/14\n110.142.177.23/29 is subnet of 110.140.246.97/14\n110.206.109.247/20 is subnet of 110.205.222.149/14\n125.43.157.205/28 is subnet of 125.42.59.132/15\n138.157.204.243/29 is subnet of 138.157.172.230/14\n158.221.173.230/30 is subnet of 158.221.69.71/14\n239.186.245.174/18 is subnet of 239.185.216.72/14\n243.3.157.156/28 is subnet of 243.3.56.96/16\n0.029s\n\nOld method:\n87.88.222.120/17 is subnet of network 87.88.133.166/17\n125.43.157.205/28 is subnet of network 125.42.59.132/15\n106.183.253.213/22 is subnet of network 106.180.121.90/14\n101.186.112.235/19 is subnet of network 101.186.155.104/14\n158.221.173.230/30 is subnet of network 158.221.69.71/14\n243.3.157.156/28 is subnet of network 243.3.56.96/16\n87.88.133.166/17 is subnet of network 87.88.222.120/17\n50.100.190.198/30 is subnet of network 50.100.216.175/16\n110.206.109.247/20 is subnet of network 110.205.222.149/14\n138.157.204.243/29 is subnet of network 138.157.172.230/14\n110.142.177.23/29 is subnet of network 110.140.246.97/14\n68.143.197.241/26 is subnet of network 68.142.21.93/15\n239.186.245.174/18 is subnet of network 239.185.216.72/14\n33.487s\n</code></pre>\n<p>A more &quot;fair&quot; comparison uses your own algorithm but with a pre-parse step:</p>\n<pre><code>def old(filename: str):\n lines = []\n with open(filename) as fileobj:\n next(fileobj)\n for line in fileobj:\n net_str = line.strip()\n lines.append((net_str, IPv4Network(net_str, False)))\n\n for subnet_str, subnet in lines:\n for supernet_str, supernet in lines:\n if subnet_str is supernet_str:\n continue\n if subnet.subnet_of(supernet):\n print(f'{subnet_str} is subnet of {supernet_str}')\n</code></pre>\n<p>This still took 1.87s on my machine, which is ~58x the time of the 32ms of the new method.</p>\n<p>Comparing the new and fair-old methods for <code>min_mask=20, rows=10_000</code> is more dramatic: 0.362s vs. 249.763s, ~690x faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T05:47:49.823", "Id": "514447", "Score": "0", "body": "Thanks for the help and the advices ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:56:05.510", "Id": "260610", "ParentId": "260598", "Score": "3" } }, { "body": "<p>To answer your question, use <code>enumerate()</code> in the first loop to get the index of each line. Then start the second loop at the next index:</p>\n<pre><code>for index, line in enumerate(lines):\n for j in range(index + 1, len(lines)):\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T18:09:58.270", "Id": "260666", "ParentId": "260598", "Score": "2" } } ]
{ "AcceptedAnswerId": "260610", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T09:04:18.840", "Id": "260598", "Score": "2", "Tags": [ "python-3.x", "ip-address" ], "Title": "Check if IP address list has subnet or is supernet" }
260598
<p>I'm trying to build a response cache with custom key values (from headers and cookies). Here's the code I have so far, and it kinda works, but I need a second opinion or suggestions for improvements.</p> <p>Are there any possible errors, faster key generation methods etc.</p> <p>Here's the code for middleware and cache key building:</p> <pre><code>app.Use(async (ctx, next) =&gt; { //cache only get requests if (ctx.Request.Method != &quot;GET&quot;) { await next(); return; } //remove cache key header in case it's appended already ctx.Request.Headers.Remove(ResponseCacheKeyProvider.CacheKeyHeader); //remove cache control header. I would like to control this (and response cache does not work if header is set to 0 if (ctx.Request.Headers.ContainsKey(&quot;Cache-Control&quot;)) ctx.Request.Headers.Remove(&quot;Cache-Control&quot;); ctx.Request.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue() { Public = true, MaxAge = TimeSpan.FromSeconds(60) }; //set cookie value if user does not have it (for a/b) testing ABTestingCookieSetter.SetAbCookie(ctx); //build a key for cache var key = ResponseCacheKeyProvider.BuildKey(ctx); //attach a key to header if (!ctx.Request.Headers.ContainsKey(ResponseCacheKeyProvider.CacheKeyHeader)) ctx.Request.Headers.Add(ResponseCacheKeyProvider.CacheKeyHeader, key); await next(); }); //mark necessary flags in request, so we know when to render international layout app.Use(async (ctx, next) =&gt; { if (ctx.Request.GetUri().AbsolutePath.StartsWith(&quot;/eng&quot;) || ctx.Request.GetUri().AbsolutePath.StartsWith(&quot;/mobile/eng&quot;)) ctx.LayoutOptions().SetAsInternational(); await next(); }); //attach response caching middleware app.UseResponseCaching(); //add header to see when cache was generated (so i can debug is it working) app.Use(async (ctx, next) =&gt; { if (ctx.Request.Method != &quot;GET&quot;) { await next(); return; } ctx.Response.Headers.Remove(&quot;Index-Generated-Utc&quot;); if (!ctx.Response.Headers.ContainsKey(&quot;Index-Generated-Utc&quot;)) ctx.Response.Headers.Add(&quot;Index-Generated-Utc&quot;, DateTime.UtcNow.ToString(&quot;HH:mm:ss&quot;)); await next(); }); //class to build a cache key public class ResponseCacheKeyProvider { public const string CacheKeyHeader = &quot;Index-Cache-Key&quot;; //header names to take values from for cache key private static readonly List &lt; string &gt; defaultVaryByHeaders = new List &lt; string &gt; { &quot;CF-IPCountry&quot;, &quot;Accept-Encoding&quot; }; //cookie names, to take values from for cache key private static readonly List &lt; string &gt; defaultVaryByCookies = new List &lt; string &gt; { ABTestUser.cookieName, &quot;dark-theme&quot;, &quot;weatherSelectedCity&quot;, &quot;hiddenBreakingNews&quot; }; public static string BuildKey(HttpContext context) { //mobile/desktop device resolver var _deviceResolver = context.RequestServices.GetService &lt; IDeviceResolver &gt; (); var sb = new StringBuilder(); sb.Append(context.Request.GetUri().AbsoluteUri); sb.Append(_deviceResolver.Device.Type.ToString()); for (var i = 0; i &lt; defaultVaryByHeaders.Count; i++) { var headerValues = context.Request.Headers[defaultVaryByHeaders[i]]; for (var j = 0; j &lt; headerValues.Count(); j++) { sb.Append(headerValues[j]); } } for (var i = 0; i &lt; defaultVaryByCookies.Count; i++) { var cookieValue = context.Request.Cookies[defaultVaryByCookies[i]]; sb.Append(defaultVaryByCookies[i]); if (cookieValue != null &amp;&amp; cookieValue != string.Empty) sb.Append(cookieValue); else if (cookieValue == string.Empty) sb.Append(&quot;empty&quot;); //if cookie has empty value, append this as a part of the string, to avoid empty Cookie corruptingCache } return CalculateHash(sb.ToString()); } private static string CalculateHash(string read) { var data = Encoding.ASCII.GetBytes(read); using(SHA384 shaM = new SHA384Managed()) { var hash = shaM.ComputeHash(data); return Convert.ToBase64String(hash); } } } </code></pre> <p>And here is where is set response caching profiles:</p> <pre><code>services.AddMvc(options =&gt; { options.CacheProfiles.Add(&quot;HomePage&quot;, new CacheProfile() { Duration = Constants.HomePageOutputCacheInSeconds, Location = ResponseCacheLocation.Any, VaryByHeader = ResponseCacheKeyProvider.CacheKeyHeader }); options.CacheProfiles.Add(&quot;Article&quot;, new CacheProfile() { Duration = Constants.ArticleOutputCacheInSeconds, Location = ResponseCacheLocation.Any, VaryByHeader = ResponseCacheKeyProvider.CacheKeyHeader }); options.CacheProfiles.Add(&quot;Default&quot;, new CacheProfile() { Duration = Constants.DefaultOutputCacheInSeconds, Location = ResponseCacheLocation.Any, VaryByHeader = ResponseCacheKeyProvider.CacheKeyHeader }); }).SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2); services.AddMemoryCache(); services.AddResponseCaching(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:49:47.857", "Id": "514408", "Score": "0", "body": "Could you please elaborate on this: *something about all this feels wrong*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:51:52.157", "Id": "514409", "Score": "0", "body": "@petercsala I've removed it to avoid a confusion. It's a personal matter, where I always think I did something wrong :)" } ]
[ { "body": "<p>I can see a few improvements that can be made. First, you can make <code>ResponseCacheKeyProvider</code> static. and rename it to something like <code>HttpCacheProfileProvider</code> so you can control all Requests/Responses headers, and can be related to the <code>CacheProfiles</code> class as well.</p>\n<p>Then, you can make some improvements to it like using <code>IReadOnlyList</code> instead of <code>List</code> to have read-only values. Add methods to Add Headers to response and headers (so you don't need to duplicates your code). Then, implement a method for each necessary header, and try to minimize each method scope and responsibility. For instance in <code>Build</code> method, you're building request headers and cookies, you might need to have a method for building the request headers, and another for cookies. this would narrow your method scope.</p>\n<p>Finally, you need to implement an extension to your middleware to recall it in the <code>Startup</code>.</p>\n<p>Here is an example on the above points :</p>\n<p>Provider :</p>\n<pre><code>public static class HttpCacheProfileProvider\n{\n public const string CacheKeyHeader = &quot;Index-Cache-Key&quot;;\n public const string CacheControl = &quot;Cache-Control&quot;;\n \n private static readonly IReadOnlyList&lt;string&gt; _defaultVaryByHeaders = new List&lt;string&gt; {\n &quot;CF-IPCountry&quot;,\n &quot;Accept-Encoding&quot; \n };\n \n private static readonly IReadOnlyList&lt;string&gt; _defaultVaryByCookies = new List&lt;string&gt; {\n ABTestUser.cookieName,\n &quot;dark-theme&quot;,\n &quot;weatherSelectedCity&quot;,\n &quot;hiddenBreakingNews&quot;\n };\n \n public static void AddRequestHeader(HttpContext context, string key, string value)\n {\n //remove cache key header in case it's appended already\n if (context.Request.Headers.ContainsKey(key))\n {\n context.Request.Headers.Remove(key); \n }\n \n context.Request.Headers.Add(key, value);\n }\n \n public static void AddResponseHeader(HttpContext context, string key, string value)\n {\n //remove cache key header in case it's appended already\n if (context.Response.Headers.ContainsKey(key))\n {\n context.Response.Headers.Remove(key); \n }\n \n context.Response.Headers.Add(key, value);\n }\n \n public static void SetCacheControl(HttpContext context) {\n //remove cache control header. I would like to control this (and response cache does not work if header is set to 0\n if (context.Request.Headers.ContainsKey(CacheControl))\n {\n context.Request.Headers.Remove(CacheControl);\n }\n \n context.Request.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue() {\n Public = true,\n MaxAge = TimeSpan.FromSeconds(60)\n };\n }\n \n\n public static void SetIndexCacheKey(HttpContext context) {\n \n var key = BuildKey(context);\n \n AddRequestHeader(context, CacheKeyHeader, key);\n }\n \n \n private static string GetDefaultVaryByHeader()\n {\n var sb = new StringBuilder();\n \n for (var i = 0; i &lt; _defaultVaryByHeaders.Count; i++) {\n \n var key = _defaultVaryByHeaders[i];\n \n if (_context.Request.Headers.ContainsKey(key))\n {\n var headerValues = _context.Request.Headers[key];\n \n foreach(var header in headerValues)\n {\n sb.Append(header);\n }\n }\n }\n \n return sb.ToString();\n }\n \n private static string GetDefaultVaryByCookies()\n {\n var sb = new StringBuilder();\n\n for (var i = 0; i &lt; _defaultVaryByCookies.Count; i++) {\n \n var key = _defaultVaryByCookies[i];\n var cookieValue = context.Request.Cookies[key];\n sb.Append(key);\n \n if (!string.IsNullOrWhiteSpace(cookieValue))\n {\n sb.Append(cookieValue);\n }\n else if (cookieValue == string.Empty) {\n sb.Append(&quot;empty&quot;); \n }\n }\n\n return sb.ToString();\n }\n\n public static string BuildKey(HttpContext context) {\n \n //mobile/desktop device resolver\n var deviceResolver = context.RequestServices.GetService &lt;IDeviceResolver&gt;();\n \n var sb = new StringBuilder();\n \n sb.Append(context.Request.GetUri().AbsoluteUri);\n\n sb.Append(deviceResolver.Device.Type.ToString());\n\n sb.Append(GetDefaultVaryByHeader());\n \n sb.Append(GetDefaultVaryByCookies());\n \n return CalculateHash(sb.ToString());\n }\n\n \n private static string CalculateHash(string read) {\n var data = Encoding.ASCII.GetBytes(read);\n\n using(SHA384 shaM = new SHA384Managed()) {\n var hash = shaM.ComputeHash(data);\n return Convert.ToBase64String(hash);\n }\n }\n}\n</code></pre>\n<p>Extension :</p>\n<pre><code>public static class ResponseCacheKeyBuilderExtension\n{\n public static IApplicationBuilder UseHttpCacheProfile(this IApplicationBuilder app)\n {\n app.Use(async (ctx, next) =&gt; {\n\n //cache only get requests\n if (ctx.Request.Method != &quot;GET&quot;) {\n await next();\n return;\n }\n \n HttpCacheProfileProvider.SetCacheControl(ctx);\n \n HttpCacheProfileProvider.SetIndexCacheKey(ctx);\n \n //set cookie value if user does not have it (for a/b) testing\n ABTestingCookieSetter.SetAbCookie(ctx);\n \n await next();\n });\n \n //mark necessary flags in request, so we know when to render international layout\n app.Use(async (ctx, next) =&gt; {\n \n var absolutePath = ctx.Request.GetUri().AbsolutePath;\n \n if (absolutePath.StartsWith(&quot;/eng&quot;) || absolutePath.StartsWith(&quot;/mobile/eng&quot;))\n ctx.LayoutOptions().SetAsInternational();\n\n await next();\n });\n \n //attach response caching middleware\n app.UseResponseCaching();\n\n //add header to see when cache was generated (so i can debug is it working)\n app.Use(async (ctx, next) =&gt; {\n \n if (ctx.Request.Method != &quot;GET&quot;) {\n await next();\n return;\n }\n\n HttpCacheProfileProvider.AddResponseHeader(&quot;Index-Generated-Utc&quot;, DateTime.UtcNow.ToString(&quot;HH:mm:ss&quot;));\n\n await next();\n });\n }\n\n return app;\n}\n</code></pre>\n<p>in your <code>Startup</code> :</p>\n<pre><code>app.UseHttpCacheProfile();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T19:22:04.567", "Id": "514423", "Score": "0", "body": "Wow, nice. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T20:25:12.633", "Id": "514425", "Score": "1", "body": "@Robert I forgot to mention that I've skipped validations for simplicity sake. Also, you might need to add an extension method for `IServiceCollection` to add `CacheProfile` similar to `UseHttpCacheProfile`. this would make things more easier to maintain." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T17:25:11.087", "Id": "260616", "ParentId": "260606", "Score": "3" } } ]
{ "AcceptedAnswerId": "260616", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:46:40.063", "Id": "260606", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Asp.net core response caching with custom key values" }
260606
<p>This is an Relative Strength Index algorithm able to buy and sell stock based on values from basic stock CSVs. It works correctly and well, but I'm not sure if it can be better optimized as it basically repeats itself twice to operate on the two stock values it's given. I can only use python itself, no numpy or anything.</p> <pre><code>def alg_rsi(filename_1, filename_2): lookback = 21 cash_balance = 10000 stocks_owned = 0 column_choice = 4 day = 1 file1 = open(filename_1).readlines() file2 = open(filename_2).readlines() file1_length = sum(1 for line in file1) file2_length = sum(1 for line in file2) if file1_length &gt;= file2_length: length = file2_length else: length = file1_length for i in range(length - lookback - 1): tday = day + lookback gains = [] losses = [] for i in range(lookback): today = float(file1[tday][:-1].split(',')[column_choice]) yesterday = float(file1[tday - 1][:-1].split(',')[column_choice]) if today &gt; yesterday: gain = today - yesterday gains.append(gain) else: loss = yesterday - today losses.append(loss) tday = tday - 1 totalgain1 = sum(gains) totalloss1 = sum(losses) averagegain1 = totalgain1 / lookback averageloss1 = totalloss1 / lookback rsi1 = 100 - (100 / (1 + (averagegain1 / averageloss1))) gains.clear() losses.clear() tday = day + lookback for i in range(lookback): today = float(file2[tday][:-1].split(',')[column_choice]) yesterday = float(file2[tday - 1][:-1].split(',')[column_choice]) if today &gt; yesterday: gain = today - yesterday gains.append(gain) else: loss = yesterday - today losses.append(loss) tday = tday - 1 totalgain2 = sum(gains) totalloss2 = sum(losses) averagegain2 = totalgain2 / lookback averageloss2 = totalloss2 / lookback rsi2 = 100 - (100 / (1 + (averagegain2 / averageloss2))) gains.clear() losses.clear() stocks_per = 10 price1 = float(file1[day + lookback][:-1].split(',')[column_choice]) price2 = float(file2[day + lookback][:-1].split(',')[column_choice]) try: if rsi1 &lt;= 30: cash_balance, stocks_owned = transact(cash_balance, stocks_owned, stocks_per, price1, buy=True, sell=False) elif rsi1 &gt;= 70: cash_balance, stocks_owned = transact(cash_balance, stocks_owned, stocks_per, price1, buy=False, sell=True) else: pass except ValueError: pass try: if rsi2 &lt;= 30: cash_balance, stocks_owned = transact(cash_balance, stocks_owned, stocks_per, price2, buy=True, sell=False) elif rsi2 &gt;= 70: cash_balance, stocks_owned = transact(cash_balance, stocks_owned, stocks_per, price2, buy=False, sell=True) else: pass except ValueError: pass day = day + 1 if price1 &gt; price2: cash_balance, stocks_owned = transact(cash_balance, stocks_owned, stocks_owned, price1, buy=False, sell=True) else: cash_balance, stocks_owned = transact(cash_balance, stocks_owned, stocks_owned, price2, buy=False, sell=True) return stocks_owned, cash_balance </code></pre> <p>Overall I'm not super pressed if this is how it has to be, as it still works quickly; it just seems to me like there's too many redundant parts.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T15:48:22.097", "Id": "514412", "Score": "0", "body": "The indentation looked wrong - I believe I've corrected it, but do please check that I got it right!" } ]
[ { "body": "<blockquote>\n<pre><code>if file1_length &gt;= file2_length:\n length = file2_length\nelse:\n length = file1_length\n</code></pre>\n</blockquote>\n<p>Or more succinctly as <code>length = max(file1_length, file2_length)</code></p>\n<hr />\n<blockquote>\n<p><code>tday</code></p>\n</blockquote>\n<p>What is <code>tday</code>? It does not look like typo for <code>today</code></p>\n<hr />\n<blockquote>\n<pre><code>for i in range(lookback):\n today = float(file1[tday][:-1].split(',')[column_choice])\n yesterday = float(file1[tday - 1][:-1].split(',')[column_choice])\n if today &gt; yesterday:\n gain = today - yesterday\n gains.append(gain)\n else:\n loss = yesterday - today\n losses.append(loss)\n tday = tday - 1\ntotalgain1 = sum(gains)\ntotalloss1 = sum(losses)\naveragegain1 = totalgain1 / lookback\naverageloss1 = totalloss1 / lookback\n</code></pre>\n</blockquote>\n<p>This whole chunk is duplicated. I suggest making a function to remove duplicate code</p>\n<p>There are more duplicated chunks, and it looks like an array of size 2 would be useful</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T17:59:03.247", "Id": "260617", "ParentId": "260613", "Score": "0" } }, { "body": "<ul>\n<li><p>Computation of <code>rsi1</code> (and <code>rsi2</code>) are a bit more complicated as necessary. Gains and losses are accumulated in their respective lists, only to be summed later on. Get rid of the lists:</p>\n<pre><code> if today &gt; yesterday:\n gain += today - yesterday\n else:\n loss += yesterday - today\n</code></pre>\n<p>Computing averages is also redundant.</p>\n<pre><code> averagegain1 = totalgain1 / lookback\n averageloss1 = totalloss1 / lookback\n rsi1 = 100 - (100 / (1 + (averagegain1 / averageloss1)))\n</code></pre>\n<p>is a very long way to say</p>\n<pre><code> rsi1 = 100 - (100 / (1 + (totalgain1 / totalloss1)))\n</code></pre>\n<p>Math guarantees that the result will be the same. <code>lookback</code> just cancels.</p>\n<p>Also you have to be very careful with division by <code>totalloss</code>. It is quite possible that it is zero. BTW, I would simplify the formula to <code>100 * gain/(gain + loss)</code>.</p>\n</li>\n<li><p>You didn't show <code>transact</code>. From what I see, passing both <code>buy</code> and <code>sell</code> seems redundant. They are always opposite to each other.</p>\n<p><em>If</em> setting them both to <code>False</code> results in no transaction, consider</p>\n<pre><code> buy, sell = False, False\n if rsi &lt;= 30:\n buy = True\n if rsi &gt;= 70:\n sell = True\n\n cash_balance, stocks_owned = transact(cash_balance,\n stocks_owned,\n stocks_per,\n price,\n buy, sell)\n</code></pre>\n</li>\n<li><p>You may achieve a certain performance increase by <em>not</em> recomputing gains and losses over the entire lookback period. Using a sliding window.</p>\n</li>\n<li><p>As noted in another answer, factor the repeated code into a function.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T22:37:10.710", "Id": "260629", "ParentId": "260613", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T15:14:02.700", "Id": "260613", "Score": "0", "Tags": [ "python", "performance", "algorithm" ], "Title": "Relative Strength Index algorithm for stock values" }
260613
<p>I'm trying to design a chain of responsibility pattern.</p> <p>It slightly differ from traditional way when handler does only one action on a request, f.e. handles http response considering status code.</p> <p>But my handlers have to do two actions. Below is an (dummy) example where handler asks a question first and then writes the user response to some store:</p> <pre><code># some object where we keep surname and name class Request: pass # some outer storage store = {} # chain of responsibility implementation class PersonIdentifier: def __init__(self) -&gt; None: self.handlers = [] def add_handler(self, handler): if self.handlers: self.handlers[-1].set_next_handler(handler) self.handlers.append(handler) def handle(self, request): return self.handlers[0].handle_request(request) # handlers for chain of responsibility class BaseHandler: handler_name = None def __init__(self) -&gt; None: self.next_handler = None def set_next_handler(self, handler): self.next_handler = handler class SurnameHandler(BaseHandler): handler_name = 'surname' handler_name_answer = 'surname-answer' question = 'Type your surname: ' def handle_request(self, request): if request.handler_name == self.handler_name: return self.question elif request.handler_name == self.handler_name_answer: global store store['surname'] = request.surname del request.surname request.handler_name = 'name' return self.next_handler.handle_request(request) else: return self.next_handler.handle_request(request) class NameHandler(BaseHandler): handler_name = 'name' handler_name_answer = 'name-answer' question = 'Type your name: ' def handle_request(self, request): if request.handler_name == self.handler_name: return self.question elif request.handler_name == self.handler_name_answer: global store store['name'] = request.name user_request = Request() chain = PersonIdentifier() chain.add_handler(SurnameHandler()) chain.add_handler(NameHandler()) # first ask for surname user_request.handler_name = 'surname' surname = input(chain.handle(user_request)) user_request.handler_name = 'surname-answer' user_request.surname = surname # then ask for name name = input(chain.handle(user_request)) user_request.name = name user_request.handler_name = 'name-answer' chain.handle(user_request) print(store) </code></pre> <p>It looks ugly for me. What do I dislike more is using <strong>handler_name</strong> and <strong>handler_name_answer</strong>.</p> <p>May be you could offer nicer way to solve my task?</p>
[]
[ { "body": "<p><em>Chain of Responsibility</em> pattern (hereby &quot;CORP&quot;) includes two things: iteration and &quot;handling&quot;.</p>\n<p>IMO, the iteration part, at least in modern programming languages such as Python and Java, can be easily &quot;extracted&quot; to an external iteration. So eventually the code could look like:</p>\n<pre><code>result = None\nfor handler in handlers:\n temp_result = handler.handle(request)\n if temp_result is not None:\n result = temp_result\n break\nif result is not None:\n # handled!\n</code></pre>\n<p>I think this approach is simpler than maintaining the inner chain, and it has the same impact.</p>\n<p>In CORP, once a handler was found, and it can handle the input, no additional handlers should be executed. It's quite similar to filtering.</p>\n<p>However, I think that the code we have in your question tries to execute <strong>as many handlers as it can</strong> (as it tries to enrich a wider context). So maybe CORP is not really needed here.</p>\n<p>Perhaps you can have enriching classes, that have a method <code>enrich</code> that accepts a request and a context, so that every enriching class could either change the state of the context object, or leave it as is:</p>\n<pre><code>class BaseEnricher:\n def enrich(request, store):\n pass\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T21:10:28.477", "Id": "260626", "ParentId": "260624", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T19:20:28.323", "Id": "260624", "Score": "2", "Tags": [ "python" ], "Title": "Chain of Responsibility design" }
260624
<p>I am looking to improve the performance of my code through best practices and cleaner code.</p> <p>My goal here is just to perform a conversion whenever there is a keyup.</p> <p>But I noticed that my code looks very repetitive. In your view, what should I do to simplify it?</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>window.oninput = function(event) { var campo = event.target.id; // DECIMALS var i = document.getElementById("decimalTemp").value; ºC.value = (ºC.value * 1).toFixed(i); ºK.value = (ºK.value * 1).toFixed(i); ºF.value = (ºF.value * 1).toFixed(i); ºRa.value = (ºRa.value * 1).toFixed(i); // TEMPERATURE if (campo == "ºC") { ºK.value = (ºC.value * 1 + 273.15).toFixed(i); ºF.value = (ºC.value * 1.8 + 32).toFixed(i); ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i); } else if (campo == "ºK") { ºC.value = (ºK.value * 1 - 273.15).toFixed(i); ºF.value = (ºK.value * 1.8 - 459.889).toFixed(i); ºRa.value = (ºK.value * 1.8).toFixed(i); } else if (campo == "ºF") { ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(i); ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(i); ºRa.value = (ºF.value * 1 + 459.67).toFixed(i); } else if (campo == "ºRa") { ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(i); ºK.value = (ºRa.value / 1.8).toFixed(i); ºF.value = (ºRa.value * 1 - 459.67).toFixed(i); } };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h3&gt;Temperature &lt;input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"&gt; &lt;small&gt;Decimals&lt;small&gt;&lt;/h3&gt; Celsius (ºC) &lt;input id="ºC" type="number" min="-273.15" value="20"&gt; &lt;br&gt; Kelvin (K) &lt;input id="ºK" type="number" min="0" value="293"&gt; &lt;br&gt; Farenheit (ºF) &lt;input id="ºF" type="number" min="-459.67" value="68"&gt; &lt;br&gt; Rankine (ºRa) &lt;input id="ºRa" type="number" min="0" value="528"&gt;</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/1ofyud56/" rel="nofollow noreferrer">Complete code on JSFiddle</a></p>
[]
[ { "body": "<p>The use of non-ASCII character <code>º</code> in variable names is surprising to me</p>\n<hr />\n<p>There is a lot of repeated <code>* 1</code> that is presumably used to convert <code>string</code> to <code>number</code>. <code>parseFloat</code> or <code>parseInt</code> will make intention more clear</p>\n<hr />\n<p>There is a lot of repetition in formulas. I would get the new user-inputted value and convert to a standard format (for example, ºC). I would then have one function to convert from ºC to any of the other units</p>\n<hr />\n<p><a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\"><code>==</code> should be replaced with <code>===</code></a> whenever possible</p>\n<hr />\n<p><code>campo</code> seems to be Portuguese for &quot;field&quot;. <a href=\"https://softwareengineering.stackexchange.com/questions/113936/is-it-a-good-practice-to-code-in-english\">Consensus</a> is that coding should be in English</p>\n<hr />\n<p>Minor bug: increasing number of decimals results in inaccuracies (It says 20ºC is 293K, but should be 293.15K). Results need to be recalculated from last user-inputted value to be accurate</p>\n<hr />\n<p>The default step for <code>input</code> tags is 1. <a href=\"https://www.w3schools.com/tags/att_input_step.asp\" rel=\"nofollow noreferrer\">This attribute</a> should be changed to <code>any</code> to remove validation errors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:45:14.030", "Id": "514468", "Score": "0", "body": "You helped me a lot! I really appreciate it! All the suggestions you made are now in use! Thank you very much!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T01:24:13.833", "Id": "260632", "ParentId": "260631", "Score": "2" } }, { "body": "<p>This code can be simplified a lot.</p>\n<p>Don't use non alpha numeric characters for naming id's, variables, functions, etc.</p>\n<p>You should consider changing the way you implemented the decimals. For example if you choose to have one decimal on a number like <code>2.19</code> you will get <code>2.1</code>. I would expect that to be rounded to the nearest integer and that would be <code>2.2</code>.</p>\n<p>Apart from that you can definitely simplify the code quite a lot.\nHere is how I would do it:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>// for being able to keep track of the unit we are using\n// type Unit = &quot;C&quot; | &quot;K&quot; | &quot;RA&quot; | &quot;RO&quot; | &quot;N&quot; | &quot;DE&quot; | &quot;RE&quot;\n\n// create a helper class that does the conversion\n// it's easier if you have a base unit to convert to and from. I chose\n// celsius\n\nclass Convertor {\n constructor(temp, unit) {\n this.tempInCelsius = this.convertToCelsius(temp, unit);\n }\n\n get toCelsius() {\n return this.tempInCelsius;\n }\n get toKelvin() {\n return this.tempInCelsius + 273.15;\n }\n get toFahrenheit() {\n return (this.tempInCelsius * 1.8) + 32;\n }\n get toRankine() {\n return (this.tempInCelsius * 9/5 + 491.67).toFixed(2)\n }\n get toRomer() {\n return this.tempInCelsius * 21/40 + 7.5;\n }\n get toNewton() {\n return this.tempInCelsius * 3.0303;\n }\n get toDelisle() {\n return (100 - this.tempInCelsius) * 3/2;\n }\n get toReaumur() {\n return this.tempInCelsius * 0.8;\n }\n\n convertToCelsius(temp, unit) {\n switch (unit) {\n case 'C':\n return temp;\n case 'K':\n return temp - 273.15;\n case 'RA':\n return (temp - 491.67) * 5/9;\n case 'RO':\n return (temp - 7.5) * 40/21;\n case 'N':\n return temp / 3.0303;\n case 'DE':\n return 100 - (temp * 2/3);\n case 'RE':\n return temp / 0.8;\n }\n }\n}\n\nwindow.oninput = function(event) {\n const campo = event.target.id; \n const i = document.getElementById(&quot;decimalTemp&quot;).value;\n // you need to rename the id's of the inputs\n // the switch inside the convertToCelsius is using that id\n const degreesCelsius = new Convertor(+(document.getElementById(campo).value), campo);\n C.value = degreesCelsius.toCelsius;\n K.value = degreesCelsius.toKelvin;\n F.value = degreesCelsius.toFahrenheit;\n RA.value = degreesCelsius.toRankine;\n RO.value = degreesCelsius.toRomer;\n N.value = degreesCelsius.toNewton;\n DE.value = degreesCelsius.toDelisle;\n RE.value = degreesCelsius.toReaumur;\n };\n</code></pre>\n<p>In your html you rename your ID's like this:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;C&quot; type=&quot;number&quot; min=&quot;-273.15&quot; value=&quot;20&quot;&gt;\n &lt;h4&gt;Celsius (degrees C)&lt;/h4&gt;\n &lt;/div&gt;\n &lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;K&quot; type=&quot;number&quot; min=&quot;0&quot; value=&quot;293&quot;&gt;\n &lt;h4&gt;Kelvin (K)&lt;/h4&gt;\n &lt;/div&gt;\n &lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;F&quot; type=&quot;number&quot; min=&quot;-459.67&quot; value=&quot;68&quot;&gt;\n &lt;h4&gt;Farenheit (degreesF)&lt;/h4&gt;\n &lt;/div&gt;\n &lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;RA&quot; type=&quot;number&quot; min=&quot;0&quot; value=&quot;528&quot;&gt;\n &lt;h4&gt;Rankine (degreesRa)&lt;/h4&gt;\n &lt;/div&gt;\n &lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;RO&quot; type=&quot;number&quot; min=&quot;-135.90&quot; value=&quot;18&quot;&gt;\n &lt;h4&gt;Rømer (degreesRø)&lt;/h4&gt;\n &lt;/div&gt;\n &lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;N&quot; type=&quot;number&quot; min=&quot;-90.14&quot; value=&quot;7&quot;&gt;\n &lt;h4&gt;Newton (degreesN)&lt;/h4&gt;\n &lt;/div&gt;\n &lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;DE&quot; type=&quot;number&quot; min=&quot;-559.73&quot; value=&quot;120&quot;&gt;\n &lt;h4&gt;Delisle (degreesDe)&lt;/h4&gt;\n &lt;/div&gt;\n &lt;div class=&quot;block-input&quot;&gt;\n &lt;input id=&quot;RE&quot; type=&quot;number&quot; min=&quot;-218.52&quot; value=&quot;16&quot;&gt;\n &lt;h4&gt;Reaumur (degreesRe)&lt;/h4&gt;\n &lt;/div&gt;\n</code></pre>\n<p>Here is a jsfiddle: <a href=\"https://jsfiddle.net/4f5nsyo8/1/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/4f5nsyo8/1/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:28:37.680", "Id": "514465", "Score": "0", "body": "I believe the Constructor will save many lines of code. Mainly when I need to write other measure systems. But how would do to keep the decimals working? Do you consider Constructor the best place to put it on?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T09:16:06.583", "Id": "260639", "ParentId": "260631", "Score": "1" } }, { "body": "<h2>Keep it simple</h2>\n<p>Your code is overly complex as you are doing too many conversions C &lt;=&gt; F, C &lt;=&gt; Ra, and Ra &lt;=&gt; F can all be avoided.</p>\n<p>When doing any type of unit conversion select a base unit and then only convert between the base unit and other units.</p>\n<p>By using a base unit you can do all the conversions with only 6 formulas, rather than the 12 you are currently using.</p>\n<h2>General review</h2>\n<h3>HTML</h3>\n<p>It is important for the content of a web page to have machine readable information that is unambiguous and semantically meaningful. Many people need assistance to interact with web pages, if the machine can not understand the content these people can not use the page.</p>\n<p>Also bots (such as search engines use to rank pages) can not accurately assess a page's content if it does not understand what the page contains.</p>\n<p>I am not HTML expert so these are just the basic points. See rewrite for more info</p>\n<ul>\n<li><p><strong>Use appropriate elements</strong></p>\n<ul>\n<li>Use the Labels to label inputs</li>\n<li>The different units temperatures are a list, use an unordered list to hold the inputs and labels.</li>\n</ul>\n</li>\n<li><p><strong>Related data</strong></p>\n<p>Do NOT! use <code>id</code> to store semantic information. That does not mean you should not use meaningful <code>id</code> names, rather you should add the semantic information using more appropriate attributes and or elements.</p>\n<p>For example you use the <code>event.target.id</code> to determine which unit is being changed. Rather than use the id store the input elements unit type as a <code>dataset</code> attribute. See rewrite</p>\n</li>\n</ul>\n<h3>JavaScript</h3>\n<ul>\n<li><p><strong><code>window</code></strong></p>\n<p>Your use of <code>window</code> is redundant as <code>window</code> is the global this (scope).</p>\n<p><code>window.oninput = function(event) {</code> is identical to <code>oninput = function(event) {</code></p>\n</li>\n<li><p><strong>Add listeners don`t set listeners</strong></p>\n<p>You should avoid assigning event listeners directly as they can be overwritten, by you accidentally, or by 3rd party content. E.G. adverts.</p>\n<p>Use <code>addEventListener</code> as it adds listeners</p>\n<p>E.G. <code>oninput = function(event) { /*... code ... */ }</code> should be <code>addEventListener(&quot;input&quot;, function(event) { /*... code ... */ });</code></p>\n<p>NOTE: The event name when using <code>addEventListener</code> does not include the <code>on</code> prefix. <code>&quot;oninput&quot;</code> becomes <code>&quot;input&quot;</code></p>\n</li>\n<li><p><strong>Constants</strong></p>\n<p>For variables that do not change declare them as constants. eg <code>const campo = event.target.id;</code></p>\n</li>\n<li><p><strong>Indentation</strong></p>\n<p>Watch your indentation, the four lines below <code>var i = document.ge...</code> are incorrectly indented.</p>\n</li>\n<li><p><strong>Use standard keyboard characters</strong></p>\n<p>The use of <code>º</code> via the keyboard dance <kbd>LEFT ALT</kbd> <kbd>1</kbd><kbd>6</kbd><kbd>7</kbd> is unnecessary as it adds nothing to the quality or readability of the code.</p>\n</li>\n<li><p><strong>Magic Numbers</strong></p>\n<p>Numbers seldom have meaning on there own. They are also easy to get wrong it you have a lot of them. Give numbers names by defining them as constants.</p>\n<p><code>1.8</code> could mean anything... so remove the guess work with <code>const RANKINE_SCALE = 1.8</code></p>\n</li>\n</ul>\n<h2>Problem</h2>\n<p>Inputs can get stuck because the input step and min values are not set or incorrect</p>\n<p>Changing the number of decimal points means you must change the step value for each input. E.G. Decimal 0 step 1, Decimal 1 step 0.1, 2 step 0.01, and so on.</p>\n<p>To control the step position you can not set the <code>min</code> attribute to be a value that is not divisible by step. For all by Kelvin and Rankine the min value is problematic.</p>\n<p>But using Kelvin as a the base unit we need only define its <code>min</code> attribute and in JS make sure its &gt;= 0 so that the other units don't go out of bounds.</p>\n<h2>Rewrite</h2>\n<p>The rewrite add some CSS, a lot of HTML and splits the JS into many parts.</p>\n<ul>\n<li><p>Only the Kelvin input value is defined with a min and step and value. The other values are set when the JavaScript first runs by calling <code>decimalEvent</code></p>\n</li>\n<li><p>Each temperature input uses <code>data-unit=&quot;&quot;</code> to name the unit used. This name is used to lookup the correct conversion function in the object <code>toKelvin</code>.</p>\n</li>\n<li><p>Temperature and decimal input events are split. The decimal listener will call the Temperature listener which will use the default target kelvin if called without an event</p>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const F_SCALE = 1.8, F_OFFSET = 459.67;\nconst C_OFFSET = 273.15;\nconst toKelvin = {\n Celsius: t =&gt; t + C_OFFSET,\n Farenheit: t =&gt; (t + F_OFFSET) / F_SCALE,\n Rankine: t =&gt; t / F_SCALE,\n Kelvin: t =&gt; t,\n};\nconst fromKelvin = {\n Celsius: k =&gt; celsiusIn.value = round(k - C_OFFSET),\n Farenheit: k =&gt; farenheitIn.value = round(k * F_SCALE - F_OFFSET),\n Rankine: k =&gt; rankineIn.value = round(k * F_SCALE),\n Kelvin: k =&gt; kelvinIn.value = round(k),\n};\nconst round = val =&gt; Math.round(val * round.scale) / round.scale;\n\ndecimalIn.addEventListener(\"input\", decimalEvent);\ntemperatureList.addEventListener(\"input\", temperatureEvent);\ndecimalEvent();\n\nfunction decimalEvent() {\n const step = 1 / (round.scale = 10 ** decimalIn.value);\n celsiusIn.step = step;\n kelvinIn.step = step;\n farenheitIn.step = step;\n rankineIn.step = step;\n temperatureEvent();\n} \nfunction temperatureEvent({target = kelvinIn} = {}) { \n if (target.value !== \"\") {\n const unit = target.dataset.units;\n const kelvin = Math.max(0, toKelvin[unit](round(Number(target.value))));\n for (const convert of Object.values(fromKelvin)) { convert(kelvin) } \n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>label {\n font-size: large;\n}\ninput {\n width: 3em;\n}\nul {\n width: 220px;\n display: flex;\n flex-direction: column;\n list-style-type: none;\n padding-inline-start: 0px;\n}\nli input {\n float: right;\n width: 7em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h3&gt;Temperature unit converter&lt;/h3&gt;\n &lt;input type=\"number\" min=\"0\" max=\"5\" value=\"0\" step=\"1\" id=\"decimalIn\"&gt;\n&lt;label for=\"decimalIn\"&gt;&lt;small&gt;Decimals&lt;small&gt;&lt;/label&gt;\n\n&lt;ul id=\"temperatureList\"&gt;\n&lt;li&gt;\n &lt;label for=\"celsiusIn\"&gt;Celsius (ºC) &lt;/label&gt;\n &lt;input id=\"celsiusIn\" type=\"number\" data-units =\"Celsius\"&gt;\n&lt;/li&gt; \n\n&lt;li&gt; \n &lt;label for=\"kelvinIn\"&gt;Kelvin (K) &lt;/label&gt;\n &lt;input id=\"kelvinIn\" type=\"number\" min=\"0\" value=\"293\" step=\"1\" data-units=\"Kelvin\"&gt;\n&lt;/li&gt; \n\n&lt;li&gt; \n &lt;label for=\"farenheitIn\"&gt;Farenheit (ºF) &lt;/label&gt;\n &lt;input id=\"farenheitIn\" type=\"number\" data-units=\"Farenheit\"&gt;\n&lt;/li&gt; \n\n&lt;li&gt;\n &lt;label for=\"rankineIn\"&gt;Rankine (ºRa) &lt;/label&gt;\n &lt;input id=\"rankineIn\" type=\"number\" data-units=\"Rankine\"&gt; \n&lt;/li&gt; \n&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Update</h2>\n<p>The original rewrite had a few problems.</p>\n<ul>\n<li>Could not type negative values in some situations</li>\n<li>Was converting digits past the decimal count</li>\n<li>Was displaying trailing zeros. Eg <code>0.000</code> should be just <code>0</code></li>\n</ul>\n<p>The code has been changed to ignore partial inputs. E.G. the negative sign '-' before the numbers are added.</p>\n<p>Using <code>Math.round</code> rather than <code>Number.toFixed</code> to set the number of decimal places.</p>\n<p>Round the decimals before converting to base unit (kelvin) to stop fractions past the number of decimal making changes to other units.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T14:51:50.477", "Id": "514470", "Score": "0", "body": "I have never seen such beautiful code and I never imagined that it would be possible to make the code as simple as that. Your explanations made me understand JavaScript much more and for sure I will apply everything you taught." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:20:02.763", "Id": "514475", "Score": "0", "body": "I just realized now that the inputs are not accepting negative numbers directly from the keyboard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:25:07.303", "Id": "514476", "Score": "1", "body": "@ArnonRodrigues The inputs should be using the change event rather than the input event. However that would require a calculate button. You can also combine the two (events) and not set the value of the focused input element until it gets a change event" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:28:00.663", "Id": "514477", "Score": "1", "body": "@ArnonRodrigues I just noticed another problem. I am out of time ATM. Will update the answer addressing the problems tomorrow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T03:22:44.697", "Id": "514507", "Score": "0", "body": "All right, @Blindman67! Your code was my basis for working with other measurement systems. The complete [JavaScript](https://github.com/arnonrdp/Multi-Converter/blob/master/assets/main.js) was a little repetitive, but for me it's perfect!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:57:16.817", "Id": "260652", "ParentId": "260631", "Score": "3" } } ]
{ "AcceptedAnswerId": "260652", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T00:16:45.810", "Id": "260631", "Score": "2", "Tags": [ "javascript", "formatting", "html5", "unit-conversion" ], "Title": "HTML/JavaScript temperature converter with rounding" }
260631
<p>I've written this <strong><a href="https://github.com/ytliuSVN/crypto-app/blob/bd36ecb67538d25fe1be401f7030b4338433cd28/app/components/CoinList.js" rel="nofollow noreferrer">Card component</a></strong> which is composed of <code>thumbnail image</code>, <code>name</code>, <code>symbol</code>, <code>total_volume</code>, <code>current_price</code>, and <code>price_change_percentage_24h</code>.</p> <p><a href="https://i.stack.imgur.com/xizRW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xizRW.png" alt="enter image description here" /></a></p> <p>I want to refactor my <code>renderPriceChange</code> function since it's using the same pattern.</p> <pre><code>const renderPriceChange = (price) =&gt; { if (price &gt; 0) { return ( &lt;Text style={styles.rise}&gt; &lt;AntDesign name='caretup' color='#03AE9D' size={10} /&gt;{' '} {percentageFormat(item.price_change_percentage_24h)}% &lt;/Text&gt; ); } else { return ( &lt;Text style={styles.drop}&gt; &lt;AntDesign name='caretdown' color='#fb2c33' size={10} /&gt;{' '} {percentageFormat(item.price_change_percentage_24h)}% &lt;/Text&gt; ); } }; </code></pre> <p>How to make it look cleaner with smart and less code?</p>
[]
[ { "body": "<p>It is equivalent to:</p>\n<pre><code>const renderPriceChange = (price) =&gt; {\n return (\n &lt;Text style={price &gt; 0 ? styles.rise : styles.drop}&gt;\n &lt;AntDesign\n name={price &gt; 0 ? 'caretup' : 'caretdown'}\n color={price &gt; 0 ? '#03AE9D' : '#fb2c33'}\n size={10}\n /&gt;{' '}\n {percentageFormat(item.price_change_percentage_24h)}%\n &lt;/Text&gt;\n )\n}\n</code></pre>\n<p>You can inline the <code>if...else</code> by using JavaScript's ternary operator <code>a ? b : c</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T05:43:43.530", "Id": "514446", "Score": "0", "body": "That’s exactly what I wanted. Thanks a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T04:14:13.673", "Id": "260634", "ParentId": "260633", "Score": "3" } } ]
{ "AcceptedAnswerId": "260634", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T02:38:19.060", "Id": "260633", "Score": "2", "Tags": [ "javascript", "react.js", "jsx", "react-native" ], "Title": "React component to render price change" }
260633
<p>Description of the App:-</p> <ol> <li>A React app that shows the public Github repositories of a user.</li> <li>The app shows an input field where we can enter a Github username and a submit button. {It provides users the feedback while getting the data in the background.}</li> <li>The repositories are shown as a list and for each repo, the following information is displayed: Repository name, the number of stars, and forks.</li> <li>Each Repository item in the list is made clickable. It opens the repository on Github when clicked.</li> <li>A reset button is provided to clear the repository list</li> <li>A username can be provided as a URL parameter while opening the application and automatically show the users repositories</li> </ol> <p>Tech Stack:-</p> <p>React (hooks), Redux, Cypress (For Testing) Material UI, AG-Grid</p> <p>The Github README.md file has all the instructions on how to run the project.</p> <p>I will appreciate it if the app can be reviewed.</p> <p>What I am looking for is the following?</p> <ol> <li>Variable, functions, Component Naming Convention.</li> <li>Commit Messages format.</li> <li>Good coding practices are followed or not?</li> <li>Inputs and Feedback if code needs some optimization.</li> <li>Directory/Folder Structure.</li> </ol> <p>Please feel free to provide comments generously. I am trying to improve my coding skills and this app is a step towards that.</p> <p>Disclaimer:- Kindly use the Github link to review the code. That will give a clear idea of the directory structure, readme file, and other important aspects of the app.</p> <p><a href="https://github.com/aryan21710/GithubRepoTool.git" rel="nofollow noreferrer">GitHub Link</a></p> <pre><code>import React from 'react'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import Login from '../components/Login'; import DisplayRepo from '../components/DisplayRepo'; import PageNotFound from '../components/PageNotFound'; import { Box } from '@material-ui/core'; import { useStyles } from '../styles/components/login.js'; const Approutes = (props) =&gt; { const classes = useStyles(props); return ( &lt;BrowserRouter&gt; &lt;Box className={classes.mainContainer}&gt; &lt;Switch&gt; &lt;Route path='/' component={Login} exact={true} /&gt; &lt;Route path='/displayuserrepo/:uname' component={DisplayRepo} strict exact={true} /&gt; &lt;Route path='/*' component={PageNotFound} strict exact={true} /&gt; &lt;/Switch&gt; &lt;/Box&gt; &lt;/BrowserRouter&gt; ); }; export default Approutes; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T09:35:44.587", "Id": "260640", "Score": "1", "Tags": [ "javascript", "react.js", "redux" ], "Title": "Working React App to display public Github Repositories of a user" }
260640
<p><strong>Hello everyone!</strong></p> <p>Here is the thing. So I wanted at first to create Robot class, I want him to move around some board. Maybe 10x10 or something like that, then i wanted to invent a Robot fights class, I want to add class players (becuase i want to play between player 1 and player 2) but here it is what I have so much.</p> <p>Lets focus on this code because I want it to make it much better then start to create robot fights!</p> <pre class="lang-py prettyprint-override"><code>class Robot: def __init__(self, name, place, start = (0,0), power = 9): self.name = name self.start = start self.place = place self.power = power def get_name(self): return self.name def get_start(self): return self.start def get_place(self): return self.place def get_power(self): return self.power def set_name(self, x): if isinstance(x, str): self.name = x else: raise TypeError(&quot;must be a string&quot;) def set_start(self, x): if isinstance(x, tuple): self.start = x else: raise TypeError(&quot;must be a tuple&quot;) def set_place(self, x): if isinstance(x, list): self.place = x else: raise TypeError(&quot;must be a list&quot;) def set_power(self, x): if isinstance(x, int): self.power = x else: raise TypeError(&quot;must a int&quot;) def check_power(self): if self.power &lt;= 0: raise ValueError(&quot;No power&quot;) def left(self, value): self.check_power() self.power -= value if self.place[0] - value &lt; 0: self.place[0] = self.place[0] - value + 8 else: self.place[0] = self.place[0] - value def up(self, value): self.check_power() self.power -= value if self.place[1] + value &gt; 7: self.place[1] = self.place[1] + value - 8 else: self.place[1] = self.place[1] + value if self.place[1] == 5: self.power += 2 def __str__(self): return self.name, self.place, self.power </code></pre> <p>Also want I want to make better in this one. Well power will be important in the Robot fights, because if some robot from player 1 will be near to robot from player 2 I want them to you know, fight, so the power will be pretty good right there, if they will be near to each other the power will decrease until the robot is destroyed. But lets focus on above code to make it better.</p> <p>Any tips how to make this SHORTER and more neat, closer to a advanced or just better solution will be definitely on point.</p> <p><strong>Have a great day!</strong></p>
[]
[ { "body": "<p><strong>Type annotations</strong></p>\n<p>Using type annotations will make your program a lot more readable and easier to debug. For example:</p>\n<pre><code>def __init__(self, name, place, start = (0,0), power = 9):\n # assignments\n</code></pre>\n<p>becomes</p>\n<pre><code>def __init__(self, name: str, place : List[int], start: Tuple[int, int] = (0,0), power: int = 9):\n # assignments\n</code></pre>\n<p>I imported <code>List, Tuple</code> from the <code>typing</code> module from the standard library:</p>\n<pre><code>from typing import List, Tuple\n</code></pre>\n<p><a href=\"https://dev.to/dstarner/using-pythons-type-annotations-4cfe\" rel=\"nofollow noreferrer\">Here's some further information on using type annotations.</a></p>\n<hr />\n<p><strong>Getter and Setter</strong></p>\n<p>Using getters and setters is rather unpythonic. You can instead modify the getting and setting behaviours by using the <code>@property</code> decorator like this:</p>\n<pre><code>def __init__(self, name: str, place : List[int], start: Tuple[int, int] = (0,0), power: int = 9):\n self._name = name\n\n # further assignments\n\n@property\ndef name(self):\n return self._name\n\n@name.setter\ndef name(self, value):\n if isinstance(value, str):\n self._name = value\n else:\n raise TypeError(&quot;must be a string&quot;)\n</code></pre>\n<p>This will allow you to use the properties without explicitly calling getter and setter methods:</p>\n<pre><code>my_robot.name = 'foo'\nprint(my_robot.name)\n</code></pre>\n<p><a href=\"https://stackoverflow.com/q/2627002/9173379\">This question on StackOverflow</a> contains some more detailed explanations.</p>\n<hr />\n<p><strong>Logic</strong></p>\n<ol>\n<li>You should also take a look at your setters for <code>place</code> and <code>start</code>.\nYou only check the type of the passed argument <code>value</code>, but do not\nverify if the elements in the <code>list</code> or <code>tuple</code> are of type <code>int</code>.</li>\n<li>You could consider using a custom class <code>Position</code> or similiar for\nhandling the positional logic of the robot. That way you can access\nthe different dimensions by their names instead of indices of\n<code>place</code> (<code>self.place[0]</code> or <code>self.place[1]</code>). You'll also be able to put further logic (like clipping, etc.) into it.</li>\n<li><code>power</code> and <code>check_power()</code>: Depending on your intended functionality you might want to limit the number of steps that can be taken by a robot to the <code>power</code> that it has left. As it is now, a robot can take any number of steps as long as it has <code>power &gt; 0</code> left.</li>\n<li>You should check the functionality <code>left(value)</code> and <code>up(value)</code> for big values, especially values that are <code>&gt; 2 * board_dimension</code>. I suspect the results might be unintended.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:15:51.470", "Id": "514473", "Score": "0", "body": "Overall agreed. I would take your \"unpythonic accessor functions\" further - if there is any kind of non-trivial logic to the get or set, `@property` is called for, but here it isn't. Just make a \"public\" variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:31:33.830", "Id": "514479", "Score": "0", "body": "Genuine question: How do you then verify / ensure that only values of a certain type are assigned to *public* attributes, if at all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:55:41.140", "Id": "514480", "Score": "3", "body": "The short answer is that you don't. Type verification - typically - is not done at all, since Python uses duck typing. Recent support for static analysis of types is helpful but doesn't apply in runtime.\n\nIf you do want to apply validation to a value before set, then you would do it as you've shown with `@properties` or - if you're able to make the class immutable, which has a lot of advantages - then during `__init__`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:12:55.010", "Id": "260659", "ParentId": "260641", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T09:44:46.780", "Id": "260641", "Score": "0", "Tags": [ "python", "object-oriented" ], "Title": "Robot OOP Class in Python" }
260641
<p>I am trying to sort an associative array by following this scheme:</p> <ol> <li>Sort by 'qt': positives first, non-positives after. Magnitude does not matter, only sign.</li> <li>In positive part: sort by sa DESC</li> <li>In negative part: sort by sa DESC</li> </ol> <p>I managed to have the desired result but by tinkering :</p> <pre class="lang-php prettyprint-override"><code>$array = [ [ &quot;id&quot; =&gt; 1, &quot;qt&quot; =&gt; 1000, &quot;sa&quot; =&gt; 50 ], [ &quot;id&quot; =&gt; 2, &quot;qt&quot; =&gt; 0, &quot;sa&quot; =&gt; 50 ], [ &quot;id&quot; =&gt; 3, &quot;qt&quot; =&gt; 0, &quot;sa&quot; =&gt; 350 ], [ &quot;id&quot; =&gt; 4, &quot;qt&quot; =&gt; 5000, &quot;sa&quot; =&gt; 250 ], [ &quot;id&quot; =&gt; 5, &quot;qt&quot; =&gt; 10, &quot;sa&quot; =&gt; 9000 ] ]; $p_qty = array(); $n_qty = array(); foreach ($array as $e) { if($e['qt'] &lt;= 0){ array_push($n_qty, $e); } else { array_push($p_qty, $e); } } usort($p_qty, function($a, $b){ return $a['sa'] == $b['sa'] ? ( $a['sa'] == $b['sa'] ? 0 : ( $a['qt'] &lt; $b['qt'] ? 1 : -1 ) ) : ( $a['sa'] &lt; $b['sa'] ? 1 : -1 ); }); usort($n_qty, function($a, $b){ return $a['sa'] == $b['sa'] ? ( $a['sa'] == $b['sa'] ? 0 : ( $a['qt'] &lt; $b['qt'] ? 1 : -1 ) ) : ( $a['sa'] &lt; $b['sa'] ? 1 : -1 ); }); </code></pre> <p>I get the wanted result: <code>ID [5, 4, 1, 3, 2]</code></p> <p>Is there a simple to do the wanted result in a unique <code>usort</code> function ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T12:14:46.517", "Id": "514456", "Score": "0", "body": "So in your example you expect qt values [ 10, 5000, 1000, 0, 0 ] ? These are not sorted. Are you sure your example is valid?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T12:22:41.307", "Id": "514458", "Score": "0", "body": "Actually, 'sa' must take priority once the 'qt' was sorted. With my code I get two arrays :\n\n`$p_qty = [ [ id=5, qt=10, sa=5000 ], [ id=4, qt=5000, sa=250 ], [ id=1, qt=1000, sa=50 ] ];\n$n_qty = [ [ id=3, qt=0, sa=350 ], [ id=2, qt=0, sa=50 ] ];`\n\nAnd for some improvements, I'd like to get this result :\n`[ [ id=5, qt=10, sa=5000 ], [ id=4, qt=5000, sa=250 ], [ id=1, qt=1000, sa=50 ], [ id=3, qt=0, sa=350 ], [ id=2, qt=0, sa=50 ] ];`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T06:00:12.713", "Id": "514517", "Score": "0", "body": "@AurélienPitaut Can `qt` value possibly be negative in your business logic? Or when you say \"negative\", do you more accurately mean \"non-positive\" (zero). Assuming `qt` means \"quantity\", is it possible to have a negative quantity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T20:14:09.970", "Id": "514643", "Score": "0", "body": "Yes it's possible to have a negative value (like -1) :')" } ]
[ { "body": "<p>You are not actually sorting on <code>qt</code>, only using it to separate two sets (positive <code>qt</code> coming first). Only within each set you are actually sorting (on <code>sa</code>). Therefore, the usort() comparator function could look like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>usort($array, function($a, $b) {\n // split in positive and negative set\n if ($a['qt'] &lt;= 0 &amp;&amp; $b['qt'] &gt; 0) return 1; // b before a\n if ($a['qt'] &gt; 0 &amp;&amp; $b['qt'] &lt;= 0) return -1; // a before b\n\n // both a and b are in the same set. sort on `sa` descending\n return $b['sa'] - $a['sa'];\n});\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:43:09.170", "Id": "260650", "ParentId": "260642", "Score": "2" } }, { "body": "<p>The spaceship operator provides a far simpler technique for implementing multi-condition sorting.</p>\n<p>Notice that there are no conditions in my sorting function's body. Arrays on either side of <code>&lt;=&gt;</code> are synchronously compared element-by-element.\nBy checking if <code>qt</code> is larger than zero and using that boolean value, zeros become <code>false</code> and non-zeros become <code>true</code>. Furthermore when sorting booleans in DESC order, <code>true</code> comes before <code>false</code>.</p>\n<p>Sort by <code>qt</code> non-zeros before zeros, then <code>sa</code> DESC: (<a href=\"https://3v4l.org/ZYvnM\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>usort(\n $array,\n function($a, $b) {\n return [$b['qt'] &gt; 0, $b['sa']] &lt;=&gt; [$a['qt'] &gt; 0, $a['sa']];\n }\n);\n</code></pre>\n<p>Same thing from PHP7.4 and higher (<a href=\"https://3v4l.org/sqjKe\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>usort($array, fn($a, $b) =&gt; [$b['qt'] &gt; 0, $b['sa']] &lt;=&gt; [$a['qt'] &gt; 0, $a['sa']]);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T01:36:54.150", "Id": "260685", "ParentId": "260642", "Score": "2" } }, { "body": "<blockquote>\n<pre><code>$array = [\n</code></pre>\n</blockquote>\n<p>I personally don't like the name <code>$array</code>. I would prefer a name like <code>data</code> if a more specific name is not available.</p>\n<blockquote>\n<pre><code>$p_qty = array();\n$n_qty = array();\n</code></pre>\n</blockquote>\n<p>It's somewhat odd that your first array uses the short syntax <code>[]</code> but these use the older long syntax <code>array()</code>. It would be more consistent to use the short syntax here as well. And of course, shorter.</p>\n<blockquote>\n<pre><code>foreach ($array as $e) {\n if($e['qt'] &lt;= 0){ array_push($n_qty, $e); }\n else { array_push($p_qty, $e); }\n}\n</code></pre>\n</blockquote>\n<p>A simpler way of doing this would be</p>\n<pre><code>$n_qty = array_filter($data, function ($v) { $v['qt'] &lt;= 0; });\n$p_qty = array_diff($data, $n_qty);\n</code></pre>\n<p>So the whole algorithm could be</p>\n<pre><code>usort($data, function ($a, $b) { return $b['sa'] &lt;=&gt; $a['sa']; });\n\n$p_qty = array_filter($data, function ($v) { return $v['qt'] &gt; 0; });\n$data = array_merge($p_qty, array_diff($data, $p_qty));\n</code></pre>\n<p>You could use the newer <code>fn</code> syntax in PHP 7.4 and later. I spend most of my time coding with a requirement of PHP 7.3 compatibility, so I'm not really up on it.</p>\n<p>Note: I am not saying that this is better than putting everything in the same comparator function (as the other two current answers are doing). That saves you the intermediate <code>$p_qty</code> array. What I am saying is that this is a simpler way of accomplishing your original approach of breaking into two arrays. PHP has a lot of array manipulation functions that will save iterating over an array. In other circumstances where you want to split an array like this, it will help to know them.</p>\n<p>Note that sorting by sa first makes it so that you don't have to sort by it twice (less code). Both subarrays will retain that order. However, sorting twice would be more efficient, as it is quicker to sort two small arrays than one combined array.</p>\n<p>In general, it is <a href=\"https://stackoverflow.com/q/14232766/6660678\">preferable</a> to do</p>\n<pre><code>$n_qty[] = e;\n</code></pre>\n<p>to</p>\n<pre><code>array_push($n_qty, e);\n</code></pre>\n<p>when adding a single element to an array. Where <code>array_push</code> shines is when you have to add multiple elements at the same time. It doesn't really matter here unless you are doing this a lot. But the <a href=\"https://www.php.net/manual/en/function.array-push.php\" rel=\"nofollow noreferrer\">PHP manual</a> recommends avoiding using <code>array_push</code> for single elements, and it may be a good habit to adopt.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T06:45:54.283", "Id": "260690", "ParentId": "260642", "Score": "1" } } ]
{ "AcceptedAnswerId": "260650", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T10:42:58.213", "Id": "260642", "Score": "3", "Tags": [ "php", "array", "sorting" ], "Title": "PHP Sort Associative Array first by relativity of value then by other value desc" }
260642
<p>This is a challenge from CodeSignal.</p> <p>For</p> <pre><code>image = [[1, 1, 1], [1, 7, 1], [1, 1, 1]] </code></pre> <p>the output should be <code>boxBlur(image) = [[1]]</code>.</p> <p>To get the value of the middle pixel in the input 3 × 3 square: <code>(1 + 1 + 1 + 1 + 7 + 1 + 1 + 1 + 1) = 15 / 9 = 1.66666 = 1</code>. The border pixels are cropped from the final result.</p> <p>For</p> <pre><code>image = [[7, 4, 0, 1], [5, 6, 2, 2], [6, 10, 7, 8], [1, 4, 2, 0]] </code></pre> <p>the output should be</p> <pre><code>boxBlur(image) = [[5, 4], [4, 4]] </code></pre> <p>There are four 3 × 3 squares in the input image, so there should be four integers in the blurred output. To get the first value: <code>(7 + 4 + 0 + 5 + 6 + 2 + 6 + 10 + 7) = 47 / 9 = 5.2222 = 5</code>. The other three integers are obtained the same way, then the surrounding integers are cropped from the final result.</p> <p>Here's my code:</p> <pre><code>function boxBlur(image) { const SQUARE = 3 const outerArr = [] for (let i = 0; i &lt; image.length; i++) { const innerArr = [] for (let j = 0; j &lt; image[0].length; j++) { if (image[i][j] !== undefined &amp;&amp; image[i][j+2] !== undefined &amp;&amp; image[i+2]) { let sum = 0 for (let k = 0; k &lt; SQUARE; k++) { for (let y = 0; y &lt; SQUARE; y++) { sum += image[i+k][j+y] } } innerArr.push(Math.floor(sum/9)) } } if (innerArr.length) outerArr.push(innerArr) } return outerArr } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Some suggestions on coding style:</p>\n<ul>\n<li><p>Your choice in variables is somewhat confusing <code>i</code>, <code>j</code>? For an algorithm operating on a 2D image, the names <code>x</code> and <code>y</code> would be better. And <code>dx</code>, <code>dy</code> for the offsets in the inner loop.</p>\n</li>\n<li><p>You defined the width of your kernel as <code>SQUARE</code>, yet you hardcode <code>2</code> in the expression <code>image[i][j+2]</code>.</p>\n</li>\n<li><p>Your boundary checks can be more efficient. Why check for <code>undefined</code> if you know the exact size of the image? You can loop <code>i</code> from <code>0</code> to <code>image.length - SQUARE</code>, and loop <code>j</code> from <code>0</code> to <code>image[0].length - SQUARE</code> and remove the if statement:</p>\n</li>\n</ul>\n<pre class=\"lang-javascript prettyprint-override\"><code>for (let i = 0; i &lt; image.length - SQUARE; i++) {\n for (let j = 0; j &lt; image[0].length - SQUARE; j++) {\n // no if-statement needed anymore\n ...\n }\n}\n</code></pre>\n<p>Note that the naive algorithm works fine for small kernels, but can be done more efficient using a summation map where you first calculate the total sum of all preceding values in a preprocessing step, and then calculate the sum of the pixels in the square using the summation map of the 4 corner points. That way, the algorithm speed becomes independent of the size <code>SQUARE</code> of your kernel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T11:42:11.363", "Id": "514538", "Score": "0", "body": "very helpful. I initially checked for `undefined` as some numbers in the `image` can evaluate to `0`; the if statement would fail then. Regarding your third bullet point, I couldn't really understand it. Could you show me a bit of code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T16:15:37.773", "Id": "514551", "Score": "1", "body": "@uber Added example code. By reducing the range of the `i` and `j` variables, the inner `k` and `y` loops will never exceed the boundaries so you can remove the if-statement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T12:09:17.807", "Id": "260645", "ParentId": "260644", "Score": "5" } }, { "body": "<p>The code in general is pretty good, so I don't have a lot to suggest, just a handful of pointers.</p>\n<ul>\n<li>As already mentioned, variable naming could be a little better. For example, I'm not sure why your two most inner loops use the variables &quot;k&quot; and &quot;y&quot;. &quot;SQUARE&quot; would probably be better named as &quot;SQUARE_SIZE&quot;. outerArr and innerArr could be newImage and newRow. etc.</li>\n<li>Four nested loops is quite a lot. You could easily extract the two most inner loops into its own &quot;calcBlurValueAtCoord()&quot; function.</li>\n<li>When checking for out-of-bounds, the <code>image[i][j] !== undefined</code> check is doing nothing - <code>image[i][j]</code> will never be undefined. In fact, that whole <code>if()</code> could be simplified to this: <code>if (image[i+2]?.[j+2] !== undefined)</code></li>\n</ul>\n<p>Once you've applied those bullet points, I think your code would be pretty solid.</p>\n<p>If you additionally wanted to make the code a little more functional and less procedural (not that you should or shouldn't, it's just a different style), you could replace the for loops with functions such as <code>.map()</code> and break out more helper functions.</p>\n<p>In the below example, you'll notice that the boxBlur() function is really high-level - just by reading it, you can get an overview of how a box-blur is done: &quot;With each coordinate in the grid, calculate a blur value, then trim the margins&quot;. What does it mean to &quot;calculate a blur value&quot;? Just look at that function definition (for blurValueAtCoord()): &quot;Take the average of the surrounding coordinates and floor it&quot; - you get the idea.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const boxBlur = grid =&gt; trimMargins(\n coordsInGrid(grid)\n .map(coord =&gt; blurValueAtCoord(grid, coord))\n)\n\nconst average = array =&gt; array.reduce((a, b) =&gt; a + b) / array.length\n\nconst coordsInGrid = grid =&gt; grid.flatMap((row, y) =&gt; row.map((_, x) =&gt; [x, y]))\n\nconst blurValueAtCoord = (grid, coord) =&gt; Math.floor(average(getSurroundingValues(grid, coord)))\n\nconst trimMargins = grid =&gt; grid.slice(1, -1).map(row =&gt; row.slice(1, -1))\n\nconst getSurroundingValues = (grid, [y, x]) =&gt; [\n grid[y-1]?.[x-1], grid[y]?.[x-1], grid[y+1]?.[x-1],\n grid[y-1]?.[x], grid[y]?.[x], grid[y+1]?.[x],\n grid[y-1]?.[x+1], grid[y]?.[x+1], grid[y+1]?.[x+1],\n].map(x =&gt; x ?? 0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T11:48:46.683", "Id": "514539", "Score": "0", "body": "loved the if statement simplification" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T05:38:36.610", "Id": "260688", "ParentId": "260644", "Score": "1" } } ]
{ "AcceptedAnswerId": "260645", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T11:22:13.200", "Id": "260644", "Score": "2", "Tags": [ "javascript", "algorithm" ], "Title": "Box Blur algorithm" }
260644
<p>I am trying to translate the book Game Coding Complete by Mike McShaffry 4E to modern C++17 standard and faced with the code of Mersenne Twister by Takuji Nishimura and Makoto Matsumoto. Is it right to convert random generator code from book like that:</p> <p>from:</p> <pre><code>#include &lt;ctime&gt; #define CMATH_N 624 #define CMATH_M 397 #define CMATH_MATRIX_A 0x9908b0df /* constant vector a */ #define CMATH_UPPER_MASK 0x80000000 /* most significant w-r bits */ #define CMATH_LOWER_MASK 0x7fffffff /* least significant r bits */ #define CMATH_TEMPERING_MASK_B 0x9d2c5680 #define CMATH_TEMPERING_MASK_C 0xefc60000 #define CMATH_TEMPERING_SHIFT_U(y) (y &gt;&gt; 11) #define CMATH_TEMPERING_SHIFT_S(y) (y &lt;&lt; 7) #define CMATH_TEMPERING_SHIFT_T(y) (y &lt;&lt; 15) #define CMATH_TEMPERING_SHIFT_L(y) (y &gt;&gt; 18) typedef int INT; typedef unsigned int UINT; #define MAXUINT ((UINT)~((UINT)0)) #define MAXINT ((INT)(MAXUINT &gt;&gt; 1)) class GCCRandom { private: unsigned int rseed; unsigned int rseed_sp; unsigned long mt[CMATH_N]; /* the array for the state vector */ int mti; /* mti==N+1 means mt[N] is not initialized */ public: GCCRandom() { rseed = 1; rseed_sp = 0; mti = CMATH_N + 1; } unsigned int Random(unsigned int n) { unsigned long y; static unsigned long mag01[2] = { 0x0, CMATH_MATRIX_A }; if (n == 0) return(0); if (mti &gt;= CMATH_N) { /* generate N words at one time */ int kk; if (mti == CMATH_N + 1) /* if sgenrand() has not been called, */ SetRandomSeed(4357); /* a default initial seed is used */ for (kk = 0; kk &lt; CMATH_N - CMATH_M; kk++) { y = (mt[kk] &amp; CMATH_UPPER_MASK) | (mt[kk + 1] &amp; CMATH_LOWER_MASK); mt[kk] = mt[kk + CMATH_M] ^ (y &gt;&gt; 1) ^ mag01[y &amp; 0x1]; } for (; kk &lt; CMATH_N - 1; kk++) { y = (mt[kk] &amp; CMATH_UPPER_MASK) | (mt[kk + 1] &amp; CMATH_LOWER_MASK); mt[kk] = mt[kk + (CMATH_M - CMATH_N)] ^ (y &gt;&gt; 1) ^ mag01[y &amp; 0x1]; } y = (mt[CMATH_N - 1] &amp; CMATH_UPPER_MASK) | (mt[0] &amp; CMATH_LOWER_MASK); mt[CMATH_N - 1] = mt[CMATH_M - 1] ^ (y &gt;&gt; 1) ^ mag01[y &amp; 0x1]; mti = 0; } y = mt[mti++]; y ^= CMATH_TEMPERING_SHIFT_U(y); y ^= CMATH_TEMPERING_SHIFT_S(y) &amp; CMATH_TEMPERING_MASK_B; y ^= CMATH_TEMPERING_SHIFT_T(y) &amp; CMATH_TEMPERING_MASK_C; y ^= CMATH_TEMPERING_SHIFT_L(y); return (y % n); } float Random() { float r = (float)Random(MAXINT); float divisor = (float)MAXINT; return (r / divisor); } void SetRandomSeed(unsigned int n) { /* setting initial seeds to mt[N] using */ /* the generator Line 25 of Table 1 in */ /* [KNUTH 1981, The Art of Computer Programming */ /* Vol. 2 (2nd Ed.), pp102] */ mt[0] = n &amp; 0xffffffff; for (mti = 1; mti &lt; CMATH_N; mti++) mt[mti] = (69069 * mt[mti - 1]) &amp; 0xffffffff; rseed = n; } unsigned int GetRandomSeed() { return rseed; } void Randomize() { SetRandomSeed((unsigned int)time(NULL)); } }; </code></pre> <p>to code with std::mt19937 engine and std::uniform_int_distribution:</p> <pre><code>#include &lt;random&gt; #include &lt;limits&gt; #include &lt;chrono&gt; class MTRandom { private: unsigned int m_rseed = 1; unsigned int m_rseed_sp = 0; static const unsigned int MAXINT = std::numeric_limits&lt;int&gt;::max(); std::mt19937 m_engine; public: MTRandom() { m_engine.seed(m_rseed); } unsigned int Random(unsigned int n) { std::uniform_int_distribution&lt;unsigned int&gt; distr(0, n); return distr(m_engine); }; float Random() { std::uniform_real_distribution&lt;float&gt; distr(0.0f, 1.0f); return distr(m_engine); } void SetRandomSeed(unsigned int n) { m_engine.seed(n); m_rseed = n; } unsigned int GetRandomSeed() { return m_rseed; } void Randomize() { SetRandomSeed((unsigned int)std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); } }; </code></pre>
[]
[ { "body": "<p>The short answer is (mostly) yes. Your use of C++17 and std::mt19937 looks mostly correct.</p>\n<p>However:</p>\n<ul>\n<li><p>You have <code>std::uniform_int_distribution&lt;unsigned int&gt; distr(0, n)</code>, and this generates random values from <code>0</code> to <code>n</code> inclusive. Your original code appears to generate values from <code>0</code> to <code>n-1</code> inclusive. So you should use <code>std::uniform_int_distribution&lt;unsigned int&gt; distr(0, n-1)</code>. In addition, before doing that, you would need to check whether <code>n</code> equals zero:</p>\n<pre><code>unsigned int Random(unsigned int n) {\n if (n == 0)\n return 0;\n std::uniform_int_distribution&lt;unsigned int&gt; distr(0, n-1);\n return distr(m_engine);\n};\n</code></pre>\n</li>\n<li><p>Your code declares <code>m_rseed_sp</code> and <code>MAXINT</code>, both of which are not used. It would be better to remove them. Then you can also remove <code>#include &lt;limits&gt;</code>.</p>\n</li>\n<li><p>It is probably slightly more efficient to create member variables for std::uniform_int_distribution and for std::uniform_real_distribution. For std::uniform_real_distribution this is trivial because you never change the parameters of the distribution. For std::uniform_int_distribution, it is <em>slightly</em> more complicated because now you have to create parameters and pass them to the distribution. Something like this (untested):</p>\n<pre><code>private:\n using IntDistribution = std::uniform_int_distribution&lt;unsigned int&gt;;\n IntDistribution m_int_distribution;\n\npublic:\n unsigned int Random(unsigned int n) {\n if (n == 0)\n return 0;\n IntDistribution::param_type parameters{0, n-1};\n return m_int_distribution(m_engine, parameters);\n };\n</code></pre>\n</li>\n<li><p>For the <code>Randomize()</code> function, you might consider something like this instead:</p>\n<pre><code>void Randomize() {\n std::random_device randomDevice;\n SetRandomSeed(randomDevice());\n}\n</code></pre>\n<p>Ideally, this seems better than just using the current time. However, I've seen rumors that <code>std::random_device</code> is not implemented well on a few platforms, so maybe what you have is better? That's a judgement call.</p>\n</li>\n<li><p>Note: There is no guarantee that std::mt19937 will initialize its internal state identically to the way your old code did, in fact I think it is very unlikely. So you can't expect identical output even if you use the same seed.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T21:43:24.723", "Id": "260677", "ParentId": "260646", "Score": "1" } } ]
{ "AcceptedAnswerId": "260677", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T12:46:38.787", "Id": "260646", "Score": "2", "Tags": [ "c++", "random", "stl" ], "Title": "convert GCCRandom(Mersenne Twister by Takuji Nishimura and Makoto Matsumoto) to stl random" }
260646
<p>Im planning to use Strategy design pattern to put it in ScheduledExecutorService.scheduleAtFixedRate. I can use create as many scheduleAtFixedrate depends on the data to be pulled. Will this cause a race condition?</p> <pre><code> public abstract class DefaultStrategy { protected Map&lt;String, String&gt; transactionMap; protected AuthParam authParam; public DefaultStrategy(Map&lt;String, String&gt; transactionMap, Projection projection) { this.transactionMap = transactionMap; this.projection= projection; } } public class BankStrategy extends DefaultStrategy implements Runnable{ public BankStrategy (Map&lt;String, String&gt; transactionMap, Projection projection) { super(transactionMap, projection); } @Override public void run() { String transaction = transactionMap.get(&quot;branch1&quot;); String balance = projection.getBalance(); // do something with transaction and balance } } public class LoanSharkStrategy extends DefaultStrategy implements Runnable{ public LoanSharkStrategy(Map&lt;String, String&gt; transactionMap, Projection projection) { super(transactionMap, projection); } @Override public void run() { String transaction = transactionMap.get(&quot;branch2&quot;); String balance = projection.getBalance(); // do something with transaction and balance } } public class Handler { private static final ScheduledExecutorService scheduledExecutorServiceFirst = MDScheduledExecutorService.wrap( new ScheduledThreadPoolExecutor(5), &quot;first-thread-%d&quot;); //assuming this is the main method to call private void main() { //assuming there is a list of Param with transactionMap and projection that was populated in other function.. List&lt;Param&gt; loanSharkStrategyParams = getParamsFromOtherFucnction(); loanSharkStrategyParams.forEach(param -&gt; { scheduledExecutorServiceFirst.scheduleAtFixedRate(new LoanSharkStrategy(param.getTransactionMap, param.getProjection())), 1, 3600, SECONDS); }); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:04:31.293", "Id": "260647", "Score": "1", "Tags": [ "java" ], "Title": "Race Condition in ScheduledExecutorService.scheduleAtFixedRate" }
260647
<p>Is it right it convert ID3DXMatrixStack to DirectXMath like that:</p> <pre><code>#include &lt;stack&gt; #include &lt;iostream&gt; #include &lt;DirectXMath.h&gt; class MatrixStack { std::deque&lt;DirectX::XMFLOAT4X4&gt; m_MatrixStack; public: MatrixStack() { DirectX::XMFLOAT4X4 identity; DirectX::XMStoreFloat4x4(&amp;identity, DirectX::XMMatrixIdentity()); m_MatrixStack.push_back(identity); } void Push() { m_MatrixStack.push_back(m_MatrixStack.back()); } void Pop() { if (!m_MatrixStack.empty()) { m_MatrixStack.pop_back(); } } void MultMatrix(DirectX::FXMMATRIX other) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4(&amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply(currentMatrix, other)); } void MultMatrix(const DirectX::XMFLOAT4X4&amp; other) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMMATRIX otherMatrix = DirectX::XMLoadFloat4x4(&amp;other); DirectX::XMStoreFloat4x4(&amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply(currentMatrix, otherMatrix)); } void MultMatrixLocal(DirectX::FXMMATRIX other) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4(&amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply(other, currentMatrix)); } void MultMatrixLocal(const DirectX::XMFLOAT4X4&amp; other) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMMATRIX otherMatrix = DirectX::XMLoadFloat4x4(&amp;other); DirectX::XMStoreFloat4x4(&amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply(otherMatrix, currentMatrix)); } void LoadIdentity() { DirectX::XMFLOAT4X4 identity; DirectX::XMStoreFloat4x4(&amp;m_MatrixStack.back(), DirectX::XMMatrixIdentity()); } void LoadMatrix(const DirectX::XMFLOAT4X4&amp; other) { m_MatrixStack.back() = other; } void LoadMatrix(DirectX::FXMMATRIX other) { DirectX::XMStoreFloat4x4(&amp;m_MatrixStack.back(), other); } const DirectX::XMFLOAT4X4&amp; GetTop() { return m_MatrixStack.back(); } void RotateAxis(const DirectX::XMFLOAT3&amp; axis, float angle) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMVECTOR axis3f = DirectX::XMLoadFloat3(&amp;axis); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( currentMatrix, DirectX::XMMatrixRotationAxis(axis3f, angle) ) ); } void RotateAxis(DirectX::FXMVECTOR axis, float angle) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( currentMatrix, DirectX::XMMatrixRotationAxis(axis, angle) ) ); } void RotateAxisLocal(const DirectX::XMFLOAT3&amp; axis, float angle) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMVECTOR axis3f = DirectX::XMLoadFloat3(&amp;axis); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( DirectX::XMMatrixRotationAxis(axis3f, angle), currentMatrix ) ); } void RotateAxisLocal(const DirectX::FXMVECTOR&amp; axis, float angle) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( DirectX::XMMatrixRotationAxis(axis, angle), currentMatrix ) ); } void RotateYawPitchRoll(float yaw, float pitch, float roll) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( currentMatrix, DirectX::XMMatrixRotationRollPitchYaw(pitch, yaw, roll) ) ); } void RotateYawPitchRollLocal(float yaw, float pitch, float roll) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( DirectX::XMMatrixRotationRollPitchYaw(pitch, yaw, roll), currentMatrix ) ); } void Scale(float x, float y, float z) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( currentMatrix, DirectX::XMMatrixScaling(x, y, z) ) ); } void ScaleLocal(float x, float y, float z) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( DirectX::XMMatrixScaling(x, y, z), currentMatrix ) ); } void Translate(float x, float y, float z) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( currentMatrix, DirectX::XMMatrixTranslation(x, y, z) ) ); } void TranslateLocal(float x, float y, float z) { DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&amp;m_MatrixStack.back()); DirectX::XMStoreFloat4x4( &amp;m_MatrixStack.back(), DirectX::XMMatrixMultiply( DirectX::XMMatrixTranslation(x, y, z), currentMatrix ) ); } }; </code></pre> <p>Supplies a mechanism to enable matrices to be pushed onto and popped off of a matrix stack. Implementing a matrix stack is an efficient way to track matrices while traversing a transform hierarchy. Matrix stack to store transformations as matrices. Implementing a Scene Hierarchy A matrix stack simplifies the construction of hierarchical models, in which complicated objects are constructed from a series of simpler objects. A scene, or transform, hierarchy is usually represented by a tree data structure.Each node in the tree data structure contains a matrix.A particular matrix represents the change in coordinate systems from the node's parent to the node. For example, if you are modeling a human arm, you might implement the following hierarchy. In this hierarchy, the Body matrix places the body in the world.The UpperArm matrix contains the rotation of the shoulder, the LowerArm matrix contains the rotation of the elbow, and the Hand matrix contains the rotation of the wrist.To determine where the hand is relative to the world, you simply multiply all the matrices from Body down through Hand together. The previous hierarchy is overly simplistic, because each node has only one child.If you begin to model the hand in more detail, you will probably add fingersand a thumb. Each digit can be added to the hierarchy as children of Hand. If you traverse the complete graph of the arm in depth - first order-traversing as far down one path as possible before moving on to the next path—to draw the scene, you perform a sequence of segmented rendering.For example, to render the handand fingers, you implement the following pattern.</p> <ol> <li>Push the Hand matrix onto the matrix stack.</li> <li>Draw the hand.</li> <li>Push the Thumb matrix onto the matrix stack.</li> <li>Draw the thumb.</li> <li>Pop the Thumb matrix off the stack.</li> <li>Push the Finger 1 matrix onto the matrix stack.</li> <li>Draw the first finger.</li> <li>Pop the Finger 1 matrix off the stack.</li> <li>Push the Finger 2 matrix onto the matrix stack.You continue in this manner until all the fingersand thumb are rendered.</li> </ol> <p>After you have completed rendering the fingers, you would pop the Hand matrix off the stack. You can follow this basic process in code with the following examples.When you encounter a node during the depth - first search of the tree data structure, push the matrix onto the top of the matrix stack.</p> <p>MatrixStack-&gt;Push();</p> <p>MatrixStack-&gt;MultMatrix(pNode-&gt;matrix);</p> <p>When you are finished with a node, pop the matrix off the top of the matrix stack.</p> <p>MatrixStack-&gt;Pop();</p> <p>In this way, the matrix on the top of the stack always represents the world - transform of the current node.Therefore, before drawing each node, you should set matrix.</p> <pre><code>// Adds a matrix to the stack. // This method increments the count of items on the stack by 1, duplicating the current matrix. // The stack will grow dynamically as more items are added. void Push(); // Removes the current matrix from the top of the stack. // Note that this method decrements the count of items on the stack by 1, effectively // removing the current matrix from the top of the stack and promoting a matrix to the top of the // stack. If the current count of items on the stack is 0, then this method returns without performing // any action. If the current count of items on the stack is 1, then this method empties the stack. void Pop(); // Determines the product of the current matrixand the given matrix. // This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin // m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat); // This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix. void MultMatrix(DirectX::FXMMATRIX other); // Determines the product of the current matrixand the given matrix. // This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin // m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat); // This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix. void MultMatrix(const DirectX::XMFLOAT4X4&amp; other); // Determines the product of the given matrix and the current matrix. // This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object). // m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos]; // This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix. void MultMatrixLocal(DirectX::FXMMATRIX other); // Determines the product of the given matrix and the current matrix. // This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object). // m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos]; // This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix. void MultMatrixLocal(const DirectX::XMFLOAT4X4&amp; other); // Loads identity in the current matrix. // The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients, // which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged. // The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, // translations, and any other transformations that can be represented by a 4x4 matrix. void LoadIdentity(); // Loads the given matrix into the current matrix. void LoadMatrix(const DirectX::XMFLOAT4X4&amp; other); // Loads the given matrix into the current matrix. void LoadMatrix(DirectX::FXMMATRIX other); // Retrieves the current matrix at the top of the stack. // Note that this method does not remove the current matrix from the top of the stack; rather, it just returns the current matrix. DirectX::XMFLOAT4X4&amp; GetTop(); // Rotates (relative to world coordinate space) around an arbitrary axis. // axis - arbitrary axis of rotation // angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin. // This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following: // D3DXMATRIX tmp; // D3DXMatrixRotationAxis(&amp;tmp, pV, angle); // m_stack[m_currentPos] = m_stack[m_currentPos] * tmp; // Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space. void RotateAxis(const DirectX::XMFLOAT3&amp; axis, float angle); // Rotates (relative to world coordinate space) around an arbitrary axis. // axis - arbitrary axis of rotation // angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin. // This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following: // D3DXMATRIX tmp; // D3DXMatrixRotationAxis(&amp;tmp, pV, angle); // m_stack[m_currentPos] = m_stack[m_currentPos] * tmp; // Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space. void RotateAxis(DirectX::FXMVECTOR axis, float angle); // Rotates (relative to the object's local coordinate space) around an arbitrary axis. // axis - arbitrary axis of rotation // angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin. // This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following: // D3DXMATRIX tmp; // D3DXMatrixRotationAxis(&amp;tmp, pV, angle); // m_stack[m_currentPos] = tmp * m_stack[m_currentPos]; // Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space. void RotateAxisLocal(const DirectX::XMFLOAT3&amp; axis, float angle); // Rotates (relative to the object's local coordinate space) around an arbitrary axis. // axis - arbitrary axis of rotation // angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin. // This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following: // D3DXMATRIX tmp; // D3DXMatrixRotationAxis(&amp;tmp, pV, angle); // m_stack[m_currentPos] = tmp * m_stack[m_currentPos]; // Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space. void RotateAxisLocal(const DirectX::FXMVECTOR&amp; axis, float angle); // Rotates around (relative to world coordinate space). // The yaw around the y-axis in radians. // The pitch around the x-axis in radians. // The roll around the z-axis in radians. // This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following: // D3DXMATRIX tmp; // D3DXMatrixRotationYawPitchRoll(&amp;tmp, yaw, pitch, roll); // m_stack[m_currentPos] = m_stack[m_currentPos] * tmp; // Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space. void RotateYawPitchRoll(float yaw, float pitch, float roll); // Rotates around (relative to world coordinate space). // The yaw around the y-axis in radians. // The pitch around the x-axis in radians. // The roll around the z-axis in radians. // This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following: // D3DXMATRIX tmp; // D3DXMatrixRotationYawPitchRoll(&amp;tmp, yaw, pitch, roll); // m_stack[m_currentPos] = tmp * m_stack[m_currentPos]; // Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space. void RotateYawPitchRollLocal(float yaw, float pitch, float roll); // Scale the current matrix about the world coordinate origin. // This method right-multiplies the current matrix with the computed scale matrix. The transformation is about the current world origin. // D3DXMATRIX tmp; // D3DXMatrixScaling(&amp;tmp, x, y, z); // m_stack[m_currentPos] = m_stack[m_currentPos] * tmp; void Scale(float x, float y, float z); // Scale the current matrix about the object origin. // This method left-multiplies the current matrix with the computed scale matrix. The transformation is about the local origin of the object. // D3DXMATRIX tmp; // D3DXMatrixScaling(&amp;tmp, x, y, z); // m_stack[m_currentPos] = tmp * m_stack[m_currentPos]; void ScaleLocal(float x, float y, float z); // Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z) // This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin). // D3DXMATRIX tmp; // D3DXMatrixTranslation(&amp;tmp, x, y, z); // m_stack[m_currentPos] = m_stack[m_currentPos] * tmp; void Translate(float x, float y, float z); // Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix. // This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object). // D3DXMATRIX tmp; // D3DXMatrixTranslation(&amp;tmp, x, y, z); // m_stack[m_currentPos] = tmp * m_stack[m_currentPos]; void TranslateLocal(float x, float y, float z); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T11:11:39.800", "Id": "514604", "Score": "0", "body": "It might be worth considering to replace deque with a vector" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T11:35:03.110", "Id": "514605", "Score": "0", "body": "it would be better to add XM_CALLCONV for 32bit systems" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T13:36:27.397", "Id": "260648", "Score": "0", "Tags": [ "c++", "matrix", "windows", "graphics", "hlsl" ], "Title": "convert ID3DXMatrixStack to DirectXMath" }
260648
<p>I have been writing a discord.py bot, running on replit.com. I gotten to the music bot part after finishing the queue part. My code is logically correct; however, the code is way too inefficient causing the bot to crash when someone adds another song to the queue. How can I program my bot to be more efficient? If my code must be completely different, then a short explanation would be appreciated.</p> <p>The code for play:</p> <pre class="lang-py prettyprint-override"><code>@bot.command(name='play', aliases=['sing', 'p']) async def _play(ctx, url : str): queueurls = [] #list with the urls vc = ctx.voice_client if not vc: channel = ctx.author.voice.channel await channel.connect() url = ctx.message.content url = ttourl(url) #the message is processed to an url queueurls.append(url) #add the url to the list voicec = ctx.voice_client if not voicec.is_playing(): #when nothing is going on while queueurls != []: #as long as the url list isn't empty I want the process to repeat voice = discord.utils.get(bot.voice_clients, guild=ctx.guild) url = queueurls[0] #url is the first item in the list queueurls.pop(0) #now erase the now used first item (url) with youtube_dl.YoutubeDL(ytdlopts) as ydl: ydl.download([url]) #download the song voice.play(discord.FFmpegPCMAudio(&quot;songstemp/song.mp3&quot;)) #play the song vcs = ctx.voice_client while vcs.is_playing: #wait for the song to be over continue if os.path.exists(&quot;songstemp/song.mp3&quot;): path = &quot;songstemp/song.mp3&quot; os.remove(path) else: #if the bot is already playing, then don't disturb the loops above pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:30:21.220", "Id": "514478", "Score": "0", "body": "Please can you include the entire traceback for the error you're getting. Having the traceback can help us identify the issue and increases the potential for you to get you the feedback you want." } ]
[ { "body": "<ul>\n<li>Prefer four-space indentation instead of a mix of four and two</li>\n<li><code>queueurls</code> should be <code>queue_urls</code></li>\n<li><code>else / pass</code> is redundant and can be deleted</li>\n<li>It's not a great idea to use a single, statically-named temporary file for your playback. Instead, use <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">tempfile</a> to generate you a random one-off temporary filename. It's possible that the inefficiency you see is actually some kind of contention around your single filename.</li>\n<li><code>while queueurls != []</code> is better-stated as <code>while len(queue_urls) &gt; 0</code>.</li>\n<li><code>while vcs.is_playing</code> is a polling loop that's probably going to saturate your CPU. At the least, add a <code>sleep(0.1)</code> to the inside of your loop to release your thread from the OS scheduler. Better yet would be a blocking call to your audio library, though I don't know whether that's possible. Based on <a href=\"https://discordpy.readthedocs.io/en/stable/api.html#discord.VoiceClient.play\" rel=\"nofollow noreferrer\">the documentation</a>, you could wait until an <code>after</code> finalizer hook is called.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T21:07:35.080", "Id": "260676", "ParentId": "260653", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T14:05:40.827", "Id": "260653", "Score": "1", "Tags": [ "python", "discord" ], "Title": "Very slow Discord bot to play music" }
260653
<p>Im fairly <strong>new to Golang</strong> and I appreciate any feedback about how to make the code cleaner.</p> <p>The code is called by <code>go-routine</code> and should update status (fail/success etc) of several installation process.</p> <pre><code>package avss import ( &quot;context&quot; &quot;sync&quot; &quot;helm.sh/helm/v3/pkg/release&quot; &quot;sigs.k8s.io/controller-runtime/pkg/client&quot; avmv1alpha1 &quot;github.vmp/avs/api/v1alpha1&quot; ) func GetUpdateStatus(ctx context.Context, log logr.Logger, cr client.Object, status *avmv1alpha1.ComponentStatusWithAggregation, statusClient client.StatusClient) func(chartStatus *avmv1alpha1.InstallStatus) error { var conditionMutex sync.Mutex return func(chartStatus *avmv1alpha1.InstallStatus) error { // prevent status update by subroutines at the same time, lock the access to prevent concurrent modification conditionMutex.Lock() defer conditionMutex.Unlock() status.ChartStatus = updateStatus(chartStatus, status.ChartStatus) status.Status = overallStatus(status.ChartStatus) err := statusClient.Status().Update(ctx, cr) return err } } func overallStatus(chartsStatus []avmv1alpha1.InstallStatus) string { overallStatus := &quot;&quot; for _, status := range chartsStatus { switch status.ReleaseStatus { case release.StatusFailed.String(): overallStatus = &quot;error&quot; case release.StatusDeployed.String(): if overallStatus == &quot;&quot; { overallStatus = &quot;installed&quot; } default: if overallStatus != release.StatusFailed.String() { overallStatus = &quot;reconcile&quot; } } } return overallStatus } func updateStatus(newStatus *avmv1alpha1.ChartStatus, cStatus []avmv1alpha1.InstallStatus) []avmv1alpha1.ChartStatus { found := false for i, status := range cStatus { if status.Name == newStatus.Name { found = true cStatus[i] = *newStatus } } if !found { cStatus = append(cStatus, *newStatus) } return cStatus } </code></pre> <p><a href="https://play.golang.org/p/9C8xGV2116O" rel="nofollow noreferrer">https://play.golang.org/p/9C8xGV2116O</a></p> <p><em>The code is working</em>! however, I guess it can be <em><strong>improved</strong></em> as this is my first Go program which should be <em><strong>run in production</strong></em> :-)</p> <p>If the code is perfect, please let me know</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T13:43:56.427", "Id": "515019", "Score": "0", "body": "I think it is proper.. changes that could be made are (\"installed\" or \"reconcile\" -> if this value is being used elsewhere I would suggest you define them as constants in a common go file like params.go)" } ]
[ { "body": "<p>Overall this looks like a pretty sensible file. Some minor points you might want to consider follow.</p>\n<h3>Imports</h3>\n<p><code>logr</code> is not imported in the file. I presume this is <a href=\"https://github.com/go-logr/logr\" rel=\"nofollow noreferrer\">https://github.com/go-logr/logr</a>. It's passed into the first function but not used. Perhaps remove it from the signature?</p>\n<h3>Discrete strings</h3>\n<p><code>overallStatus</code> returns one of four strings. You could define these strings as constants <a href=\"https://codereview.stackexchange.com/questions/260654/golang-keep-installation-status-for-multiple-installations-process#comment515019_260654\">like Siva mentioned</a>. A step further is to introduce a type that groups these strings together. This</p>\n<ul>\n<li>ensures the function returns one of the strings defined, and</li>\n<li>makes it clear what strings can be returned from the function by looking at the signature.</li>\n</ul>\n<pre class=\"lang-golang prettyprint-override\"><code>type status string\n\nconst (\n statusUnknown status = &quot;&quot;\n statusError status = &quot;error&quot;\n statusInstalled status = &quot;installed&quot;\n statusReconcile status = &quot;reconcile&quot;\n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-21T15:14:33.767", "Id": "261040", "ParentId": "260654", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T14:25:56.907", "Id": "260654", "Score": "4", "Tags": [ "beginner", "go" ], "Title": "Golang keep installation status for multiple installations process" }
260654
<p>I have a situation where I've used the strategy pattern but got many different strategies that are available to the client code that needs to select the appropriate strategy, this is because there's a lot of different usages to the strategy depending on the machine that's being calculated, because of the domain it's being used in.</p> <p>My question is specifically about the filter part of the code, the part where a relevant strategy is picked, I decide to filter first on the location, then the main category of the machine object and then the MachineName (an enum). These can all influence what kind of calculation can be done.</p> <p>A machine object looks like this (other parts removed for brevity):</p> <pre><code>public class Machine() { public Category MainCategory { get; set; } public MachineName MachineName { get; set; } public Location MachineLocation {get; set; } } </code></pre> <p>My filter code for the client part looks like this, note that there are around 30-35 options in total based on either the MachineName or the machine location (first in line for example).</p> <pre><code>public void BasicFilter(Machine Current_Machine) { if(Current_Machine.MachineLocation == 1) { _strategyService.SetStrategy(new FirstMachineStrategy);} else if ( Current_Machine.MainCategory == MainCategory.Producer) { switch (Current_Machine.MachineName) { case MachineName.MultiRoller: _strategyService.SetStrategy(new MultiRollerStrategy); // Other options removed for brevity default: _strategyService.SetStrategy(new RollerStrategy); } } else if ( Current_Machine.MainCategory == MainCategory.Reciever) { _strategyService.SetStrategy(new RecieverStrategy); } } </code></pre> <p>For completeness sake; I've also added a strategy as an example, again this differs on the location, name, or category. Where the strategy below is one of the default one(s)</p> <pre><code>public class RollerStrategy : ICalculationStrategy { public object CalculateSteelValues(Machine Current_Machine, Machine Last_Machine) { Current_Machine.SteelAmount = Last_Machine.SteelAmount; if (Current_Machine.Reduction == 0) { // Can't divide through 0. So do nothing } else { Current_Machine.SteelThickness = Last_Machine.SteelThickness / Current_Machine.Reduction; Current_Machine.SteelWidth = Last_Machine.SteelWidth + Last_Machine.SteelThickness - Current_Machine.SteelThickness; } return Current_Machine; } </code></pre> <p>Is there a better implementation for filtering the different strategies, or something that would be cleaner to maintain, I didn't use a singular switch case statement on the name because I thought it would clutter and I'd need to find another solution for the location(s).</p> <p>I've just recently started to use this pattern, so I was wondering if I was missing something.</p> <p>EDIT:</p> <p>The machine enums are nothing more than it's the exact name; here's a sample of the Enum's used:</p> <pre><code> public enum MachineName { MultiRoller, TwoRoller, // Etc } public enum Category { Blank, Roller, Infeed, } public enum Location { Blank, FirstInLine, LastInLine, } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T16:08:23.913", "Id": "514481", "Score": "3", "body": "Do not prefix your variable names with the class name. `machine.Name` is plenty clear, `machine.MachineName` is overkill. Also, `MachineName` doesn't seem to be a name but a type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T06:51:33.893", "Id": "514523", "Score": "1", "body": "I'm confused. In the text you are saying *filter first on the main category, then the machine name and if needed the location* then in your code the first line examines the location. Could you please sync your code and the text?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T07:09:43.313", "Id": "514524", "Score": "0", "body": "Please also share with us the definitions of the enums." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T11:48:03.900", "Id": "514606", "Score": "1", "body": "Code reviews are different from debugging, the more code you provide the better the review we can do. A statement in the question such as `A machine object looks like this (other parts removed for brevity):` means that we really can't do a good code review and that perhaps you aren't really looking for a code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T13:23:36.090", "Id": "514608", "Score": "0", "body": "Providing the entire Machine object is of no issue; I just thought that it wasn't relevant for this particular part of code hence why I indeed removed it" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T14:40:53.193", "Id": "260656", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "Filtering what strategy to use in strategy pattern" }
260656
<p>As you may know, C++20 has added <code>std::atomic&lt;std::shared_ptr&lt;T&gt;&gt;</code> specialization to the standard, but sadly, most compilers have not implemented it yet. So I decided to implement it myself.</p> <p>I want to know if I can improve this code or not. In addition, I'm not sure if my implementations of <code>wait()</code>, <code>notify_one()</code> and <code>notify_all()</code> are correct using condition variable.</p> <pre><code>#include &lt;atomic&gt; #include &lt;memory&gt; #include &lt;condition_variable&gt; #include &lt;thread&gt; #include &lt;version&gt; #if !defined(__cpp_lib_atomic_shared_ptr) || (__cpp_lib_atomic_shared_ptr == 0) namespace std { template&lt;typename T&gt; struct atomic&lt;shared_ptr&lt;T&gt;&gt; { using value_type = shared_ptr&lt;T&gt;; static constexpr bool is_always_lock_free = false; bool is_lock_free() const noexcept { return false; } constexpr atomic() noexcept {}; atomic(shared_ptr&lt;T&gt; desired) noexcept : ptr_(std::move(desired)) {}; atomic(const atomic&amp;) = delete; void operator=(const atomic&amp;) = delete; void store(shared_ptr&lt;T&gt; desired, memory_order order = memory_order::seq_cst) noexcept { std::lock_guard&lt;std::mutex&gt; lk(cv_m_); atomic_store_explicit(&amp;ptr_, std::move(desired), order); } void operator=(shared_ptr&lt;T&gt; desired) noexcept { store(std::move(desired)); } shared_ptr&lt;T&gt; load(memory_order order = memory_order::seq_cst) const noexcept { return atomic_load_explicit(&amp;ptr_, order); } operator shared_ptr&lt;T&gt;() const noexcept { return load(); } shared_ptr&lt;T&gt; exchange(shared_ptr&lt;T&gt; desired, memory_order order = memory_order::seq_cst) noexcept { return atomic_exchange_explicit(&amp;ptr_, std::move(desired), order); } bool compare_exchange_weak(shared_ptr&lt;T&gt;&amp; expected, shared_ptr&lt;T&gt; desired, memory_order success, memory_order failure) noexcept { return atomic_compare_exchange_weak_explicit(&amp;ptr_, &amp;expected, std::move(desired), success, failure); } bool compare_exchange_strong(shared_ptr&lt;T&gt;&amp; expected, shared_ptr&lt;T&gt; desired, memory_order success, memory_order failure) noexcept { return atomic_compare_exchange_strong_explicit(&amp;ptr_, &amp;expected, std::move(desired), success, failure); } bool compare_exchange_weak(shared_ptr&lt;T&gt;&amp; expected, shared_ptr&lt;T&gt; desired, memory_order order = memory_order::seq_cst) noexcept { return compare_exchange_weak(expected, std::move(desired), order, convert_order(order)); } bool compare_exchange_strong(shared_ptr&lt;T&gt;&amp; expected, shared_ptr&lt;T&gt; desired, memory_order order = memory_order::seq_cst) noexcept { return compare_exchange_strong(expected, std::move(desired), order, convert_order(order)); } void wait(shared_ptr&lt;T&gt; old, memory_order order = memory_order::seq_cst) const noexcept { std::unique_lock&lt;std::mutex&gt; lk(cv_m_); cv_.wait(lk, [&amp;]{ return !(load(order) == old); }); } void notify_one() noexcept { cv_.notify_one(); } void notify_all() noexcept { cv_.notify_all(); } private: shared_ptr&lt;T&gt; ptr_; mutable std::condition_variable cv_; mutable std::mutex cv_m_; constexpr memory_order convert_order(memory_order order) { switch(order) { case std::memory_order_acq_rel: return std::memory_order_acquire; case std::memory_order_release: return std::memory_order_relaxed; default: return order; } } }; } #endif int main() { std::atomic&lt;std::shared_ptr&lt;int&gt;&gt; a; } </code></pre> <p>I will be happy about your suggestions. Thanks in advance.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T15:07:57.810", "Id": "260658", "Score": "5", "Tags": [ "c++", "pointers", "atomic" ], "Title": "Implementation of std::atomic<std::shared_ptr<T>> for C++20" }
260658