body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Recently I'm interested in the Tower of Hanoi problem. The simplest solution is probably the recursive one but I'm trying to challenge myself by solving it iteratively. After observing the pattern of Tower of Hanoi position sequence I came up with this:</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>function count (disk, step) { let temp = Math.ceil( (step + (disk % 2 === 1 ? 2 ** (disk + 2) : 0) - 2 ** disk + 1) / (2 ** (disk + 1)) ) % 3; return disk % 2 === 1 ? 2 - temp : temp; } function solve (diskCount) { const trackDiskPosition = Array(diskCount).fill(0); for (let stepCount = 0; stepCount &lt; 2 ** diskCount; ++ stepCount) { for (let currentDisk = 0; currentDisk &lt; diskCount; ++ currentDisk) { const expectedPosition = count(currentDisk, stepCount); if (trackDiskPosition[currentDisk] !== expectedPosition) { console.log(`Move disk ${currentDisk + 1} from ${trackDiskPosition[currentDisk] + 1} to ${expectedPosition + 1}`); trackDiskPosition[currentDisk] = expectedPosition; break; } } } } solve(4);</code></pre> </div> </div> </p> <p>Currently my solution have a limitation such that it can't specify the final tower position all of the disk should be inside (since I have no idea if I can implement it yet, I'll probably ask for help on StackOverflow).</p> <ul> <li>Performance: I did not check my code performance against other solution so I'm interested (either in Javascript or other languages).</li> <li>Simplification: the <code>count</code> function looks complex and it uses a lots of power operation and a probably unnecessary <code>Math.ceil</code> function. Is there a way to make <code>count</code> run faster (either by reducing the overall power operation, removing <code>Math.ceil</code> completely or simplify the function)? There's also the <code>solve</code> function which have O(n^2) complexity. Can I reduce that to either O(log n) or even O(n), is that possible?</li> <li>Formatting: since using tab is much better than pressing space 4 times so I guess :). Other than that is there any other problem?</li> <li>Other: is there any other problem that I overlooked?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T04:24:24.010", "Id": "268892", "Score": "0", "Tags": [ "javascript", "programming-challenge" ], "Title": "Iterative solution for Tower of Hanoi challenge" }
268892
<p>I've a list of strings and a list of regular expressions. I need to categorize each string to get what type of string it is based on regex.</p> <p>This is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const caseARegex = /^[\s]*[0-9]{4}[\s]*-[\s]*[0-9]{4}[\s]*$/gi; const caseBRegex = /^[\s]*[0-9]{4}[\s]*-[\s]*$/gi; const caseCRegex_1 = /^[\s]*-[\s]*[0-9]{4}[\s]*$/gi; const caseCRegex_2 = /^(until)[\s]*[0-9]{4}[\s]*$/gi; const caseDRegex_1 = /^(by|before)[\s]*[0-9]{4}[\s]*[-]*[\s]*$/gi; const caseDRegex_2 = /^[\s]*-[\s]*still[\s]*in[\s]*[0-9]{4}[\s]*$/gi; const caseERegex = /^(by|probably)[\s]*[0-9]{4}[\s]*-[\s]*[0-9]{4}[\s]*$/gi; const caseFRegex = /^[\s]*[0-9]{4}[\s]*-[\s]*(still in|probably)[\s]*[0-9]{4}[\s]*$/gi; const labelsWithCase = [ "1968 - 1970", "1868 -", "- 1868", "until 1868", "by 1968", "by 1968 -", "before 1868", "- still in 1868", "by 1868 - 1870", "probably 1868 - 1870", "1868 - still in 1870", "1868 - probably 1870" ].map((l) =&gt; computeInfo(l)); console.log(labelsWithCase); function computeInfo(label) { if (caseARegex.test(label)) { return { case: "a", start: 0, end: 0 }; } else if (caseBRegex.test(label)) { return { case: "b", start: 0, end: 0 }; } else if (caseCRegex_1.test(label) || caseCRegex_2.test(label)) { return { case: "c", start: 0, end: 0 }; } else if (caseDRegex_1.test(label) || caseDRegex_2.test(label)) { return { case: "d", start: 0, end: 0 }; } else if (caseERegex.test(label)) { return { case: "e", start: 0, end: 0 }; } else if (caseFRegex.test(label)) { return { case: "f", start: 0, end: 0 }; } else { console.error(`Something goes wrong.`); return {}; } }</code></pre> </div> </div> </p> <p>Is there a better way to do that? Consider that I could have more and more strings and regex.</p>
[]
[ { "body": "<p>What I think is wrong in your code :</p>\n<ul>\n<li>Instead of assigning one variable name per Regex, put them all in an Array, or an Object. An Object makes sense here, because you want to associate regexes to letters.</li>\n<li><code>if() else if () else if()</code> is cumbersome to read and maintain. Instead, it's easier to loop over your regexes, and return the result whenever you find a match. Listing the regexes one by one require 2N lines of code (50 lines for 25 regexes), whereas looping is only the same two or three lines, no matter how many regexes you're going through.</li>\n</ul>\n<p>I'd do it this way. Create a regex store, in which each letter can be associated with one or multiple regexes. Then, apply <code>array.some()</code> to detect if one of the regexes is a match, and return the corresponding letter.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const regexesStore = {\n a: [/^[\\s]*[0-9]{4}[\\s]*-[\\s]*[0-9]{4}[\\s]*$/gi],\n b: [/^[\\s]*[0-9]{4}[\\s]*-[\\s]*$/gi],\n c: [/^[\\s]*-[\\s]*[0-9]{4}[\\s]*$/gi, /^(until)[\\s]*[0-9]{4}[\\s]*$/gi],\n d: [/^(by|before)[\\s]*[0-9]{4}[\\s]*[-]*[\\s]*$/gi, /^[\\s]*-[\\s]*still[\\s]*in[\\s]*[0-9]{4}[\\s]*$/gi],\n e: [/^(by|probably)[\\s]*[0-9]{4}[\\s]*-[\\s]*[0-9]{4}[\\s]*$/gi],\n f: [/^[\\s]*[0-9]{4}[\\s]*-[\\s]*(still in|probably)[\\s]*[0-9]{4}[\\s]*$/gi],\n}\n\nconst computeInfo = label =&gt; {\n for (let [letter, regexes] of Object.entries(regexesStore)) {\n if (regexes.some(regex =&gt; regex.test(label))) return { case: letter, start: 0, end: 0 };\n }\n return {};\n}\n\nconst labelsWithCase = [\"1968 - 1970\", \"1868 -\", \"- 1868\", \"until 1868\", \"by 1968\", \"by 1968 -\", \"before 1868\", \"- still in 1868\", \"by 1868 - 1870\", \"probably 1868 - 1870\", \"1868 - still in 1870\", \"1868 - probably 1870\"].map(computeInfo);\n\nconsole.log(labelsWithCase);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T07:57:48.677", "Id": "530379", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T08:02:43.687", "Id": "530380", "Score": "0", "body": "OK thanks, will read and try to improve. I'm very much used to Stackoverflow, not yet to Codereview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T08:42:55.257", "Id": "530381", "Score": "0", "body": "That means that you might benefit from [A guide to Code Review for Stack Overflow users](https://codereview.meta.stackexchange.com/q/5777/75307). That's quite a good summary of the differences between the sites. Your answer already looks much better - thank you for improving it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T08:43:44.310", "Id": "530382", "Score": "0", "body": "You're full of resources :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T06:58:59.227", "Id": "268894", "ParentId": "268893", "Score": "3" } }, { "body": "<p>You want a code that can scale as the incoming data increases... First of all, don't make a mess of <code>if</code> and <code>else</code> statements. It is painful to read and to code.</p>\n<p>There are few browsers which don't support the <code>let</code> and <code>of</code> keywords, it really is a pain but one such example is Opera Mini.</p>\n<p><strong>Who uses Opera Mini?</strong>\nFirst of all, even if there are 2 users of Opera Mini in the world, we as web-developers need make the web accessible to them. But there are still 260 million users present for Opera Mini, as per Google and Opera themselves.</p>\n<p>And to take it even a step further, people still use <strong>internet explorer</strong>... I am stupefied too.</p>\n<p>So lets make web accessible for them... I hate this, but we have no choice its about moral code.</p>\n<h2>What's wrong with your code</h2>\n<p><strong>First:</strong> Too many <code>if</code> and <code>else</code> statements.</p>\n<p><strong>Second:</strong> Non scalable structure... You must not declare so many regex expressions globally.</p>\n<p><strong>Finally:</strong> This is not a malpractice but please don't return empty objects.</p>\n<p>Also please try not to map a list by overwriting its contents, you won't be able to recover it once it is gone. This might lead to few unknown bugs later along the lines.</p>\n<h2>What you should do?</h2>\n<p>Using your logic you need a list of regex expressions and a list of labels... Then you want to map the labels with a matching regex case.</p>\n<p>Here is what I came up with...</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// --- This is your regex list which follows the format given below --- //\n// -------- regexStockList = { case: name, regex: expression } -------- //\n\nconst regexStockList = [];\n\n// ----------- This is your label list ------------ //\n// --- Here you can add labels you want to test --- //\nconst labels = [];\n\n// --- Here is a function to add new regex expressions --- //\nfunction addNewRegexStock(caseLabel, expression) {\n regexStockList.push({\n case: caseLabel,\n regex: expression\n });\n}\n\n// --- This function can be used to add new labels --- //\nfunction addNewLabel(label) {\n labels.push(label);\n}\n\n// --- Your original mapping function --- //\nfunction computeInfo(label) {\n for (var stockNumber in regexStockList) {\n if (regexStockList[stockNumber].regex.test(label)) {\n return {\n case: regexStockList[stockNumber].case,\n label: label,\n start: 0,\n end: 0,\n };\n }\n }\n return {\n case: \"no match\",\n label: label,\n start: 0,\n end: 0,\n };\n}\n\n// --- Adding your regex expression here --- //\n// ---- You can use a for loop for this ---- //\naddNewRegexStock(\"a\", /^[\\s]*[0-9]{4}[\\s]*-[\\s]*[0-9]{4}[\\s]*$/gi);\naddNewRegexStock(\"b\", /^[\\s]*[0-9]{4}[\\s]*-[\\s]*$/gi);\naddNewRegexStock(\"c-1\", /^[\\s]*-[\\s]*[0-9]{4}[\\s]*$/gi);\naddNewRegexStock(\"c-2\", /^(until)[\\s]*[0-9]{4}[\\s]*$/gi);\naddNewRegexStock(\"d-1\", /^(by|before)[\\s]*[0-9]{4}[\\s]*[-]*[\\s]*$/gi);\naddNewRegexStock(\"d-2\", /^[\\s]*-[\\s]*still[\\s]*in[\\s]*[0-9]{4}[\\s]*$/gi);\naddNewRegexStock(\"e\", /^(by|probably)[\\s]*[0-9]{4}[\\s]*-[\\s]*[0-9]{4}[\\s]*$/gi);\naddNewRegexStock(\"f\", /^[\\s]*[0-9]{4}[\\s]*-[\\s]*(still in|probably)[\\s]*[0-9]{4}[\\s]*$/gi);\n\n\n// ----- Adding the label ----- //\n// --- Use a for loop later --- //\naddNewLabel(\"1968 - 1970\");\naddNewLabel(\"1868 -\");\naddNewLabel(\"- 1868\");\naddNewLabel(\"until 1868\");\naddNewLabel(\"by 1968\");\naddNewLabel(\"by 1968 -\");\naddNewLabel(\"before 1868\");\naddNewLabel(\"- still in 1868\");\naddNewLabel(\"by 1868 - 1870\");\naddNewLabel(\"probably 1868 - 1870\");\naddNewLabel(\"1868 - still in 1870\");\naddNewLabel(\"1868 - probably 1870\");\n\n\n// --- With this function you can get a map of your label cases --- //\nfunction getMappedLabelsWithCases() {\n var labelWithCases = []\n for (var labelNumber in labels) {\n labelWithCases.push(computeInfo(labels[labelNumber]));\n }\n return labelWithCases;\n}\n\nconsole.log(getMappedLabelsWithCases())</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>As you can see... This code will scale pretty well for your case</p>\n<p>I also think you got support for Opera Mini and internet explorer with this code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T11:09:50.747", "Id": "268900", "ParentId": "268893", "Score": "0" } } ]
{ "AcceptedAnswerId": "268894", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T06:30:18.143", "Id": "268893", "Score": "0", "Tags": [ "javascript", "regex" ], "Title": "Test strings with a lot of regular expressions" }
268893
<p>I'm trying to sort a <code>Sector</code> array and a <code>Province</code> array based on the language.</p> <p><code>sector.ts</code>:</p> <pre><code>export interface Sector { id: string; Label_FR: string; Label_NL: string; } </code></pre> <p><code>province.ts</code>:</p> <pre><code>export interface Province { id: string; frenchName: string; dutchName: string; } </code></pre> <pre><code>constructor( private readonly _translateService: TranslateService, private statisticsManager: StatisticsManager) { let currentLang = _translateService.currentLang; // 'fr' / 'nl' statisticsManager.sectors$.pipe(takeUntil(this.onDestroy$)) .subscribe((sector: Sector[]) =&gt; (this.sectorOptions = sector)); statisticsManager.provinces$.pipe(takeUntil(this.onDestroy$)) .subscribe((province: Province[]) =&gt; (this.provinceOptions = province)); this._translateService.onLangChange.subscribe(() =&gt; { this.sortFilters(); }) } sortFilters() { let currentLang = this._translateService.currentLang; this.sectorOptions = this.sectorOptions.sort((a, b) =&gt; { if (currentLang == 'fr') { return this.sortFunc(a.Label_FR, b.Label_FR); } else { return this.sortFunc(a.Label_NL, b.Label_NL); } }); this.provinceOptions = this.provinceOptions.sort((a, b) =&gt; { if (currentLang == 'fr') { return this.sortFunc(a.frenchName, b.frenchName); } else { return this.sortFunc(a.dutchName, b.dutchName); } }); } sortFunc(obj1: any, obj2: any) { if (obj1 &gt; obj2) { return 1; } else if (obj1 &lt; obj2) { return -1; } else { return 0; } } </code></pre> <p>The code does the job but is really 'long' for that kind of task, is there any short / optimisation to achieve the same result?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T09:29:38.283", "Id": "530472", "Score": "2", "body": "Have you considered [`localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) for `sortFunc` implementation?" } ]
[ { "body": "<p>The constructor should mostly just be used for injection:</p>\n<pre class=\"lang-js prettyprint-override\"><code>currentLang: string // Declare members above constructor\n\nconstructor(\n private readonly _translateService: TranslateService,\n private statisticsManager: StatisticsManager\n) { }\n</code></pre>\n<p>Initialization should go in <code>ngOnInit</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>ngOnInit(): void {\n this.currentLang = this._translateService.currentLang;\n}\n</code></pre>\n<p>I also prefer to declare any Observables above the constructor:</p>\n<pre class=\"lang-js prettyprint-override\"><code>sector$ : Observable&lt;Sector[]&gt; = this.statisticsManager.sectors$\nprovinces$ : Observable&lt;Province[]&gt; = this.statisticsManager.provinces$\n</code></pre>\n<p>And in the template we can then use an async pipe on them, e.g.:</p>\n<pre class=\"lang-html prettyprint-override\"><code>*ngFor=&quot;let sector of sort((sector$ | async)!)&quot;\n</code></pre>\n<p>And for the sort function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>sortSectors(sectors: Sector[]) {\n let currentLangProperty = getCurentLangProvinceProperty()\n return sectors?.sort(\n (a, b) =&gt; (a as any)[currentLangProperty].toLocaleLowerCase().localeCompare((b as any)[currentLangProperty].toLocaleLowerCase())\n )\n}\n\nsortProvinces(provinces: Province[]) {\n let currentLangProperty = getCurentLangProvinceProperty()\n return provinces?.sort(\n (a, b) =&gt; (a as any)[currentLangProperty].toLocaleLowerCase().localeCompare((b as any)[currentLangProperty].toLocaleLowerCase())\n )\n}\n\ngetCurrentLangSectorProperty(){\n return 'Label_' + this._translateService.currentLang.toUpperCase()\n}\n\ngetCurrentLangProvinceProperty(){\n return this.currentLang === 'fr' ? 'frenchName' : 'dutchName'\n}\n</code></pre>\n<p><em>You might be able to further generify this by using <strong>toBeSorted: Sector[] | Province[]</strong> as parameter.</em></p>\n<p>This way, you can use the OnPush ChangeDetectionStrategy:</p>\n<pre class=\"lang-js prettyprint-override\"><code>@Component({\n changeDetection: ChangeDetectionStrategy.OnPush,\n // ...\n})\n</code></pre>\n<p>You can be sure that subscriptions are handled automatically, and don't need an <code>onDestroy</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T12:35:15.227", "Id": "269129", "ParentId": "268895", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T07:25:37.810", "Id": "268895", "Score": "1", "Tags": [ "typescript", "angular-2+" ], "Title": "Sort an object array with two variable based on the language" }
268895
<pre><code> r←n optimal img;bmp;bin;rgb ;i;p;v;b;euclid;most ;m;⎕IO ⍝ compute optimal palette ⍝ it is recomended using ⍝ a shrinked image ⎕IO←0 r←⍬ ⍝ 12996=114*2=(⌊0.45×255)*2, 0.45 is the threshold constant from the paper. euclid←{∧/12996≤+⌿×⍨r(-⍤1 0⍤¯1)⍥((3⍴256)∘⊤)⍵} most←(((⊢⍳⌈/)⊢/)⌷⊣/){⍺(+/⍵)}⌸ ⍝ 16*3 binning map, instead of 10*3 bins used in the paper. bmp←16⊥⌊img÷16 p←,rgb←256⊥img ⍝ vote i←0 :Repeat v←euclid rgb ⍝ count bins b←bmp most⍥,v r,←p[⊃⍒,(⊢×{+/,⍵}⌺21 21)bmp=b] i+←1 :Until i=n ⍝ User has to specify the number of colors. ⍝ fin, translate the compressed palette r←(3 1,≢r)⍴(3⍴256)⊤r </code></pre> <p>The above APL code is an altered implementation of <a href="https://v-sense.scss.tcd.ie/wp-content/uploads/2018/09/IMVIP18_palette.pdf" rel="nofollow noreferrer">https://v-sense.scss.tcd.ie/wp-content/uploads/2018/09/IMVIP18_palette.pdf</a></p> <p>The input is an array of <code>3 Y X</code> describes the RGB image of size <code>X×Y</code>. The output is an array of <code>3 1 X</code> describes the palette of length <code>X</code>. The max value of these arrays are assumed to be 255.</p> <p>I'd like to have comments on APL coding style, performance, and space efficiency.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T07:58:05.147", "Id": "268896", "Score": "4", "Tags": [ "image", "apl" ], "Title": "Compute the optimized palette for RGB image" }
268896
<p>This is a finished project where 2 players each roll 2 dice. If the sum of the number that a player has rolled is even, then 10 is added to their score; if the sum of their 2 rolls isn't even then 5 is subtracted from the player's score. If the player's first role = the second roll, then another roll is done and added to their score. And the end of 5 rounds, whoever has the highest score wins - if necessary, tiebreaker rounds will be conducted in order to determine the winner.</p> <p>After that, the winner's score must be saved in an external file and then the top 5 highest scores are fetched from the file and ordered to form a leaderboard-style message.</p> <p>The code has a substantially high amount of comments because this was my GCSE computer science coursework (NEA) for 2020.</p> <p>As far as I know, this was the last year of the Programming Project (at GCSE-level, that is) which is sad as I believe GCSE students should have some sort of experience with designing and altering a python programme, based on a specification.</p> <p>The code shouldn't be hard to understand due to the amount of comments, lol.</p> <p>My teachers graded this coursework a 9 (A*, on the old UK grading system).</p> <pre class="lang-py prettyprint-override"><code>from random import randint # import the randint function from the random package; can be accessed via randint() from typing import List # support for type annotations (prevents my linter from throwing errors) from time import sleep # import sleep from the time module from operator import itemgetter as ItemGetter # Import the itemgetter module; this makes it easier to manipulate 2 dimensional lists. represents a callable object that fetches the given item(s) from its operand. usernames = ['user', 'admin'] # list of valid usernames; pins = ['2369', '1642'] # list of valid PINS (PIN for usernames[0] is pins[0]); active_players = [] # List of active players, prevents a user from logging in twice under the same username rounds = 0 # int | Number of rounds that have passed, used to ensure only 5 rounds have gone before a winner is determined # Initiate score trackers for both players. player1_score = 0 player2_score = 0 carry_on = True # Whether or not rounds should be ran # Initiate tracker for the winner's name and score winning_player = None winning_score = None tie_breaker = False # Whether tie breaker (tie_breaker) mode is enabled sep = '------------------------------------------' # used as a separator for each round, purely to be aesthetically pleasing class InputMessages: username: str = f&quot;Player $playernum: please enter a valid username: &quot; pin: str = f&quot;Player $playernum: please enter the PIN for $player: &quot; welcome: str = f&quot;\nWelcome $player, you've successfully logged in!&quot; print(&quot;Welcome!\nYou need to be logged in to access this game.&quot;) while len(active_players) &lt; 2: # while the number of usernames in the active_players list is less than 2: # input and validate username: _id = f&quot;(Player {len(active_players) + 1}): &quot; username = str(input(f&quot;{_id}Please enter a valid username: &quot;)).lower() while username in active_players: # if the username is in the active_users list, completely prevent the user from logging in as that user by creating a loop that can only be broken if the user enters a username that is not in this list; print(f'Someone is already logged in by that username!') username = str(input(f&quot;{_id}Please enter a valid username: &quot;)).lower() # re-assign the new inputted value to the username var, allowing the loop to break if the user has entered a valid username (that is not already taken; while not username in usernames: # If a username is not in the usernames list, create a loop which will ask the user to re-input a valid username print(f'A user by that username was not found!') username = str(input(f&quot;{_id}Please enter a valid username: &quot;)).lower() # re-assign to the new inputted value to &quot;username&quot;, allowing the loop to break if the user has entered a username that is not in the active_players list. username_index = usernames.index(username) # Find the &quot;username&quot; that the user has enterd's position in the pins list. This will allow me to check if the pin provided is the CORRECT pin for the user identified; # check pin (relative to the username inputted above) pin = str(input(f&quot;{_id}Please enter the PIN for {username.capitalize()}: &quot;)) # prompt user to input their &quot;pin&quot; (Type: str) while not pins[username_index] == pin: # If the pin for the identified user is incorrect, instantiate a loop asking user to input the correct PIN print(f&quot;Invalid PIN! Please try again&quot;) pin = str(input(f&quot;{_id}Please enter the PIN for {username.capitalize()}: &quot;)) # re-assign the new inputted value so the loop takes the new value into account print(f&quot;{_id}Welcome {username.capitalize()}! You're now logged in.&quot;) active_players.append(username) # Add the username to the end of the active_users list player1 = active_players[0].capitalize() # Assigns the active_players[0] username to the player1 variable, purely for convenience player2 = active_players[1].capitalize() # Assigns the active_players[1] username to the player2 variable, purely for convenience ''' This function will roll a dice and perform the required actions upon the returned value (if even, +10, if odd, -5 etc) param {bool} Tie_breaker: Whether or not tie breaker mode is active ''' def roll(Tie_breaker: bool = False): if Tie_breaker == True: # If the Tie_breaker boolean param is True, only return 1 random int between 1 and 6 (tie breaker mode rules) return randint(1, 6) score = 0 # The final number of points that the &lt;user&gt; has scored. # Generate a random number between 1 and 6 roll1 = randint(1, 6) roll2 = randint(1, 6) roll3 = randint(1, 6) score = roll1 + roll2 # Add together all of the rolls and store them under one variable, making it easier to manipulate; if score % 2 == 0: # Check if the score is an even number; % just divides the number and returns the remainder of the division; # Even number, +10 to the user's score. score += 10 else: score -= 5 # User rolled an odd number; -5 from their score if score &lt; 0: # Checks if the int score is less than 0; if it is, set it to 0 score = 0 if roll1 == roll2: # If roll1 equates to roll2, then add the value of roll3 to the final, total score score += roll3 return score ''' The following function will return either None, 1 or 2 depending on who out of the 2 players now has the highest score param: {int} score1 --&gt; Player 1's Score to take into account; param: {int} score2 --&gt; Player 2's Score to take into account returns: --&gt; 1 IF score1 &gt; score2 --&gt; 2 IF score2 &gt; scrore1 --&gt; None IF score1 == score2 ''' def identify_winner(score1: int, score2: int): if score1 == score2: # If score 1 is equal to score2, it is a draw: return None # elif acts as a shorthand for else if elif score1 &gt; score2: # Player 1 has a higher score than player 2; return 1. return 1 else: # Player 2's score is greater than player 1's score; return 2. return 2 while rounds &lt; 5 or tie_breaker == True and (carry_on == True): # Instantiate a loop: this will continue if the number of rounds (rounds) is less than 5 **OR** if tie breaker (tie_breaker) is set as True **AND** if carry on is as True. Since this part is in parenthesis, this will be checked first rounds += 1 # Increment number of rounds input(f&quot;Press Enter to proceed to round {rounds} &quot;) print(&quot;Rolling Die...&quot;) sleep(0.5) # wait for 1/2 seconds [just to add effect]; print(sep) print(f&quot;Round No: {rounds}&quot;) if tie_breaker != True: # make sure that 2 dice are only rolled if tie breaker mode is not active. # Roll die and perform actions based on the number player1_scored = roll() player2_scored = roll() # Add the amount of points scored to the player who scored them player1_score += player1_scored player2_score += player2_scored else: # If the above condition if False, then we know that tie breaker mode is active. # Call the roll function with the tie_breaker param as True player1_scored = roll(True) player2_scored = roll(True) player1_score += player1_scored player2_scored += player2_scored new_winner = identify_winner(player1_score, player2_score) # Utilise the identify_winner() function and determine a winner by the result of this function; if new_winner == None: # If None is returned, THEN there is a DRAW; winning_player = 'DRAW' # set the winning_player to draw; this will be displayed below; winning_score = player1_score elif new_winner == 1: winning_player = player1 # set the winning player as player1 winning_score = player1_score else: winning_player = player2 # set the winning player as player2 winning_score = player2_score # Utilise the &quot;ternary&quot; (compressded if statements) operator to reduce the hassle of a huge if-elseif-else block. player1_display_gained_points = &quot;did not gain any additional points&quot; if player1_scored == 0 else f&quot;has gained {player1_scored} points&quot; player2_display_gained_points = &quot;did not gain any additional points&quot; if player2_scored == 0 else f&quot;has gained {player2_scored} points&quot; print(f&quot;{player1} {player1_display_gained_points}&quot;) print(f&quot;{player2} {player2_display_gained_points}&quot;) print(sep) print(f''' {player1}'s Score: {player1_score} {player2}'s Score: {player2_score} || Currently Winning Player: {winning_player} (score {winning_score}) {sep} ''') if rounds &gt;= 5: # IF the number of rounds incurred (rounds) is greater than or equal to 5, attempt to determine a winner or start tie breaker; if new_winner != None: # Only attempt to determine a winner if new_winner != None, ensuring that it is NOT a draw print(&quot; WE HAVE A WINNER! &quot;) print(sep) print(f''' {winning_player} has won the game with their score of {winning_score}! ''') # Prevent further rounds from being ran =&gt; carry_on = False else: # Enable tie breaker mode print(&quot;It seems to be a draw; tie breaker mode will now be activated.&quot;) print(&quot;This means that each user will now only have 1 roll each and any odd/even bonuses will not be applied henceforth.&quot;) if tie_breaker != True: tie_breaker = True ''' INTENDED FORMAT FOR EXTERNAL FILE: PlayerName:PlayerScore where PlayerName represents a player's name where PlayerScore represents a player's score - If the external file is manually edited to a format different to this, it will result in the production of error(s) ''' to_w = f&quot;{winning_player}:{winning_score}&quot; # What to write to the external file # Use python with open() to open the file, as target followed by a block of code. # This reduces how cluttery the code is and makes it easier to manage resources, such as file streams as utilised below: # List of all winners, read from ext file and the winner of this game winners = [] # this will be the new content of the external file # This code will prevent the write file to completely wipe it each time; it will create some sort of persistence in regards to data in that file. with open('./winners.txt', 'r') as f: for line in f.readlines(): # for each line in the file: # add the line into the winners list, ensuring \n (newline character) is removed winners.append(line.replace('\n', '')) winners.append(to_w) # add the winner of this game f.close() # close file with open('./winners.txt', 'w') as f: f.write('\n'.join(winners)) # write to the file; f.close() # Close the file after it has been written to. data = [] # This will be the final, formatted, ready-to-sort list for w in winners: # for every value in the winner_cache list: data.append([str(w.split(':')[0]), int(w.split(':')[1])]) # create a new 2d list with the name and the score of the player # Now we sort the data based on the int score # Utilise python slice notation on the returned list --&gt; sorted_data = sorted(data, key = ItemGetter(1), reverse = True)[:5]; # map through the list, converting the end result to a list. msg = list(map(lambda arg: f&quot;{arg[0].capitalize()} ({arg[1]} points)&quot;, sorted_data)) print(f&quot;Top 5 scores:\n(loaded from ./winners.txt)&quot;) printed = 0 # Amount of printed scores # Loop through the printing of each player name and score for x in range(0, len(sorted_data)): printed += 1 print(str(x + 1) + '.', msg[x]) # --&gt; 1. Userz (10 points) # 2. Admin (5 points) # ... # Print that not data is found if no data is found - simply reduces confusion for the End User while printed &lt; 5: # count controlled loop; only run while printed less than (&lt;) 5 printed += 1 print(f'{printed}. -- No Data Found --') </code></pre> <p>Here's the link to the GitHub in case I copied this over wrong - <a href="https://github.com/almostStatic/gcse-cs-nea/blob/main/main.py" rel="noreferrer">GitHub</a></p> <p>Hopefully this has also helped somebody else in the process.</p> <p>Thanks for reading :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T21:36:30.937", "Id": "530528", "Score": "0", "body": "Is the list of valid users public information? If not, you have a security issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:46:40.530", "Id": "530550", "Score": "1", "body": "\"The code shouldn't be hard to understand due to the amount of comments\". This actually makes the code much harder to understand" } ]
[ { "body": "<p>This… … … is a mouthfull. The sheer amount of comments make the code very hard to read as it gets buried under tons upon tons of other information. Most of them being just there to state the obvious of what the line of code is doing. This is not what comments are about. Comments, if any, should state why we went some route or another and explain the rationale of not doing it any other way. They should be here to prevent the reader being caught off-guard by a piece of code that may seem to be overly complicated or otherwise non-obvious.</p>\n<p>You don't need to explain that you're importing a function from a module: we just read the <code>import</code> keyword on the line, so we know that. You don't need to say that you’ll sort a list: you're using <code>sorted</code>, we will figure it out; maybe explain why you need the list sorted instead, or use a better variable name than <code>sorted_data</code> to explain it for you, like <code>leaderboard</code> for instance.</p>\n<p>So clean up the code from the unnecessary, remove the unused bits too (such as the <code>InputMessages</code> class) and it will be much easier to read.</p>\n<h1>Use functions</h1>\n<p>Your code is almost all linear. Even though it works, it makes it hard to think about it in terms of logical units. Defining functions will make it easier to digest and reason about. It will also allows you to define <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstrings</a> that act as documentation and will let you get rid of most of the comments as you can explain the whys of these functions into the docstring themselves.</p>\n<p>Note that docstrings are defined right after the function declaration, not before.</p>\n<p>Using functions will also help get rid of this ugly pile of variable definition at the top. Variables should be defined when you need them, so it's easier to go back and forth between their usage and their initial value, and having functions will help you manage their scope so you only need to care about a few of them at once.</p>\n<p>Lastly, breaking your code into functions will make it easier to test and reuse.</p>\n<h1>Improve your file handling</h1>\n<p>First off, you don't need to <code>close</code> your files manually, as the <code>with</code> block will do it for you.</p>\n<p>Second, to add a line to a file, there is absolutely no need to read it first and write it back entirely. The append mode (<code>mode='a'</code>) is there for exactly this purpose: it opens the file and seeks to the end so any write will happen after existing content.</p>\n<p>And third, the <code>print</code> function can help you write to a file. Note that <code>print</code> can handle any type and help you avoid type conversions all around in your code as well.</p>\n<h1>Handling Data</h1>\n<p>You have two lists to handle your credentials and their order is dependant on each other. That's not the job for two lists; it's more suited to a dictionary.</p>\n<p>Same for the users names and their score: you can store that in a dictionary and be set for the day you want to play at 3 or 5 users at once.</p>\n<p>A lot of your comparisons are unnecessarily complicated and error-prone: <code>if something == True</code> should be written <code>if something:</code> to remove the unwanted repetition and be able to leverage the comparisons of anything in a boolean context if necessary (for example the fact that empty collections evaluate to <code>False</code>).</p>\n<p>Remember that collections are iterable and you can get elements inside of them using a simple <code>for element in collection:</code> rather than using a index and retrieving the elements yourself by hand. Watch the excellent <a href=\"https://www.youtube.com/watch?v=EnSu9hHGq5o\" rel=\"noreferrer\">loop like a native</a> talk for more on the subject.</p>\n<h1>Proposed improvements</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from operator import itemgetter\nfrom random import randint\nfrom time import sleep\n\n# Used as a separator for each round, purely to be aesthetically pleasing\nSEP = '------------------------------------------'\n\nCREDENTIALS = {\n 'user': '2369',\n 'admin': '1642',\n}\n\n\ndef get_logged_on_player(credentials, exclude_players=set()):\n &quot;&quot;&quot;Ask a user for their name and their PIN and return the username\n if successfully authenticated.\n\n This function checks the :credentials: dictionnary for valid usernames\n and ask the players to authenticate using their PIN. Keep asking until\n a valid username and the corresponding PIN are entered by a player.\n\n If a provided username is found in :exclude_players:, this function\n forbids them for logging again.\n &quot;&quot;&quot;\n\n player_id = f&quot;Player {len(exclude_players) + 1}:&quot;\n while True:\n username = input(f&quot;{player_id} Please enter a valid username: &quot;).lower()\n if username in exclude_players:\n print('Someone is already logged in by that username!')\n continue\n if username not in credentials:\n print('A user by that username was not found!')\n continue\n pin = credentials[username]\n pin = input(f&quot;{player_id} Please enter the PIN for {username.capitalize()}: &quot;)\n if pin == credentials[username]:\n print(&quot;Welcome &quot;, username.capitalize(), &quot;! You're now logged in.&quot;, sep='')\n return username\n print(&quot;Invalid PIN! Please try again&quot;)\n\n\ndef roll(tie_breaker: bool=False): \n &quot;&quot;&quot;Roll a dice and perform the required actions\n\n Rules define the following actions:\n - add the first two dice to get the initial amount of points\n - first two dice add up to an even number =&gt; +10 points\n - first two dice add up to an odd number =&gt; -5 points\n - first two dice are equal =&gt; add the value of the third die to the points\n\n If the tie_breaker mode is requested, only return the value of a single die.\n &quot;&quot;&quot;\n\n if tie_breaker:\n return randint(1, 6)\n\n roll1 = randint(1, 6)\n roll2 = randint(1, 6)\n roll3 = randint(1, 6)\n\n score = roll1 + roll2\n score += 10 if score % 2 == 0 else -5\n if roll1 == roll2:\n score += roll3\n\n return max(score, 0)\n\n\ndef display_score(username: str, points: int):\n &quot;&quot;&quot;Pretty prints how much point a user gained in a round&quot;&quot;&quot;\n\n if points &gt; 0:\n print(username, 'has gained', points, 'points')\n else:\n print(username, 'did not gain any additional points')\n\n\ndef play_a_round(players, round_number=None):\n &quot;&quot;&quot;Simulate a round of the dice roll game\n\n Display the scores along the way and a summary of the\n scores so far at the end of the round.\n\n If no :round_number: is provided, simulate a tie-breaking round \n &quot;&quot;&quot;\n\n input(f&quot;Press Enter to proceed to round {round_number or 'tie-breaking'}&quot;)\n print(&quot;Rolling Die...&quot;)\n sleep(0.5) # Cosmetic pause, add dramatic effect\n print(f&quot;{SEP}\\nRound No: {round_number or 'tie-breaking'}&quot;)\n\n for player in players:\n score = roll(bool(round_number))\n display_score(player, score)\n players[player] += score\n\n # Roll our own `max` implementation to search for draws\n # Use the loop to display scores as well\n print(SEP)\n best_score = 0\n best_player = None\n for player, score in players.items():\n print(player, &quot;'s Score: &quot;, score, sep='')\n if score &gt; best_score:\n best_score = score\n best_player = player\n elif score == best_score:\n best_player = None\n\n print(f&quot; || Currently Winning Player: {best_player or 'DRAW'} (score {best_score})\\n{SEP}&quot;)\n return best_player\n\n\ndef play(player_count=2, rounds=5):\n &quot;&quot;&quot;Run several rounds of the dice roll game and return the overall winner&quot;&quot;&quot;\n\n print(&quot;Welcome!\\nYou need to be logged in to access this game.&quot;)\n players = {}\n while len(players) &lt; player_count:\n player = get_logged_on_player(CREDENTIALS, players)\n players[player] = 0\n\n for r in range(rounds):\n winner = play_a_round(players, r + 1)\n\n while winner is None:\n print(&quot;It seems to be a draw; tie breaker mode will now be activated.&quot;)\n print(&quot;This means that each user will now only have 1 roll each and any odd/even bonuses will not be applied henceforth.&quot;)\n winner = play_a_round(players)\n\n score = players[winner]\n print(&quot; WE HAVE A WINNER! &quot;)\n print(f&quot;{SEP}\\n\\n{winner.capitalize()} has won the game with their score of {score}!\\n&quot;)\n\n return winner, score\n\n\ndef save_winner(winner, score, filename='winners.txt'):\n &quot;&quot;&quot;Add a new entry to the provided file with a new winner\n\n Added entry is a single line of the form\n PlayerName:PlayerScore\n &quot;&quot;&quot;\n\n with open(filename, 'a') as f:\n print(winner, score, sep=':', file=f)\n\n\ndef leaderboard(filename='winners.txt', limit=5):\n &quot;&quot;&quot;Read from the provided file and prints the best :limit: players\n\n INTENDED LINE FORMAT FOR EXTERNAL FILE:\n PlayerName:PlayerScore\n\n If the external file is manually edited to a format different to\n this, it will result in the production of error(s).\n &quot;&quot;&quot;\n\n scores = []\n with open(filename) as f:\n for line in f:\n name, score = line.rsplit(':', 1)\n scores.append([name, int(score)])\n\n leaderboard = sorted(scores, key=itemgetter(1), reverse=True)[:limit]\n print(&quot;Top&quot;, limit, &quot;scores (loaded from&quot;, filename, &quot;):&quot;)\n\n for i, (name, score) in enumerate(leaderboard, start=1):\n print(i, &quot;. &quot;, name.capitalize(), &quot; (&quot;, score, &quot; points)&quot;, sep='')\n\n # Add missing entries to always have a display of :limit: items\n for i in range(len(leaderboard), limit):\n print(i + 1, &quot;. -- No Data Found --&quot;, sep='')\n\n\nif __name__ == '__main__':\n winner, score = play()\n save_winner(winner, score)\n leaderboard()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T20:52:32.543", "Id": "530607", "Score": "0", "body": "For that matter, you don't even *need* the third roll unless the first 2 are the same. And there should probably be a completely separate function for tie-breakers, rather than having `roll` do two different things depending on a boolean argument." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T12:31:16.000", "Id": "268905", "ParentId": "268897", "Score": "25" } }, { "body": "<p>You got an excellent grade for this assignment, but there is still room for improvement!</p>\n<h1>Readability</h1>\n<p>First and foremost, you'll learn that code readability is very important, as code is harder to read than to write but is read more often than written, and should be a prime consideration.</p>\n<p>Unfortunately, various factors make your code harder to read than necessary.</p>\n<p>Most of them are covered in the official Python style guide known as <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>. It's good practice to follow it, as it is designed to produce readable code, and it makes most Python code consistent with your own style, and thus easier to read.</p>\n<p>Although I'll point to some specific issues regarding your code, I'd recommend reading it.</p>\n<h2>Use of comments</h2>\n<p>You said:</p>\n<blockquote>\n<p>The code has a substantially high amount of comments because this was my GCSE computer science coursework (NEA) for 2020.</p>\n</blockquote>\n<p>Even with that context, there are <em>a lot</em> of comments, and a lot of them are redundant or out of place, and it adds a lot of unnecessary clutter.</p>\n<p>Take your first line for example:</p>\n<pre><code>from random import randint # import the randint function from the random package; can be accessed via randint()\n</code></pre>\n<p>The first part of the comment is barely parroting the actual code, it even uses the same words (&quot;import&quot;, &quot;from&quot;, &quot;random&quot;, &quot;randint&quot;). It adds no information.</p>\n<p>The second part of the comment is not a code comment, it's a personal note. It would make more sense to keep an annotated version of this code in your class notes than including the notes in the actual code:</p>\n<ol>\n<li>when you'll need to read your notes for future reference, you will have a harder time finding the relevant code and annotation than if you had proper notes structured as class notes</li>\n<li>it clutters the code and makes it unnessessarily harder to review, whether by your teacher who graded it, by yourself in the future if you want to use it as a reference, or by a benevolent reviewer on the internet.</li>\n</ol>\n<p>I'd argue that at least 90% of the comments can be removed, and most of the remainder can be replaced by a more explicit variable name. For example you can simplify this line:</p>\n<pre><code>tie_breaker = False # Whether tie breaker (tie_breaker) mode is enabled \n</code></pre>\n<p>to:</p>\n<pre><code>enable_tie_breaker = False\n</code></pre>\n<p>without losing any information.</p>\n<h2>Vertical whitespace</h2>\n<p>Give your code some space to breathe. There are few blank lines, making it harder to visualize the various logic blocks to read.</p>\n<p>PEP8 recommends 2 empty lines around top-level function definitions, and 1 empty line between logical sections, which you already mostly do.</p>\n<h2>Loooooong lines</h2>\n<p>PEP8 recommends a maximum line length of 80 characters. Some people feel like it's safe to assume no-one will ever read modern code on 1980's terminals and bump this number up a bit, usually to 100 characters.</p>\n<p>You, however, have lines extending to almost 300 characters, and if you exclude comments to 140 characters. This is bad, as it forces to scroll horizontally, which is anti-ergonomic.</p>\n<h2>Naming conventions</h2>\n<p>Once again, PEP8 has an opinion on that. Variables should be <code>snake_case</code>, which you did, and constants should be <code>ALL_CAPS</code>. This allows the reader to immediately identify constants as such, and know not to worry about the value of the constant. Also, use the most descriptive names you can think of, and avoid abbreviations unless they are clear in every context.</p>\n<p>For example <code>print(SEPARATOR)</code> is immediately clear that the printed value is not a result from prior computation, but just a separator. <code>print(sep)</code> is not.</p>\n<h2>Docstrings</h2>\n<p>You documented your functions with docstrings, eg. triple-quoted strings describing their usage. This very good. However, they should be placed <em>after</em> the function definition, not before. Furthermore, PEP8 recommends limiting the line length to 72 characters, as when they are displayed through the <code>help</code> function, they are indented a couple more levels. Example for one of your functions:</p>\n<pre><code>def identify_winner(score1: int, score2: int): \n '''\n The following function will return either None, 1 or 2 depending on\n who out of the 2 players now has the highest score\n param: {int} score1 --&gt; Player 1's Score to take into account\n param: {int} score2 --&gt; Player 2's Score to take into account \n returns: \n --&gt; 1 IF score1 &gt; score2\n --&gt; 2 IF score2 &gt; scrore1\n --&gt; None IF score1 == score2\n '''\n # Do stuff\n</code></pre>\n<h1>Code structure</h1>\n<h2>Global variables</h2>\n<p>You use global variables to keep track of the game state. Global variables are considered bad practice, the main reason is making it hard to keep track of their values (and where these values are acted upon) when following the code logic. You should keep the scope of variables as small as possible.</p>\n<p>Having global constants, however, is acceptable and in fact quite often used, as long as they are clearly identified as constants (see above).</p>\n<h2>Hardcoded values</h2>\n<p>The game is played in 5 rounds. This value is hard-coded, and only found in the line <code>while rounds &lt; 5</code>.</p>\n<p>Say you (or someone else) want to change that number for some reason (maybe the game is too short/long? Maybe you want to test the file I/O without waiting through 5 rounds?), finding where it is in the code is harder than needs be. Make it a named constant at the top of the script.</p>\n<p>Same goes for the <code>0.5</code> used as an argument for <code>sleep</code> or the path to the high score text file.</p>\n<h2>Constant class</h2>\n<p>The <code>InputMessages</code> class exists only to holds a few constant strings. This is very unusual, a dictionary is usually the solution for this use case.</p>\n<p>Although I wouldn't say doing it your way is wrong, a class is overkill as it can do a lot of other things, whereas a dict is specifically designed for holding and accessing key-value pairs, which is what is done here.</p>\n<p>Also, since you're using a data structure (either a dict or a special class) to hold constant strings, you really should put all of your strings there, yet many are baked right in the middle of the code.</p>\n<h2>Separation of concerns / lack of structure</h2>\n<p>Most of your code unroll at the top level, making little use of functions and interleaving actions with different scopes (game logic, user I/O, file I/O).</p>\n<p>I suppose, at first, this makes perfect sense when writing the code, as everything is coded in the order it happens when playing the game: log in, initialize game, say game is about to start, roll, display results...</p>\n<p>However, it hurts readability, reusability, and maintenance. Say you want to change something in the way things are displayed to the player, or I want to review specifically how logging in is handled, or you want to reuse your high score saving logic... We now have to read through the whole code to find the relevant section, then do whatever we want.</p>\n<p>The way to solve this is to:</p>\n<ul>\n<li>use more functions, each abstracting how to do a specific thing, preferably one at a time.</li>\n<li>use classes to group things that belong together</li>\n</ul>\n<p>For a simple game like this, I think I wold have a class for the game logic keeping track of the game state and advance it, and a class for the player.</p>\n<p>You should have very little code left at the top level.</p>\n<p>The code I would write may look something like this:</p>\n<pre><code>def ask_for_input(prompt)\n value = input(prompt)\n # Validate input\n return value\n\n\nclass Player\n '''a player for the dice roll game'''\n \n def __init__(self, name)\n self.name = name\n self.score = 0\n \n @staticmethod\n def from_login(username, pin):\n if [username matches pin]:\n return Player(username)\n return None\n\n\nclass DiceGame\n '''A simple dice game'''\n \n high_score_path = './winners.txt'\n \n def __init__(self, round_number, player_1, player_2):\n self.round_number = round_number\n \n def run(self)\n round = 0\n while round &lt; self.round_number and self.identify_winner() is not None:\n # Main game loop\n self.add_to_high_score(identify_winner())\n self.display_high_scores()\n \n def play_round(self)\n # Do stuff\n \n def display_scores(self)\n # Do stuff\n \n def identify_winner(self)\n # Do stuff\n \n def roll(self):\n # Do stuff\n \n def add_to_high_score(self, player):\n # Do stuff\n \n def display_high_scores(self):\n # Do stuff\n\n\nif __name__ == '__main__':\n ROUND_NUMBER = 5\n \n payers = []\n while len(players) &lt; 2:\n player = Player.from_login(\n ask_for_input('Please enter your username: '),\n ask_for_input('Pease enter your PIN: '))\n if player is not None:\n players.append(player)\n \n game = Game(ROUND_NUMBER, players[0], players[1])\n game.run()\n</code></pre>\n<p>Note how there are only 10 lines of logic left outside of any class. I could now work on each of the aspect of the game one at a time, and come back to any of them later if I'm no longer satisfied with them.</p>\n<p>Also note I included all of these lines after a <code>if __name__ == '__main__':</code> statement. This means they will get executed if you run this script, but not if you <code>import</code> this script from another one, an re-use the game logic in a broader project (for example, a project that lets you play this game or another one).</p>\n<h1>Random things</h1>\n<pre><code>with open('./winners.txt', 'w') as f:\n f.write('\\n'.join(winners))\n f.close() \n</code></pre>\n<p>You don't need the <code>f.close()</code> here, the file is closed automatically at the end of the <code>with</code> statement.</p>\n<hr />\n<p>At one point, you compare a value to <code>None</code> this way: <code>if foo == None</code>.</p>\n<p>The right way of comparing to <code>None</code> is <code>if foo is None</code>. Indeed, for some objects, <code>foo == None</code> may return <code>True</code> although <code>foo is None</code> is <code>False</code>, depending on how the <code>==</code> operator is defined for <code>foo</code>.</p>\n<p>Further reading on the subject on <a href=\"https://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or\">StackOverflow</a></p>\n<hr />\n<pre><code>sorted_data = sorted(data, key = ItemGetter(1), reverse = True)[:5];\n</code></pre>\n<p>Glossing over the extra <code>;</code> at the end of the line, this creates a sorted copy of the list. This is wasteful, as you don't need the unsorted list anymore.</p>\n<p>Instead, you can <code>sort</code> the <code>data</code> list: <code>sort(data, ...)</code></p>\n<hr />\n<p>I hope you do realize that this is not even remotely close to the proper way to handle secrets like a PIN to log in a player. I won't go into detail on how to do that, as I feel it is a requirement for the assignment, but not related to the game <em>per se</em>.</p>\n<h1>Going further</h1>\n<p>If you want, as a further exercise, I can think of a few things to bring this program a little further.</p>\n<p>First of all, I found it frustrating to see the points total score gained in each round, wouldn't it be more exciting to see the outcome of each roll individually?</p>\n<p>Also, overall, this just amounts to an overengineered coin toss, there are no player decision, which is not much fun to play. Maybe you could add a betting mechanic to it, to make it interesting? It also gives the possibility to have a human or computer player.</p>\n<p>Have fun coding!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:10:02.590", "Id": "530621", "Score": "0", "body": "Hello yes I have read your reply - I understand that the sheer number of comments makes it unreadable and I will work on this in the future. In regards with using `f.close()` when in the with block, I knew the with block would automatically close however I needed to show that I knew that we had to close a file after opening it, just to show that I know the method exists.\n\nIn regards to the extra semicolon on the `sorted_data = ...` line, that's my bad - I'm usually coding in JavaScript and semicolons are pretty essential there so it gets in bad habit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:12:55.850", "Id": "530623", "Score": "0", "body": "I totally agree with you in terms of the comments and everything you've said about the structure and logic about the code. At the time of writing the assignment I was really overwhelmed by other subjects too, such as Chemistry etc, and whilst under a certain time frame so it was quite stressful. Also, I have wayyyy more experience in JavaScript/nodejs, and only really used Python for this coursework." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:14:01.740", "Id": "530624", "Score": "0", "body": "I never really knew how to utilise a `class` system in PY and I didn't really know a dict exiisted LOL, from what you've shown me, a dict looks like a JavaScript object (`obj={key:\"value\",key0:\"value0\"}`)`. But I 100% agree with the things you've said, and thank you for providing feedback on this. I'll be sure to take it on further. I was also aware that this is by no means a good way to have someone's PIN stored, it was only really a requirement to have a login system and there was no additional security required." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T13:49:05.430", "Id": "268909", "ParentId": "268897", "Score": "17" } }, { "body": "<p>Something else that you might consider is using a different random number generator than the one in the standard library when you are working with simulations.</p>\n<p>The <a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\">standard library's implementation</a> uses the <a href=\"https://en.wikipedia.org/wiki/Mersenne_Twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a>, which is alright, but <a href=\"https://www.pcg-random.org/\" rel=\"nofollow noreferrer\">it has some drawbacks</a>. Specifically, the statistical properties of the generated output tend to be differentiable from a truly random sequence. This is obviously why it shouldn't be used for cryptographic purposes, but the deviation is significant enough that it can cause problems in things like Monte Carlo simulations.</p>\n<p>This is obviously not a Monte Carlo simulation, but I would recommend getting acquainted with the random number generator in the Numpy library anyways, since it not only outperforms the Mersenne Twister (both statistically and in actual speed), but getting used to using Numpy for numerical python programming is a good idea, since it's pretty much the standard. The generator itself is based on the PCG64 family of random number generators (you can read <a href=\"https://www.pcg-random.org/pdf/hmc-cs-2014-0905.pdf\" rel=\"nofollow noreferrer\">the original paper introducing them here</a>), and instantiating and using the generator isn't too much more involved.</p>\n<p>To obtain random deviates sampled from a uniformly distributed sample space consisting of the integers from 1 to 6, inclusive, simply instantiate the random number generator as follows.</p>\n<pre><code>from numpy.random import default_rng\n\n# Default generator uses PCG64.\nrng = default_rng()\n\n# Simulate a simple dice roll. Note that the endpoint\n# parameter must be explicitly set to True, as the\n# default behavior is to assume a half-open interval\n# which excludes the high point.\ndice_roll = rng.integers(low=1, high=6, endpoint=True)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T08:33:17.320", "Id": "530629", "Score": "0", "body": "Suggesting learning numpy for a simple dice rolling game is overkill" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T08:57:11.663", "Id": "530630", "Score": "0", "body": "@qwr I only suggested using the rng from the numpy random module, although I respectfully disagree that it's overkill. The goal is not overengineering a simple task, but rather using these learning exercises to gain exposure to the standard implementation methodologies and processes used in professional environments, is it not? Although in fairness I do agree that if you literally just wanted a dice game, learning numpy is overkill, although the rng suggestion I think remains valid" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T08:10:22.843", "Id": "268976", "ParentId": "268897", "Score": "1" } } ]
{ "AcceptedAnswerId": "268909", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T08:59:43.357", "Id": "268897", "Score": "9", "Tags": [ "python", "python-3.x", "dice" ], "Title": "Two player dice roll game" }
268897
<p><strong>Intro:</strong> I started working three month ago and i have never used JavaScript before, i don't know what is the best practice in JS and i feel like my code can be improved a lot, so i'm here searching for tips and tricks or other infos who can make my code better.</p> <p><strong>Task:</strong> Take in input a dictionary with all opening time of a shop and return a formatted string.</p> <p><strong>Input:</strong> A dictionary with seven pairs, the key is &quot;openingMon&quot; .. &quot;openingSun&quot;.<br /> Time separated with dash &quot;-&quot; it's the opening time, if there is a &quot;;&quot; in that time is closed.<br /> Note that the input is always a dictionary and always have this keys.</p> <pre><code>openings = { &quot;openingMon&quot; : &quot;08:00 - 12:00 ; 13:00 - 21:00&quot;, &quot;openingTue&quot; : &quot;08:00 - 10:00 ; 16:00 - 20:00&quot;, &quot;openingWed&quot; : &quot;10:00 - 10:00 ; 16:00 - 20:00&quot;, &quot;openingThu&quot; : &quot;08:00 - 14:00 &quot;, &quot;openingFri&quot; : &quot;08:00 - 20:00&quot;, &quot;openingSat&quot; : &quot;&quot;, &quot;openingSun&quot; : &quot;&quot; } </code></pre> <p><strong>Output:</strong> a formatted string with the following rule:</p> <ul> <li>If all value is empty you must return &quot;Missing opening time&quot;.</li> <li>If the value corresponding to the current day of the week is not empty you must return if the shop is open or closed and the closing/opening time.</li> <li>If the value corresponding to the current day of the week is empty but at least another value is not empty you must return that the shop is closed and the opening time of the next day of the week with not empty value.</li> <li>If tomorrow's value is empty you must include the name of the next day with opening time.</li> <li>If the shop is closed for the rest of the day you must return a string like if the current day's value it's empty.</li> </ul> <p>Examples (for the given input):</p> <ul> <li>If it's Sunday return &quot;Closed today - Opening: Tomorrow 08:00&quot;.</li> <li>If it's Saturday return &quot;Closed today - Opening: Monday 08:00&quot;.</li> <li>If it's Thursday and it's 09:00 return &quot;Open now - Closing: 14:00&quot;.</li> <li>If it's Tuesday and it's 11:00 return &quot;Closed now - Opening: 16:00&quot;.</li> <li>If it's Tuesday and it's 21:00 return &quot;Closed today - Opening: Tomorrow 10:00&quot;.</li> <li>If it's Friday and it's 21:00 return &quot;Closed today - Opening: Monday 08:00&quot;.</li> </ul> <p><strong>Solution:</strong></p> <pre><code>// Set the string with the opening information function set_opening(opening_dict) { // Convert from a time string to an int: &quot;08:36&quot; -&gt; 836 let toInt = (x) =&gt; parseInt(x.replace(&quot;:&quot;, &quot;&quot;)); // For using a string of opening time like a list: i = 2, o = &quot;08:30 - 13:00 ; 15:00 - 20:00&quot; -&gt; &quot;15:00&quot; let toList = (i, o = opening) =&gt; o == &quot;&quot; ? o : (o.includes(&quot;;&quot;) ? (o.split(&quot; ; &quot;)[Math.floor(i / 2)]).split(&quot; - &quot;)[i % 2] : o.split(&quot; - &quot;)[i]); // Get opening time based on a day of the week: 2 -&gt; &quot;08:30 - 13:00 ; 15:00 - 20:00&quot; let getOpening = (x) =&gt; opening_dict[&quot;opening&quot; + week_days[x].slice(0, 3)]; // Get last closing time from a string: &quot;08:30 - 13:00 ; 15:00 - 20:00&quot; -&gt; 2000 let getClose = (o = opening) =&gt; o == &quot;&quot; ? 0 : o.includes(&quot;;&quot;) ? toInt(toList(3, o)) : toInt(toList(1, o)); // Get opening time from opening as an int: i = 2, o = &quot;08:30 - 13:00 ; 15:00 - 20:00&quot; -&gt; 1500 let getTime = (i, o = opening) =&gt; o == &quot;&quot; ? 0 : toInt(toList(i, o)); // Check if all value is empty let is_empty = true; for (const value of Object.values(opening_dict)) { is_empty = is_empty &amp;&amp; value == &quot;&quot;; } // If all value is empty there is no openings if (is_empty) { return &quot;Missing opening time&quot;; } let week_days = [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;]; let now = new Date(Date.now()); // Save current time as an int let time_now = now.getHours() + (now.getMinutes() &gt; 9 ? &quot;&quot; : &quot;0&quot;) + now.getMinutes(); // Save the opening time for today (getDay return 0 for sunday and 6 for saturday) let opening = getOpening(now.getDay()); // If today is closed tell next opening day if (opening == &quot;&quot; || time_now &gt;= getClose()) { let next_opening_day = now.getDay() + 1; // Save next opening day while (next_opening_day != now.getDay()) { if (getOpening(next_opening_day) != &quot;&quot;) { break; } // If it's sunday go to monday next_opening_day = (next_opening_day + 1) % 7; } let next_opening = next_opening_day == now.getDay() + 1 ? &quot;Tomorrow&quot; : week_days[next_opening_day]; return `Closed today - Opening: ${next_opening} ${toList(0, getOpening(next_opening_day))}`; } // Check current time and say if it's is open or closed, along with next opening/closing time if (time_now &lt; getTime(0)) { return `Closed now - Opening: ${toList(0)}`; } else if (getTime(0) &lt;= time_now &amp;&amp; time_now &lt; getTime(1)) { return `Open now - Closing: ${toList(1)}`; } // If current openings have four time if (time_now &lt; getTime(2)) { return `Closed now - Opening: ${toList(2)}`; } else if (getTime(2) &lt;= time_now &amp;&amp; time_now &lt; getTime(3)) { return `Open now - Closing: ${toList(3)}`; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T13:42:37.970", "Id": "530408", "Score": "0", "body": "Welcome to the site!! I’m not sure what version of JavaScript you used but I’m getting some errors when running it in Chrome and Node.js [TIO](https://bit.ly/3DyMRVT)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T13:54:49.787", "Id": "530409", "Score": "0", "body": "@JohanduToit what error are you getting? i'm using JavaScript v1.7 and Node.js v12.22.3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T14:21:39.993", "Id": "530411", "Score": "0", "body": "`let getClose = (o = opening) => o == \"\" ? 0 : o.includes(\";\") ? toInt(toList(3, o)) : toInt(toList(1, o));` `TypeError: Cannot read property 'includes' of undefined`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T14:49:14.303", "Id": "530413", "Score": "0", "body": "Perhaps, I'm just doing something stupid, can you perhaps add how you call `set_opening`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T15:12:14.857", "Id": "530415", "Score": "0", "body": "@JohanduToit i'm sorry, there was an error in getOpening because i translated the function from my language to english, it work now" } ]
[ { "body": "<p>I think you are overcomplicating things with all the inline lambda functions.</p>\n<p>A Simple way to compare two times is to use the following formula:</p>\n<pre><code>time = hour * 60 + minute.\n</code></pre>\n<p>Based on this you can use the following function to create a time representation from a string, ie <code>08:30</code></p>\n<pre><code>timeToInt = function(text) {\n let hour = parseInt(text.substring(0, 2));\n let minute = parseInt(text.substring(3));\n return hour * 60 + minute;\n}\n</code></pre>\n<p>And use the same formula to get an integer representation of the current time:</p>\n<pre><code>let date = new Date();\nlet currentTime = date.getHours() * 60 + date.getMinutes();\n</code></pre>\n<p>At this point everything starts to become much simpler:</p>\n<pre><code>set_opening = function (openings) {\n let date = new Date();\n let currentTime = date.getHours() * 60 + date.getMinutes();\n let startDay = date.getDay();\n let dayOfWeek = startDay;\n let weekDayLookup = [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;];\n let nextTime = false;\n for (; ;) {\n let dayName = weekDayLookup[dayOfWeek % 7];\n let opening = openings[&quot;opening&quot; + dayName.substring(0, 3)];\n let timeSpans = opening.split(';').map(item =&gt; item.trim());\n for (span of timeSpans) {\n let hours = span.split('-').map(item =&gt; item.trim())\n if (nextTime == false) {\n let openTime = timeToInt(hours[0]);\n let closeTime = timeToInt(hours[1]);\n if (currentTime &gt;= openTime &amp;&amp; currentTime &lt;= closeTime)\n return &quot;Open now - Closing: &quot; + hours[1];\n nextTime = true;\n }\n else {\n if (dayOfWeek == startDay)\n return &quot;Closed now - Opening: &quot; + dayName + &quot; &quot; + hours[0];\n else \n return &quot;Closed today - Opening: &quot; + (dayOfWeek - startDay == 1 ? &quot;Tomorrow&quot; : dayName) + &quot; &quot; + hours[0];\n }\n }\n dayOfWeek++;\n if (dayOfWeek &gt; 14)\n return &quot;No opening time found&quot;;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:55:30.363", "Id": "530551", "Score": "0", "body": "Thank you nice tips :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T15:17:17.973", "Id": "268913", "ParentId": "268899", "Score": "0" } } ]
{ "AcceptedAnswerId": "268913", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T10:29:45.920", "Id": "268899", "Score": "1", "Tags": [ "javascript", "datetime" ], "Title": "Find when the shop will next open or close" }
268899
<p>To learn some rust I decided to write a simple calculator. This calculator can take a string in the form of <code>1+2*3/4-5</code>, and calculate the result. It does so while keeping the order of operations in mind (*/ before +-).</p> <p>I came up with the following:</p> <pre><code>/// Token containing either a number or an operation. Never both. #[derive(Debug, PartialEq)] enum Token { NUMBER(i64), /// Operation being one of +/*- OPERATION(char), } impl Token { pub fn from_string(string: &amp;str) -&gt; Result&lt;Self, &amp;str&gt; { let number = string.parse::&lt;i64&gt;().ok(); if number.is_some() { Ok(Token::NUMBER(number.unwrap())) } else { match string.chars().nth(0) { Some(c) =&gt; Ok(Token::OPERATION(c)), None =&gt; Err(&quot;Can't parse token from empty string.&quot;), } } } } /// Tokenizes the given string. Splits numbers from non-numbers. Returns a vector of tokens. fn tokenize(sum: &amp;str) -&gt; Vec&lt;Token&gt; { let mut parts: Vec&lt;String&gt; = Vec::new(); let mut prev_is_number = false; for c in sum.chars() { if c.is_numeric() != prev_is_number { prev_is_number = c.is_numeric(); parts.push(String::new()); } parts.last_mut().unwrap().push(c); } let mut tokens: Vec&lt;Token&gt; = Vec::new(); for token in parts { tokens.push(Token::from_string(&amp;token).expect(&amp;format!(&quot;Failed to parse {}&quot;, token))); } prev_is_number = false; for token in &amp;tokens { let is_number = match token { Token::NUMBER(..) =&gt; true, _ =&gt; false }; assert_ne!(prev_is_number, is_number ); // Assert numbers always followed by tokens and otherwise. prev_is_number = is_number; } return tokens; } /// Solves the multiplications and divisions in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place. /// e.g. 1+2*3 returns 1+6. fn solve_multiply_divide(tokens: &amp;Vec&lt;Token&gt;) -&gt; Vec&lt;Token&gt; { let mut prev_number: Option&lt;i64&gt; = None; let mut prev_operation: Option&lt;char&gt; = None; let mut result: Vec&lt;Token&gt; = Vec::new(); for token in tokens { match token { Token::NUMBER(number) =&gt; { match prev_number { None =&gt; { prev_number = Some(*number); }, Some(unwrapped_prev_number) =&gt; { match prev_operation { Some('*') =&gt; { prev_number = Some(unwrapped_prev_number * number); }, Some('/') =&gt; { prev_number = Some(unwrapped_prev_number / number); }, _ =&gt; {panic!(&quot;Found two numbers after each other without operator in between. Incorrect token sequence supplied.&quot;)} } prev_operation = None; } } } Token::OPERATION(operation) =&gt; { if *operation == '*' || *operation == '/' { prev_operation = Some(*operation); } else { if prev_number.is_some() { result.push(Token::NUMBER(prev_number.unwrap())); } result.push(Token::OPERATION(*operation)); prev_number = None; prev_operation = None; } } } } if prev_number.is_some() { result.push(Token::NUMBER(prev_number.unwrap())); } return result; } /// Solves the plus and minus in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place. /// e.g. 1+2*3 returns 3*3 fn solve_plus_minus(tokens: &amp;Vec&lt;Token&gt;) -&gt; Vec&lt;Token&gt; { let mut prev_number: Option&lt;i64&gt; = None; let mut prev_operation: Option&lt;char&gt; = None; let mut result: Vec&lt;Token&gt; = Vec::new(); for token in tokens { match token { Token::NUMBER(number) =&gt; { match prev_number { None =&gt; { prev_number = Some(*number); }, Some(unwrapped_prev_number) =&gt; { match prev_operation { Some('+') =&gt; { prev_number = Some(unwrapped_prev_number + number); }, Some('-') =&gt; { prev_number = Some(unwrapped_prev_number - number); }, _ =&gt; {panic!(&quot;Found two numbers after each other without operator in between. Incorrect token sequence supplied.&quot;)} } prev_operation = None; } } } Token::OPERATION(operation) =&gt; { if *operation == '+' || *operation == '-' { prev_operation = Some(*operation); } else { if prev_number.is_some() { result.push(Token::NUMBER(prev_number.unwrap())); } result.push(Token::OPERATION(*operation)); prev_number = None; prev_operation = None; } } } } if prev_number.is_some() { result.push(Token::NUMBER(prev_number.unwrap())); } return result; } /// Solves a given equation. pub fn solve(sum: &amp;str) -&gt; Result&lt;i64, &amp;str&gt; { let tokens = tokenize(sum); let tokens_multiplied_divided = solve_multiply_divide(&amp;tokens); let tokens_plus_minus = solve_plus_minus(&amp;tokens_multiplied_divided); assert_eq!(tokens_plus_minus.len(), 1); match tokens_plus_minus.first().unwrap() { Token::NUMBER(result) =&gt; Ok(*result), _ =&gt; Err(&quot;Could not solve. Invalid equation?&quot;) } } #[cfg(test)] mod tests { use super::*; /// Returns the vector of tokens for 1+2*3/4-5 fn get_test_tokens() -&gt; Vec&lt;Token&gt; { return vec![ Token::NUMBER(1), Token::OPERATION('+'), Token::NUMBER(2), Token::OPERATION('*'), Token::NUMBER(3), Token::OPERATION('/'), Token::NUMBER(4), Token::OPERATION('-'), Token::NUMBER(5), ]; } #[test] fn test_tokenize() { assert_eq!(tokenize(&quot;1+2*3/4-5&quot;), get_test_tokens()); } #[test] fn test_multiply_divide() { assert_eq!( solve_multiply_divide(&amp;get_test_tokens()), [ Token::NUMBER(1), Token::OPERATION('+'), Token::NUMBER(2 * 3 / 4), Token::OPERATION('-'), Token::NUMBER(5), ] ) } #[test] fn test_solve() { match solve(&quot;1+2*3/4-5&quot;) { Ok(-3) =&gt; assert!(true), Ok(number) =&gt; assert!(false, &quot;wrong answer: {}&quot;, number), Err(error) =&gt; assert!(false, &quot;got an error: {}&quot;, error) } } } </code></pre> <p>One problem that I do have with this code is the overlap between solve_multiply_divide and solve_plus_minus, I feel like these could be merged somehow but I haven't figured out how yet.</p> <p>I'm coming from a C++ background, which could shine through in this code. How could I improve my code and make it adhere more to a rust way of thinking, instead of c++?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T13:11:08.027", "Id": "268907", "Score": "2", "Tags": [ "rust" ], "Title": "Rust calculator" }
268907
<p>I have to sort the array based on rating in a specific pattern.</p> <p>3 star = 5, 4star = 3 , 5 star =7</p> <p>[3 star hotel, 4 star hotel, 5 star hotel]</p> <p>Note: Replace 3 star hotel with 4 star hotel if 4 star are not there.</p> <p>expected pattern: 345 345 345 335 555</p> <p>basically i want to sort some hotels based on rating</p> <p>inputs :</p> <p>3* = 5 (number of 3 star hotels is 5)</p> <p>4* = 3 (number of 4 star hotels is 3)</p> <p>5* = 4 (number of 5 star hotels is 4)</p> <pre><code>{ 3: [&quot;3&quot;,&quot;3&quot;,&quot;3&quot;,&quot;3&quot;,&quot;3&quot;], 4: [&quot;4&quot;, &quot;4&quot;, &quot;4&quot;], 5: [&quot;5&quot;, &quot;5&quot;, &quot;5&quot;, &quot;5&quot;] } </code></pre> <p>output:</p> <p><a href="https://i.stack.imgur.com/TPgcF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TPgcF.png" alt="enter image description here" /></a></p> <p>can anyone know how can we achieve the solution in a better way?</p> <p>my current implementation is</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>function getMaxLength(hotelRating) { return Math.max(hotelRating[3].length, hotelRating[4].length, hotelRating[5].length); } function getOrderedHotelRating(hotelRating) { const orderedHotelRatingArr = []; const unorderedHotelRatingArr = []; const modifiedHotelRatingArr = []; const unorderedHotelRatingObj = { 3: [], 4: [], 5: [] }; for (let i = 0; i &lt; getMaxLength(hotelRating); i++) { if (hotelRating[3][i] &amp;&amp; hotelRating[4][i] &amp;&amp; hotelRating[5][i]) { orderedHotelRatingArr.push([hotelRating[3][i], hotelRating[4][i], hotelRating[5][i]]); } else { unorderedHotelRatingArr.push([hotelRating[3][i] || 0, hotelRating[4][i] || 0, hotelRating[5][i] || 0]); } } unorderedHotelRatingArr.forEach(ar=&gt;{ if (ar[0]) { unorderedHotelRatingObj[3].push(ar[0]); } if (ar[1]) { unorderedHotelRatingObj[4].push(ar[1]); } if (ar[2]) { unorderedHotelRatingObj[5].push(ar[2]); } }); [...unorderedHotelRatingObj[3], ...unorderedHotelRatingObj[4], ...unorderedHotelRatingObj[5]].forEach((ar,index,list)=&gt;{ // console.log(index) if (index % 3 === 0) { modifiedHotelRatingArr.push(list.slice(index, index + 3)); } } ); return [...orderedHotelRatingArr, ...modifiedHotelRatingArr]; } let result = getOrderedHotelRating({ 3: ["3","3","3","3","3"], 4: ["4", "4", "4"], 5: ["5", "5", "5", "5"] }); console.log(result);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T20:45:12.533", "Id": "530444", "Score": "0", "body": "What exactly do you want to improve? Performance, shorten the code?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T13:33:02.000", "Id": "268908", "Score": "0", "Tags": [ "javascript", "algorithm", "array" ], "Title": "Order array based on rating in a specific pattern" }
268908
<p><code>wordList</code> is an array of non-empty strings (&quot;words&quot;). The following code I have written with the purpose of obtaining a Map, containing the unique words and their respective count:</p> <pre><code>for (let p = 0; p &lt; wordList.length; p++) { const word = wordList[p]; if (wordMap.has(word)) { wordMap.set(word, wordMap.get(word) + 1); //increase frequency of word } else { wordMap.set(word, 1); //add word } } </code></pre> <p>I'd like to know if there is a better way to obtain this frequency distribution. Although the code seems to be working, feels a bit awkward (I am aware of the existence of the reducer(), but I have difficulty figuring it out).</p> <p>If possible, I'd Like also to know how to make this case insensitive.</p>
[]
[ { "body": "<h2>General review points</h2>\n<ul>\n<li><p>Rather than use a <code>for(;;)</code> loop use a <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> loop as you dont need the idx <code>p</code> for anything but indexing the word array.</p>\n<pre><code>for (const word of wordList) {\n</code></pre>\n</li>\n<li><p>You don't need the comments as what is happening is obvious in the code.</p>\n</li>\n<li><p>You can combine the get and set into one expression by using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Nullish coalescing operator\">?? (Nullish coalescing operator)</a> to check for undefined.</p>\n<pre><code>wordMap.set(word, (wordMap.get(word) ?? 0) + 1);\n</code></pre>\n</li>\n<li><p>Always create functions rather than flat code. Even when only showing example code.</p>\n</li>\n</ul>\n<h2>Reducer</h2>\n<blockquote>\n<p><em>&quot;... (I am aware of the existence of the reducer(), but I have difficulty figuring it out) ...&quot;</em></p>\n</blockquote>\n<p>Is not needed in this case but can be use if so desired. (See last rewrite)</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array reduce\">Array.reduce</a> a reference if needed.</p>\n<h2>Rewrite</h2>\n<p>There are several ways you can write the function</p>\n<pre><code>function mapWordCounts(words) {\n const counts = new Map();\n for (const word of words) { counts.set(word, (counts.get(word) ?? 0) + 1) }\n return counts;\n}\n</code></pre>\n<p>Or using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array forEach\">Array.forEach</a></p>\n<pre><code>function mapWordCounts(words) {\n const counts = new Map();\n words.forEach(word =&gt; counts.set(word, (counts.get(word) ?? 0) + 1));\n return counts;\n}\n</code></pre>\n<p>Or with a reducer in an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Functions/Arrow functions\">arrow function</a> which will save the need for the return token as return are implied in arrow functions with out a delimited <code>{}</code> code body. This only works because <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Map set\">Map.set</a> return the map when called.</p>\n<pre><code>const mapWordCounts = words =&gt; words.reduce(\n (counts, word) =&gt; counts.set(word, (counts.get(word) ?? 0) + 1), new Map()\n );\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T06:49:06.613", "Id": "530463", "Score": "0", "body": "Thank you, very kind. Your answer is very helpful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T02:10:31.113", "Id": "268934", "ParentId": "268917", "Score": "2" } } ]
{ "AcceptedAnswerId": "268934", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T16:43:12.443", "Id": "268917", "Score": "2", "Tags": [ "javascript", "strings", "hash-map" ], "Title": "word frequency distribution" }
268917
<p>Looking for any suggestions - alternative design, improvements to readability, improvements to the comments, etc.</p> <hr /> <p>I implemented this letter dictionary to see if it would faster than a regular dictionary in a Trie implementation. Keys into this dictionary must be lowercase letters. <code>LetterDict</code> maintains an integer bitset, <code>K</code>, and a list, <code>V</code> s.t. if the <code>o</code>th lowercase letter is a key in the dictionary, then the <code>o</code>th bit of <code>K</code> is set and <code>V</code> holds the value corresponding to the letter key. For example, the regular dictionary <code>{'c': 22, 'a': 0, 'b': 11, 'd': 33, 'x': 23, 'j': 10}</code> would be maintained as:</p> <pre><code> zy xwvu tsrq ponm lkji hgfe dcba &lt;- letter 54 3210 9876 5432 1098 7654 3210 &lt;- letter/bit index K = 0b00_1000_0000_0000_0010_0000_1111 &lt;- keys a b c d j x &lt;- keys V = [0, 11, 22, 33, 10, 23] &lt;- values </code></pre> <pre><code>class LetterDictCompact: '''A dicitionary whose keys must be lowercase letters [a-z].''' ORD_a = ord('a') def __init__(self): self.K = 0b0 # keys are lowercase letters [a-z] self.V = [] # values can be anything def __contains__(self, key: str) -&gt; bool: o = ord(key) - self.ORD_a return self.K &amp; (1 &lt;&lt; o) def __getitem__(self, key: str): present, i = self.__i(key) if present: return self.V[i] raise KeyError(key) def __setitem__(self, key: str, val): present, i = self.__i(key) if present: self.V[i] = val else: self.V.insert(i, val) def setdefault(self, key: str, defval=None): present, i = self.__i(key) if present: return self.V[i] self.V.insert(i, defval) return defval # SIDE EFFECT: Modifies self.K # As such, __contains__ should not call this method def __i(self, key: str) -&gt; tuple[bool, int]: o = ord(key) - self.ORD_a target = 1 &lt;&lt; o present = self.K &amp; target self.K |= target K = self.K i = 0 while (K := K &amp; (K - 1)) &amp; target: i += 1 return present, i </code></pre> <p>I also implemented a version of <code>LetterDict</code> that is not as compact because it maintains <code>V</code> as a constant-26-length <code>list</code> (actually, as a constant-27-length because an extra character is needed to denote the end of a word in the Trie implementation). As mentioned, this version is not as compact, but it does simplify the logic a lot:</p> <pre><code>class LetterDictSparse: '''A dicitionary whose keys must be lowercase letters [a-z].''' NUM_LETTERS = 26 + 1 # + 1 to accomoated Trie.END = chr(ord('z') + 1) EMPTY_VALUE = object() # Cannot be `None` because `None` is a possible value ORD_a = ord('a') def __init__(self): self.K = 0b0 # keys are lowercase letters [a-z] self.V = [self.EMPTY_VALUE] * self.NUM_LETTERS # values can be anything def __contains__(self, key: str) -&gt; bool: o = ord(key) - self.ORD_a return self.V[o] != self.EMPTY_VALUE def __getitem__(self, key: str): o = ord(key) - self.ORD_a if (val := self.V[o]) == self.EMPTY_VALUE: raise KeyError(key) return val def __setitem__(self, key: str, val): o = ord(key) - self.ORD_a self.V[o] = val def setdefault(self, key: str, defval=None): o = ord(key) - self.ORD_a if (val := self.V[o]) == self.EMPTY_VALUE: self.V[o] = defval return defval return val </code></pre> <p>Both of the above implementations of <code>LetterDict</code> are correct in as much as I used them to implement a Trie and that Trie passed all the <a href="https://leetcode.com/problems/implement-trie-prefix-tree/" rel="nofollow noreferrer">leetcode Trie tests</a>. <a href="https://pastebin.com/uWj46fpi" rel="nofollow noreferrer">Here</a> you can see the code in context.</p> <hr /> <p>In general, any dictionary whose keys are restricted to fall within a contiguous range of values can be implemented like <code>LetterDictCompact</code> and <code>LetterDictSparese</code> for some definition of &quot;contiguous range of values&quot; (what's required is that there's a one-to-one mapping between the &quot;contiguous range of values&quot; to the range <code>[0..N]</code> for <code>N</code> equal to the number of values in the &quot;contiguous range of values&quot;).</p>
[]
[ { "body": "<h1>Counting bits</h1>\n<pre class=\"lang-py prettyprint-override\"><code> K = self.K\n i = 0\n while (K := K &amp; (K - 1)) &amp; target:\n i += 1\n</code></pre>\n<p>This loop is counting the number of <code>1</code>-bits below the <code>target</code> bit.</p>\n<p>The <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=bit_count#int.bit_count\" rel=\"nofollow noreferrer\"><code>int.bit_count()</code></a> function can give you the population of 1's in any integer, so this loop could be replaced with one statement:</p>\n<pre class=\"lang-py prettyprint-override\"><code> i = (self.K &amp; (target - 1)).bit_count()\n</code></pre>\n<p>Note: In Python 3.9 and earlier, you could use:</p>\n<pre class=\"lang-py prettyprint-override\"><code> i = bin(self.K &amp; (target - 1)).count(&quot;1&quot;)\n</code></pre>\n<p>but the efficiency of this is questionable due to conversion to string.</p>\n<h1>Public -vs- Private</h1>\n<p>The members <code>K</code> and <code>V</code> should be named <code>_k</code> and <code>_v</code> (or even <code>_keys</code> and <code>_vals</code>)</p>\n<ul>\n<li>The leading underscore, by convention, indicates they are not part of the public interface.</li>\n<li><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8: The Style Guide for Python Code</a> recommends all members use <code>lowercase_lettering</code>. Upper case letters are reserved for use in <code>CONSTANT_VALUES</code> and <code>ClassNames</code>.</li>\n</ul>\n<h1>Unused members</h1>\n<p>The member <code>K</code> is unused in <code>LetterDictSparse</code>, and should be removed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T19:38:04.327", "Id": "530434", "Score": "0", "body": "Thanks! Made the changes in github. Just for my future reference:`int.bit_count()` was added in Python 3.10." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T19:47:08.787", "Id": "530436", "Score": "1", "body": "Whoops! Didn't notice that. Knew Java has `Integer.bitCount()` for ever (well, since 1.5 anyway), and knew Python integers had `.member_function()` methods. Opened an IDLE shell, typed `x = 1` and `x.`, pressed tab, saw `bit_count` in the possible completions, searched `bit_count` in the Python docs I had open in my browser, copy-pasted the link, and moved on. Didn't notice it was a newly added function. :-p For Python 3.9 and earlier, `i = bin(self.K & (target - 1)).count(\"1\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T20:10:45.050", "Id": "530440", "Score": "0", "body": "Still, it's very useful to know about the new function. Thanks again!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T18:28:08.040", "Id": "268924", "ParentId": "268919", "Score": "1" } } ]
{ "AcceptedAnswerId": "268924", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T17:50:09.057", "Id": "268919", "Score": "3", "Tags": [ "python", "hash-map", "bitwise", "trie" ], "Title": "LetterDict, a dictionary whose keys must be lowercase letters [a-z]" }
268919
<p>I have a string of Hebrew text which also contains&quot;:&quot;, &quot;-&quot;, &amp; &quot;|&quot;. Attempting to replace &quot;-&quot;, &quot;|&quot;, and &quot;:&quot; with a space. How can I do this efficiently?</p> <pre><code>string my_string = &quot;עַל־פְּנֵי:על־פני|על־פני&quot;; string[] replace_chars = new string[] {&quot;:&quot;,&quot;-&quot;,&quot;|&quot;}; foreach (string char_change in replace_chars){ if(char_change == &quot;:&quot; || char_change == &quot;-&quot; || char_change == &quot;|&quot;){ my_string = my_string.Replace(char_change, &quot; &quot;); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T19:54:01.007", "Id": "530437", "Score": "0", "body": "Is there any alternative to have this done ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T20:46:19.520", "Id": "530445", "Score": "0", "body": "You can look at this stackoverflow question https://stackoverflow.com/q/7265315. Pretty much covers all the options. from regex to string split to linq" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T06:34:33.427", "Id": "530462", "Score": "0", "body": "Your code does not follow the Microsoft guidelines: https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions : \"DO NOT use underscores, hyphens, or any other nonalphanumeric characters.\" Also, you use the word \"char\" when in reality it is a string." } ]
[ { "body": "<p>you can always use <code>Replace</code> extension, it's fast, durable, and under your hands. So, your work would be something like :</p>\n<pre><code>const char space = '\\u0020'; // for readability purpose.\n\nvar result = my_string.Replace(':', space).Replace('-', space).Replace('|', space);\n</code></pre>\n<p>or if you have larger strings or you think it would be executed repeatedly, you can always use <code>StringBuilder</code>.</p>\n<pre><code>const char space = '\\u0020'; // for readability purpose.\n\nvar builder = new StringBuilder(my_string);\n\nvar result = builder\n .Replace(':', space)\n .Replace('-', space)\n .Replace('|', space)\n .ToString();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T03:08:28.153", "Id": "268970", "ParentId": "268920", "Score": "4" } } ]
{ "AcceptedAnswerId": "268970", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T18:00:11.527", "Id": "268920", "Score": "2", "Tags": [ "c#", "performance", "strings" ], "Title": "replace substrings from within Hebrew text" }
268920
<p>I have the following entity, I am getting it in response of REST API.</p> <pre><code>class Account { private String ownerId; private List&lt;String&gt; coOwners; } </code></pre> <p>REST API accepts UUID and returns linked Account.</p> <p>Now my task here is to call this REST API for multiple bank accounts owned by the same person, combine coOwner and owner and return it back.</p> <p>For combining coOwners and owner I have created a separate model.</p> <pre><code>class LinkedOwners { private String ownerId; private List&lt;String&gt; coOwners; // getters and setters } </code></pre> <p>My solution:</p> <pre><code>public LinkedOwners getLinkedOwners(List&lt;UUID&gt; uuids) { LinkedOwners linkedOwners = new LinkedOwners(); String ownerId = null; Set&lt;String&gt; coOwners = new HashSet&lt;&gt;(); for (UUID uuid : uuids) { Account account = // call REST API with uuid ownerId = account.getOwnerId(); coOwners.addAll(account.getCoOwners()); } linkedOwners.setOwnerId(ownerId); linkedOwners.setCoOwners(coOwners); return linkedOwners; } </code></pre> <p>Now the problem here is, as I am calling the API with UUIDs belonging to the same user. each Account will have the same owner, and <code>ownerId = account.getOwnerId();</code> will set the same value again and again and it looks hacky.</p> <p>The other solution would be to create <code>List&lt;Account&gt;</code> and perform groupBy stream operation on it.</p> <p>is there a better/elegant way to merge <code>owner</code> and <code>coOwners</code>? Unfortunately, I cannot change the REST API definition as it's a third-party service.</p>
[]
[ { "body": "<p>You could clean it up by splitting into multiple steps. It feels wrong to make a class for ownerId and coOwners... Don't you know the ownerId at the time of making the request? (How do you know that accounts belong to the same owner?)</p>\n<pre><code>public List&lt;String&gt; fetchDistinctCoOwners(List&lt;UUID&gt; accountIds) {\n List&lt;Account&gt; accounts = fetchAccounts(accountIds);\n return getDistinctCoOwners(accounts);\n}\n\nprivate List&lt;Account&gt; fetchAccounts(List&lt;UUID&gt; accountIds) {\n return accountIds.stream()\n .map(id -&gt; // call API)\n .collect(Collectors.toList());\n}\n\nprivate List&lt;String&gt; getDistinctCoOwners(List&lt;Account&gt; accounts) {\n return uuids.stream()\n .map(Account::getCoOwners)\n .flatMap(Collections::stream)\n .distinct()\n .collect(Collectors.toList());\n}\n</code></pre>\n<p>It feels odd and awkward to have accountIds and not ownerId of the account at the beginning. If you are doing an API a good design for this seems something like 'owners/:ownerId/co-owners', where the result is a list of coowners. But again, I do not know the whole context.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T20:05:51.290", "Id": "268929", "ParentId": "268925", "Score": "0" } }, { "body": "<p>Note on how to publish here: In general, it's better to try to post complete code which will compile (and ideally run) rather than fragments of code. Later in this post I show an example with test data that's runnable, you could and should have done the same thing.</p>\n<p>Now to discuss the issue at hand.</p>\n<p>I assume from the description that you know that your set of UUIDs relate to the same ownerId, in which case I'm a little surprised that you don't know the relevant ownerid.</p>\n<p>However, assuming that you don't know that, then I think that the processing really needs to handle the first returned Account slightly different from the rest.</p>\n<p>(Aside: I'm not sure Streams add much here, but then I'm not so familiar with them that I automatically reach for a Stream-based solution.)</p>\n<p>I think your LinkedOwners class (I don't like this name, so called it MergedAccount in my solution, though I'm not sure that name is much better) should take care of the Collection of coOwners, rather than building it separately and then storing it.</p>\n<p>Here's my approach, which has at least had some basic test data through it:</p>\n<pre><code>import java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.TreeSet;\n public class Govinda {\n private static class Account {\n private String ownerId;\n private List&lt;String&gt; coOwners;\n Account(String ownerId, List&lt;String&gt; coOwners) {\n this.ownerId = ownerId;\n this.coOwners = coOwners;\n }\n public String getOwnerId() {\n return ownerId;\n }\n public List&lt;String&gt; getCoOwners() {\n return coOwners;\n }\n }\n \n // Haven't got a REST API, so just set up some test data\n private static final List&lt;Account&gt; testAccounts = Arrays.asList(\n new Account(&quot;Fred&quot;, Arrays.asList(&quot;Joe&quot;, &quot;Margo&quot;)),\n new Account(&quot;Fred&quot;, Arrays.asList(&quot;Joe&quot;, &quot;Margo&quot;)),\n new Account(&quot;Fred&quot;, Arrays.asList(&quot;Bill&quot;, &quot;Karen&quot;, &quot;Pete&quot;)),\n new Account(&quot;Fred&quot;, Arrays.asList(&quot;Mark&quot;)));\n\n private static class MergedAccount {\n private String ownerId;\n private Set&lt;String&gt; coOwners;\n MergedAccount(String ownerId) {\n this.ownerId = ownerId;\n coOwners = new TreeSet&lt;&gt;(); // Sorted \n }\n public String getOwnerId() {\n return ownerId;\n }\n public Set&lt;String&gt; getCoOwners() {\n return coOwners;\n }\n public MergedAccount addCowners(List&lt;String&gt; coOwnersToAdd) {\n coOwners.addAll(coOwnersToAdd);\n return this; // easy to chain with constructor\n }\n }\n\n public static void main(String[] args) {\n Iterator&lt;Account&gt; accountIterator = testAccounts.iterator();\n if (accountIterator.hasNext()) {\n Account currentAccount = accountIterator.next();\n MergedAccount mergedAccount = new MergedAccount(currentAccount.getOwnerId()).addCowners(currentAccount.getCoOwners());\n while (accountIterator.hasNext()) {\n currentAccount = accountIterator.next();\n mergedAccount.addCowners(currentAccount.getCoOwners());\n }\n\n System.out.format(&quot;OwnerId: %s CoOwners: %s%n&quot;, mergedAccount.getOwnerId(), String.valueOf(mergedAccount.getCoOwners()));\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T10:25:57.647", "Id": "268943", "ParentId": "268925", "Score": "2" } }, { "body": "<p>It's a bit unclear to me what the UUID you're passing to the rest service represents. Is it the ID for an account, the ID for an owner, the ID for an owner/account relationship. The answer is probably in the source of the UUID, which isn't included in the question, but presumably it's been returned from the REST service at some point. Does it really matter... well, maybe.</p>\n<p>If there's a 1-1 mapping between UUID and ownerId, how come you don't already know the ownerId? Do you just not store it because it seems like redundant data? Are you just acting as a pass-through where your clients are responsible for knowing things like the UUID? Do your clients really need to know <code>ownerId</code>, rather than the UUID? What information do you/they need for future calls to the API?</p>\n<p>Setting the <code>ownerid</code> over and over again with what you think is the same value and then using the last value may seem hacky, but it does avoid branching logic that doesn't add any value (<code>if(ownerId==null)</code>). However, you may want to consider <strong>validating your assumptions</strong>.</p>\n<p>The rest API is a third party service, which you can't change, so have no control over. Perhaps it's really well documented and you're completely confident it does what you're expecting, however if not what happens? If the UUID represents an account, is it possible that the particular owner you are querying could be returned in the co-owner list, instead of the owner field? If this happens on the last account retrieved it will appear as if the co-owner owns all of the returned accounts.</p>\n<p>Your clients generally are going to blame you for any mistakes that are passed back to them, so where possible consider adding in basic validation around your assumptions. In this case, validating that all of the returned accounts have the same ownerId would seem to be reasonable. If they don't, then the UUIDs are wrong, the client service isn't behaving, or your assumptions about how it works are incorrect. However if any of these happen it seems likely you'd want to know.</p>\n<p>As an aside... it also seems a little odd to me that the <code>Account</code> returned from the API doesn't appear to have anything like an account identifier in it, but I guess that's not your API.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T12:27:08.463", "Id": "268947", "ParentId": "268925", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T18:44:35.213", "Id": "268925", "Score": "0", "Tags": [ "java", "object-oriented", "design-patterns" ], "Title": "What is the elegant way to merge collection of entities with a duplicate field?" }
268925
<p>This is my first game ever. I' learning C++ now and I decided to make a game. I saw a snake game that works with the draw-input-logic system and I really liked it. I tried to make a tic tac toe game.</p> <p>Please rate it and show me how can I improve it, or give me any other simple game ideas.</p> <p>input: x y;</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; // 1 -&gt; X | -1 -&gt; O | 0 -&gt; Empty bool GameOver; bool checkDraw(std::vector&lt;std::vector&lt;int&gt;&gt;&amp;); void draw(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; v) { system(&quot;CLS&quot;); for (int i = 0; i &lt; 11; i++) { std::cout &lt;&lt; &quot; &quot;; if (i == 4) std::cout &lt;&lt; &quot;1&quot;; else if (i == 7) std::cout &lt;&lt; &quot;2&quot;; else if (i == 10) std::cout &lt;&lt; &quot;3\n&quot;; } int num = 1, val = 0; for (int i = 0; i &lt; 7; i++) { if (i % 2 == 0) { std::cout &lt;&lt; &quot; &quot;; for (int j = 0; j &lt; 3; j++) { std::cout &lt;&lt; &quot;+---&quot;; } std::cout &lt;&lt; &quot;+\n&quot;; } else { std::cout &lt;&lt; &quot; &quot; &lt;&lt; num &lt;&lt; &quot; &quot;; num++; for (int j = 0; j &lt; 3; j++) { if (v[val][j] == 1) std::cout &lt;&lt; &quot;| X &quot;; else if (v[val][j] == -1) std::cout &lt;&lt; &quot;| O &quot;; else std::cout &lt;&lt; &quot;| &quot;; } std::cout &lt;&lt; &quot;|&quot; &lt;&lt; std::endl; val++; } } std::cout &lt;&lt; std::endl; } void logic(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; v) { int num1 = 0, num2 = 0; int XorO_1 = 0, XorO_2 = 0, XorO_3 = 0; bool x, y, z = false; for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 3; j++) { if (v[i][j] == v[i][0] &amp;&amp; v[i][0] != 0) { x = true; XorO_1 = v[i][0]; num1++; if (num1 == 3) break; } else { x = false; break; } } num1 = 0; if (x) break; } for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 3; j++) { if (v[j][i] == v[0][i] &amp;&amp; v[0][i] != 0) { y = true; XorO_2 = v[0][i]; num2++; if (num2 == 3) break; } else { y = false; break; } } num2 = 0; if (y) break; } if (v[0][0] == v[1][1] &amp;&amp; v[1][1] == v[2][2] &amp;&amp; v[1][1] != 0) { if (v[0][0] == 1) { z = true; XorO_3 = 1; } else if (v[0][0] == -1) { z = true; XorO_3 = -1; } } else if (v[0][2] == v[1][1] &amp;&amp; v[1][1] == v[2][0] &amp;&amp; v[1][1] != 0) { if (v[0][2] == 1) { z = true; XorO_3 = 1; } else if (v[0][2] == -1) { z = true; XorO_3 = -1; } } if (x || y || z) { if (XorO_1 == 1 || XorO_2 == 1 || XorO_3 == 1) { std::cout &lt;&lt; &quot;USER 1 (X) IS THE WINNER :D\n&quot;; GameOver = true; } else if (XorO_1 == -1 || XorO_2 == -1 || XorO_3 == -1) { std::cout &lt;&lt; &quot;USER 2 (O) THE IS WINNER :D\n&quot;; GameOver = true; } } else if (!checkDraw(v)) { std::cout &lt;&lt; &quot;DRAW...\n&quot;; GameOver = true; } } void input(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; v) { static int turn = 0; int x, y; if (turn % 2 == 0) { do { std::cout &lt;&lt; &quot;User 1 (X) its your turn, Enter position: &quot;; std::cin &gt;&gt; x &gt;&gt; y; } while ((x &gt; 3 || x &lt;= 0) || (y &gt; 3 || y &lt;= 0)); while (v[y - 1][x - 1] == 1 || v[y - 1][x - 1] == -1) { std::cout &lt;&lt; &quot;Wrong input User 1 (X), Try Again : &quot;; std::cin &gt;&gt; x &gt;&gt; y; } v[y - 1][x - 1] = 1; } else { do { std::cout &lt;&lt; &quot;User 2 (O) its your turn, Enter position: &quot;; std::cin &gt;&gt; x &gt;&gt; y; } while ((x &gt; 3 || x &lt;= 0) || (y &gt; 3 || y &lt;= 0)); while (v[y - 1][x - 1] == 1 || v[y - 1][x - 1] == -1) { std::cout &lt;&lt; &quot;Wrong input User 2 (O), Try Again : &quot;; std::cin &gt;&gt; x &gt;&gt; y; } v[y - 1][x - 1] = -1; } turn++; } bool checkDraw(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; v) { for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 3; j++) { if (v[i][j] == 0) return 1; } } return 0; } int main() { std::vector&lt;std::vector&lt;int&gt;&gt; game{ {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; draw(game); // i did this for a reason, if not u can't see the winnig position, try it yourself while (!GameOver) { input(game); draw(game); logic(game); } } </code></pre>
[]
[ { "body": "<p>I'll start with the good.</p>\n<ol>\n<li>You did not have <code>using namespace std;</code>.</li>\n<li>You are passing <code>std::vector&lt;std::vector&lt;int&gt;&gt; game</code> by a reference, nice!</li>\n</ol>\n<p>Now for the bad, and unfortuanatly there is quite a bit.</p>\n<p>This looks like it started life as C code. The only thing C++ about this is the use of <code>std::vector</code> instead of <code>int[]</code> and <code>std::cout</code> instead of <code>printf</code>.</p>\n<p>In C++ we have classes. Consider creating one:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Game\n{\npublic:\n void draw();\n void input();\n int logic();\n\nprivate:\n bool gameOver;\n std::vector&lt;std::vector&lt;int&gt;&gt; game;\n};\n</code></pre>\n<p><b>Draw</b></p>\n<p><code>system(&quot;CLS&quot;);</code> will only work on Windows, you can find some alternatives <a href=\"https://stackoverflow.com/questions/6486289/how-can-i-clear-console\">here</a>.</p>\n<p>This could have been much simpler if you used <code>X</code>, <code>O</code> and <code> </code> for the symbols instead of 1, -1, and a zero.</p>\n<p><b>logic</b></p>\n<p>This is a hot mess! Consider what you actually need to do here.</p>\n<ol>\n<li>Check if player 1 has won</li>\n<li>Check if player 2 has won</li>\n<li>Check if it's a draw</li>\n</ol>\n<p>I would create the following function:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool checkIfPlayerWon(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; v, int player);\n</code></pre>\n<p>and then simplify <code>logic</code> to the following</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void logic(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; v) {\n if (checkIfPlayerWon(v, 1)) {\n std::cout &lt;&lt; &quot;USER 1 (X) IS THE WINNER :D\\n&quot;;\n GameOver = true; \n }\n else if (checkIfPlayerWon(v, -1)) {\n std::cout &lt;&lt; &quot;USER 0 (O) IS THE WINNER :D\\n&quot;;\n GameOver = true; \n }\n else if (!checkDraw(v)) {\n std::cout &lt;&lt; &quot;DRAW :-(\\n&quot;;\n GameOver = true;\n }\n}\n</code></pre>\n<p><b>Input</b></p>\n<p>You are basically repeating yourself here, don't do that!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T17:42:47.543", "Id": "530503", "Score": "0", "body": "Thanks! althought im not familiar with oop just yet im kinda new, and i heared that it's not necessary to use classes while making simple games like this one no? i will try to rewrite it with more functions and simplify the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T18:41:11.403", "Id": "530505", "Score": "0", "body": "Cool, experimenting is the best way to learn! A logical next step would be to see if you can create a computer opponent…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T19:48:24.837", "Id": "530513", "Score": "0", "body": "i would like to know how can i do that? it requires ai stuff no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T20:44:02.407", "Id": "530526", "Score": "0", "body": "start with a simple one that picks random spaces" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T11:55:15.760", "Id": "268946", "ParentId": "268928", "Score": "3" } }, { "body": "<pre><code> for (int i = 0; i &lt; 11; i++) {\n std::cout &lt;&lt; &quot; &quot;;\n if (i == 4)\n std::cout &lt;&lt; &quot;1&quot;;\n else if (i == 7)\n std::cout &lt;&lt; &quot;2&quot;;\n else if (i == 10)\n std::cout &lt;&lt; &quot;3\\n&quot;;\n }\n</code></pre>\n<p>If I'm reading that right, it does nothing more than:<br />\n<code>cout &lt;&lt; &quot; 1 2 3\\n&quot;;</code><br />\n<em>Why</em> would you write it the way you did? Was it supposed to do something more that I'm not seeing?</p>\n<hr />\n<pre><code> if (v[val][j] == 1)\n std::cout &lt;&lt; &quot;| X &quot;;\n else if (v[val][j] == -1)\n std::cout &lt;&lt; &quot;| O &quot;;\n else\n std::cout &lt;&lt; &quot;| &quot;;\n</code></pre>\n<p>Here is an example where you are repeating way too much. The different branches are referring to <code>v[val][j]</code>, and repeat the result of sending something to <code>cout</code>, and even repeat the fact that what it sends is <code>&quot;| ? &quot;</code>. The <em>only</em> difference is what character is used for the <code>?</code>. That is, there is only <em>one character</em> different in the three different branches.</p>\n<p>This is a general thing to learn, not specific to this example.<br />\n<strong>Abstract out the thing you really want to vary.</strong><br />\nHere, you just want to print <code>&quot;| ? &quot;</code> with <code>?</code> meaning the proper character depending on another value.</p>\n<p>That should be as simple as:<br />\n<code>std::cout &lt;&lt; &quot;| &quot; &lt;&lt; mark_for(v[val][j]) &lt;&lt; ' ';</code></p>\n<p>This has <strong>decomposed</strong> the problem into a simple call to a function that maps a cell value to the character to be shown. You could write it like this:</p>\n<pre><code>char mark_for (int x)\n{\n switch (x) {\n case -1: return 'O';\n case 1 : return 'X';\n default: return ' ';\n }\n}\n</code></pre>\n<p>Note that this concentrates the logic of the actual problem into a simple function. It doesn't care where the value came from; that is, it has nothing to do with the board vector or <code>j</code>. The specific value is found by giving the parameter to the function call.</p>\n<p>So, you started out with the program decomposed into <em>input</em>, <em>logic</em>, and <em>draw</em> functions, which is good. But, you did not further decompose any of those functions into simpler steps when implementing it.</p>\n<p>Don't think of implementing a major function as a brutal thing where you grab one end and chew your way through to the end. Rather, <em>decompose</em> it into logical steps such that the function has a few number of steps that are just one level simpler than the original function.</p>\n<hr />\n<p>It does not make good sense for your board to use a vector of vectors.<br />\nYou have a fixed size for the board and have to take extra steps to set that up, since the whole point of a vector is to be variable sized and only hold what you added. The overhead of the nested vectors is significant, and requires that each row be allocated on the heap separately.</p>\n<p>Since you have a fixed size known at compile time, this is a perfect use of arrays. You can just change <code>std::vector</code> to <code>std::array</code> and get the same two-subscript behavior you want. The arrays solution will have zero overhead and not use memory indirectly but rather will store the whole thing inside the variable itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T17:44:28.773", "Id": "530504", "Score": "1", "body": "i just realised how stupid does the draw func looks lol, i will try to rewrite the code with more functions and better code. Thanks for the advices tho!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:24:11.570", "Id": "530581", "Score": "0", "body": "@ZakiMkn keep at it!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T14:11:45.437", "Id": "268950", "ParentId": "268928", "Score": "1" } }, { "body": "<h2>Binary Tic-Tac-Toe</h2>\n<p>You can greatly simplify your code by representing moves as bits.</p>\n<p>Rather than have vectors of vector and all the loops in loops and indexes needed to search for patters bit field collapse all the logic into very simple math operations.</p>\n<h2>9 bits per player</h2>\n<p>There are 9 positions so each player needs only 9 bits to represent there current moves.</p>\n<p>To set a played position add or bitwise OR the players bit values with <code>player |= 1 &lt;&lt; cell</code> where cell is a board position 0 to 8.</p>\n<p>To check is a position is free add the two player bit values and AND the result with the bit pos of the cell you want to check if <code>(!((playerO + playerX) &amp; (1 &lt;&lt; cell))) { /* cell is empty */ }</code></p>\n<h2>Bit logic</h2>\n<p>This also makes game logic much simpler as all winning moves can be represent with only 8 9bit values.</p>\n<p>Thus to check the bottom horizontal row for a win <code>if ((player &amp; 0b111000000) == 0b111000000) { /* player wins */ }</code></p>\n<p>A drawn game can be found by checking if the sum of both players move is equal to 511 (<code>0b111111111</code> or <code>0x1FF</code>)</p>\n<p>In the rewrite the bit locations from 0 to 8 represent positions on the board from top left down to bottom right</p>\n<pre><code>0|1|2 X| |O Bits.......876543210 \n-+-+- -+-+- Player X 0b101000001\n3|4|5 |O| Player O 0b000010100 \n-+-+- -+-+-\n6|7|8 X| |X\n</code></pre>\n<p>The bits are from low (bit 0) to high bit (bit 8) thus setting bit 8 is <code>0b100000000</code> or <code>0x100</code> or <code>256</code> or <code>1 &lt;&lt; 8</code></p>\n<h2>Display</h2>\n<p>To display the board you can pre define a string representing the empty board and have an array point to the position of each cell in that string.</p>\n<p>Then for each bit set in the two player bit values set the appropriate character to <code>X</code>, or <code>O</code></p>\n<h2>Input</h2>\n<p>Needing the player to enter 2 values to make a move is rather demanding, There are 9 position so ask for one of nine values. Show the player a board with all the numbered position to help if needed.</p>\n<h2>Rewrite</h2>\n<p>Using binary math and simplifying the display there is much less code.</p>\n<p>I use binary notation for some of the numbers to make it easier to read if you are not comfortable with binary. Once you get used to it these can be entered as decimal, eg the wins are <code>unsigned wins[8] {292, 146, 73, 448, 56, 7, 273, 84};</code></p>\n<pre><code>std::string movePositions = &quot;1|2|3\\n-+-+-\\n4|5|6\\n-+-+-\\n7|8|9\\n&quot;;\nstd::string board = &quot;\\n&quot;\n &quot; | | \\n&quot; // 1 3 5\n &quot;-+-+-\\n&quot;\n &quot; | | \\n&quot; // 13 15 17\n &quot;-+-+-\\n&quot;\n &quot; | | \\n\\n&quot;; // 25 27 29\nsize_t positions[9] { // 9 cells 0 - 8\n 1, 3, 5, 13, 15, 17, 25, 27, 29 // position on board for each cell 0 to 8\n}; \nunsigned wins[8] { // All wining plays\n 0b100100100, 0b010010010, 0b001001001, // vertical wins\n 0b111000000, 0b111000, 0b111, // horizontal wins\n 0b100010001, 0b1010100 // diagonal wins\n};\n\nvoid draw(unsigned plyX, unsigned plyO) {\n std::string copy = board;\n size_t i = 9;\n while (i--) {\n copy[positions[i]] = plyX &amp; 1 &lt;&lt; i ? 'X' : plyO &amp; 1 &lt;&lt; i ? 'O' : ' ';\n }\n std::cout &lt;&lt; copy;\n}\nbool isWinner(unsigned player) {\n for (auto wbits : wins) {\n if ((player &amp; wbits) == wbits) { return true; }\n }\n return false;\n}\nbool gameInPlay(unsigned plyX, unsigned plyO) {\n bool inPlay {false};\n if (isWinner(plyX)) { std::cout &lt;&lt; &quot;Player X wins.\\n&quot;; }\n else if (isWinner(plyO)) { std::cout &lt;&lt; &quot;Player O wins.\\n&quot;; }\n else if (plyX + plyO == 511) { std::cout &lt;&lt; &quot;Game is drawn.\\n&quot;; }\n else { inPlay = true; }\n return inPlay;\n}\nunsigned getInput(unsigned player, char playerSide, unsigned plyB) {\n int pMove;\n unsigned usedPositions = player + plyB;\n while (true) {\n std::cout &lt;&lt; &quot;Player &quot; &lt;&lt; playerSide &lt;&lt; &quot; Enter move option [1-9]? &quot;;\n std::cin &gt;&gt; pMove;\n if (pMove &gt;= 1 &amp;&amp; pMove &lt;= 9) {\n const unsigned bit = 1 &lt;&lt; (pMove - 1);\n if (usedPositions &amp; bit) { std::cout &lt;&lt; &quot;Position &quot; &lt;&lt; pMove &lt;&lt; &quot; is occupied.\\n&quot;; }\n else { return player + bit; }\n } else { std::cout &lt;&lt; &quot;Enter a value between [1 - 9]\\n&quot;; }\n }\n}\nvoid play() {\n unsigned moveCount{1}; // 1 X first 0 O first\n unsigned plyX{0}, plyO{0};\n std::cout &lt;&lt; movePositions;\n while (gameInPlay(plyX, plyO)) {\n if (moveCount++ % 2) { plyX = getInput(plyX, 'X', plyO); }\n else { plyO = getInput(plyO, 'O', plyX); }\n draw(plyX, plyO);\n }\n std::cout &lt;&lt; &quot;Game done!\\n&quot;;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T23:51:52.383", "Id": "269001", "ParentId": "268928", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T19:52:17.883", "Id": "268928", "Score": "2", "Tags": [ "c++", "beginner", "game", "tic-tac-toe" ], "Title": "tic-tac-toe game with a vector" }
268928
<p>I did a lot of research trying to find a React Native component which could reference its own dimensions in order to scale different elements in its style, but could not find any solid examples. I created a hook which boils a component's dimension down to its simplest, easiest to use components and this is what I cooked up:</p> <pre class="lang-js prettyprint-override"><code>import React, { Dispatch, SetStateAction } from &quot;react&quot;; import { LayoutChangeEvent } from &quot;react-native&quot;; /** * A function to be invoke when a component's layout changes; passed via the onLayout attribute. */ type OnLayoutFunc = (event: LayoutChangeEvent) =&gt; void; /** * The dimensions of a component. * */ export class ComponentDimensions { private dims: BasicDimensions; private setDims: Dispatch&lt;SetStateAction&lt;BasicDimensions&gt;&gt;; private onLayoutFunc: OnLayoutFunc; /** * Construct a {@link ComponentDimensions} object. */ constructor() { const [dims, setDims] = React.useState&lt;BasicDimensions&gt;({ w: 0, h: 0 }); this.dims = dims; this.setDims = setDims; this.onLayoutFunc = (event: LayoutChangeEvent): void =&gt; { const { width, height } = event.nativeEvent.layout; this.setDims({ w: width, h: height }); }; } /** * The component's width. * * @return {number} width in pixels. */ public w(): number { return this.dims.w; } /** * The component's height. * * @return {number} height in pixels. */ public h(): number { return this.dims.h; } /** * The function to be passed to a {@link ReactElement ReactElement's} onLayout attribute. * * @return {OnLayoutFunc} function to be passed as an onLayout attribute. */ public getOnLayoutFunc(): OnLayoutFunc { return this.onLayoutFunc; } } /** * React-Native hook to allow a component to reference its own dimensions. * * @return {ComponentDimensions} the dimensions of the component. */ export default function useDimensions(): ComponentDimensions { return new ComponentDimensions(); } /** * The layout dimensions of the component. */ type BasicDimensions = { /** * The width of the component in pixels. */ w: number; /** * The height of the component in pixels. */ h: number; }; </code></pre> <p>This hook can be used like this:</p> <pre class="lang-js prettyprint-override"><code>import React from &quot;react&quot;; import { View } from &quot;react-native&quot;; import { ReactElement } from &quot;react-native/node_modules/@types/react&quot;; import useDimensions, { ComponentDimensions } from &quot;../../hooks/useDimensions&quot;; export default function HookExample(): ReactElement { const dims: ComponentDimensions = useDimensions(); return ( &lt;View onLayout={dims.getOnLayoutFunc()} style={{ width: &quot;100%&quot;, height: &quot;100%&quot; }} &gt; {/* A red circle. */} &lt;View style={{ width: &quot;20%&quot;, height: dims.w(), borderRadius: 150, backgroundColor: &quot;red&quot;, }} &gt; &lt;/View&gt; {/* A blue rectangle. */} &lt;View style={{ width: &quot;100%&quot;, height: dims.w() / 4, backgroundColor: &quot;blue&quot;, }} &gt; &lt;/View&gt; &lt;/View&gt; ); } </code></pre> <p>I'm new to both TypeScript and React-Native, so I'd appreciate some feedback for how I can make this simpler or clean it up. Also, I don't have any intuition for performance in React, so I'd be interested in feedback about that if anyone has any.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T21:45:50.303", "Id": "268931", "Score": "1", "Tags": [ "beginner", "typescript", "jsx", "react-native" ], "Title": "Typescript React-Native Component Dimension Hook" }
268931
<p>Find shape of n-dim array that'd be formed from nested list of lists with variable lengths if we were to pad the lists to same length at each nest level. E.g.</p> <pre><code>ls = [[1], [2, 3], [4, 5, 6]] # (3, 3) because ls_padded = [[1, 0, 0], [2, 3, 0], [4, 5, 6]] </code></pre> <h4>Attempt</h4> <pre class="lang-py prettyprint-override"><code>def find_shape(seq): try: len_ = len(seq) except TypeError: return () shapes = [find_shape(subseq) for subseq in seq] return (len_,) + tuple(max(sizes) for sizes in itertools.zip_longest(*shapes, fillvalue=1)) </code></pre> <h4>Problem</h4> <p>Too slow for large arrays. Can it be done faster? <a href="https://replit.com/@OverLordGoldDra/SpryFaintCgi#main.py" rel="nofollow noreferrer">Test &amp; bench code</a>.</p> <p>Solution shouldn't require list values at final nest depth, only basic attributes (e.g. <code>len</code>), as that depth in application contains 1D arrays on GPU (and accessing values moves them back to CPU). It must work on <strong>n-dim arrays</strong>.</p> <p><strong>Exact goal</strong> is to attain such padding, but with choice of padding from left or from right. The data structure is a list of lists that's to form a 5D array, and only the final nest level contains non-lists, which are 1D arrays. First two nest levels have fixed list lengths (can directly form array), and the 1D arrays are of same length, so the only uncertainty is on 3rd and 4th dims.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T01:22:33.863", "Id": "530455", "Score": "0", "body": "Is there a reason you're seemingly rewriting [basic NumPy functionality](https://numpy.org/devdocs/reference/generated/numpy.shape.html) here? Why not use NumPy to manage your arrays? How large/layers deep are you dealing with? Could you write a class abstraction that stores the length upon construction? I can say right off the bat that `(len_,) + tuple(...)` allocates 2 unnecessary objects that just go straight to the garbage collector after the concatenation but this seems like a micro-optimization given that depth would be unlikely to be huge, I'd imagine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T16:08:26.233", "Id": "530501", "Score": "0", "body": "Given that if you know nothing about the sequence, you'll have to check every element recursively, you can't do better algorithmicly speaking. You could maybe optimize the implementation but not much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T18:56:40.187", "Id": "530506", "Score": "0", "body": "@ggorlen End goal is to create the padded n-dim array as described, except need freedom to pad from left or right. I have the full function and `find_shape` is the bottleneck, especially when ran on GPU. Numpy can only create ragged, and not on GPU; Pytorch is used. If you have something in mind for this goal, I can open a question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T01:38:15.817", "Id": "530613", "Score": "0", "body": "What do you mean with \"Solution shouldn't require list values, only basic attributes\"? You can't check a value's attributes without the value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T17:28:10.370", "Id": "530666", "Score": "0", "body": "@don'ttalkjustcode `len(x)` doesn't require knowing `x[0]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T17:34:23.767", "Id": "530668", "Score": "0", "body": "Right, but it requires knowing `x`. And you don't know whether `x` is a list until you look at it. Same for `x[0]`. You need to look at it anyway, because it could be a list. Btw, is that \"Solution shouldn't require list values\" paragraph part of the \"Problem\" section, i.e., you're saying your solution *does* have that problem, i.e., it does \"require list values\"? Or is that paragraph an epilogue to the question, not intended to describe a problem with your solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T17:48:28.820", "Id": "530669", "Score": "0", "body": "Hmm... is it guaranteed that all *numbers* are at the same depth and that there are no lists at that depth? Or could there be cases like `[1, [2, 3]]` or `[4, [], 5]`? And can there be empty lists (your `fillvalue=1` somewhat suggests \"no\")?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T18:36:28.653", "Id": "530671", "Score": "0", "body": "@don'ttalkjustcode Updated. Yes, it's guaranteed, and no empties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T19:09:33.483", "Id": "530674", "Score": "1", "body": "Ok, that allows much optimization. So it's guaranteed 5D and only third and fourth are unknown? That would also allow simpler code, and in that case it would help if your Test & bench code reflected that (that's excellent stuff, btw, I wish every question was that helpful :-), so that solutions making those assumptions would work there." } ]
[ { "body": "<p>Get the length of the longest row, then pad each row with a sufficient number of zeros.</p>\n<pre><code>from itertools import islice, repeat, chain\n\n\ndef pad(x):\n zeros = repeat(0)\n n = maximum(map(len, x))\n return [list(islice(chain(row, zeros), n)) for row in x]\n</code></pre>\n<p><code>zeros</code> is an &quot;infinite&quot; stream of 0s. It doesn't actually store them in memory, but the instance of <code>repeat</code> defines a <code>__next__</code> method that always returns 0.</p>\n<p><code>chain</code> just glues two iterators together, so <code>chain(row, zeros)</code> will first yield the elements of <code>row</code>, then elements from <code>zeros</code>.</p>\n<p><code>islice(..., n)</code> yields the first <code>n</code> elements of the given iterator. How many zeros it will yield from <code>chain(row, zeros)</code> thus depends on how long <code>row</code> is in the first place.</p>\n<p>Visually, you are constructing a sequence of infinite\nrows, then taking finite prefixes from each. That is</p>\n<pre><code>[1, 0, 0, 0, 0, 0, ... ] -&gt; [1, 0, 0]\n[2, 3, 0, 0, 0, 0, ... ] -&gt; [2, 3, 0]\n[4, 5, 6, 0, 0, 0, ... ] -&gt; [4, 5, 6]\n</code></pre>\n<p>The list comprehension then just puts each row in a single list to complete the new array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T21:23:08.560", "Id": "530609", "Score": "0", "body": "Isn't this only for 2D? I specified n-dim in opening sentence and test code, maybe I should've been more explicit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T22:38:48.123", "Id": "530610", "Score": "0", "body": "Oops, I did miss the n-dim request." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T22:45:14.923", "Id": "530611", "Score": "0", "body": "I'll upvote but keep question open - clarified" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T21:05:50.660", "Id": "268998", "ParentId": "268932", "Score": "1" } }, { "body": "<p>From your question:</p>\n<blockquote>\n<p>The data structure is a list of lists that's to form a 5D array, and only the final nest level contains non-lists, which are 1D arrays. First two nest levels have fixed list lengths (can directly form array), and the 1D arrays are of same length, so the only uncertainty is on 3rd and 4th dims.</p>\n</blockquote>\n<p>From your comment:</p>\n<blockquote>\n<p>and no empties</p>\n</blockquote>\n<p>We can make it much faster by taking advantage of that specification.</p>\n<p>Your solution walks over <em>everything</em>. Including the numbers, at the recursion leafs. Even always catching exceptions there, and <a href=\"https://docs.python.org/3/faq/design.html#how-fast-are-exceptions\" rel=\"nofollow noreferrer\">&quot;catching an exception is expensive&quot;</a></p>\n<p>Instead, for the fixed-size dimensions just take the first length, and for the others run over all their lists and take the maximum length.</p>\n<pre><code>from itertools import chain\n\ndef find_shape_new(seq):\n flat = chain.from_iterable\n return (\n len(seq),\n len(seq[0]),\n max(map(len, flat(seq))),\n max(map(len, flat(flat(seq)))),\n len(seq[0][0][0][0]),\n )\n</code></pre>\n<p>(Only partially tested, as your Test &amp; bench code doesn't adhere to your specification.)</p>\n<p>Could also be generalized, maybe like this:</p>\n<pre><code>def find_shape_new(seq, num_dims=None, fixed_dims=None):\n ...\n</code></pre>\n<p>Parameters:</p>\n<ul>\n<li><code>fixed_dims</code> would be a set naming the fixed dimensions. Like <code>{0, 1, 4}</code> or <code>{1, 2, 5}</code> for your specification above. For each fixed dimension, the function would use the <code>len(seq[0][0][0][0])</code> way, and for each non-fixed dimension, it would use the <code>max(map(len, flat(flat(seq))))</code> way.</li>\n<li><code>num_dims</code> would tell the dimensionality, e.g., for a 5D array it would be 5. If unknown, represented by <code>None</code>, you'd just keep going until you reach a number instead of a list. That would involve looking at a number, but only at one.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T21:14:29.363", "Id": "530678", "Score": "0", "body": "So basically take short route for dims 0, 1, 4 and apply a faster `find_shape_old` on the rest? It's what I had in mind but hoped there's better, though it may very well be that better isn't needed - will test this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T22:24:11.357", "Id": "530681", "Score": "0", "body": "@OverLordGoldDragon That, plus not looking at dim 5. It should be a lot better. Looking forward to your results. This is visiting almost only what needs to be visited, so I don't see how you'd hope for something better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T19:06:11.347", "Id": "530857", "Score": "0", "body": "I omitted the simplifying parts to avoid \"divide and conquer\" solutions, instead focusing on the irreducible worst-case. Perhaps exhaustive iteration is the only way, which shifts optimization to parallelization. Your answer includes things I didn't think of, and I like that it can easily target the fixed dims, so I'll take it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T20:12:53.270", "Id": "269021", "ParentId": "268932", "Score": "1" } } ]
{ "AcceptedAnswerId": "269021", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T23:35:09.490", "Id": "268932", "Score": "1", "Tags": [ "python", "array", "iteration", "nested" ], "Title": "Variable length nested list of lists pad shape" }
268932
<p>As part of a larger project, I've written the following code for interacting with <a href="https://git-annex.branchable.com/git-annex-addurl/" rel="nofollow noreferrer">git-annex's <code>addurl</code> command</a> in batch mode. <code>addurl</code> takes a series of URLs and output filepaths on stdin, and it outputs a one-line JSON object for each file when that file finishes downloading. git-annex performs the downloads asynchronously, so the order of the input need not match the order of the output, and the caller should input as many URLs as possible before reading any output. It's also necessary for UX, logging, etc. purposes that a &quot;Download completed&quot; message be printed as soon as each download is complete; thus, writing everything at once and then reading everything at once with <code>Popen.communicate()</code> is not an option. Naïvely, you would think this could be done with a basic <code>Popen</code> instance by writing all the lines to the subprocess and then reading the output line by line, but this will encounter blocking issues as soon as you exceed the pipe buffer size (which I believe is 64 kiB on Linux). Hence, I figured this was as good a time as any to finally do something with Python's asynchronous programming.</p> <p>The below code is written for Python 3.8. Aside from general advice (which is especially needed as this is my first asyncio code), key things I want to know include:</p> <ul> <li><p>Is splitting up the reading and writing into separate functions that are run at the same time with <code>asyncio.gather()</code> the best/only way to write to &amp; read from a process at once with asyncio?</p> </li> <li><p>Is asyncio even the right way to go, or is there a completely different (yet still sane, i.e., not involving constant polling) way to communicate with a process asynchronously without risking overflowing the pipe buffer that doesn't involve asyncio or threading?</p> </li> <li><p>How would I make the git-annex process terminate when the Python process receives a Cntrl-C or otherwise hits an error?</p> </li> <li><p>Is it possible to make <code>read_output()</code> into an asynchronous iterator that yields decoded <code>data</code> dicts that are then processed inside <code>download_urls()</code> instead of inside <code>read_output()</code>?</p> </li> </ul> <p>(Note: The <code>main()</code> function here is just something minimal for testing purposes; I am aware that the input it splits apart is almost the same as what <code>feed_input()</code> puts back together again, and I know it does almost nothing with the return value of <code>download_urls()</code>. The calling code for <code>download_urls()</code> in the actual codebase is much different.)</p> <pre class="lang-py prettyprint-override"><code>import argparse import asyncio import json import logging from pathlib import Path import subprocess from typing import Dict, Iterable, List, Optional, Tuple log = logging.getLogger(&quot;async_downloader&quot;) async def download_urls( repo_path: Path, urls_paths: Iterable[Tuple[str, str]], jobs: int = 10 ) -&gt; Dict[str, Optional[str]]: &quot;&quot;&quot; :param repo_path: path to a git-annex repository in which to download the files :param urls_paths: an iterable of (URL, output file path) pairs :param jobs: the number of jobs for git-annex to use for downloading :returns: a `dict` mapping output file paths to git-annex keys &quot;&quot;&quot; process = await asyncio.create_subprocess_exec( &quot;git-annex&quot;, &quot;addurl&quot;, &quot;--batch&quot;, &quot;--with-files&quot;, &quot;--jobs&quot;, str(jobs), &quot;--json&quot;, &quot;--json-error-messages&quot;, &quot;--raw&quot;, stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=repo_path, ) assert process.stdin is not None assert process.stdout is not None _, (downloaded, failures) = await asyncio.gather( feed_input(process.stdin, urls_paths), read_output(process.stdout), ) log.info(&quot;Downloaded %d files&quot;, len(downloaded)) r = await process.wait() if failures: raise RuntimeError(f&quot;{failures} files failed to download&quot;) if r != 0: raise RuntimeError(f&quot;git-annex addurl exited with return code {r}&quot;) return downloaded async def feed_input( fp: asyncio.StreamWriter, urls_paths: Iterable[Tuple[str, str]] ) -&gt; None: for url, path in urls_paths: fp.write(f&quot;{url} {path}\n&quot;.encode(&quot;utf-8&quot;)) await fp.drain() fp.close() await fp.wait_closed() async def read_output(fp: asyncio.StreamReader) -&gt; Tuple[Dict[str, Optional[str]], int]: downloaded: Dict[str, Optional[str]] = {} failures = 0 async for line in fp: data = json.loads(line) if not data[&quot;success&quot;]: log.error( &quot;%s: download failed; error messages: %r&quot;, data[&quot;file&quot;], data[&quot;error-messages&quot;], ) failures += 1 else: key = data.get(&quot;key&quot;) log.info(&quot;Finished downloading %s (key = %s)&quot;, data[&quot;file&quot;], key) downloaded[data[&quot;file&quot;]] = key return (downloaded, failures) def main() -&gt; None: parser = argparse.ArgumentParser() parser.add_argument( &quot;repo&quot;, type=Path, help=( &quot;Path to a git-annex repository; will be created if it does not&quot; &quot; already exist&quot; ), ) parser.add_argument( &quot;downloads_file&quot;, type=argparse.FileType(&quot;r&quot;, encoding=&quot;utf-8&quot;), help=&quot;File containing lines of the form '&lt;URL&gt; &lt;output file path&gt;'&quot;, ) args = parser.parse_args() logging.basicConfig( format=&quot;%(asctime)s [%(levelname)-8s] %(name)s %(message)s&quot;, datefmt=&quot;%H:%M:%S%z&quot;, level=logging.DEBUG, ) urls_paths: List[Tuple[str, str]] = [] with args.downloads_file: for line in args.downloads_file: line = line.strip() if line and not line.startswith(&quot;#&quot;): url, path = line.split(maxsplit=1) urls_paths.append((url, path)) if not args.repo.exists(): subprocess.run([&quot;git&quot;, &quot;init&quot;, args.repo], check=True) subprocess.run([&quot;git-annex&quot;, &quot;init&quot;], cwd=args.repo, check=True) downloads = asyncio.run(download_urls(args.repo, urls_paths)) subprocess.run( [&quot;git&quot;, &quot;commit&quot;, &quot;-m&quot;, f&quot;Downloaded {len(downloads)} URLs&quot;], cwd=args.repo, check=True, ) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T05:19:58.413", "Id": "531905", "Score": "0", "body": "For anyone who finds this post later: I ended up rewriting this code using [trio](https://trio.readthedocs.io/en/stable/), and I expanded it a bit into a package: https://github.com/jwodder/gamdam." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T01:35:19.987", "Id": "268933", "Score": "2", "Tags": [ "python", "python-3.x", "asynchronous", "asyncio" ], "Title": "Asynchronous line-based communication with an external program" }
268933
<p>I started out to learn more about C to learn more about low level programming and hardware and I can improve.</p> <p>It generates a random number between 1 and 4 then stores it into two variables.</p> <p>It takes in to x,y board values ranging to 1,4 in the board then if the two inputs equal the random values it gives a point and resets but if not it marks the board and takes one try away. If the amount of tries reaches 5 then it resets the board</p> <p>It's basic and meant to only have one target for each round and I did not do any error checking for ascii inputs.</p> <pre><code>/*---------#include---------*/ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;unistd.h&gt; /*---------value definitions---------*/ #define BOARD_SIZE 5 #define LOW_BOUNDS 0 #define HIGH_BOUNDS 4 #define TRIES 5 //functions void DRAW_BOARD(); int GEN_RND_ZERO(); void CLEAR_BOARD(); int I1,I2; //Iterator values char LAYOUT[BOARD_SIZE][BOARD_SIZE] = { {'X','1','2','3','4'}, {'1','o','o','o','o'}, {'2','o','o','o','o'}, {'3','o','o','o','o'}, {'4','o','o','o','o'}, }; /*-----MAIN-----*/ int main() { srand(time(NULL)); //rnd val seed unsigned short INPUT1,INPUT2; int RND1,RND2; unsigned short PNT = 0,Counter; printf(&quot;-Battleship Game-\n&quot;); sleep(2); set1: RND1 = GEN_RND_ZERO(); RND2 = GEN_RND_ZERO(); set2: printf(&quot;\n%d %d\n\n&quot;,RND1,RND2); DRAW_BOARD(); printf(&quot;\nEnter an X value: &quot;); scanf(&quot;%hu&quot;,&amp;INPUT1); printf(&quot;\nEnter a Y value: &quot;); scanf(&quot;%hu&quot;,&amp;INPUT2); //Input error check if(INPUT1 &lt;= 0 || INPUT1 &gt; 4 || INPUT2 &lt;= 0 || INPUT2 &gt; 4) { printf(&quot;\n\nInput failure\n\n&quot;); sleep(3); system(&quot;cls&quot;); goto set2; } if(INPUT1==RND1&amp;&amp;INPUT2==RND2) { PNT++; printf(&quot;\n\nPoint increase [%d]\n&quot;,PNT); CLEAR_BOARD(); sleep(3); system(&quot;cls&quot;); goto set1; } else { Counter++; printf(&quot;\n\nIncorrect\n\n&quot;); LAYOUT[INPUT1][INPUT2] = 'x'; if(Counter == TRIES) { printf(&quot;Out of tries&quot;); Counter = 0; sleep(3); system(&quot;cls&quot;); goto set1; } sleep(3); system(&quot;cls&quot;); goto set2; } } /*---------function bodys---------*/ //Draws the player board void DRAW_BOARD() { for(I1 = 0; I1&lt;BOARD_SIZE; I1++) { for(I2 = 0; I2&lt;BOARD_SIZE; I2++) { printf(&quot;%c &quot;,LAYOUT[I1][I2]); } printf(&quot;\n&quot;); } } //Replace all marked characters back to an o void CLEAR_BOARD() { for(I1 = 1; I1&lt;BOARD_SIZE; I1++) { for(I2 = 1; I2&lt;BOARD_SIZE; I2++) { LAYOUT[I1][I2] = 'o'; } printf(&quot;\n&quot;); } } //Checks if the random value generated is zero if it is then it will increment to 1 int GEN_RND_ZERO() { int temp = rand()%4; //Pure Laziness if(temp == 0) { temp++; } return temp; } </code></pre>
[]
[ { "body": "<h3>Naming conventions</h3>\n<p>There doesn't seem to be one definite naming convention for C, but there's still something to be said here.</p>\n<ul>\n<li>I haven't seen functions in <code>SCREAMING_SNAKE_CASE</code>, they are usually written in something like <code>snake_case</code> or <code>camelCase</code></li>\n<li>Your variable naming is inconsistent, as seen by the examples of <code>temp</code>, <code>PNT</code> and <code>Counter</code>. They are all integers local to a functions, so they should be named in a similar style</li>\n</ul>\n<h3>GEN_RND_ZERO</h3>\n<p>The comment above the function is misleading, as this function doesn't check anything, it generates something.<br />\nIf I understood correctly, this is supposed to generate a number between 1 and 4, used for coordinates. The method used however is wrong: <code>rand()%4</code> will only generate the numbers 0, 1, 2 and 3, and if you increment only if the result is 0, then the result will be 1, 1, 2, 3. This not only leads to the last row/column always being empty, it also leads to the first row/column being more likely to contain a target. The correct way is to use <code>rand() % 4 + 1</code>, creating the desired values 1, 2, 3, 4.</p>\n<h3>The iterators</h3>\n<p>Making the for-loop iterators global is a bad idea. They clutter up your namespace without being used somewhere outside of the loops. It may also be confusing to readers. Keep the scope of variable as small as needed! The two &quot;correct&quot; ways to declare and initialize iterators are these:</p>\n<pre><code>int i;\nfor (i = 0; i &lt; 100; i++) { //...\n</code></pre>\n<pre><code>for (int i = 0; i &lt; 100; i++) { //...\n</code></pre>\n<p>The latter one is to be preferred, but it's only possible if the compiler supports the C99 standard. Yours seems to support it, as you are able to make single line comments with <code>//</code> (unless it's a pre-C99 compiler with an extension, which is unlikely these days. You seem to be using a POSIX-compliant environment, so your compiler is most certainly a recent <code>gcc</code>. No problems here.).</p>\n<h3>Long lines</h3>\n<ul>\n<li><code>sleep(3); system(&quot;cls&quot;); goto set2;</code> should be three lines instead of one</li>\n<li><code>printf(&quot;\\nEnter an X value: &quot;); scanf(&quot;%hu&quot;,&amp;INPUT1);</code> should be two lines</li>\n</ul>\n<p>Long lines like this I find to be just as readable as multiple lines at best. Why put this on one line, when you can use multiple lines and maybe an empty line after instead?</p>\n<pre><code>//...\nsleep(3); \nsystem(&quot;cls&quot;); \ngoto set2;\n\n// ...\n\nprintf(&quot;\\nEnter an X value: &quot;); \nscanf(&quot;%hu&quot;,&amp;INPUT1);\n\nprintf(&quot;\\nEnter an Y value: &quot;); \nscanf(&quot;%hu&quot;,&amp;INPUT2);\n</code></pre>\n<h3>goto</h3>\n<p><em>[softly]</em>: Don't.</p>\n<p>Jokes aside, if you must use goto, use expressive labels. In this case, I'd suggest <code>new_game</code> for <code>set1</code> and <code>try</code> for <code>set2</code>. Then again, this can (and probably should) be rewritten to use loops instead of gotos (How, I'll leave as an exercise for the reader <code>:)</code>). gotos do have some &quot;good&quot; use though, as they are a nice way to do error handling.</p>\n<h3>DRAW_BOARD</h3>\n<p>This function should have another <code>printf(&quot;\\n&quot;);</code> outside of the outer loop. You probably don't want to print something next to the board and having to print the newline outside of DRAW_BOARD makes it hard to keep track of where to print newlines.</p>\n<h3>Idea</h3>\n<p>Why not show the total score reached on game over?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T00:22:49.600", "Id": "530530", "Score": "0", "body": "Thanks for the guidance, It helped let me more problems in my code to learn off!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T08:28:24.967", "Id": "268941", "ParentId": "268935", "Score": "3" } }, { "body": "<p><b>Portability</b></p>\n<p>The following functions are not portable: <code>sleep()</code> and <code>system(&quot;cls&quot;)</code>. I had to add this to get it to compile with MSVC</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifdef _WIN32\n#include &lt;Windows.h&gt;\n#define sleep(x) Sleep(x * 1000)\n#endif\n</code></pre>\n<p><code>system(&quot;cls&quot;);</code> will clear screen on Windows but fail on all other operating systems.</p>\n<hr>\n<b>Uninitialized variables</b>\n<p>Consider the following line:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>unsigned short PNT = 0, Counter;\n</code></pre>\n<p>Why did you give an initial value for <code>PT</code> but not for <code>Counter</code>?</p>\n<hr>\n<b>Input validation</b>\n<br>\nSee what happens if you enter a non-numeric value. The program goes into a crazy loop.\nConsider creating a function to validate your input instead of using `scanf`:\n<pre class=\"lang-cpp prettyprint-override\"><code>int readNumber(int minVal, int maxVal)\n{\nretry_input:\n char buf[BUFLEN];\n if (fgets(buf, BUFLEN, stdin) == 0)\n return -1;\n int value = strtol(buf, 0, 10);\n if (value &lt; minVal || value &gt; maxVal)\n {\n printf(&quot;Please enter a number between %d and %d: &quot;, minVal, maxVal);\n goto retry_input;\n }\n return value;\n}\n</code></pre>\n<p>And changing <code>main</code> to the following:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>printf(&quot;\\nEnter an X value: &quot;);\nINPUT1 = readNumber(1, 4);\nif (INPUT1 == -1)\n return EXIT_FAILURE;\n\nprintf(&quot;\\nEnter a Y value: &quot;); \nINPUT2 = readNumber(1, 4);\nif (INPUT2 == -1)\n return EXIT_FAILURE;\n\nif (INPUT1 == RND1 &amp;&amp; INPUT2 == RND2)\n{\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T19:14:50.430", "Id": "268993", "ParentId": "268935", "Score": "0" } } ]
{ "AcceptedAnswerId": "268941", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T04:00:01.000", "Id": "268935", "Score": "6", "Tags": [ "beginner", "c", "game", "battleship" ], "Title": "Console battleship game made in C" }
268935
<p>So I've created this Header to include in all my PHP files, and think everything works as it should for now. But since it's the first time I'm creating one, I wanted to have it reviewed just to learn from you guys.</p> <p><code>LocalStorage</code> doesn't work on stackoverflow, so to try this the example code have to be downloaded into your own pc. I have some SVG files on my pc that I use, but since I don't have access to them on stackoverflow I just copied some random URLs into my <code>scss</code> file.</p> <p>the header is mostly just a <code>menu</code> with a light/dark mode toggle (this is where localStorage come into the picture), but does this code look good, or is there any hidden problems with it?</p> <p><strong>Example code</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// check for saved 'darkModeCookie' in localStorage let darkModeCookie = localStorage.getItem('darkModeCookie'); const darkModeToggle = document.querySelector('#dark-mode-toggle'); const enableDarkMode = () =&gt; { // 1. Add the class to the body document.body.classList.add('darkmodescss'); // 2. Update darkModeCookie in localStorage localStorage.setItem('darkModeCookie', 'enabled'); } const disableDarkMode = () =&gt; { // 1. Remove the class from the body document.body.classList.remove('darkmodescss'); // 2. Update darkModeCookie in localStorage localStorage.setItem('darkModeCookie', null); } // If the user already visited and enabled darkModeCookie, start things off with it on if (darkModeCookie === 'enabled') { enableDarkMode(); } // When someone clicks the button darkModeToggle.addEventListener('click', () =&gt; { // Get their darkModeCookie setting darkModeCookie = localStorage.getItem('darkModeCookie'); // If it not current enabled, enable it if (darkModeCookie !== 'enabled') { enableDarkMode(); // If it has been enabled, turn it off } else { disableDarkMode(); } }); function menuToggle() { var x = document.getElementById("burgerMenu"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>:root { /* Static Colors*/ --clr-heading-footer: #4C5BA0; --clr-button: #4C5BA0; --clr-nav-color: #8D90A1; /* Dark Theme */ --clr-bg-dark: #2F2F35; --clr-card-bg-dark: #3A3B41; --clr-card-body-text-dark: #8D90A1; --clr-card-title-text-dark: #D3D3D9; --clr-nav-activ-color-dark: #D3D3D9; --clr-nav-hover-color-dark: #D3D3D9; --dark-moon: url("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/2048px-Instagram_icon.png") center no-repeat; --dark-hover-moon: url("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/2048px-Instagram_icon.png") center no-repeat; /* (Default) Light Theme */ --clr-bg-light: #E1E1E1; --clr-nav-activ-color-light: #3A3B41; --clr-nav-hover-color-light: #3A3B41; --light-sun: url("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/2048px-Instagram_icon.png") center no-repeat; --light-hover-sun: url("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/2048px-Instagram_icon.png") center no-repeat; /* (Default) Set Colors */ --foreground: var(--clr-bg-dark); --background: var(--clr-bg-light); --activ-mode-icon: var(--light-sun); --activ-hover-mode-icon: var(--light-hover-sun); --selected-nav-page: var(--clr-nav-activ-color-light); --hover-nav: var(--clr-nav-hover-color-light); /* (Default) Page Settings */ height: 100%; font-family: 'Montserrat'; padding: 0% 12%; } .darkmodescss { /* Used as classList.add('darkmodescss') by js/toggletheme.js Replaces the (Default) Light Theme parameters with Dark Theme */ --foreground: var(--clr-bg-light); --background: var(--clr-bg-dark); --activ-mode-icon: var(--dark-moon); --activ-hover-mode-icon: var(--dark-hover-moon); --selected-nav-page: var(--clr-nav-activ-color-dark); --hover-nav: var(--clr-nav-hover-color-dark); --clr-icon-width: var(--clr-icon-width); --clr-icon-height: var(--clr-icon-height); } body { background: var(--background); color: var(--foreground); } .logo-style { /* Logo Style */ font-style: normal; font-weight: bold; font-size: 2rem; line-height: 2.438rem; letter-spacing: 0.05em; color: #4C5BA0; } /* Navigation */ .topnav { overflow: hidden; background: none !important; align-items: center; display: flex; justify-content: space-between; } .topnav button { border: none; cursor: pointer; } .topnav a { color: var(--clr-nav-color); text-align: center; padding: 0.09rem 0.30rem; text-decoration: none; font-size: 1.063rem; } .topnav a:hover { color: var(--hover-nav); } .topnav a.active { color: var(--selected-nav-page); } .right-nav { display: flex; flex-direction: row; gap: 0.625rem; align-items: center; } .nav-icon { /* Navigation Icon Sizing - SVG Only */ width: 2em; height: 2em; padding: 0.09rem 0.15rem; margin-left: 0.5rem; margin-right: 0.5rem; } .disp_mode { /* (Default) Dark / Light Mode - Icon Handling */ background: var(--activ-mode-icon) no-repeat; } .disp_mode:hover { /* (Hover) Dark / Light Mode - Icon Handling */ background: var(--activ-hover-mode-icon) no-repeat; } .topnav-menu { /* Burger Menu Content*/ width: 100%; overflow: hidden; padding: 0.09rem 0.30rem; } .topnav-menu ul { /* Burger Menu Content*/ float: right; list-style-type: none; } .topnav-menu a { color: var(--clr-nav-color); text-align: center; padding: 0.09rem 0.30rem; text-decoration: none; font-size: 1.063rem; } .topnav-menu a:hover { color: var(--hover-nav); } .topnav-menu a.active { color: var(--selected-nav-page); } /* Navigation Burger Menu */ .line-one { width: 1.875rem; } .line-two { width: 1.875rem; } .line-three { width: 1.875rem; } .burger-menu div { width: 1.875rem; height: 0.25rem; background-color: var(--clr-nav-color); margin: 0.313rem 0; border-radius: 1.563rem; } .burger-menu { width: 1.875rem; } .burger-menu:hover div { width: 1.875rem; background-color: var(--hover-nav); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;Metrics&lt;/title&gt; &lt;link href="https://fonts.googleapis.com/css?family=Montserrat:600" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;div class="topnav"&gt; &lt;div class="left-nav"&gt; &lt;a href="#home"&gt;&lt;p class="logo-style"&gt;Metrics&lt;/p&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="right-nav"&gt; &lt;a href="#home" class="active"&gt;Home&lt;/a&gt; &lt;a href="#archives"&gt;Archives&lt;/a&gt; &lt;a href="#coverage"&gt;Coverage&lt;/a&gt; &lt;button type="button" class="dark-mode-toggle disp_mode nav-icon" id="dark-mode-toggle"&gt;&lt;/button&gt; &lt;a href="#burger-menu" class="burger-menu" onclick="menuToggle()"&gt; &lt;div class="line-one"&gt;&lt;/div&gt; &lt;div class="line-two"&gt;&lt;/div&gt; &lt;div class="line-three"&gt;&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Burger Menu Hidden By Default Untill menuToggle() is activated --&gt; &lt;div class="topnav-menu" id="burgerMenu" style="display: none;"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#item1"&gt;item1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#item2"&gt;item2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#item3"&gt;item3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/header&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T06:57:27.033", "Id": "268939", "Score": "0", "Tags": [ "javascript", "html", "css" ], "Title": "Creation of a header file" }
268939
<p>I am coding a Splay Tree class in C++. I am looking for code review.</p> <p>Currently, my Splay Tree class has search and rotate function.</p> <p>I feel that I'm doing things overcomplicated.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;regex&gt; using namespace std; class TreeNode { public: int key; TreeNode* left = nullptr; TreeNode* right = nullptr; TreeNode(int key) { this-&gt;key = key; } }; class SplayTree { public: SplayTree() { // This is temporary, will refactor later root = newNode(10); root-&gt;right = newNode(15); root-&gt;right-&gt;right = newNode(16); root-&gt;right-&gt;right-&gt;right = newNode(20); root-&gt;right-&gt;right-&gt;right-&gt;right = newNode(21); root-&gt;right-&gt;right-&gt;right-&gt;right-&gt;right = newNode(22); }; ~SplayTree() {}; TreeNode* newNode(int key) { TreeNode* Node = new TreeNode(key); return (Node); } TreeNode* rightRotate(TreeNode* x) { TreeNode* y = x-&gt;left; x-&gt;left = y-&gt;right; y-&gt;right = x; return y; } TreeNode* leftRotate(TreeNode* x) { TreeNode* y = x-&gt;right; x-&gt;right = y-&gt;left; y-&gt;left = x; return y; } void splay(int key) { if (this-&gt;root == nullptr) return; this-&gt;root = splaySub(this-&gt;root, key); // Odd edge if (this-&gt;root-&gt;key != key) this-&gt;root = (key &lt; this-&gt;root-&gt;key) ? rightRotate(this-&gt;root) : leftRotate(this-&gt;root); } void search(int key) { splay(key); } void preOrder() { preOrder(this-&gt;root); } private: void preOrder(TreeNode* root) { if (root != nullptr) { cout &lt;&lt; root-&gt;key &lt;&lt; &quot; &quot;; preOrder(root-&gt;left); preOrder(root-&gt;right); } } TreeNode* splaySub(TreeNode* root, int key) { if (root-&gt;key == key) return root; // Code deal with root-&gt;left if (key &lt; root-&gt;key) { // Not found. Return last accessed node. Do as if we looked for current node's key if (root-&gt;left == nullptr) { key = root-&gt;key; // Modifies the outer-scoped variable return root; } root-&gt;left = splaySub(root-&gt;left, key); // Check if return path is odd if (root-&gt;left-&gt;key == key) return root; // Apply a double rotation, top-down: root = (key &lt; root-&gt;key) ? rightRotate(root) : leftRotate(root); return root = (key &lt; root-&gt;key) ? rightRotate(root) : leftRotate(root); } // Code deal with root-&gt;right else { if (root-&gt;right == nullptr) { key = root-&gt;key; return root; } root-&gt;right = splaySub(root-&gt;right, key); if (root-&gt;right-&gt;key == key) return root; root = (key &lt; root-&gt;key) ? rightRotate(root) : leftRotate(root); return root = (key &lt; root-&gt;key) ? rightRotate(root) : leftRotate(root); } } TreeNode* root = nullptr; }; int main() { SplayTree Tree = SplayTree(); Tree.search(20); Tree.preOrder(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T02:01:00.107", "Id": "530531", "Score": "0", "body": "`key = root->key; // Modifies the outer-scoped variable` does it?!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:43:43.460", "Id": "530548", "Score": "0", "body": "(I think the assignment to a parameter only has a chance to modify an outside-function value only if that parameter was passed by/as a reference. (Then again, I didn't code C++ *in anger* for two decades.))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:45:14.767", "Id": "530549", "Score": "0", "body": "I do in on purpose" } ]
[ { "body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"nofollow noreferrer\">SF.7</a>.)</p>\n<hr />\n<pre><code> TreeNode(int key) {\n this-&gt;key = key;\n }\n</code></pre>\n<p>Use the base/member init list in your constructor, rather than assigning values in the body. So:</p>\n<pre><code> TreeNode(int key)\n : key{key} {}\n</code></pre>\n<hr />\n<p>Where's the destructor, copy constructor, etc? Remember the <strong>rule of three</strong>.</p>\n<p>It looks like you don't have any way of removing nodes at all, and leak memory if you discard the entire tree when you are done with it.</p>\n<hr />\n<p><code> if (this-&gt;root == nullptr) return;</code></p>\n<p>Don't do explicit comparisons against <code>nullptr</code>. Don't write <code>this-&gt;</code> everywhere either! This line would just be: <code>if (!root) return;</code></p>\n<hr />\n<pre><code>TreeNode* newNode(int key)\n {\n TreeNode* Node = new TreeNode(key);\n return (Node);\n }\n</code></pre>\n<p>What's the point of that? I think you can rely on the constructor doing what it's supposed to and not need to make another function to create an instance of an object.</p>\n<hr />\n<pre><code>cout &lt;&lt; root-&gt;key &lt;&lt; &quot; &quot;;\n</code></pre>\n<p>Don't use a string where a char will do. Use <code>' '</code> here instead of <code>&quot; &quot;</code>.</p>\n<hr />\n<p>This code is duplicated:</p>\n<pre><code> root = (key &lt; root-&gt;key) ? rightRotate(root) : leftRotate(root);\n return root = (key &lt; root-&gt;key) ? rightRotate(root) : leftRotate(root);\n</code></pre>\n<p>Try and make it back on the common branch rather than on both sides of a conditional statement, or stick it into a helper function.</p>\n<p>Just looking at the code, I wonder if there is some subtle difference ... or were they supposed to be mirror images? It's actually a lot of work and cognitive overhead to deal with duplication like this.</p>\n<h1>P.S.</h1>\n<p>Otherwise, I think you're doing good. Keep it up! Your comments are meaningful and aid in reading the code.</p>\n<h1>mirroring code</h1>\n<blockquote>\n<p>Is there any way I can dynamically assign left or right to root? Like root[side] with side = &quot;left&quot;/&quot;right&quot;</p>\n</blockquote>\n<p>Yes. I've done this on a data structure that had a kind of <a href=\"https://en.wikipedia.org/wiki/AVL_tree\" rel=\"nofollow noreferrer\">AVL tree</a> at its heart. I only needed one copy of each algorithm, such as rotating. It could rotate to the left or rotate to the right with the same code. This has a benefit in coverage testing too.</p>\n<p>The key is to make the two different fields (left pointer and right pointer) an array of two things so they can be indexed.</p>\n<pre><code> Treenode* children[2]; // left and right\n</code></pre>\n<p>Then, you can use an enumeration for <code>Left=0</code> and <code>Right=1</code>. Now each function can take another parameter, say:</p>\n<pre><code>TreeNode* rightRotate (TreeNode* x, direction dir)\n{\n</code></pre>\n<p>The first thing you do is set up <em>local</em> meanings for &quot;this way&quot; and &quot;the other way&quot;. I used <em>S</em> and <em>D</em> as the two logical directions (for <em>sinistral</em> and <em>dexteral</em>) instead of switching the meanings of the actual Left and Right locally.</p>\n<pre><code> const direction S = dir; // the way I'm going\n const direction S = 1-dir; // the other way\n</code></pre>\n<p>I'm not showing the needed casting for &quot;strong&quot; types, just the underlying math that <code>1-dir</code> is always the other one. In real code, this was a separate helper function that's used everywhere I have mirroring-enabled code.</p>\n<p>Then your code becomes:</p>\n<pre><code> TreeNode* y = x-&gt;children[S];\n x-&gt;children[S] = y-&gt;children[D];\n y-&gt;children[D] = x;\n return y;\n}\n</code></pre>\n<p>That is, change <code>left</code> to <code>children[S]</code> and <code>right</code> to <code>children[D]</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T06:19:44.517", "Id": "530537", "Score": "0", "body": "Thanks. It's a lot of insight" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T06:47:31.220", "Id": "530539", "Score": "0", "body": "Is there any way I can dynamically assign left or right to root? Like root[side] with side = \"left\"/\"right\" (JavaScript can do this)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:06:58.010", "Id": "530573", "Score": "1", "body": "@TanNguyen I updated my post to answer this. You can also look into _pointers to members_ to do what you can with JavaScript. Though the way I showed is simple and generates very efficient code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T15:57:28.633", "Id": "268957", "ParentId": "268940", "Score": "1" } }, { "body": "<p>I &quot;feel&quot; symmetries could be leveraged using references.</p>\n<pre><code>// to do: doc comment, decent variable names, access, const correctness\nTreeNode* rotate(TreeNode* x, TreeNode *&amp;y, TreeNode *&amp;y_child)\n{\n const TreeNode* r = y;\n y = y_child;\n y_child = x;\n return r;\n}\n\nTreeNode* rightRotate(TreeNode* x)\n{\n return rotate(x, x-&gt;left, x-&gt;left-&gt;right);\n}\n\nTreeNode* leftRotate(TreeNode* x)\n{\n return rotate(x, x-&gt;right, x-&gt;right-&gt;left);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T02:22:24.963", "Id": "530533", "Score": "0", "body": "(Um. Complicated. ?) Any takers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T06:10:38.343", "Id": "530536", "Score": "0", "body": "No. It's okay. I'm thinking" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T06:47:27.767", "Id": "530538", "Score": "0", "body": "Is there any way I can dynamically assign left or right to root? Like root[side] with side = \"left\"/\"right\" (JavaScript can do this)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T08:35:09.477", "Id": "530553", "Score": "0", "body": "(as in *dynamically add an object property*? No. That's easy in *prototypal* object modelling. I remember \"morphing\" Python objects.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:07:48.640", "Id": "530574", "Score": "0", "body": "I added details for this to my Answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:11:04.990", "Id": "530575", "Score": "0", "body": "(@JDługosz Coincidentally, AVL is where I used Python object morphing (left-high, balanced, right-high). No need to waste one or even *two* bits in every node, is there?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:13:57.283", "Id": "530576", "Score": "0", "body": "@greybeard I don't know what you are referring to with regards to wasting bits in each node." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:16:01.843", "Id": "530578", "Score": "0", "body": "(@JDługosz: traditionally, two \"balance flags\" are used with every \"AVL node\".)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:18:47.433", "Id": "530579", "Score": "0", "body": "@greybeard so you used the _type_ to represent which state it was in? Clever. If every object has the overhead of metadata (unlike C++, where if you don't have any virtual functions you get just the plain structure members you declared) that would save space." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T02:04:31.600", "Id": "268969", "ParentId": "268940", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T07:30:29.013", "Id": "268940", "Score": "2", "Tags": [ "c++", "algorithm" ], "Title": "C++ Splay Tree implementation" }
268940
<p>Not sure if I have gone over board with this or if I have even approached it correctly.</p> <p>Basic I wanted to created classes which fulfilled the following:</p> <ul> <li>Single class that can be used to create a connection to either a known Redis or Mysql DB</li> <li>Decoupled classes for DI (Eventually)</li> <li>PHP7.4 with strict=1</li> </ul> <p>I've attempted to use both strategy patterns and Factory patterns but unsure if the factories are really needed.</p> <p><strong>E.g. of usage</strong></p> <pre><code>&lt;?php include '../vendor/autoload.php'; use Jc\Omni\Storage\MysqlConnectorFactory; use Jc\Omni\Storage\RedisConnectorFactory; use Jc\Omni\Storage\OmniStorage; ?&gt;&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en-gb&quot;&gt; &lt;head&gt; &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot; /&gt; &lt;title&gt;Test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt; &lt;?php // OmniStorage $conn1 = OmniStorage::getConnection(OmniStorage::MYSQL); echo '$conn1: '.$conn1-&gt;gettype().'&lt;br&gt;'; $conn2 = OmniStorage::getConnection(OmniStorage::REDIS); echo '$conn2: '.$conn2-&gt;gettype().'&lt;br&gt;'; ?&gt; &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>OmniStorage</strong></p> <pre><code>&lt;?php declare(strict_types=1); namespace Jc\Omni\Storage; class OmniStorage { const REDIS = 'redis'; const MYSQL = 'mysql'; private function __constructor(string $connType): void { } public static function getConnection(string $connType): ?ConnectorInterface { if ($connType == self::MYSQL) return MysqlConnectorFactory::create(); if ($connType == self::REDIS) return RedisConnectorFactory::create(); return null; } } </code></pre> <p><strong>MysqlConnectorFactory</strong></p> <pre><code>&lt;?php declare(strict_types=1); namespace Jc\Omni\Storage; class MysqlConnectorFactory { public static function create(): ?ConnectorInterface { return (new MySqlConnector())??null; } } </code></pre> <p><strong>RedisConnectorFactory</strong></p> <pre><code>&lt;?php declare(strict_types=1); namespace Jc\Omni\Storage; class RedisConnectorFactory { public static function create(): ?ConnectorInterface { return (new RedisConnector())??null; } } </code></pre> <p><strong>MySqlConnector</strong></p> <pre><code>&lt;?php declare(strict_types=1); namespace Jc\Omni\Storage; use mysqli; final class MySqlConnector implements ConnectorInterface { public ?mysqli $connection; public string $connType = 'MYSQL'; public function __construct() { } function connect() { } public function gettype(): string { return $this-&gt;connType; } } </code></pre> <p><strong>RedisConnector</strong></p> <pre><code> &lt;?php declare(strict_types=1); namespace Jc\Omni\Storage; use redis; final class RedisConnector implements ConnectorInterface { public ?redis $connection; public string $connType ='REDIS'; public function __construct(){ } function connect(){ } public function gettype(): string { return $this-&gt;connType; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T14:44:51.643", "Id": "268951", "Score": "0", "Tags": [ "design-patterns", "php7" ], "Title": "PHP Class(es) for setting up DB adaptor" }
268951
<p><strong>I have attempted [and made one] function to convert string to integer and catch errors in pure c</strong></p> <p><em><strong>Working method</strong></em></p> <p>The whole working method is present in code itself</p> <p><em>The header file</em></p> <p><em>The str2num.h here:-</em></p> <pre class="lang-c prettyprint-override"><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; int StrNumErr = 0; int str2numErrCheck(){ if(StrNumErr&gt;0){ int ab = StrNumErr; StrNumErr = 0; return ab; }else{ return 0; } } char * __restrict__ str2numErrText(int errnum){ if(errnum==22){ return &quot;Alphabets or Symbols present in the String&quot;; } else if(errnum==23){ return &quot;Two Points in one number Error&quot;; } else if(errnum==24){ return &quot;Minus between two numbers Error&quot;; }else{ return &quot;&quot;; } } void invalid_argument(const char * __restrict__ _err,int errcode) { StrNumErr = errcode; } float power(float a,int b) //can also produce results to invalid powers [ex:- 0 to power 0 returns -1 [means invalid]] //also can return negative powers [ex:- 2 to power -3 = 0.123] //also calculates value for float numbers but power should be integer not **float** { if(a==0 &amp;&amp; b==0){ return -1; } if(b==0){ return 1; } if(b&lt;0){ float c=a; for(int i=0;i&lt;-(b-1);i++) { c/=a; } return c; } float c=a; for(int i=0;i&lt;b-1;i++) { c*=a; } return c; } float str2num_C(const char * __restrict__ _string) { /* -=-=-=- Presenting the Str2Num_C Function -=-=-=-=-=- Advantages =&gt; =&gt; Can return float numbers =&gt; Can return negative numbers =&gt; Also throws error if the string is not a number =&gt; Can execute Fast =&gt; Also, The code is pretty straightforward -=-=- How does this function Work -=-=- Basically, it takes the string and loops around all the charachters it checks if the charachter is '.' or '-' or among '0','1','2','3','4','5','6','7','8','9' if the charachter is none of the above it throws error because if it is none of above then alphabet or symbol is used! if it finds '.' it checks if already point has been found or not if yes =&gt; it throws error two points in number if not it will make point=1[means point has been found] and pointplace to 1 if it finds '-', it makes _minus = -1 which is multiplied at last to return minus number, ex- &quot;-98&quot; returns 98 * minus = 98 * -1 = -98 also however if the minus is in between numbers it throws an error ex- &quot;98-67&quot; throws error For all numbers it finds (0-9) as num if it is first number, make num=number else it will multiply number by 10 and add the num for ex- 98 num = 9 num = num * 10 + 8 [ which is 90 + 8 = 98 ] */ int _strlen = strlen(_string); int _point=0; int _minus = 1; int _pointplace=0; char _curchar; float _return_num; int _numfound = 0; for(int _var=0;_var&lt;_strlen;_var++) { //store current charachter _curchar = _string[_var]; if(_curchar=='.'){ //if the value contains point! if(_point==1){ //checking if already point is defined //two points in one number huh?&gt; //error here :D invalid_argument(&quot;Str2Num_C Error: Two Points in one number&quot;,23); return 0; } //makes that _point is 1 [i.e point is true] //and the pointplace is 1 like in 9.86 ['8' is in 1st pointplace] _point=1; _pointplace=1; } else if(_curchar=='-'){ //if the value contains minus //check if its first position like &quot;-98&quot; //if not then its something like &quot;34-56&quot; but that in whole is not number so throw error if(_var==0){ _minus=-1; }else{ invalid_argument(&quot;Str2Num_C Error: Minus in between numbers\n&quot;,24); return 0; } } else if(_curchar=='0'){ //if char is 0! if(!(_numfound==1)){ _numfound=1; _return_num = 0; } else if(_point==1){ _return_num+= 0/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=0; } } else if(_curchar=='1'){ //if char is 1! if(!(_numfound==1)){ _numfound=1; _return_num = 1; } else if(_point==1){ _return_num+= 1/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=1; } } else if(_curchar=='2'){ //if char is 2! if(!(_numfound==1)){ _numfound=1; _return_num = 2; } else if(_point==1){ _return_num+= 2/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=2; } } else if(_curchar=='3'){ //if char is 3! if(!(_numfound==1)){ _numfound=1; _return_num = 3; } else if(_point==1){ _return_num+= 3/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=3; } } else if(_curchar=='4'){ //if char is 4! if(!(_numfound==1)){ _numfound=1; _return_num = 4; } else if(_point==1){ _return_num+= 4/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=4; } } else if(_curchar=='5'){ //if char is 5! if(!(_numfound==1)){ _numfound=1; _return_num = 5; } else if(_point==1){ _return_num+= 5/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=5; } } else if(_curchar=='6'){ //if char is 6! if(!(_numfound==1)){ _numfound=1; _return_num = 6; } else if(_point==1){ _return_num+= 6/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=6; } } else if(_curchar=='7'){ //if char is 7! if(!(_numfound==1)){ _numfound=1; _return_num = 7; } else if(_point==1){ _return_num+= 7/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=7; } } else if(_curchar=='8'){ //if char is 8! if(!(_numfound==1)){ _numfound=1; _return_num = 8; } else if(_point==1){ _return_num+= 8/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=8; } } else if(_curchar=='9'){ //if char is 9! if(!(_numfound==1)){ _numfound=1; _return_num = 9; } else if(_point==1){ _return_num+= 9/(power(10,_pointplace)); _pointplace+=1; } else{ _return_num*=10; _return_num+=9; } }else{ invalid_argument(&quot;The string contains alphabetic charachters or symbol&quot;,22); return 0; } } return _return_num*_minus; } </code></pre> <p><strong>Example usage:</strong></p> <pre class="lang-c prettyprint-override"><code>#include&lt;stdio.h&gt; #include&lt;string.h&gt; #include&lt;stdlib.h&gt; #include &quot;str2num.h&quot; int main() { //declaring variables char string[20]; float num; int err; //input a string printf(&quot;Enter a number: &quot;); gets(string); //convert into number and add 2 num = str2num_C(string); num+=2; //check errors err = str2numErrCheck(); if(err&gt;0){ printf(&quot;ERROR: %s&quot;,str2numErrText(err)); } else{ printf(&quot;Number + 2 is: %f&quot;,num); } } </code></pre> <p><strong>EDIT: the invalid_argument() also has a field to give string to it because when converting this code to c++ you just have to add throw and remove the numbers</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T17:02:36.627", "Id": "530599", "Score": "0", "body": "Hmmm, \"Convert string to integer and catch errors\" and test code uses [`gets()`](https://stackoverflow.com/q/1694036/2410359)???" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T03:01:38.947", "Id": "530614", "Score": "0", "body": "@chux i didnt know that - i am new to c-programming as i am :l" } ]
[ { "body": "<p>There are a few things about your code that can be improved.</p>\n<h2>Style</h2>\n<p>You obviously <em>have</em> a style, which is to the good. But it's one I have some problems with:</p>\n<ol>\n<li><p>Spaces. I don't know why you are so chary with your horizontal space, but I suggest you amend your style to favor more white space rather than less. Many operations, both manual and automated, benefit from having spaces separating tokens. For example, &quot;filling&quot; text (to break code at a max. width boundary), transposing words (changing <code>if</code> for <code>else</code>), searching for and/or replacing identifiers all are technically possible without spaces, but are much easier when spaces are present.</p>\n</li>\n<li><p>Underscores. Leading underscores are not universally reserved by the standard. But entire classes of them are reserved, so your habit suffers from (a) making readers uncomfortable, and (b) being harder to type. I don't know of any keyboard where the underscore is easy to type by default. (I have modified my own editor to support SHIFT+SPACE as underscore. But this is still a shifted key.) On a US keyboard, a leading underscore by default will displace one or both hands <em>just as you begin typing the name.</em> I suggest you adopt a convention that lets you create short, simple, and <em>fast</em> names, especially for temporaries and loop variables.</p>\n</li>\n<li><p>Organization. Header files are for declarations, types, constants, and inline definitions that cannot be placed elsewhere. You are including your entire source code in the header, which is likely to cause problems in the future if more than one file includes the header and creates parallel definitions of the same functions in different object files. I suggest you partition your code so that declarations remain in the header while function <em>definitions</em> are in a separate <code>.c</code> file.</p>\n</li>\n</ol>\n<h2>Implementation</h2>\n<p>There are some problems with your implementation, as well:</p>\n<ol>\n<li><p>Your code returns a <code>float</code>. That is the smallest of the standard floating point values, which means you cannot usefully parse wider floating point values from input. I believe it would be better to return a wider value and then narrow it down into a smaller storage unit if need be. Return a <code>double</code> or something wider, then let the user convert it down to <code>float</code> if they wish.</p>\n</li>\n<li><p>Your use of the <code>__restrict__</code> keyword is inappropriate. First, because it is an implementation extension -- the correct keyword is <code>restrict</code>. And second because applying it to the return value of a function makes little sense. I could easily call your function twice and violate the restrict contract, which would lead to undefined behavior.</p>\n</li>\n<li><p>You should mark string literals as <code>const char *</code> unless you have a compelling reason not to. (Which you do not!)</p>\n</li>\n<li><p>Floating point values already have a built-in &quot;bogus&quot; value. Using <code>0</code> as some kind of &quot;null float&quot; is nonsensical. Instead, use <code>NAN</code> from <code>math.h</code> and let the user check with <code>isnan()</code>.</p>\n</li>\n<li><p>You are accumulating floating point errors all over the place. Every time you perform a floating point operation, you introduce a source of error. Every addition, every division, is a place where one of many discrepancies can find their way into your results. I suggest you rely more on the standard functions, like <code>pow()</code> (or <code>powf()</code> for floats) and less on hand-rolled code. Also, consider parsing your values as integers and only converting them to floats once you have finished parsing the digits successfully. (Something like &quot;12.34&quot; -&gt; whole_part=12, frac_part=34, frac_div=100, then when finished do <code>result = whole_part + (float)frac_part / frac_div</code>)</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T04:31:27.607", "Id": "530534", "Score": "0", "body": "The reason behind my horizontal space is because i focus to write code then making them _stylish_ i hope that makes sense _and saves time?_. anyways your suggestion is great! i am newbie in here as well as in c programming. i looked up some tutorials and started coding so obviously there won't be good codes :) but thanx for a reveiw!\n\ni use underscores for function variables so i dont get confused them with the global variables!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T04:41:31.020", "Id": "530535", "Score": "0", "body": "Hey @aghast can u make point 2 clear in implementation where exactly [ or which function ] can u call to make the reult undesired?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T08:26:52.000", "Id": "530552", "Score": "0", "body": "if i was to enter only restrict it would generate error please elaborate your point 2 in implementation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T13:12:24.273", "Id": "530569", "Score": "0", "body": "@pear The `restrict` keyword is a contract between the code author (you) and the compiler. It guarantees that if a `restrict`ed pointer references an object, the only references to that object will be via the `restrict`ed pointer -- there are no aliases to the object through other pointers. If I call `a = str2numErrText(22);` and also call `b = str2numErrText(22);` then I have violated the `restrict` contract and have two unrelated pointers to the same data. As soon as I modify through one of the pointers (which you don't want me to do, but the result is not `const`), there is UB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T13:15:44.500", "Id": "530570", "Score": "1", "body": "@pear It sounds like you are using `gcc` (since I think `__restrict__` is a gcc-ism) and maybe you are using it in C89 mode? Since `restrict` is a C99 keyword, it should be valid if you use any modern standard. I'll suggest you use the latest standard you can get away with. If you have to use C89, then use `#ifdef / #define / #endif` to write a `restrict` macro that expands to `__restrict__`. (Better still, don't use `restrict` at all if it's not useful.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T13:20:53.463", "Id": "530571", "Score": "0", "body": "@adghast according to my editor:\n the compiler i m using is: TDM-GCC 9.2.0 64-bit-release. I have no idea what it is and i am using dev c++" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T17:29:06.053", "Id": "268960", "ParentId": "268952", "Score": "3" } }, { "body": "<h3>Repeated code</h3>\n<p>You do the following once for every possible digit:</p>\n<pre><code>if(_curchar=='x'){\n //if char is 0!\n if(!(_numfound==1)){\n _numfound=1;\n _return_num = x;\n }\n else if(_point==1){\n _return_num+= x/(power(10,_pointplace));\n _pointplace+=1;\n }\n else{\n _return_num*=10;\n _return_num+=x;\n }\n}\n</code></pre>\n<p>Unless I overlooked something, this could very well be replaced with a general approach:</p>\n<pre><code>// get int val of character. this is a quick-and-dirty way and may not work with non-ascii strings!\nint char_val = _curchar - '0';\n\nif(!(_numfound==1)){\n _numfound=1;\n _return_num = char_val; \n}\nelse if(_point==1){\n _return_num+= char_val/(power(10,_pointplace));\n _pointplace+=1;\n}\nelse{\n _return_num*=10;\n _return_num+=char_val;\n}\n\n</code></pre>\n<p>Now you won't have to do a bunch of <code>else if</code>s as this works for every valid numeric digit. For the latter, this may be checked with a condition between the digit conversion and the check for <code>.</code> and <code>-</code>:</p>\n<pre><code>if (_curchar &lt; '0' || _curchar &gt; '9') {\n invalid_argument(&quot;The string contains alphabetic charachters or symbol&quot;,22);\n}\n</code></pre>\n<h3>invalid_argument</h3>\n<p>Passing a string you never use a function is pointless, and only setting a global error code could very well be done directly inside the function.</p>\n<h3>Error codes</h3>\n<p>Magic number alert! Your error codes should either be a <code>const int</code> or be <code>#define</code>d. It's easier to see what happens if set your error var to, say <code>ERR_INV_CHAR</code> instead of <code>22</code>. This makes things easier to chage as well. The reason that functions like <code>strerror</code> or <code>str2numErrText</code> exist is a similar reason: the user doesn't have to look up &quot;error code 22&quot; but instead can just <code>str2numErrText(22)</code> and get something useful.</p>\n<h3>C booleans</h3>\n<p>You use some vars as a boolean flag (e.g. <code>_point</code>). They should be renamed to something like <code>_point_found</code> to express this usage. Secondly, C evaluates 0 as false and 1 (or every other int for that matter) as true. This means that you can do the follwing:</p>\n<pre><code>if (_point_found == 1) // feels like writing &quot;if _point_found == True&quot; in python. \nif (_point_found) // good\n</code></pre>\n<p>And if you want to go the distance, import <code>&lt;stdbool.h&gt;</code> and do this:</p>\n<pre><code>int _point_found = 1; // &quot;classic&quot; way\nbool _point_found = true; // with stdbool.h\n</code></pre>\n<h3>Correct use of headers</h3>\n<p>As @aghast pointed out, this is not how you use headers. I'll provide an example to illustrate further:</p>\n<pre><code>// str2num.h\n////////////////////\n\n// include guard to stop multiple inclusions from different files.\n#ifndef STR2NUN_INCL\n#define STR2NUN_INCL\n\nconst int ERR_INV_CHAR;\n\nint str2numErrCheck();\nvoid invalid_argument(const char * __restrict__ _err,int errcode);\n\n#endif\n</code></pre>\n<pre><code>// str2num.c\n////////////////////\n\n#include &quot;str2num.h&quot;\n\nconst int ERR_INV_CHAR = 22;\n\nint StrNumErr = 0;\n\nint str2numErrCheck(){\n if(StrNumErr&gt;0){\n int ab = StrNumErr;\n StrNumErr = 0;\n return ab;\n }else{\n return 0;\n }\n}\n\nvoid invalid_argument(const char * __restrict__ _err,int errcode)\n{\n StrNumErr = errcode;\n}\n</code></pre>\n<p>You now keep the implementation in <code>str2num.c</code> and include <code>str2num.h</code> as you've done before.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T12:20:59.090", "Id": "530563", "Score": "0", "body": "I am new to #ifdef and #ifndef stuff! this is perfect now i am understanding about it was expecting yours like answer. I know @aghast is also correct but i didnt understood what he was trying to say [ I am new to c so..... ] You made me crystal clear thanx!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T12:27:17.870", "Id": "530564", "Score": "0", "body": "would you mind if you tell me how do i make the header file such a way that in main() program i can use functions and i dont have to create it into another file.\nIf u dont understand what i am trying to say:- 1) i want the header to be used in different files , 2) i dont want to repeteadly create invalid_argument() and strErr functions, 3) i want the functions to be working inside any file with minimal code and all the stuff should be stored inside other things _probably header files?_ But i have to say **Repetition is gone thx** _and i also work with python how did u guess? :O_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T12:43:36.063", "Id": "530565", "Score": "0", "body": "Magic number alert! that really got me i could've done that, my mind :|" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T12:57:19.543", "Id": "530566", "Score": "0", "body": "1) You can. Whereever a method from str2num.c is needed, include str2num.h and it'll work. 2) You don't have to...? Just the function declaration in the .h and the function implementation in the .c file. That's one line you'll duplicate. 3) Again, they should work everywhere. What do you mean with \"stuff\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T12:58:37.763", "Id": "530567", "Score": "0", "body": "Also I used python for no reason in that example, but it's the only language I know that uses underscores for internals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T13:08:10.027", "Id": "530568", "Score": "0", "body": "the _stuff_ relates to all the functions currently present in my header file in my question\n. So you're telling me that i just can use `#include \"str2num.h\"` and all the functions would load automatically which are stored in :str2num.c\" while accessing it from another file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:14:10.770", "Id": "530577", "Score": "0", "body": "Yes, such is the magic of the compiler. I'm not too sure that my understanding of how this part works is correct atm, I'll do some research and add another comment when I know" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T03:11:29.787", "Id": "530615", "Score": "0", "body": "it didnt it generated error :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T03:11:44.073", "Id": "530616", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/130537/discussion-between-pear-and-mindoverflow)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:25:26.923", "Id": "530661", "Score": "0", "body": "If you are asking for how to make a \"header-only\" library, note that C++ has had features added/improved specifically to facilitate this. Generally, declare the function `inline` to allow it to be in a header. Global variables will be more of an issue." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T10:24:03.473", "Id": "268978", "ParentId": "268952", "Score": "3" } }, { "body": "<p>Firstly, this code doesn't do what is described. It converts a string to <em>float</em>, not <em>integer</em>.</p>\n<hr />\n<p>Your header file should contain only the public declarations. Put the implementation into a normal source file.</p>\n<hr />\n<blockquote>\n<pre><code>int StrNumErr = 0;\n</code></pre>\n</blockquote>\n<p>Avoid global variables - they make it hard to reason about code, and can inhibit concurrent use of the functions.</p>\n<hr />\n<blockquote>\n<pre><code>int str2numErrCheck(){\n</code></pre>\n</blockquote>\n<p>Should be declared as taking no arguments, i.e. <code>int str2numErrCheck(void)</code>. And we're not allowed to give it a name beginning with <code>str</code> - it needs to be changed to one that's not reserved for <code>&lt;string.h&gt;</code>.</p>\n<blockquote>\n<pre><code> if(StrNumErr&gt;0){\n int ab = StrNumErr;\n StrNumErr = 0;\n return ab;\n }else{\n return 0;\n }\n}\n</code></pre>\n</blockquote>\n<p>As we never set <code>StrNumErr</code> to a negative value, and both branches have the same observable behaviour for <code>StrNumErr==0</code>, then we don't need the test. We could do with a better variable name than <code>ab</code>, too.</p>\n<hr />\n<blockquote>\n<pre><code>char * __restrict__ str2numErrText(int errnum){\n</code></pre>\n</blockquote>\n<p>The <code>__restrict__</code> doesn't provide any value here.</p>\n<blockquote>\n<pre><code>if(errnum==22){\n return &quot;Alphabets or Symbols present in the String&quot;;\n}\n</code></pre>\n</blockquote>\n<p>What's the significance of <code>22</code>? Why aren't we using named (enum) constants?</p>\n<p>We shouldn't be returning <code>const char*</code> from a function declared to return <code>char *</code>. I suggest changing the function to return <code>const char*</code> instead.</p>\n<hr />\n<blockquote>\n<pre><code>void invalid_argument(const char * __restrict__ _err,int errcode)\n{\n StrNumErr = errcode;\n}\n</code></pre>\n</blockquote>\n<p>Again, no benefit from <code>__restrict__</code> here. Avoid declaring identifiers beginning with <code>_</code> (since that's easier than remembering exactly which ones are safe, and where) - and why are we ignoring <code>_err</code> anyway? That leads to inconsistency between what the caller provides and what we return from <code>str2numErrText()</code>.</p>\n<hr />\n<blockquote>\n<p>float power(float a,int b)</p>\n</blockquote>\n<p>This function should be declared with <code>static</code> linkage, unless you really intend it to be part of the public interface.</p>\n<p>The usual floating-point type is <code>double</code>. Calculating with <code>float</code> sacrifices a lot of precision.</p>\n<p>And calculating powers by repeated multiplication is inefficient compared to binary exponentiation.</p>\n<p>I don't see any benefit to using this function rather than the standard <code>pow()</code> from <code>&lt;math.h&gt;</code>.</p>\n<hr />\n<blockquote>\n<pre><code> int _strlen = strlen(_string);\n</code></pre>\n</blockquote>\n<p>Use the right type - <code>strlen()</code> returns a <code>size_t</code>. But we don't need to measure the string anyway, as we're walking it character by character - we should <em>loop like a native</em> with <code>for (const char *s = string; *s; ++)</code> (or just use the passed string pointer here. Code that does unnecessary string indexing looks like it's written by a FORTRAN or Java programmer who is still uncomfortable with pointers.</p>\n<hr />\n<blockquote>\n<pre><code>float str2num_C(const char * __restrict__ _string)\n</code></pre>\n</blockquote>\n<p>Another reserved identifier, and another pointless <code>__restrict__</code>.</p>\n<hr />\n<blockquote>\n<pre><code> else if(_curchar=='0'){\n //if char is 0!\n if(!(_numfound==1)){\n _numfound=1;\n _return_num = 0;\n }\n else if(_point==1){\n _return_num+= 0/(power(10,_pointplace));\n _pointplace+=1;\n }\n else{\n _return_num*=10;\n _return_num+=0;\n }\n }\n else if(_curchar=='1'){\n //if char is 1!\n if(!(_numfound==1)){\n _numfound=1;\n _return_num = 1;\n }\n else if(_point==1){\n _return_num+= 1/(power(10,_pointplace));\n _pointplace+=1;\n }\n else{\n _return_num*=10;\n _return_num+=1;\n }\n }\n</code></pre>\n</blockquote>\n<p>These branches can all be combined, using the fact that C guarantees that the encoding of digits <code>0</code>...<code>9</code> are contiguous (so <code>curchar - '0'</code> gives the integer value of the digit).</p>\n<p>Instead of computing <code>power()</code> each time around, it might be worth keeping that value in a variable, and scaling it by 10 each time it's used:</p>\n<pre><code>double place_value = 1;\n⋮\n\nfor (…) {\n ⋮\n if (curchar &gt;= '0' &amp;&amp; curchar &lt;= '9') {\n int digit = curchar - '0';\n if (!numfound) { numfound = 1; }\n if (point) {\n place_value /= 10;\n }\n return_num = return_num * 10 + digit;\n }\n ⋮\n}\nreturn return_num * minus * place_value;\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> invalid_argument(&quot;The string contains alphabetic charachters or symbol&quot;,22);\n</code></pre>\n</blockquote>\n<p>Check your spelling (<strong>characters</strong>). We might have spotted this if we'd actually used the value.</p>\n<hr />\n<blockquote>\n<pre><code> //declaring variables\n char string[20];\n gets(string);\n</code></pre>\n</blockquote>\n<p>That's probably the most useless comment I've seen today.</p>\n<p>What if 20 characters or more are entered? Eschew <code>gets()</code> - that's the most dangerous function in the Standard Library (it's impossible to use it safely). Use <code>fgets()</code>:</p>\n<pre><code>fgets(string, sizeof string, stdin);\n</code></pre>\n<p>And don't forget to examine its return value before relying on <code>string</code> containing anything valid.</p>\n<blockquote>\n<pre><code> num = str2num_C(string);\n</code></pre>\n</blockquote>\n<p>Well, that's not going to work, because <code>str2num_C()</code> will error on the newline character that <code>gets()</code> read.</p>\n<hr />\n<blockquote>\n<pre><code>if(err&gt;0){\n printf(&quot;ERROR: %s&quot;,str2numErrText(err));\n}\nelse{\n printf(&quot;Number + 2 is: %f&quot;,num);\n</code></pre>\n</blockquote>\n<p>Please write full lines of output (ending in <code>\\n</code>). It's very bad behaviour to terminate with a partial line written.</p>\n<p>And error messages ought to be printed to <code>stderr</code>, not <code>stdout</code>.</p>\n<hr />\n<p>My overall assessment is that this reinvention of the wheel is pointless anyway. It's much simpler to wrap standard parsers such as <code>strtof()</code> to fit the interface you need than to write this stuff from scratch. It's likely to be more efficient, too - although you'll want to run some actual benchmarks to determine that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T07:25:29.430", "Id": "530689", "Score": "0", "body": "_Thats probably the most useless comment I've seen_ . are newcomers not allowed here? i am a newcomer and writing that in comment i think would not change any output because from what i've learnt comments dont compile" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T09:14:19.063", "Id": "530752", "Score": "0", "body": "If the comment were not there, would you struggle to understand that variables are being declared? No matter how new you are, that's pretty unlikely. So all the comment does is get in the way of the important stuff. That's the kind of comment even a [tag:beginner] needs to learn isn't helpful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:11:44.233", "Id": "269008", "ParentId": "268952", "Score": "0" } } ]
{ "AcceptedAnswerId": "268978", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T14:50:49.333", "Id": "268952", "Score": "2", "Tags": [ "c", "strings", "converting", "integer" ], "Title": "Convert string to integer and catch errors" }
268952
<p>Due to recent need I wrote a simple <code>main</code> function that has the goal to convert the C-style strings and arrays into a more STL-style. Then because I also had a need for it, I created a variation that converts all the involved <code>std::string</code>s into <code>std::wstring</code>s.</p> <p>So essentially this is to be seen as two parts:</p> <ul> <li>Converting C-style main into STL-style main</li> <li>Converting STL-style main into STL-style main with wide strings (in practice you can leave that out if you don't need wide strings)</li> </ul> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;codecvt&gt; #include &lt;locale&gt; #include &lt;string&gt; #include &lt;vector&gt; int main(int argc, char* argv[]); int stlMain(std::string&amp;&amp; cmd, std::vector&lt;std::string&gt;&amp;&amp; args); int stlWMain(std::wstring&amp;&amp; cmd, std::vector&lt;std::wstring&gt;&amp;&amp; args); int main(int argc, char* argv[]) { std::string cmd{argv[0]}; std::vector&lt;std::string&gt; args; args.reserve(argc - 1); args.assign(argv + 1, argv + argc); return stlMain(std::move(cmd), std::move(args)); } int stlMain(std::string&amp;&amp; cmd, std::vector&lt;std::string&gt;&amp;&amp; args) { // main with STL objects std::wstring_convert&lt;std::codecvt_utf8_utf16&lt;wchar_t&gt;&gt; converter; std::wstring wcmd = converter.from_bytes(cmd); std::vector&lt;std::wstring&gt; wargs; wargs.reserve(args.size()); std::transform(args.cbegin(), args.cend(), std::back_inserter(wargs), [&amp;converter](const std::string&amp; str) { return converter.from_bytes(str); }); return stlWMain(std::move(wcmd), std::move(wargs)); } int stlWMain(std::wstring&amp;&amp; cmd, std::vector&lt;std::wstring&gt;&amp;&amp; args) { // main with wide strings // Start you program here } </code></pre> <p>I'm aware that this requires C++11 at least due to the <code>codecvt</code> header and that some compilers don't support it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T10:18:25.620", "Id": "530558", "Score": "0", "body": "No I'm compiling this with C++17, but the code itself works up until C++11, that's why I tagged it that way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T10:40:59.397", "Id": "530559", "Score": "0", "body": "That's not how the tags work here - you should tag for your target platform, so that you get reviews appropriate to C++17. I've made that change for you." } ]
[ { "body": "<p>This is not as portable as we'd like it to be. Instead of assuming that the arguments are supplied as UTF-8 bytes, we ought to use the local character encoding, as used by <code>std::locale{&quot;&quot;}</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T08:37:31.780", "Id": "268977", "ParentId": "268958", "Score": "1" } }, { "body": "<h2>Design:</h2>\n<p>I'd recommend going the <a href=\"https://utf8everywhere.org/#windows\" rel=\"nofollow noreferrer\">UTF-8 Everywhere</a> route instead.</p>\n<p>This means avoiding <code>std::wstring</code>s and using <code>std::string</code>s in your program, encoded as utf-8. This requires a little care when processing strings, since you can't assume that one byte is one character, but it's better overall (see the link above for details).</p>\n<p>On Windows, you then need to convert strings back to UTF-16 (what Microsoft calls &quot;Unicode&quot;) when calling functions to open files, or using the Windows API. You can convert UTF-8 to UTF-16 with <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar\" rel=\"nofollow noreferrer\"><code>MultiByteToWideChar</code></a>, and back again with <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte\" rel=\"nofollow noreferrer\"><code>WideCharToMultiByte</code></a>.</p>\n<p>You can get UTF-16 command line arguments on Windows with <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getcommandlinew\" rel=\"nofollow noreferrer\"><code>GetCommandLineW</code></a> or <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw\" rel=\"nofollow noreferrer\"><code>CommandLineToArgvW</code></a>, which should then be converted to UTF-8 for use internally.</p>\n<hr />\n<p>On Linux <a href=\"https://stackoverflow.com/a/5596232\">there is no fixed encoding</a> for command line arguments. Perhaps it's reasonable to simply require that arguments to your program are passed as UTF-8.</p>\n<p>Otherwise I guess you're stuck with converting from the current locale... But you might run into issues with arguments in different encodings as described in that stackoverflow link.</p>\n<hr />\n<h2>Code:</h2>\n<p>I'd suggest avoiding the nested call to an inner <code>main</code> function. Extracting the first argument and passing it separately also seems unnecessary.</p>\n<p>So perhaps:</p>\n<pre><code>std::vector&lt;std::string&gt; read_args(int argc, char* argv[]);\nstd::vector&lt;std::wstring&gt; convert_strings_utf8_to_utf16(std::vector&lt;std::string&gt; const&amp; args);\n\nint main(int argc, char* argv[]) {\n \n auto args = read_args(argc, argv);\n auto wargs = convert_strings_utf8_to_utf16(args);\n\n return run_program(wargs);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T11:37:26.370", "Id": "530561", "Score": "0", "body": "That's twice the allocations necessary..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T11:44:04.320", "Id": "530562", "Score": "0", "body": "@Deduplicator Do you mean that it should convert each argument to a `std::wstring` first before adding directly to the `std::vector<std::wstring>` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T19:53:19.330", "Id": "530861", "Score": "0", "body": "I wanted to separate the program name from the arguments, as to me that isn't an argument. I do understand the technical reasons as to why it has been implemented like this, but personally speaking I see it as something separate enough to warrant putting it into it's own variable" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T11:36:17.313", "Id": "268979", "ParentId": "268958", "Score": "0" } }, { "body": "<p>For just upgrading the <code>char*</code> arguments to object types, you should use <code>string_view</code> instead, and this does not require recopying the data. That's true for parameters in general.</p>\n<p><code>std::wstring_convert&lt;std::codecvt_utf8_utf16&lt;wchar_t&gt;&gt; converter;</code></p>\n<p>The meaning of <code>wchar_t</code> is implementation-dependent. I understand that on non-Windows platforms it's actually a 32-bit value. Yet you are only wanting 16-bit code points. Use <code>char16_t</code> instead.</p>\n<p>I agree with the posters that said &quot;UTF-8 everywhere&quot; is better than wide characters. But working in UTF-16 is useful/necessary/efficient for some purposes including specific platforms (specifically Windows). I understand that the convert stuff in <code>std</code> is actually deprecated because it is flawed and has issues. If you're doing this because it's for a specific platform, it might be better to use the platform-specific features instead. OTOH, the supplied Win32 functions also have issues with error checking and reporting and lack of options for dealing with invalid data, so in a similar situation I used my own code.</p>\n<p>You're not doing any error checking or trapping. It also assumes that the arguments coming into the program are encoded as UTF-8! (That's certainly not the case in Windows) It needs to check the Locale to determine how the incoming characters are encoded; or I should say how they are <em>supposed to be</em> encoded, as if the program was not invoked from an interactive command line it could still get it wrong.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:41:13.717", "Id": "268984", "ParentId": "268958", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T16:51:04.830", "Id": "268958", "Score": "3", "Tags": [ "c++", "strings", "c++17", "converting" ], "Title": "Convert program arguments to std::wstring" }
268958
<p>I'm building a contact manager with Flask for a community group, and I'm working on the function to export contacts as a spreadsheet. I want to export either all contacts, only those who have been assigned to a ticket seller, only those assigned to a <strong>specific</strong> ticket seller, or those assigned to <strong>no</strong> ticket seller.</p> <p>The form layout I want is something like this:</p> <ul> <li>RadioButton: All Sellers</li> <li>RadioButton: Select Seller <ul> <li>SelectField: Seller ID</li> </ul> </li> <li>RadioButton: No Seller Assigned</li> </ul> <p>with a select field tucked in between two of the radio buttons. This requires that I render the radio buttons individually, rather than letting Jinja render them as a group. This is possible, but <strong>referencing</strong> each individual button for rendering has proven difficult.</p> <p>Here's the Jinja code I've come up with:</p> <pre><code>{% for subfield in form.sellers_filter %} {% if subfield.id.endswith('0') %} &lt;div class=&quot;form-group col-4&quot;&gt; {{ subfield.label }} {{ subfield }} &lt;/div&gt; {% endif %} {% if subfield.id.endswith('1') %} &lt;div class=&quot;form-group col-4&quot;&gt; {{ subfield.label }} {{ subfield }} {{ form.seller }} &lt;/div&gt; {% endif %} {% if subfield.id.endswith('2') %} &lt;div class=&quot;form.group col-4&quot;&gt; {{ subfield.label }} {{ subfield }} &lt;/div&gt; {% endif %} {% endfor %} </code></pre> <p>I'm bothered, though, by the <code>subfield.id.endswith()</code> part, and I'm hoping someone can suggest a more elegant solution.</p> <p>For reference, here is my form code:</p> <pre><code>def list_sellers(): c1 = aliased(Contact) c2 = aliased(Contact) return db.session.query(c2). select_from(c1).join(c2, c2.id==c1.seller_id). filter(c1.seller_id != None) class ExportForm(FlaskForm): filtered = BooleanField('Apply Filters') sellers_filter = RadioField( 'Filter by Seller', choices=[ ('all', 'All Sellers'), ('select', 'Select Seller'), ('none', 'No Seller') ], validators=[Optional()] ) seller = QuerySelectField( 'Seller', query_factory=list_sellers, allow_blank=False, validators=[Optional()], render_kw={'class': 'form-select'}, ) submit = SubmitField('Download') </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T17:08:22.143", "Id": "268959", "Score": "0", "Tags": [ "python", "flask" ], "Title": "Rendering Radio Buttons Individually in WTForms/Jinja2" }
268959
<p>I have the following code snippet:</p> <pre><code>for index, row in df.iterrows(): if row['MSI Status'] == 'MSS': print(row['Patient ID']) for dirpath, dirnames, filenames in os.walk(path): for dirname in dirnames: joined_path = os.path.join(path, dirname) if row['Patient ID'] in dirname: shutil.copytree(joined_path, os.path.join('/SeaExp/mona/MSS_Status/MSS', dirname)) if row['MSI Status'] == 'MSI-H': print(row['Patient ID']) for dirpath, dirnames, filenames in os.walk(path): for dirname in dirnames: joined_path = os.path.join(path, dirname) if row['Patient ID'] in dirname: shutil.copytree(joined_path, os.path.join('/SeaExp/mona/MSS_Status/MSI-H', dirname)) </code></pre> <p>I only have 100 rows in my df but I have many directories in my os.walk. I understand my code is not written well or not efficient and is slow and I hope to get some feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T19:03:40.760", "Id": "530507", "Score": "1", "body": "What does the file structure look like?" } ]
[ { "body": "<ul>\n<li><p>You should make a function to contain the <code>os.walk(path)</code>. As both walks are almost identical, the difference is the destination directory.</p>\n</li>\n<li><p>You're not walking correctly. If I have the file structure:</p>\n<pre><code>──.\n └─test\n └─test_nested\n └─test_file\n</code></pre>\n<p>Then <code>os.walk</code> would walk down the tree, and <code>dirnames</code> would only contain the directory's name (<code>test</code>, <code>test_nested</code>).\nOk, so lets say <code>row['Patient ID']</code> is <code>test_nested</code> then we're into the <code>if</code>.</p>\n<p>Now we're copying from <code>./test_nested</code> to <code>/SeaExp/mona/MSS_Status/MSS/test_nested</code>.\nHowever the path to <code>test_nested</code> is actually <code>./test/test_nested</code>.</p>\n<p>You need to either:</p>\n<ol>\n<li>Include <code>dirpath</code> in the source and/or the destination path.\n<code>os.path.join(src, dirpath, dirname)</code>.</li>\n<li>Or assuming your code works correctly because <code>if row['Patient ID'] in dirname:</code> is never true in a subdirectory you need to break after the first iteration of the tree.</li>\n</ol>\n</li>\n<li>\n<blockquote>\n<p>When <em>topdown</em> is <code>True</code>, the caller can modify the <em>dirnames</em> list in-place (perhaps using <a href=\"https://docs.python.org/3/reference/simple_stmts.html#del\" rel=\"nofollow noreferrer\">del</a> or slice assignment), and <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\">walk()</a> will only recurse into the subdirectories whose names remain in <em>dirnames</em>; this can be used to prune the search, impose a specific order of visiting, or even to inform <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\">walk()</a> about directories the caller creates or renames before it resumes <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\">walk()</a> again.<br />\n<a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\">Python's <code>os.walk</code> docs</a></p>\n</blockquote>\n<p>As such you should <code>dirnames.remove(dirname)</code> to prevent walking the path and duplicating copies.\nOr just wasting time.</p>\n</li>\n</ul>\n<pre><code>def copy_tree__nested(src, dest):\n for dirpath, dirnames, filenames in os.walk(src):\n for dirname in dirnames[:]:\n if row['Patient ID'] in dirname:\n dirnames.remove(dirname)\n shutil.copytree(os.path.join(src, dirpath, dirname), os.path.join(dest, dirpath, dirname))\n\n\ndef copy_tree__tld(src, dest):\n for dirpath, dirnames, filenames in os.walk(src):\n for dirname in dirnames:\n if row['Patient ID'] in dirname:\n shutil.copytree(os.path.join(src, dirname), os.path.join(dest, dirname))\n break\n\n\nfor index, row in df.iterrows():\n if row['MSI Status'] == 'MSS':\n print(row['Patient ID'])\n copy_tree(path, '/SeaExp/mona/MSS_Status/MSS')\n if row['MSI Status'] == 'MSI-H':\n print(row['Patient ID'])\n copy_tree(path, '/SeaExp/mona/MSS_Status/MSI-H')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T19:36:30.880", "Id": "268964", "ParentId": "268961", "Score": "3" } }, { "body": "<ul>\n<li><p>First off, you seem to have a typo: <code>os.path.join(path, dirname)</code> should almost certainly be <code>os.path.join(dirpath, dirname)</code>. The only way I could see this not causing problems is if all the directories you want to copy are immediate children of <code>path</code> - and in that case you don't want <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\"><code>os.walk</code></a> at all, but should instead use <a href=\"https://docs.python.org/3/library/os.html#os.scandir\" rel=\"nofollow noreferrer\"><code>os.scandir</code></a>. But going forward I'll assume that <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\"><code>os.walk</code></a> is in fact needed here</p>\n</li>\n<li><p>Since the target directory's name matches the <code>MSI Status</code> field, and those two loops are otherwise identical, it'd be easy to merge those two loops into a single one, ending with something like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>destination = os.path.join(&quot;/SeaExp/mona/MSS_Status&quot;, row[&quot;MSI Status&quot;], dirname)\nshutil.copytree(joined_path, destination)\n</code></pre>\n</li>\n<li><p>If those are the only two statuses that are possible, you'd be able to get rid of the <code>if</code>s entirely. If not, you can still simplify it to something akin to <code>if row['MSI Status'] in {'MSI-H', 'MSS'}:</code></p>\n</li>\n<li><p>Back to <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\"><code>os.walk</code></a> issues, once you've found a directory to copy, will you ever need to copy any subdirectory of that directory? For example, for a patient with ID <code>somebody</code>, would you want/need to copy <em>both</em> <code>./somebody/</code> and <code>./somebody/appointment_history/somebody_2020-12-13</code> independently? If not, you should modify the <code>dirnames</code> list while iterating to avoid descending into the directories you've already copied - which could perhaps look like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for dirpath, dirnames, filenames in os.walk(path):\n remaining = []\n\n for dirname in dirnames:\n if row['Patient ID'] in dirname:\n source = os.path.join(path, dirname)\n destination = os.path.join('/SeaExp/mona/MSS_Status', row['MSI Status'], dirname)\n else:\n remaining.append(dirname)\n\n dirnames[:] = remaining # Note the use of [:] to update in-place\n</code></pre>\n</li>\n<li><p>Finally, pandas' <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html\" rel=\"nofollow noreferrer\"><code>iterrows</code></a> is almost certainly faster than <code>os.walk</code>, so if we're going to do one of those multiple times, it might be best to let that be the <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html\" rel=\"nofollow noreferrer\"><code>iterrows</code></a>. You might save time by turning your code inside-out like so:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for dirpath, dirnames, filenames in os.walk(path):\n remaining = []\n\n for index, row in df.iterrows():\n for dirname in dirnames:\n if row['Patient ID'] in dirname:\n source = os.path.join(dirpath, dirname)\n destination = os.path.join(\n '/SeaExp/mona/MSS_Status',\n row['MSI Status'],\n dirname\n )\n shutil.copytree(source, destination)\n else:\n remaining.append(dirname)\n\n dirnames[:] = remaining\n\n\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T11:06:16.740", "Id": "530560", "Score": "1", "body": "If one were to combine our answers, your final bullet point would have the benefit of never walking down trees we've copied from ever. Gaining an even larger benefit than either of our answers would have standing alone. Nice answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T20:30:31.630", "Id": "268966", "ParentId": "268961", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T17:55:19.713", "Id": "268961", "Score": "0", "Tags": [ "python", "file-system", "pandas" ], "Title": "Combining iterrows of pandas with os.walk given I have a lot of directories" }
268961
<p>This question applies to any language with flatMap -- e.g. functional languages -- but I'll use an example in JavaScript.</p> <hr /> <p>I'm working my way through <a href="http://reactivex.io/learnrx/" rel="nofollow noreferrer">Functional Programming in JavaScript</a>, which is a set of exercise for learning rxjs. Here's a simplified version of Exercise 12, which I have a question about.</p> <p><strong>The exercise is:</strong> Given a collection of states, which contain cities, which contain public officials, make a list of all the cities and their mayors.</p> <p><strong>My question is:</strong> The first approach (<code>const mayors = ...</code>) is the one I came up with. The second approach (<code>const mayors2 = ...</code>) is the reference solution. My approach seems more comprehensible to me -- but I'm a newbie to FP, and of course I'd be biased towards my code over someone else's.</p> <p>But is the second solution a more typical style? Are there benefits to it that I don't see? Are there other problems that I'd be able to solve with the second approach but not the first?</p> <pre><code>const states = [ { name: 'California', cities: [ { name: 'San Francisco', officials: [ { name: 'London Breed', position: 'Mayor', }, { name: 'Reginald Freeman', position: 'Fire Chief', }, ] }, { name: 'Anaheim', officials: [ { name: 'Harry Sidhu', position: 'Mayor', }, ] }, ] }, { name: 'Texas', cities: [ { name: 'Houston', officials: [ { name: 'Sylvester Turner', position: 'Mayor', }, ] }, ] }, ]; </code></pre> <pre><code>const mayors = states .flatMap(county =&gt; county.cities) .flatMap(city =&gt; city.officials .filter(official =&gt; official.position === 'Mayor') .map(official =&gt; ({ city: city.name, mayor: official.name })) ); console.log(mayors); </code></pre> <pre><code>const mayors2 = states .flatMap(county =&gt; county.cities .flatMap(city =&gt; city.officials .filter(official =&gt; official.position === 'Mayor') .map(official =&gt; ({ city: city.name, mayor: official.name })) ) ); console.log(mayors2); </code></pre> <p>Output: (Both approaches give the same result)</p> <pre><code>[ { city: 'San Francisco', mayor: 'London Breed' }, { city: 'Anaheim', mayor: 'Harry Sidhu' }, { city: 'Houston', mayor: 'Sylvester Turner' } ] [ { city: 'San Francisco', mayor: 'London Breed' }, { city: 'Anaheim', mayor: 'Harry Sidhu' }, { city: 'Houston', mayor: 'Sylvester Turner' } ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T06:54:40.507", "Id": "530540", "Score": "1", "body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T18:12:21.100", "Id": "531159", "Score": "0", "body": "Not sure if I'm blind, but other than a tiny difference in formatting (spacing, actually) the code is exactly the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T01:26:53.883", "Id": "533024", "Score": "0", "body": "The difference is subtle, but might be important in some cases. What if in your final object `{ city: ..., mayor: ... }` you also need something from county? In this case you need to do it like in `mayor2` example -- deeper nesting allows you to reference outer objects. And what if you don't need `city` in the final object? In that case you could make `.flatMap()` calls even flatter by one level. Either way is fine, as long as task is done." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T23:59:33.383", "Id": "268967", "Score": "0", "Tags": [ "javascript", "functional-programming", "comparative-review", "rxjs" ], "Title": "Multiple flatMap style: Nested or sequential?" }
268967
<p>I have this view in SwiftUI; it works as expected, and for the most part, works great. My only concern with it is that it feels extremely clunky. Reading through the view itself is very difficult. Does anyone have recommendations for cleaning this thing up?</p> <p>Effectively, the sign in and register pages both have the same options, and there are only minor text differences. however you'll notice I've got some buttons that seem to repeat, but I don't see the need in extracting to its own view because this is the only place it'll be used.</p> <pre><code>struct RegisterOptionsView: View { @EnvironmentObject var baseNavVM: BaseLaunchViewModel @ObservedObject var registerOptionsViewModel = RegisterOptionsViewModel() @State var isLoggingIn = false var body: some View { ZStack { VStack(spacing: 20) { NavigationLink(destination: getDestination(), isActive: $registerOptionsViewModel.shouldNavigateToRegister) { EmptyView() } .navigationTitle(isLoggingIn ? &quot;Login&quot; : &quot;Register&quot;) Spacer() VStack(spacing: 30) { VStack { Text(&quot;Stello&quot;) .font(Fonts.title) Text(&quot;[STEL'-LO]&quot;) .font(Fonts.body) Text(&quot;VERB, GREEK&quot;) .font(Fonts.body) } StelloDivider() Text(&quot;SENT WITH A PURPOSE&quot;) .font(Fonts.subheading) .multilineTextAlignment(.center) } Spacer() // MARK: - APPLE SIGN IN VStack { Button(action: { registerOptionsViewModel.selectedLoginOption = .apple withAnimation { isLoggingIn ? baseNavVM.loggedIn = true : registerOptionsViewModel.shouldNavigateToRegister.toggle() } }, label: { HStack(spacing: 16) { Image(systemName: &quot;applelogo&quot;) .font(.system(size: 20)) Text(isLoggingIn ? &quot;Sign in with Apple&quot; : &quot;Register with Apple&quot;) .font(Fonts.button) } }).buttonStyle(StelloFillButtonStyle()) .offset(y: 32 ) .frame(height: registerOptionsViewModel.showOptions ? 0 : 60 ) .hidden(registerOptionsViewModel.showOptions) // MARK: - Forgot Password Group { NavigationLink(destination: Text(&quot;Forgot Password&quot;), label: { Text(&quot;Forgot Password?&quot;) .font(Fonts.body) .underline() .foregroundColor(.blue) }) .frame(height: !isLoggingIn ? 0 : 60 ) .hidden(!isLoggingIn) .navigationTitle(&quot;Password Recovery&quot;) // MARK: - Email Button(action: { registerOptionsViewModel.selectedLoginOption = .email withAnimation { isLoggingIn ? baseNavVM.loggedIn = true : registerOptionsViewModel.shouldNavigateToRegister.toggle() } }, label: { Text(isLoggingIn ? &quot;Email&quot; : &quot;Register with Email&quot;) .font(Fonts.button) }).buttonStyle(StelloFillButtonStyle()) //MARK: - Facebook Button(action: { registerOptionsViewModel.selectedLoginOption = .facebook withAnimation { isLoggingIn ? baseNavVM.loggedIn = true : registerOptionsViewModel.shouldNavigateToRegister.toggle() } }, label: { Text(isLoggingIn ? &quot;Facebook&quot; : &quot;Register with Facebook&quot;) .font(Fonts.button) }).buttonStyle(StelloFillButtonStyle()) //MARK: - Google Button(action: { registerOptionsViewModel.selectedLoginOption = .google withAnimation { isLoggingIn ? baseNavVM.loggedIn = true : registerOptionsViewModel.shouldNavigateToRegister.toggle() } }, label: { Text(isLoggingIn ? &quot;Google&quot; : &quot;Register with Google&quot;) .font(Fonts.button) }).buttonStyle(StelloFillButtonStyle()) } .frame(height: !registerOptionsViewModel.showOptions ? 0 : 60 ) .hidden(!registerOptionsViewModel.showOptions) // MARK: - Other Options Button(action: { withAnimation(.easeInOut) { registerOptionsViewModel.showOptions.toggle() } }, label: { if !registerOptionsViewModel.showOptions { Text(&quot;Other Options&quot;) .font(Fonts.button) } else { Text(&quot;Cancel&quot;) .font(Fonts.button) } }).buttonStyle(StelloFillButtonStyle()) } } .padding(.horizontal) } } // MARK: - View Functions func getDestination() -&gt; AnyView { switch registerOptionsViewModel.selectedLoginOption { case .apple: return AnyView(Text(&quot;Apple&quot;)) case .email: return AnyView(Text(&quot;Email&quot;)) case .facebook: return AnyView(Text(&quot;Facebook&quot;)) case .google: return AnyView(Text(&quot;Google&quot;)) default: return AnyView(EmptyView()) } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T00:27:12.050", "Id": "268968", "Score": "0", "Tags": [ "gui", "swiftui" ], "Title": "SwiftUI Reusable Login & Register View" }
268968
<p>Have this code do what I want: If there is argument pass to constructor, initialize; otherwise, set it to default value?</p> <pre><code>class Node { public: Node(string id, bool isNum, int level, string data, bool duplicate, Node *next) : id(id), isNum(isNum), level(level), data(data), duplicate(duplicate), next(next) {} private: string id; bool isNum = false; int level = 0; string data; bool duplicate = false; Node *next = nullptr; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:27:36.627", "Id": "530546", "Score": "0", "body": "It's usually a good idea to write the initialisers in the same order as the members, to avoid reader confusion when there's a dependency - remember that initialisers execute in the order the members appear, not the order the initialisers are written!" } ]
[ { "body": "<p>Don't use default arguments, but provide various overloaded constructors like this</p>\n<pre><code>#include &lt;string&gt;\n\nclass Node\n{\npublic:\n // pass string by const reference, this avoids unecessary copying of the string\n // pass all other arguments as const, initializer is not supposed to change them\n Node(const std::string&amp; id, const std::string data, const bool isNum, const int level, const bool duplicate, Node* next) :\n m_id(id),\n m_data(data),\n m_isNum(isNum),\n m_level(level),\n m_duplicate(duplicate),\n m_next(next)\n {\n }\n\n Node(const std::string&amp; id, const std::string&amp; data) :\n m_id(id),\n m_data(data)\n // rest of the members will be default initialized\n {\n }\n\nprivate:\n // changed the order so that all non-default initialized members\n // are listed together.\n std::string m_id;\n std::string m_data;\n bool m_isNum = false;\n int m_level = 0;\n bool m_duplicate = false;\n Node* m_next = nullptr;\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:14:19.907", "Id": "530544", "Score": "0", "body": "`Node(const std::string& id, const std::string data, const bool isNum, const int level, const bool duplicate, Node* next) :\n m_id(id),\n m_data(data),\n m_isNum(isNum),\n m_level(level),\n m_duplicate(duplicate),\n m_next(next)\n {\n }`\n\nIf I use like this: `new Node(1, \"data\", true)`, will the rest of data member be default initialized? If yes, why you declare overload constructor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:24:12.077", "Id": "530545", "Score": "0", "body": "It's generally better to pass the strings by value, then move-initialise the members from them. That saves a copy when passing rvalues (e.g. when a string literal is implicitly converted to `std::string`). Always assuming that `string` in the code is an alias to `std::string`, but there's no evidence of that in the fragment we're given, of course!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:09:19.817", "Id": "268974", "ParentId": "268972", "Score": "0" } }, { "body": "<p><code> Node(string id ={}, bool isNum=false, int level=0, string data={}, bool duplicate=false, Node* next={})</code></p>\n<p>Put the defaults in the argument list. That way you can leave off any number of trailing arguments.</p>\n<p>With Pepijn Kramer's answer, you only have two choices: give all the parameters or give exactly 2 parameters. You would need to overload 6 different forms, each taking a different number of arguments, to get the same feature that way.</p>\n<p>You might want to give distinct overloaded functions for <em>some</em> of them, though. Specifically, a constructor called with 0 arguments is a default constructor, and a constructor called with exactly 1 argument might be an implicit conversion and you can mark it <code>explicit</code> to prevent that.</p>\n<p>If the constructors are being inlined anyway, then the default arguments is no less efficient than having distinct constructors. But you might want to mark the one-argument case as <code>explicit</code> and <em>not</em> mark the others, so it needs to be on its own.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:25:03.797", "Id": "530625", "Score": "0", "body": "\"A constructor that can be called with one argument\" isn't identical to \"a constructor with exactly 1 argument\". The first line of your answer shows a 6-argument constructor that is also a converting constructor (and also a default constructor)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T13:55:07.470", "Id": "530654", "Score": "1", "body": "@TobySpeight I clarified the wording. I was referring to the call, not the total number of arguments declared." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:55:30.263", "Id": "268986", "ParentId": "268972", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T06:33:42.993", "Id": "268972", "Score": "-1", "Tags": [ "c++" ], "Title": "Refactoring class member initialization C++" }
268972
<p>Here are implementations of both non-const and const view of submatrices, which is a subclass of my toy C++ 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>MatrixView.h</p> <pre><code>template &lt;std::semiregular T, std::size_t N, bool Const&gt; class MatrixView final : public MatrixBase&lt;MatrixView&lt;T, N, Const&gt;, T, N&gt; { public: using Base = MatrixBase&lt;MatrixView&lt;T, N, Const&gt;, T, N&gt;; using Base::size; using Base::dims; using Base::strides; using Base::applyFunction; using Base::applyFunctionWithBroadcast; using Base::operator=; using Base::operator+=; using Base::operator-=; using Base::operator*=; using Base::operator/=; using Base::operator%=; using value_type = T; using reference = std::conditional_t&lt;Const, const T&amp;, T&amp;&gt;; using const_reference = const T&amp;; using pointer = std::conditional_t&lt;Const, const T*, T*&gt;; using stride_type = std::array&lt;std::size_t, N&gt;; private: pointer data_view_; stride_type orig_strides_; public: ~MatrixView() noexcept = default; explicit MatrixView(const stride_type&amp; dims, pointer data_view, const stride_type&amp; orig_strides); template &lt;typename DerivedOther&gt; MatrixView(const MatrixBase&lt;DerivedOther, T, N&gt;&amp; other); template &lt;typename DerivedOther, std::semiregular U&gt; requires std::is_convertible_v&lt;U, T&gt; MatrixView&amp; operator=(const MatrixBase&lt;DerivedOther, U, N&gt;&amp; other) requires (!Const); friend void swap(MatrixView&amp; a, MatrixView&amp; b) noexcept { swap(static_cast&lt;Base&amp;&gt;(a), static_cast&lt;Base&amp;&gt;(b)); std::swap(a.data_view_, b.data_view_); std::swap(a.orig_strides_, b.orig_strides_); } template &lt;bool IterConst&gt; struct MVIterator { using difference_type = std::ptrdiff_t; using value_type = T; using pointer = std::conditional_t&lt;(Const || IterConst), const T*, T*&gt;; using reference = std::conditional_t&lt;(Const || IterConst), const T&amp;, T&amp;&gt;; using iterator_category = std::random_access_iterator_tag; using MatViewType = std::conditional_t&lt;(Const || IterConst), const MatrixView*, MatrixView*&gt;; MatViewType ptr_ = nullptr; std::array&lt;std::size_t, N&gt; pos_ = {0}; std::size_t offset_ = 0; std::size_t index_ = 0; MVIterator() = default; MVIterator(MatViewType ptr, std::array&lt;std::size_t, N&gt; pos = {0}) : ptr_ {ptr}, pos_ {pos} { ValidateOffset(); } reference operator*() const { return ptr_-&gt;data_view_[offset_]; } pointer operator-&gt;() const { return ptr_-&gt;data_view_ + offset_; } void ValidateOffset() { offset_ = std::inner_product(std::cbegin(pos_), std::cend(pos_), std::cbegin(ptr_-&gt;origStrides()), 0lu); index_ = std::inner_product(std::cbegin(pos_), std::cend(pos_), std::cbegin(ptr_-&gt;strides()), 0lu); assert(index_ &lt;= ptr_-&gt;size()); } void Increment() { for (std::size_t i = N - 1; i &lt; N; --i) { ++pos_[i]; if (pos_[i] != ptr_-&gt;dims(i) || i == 0) { break; } else { pos_[i] = 0; } } ValidateOffset(); } void Increment(std::ptrdiff_t n) { if (n &lt; 0) { Decrement(-n); return; } auto carry = static_cast&lt;std::size_t&gt;(n); for (std::size_t i = N - 1; i &lt; N; --i) { std::size_t curr_dim = ptr_-&gt;dims(i); pos_[i] += carry; if (pos_[i] &lt; curr_dim || i == 0) { break; } else { carry = pos_[i] / curr_dim; pos_[i] %= curr_dim; } } ValidateOffset(); } void Decrement() { for (std::size_t i = N - 1; i &lt; N; --i) { --pos_[i]; if (pos_[i] != static_cast&lt;std::size_t&gt;(-1) || i == 0) { break; } else { pos_[i] = ptr_-&gt;dims(i) - 1; } } ValidateOffset(); } void Decrement(std::ptrdiff_t n) { if (n &lt; 0) { Increment(-n); return; } auto carry = static_cast&lt;std::size_t&gt;(n); for (std::size_t i = N - 1; i &lt; N; --i) { std::size_t curr_dim = ptr_-&gt;dims(i); pos_[i] -= carry; if (pos_[i] &lt; curr_dim || i == 0) { break; } else { carry = static_cast&lt;std::size_t&gt;(-quot(static_cast&lt;long&gt;(pos_[i]), static_cast&lt;long&gt;(curr_dim))); pos_[i] = mod(static_cast&lt;long&gt;(pos_[i]), static_cast&lt;long&gt;(curr_dim)); } } ValidateOffset(); } MVIterator&amp; operator++() { Increment(); return *this; } MVIterator operator++(int) { MVIterator temp = *this; Increment(); return temp; } MVIterator&amp; operator--() { Decrement(); return *this; } MVIterator operator--(int) { MVIterator temp = *this; Decrement(); return temp; } MVIterator operator+(difference_type n) const { MVIterator temp = *this; temp.Increment(n); return temp; } MVIterator&amp; operator+=(difference_type n) { Increment(n); return *this; } MVIterator operator-(difference_type n) const { MVIterator temp = *this; temp.Decrement(n); return temp; } MVIterator&amp; operator-=(difference_type n) { Decrement(n); return *this; } reference operator[](difference_type n) const { return *(*this + n); } template &lt;bool IterConstOther&gt; difference_type operator-(const MVIterator&lt;IterConstOther&gt;&amp; other) const { return index_ - other.index_; } }; template &lt;bool IterConst&gt; friend bool operator==(const MVIterator&lt;IterConst&gt;&amp; it1, const MVIterator&lt;IterConst&gt;&amp; it2) { return it1.ptr_ == it2.ptr_ &amp;&amp; it1.index_ == it2.index_; } template &lt;bool IterConst&gt; friend bool operator!=(const MVIterator&lt;IterConst&gt;&amp; it1, const MVIterator&lt;IterConst&gt;&amp; it2) { return !(it1 == it2); } template &lt;bool IterConst1, bool IterConst2&gt; friend auto operator&lt;=&gt;(const MVIterator&lt;IterConst1&gt;&amp; it1, const MVIterator&lt;IterConst2&gt;&amp; it2) { return it1.pos_ &lt;=&gt; it2.pos_; } using iterator = MVIterator&lt;Const&gt;; using const_iterator = MVIterator&lt;true&gt;; using reverse_iterator = std::reverse_iterator&lt;iterator&gt;; using const_reverse_iterator = std::reverse_iterator&lt;const_iterator&gt;; iterator begin() { return iterator(this);} const_iterator begin() const { return const_iterator(this); } const_iterator cbegin() const { return const_iterator(this); } iterator end() { return iterator(this, {dims(0), });} const_iterator end() const { return const_iterator(this, {dims(0), });} const_iterator cend() const { return const_iterator(this, {dims(0), });} reverse_iterator rbegin() { return std::make_reverse_iterator(end());} const_reverse_iterator rbegin() const { return std::make_reverse_iterator(cend());} const_reverse_iterator crbegin() const { return std::make_reverse_iterator(cend());} reverse_iterator rend() { return std::make_reverse_iterator(begin());} const_reverse_iterator rend() const { return std::make_reverse_iterator(cbegin());} const_reverse_iterator crend() const { return std::make_reverse_iterator(cbegin());} [[nodiscard]] pointer dataView() const { return data_view_; } [[nodiscard]] const stride_type&amp; origStrides() const { return orig_strides_; } MatrixView&amp; operator-() { Base::Base::operator-(); return *this; } }; </code></pre> <p>MatrixBase.h</p> <pre><code>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; using extent_type = std::array&lt;std::size_t, N&gt;; using value_type = T; using reference = T&amp;; using const_reference = const T&amp;; using pointer = T*; using view_type = MatrixView&lt;T, N, false&gt;; using const_view_type = MatrixView&lt;T, N, true&gt;; using row_type = MatrixView&lt;T, N - 1, false&gt;; using const_row_type = MatrixView&lt;T, N - 1, true&gt;; // ... details ... view_type submatrix(const extent_type&amp; pos_begin); view_type submatrix(const extent_type&amp; pos_begin, const extent_type&amp; pos_end); row_type row(std::size_t n); row_type col(std::size_t n); row_type operator[](std::size_t n) { return row(n); } const_view_type submatrix(const extent_type&amp; pos_begin) const; const_view_type submatrix(const extent_type&amp; pos_begin, const extent_type&amp; pos_end) const; const_row_type row(std::size_t n) const; const_row_type col(std::size_t n) const; const_row_type operator[](std::size_t n) const { return row(n); } // ... details ... }; // N == 1 specialization 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; using extent_type = std::array&lt;std::size_t, 1&gt;; using value_type = T; using reference = T&amp;; using const_reference = const T&amp;; using pointer = T*; using view_type = MatrixView&lt;T, 1, false&gt;; using const_view_type = MatrixView&lt;T, 1, true&gt;; using row_type = reference; using const_row_type = const_reference; // ... details ... }; </code></pre> <p>Maintaining const-correctness correctly is extremely tedious and tricky. I posted code only relevant to techniques implementating const and non-const iterators and views. If you're interested in the full code, you can visit <a href="https://github.com/frozenca/Ndim-Matrix" rel="nofollow noreferrer">https://github.com/frozenca/Ndim-Matrix</a></p> <p>Feel free to comment anything!</p>
[]
[ { "body": "<h1>Unnecessary use of <code>using</code></h1>\n<p>You are publicly inheriting from <code>MatrixBase&lt;...&gt;</code>, so there is usually no need to use <code>using Base::...</code> to explicitly bring member functions and operator overloads into the derived class. The only reason to do this is if you are providing an overload of such a member function in the derived class with different arguments types, and still want the version from base to be available as well (by default it would be <a href=\"https://isocpp.org/wiki/faq/strange-inheritance#hiding-rule\" rel=\"nofollow noreferrer\">hidden</a>).</p>\n<p>I would strongly recommend removing the redundant <code>using</code>s, it makes it seem like there is something special going on when there's not, and it's just a lot of work to maintain for no gain at all.</p>\n<h1>Maintaining const-correctness</h1>\n<blockquote>\n<p>Maintaining const-correctness correctly is extremely tedious and tricky.</p>\n</blockquote>\n<p>Indeed, it is a bit tedious. However, you can reduce the amount of code you need to write somewhat. First, instead of duplicating the whole body of a member function you need to make const and non-const overloads for, just have one with the full body, and others call the full version where possible. For example, an easy case is this:</p>\n<pre><code>const_iterator begin() const { return const_iterator(this); }\nconst_iterator cbegin() const { return begin(); }\n</code></pre>\n<p>It would also help if <code>iterator</code> didn't have a <code>bool</code> template parameter, but could automatically detect if it should be <code>const</code> or not. Perhaps this makes things simpler:</p>\n<pre><code>template &lt;MatViewType&gt;\nrequires std::same_as&lt;std::remove_cv_t&lt;MatViewType&gt;, MatrixView&gt;\nstruct MVIterator {\n constexpr bool IterConst = std::is_const_v&lt;MatViewType&gt;;\n using std::conditional_t&lt;Const || IterConst, const T*, T*&gt;;\n ...\n MatViewType *ptr_{};\n ...\n MVIterator(MatViewType *ptr, ...): ptr_{ptr} {...}\n ...\n};\n</code></pre>\n<p>With that, <code>iterator(this)</code> would automatically get you a const iterator if <code>this</code> is <code>const</code>.</p>\n<p>Perhaps <code>MatrixView</code> itself could determine in a similar way if it's const or not, based on whether <code>pointer data_view</code> is <code>const</code> or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T21:13:25.870", "Id": "530608", "Score": "1", "body": "\"The explicit keyword only has an effect on constructors that take exactly one argument.\" I don't think that's true though? It prevents implicit conversions like `return { blah, blah, blah };` which one might want to avoid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:37:54.050", "Id": "530626", "Score": "1", "body": "@user673679 You are right. Although normally I would not think that is something you want to avoid (it only works if the return type is known in advance and it's clear you are going to construct a new object of that type), since there's inheritance involved here, it might indeed be better to keep the `explicit` to avoid surprises." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T12:24:04.087", "Id": "530651", "Score": "1", "body": "There is also a use for \"redundant\" using if the base-class depends on a template-argument, so you can use the name in the derived class. Not that that is the case for most of them here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T19:40:28.323", "Id": "268996", "ParentId": "268975", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T07:22:39.540", "Id": "268975", "Score": "3", "Tags": [ "c++", "c++20" ], "Title": "View of submatrix, in const and non-const form, preserving const-correctness" }
268975
<p>Following is bubble sorting code.</p> <p>I tried bubble sort after reading theory. Please let me know if my solution is correct and if so anyway I can make it more efficient?</p> <pre><code> static int[] BubbleSort(int[] arr) { int count = arr.Length; while (count &gt; 0) { int swapCount = 0; for (int y = 0; y &lt; count - 1; y++) { if (arr[y] &gt; arr[y + 1]) { swapCount++; var temp = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = temp; } } if (swapCount == 0) return arr; count--; } return arr; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:22:32.527", "Id": "530585", "Score": "6", "body": "*\"let me know if my solution is correct\"* - it is up to you to determine if it is correct or not, preferably with automated unit tests. If it is not correct, it does not belong on Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:27:12.960", "Id": "530595", "Score": "1", "body": "Hi, The code is running properly. My question was if the code is correct with the context to bubble sorting algorithm in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:53:32.613", "Id": "530598", "Score": "3", "body": "Does it appear to produce the correct output when running tests? Code can run yet be completely faulty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T20:38:00.427", "Id": "530603", "Score": "3", "body": "_\"Can I make it more efficient?\"_ - the biggest gain is to use a more efficient algorithm. Bubble sort has notoriously poor average and worst-case performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T08:25:01.240", "Id": "530628", "Score": "0", "body": "Are you looking for tiny tricks like this:`(arr[y], arr[y+1]) = (arr[y + 1], arr[y]);` to avoid the usage of a `temp` variable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:19:34.543", "Id": "530658", "Score": "1", "body": "@Mast Hi Mast, yes it is giving correct outputs :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:22:26.663", "Id": "530659", "Score": "1", "body": "@TobySpeight I see, Thanks a lot for your reply. I will read about more efficient algos. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:22:30.423", "Id": "530660", "Score": "1", "body": "@PeterCsala Hi yes, Please let me know where I can learn more such tricks to reduce memory usage." } ]
[ { "body": "<p>Let me show you how you can setup an environment where you can safely experiment with optimisation probes. I'll use <a href=\"https://benchmarkdotnet.org/\" rel=\"nofollow noreferrer\">BenchmarkDotNet</a> for this purpose, which might seem an overkill for this simple use case. But it demonstrates the basic ideas.</p>\n<p>So, let's create a simple console app, with the following code:</p>\n<pre><code>class Program\n{\n static void Main()\n {\n BenchmarkRunner.Run&lt;BubbleSortExperiment&gt;();\n }\n}\n</code></pre>\n<p>Now, let's create the <code>BubbleSortExperiment</code> class:</p>\n<pre><code>[MemoryDiagnoser]\n[ShortRunJob] \npublic class BubbleSortExperiment\n{\n int[] array;\n Random rnd = new Random();\n\n [Params(500, 1000, 1500)]\n public int Length { get; set; }\n\n [GlobalSetup]\n public void Setup()\n { \n array = Enumerable.Range(0, Length).OrderBy(x =&gt; rnd.Next()).ToArray();\n }\n\n [Benchmark]\n public void WhileWhileTemp() =&gt; BubbleSortWhileWhileTemp(array.ToArray());\n\n [Benchmark(Baseline = true)]\n public void WhileForTemp() =&gt; BubbleSortWhileForTemp(array.ToArray());\n\n [Benchmark]\n public void WhileForTuple() =&gt; BubbleSortWhileForTuple(array.ToArray());\n\n [Benchmark]\n public void ForForTuple() =&gt; BubbleSortForForTuple(array.ToArray());\n\n [Benchmark]\n public void ForForTemp() =&gt; BubbleSortForForTemp(array.ToArray());\n\n [Benchmark]\n public void ForWhileTemp() =&gt; BubbleSortForWhileTemp(array.ToArray());\n\n [Benchmark]\n public void ForWhileTuple() =&gt; BubbleSortForWhileTuple(array.ToArray());\n\n public int[] BubbleSortWhileForTemp(int[] arr)\n {\n int count = arr.Length;\n\n while (count &gt; 0)\n {\n int swapCount = 0;\n for (int y = 0; y &lt; count - 1; y++)\n {\n if (arr[y] &gt; arr[y + 1])\n {\n var temp = arr[y];\n arr[y] = arr[y + 1];\n arr[y + 1] = temp;\n }\n }\n if (swapCount == 0)\n return arr;\n count--;\n }\n\n return arr;\n }\n\n //...\n \n public int[] BubbleSortForForTuple(int[] arr)\n {\n for (int count = arr.Length; count &gt; 0; count--)\n {\n int swapCount = 0;\n for (int y = 0; y &lt; count - 1; y++)\n {\n if (arr[y] &gt; arr[y + 1])\n {\n swapCount++;\n (arr[y], arr[y + 1]) = (arr[y + 1], arr[y]);\n }\n }\n if (swapCount == 0)\n return arr;\n }\n\n return arr;\n }\n}\n</code></pre>\n<ul>\n<li><code>MemoryDiagnoser</code> allows us to measure memory allocation and GC times.\n<ul>\n<li>Most of the variables are allocated on a stack, so in this particular case this will not give us too much valuable information</li>\n</ul>\n</li>\n<li><code>Length</code> it allows us to run the experiments with different values\n<ul>\n<li>In our case this means that the to be sorted array's length is 500, 1000 or 1500</li>\n</ul>\n</li>\n<li><code>Setup</code>: creates an array with the specified length and then we are shuffling its elements</li>\n<li><code>.ToArray</code>: copies the original <code>array</code>, so each and every benchmark will run against the same dataset</li>\n<li><code>[Benchmark]</code> this attribute depicts the different probes</li>\n<li><code>[Benchmark(Baseline = true)]</code>: specifies which probe is the baseline &lt;&lt; against which the other probes are compared</li>\n</ul>\n<p>For the sake of demonstration I've created several probes where I used <code>for</code> or <code>while</code> for inner or outer loops. I've also change the <code>temp</code> variable to tuple in some probes.</p>\n<p>Here are the results:</p>\n<pre class=\"lang-none prettyprint-override\"><code>BenchmarkDotNet=v0.13.1, OS=macOS Catalina 10.15.7 (19H1419) [Darwin 19.6.0]\nIntel Core i9-9980HK CPU 2.40GHz, 1 CPU, 16 logical and 8 physical cores\n.NET SDK=5.0.402\n [Host] : .NET 5.0.11 (5.0.1121.47308), X64 RyuJIT [AttachedDebugger]\n ShortRun : .NET 5.0.11 (5.0.1121.47308), X64 RyuJIT\n\nJob=ShortRun IterationCount=3 LaunchCount=1 \nWarmupCount=3 \n\n| Method | Length | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Allocated |\n|--------------- |------- |---------------:|--------------:|-------------:|-------:|--------:|-------:|----------:|\n| WhileWhileTemp | 500 | 167,910.5 ns | 63,281.94 ns | 3,468.70 ns | 257.04 | 5.25 | - | 2 KB |\n| WhileForTemp | 500 | 653.3 ns | 23.83 ns | 1.31 ns | 1.00 | 0.00 | 0.2413 | 2 KB |\n| WhileForTuple | 500 | 164,168.9 ns | 109,913.01 ns | 6,024.70 ns | 251.30 | 8.75 | - | 2 KB |\n| ForForTuple | 500 | 166,614.4 ns | 57,209.60 ns | 3,135.85 ns | 255.06 | 5.00 | - | 2 KB |\n| ForForTemp | 500 | 163,877.6 ns | 83,371.18 ns | 4,569.86 ns | 250.87 | 7.50 | - | 2 KB |\n| ForWhileTemp | 500 | 162,630.7 ns | 116,827.12 ns | 6,403.69 ns | 248.95 | 9.48 | - | 2 KB |\n| ForWhileTuple | 500 | 167,843.9 ns | 10,366.49 ns | 568.22 ns | 256.94 | 1.09 | - | 2 KB |\n| | | | | | | | | |\n| WhileWhileTemp | 1000 | 606,767.4 ns | 209,931.79 ns | 11,507.07 ns | 479.10 | 28.97 | - | 4 KB |\n| WhileForTemp | 1000 | 1,268.6 ns | 975.12 ns | 53.45 ns | 1.00 | 0.00 | 0.4807 | 4 KB |\n| WhileForTuple | 1000 | 571,378.7 ns | 318,583.91 ns | 17,462.66 ns | 450.93 | 22.99 | - | 4 KB |\n| ForForTuple | 1000 | 599,922.2 ns | 516,351.81 ns | 28,302.98 ns | 473.16 | 21.59 | - | 4 KB |\n| ForForTemp | 1000 | 579,985.4 ns | 275,509.73 ns | 15,101.62 ns | 457.97 | 29.01 | - | 4 KB |\n| ForWhileTemp | 1000 | 626,296.2 ns | 46,020.80 ns | 2,522.56 ns | 494.31 | 22.15 | - | 4 KB |\n| ForWhileTuple | 1000 | 654,724.1 ns | 305,874.18 ns | 16,766.00 ns | 516.39 | 12.18 | - | 4 KB |\n| | | | | | | | | |\n| WhileWhileTemp | 1500 | 1,286,912.4 ns | 350,886.64 ns | 19,233.28 ns | 681.36 | 16.21 | - | 6 KB |\n| WhileForTemp | 1500 | 1,889.1 ns | 527.12 ns | 28.89 ns | 1.00 | 0.00 | 0.7172 | 6 KB |\n| WhileForTuple | 1500 | 1,264,461.8 ns | 61,117.64 ns | 3,350.06 ns | 669.45 | 9.78 | - | 6 KB |\n| ForForTuple | 1500 | 1,189,902.7 ns | 115,899.43 ns | 6,352.84 ns | 629.98 | 10.63 | - | 6 KB |\n| ForForTemp | 1500 | 1,282,977.9 ns | 560,781.86 ns | 30,738.35 ns | 679.09 | 5.92 | - | 6 KB |\n| ForWhileTemp | 1500 | 1,293,583.1 ns | 604,180.28 ns | 33,117.16 ns | 684.70 | 8.00 | - | 6 KB |\n</code></pre>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Method</th>\n<th>Length</th>\n<th style=\"text-align: right;\">Mean</th>\n<th style=\"text-align: right;\">Error</th>\n<th style=\"text-align: right;\">StdDev</th>\n<th style=\"text-align: right;\">Ratio</th>\n<th style=\"text-align: right;\">RatioSD</th>\n<th style=\"text-align: right;\">Gen 0</th>\n<th style=\"text-align: right;\">Allocated</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>WhileWhileTemp</td>\n<td>500</td>\n<td style=\"text-align: right;\">167,910.5 ns</td>\n<td style=\"text-align: right;\">63,281.94 ns</td>\n<td style=\"text-align: right;\">3,468.70 ns</td>\n<td style=\"text-align: right;\">257.04</td>\n<td style=\"text-align: right;\">5.25</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">2 KB</td>\n</tr>\n<tr>\n<td>WhileForTemp</td>\n<td>500</td>\n<td style=\"text-align: right;\">653.3 ns</td>\n<td style=\"text-align: right;\">23.83 ns</td>\n<td style=\"text-align: right;\">1.31 ns</td>\n<td style=\"text-align: right;\">1.00</td>\n<td style=\"text-align: right;\">0.00</td>\n<td style=\"text-align: right;\">0.2413</td>\n<td style=\"text-align: right;\">2 KB</td>\n</tr>\n<tr>\n<td>WhileForTuple</td>\n<td>500</td>\n<td style=\"text-align: right;\">164,168.9 ns</td>\n<td style=\"text-align: right;\">109,913.01 ns</td>\n<td style=\"text-align: right;\">6,024.70 ns</td>\n<td style=\"text-align: right;\">251.30</td>\n<td style=\"text-align: right;\">8.75</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">2 KB</td>\n</tr>\n<tr>\n<td>ForForTuple</td>\n<td>500</td>\n<td style=\"text-align: right;\">166,614.4 ns</td>\n<td style=\"text-align: right;\">57,209.60 ns</td>\n<td style=\"text-align: right;\">3,135.85 ns</td>\n<td style=\"text-align: right;\">255.06</td>\n<td style=\"text-align: right;\">5.00</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">2 KB</td>\n</tr>\n<tr>\n<td>ForForTemp</td>\n<td>500</td>\n<td style=\"text-align: right;\">163,877.6 ns</td>\n<td style=\"text-align: right;\">83,371.18 ns</td>\n<td style=\"text-align: right;\">4,569.86 ns</td>\n<td style=\"text-align: right;\">250.87</td>\n<td style=\"text-align: right;\">7.50</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">2 KB</td>\n</tr>\n<tr>\n<td>ForWhileTemp</td>\n<td>500</td>\n<td style=\"text-align: right;\">162,630.7 ns</td>\n<td style=\"text-align: right;\">116,827.12 ns</td>\n<td style=\"text-align: right;\">6,403.69 ns</td>\n<td style=\"text-align: right;\">248.95</td>\n<td style=\"text-align: right;\">9.48</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">2 KB</td>\n</tr>\n<tr>\n<td>ForWhileTuple</td>\n<td>500</td>\n<td style=\"text-align: right;\">167,843.9 ns</td>\n<td style=\"text-align: right;\">10,366.49 ns</td>\n<td style=\"text-align: right;\">568.22 ns</td>\n<td style=\"text-align: right;\">256.94</td>\n<td style=\"text-align: right;\">1.09</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">2 KB</td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n</tr>\n<tr>\n<td>WhileWhileTemp</td>\n<td>1000</td>\n<td style=\"text-align: right;\">606,767.4 ns</td>\n<td style=\"text-align: right;\">209,931.79 ns</td>\n<td style=\"text-align: right;\">11,507.07 ns</td>\n<td style=\"text-align: right;\">479.10</td>\n<td style=\"text-align: right;\">28.97</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">4 KB</td>\n</tr>\n<tr>\n<td>WhileForTemp</td>\n<td>1000</td>\n<td style=\"text-align: right;\">1,268.6 ns</td>\n<td style=\"text-align: right;\">975.12 ns</td>\n<td style=\"text-align: right;\">53.45 ns</td>\n<td style=\"text-align: right;\">1.00</td>\n<td style=\"text-align: right;\">0.00</td>\n<td style=\"text-align: right;\">0.4807</td>\n<td style=\"text-align: right;\">4 KB</td>\n</tr>\n<tr>\n<td>WhileForTuple</td>\n<td>1000</td>\n<td style=\"text-align: right;\">571,378.7 ns</td>\n<td style=\"text-align: right;\">318,583.91 ns</td>\n<td style=\"text-align: right;\">17,462.66 ns</td>\n<td style=\"text-align: right;\">450.93</td>\n<td style=\"text-align: right;\">22.99</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">4 KB</td>\n</tr>\n<tr>\n<td>ForForTuple</td>\n<td>1000</td>\n<td style=\"text-align: right;\">599,922.2 ns</td>\n<td style=\"text-align: right;\">516,351.81 ns</td>\n<td style=\"text-align: right;\">28,302.98 ns</td>\n<td style=\"text-align: right;\">473.16</td>\n<td style=\"text-align: right;\">21.59</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">4 KB</td>\n</tr>\n<tr>\n<td>ForForTemp</td>\n<td>1000</td>\n<td style=\"text-align: right;\">579,985.4 ns</td>\n<td style=\"text-align: right;\">275,509.73 ns</td>\n<td style=\"text-align: right;\">15,101.62 ns</td>\n<td style=\"text-align: right;\">457.97</td>\n<td style=\"text-align: right;\">29.01</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">4 KB</td>\n</tr>\n<tr>\n<td>ForWhileTemp</td>\n<td>1000</td>\n<td style=\"text-align: right;\">626,296.2 ns</td>\n<td style=\"text-align: right;\">46,020.80 ns</td>\n<td style=\"text-align: right;\">2,522.56 ns</td>\n<td style=\"text-align: right;\">494.31</td>\n<td style=\"text-align: right;\">22.15</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">4 KB</td>\n</tr>\n<tr>\n<td>ForWhileTuple</td>\n<td>1000</td>\n<td style=\"text-align: right;\">654,724.1 ns</td>\n<td style=\"text-align: right;\">305,874.18 ns</td>\n<td style=\"text-align: right;\">16,766.00 ns</td>\n<td style=\"text-align: right;\">516.39</td>\n<td style=\"text-align: right;\">12.18</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">4 KB</td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n</tr>\n<tr>\n<td>WhileWhileTemp</td>\n<td>1500</td>\n<td style=\"text-align: right;\">1,286,912.4 ns</td>\n<td style=\"text-align: right;\">350,886.64 ns</td>\n<td style=\"text-align: right;\">19,233.28 ns</td>\n<td style=\"text-align: right;\">681.36</td>\n<td style=\"text-align: right;\">16.21</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">6 KB</td>\n</tr>\n<tr>\n<td>WhileForTemp</td>\n<td>1500</td>\n<td style=\"text-align: right;\">1,889.1 ns</td>\n<td style=\"text-align: right;\">527.12 ns</td>\n<td style=\"text-align: right;\">28.89 ns</td>\n<td style=\"text-align: right;\">1.00</td>\n<td style=\"text-align: right;\">0.00</td>\n<td style=\"text-align: right;\">0.7172</td>\n<td style=\"text-align: right;\">6 KB</td>\n</tr>\n<tr>\n<td>WhileForTuple</td>\n<td>1500</td>\n<td style=\"text-align: right;\">1,264,461.8 ns</td>\n<td style=\"text-align: right;\">61,117.64 ns</td>\n<td style=\"text-align: right;\">3,350.06 ns</td>\n<td style=\"text-align: right;\">669.45</td>\n<td style=\"text-align: right;\">9.78</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">6 KB</td>\n</tr>\n<tr>\n<td>ForForTuple</td>\n<td>1500</td>\n<td style=\"text-align: right;\">1,189,902.7 ns</td>\n<td style=\"text-align: right;\">115,899.43 ns</td>\n<td style=\"text-align: right;\">6,352.84 ns</td>\n<td style=\"text-align: right;\">629.98</td>\n<td style=\"text-align: right;\">10.63</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">6 KB</td>\n</tr>\n<tr>\n<td>ForForTemp</td>\n<td>1500</td>\n<td style=\"text-align: right;\">1,282,977.9 ns</td>\n<td style=\"text-align: right;\">560,781.86 ns</td>\n<td style=\"text-align: right;\">30,738.35 ns</td>\n<td style=\"text-align: right;\">679.09</td>\n<td style=\"text-align: right;\">5.92</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">6 KB</td>\n</tr>\n<tr>\n<td>ForWhileTemp</td>\n<td>1500</td>\n<td style=\"text-align: right;\">1,293,583.1 ns</td>\n<td style=\"text-align: right;\">604,180.28 ns</td>\n<td style=\"text-align: right;\">33,117.16 ns</td>\n<td style=\"text-align: right;\">684.70</td>\n<td style=\"text-align: right;\">8.00</td>\n<td style=\"text-align: right;\">-</td>\n<td style=\"text-align: right;\">6 KB</td>\n</tr>\n</tbody>\n</table>\n</div>", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T17:39:22.883", "Id": "530721", "Score": "0", "body": "Wow, Thank you so much, Toby. This is a really useful thing. Many thanks for sharing this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T20:30:17.313", "Id": "530726", "Score": "0", "body": "@Saurabh It was me, Peter, who posted this. Tody just fixed something on the formatting. I'm glad that you have found it useful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T16:15:32.977", "Id": "269018", "ParentId": "268983", "Score": "4" } } ]
{ "AcceptedAnswerId": "269018", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:21:06.820", "Id": "268983", "Score": "2", "Tags": [ "c#" ], "Title": "Is my approach to bubble sort correct?" }
268983
<p>I'm learning Dynamic Programming and trying to solve this Target Sum array problem. I've to find an array of integers that sums to a given target sum using the integers of given input array. I've used memoization technique but still getting TLE. Can somebody help what I might be doing wrong. This is my code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;optional&gt; std::optional&lt;std::vector&lt;int&gt;&gt; can_sum(const long long target_sum, const std::vector&lt;int&gt;&amp; nums, std::vector&lt;std::optional&lt;std::vector&lt;int&gt;&gt;&gt;&amp; memo) { if (target_sum == 0) return std::vector&lt;int&gt;(); else if (target_sum &lt; 0) return std::nullopt; else if (memo[target_sum]) return memo[target_sum]; for (const auto val : nums) { std::optional&lt;std::vector&lt;int&gt;&gt; arr = can_sum(target_sum - val, nums, memo); if (arr) { arr.value().push_back(val); memo[target_sum] = arr; return arr; } } memo[target_sum] = std::nullopt; return std::nullopt; } int main() { const long long target_sum = 300LL; const std::vector&lt;int&gt; nums { 7, 14 }; std::vector&lt;std::optional&lt;std::vector&lt;int&gt;&gt;&gt; memo(target_sum + 1); std::optional&lt;std::vector&lt;int&gt;&gt; arr = can_sum(target_sum, nums, memo); if (arr) { for (const auto val : arr.value()) std::cout &lt;&lt; val &lt;&lt; &quot;, &quot;; std::cout &lt;&lt; std::endl; } else std::cout &lt;&lt; &quot;null&quot; &lt;&lt; std::endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:20:23.840", "Id": "530584", "Score": "0", "body": "\"_Can somebody help what I might be doing wrong._\" Code Review is for reviewing working code, looking for: security holes, hidden bugs, clarity, maintainability, inefficiencies, and scalability. It is not for assistance getting the code to work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:25:13.723", "Id": "530586", "Score": "0", "body": "@AJNeufeld My code works for small target sums, but for this case I'm getting TLE" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:27:11.697", "Id": "530587", "Score": "3", "body": "You'll should include the problem text in the body of your post. It is not clear what the \"Target Sum array problem\" exactly is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:32:02.213", "Id": "530588", "Score": "0", "body": "@AJNeufeld updated the post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:39:24.800", "Id": "530589", "Score": "3", "body": "The exact problem text, with limits, and examples. Perhaps even a link to the target question as well (does not eliminate the need to embed the exact problem text with limits and examples in your post, as links do vanish over time, or may require logins to view). It does not seem to match [Target Sum](https://leetcode.com/problems/target-sum/) or [Combination Sum](https://leetcode.com/problems/combination-sum/) or [Two Sum](https://leetcode.com/problems/two-sum/) or any other challenge I can see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:18:13.697", "Id": "530593", "Score": "0", "body": "I'm not sure what this is supposed to do, am I on the right track [TIO](https://bit.ly/3lEIVwt)?" } ]
[ { "body": "<p>In your memoization you cannot distinguish between target sums that have not been evaluated, and ones that you have evaluated but have no solution. This results in re-running these unsuccessful possibilities.</p>\n<p>You should add some way to tell these two cases apart: Either use an empty vector to indicate that there is no viable sum, or use a class that stores the vector and has a couple of flags, one to indicate that the cached value is valid (has already been computed) and the other if the solution has been computed and is not possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:49:45.533", "Id": "530590", "Score": "0", "body": "doesn't `std::vector<std::optional<std::vector<int>>> memo` serve that purpose. If `memo[target_sum]` which is `std::optional<std::vector<int>>` is initialized return that `std::optional<std::vector<int>>` else compute it and store it `memo[target_sum]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:52:21.427", "Id": "530591", "Score": "1", "body": "@Harry You have [default constructed](https://en.cppreference.com/w/cpp/utility/optional/optional) `optional` objects (which will have not have a value (`std::nullopt`). If the sum fails, you store `std::nullopt` in to the optional value, which is the same as a default constructed one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:06:17.110", "Id": "530592", "Score": "0", "body": "Thanks for correcting me. I used an `std::map` instead of `std::vector` for declaring `memo` type. It now works." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T15:40:27.743", "Id": "268987", "ParentId": "268985", "Score": "3" } } ]
{ "AcceptedAnswerId": "268987", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T14:48:16.463", "Id": "268985", "Score": "1", "Tags": [ "c++", "time-limit-exceeded", "dynamic-programming" ], "Title": "Target Sum array using Dynamic Programming" }
268985
<p><strong>What do I need help with?</strong></p> <p>I'm doing the challenge below, in which I need to increase code performance. It's currently at 63% and I need to increase it to at least 71% however I can't optimize more than the current one.<br /> How can it be optimized?</p> <blockquote> <p><strong>Introduction</strong></p> <p>You are a member of a biotechnology programming team that is responsible for creating a system for lab technicians, which will assist them with drug analysis.</p> <p>Your goal is to create the application that will let them input their findings into the system, provide a meaningful analysis and verify the correctness of the data that they have sent.</p> <p><strong>Prerequisites</strong></p> <p>To complete this task, use <code>Python 3</code>.</p> <p><strong>Task Details</strong></p> <p>Note: Please do <em>NOT</em> modify any tests unless specifically told to do so.</p> <h3>Part 1</h3> <p>Your goal in this part is to implement the <code>app.drug_analyzer.DrugAnalyzer</code> class. It will be responsible for analyzing data like the data presented below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">pill_id</th> <th style="text-align: right;">pill_weight</th> <th style="text-align: right;">active_substance</th> <th style="text-align: right;">impurities</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">L01-10</td> <td style="text-align: right;">1007.67</td> <td style="text-align: right;">102.88</td> <td style="text-align: right;">1.00100</td> </tr> <tr> <td style="text-align: center;">L01-06</td> <td style="text-align: right;">996.42</td> <td style="text-align: right;">99.68</td> <td style="text-align: right;">2.00087</td> </tr> <tr> <td style="text-align: center;">G02-03</td> <td style="text-align: right;">1111.95</td> <td style="text-align: right;">125.04</td> <td style="text-align: right;">3.00004</td> </tr> <tr> <td style="text-align: center;">G03-06</td> <td style="text-align: right;">989.01</td> <td style="text-align: right;">119.00</td> <td style="text-align: right;">4.00062</td> </tr> </tbody> </table> </div> <ul> <li>The initialization of the class can be done from Python's list of lists (or nothing) and stored in the instance variable called <code>data</code> as per example below:</li> </ul> <pre><code>&gt;&gt; my_drug_data = [ ... ['L01-10', 1007.67, 102.88, 1.00100], ... ['L01-06', 996.42, 99.68, 2.00087], ... ['G02-03', 1111.95, 125.04, 3.00100], ... ['G03-06', 989.01, 119.00, 4.00004] ... ] &gt;&gt;&gt; my_analyzer = DrugAnalyzer(my_drug_data) &gt;&gt;&gt; my_analyzer.data [['L01-10', 1007.67, 102.88, 0.001], ... ['L01-06', 996.42, 99.68, 0.00087], ... ['G02-03', 1111.95, 125.04, 0.00100], ... ['G03-06', 989.01, 119.00, 0.00004]] &gt;&gt;&gt; DrugAnalyzer().data [] </code></pre> <ul> <li>The class should also have an option to add single lists into the object. Adding a list to the <code>DrugAnalyzer</code> object should return a new instance of this object with an additional element. Adding improper type or a list with improper length should raise a <code>ValueError</code>. An example of a correct and wrong addition output is shown below:</li> </ul> <pre><code>&gt;&gt;&gt; my_new_analyzer = my_analyzer + ['G03-01', 789.01, 129.00, 0.00008] &gt;&gt;&gt; my_new_analyzer.data [['L01-10', 1007.67, 102.88, 0.001], ... ['L01-06', 996.42, 99.68, 0.00087], ... ['G02-03', 1111.95, 125.04, 0.00100], ... ['G03-06', 989.01, 119.00, 0.00004], ... ['G03-01', 789.01, 129.00, 0.00008]] &gt;&gt;&gt; my_new_analyzer = my_analyzer + ['G03-01', 129.00, 0.00008] Traceback (the most recent call is displayed as the last one):   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ValueError: Improper length of the added list. </code></pre> <h3>Part 2</h3> <p>Implement the <code>verify_series</code> method inside the <code>app.drug_analyzer.DrugAnalyzer</code> class.</p> <p>The goal of this method is to receive a list of parameters and use them to verify if the pills described inside the instance variable <code>data</code> matches the given criteria. It should return a <code>Boolean</code> value as a result.</p> <p>The function would be called as follows:</p> <pre><code>verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001) </code></pre> <p>Where:</p> <ul> <li>the <code>series_id</code> is a 3 characters long string that is present at the beginning of every <code>pill_id</code>, before the <code>-</code> sign, for example, <code>L01</code> is the <code>series_id</code> in <code>pill_id = L01-12</code>.</li> <li>the <code>act_subst_wgt</code> is the expected weight (<em>mg</em>) of the active substance content in the given series in one pill.</li> <li>the <code>act_subst_rate</code> is the allowed rate of difference in the active substance weight from the expected one. For example, for <code>100 mg</code>, the accepted values would be between <code>95</code> and <code>105</code>.</li> <li>the <code>allowed_imp</code> is the allowed rate of impure substances in the <code>pill_weight</code>. For example, for <code>1000 mg</code> pill_weight and <code>0.001</code> rate, the allowed amount of impurities is <code>1 mg</code>.</li> </ul> <p>The function should take all pills that are part of the <code>L01</code> series, sum their weight and calculate if the amount of <code>active_substance</code>, as well as <code>impurities</code>, match the given rates. It should return <code>True</code> if both conditions are met and <code>False</code> if any of them is not met.</p> <p>The <code>False</code> result should mean that all the passed parameters are proper, but either the <code>active_substance</code> amount or the <code>impurities</code> amount is improper.<br /> In case of a <code>series_id</code> that is not present in the <code>data</code> at all or in case of any improper parameter, the function should throw a <code>ValueError</code>.<br /> Please think what could be the possible edge case in such a scenario.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; my_drug_data = [ ... ['L01-10', 1000.02, 102.88, 1.00100], ... ['L01-06', 999.90, 96.00, 2.00087], ... ['G02-03', 1000, 96.50, 3.00100], ... ['G03-06', 989.01, 119.00, 4.00004] ... ] &gt;&gt;&gt; my_analyzer = DrugAnalyzer(my_drug_data) &gt;&gt;&gt; my_analyzer.verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001) False &gt;&gt;&gt; // The overall active_substances weight would be 198.88, which is within the given rate of 0.05 for 200 mg (2 * act_subst_wgt). &gt;&gt;&gt; // However, the sum of impurities would be 3.00187, which is more than 0.001*1999.92 (allowed_imp_rate * (1000.02 + 999.90). &gt;&gt;&gt; my_analyzer.verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.0001) True &gt;&gt;&gt; my_analyzer.verify_series(series_id = 'B03', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001) Traceback (the most recent call is displayed as the last one):   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ValueError: B03 series is not present within the dataset. </code></pre> </blockquote> <h3>My Code:</h3> <pre><code>class DrugAnalyzer: def __init__(self, data=[]): self.data = data def __add__(self, other): if len(self.data[0]) != len(other): raise ValueError('Improper length of the added list.') if type(other[0]) is not str or type(other[1]) is not float or type(other[2]) is not float or type(other[3]) is not float: raise ValueError('Wrong type.') total_data = self.data total_data.append(other) return DrugAnalyzer(total_data) def verify_series( self, series_id: str, act_subst_wgt: float, act_subst_rate: float, allowed_imp: float, ) -&gt; bool: lists = list(filter(lambda k: series_id in k[0], self.data)) pills_weight = sum([liste[1] for liste in lists]) actives_substances = sum([liste[2] for liste in lists]) impurities = sum([liste[3] for liste in lists]) if (len(lists) * act_subst_wgt * (1 + act_subst_rate)) &gt; actives_substances &gt; (len(lists) * act_subst_wgt * (1 - act_subst_rate)): if impurities &lt; (allowed_imp * pills_weight): return True return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:35:30.243", "Id": "530596", "Score": "1", "body": "This fails but should succeed: `my_analyzer = DrugAnalyzer(); my_new_analyzer = my_analyzer + ['G03-01', 789.01, 129.00, 0.00008]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:38:27.477", "Id": "530597", "Score": "1", "body": "This returns a value, but should raise an exception: `DrugAnalyzer().verify_series('L01', 0, 0, 0)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T18:28:38.360", "Id": "530601", "Score": "0", "body": "Does the problem specify any limits on the size of various inputs. That is, how many different pill_id's, series_id's, additions, or calls to verify_series?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T11:07:58.503", "Id": "530762", "Score": "0", "body": "Welcome to Code Review@SE. Brainly's recruitment? For content not originated by you, please [tell who did and where you encountered it](https://codereview.stackexchange.com/help/referencing) - hyperlinks welcome." } ]
[ { "body": "<ul>\n<li><p><code>__init__</code> has a mutable default argument. The default argument is <em>not</em> reset between calls to a function, so multiple analyzers that start out empty will have <em>the same</em> list, which could be a problem if one of them changes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; a1 = DrugAnalyzer()\n&gt;&gt;&gt; a1.data.append(['G03-01', 789.01, 129.00, 0.00008])\n&gt;&gt;&gt; a2 = DrugAnalyzer()\n&gt;&gt;&gt; a2.data\n[['G03-01', 789.01, 129.0, 8e-05]]\n</code></pre>\n<p>One option to avoid that could be explicitly copying the argument's content to a new list, perhaps like</p>\n<pre><code>def __init__(self, drug_data=None):\n self.data = []\n if drug_data:\n self.data[:] = drug_data\n</code></pre>\n</li>\n<li><p>It feels weird that <code>__add__</code> verifies the shape of its input, but <code>__init__</code> doesn't. Especially since the pre-existing data is used to decide whether a list is valid to add with <code>__add__</code> - what if someone did <code>DrugAnalyzer([[]])</code>? Then you could only add 0-length lists to that analyzer, and a 0-length list will never pass the type check!</p>\n</li>\n<li><p>By the way, the reason I used <code>a1.data.append</code> instead of <code>+=</code> earlier? <code>__add__</code> does not work on empty <code>DrugAnalyzer</code>s - it tries to get <code>self.data[0]</code>, which won't work if <code>self.data</code> is empty</p>\n</li>\n<li><p><code>__add__</code> modifies <code>self.data</code>. Try:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; a1 = DrugAnalyzer([['G03-01', 789.01, 129.00, 0.00008]])\n&gt;&gt;&gt; a2 = a1 + ['G02-03', 1111.95, 125.04, 3.00100]\n&gt;&gt;&gt; a1.data\n[['G03-01', 789.01, 129.0, 8e-05], ['G02-03', 1111.95, 125.04, 3.001]]\n</code></pre>\n<p>This is because both the old and new analyzer share the <em>same</em> list. You probably want to explicitly create a new list instead - <code>total_data = self.data + [other]</code> could be one way to do that</p>\n</li>\n<li><p>The <code>if</code> in <code>verify_series</code> is annoyingly long. I would consider at least calculating <code>len(lists) * act_subst_weight)</code> in advance and going <code>if target_weight * (1 + act_subst_rate) &gt; active_substances &gt; (1 - act_subst_rate)</code>. Or perhaps something like <code>actual_rate = actives_substances / act_subst_weight</code> followed by <code>if (1 + act_subst_rate) &gt; actual_rate &gt; (1 - act_subst_rate)</code></p>\n</li>\n<li><p><code>verify_series</code> does not throw a <code>ValueError</code> for non-existing pill series' as the requirements demand, but instead returns <code>False</code></p>\n</li>\n<li><p><code>verify_series</code> may mis-identify pills as belonging to the wrong pill series - if I understand the requirements correctly, <code>G03-06</code> should <em>only</em> belong to the <code>G03</code> series, not <code>G0</code>, <code>06</code> or <code>3-0</code>, but this implementation will count it as being part of all those. Something like <code>series_id == k[0].split('-')[0]</code> or <code>k[0].startswith(series_id + &quot;-&quot;)</code> might be more robust</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:32:55.833", "Id": "532703", "Score": "0", "body": "Wow, very good, it helped a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T19:20:23.027", "Id": "268994", "ParentId": "268988", "Score": "2" } } ]
{ "AcceptedAnswerId": "268994", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:00:04.010", "Id": "268988", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "programming-challenge" ], "Title": "Drug Analyzer challenge" }
268988
<p>I have used below method for throttling which is a Higher Order Function (HOF), but find some difficulties to choose which one is better way to write it. Below are both methods.</p> <ol> <li>return of the <code>setTimeout()</code> assigned in a variable</li> </ol> <pre><code>const throttle = (fn, delay) =&gt; { let timerId; if (timerId) { return; } return (...args) =&gt; { timerId = setTimeout(() =&gt; { return fn(...args); }, delay); }; }; </code></pre> <ol start="2"> <li>used a boolean variable (used in snippet)</li> </ol> <pre><code>const throttle = (fn, delay) =&gt; { let inThrottle = false; return (...args) =&gt; { if (inThrottle) return; inThrottle = true; fn(...args); setTimeout(() =&gt; (inThrottle = false), delay); }; }; </code></pre> <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 positionElement = document.querySelector('#positionElement'); const main = document.querySelector('#main'); /* const throttle2 = (fn, delay) =&gt; { let timerId; if (timerId) { return; } return (...args) =&gt; { timerId = setTimeout(() =&gt; { return fn(...args); }, delay); }; }; */ const throttle = (fn, delay) =&gt; { let inThrottle = false; return (...args) =&gt; { if (inThrottle) return; inThrottle = true; fn(...args); setTimeout(() =&gt; inThrottle = false, delay); } }; const logMousePosition = (e) =&gt; { const { clientX, clientY } = e; positionElement.innerHTML = ` X: ${clientX} Y: ${clientY} Time: ${new Date().toUTCString()} `; }; main.addEventListener('mousemove', throttle(logMousePosition, 5000));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>main { width: 50vw; height: 20vh; background-color: blue; display: grid; place-items: center; color: white; margin: 2em; transform: background-color 0.3s ease-in; cursor: pointer; } main:hover { background-color: black; } section { padding: 4px; border: 1px dashed red; will-change: content; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;main id="main"&gt;Main&lt;/main&gt; &lt;section id="positionElement"&gt;&lt;/section&gt;</code></pre> </div> </div> </p> <p>Which is the better way to write it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:33:59.827", "Id": "268989", "Score": "1", "Tags": [ "javascript", "functional-programming", "comparative-review", "meta-programming" ], "Title": "Higher-order function to do throttling, written two ways" }
268989
<p>I have very recently learned some Python and found out about web scraping.</p> <p>This is my first bash at writing some code to get a playlist from a site I had previously been copying and pasting. I would love it if someone could have a look at the code and review it for me. Any advice, tips, suggestions welcome.</p> <p>sample URL - <a href="https://www.bbc.co.uk/programmes/m000yzhb" rel="nofollow noreferrer">https://www.bbc.co.uk/programmes/m000yzhb</a></p> <pre><code># Create environment by importing required functions from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup # Ask user for URL of playlist my_url = input(&quot;paste the URL here: &quot;) # Grab and process URL. Having uClient.Close() in this section bugged out - not sure why. uClient = uReq(my_url) page_html = uClient.read() page_soup = soup(page_html, &quot;html.parser&quot;) # Prep CSV file for writing. filename = &quot;take the floor.csv&quot; f = open(filename,&quot;w&quot;) # Find the section with the date of the broadcast and assign it to a variable. containers = page_soup.findAll(&quot;div&quot;,{&quot;class&quot;:&quot;broadcast-event__time beta&quot;}) date_container = containers[0] # Pull the exact info and assign it to a variable. show_date = str(date_container[&quot;title&quot;]) # Find the section with the playlist in it and assign it to a variable. containers = page_soup.findAll(&quot;div&quot;,{&quot;class&quot;:&quot;feature__description centi&quot;}) title_container = containers[0] # Pull the exact info and assign it to a variable. dance_title = str(title_container) # Clean the data a little dance1 = dance_title.replace(&quot;&lt;br/&gt;&quot; , &quot; &quot;) dance2 = dance1.replace(&quot;&lt;p&gt;&quot;, &quot; &quot;) #Write to CSV. f.write(show_date + &quot;,&quot; + dance2.replace(&quot;&lt;/p&gt;&quot;,&quot;&quot;)) f.close() </code></pre> <p>Notes: My next steps with this code (but I dont know where to start) would be to have this code run automatically once per month finding the webpages itself.(4 most recent broadcasts)</p> <p>Also worth noting is that I have added some code in here to show some data manipulation but I actually do this manipulation with a macro in excel since I found it easier to get the results I wanted that way.</p> <p>I have really enjoyed this project. I have learnt a huge amount and it has saved me a bunch of time manually copying and pasting this data to a word document.</p> <p>Thank you for taking this time to look at this any suggestions or tips are greatly appreciated!</p> <p>Cheers</p>
[]
[ { "body": "<p>I don't think the CSV format is benefiting you all that much here. You haven't written header names, and it seems you only have one column - and maybe only one row? Either you should have multiple columns with headers, or give up on CSV and just call it a text file.</p>\n<p>Otherwise:</p>\n<ul>\n<li>Prefer Requests over <code>urllib</code></li>\n<li>Check for errors during the HTTP request</li>\n<li>If possible, constrain the part of the DOM that BeautifulSoup parses, using a strainer</li>\n</ul>\n<p>The first part could look like:</p>\n<pre><code>def download_programme(session: Session, name: str) -&gt; str:\n with session.get(\n 'https://www.bbc.co.uk/programmes/' + name,\n headers={'Accept': 'text/html'},\n ) as response:\n response.raise_for_status()\n return response.text\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T19:49:06.057", "Id": "268997", "ParentId": "268990", "Score": "2" } }, { "body": "<h2>CSV</h2>\n<p>I agree with reinderien. You're not writing a CSV file. You're just writing a file you've added the extension .csv to. I suggest going at looking at an <a href=\"https://people.sc.fsu.edu/%7Ejburkardt/data/csv/csv.html\" rel=\"nofollow noreferrer\">example CSV file</a> to understand the format, which may or may not fit your needs.</p>\n<p>If you do decide to write a CSV, one line per dance might be a reasonable format.</p>\n<h2>Libraries</h2>\n<ul>\n<li>As Reinderien mentions, prefer requests over urllib</li>\n<li>BeautifulSoup is a good choice already</li>\n<li>If you're going to read or write csvs, use the standard <code>csv</code> library. But as I mention above, I don't think you're using the format right now.</li>\n</ul>\n<h2>Style</h2>\n<ul>\n<li>All code should be in a function, or in an <code>if __name__ == '__main__':</code> block.</li>\n<li>Consider splitting code into functions. Separate getting a URL, grabbing the HTML, parsing the HTML, and writing a CSV file. This code is short enough that it's not necessary, but if you want functions that's how I would split the code.</li>\n<li>Several of your comments are useless, such as <code># Pull the exact info and assign it to a variable.</code>. Not everything needs a comment--in this case, your variables names are good enough to not need them.</li>\n<li>Your comments are all about the line they're next to, which is not good style. I often have a good idea of what each line does already as a programmer, so it's equally important to help me understand what the program does as a whole. Document what the entire program does at the very top, maybe with sample output. A larger section should be labeled with a comment like &quot;read the HTML and extract a list of dances&quot;, which summarizes what a whole set of lines does. If you've seen an outline in English class, imagine something similar.</li>\n</ul>\n<h2>Next Steps</h2>\n<ul>\n<li>You can't run it monthly as long as you're taking input from the user when it runs, because you might not be there! Take input from a file or command-line arguments instead. Over time, I've found this is more flexible in general if you're the only user.</li>\n<li>What operating system are you on?\n<ul>\n<li>If you're on Windows, I'm told you can use 'scheduled tasks' to run your script monthly.</li>\n<li>If you're on Linux, <code>cron</code> can run your task monthly.</li>\n<li>If you're on Mac, you can do the same stuff as in Linux, or you could use Automator to run your script monthly.</li>\n</ul>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T04:21:17.730", "Id": "531238", "Score": "0", "body": "Thank you both so much for your input, I really appreciate you both taking the time to look at the code and offer feedback.\n\nI agree, I am not writing an CSV properly, I need to work on formatting the data in python. I basically got the information to my CSV file and created a macro to format the data before adding it to my main workbook with all the other playlists. Thank you very much for the link Zachary I will look into formatting my data before writing it to CSV.\n\nThank you both for all the comments, each comment has help me learn and further my understanding! \n\nCheers\n\nCraig" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T22:46:15.933", "Id": "269273", "ParentId": "268990", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:38:00.860", "Id": "268990", "Score": "2", "Tags": [ "python", "web-scraping", "beautifulsoup" ], "Title": "Web scraping playlist from website and writing to CSV" }
268990
<p>I need to classify URLs from a DataFrame and modify it by exact match and contains conditions:</p> <pre><code>class PageClassifier: def __init__(self, contains_pat, match_pat): &quot;&quot;&quot; :param match_pat: A dict with exact match patterns in values as lists :type match_pat: dict :param contains_pat: A dict with contains patterns in values as lists :type contains_pat: dict &quot;&quot;&quot; self.match_pat = match_pat self.contains_pat = contains_pat def worker(self, data_frame): &quot;&quot;&quot; Classifies pages by type (url patterns) :param data_frame: DataFrame to classify :return: Classified by URL patterns DataFrame &quot;&quot;&quot; try: for key, value in self.contains_pat.items(): reg_exp = '|'.join(value) data_frame.loc[data_frame['url'].str.contains(reg_exp, regex=True), ['page_class']] = key for key, value in self.match_pat.items(): data_frame.loc[data_frame['url'].isin(value), ['page_class']] = key return data_frame except Exception as e: print('page_classifier(): ', e, type(e)) df = pd.read_csv('logs.csv', delimiter='\t', parse_dates=['date'], chunksize=1000000) contains = {'catalog': ['/category/', '/tags', '/search'], 'resources': ['.css', '.js', '.woff', '.ttf', '.html', '.php']} match = {'info_pages': ['/information', '/about-us']} classify = PageClassifier(contains, match) new_pd = pd.DataFrame() for num, chunk in enumerate(df): print('Start chunk ', num) new_pd = pd.concat([new_pd, classify.worker(chunk)]) new_pd.to_csv('classified.csv', sep='\t', index=False) </code></pre> <p>But it is very slow and takes to much RAM when I work with files over 10GB. How can I search and modify data faster? I need &quot;exact match&quot; and &quot;contains&quot; patterns searching in one func.</p>
[]
[ { "body": "<p>The first thing I notice here that will tank performance the most is:</p>\n<pre><code>new_pd = pd.concat([new_pd, classify.worker(chunk)])\n</code></pre>\n<p>cs95 outlines this issue very well in <a href=\"https://stackoverflow.com/a/56746204/15497888\">their answer here</a>. The general advice is &quot;NEVER grow a DataFrame!&quot;. Essentially creating a new copy of the DataFrame in each iteration is quadratic in time complexity as the entire DataFrame is copied each iteration, <em>and</em> the DataFrame only gets larger which ends up costing more and more time.</p>\n<p>If we wanted to improve this approach we might consider something like:</p>\n<pre><code>df_list = []\nfor num, chunk in enumerate(df):\n df_list.append(classify.worker(chunk))\n\nnew_pd = pd.concat(df_list, ignore_index=True)\nnew_pd.to_csv('classified.csv', sep='\\t', index=False)\n</code></pre>\n<p>However, assuming we don't ever need the entire DataFrame in memory at once, and given that our <code>logs.csv</code> is so large that we need to <em>read it</em> in chunks, we should also consider <em>writing out</em> our DataFrame in chunks:</p>\n<pre><code>for num, chunk in enumerate(df):\n classify.worker(chunk).to_csv(\n 'classified.csv', sep='\\t', index=False,\n header=(num == 0), # only write the header for the first chunk,\n mode='w' if num == 0 else 'a' # append mode after the first iteration\n )\n</code></pre>\n<hr />\n<p>In terms of reading in the file, we appear to only using the <code>url</code> and <code>page_class</code> columns. Since we're not using the DateTime functionality of the <code>date</code> column we don't need to take the time to parse it.</p>\n<pre><code>df = pd.read_csv('logs.csv', delimiter='\\t', chunksize=1000000)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:00:45.647", "Id": "530620", "Score": "0", "body": "Thanks for your answer. Especially for \"header=(num == 0), mode='w' if num == 0 else 'a'\". This was very useful example for my practice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T04:35:09.097", "Id": "269005", "ParentId": "268992", "Score": "2" } } ]
{ "AcceptedAnswerId": "269005", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T19:00:27.540", "Id": "268992", "Score": "1", "Tags": [ "python", "python-3.x", "csv", "pandas" ], "Title": "How to speed up the search by patterns matching and modifying a DataFrame" }
268992
<p>Realize the Radio and Channel classes that represent radio and a radio station. The radio class offers an argumentless constructor and the following methods:</p> <ul> <li>addChannel: stores and returns a new station, characterized by name, frequency. Attempting to store a station that has the same frequency as an already stored station should result in an exception.</li> <li>nearest: accepts a frequency and returns the station with the closest frequency to that given.</li> </ul> <p>Furthermore, if you iterate on a Radio object you get the sequence of stations entered, in increasing order of frequency.</p> <p>Make sure that the only way to create Channel objects is through the addChannl method.</p> <p>Observe the following example of use:</p> <pre><code>Radio r = new Radio(); Channel c1 = r.addChannel(&quot;Rai Radio Uno&quot;, 89.3); Channel c2 = r.addChannel(&quot;Radio Monte Carlo&quot;, 96.4); Channel c3 = r.addChannel(&quot;Radio Kiss Kiss&quot;, 101.4); for(Channel c: r) { System.out.println(c); } System.out.println(r.nearest(98.1)); </code></pre> <p><strong>Output: Radio Monte Carlo (96.4)</strong></p> <p>I would like your opinion on my implementation. What can be improved or fixed?</p> <p>My implementation:</p> <pre><code>import java.util.*; public class Radio implements Iterable&lt;Radio.Channel&gt;{ public static final Comparator&lt;Channel&gt; COMP = (Channel c1, Channel c2) -&gt; { return Double.compare(c1.frequenza, c2.frequenza); }; private Set&lt;Channel&gt; channels; private List&lt;Channel&gt; my_nesteds; public Radio() { channels = new TreeSet&lt;&gt;(COMP); my_nesteds = new ArrayList&lt;&gt;(); } public Channel addChannel(String nome, double frequenza) { Channel new_channel = new Channel(nome,frequenza); if(!channels.add(new_channel)){ throw new RuntimeException(&quot;...&quot;); } return new_channel; } public Channel nearest(double frequenza){ double distance = 0.0; double min = 0.0; boolean first = true; Channel ret_channel = null; for(Channel cc: channels) { if(first) { min = Math.abs(cc.frequenza - frequenza); ret_channel = cc; first = false; }else { distance = Math.abs(cc.frequenza - frequenza); if(min &gt; distance) { min = distance; ret_channel = cc; } } } return ret_channel; } @Override public Iterator&lt;Radio.Channel&gt; iterator() { return new Iterator&lt;&gt;() { int index = 0; @Override public boolean hasNext() { if(index &lt; channels.size()) { return true; } return false; } @Override public Channel next() { if(index &lt; channels.size()) { Channel c = my_nesteds.get(index); index++; return c; } throw new NoSuchElementException(); } }; } /* **************************************************** */ protected class Channel{ private String nome; private double frequenza; public Channel(String nome, double frequenza) { this.nome = nome; this.frequenza = frequenza; my_nesteds.add(this); } @Override public String toString() { return nome+&quot; &quot;+&quot;(&quot;+frequenza+&quot;)&quot;; } @Override public boolean equals(Object o){ if(!(o instanceof Channel)){ return false; } Channel c = (Channel) o; if(COMP.compare(this,c) == 0){ return true; } return false; } } /* **************************************************** */ } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:14:11.703", "Id": "530638", "Score": "0", "body": "@dariosicily `comp` is a static final field after the constructor. Unusual, but working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:18:51.313", "Id": "530639", "Score": "0", "body": "We see a classic problem with homework here. `TreeSet` is a `NavigableSet` which has readymade `ceiling()` and `floor()` functions. In a professional review, I'd tell the developer to use these instead of calculating the distance manually. Here, I guess these features have not been subject in the class yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:19:24.983", "Id": "530640", "Score": "0", "body": "Hi @dariosicily, thanks for the welcome.\nThe code compiles correctly. If you pay attention, after the Radio constructor there is the \"comp\" comparator that I used in the TreeSet constructor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:24:50.420", "Id": "530641", "Score": "0", "body": "@mtj and Giuseppe. Thank you and excuse me, I wrote a stupid thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:26:27.513", "Id": "530642", "Score": "0", "body": "Hi @mtj, why is it unusual to have a constant like mine? In the String library, there are class constants like this, one example is: `public static final Comparator <String> CASE_INSENSITIVE_ORDER`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:30:11.553", "Id": "530643", "Score": "0", "body": "@Giuseppe First of all, you'd normally name a constant in uppercase (`COMP`), then you usually declare constants at the top of the class, followed by member variables, then constructors, and methods last. That's probably why dariosicily did not spot it at the first glance. (And yes, the java library does not folllow this accepted standard in some cases. ;-))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:32:34.130", "Id": "530644", "Score": "0", "body": "@mtj Exactly, I thought `comp` was absent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T10:51:35.277", "Id": "530645", "Score": "0", "body": "@mtj thank you for your advice, but the `channels` are of the declared type `Set` and I cannot use the methods you advised me. These methods also take a `Channel` as an argument (in my case), but it is not possible to create a `Channel` with a given frequency because the trace explicitly says that: \"Make sure the only way to create Channel objects is through the addChannel method\"." } ]
[ { "body": "<p><strong>Advice 1: missing package</strong></p>\n<p>I suggest you put your classes into a package. Consider something like:</p>\n<pre><code>package com.github.giuseppe.radio;\n\nimports...\n\ncode...\n</code></pre>\n<p><strong>Advice 2</strong></p>\n<pre><code>import java.util.*;\n</code></pre>\n<p>I suggest you explicitly list all the classes you import from <code>java.util</code>.</p>\n<p><strong>Advice 3</strong></p>\n<pre><code>private Set&lt;Channel&gt; channels;\nprivate List&lt;Channel&gt; my_nesteds;\n</code></pre>\n<p>I suggest the following:</p>\n<pre><code>private final NavigableSet&lt;Channel&gt; channels = new TreeSet&lt;&gt;();\n</code></pre>\n<p>(See later.) With that arrangement you can get rid of the constructor since you initialize the data structures within field definition.</p>\n<p><strong>Advice 4</strong></p>\n<pre><code>public Channel addChannel(String nome, double frequenza) {\n Channel new_channel = new Channel(nome,frequenza);\n if(!channels.add(new_channel)){\n throw new RuntimeException(&quot;...&quot;);\n }\n return new_channel;\n\n}\n</code></pre>\n<p>Allow me to disagree, but I think the following is more idiomatic:</p>\n<pre><code>public void addChannel(Channel channel) {\n channels.add(Objects.requireNonNull(channel, &quot;Channel is null.&quot;));\n}\n</code></pre>\n<p><strong>Advice 5: the nearest channel algorithm</strong></p>\n<p>Your current solution will iterate the entire (sorted by frequencies) channel set. You can stop the iteration earlier. (See later.)</p>\n<p><strong>Advice 6</strong></p>\n<pre><code>protected class Channel{\n\n private String nome;\n private double frequenza;\n\n public Channel(String nome, double frequenza) {\n this.nome = nome;\n this.frequenza = frequenza;\n my_nesteds.add(this);\n }\n\n @Override\n public String toString() {\n return nome+&quot; &quot;+&quot;(&quot;+frequenza+&quot;)&quot;;\n }\n\n\n @Override\n public boolean equals(Object o){\n if(!(o instanceof Channel)){ return false; }\n Channel c = (Channel) o;\n if(COMP.compare(this,c) == 0){ return true; }\n return false;\n }\n\n }\n</code></pre>\n<p><code>nome</code>, <code>frequenza</code>: I suggest you use English for naming your identifiers. Consider <code>name</code> and <code>frequency</code> instead.</p>\n<p><strong>Summa summarum</strong></p>\n<p>All in all, I though about this implementation:</p>\n<p><strong><code>radio.Channel</code>:</strong></p>\n<pre><code>package radio;\n\nimport java.util.Objects;\n\npublic class Channel implements Comparable&lt;Channel&gt; {\n\n private final String name;\n private final double frequency;\n\n public Channel(String name, double frequency) {\n this.name = checkName(name);\n this.frequency = checkFrequency(frequency);\n }\n \n public double getFrequency() {\n return frequency;\n }\n \n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(&quot;[Channel: &quot;);\n return sb.append(name)\n .append(&quot;, frequency: &quot;)\n .append(frequency)\n .append(&quot;]&quot;).toString();\n }\n\n @Override\n public boolean equals(Object o){\n if(!(o instanceof Channel)){ \n return false; \n }\n \n Channel c = (Channel) o;\n return frequency == c.frequency;\n }\n\n private static String checkName(String name) {\n Objects.requireNonNull(name, &quot;The channel name is null.&quot;);\n \n if (name.isBlank()) {\n throw new IllegalArgumentException(&quot;The channel name is blank.&quot;);\n }\n \n return name;\n }\n \n private static double checkFrequency(double frequency) {\n if (Double.isNaN(frequency)) {\n throw new IllegalArgumentException(&quot;The frequency is NaN.&quot;);\n }\n \n if (Double.isInfinite(frequency)) {\n throw new IllegalArgumentException(\n frequency &lt; 0.0 ? \n &quot;The frequency is positive infinite.&quot; :\n &quot;The frequency is negative infinite.&quot;);\n }\n \n return frequency;\n }\n\n @Override\n public int compareTo(Channel o) {\n return Double.compare(frequency, o.frequency);\n }\n}\n</code></pre>\n<p><strong><code>radio.Radio</code>:</strong></p>\n<pre><code>package radio;\n\nimport java.util.Iterator;\nimport java.util.NavigableSet;\nimport java.util.NoSuchElementException;\nimport java.util.Objects;\nimport java.util.TreeSet;\nimport java.util.function.Consumer;\n\npublic class Radio {\n\n private final NavigableSet&lt;Channel&gt; channels = new TreeSet&lt;&gt;();\n\n public void addChannel(Channel channel) {\n channels.add(Objects.requireNonNull(channel, &quot;Channel is null.&quot;));\n }\n\n public Channel getNearest(double frequency) {\n switch (channels.size()) {\n case 0:\n throw new NoSuchElementException(&quot;No channels in radio.&quot;);\n\n case 1:\n return channels.first();\n }\n\n if (frequency &lt;= channels.first().getFrequency()) {\n return channels.first();\n }\n\n if (frequency &gt;= channels.last().getFrequency()) {\n return channels.last();\n }\n\n Channel token = new Channel(&quot;Token&quot;, frequency);\n Channel channelA = channels.floor(token);\n Channel channelB = channels.ceiling(token);\n\n double frequencyDistanceA = frequency - channelA.getFrequency();\n double frequencyDistanceB = channelB.getFrequency() - frequency;\n\n return frequencyDistanceA &lt;= frequencyDistanceB ?\n channelA :\n channelB;\n }\n\n public Iterable&lt;Channel&gt; getChannelsIterable() {\n return new Iterable&lt;&gt;() {\n\n @Override\n public Iterator&lt;Channel&gt; iterator() {\n\n return new Iterator&lt;&gt;() {\n private final Iterator&lt;Channel&gt; iterator = \n channels.iterator();\n\n @Override\n public boolean hasNext() {\n return iterator.hasNext();\n }\n\n @Override\n public Channel next() {\n return iterator.next();\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\n &quot;No remove allowed.&quot;);\n }\n\n @Override\n public void forEachRemaining(\n Consumer&lt;? super Channel&gt; action) {\n throw new UnsupportedOperationException(\n &quot;No forEachRemaining allowed.&quot;);\n }\n };\n }\n };\n }\n\n public static void main(String[] args) {\n Radio r = new Radio();\n r.addChannel(new Channel(&quot;Rai Radio Uno&quot;, 89.3));\n r.addChannel(new Channel(&quot;Radio Monte Carlo&quot;, 96.4));\n r.addChannel(new Channel(&quot;Radio Kiss Kiss&quot;, 101.4));\n\n for (Channel c: r.getChannelsIterable()) {\n System.out.println(c);\n }\n\n System.out.println(r.getNearest(98.1));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:12:02.233", "Id": "530657", "Score": "0", "body": "Thanks for the advice and for your elegant creation.\nI am a student and I still know too little Java.\nMy implementations are based on things studied in the classroom and for exams.\nBut I would like to deepen the language as much as possible and have a wider knowledge. So I thank the community, which allows me to always learn new things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:26:37.097", "Id": "530662", "Score": "0", "body": "Not the best way to learn Java, but I did it by reading (back in the days) Java Language Specification. Consider doing the same, or find a book on the subject. Not just read, but also write the code snippets. Best of luck!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T13:05:56.397", "Id": "269012", "ParentId": "268999", "Score": "1" } }, { "body": "<p>Some additions to coderodde's valuable comments:</p>\n<h2>equals() and hashCode()</h2>\n<p>In the <code>Channel</code> class, you override the <code>equals()</code> method, but not <code>hashCode()</code>. Then, using Channels in hashtable-based collections (<code>Hashtable</code>, <code>HashMap</code>, <code>HashSet</code> etc.) will give unexpected results.</p>\n<p>So, <strong>always override both</strong>, using the same fields for comparison and for hash value calculation (or let your IDE like Eclipse generate these methods for you).</p>\n<h2>Channel constructor</h2>\n<p>It's at least unusual to have a constructor register the newly-created object in some registry outside of the instance (the <code>my_nesteds.add(this);</code> statement). A constructor should only create the instance. It's the responsibility of the code calling the constructor to put this instance into a list or set. What makes things worse is that you add to <code>my_nesteds</code> inside the <code>Channel</code> constructor, but to <code>channels</code> in the <code>addChannel()</code> method.</p>\n<h2>Iterator</h2>\n<p>You implement an <code>Iterator</code> yourself, but you could as well just let the <code>channels</code> set do it for you:</p>\n<pre><code>@Override\npublic Iterator&lt;Radio.Channel&gt; iterator() {\n return channels.iterator();\n}\n</code></pre>\n<p>The only risk is that a (non-cooperative) caller of that iterator might use the <code>Iterator.remove()</code> method and change your channels list from outside. If you want to protect against that, you can do</p>\n<pre><code>@Override\npublic Iterator&lt;Radio.Channel&gt; iterator() {\n return Collections.unmodifiableSet(channels).iterator();\n}\n</code></pre>\n<h2>Naming conventions</h2>\n<p>While most of your names follow the established Java naming conventions, <code>my_nesteds</code> doesn't. Instance fields should be written in &quot;camelCase&quot;, meaning your variable should be written <code>myNesteds</code>. The underscore is only used in ALL_CAPITALS constants. By the way, <code>myNesteds</code> is not a good name anyway, something like <code>channelsList</code> would be more helpful.</p>\n<p>Regarding English or Italian: that's up to you, but your current code shows a wild mixture of both languages. Of course, if you want to collaborate on an international level (what you're already doing here), English is the way to go (and doesn't seem to be a problem for you).</p>\n<h2>Javadoc</h2>\n<p>You should make it a habit to document public classes and methods, those that might be called by someone else when working in a team, so they know what to expect from e.g. calling the <code>nearest()</code> method. Use the Javadoc conventions (probably well supported by your IDE). You can use the wording from the task text as a good example.</p>\n<p>Describe what the method does, not how it does it (your version vs. coderodde's version). Describe it from the user's point of view - to the user it doesn't matter whether you use a linear search or some TreeSet methods to find the nearest channel.</p>\n<p>This not only helps you when writing your code (and reading it, maybe next year), but also defines the interface, how to use the class. Users should be able to create Radios and Channels without having to read your code, just by looking at the documentation. And if you want to improve your implementation later, you can throw away everything, as long as you still provide the same public classes and methods, and they stille follow the documented behaviour.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T08:15:07.977", "Id": "530690", "Score": "0", "body": "Thanks for your advice. In the Channel class, that override of equals is to ensure that the contract of Set (which considers two elements equal according to equals) and the contract of TreeSet (which considers two elements equal according to the comparator) are respected. So you have to respect x.equals (y) == true <-> COMP.compare (x, y) == 0." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T15:50:24.310", "Id": "269016", "ParentId": "268999", "Score": "1" } } ]
{ "AcceptedAnswerId": "269016", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T21:26:58.673", "Id": "268999", "Score": "2", "Tags": [ "java", "array", "iterator", "lambda", "set" ], "Title": "Radio with channels" }
268999
<p>Given the following data struct:</p> <pre><code>typdef struct lista { int num1, num2; struct lista* sig; } nodoNum ; </code></pre> <p>and a declared <code>nodoNum</code> pointer variable, the following function will take said variable and create nodes, link them and stop when the user inputs &quot;0&quot; as the first number and return a pointer to the first node (or a null pointer if numbers were provided).</p> <pre><code>nodoNum * crearLista(nodoNum * registro) { nodoNum * auxNodo; int tempNum1; printf(&quot;Introducir numero 1 &gt;\n&quot;); scanf(&quot;%d&quot;, &amp;tempNum1); if (tempNum1 != 0) { auxNodo = (nodoNum *) malloc(sizeof(nodoNum)); auxNodo-&gt;num1 = tempNum1; printf(&quot;Introducir numero 2 &gt;\n&quot;); scanf(&quot;%d&quot;, &amp;auxNodo-&gt;num2); auxNodo-&gt;sig = crearLista(auxNodo); return auxNodo; } else { return NULL; } } </code></pre> <p>I have been asking some questions over at Stack Overflow to understand more about pointers. I have arrived at this solution after a while. I'm interested in knowing if I'm breaking some best practice or where there could be room for improvement. As far as I know, it works... but as a beginner, I can never be sure!</p>
[]
[ { "body": "<p>There is a small typo in this line:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>typdef struct lista {\n</code></pre>\n<p>It should be</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>typedef struct lista {\n</code></pre>\n<p>I ran <code>sig</code> through Google translate and it came up with <code>Mr</code>. Not very helpful, so I'm asuming the <code>sig</code> means <code>next</code> :-)</p>\n<p>I used the following <code>main</code> function to confirm that it's working:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main() {\n nodoNum* root = crearLista(0);\n for (nodoNum* nodo = root; nodo; nodo = nodo-&gt;sig)\n printf(&quot;%d, %d\\n&quot;, nodo-&gt;num1, nodo-&gt;num2);\n}\n</code></pre>\n<p><b>Recursion</b></p>\n<p>Recursion is great when used in the correct context. Here it is not. Red flags go up when I see a recursive function without any <code>depth</code> indicator or checks. You can get a stack overflow exception if you piped enough numbers in.</p>\n<p><b>Error checking</b></p>\n<p>You should check if the <code>scanf</code> functions succeeded. If you enter a non-numeric value the program goes into a loop and crashes.</p>\n<p>Additionally, you should check if <code>malloc</code> succeeded and exit the function gracefully if not.</p>\n<p><b>Splitting out logic</b></p>\n<p>You can create a separate function to add a node to the list and remove the complexities from <code>crearLista</code>. I would recommend something like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>nodoNum* addNodo(nodoNum* registro, int num1, int num2) {\n nodoNum* auxNodo = (nodoNum*)malloc(sizeof(nodoNum));\n if (auxNodo == NULL)\n return NULL;\n auxNodo-&gt;num1 = num1;\n auxNodo-&gt;num2 = num2;\n if (registro != NULL)\n registro-&gt;sig = auxNodo;\n return auxNodo;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T18:48:21.140", "Id": "530672", "Score": "0", "body": "Yeap, \"Siguiente\" == \"Next\" in this context!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T20:09:36.433", "Id": "530676", "Score": "1", "body": "@4d4143 thanks, I know just enough Spanish to get myself into trouble ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T11:11:12.747", "Id": "269010", "ParentId": "269000", "Score": "4" } }, { "body": "<p>The obvious problems to me are:</p>\n<ol>\n<li><p>You are not using your function's parameter.</p>\n</li>\n<li><p>You are using <code>scanf</code>.</p>\n</li>\n<li><p>You are using <a href=\"https://en.wikipedia.org/wiki/Recursion\" rel=\"nofollow noreferrer\">recursion</a> where you should not use recursion.</p>\n</li>\n<li><p>You are mixing several different concerns (node creation, list organization, user input, input validation).</p>\n</li>\n<li><p>You are not handling errors.</p>\n</li>\n</ol>\n<h2>Using your function's parameter</h2>\n<p>Since you don't use the parameter, we can ask, &quot;what should the parameter be?&quot;</p>\n<p>This is a pitfall for linked lists. If your list uses a data structure to store list metadata, then the parameter would be a pointer to that data structure.</p>\n<p>If the list just uses a single variable to store a pointer to the first node in the list, then your parameter should be <em>a pointer to that variable.</em> (So you can change the actual pointer to NULL, or replace NULL with a new pointer when you create the first node.)</p>\n<p>Thus, your parameter would be something like:</p>\n<pre><code>... \ncrearLista(nodoNum ** primer) \n{\n ...\n}\n</code></pre>\n<p>And you would call it something like:</p>\n<pre><code>nodoNum * La_lista = NULL;\n\n... main(...) {\n ... crearLista(&amp;La_lista) ...\n}\n</code></pre>\n<h2>Using <code>scanf</code>.</h2>\n<p>Q: What is the difference between:</p>\n<ol>\n<li>[[something cringe-worthy and incredibly painful]]; and</li>\n<li>using <code>scanf()</code>?</li>\n</ol>\n<p>A: If someone held a gun to your head, you would agree to #1.</p>\n<p>The <code>scanf</code> function is very, very hard to use correctly. It is even harder to use <em>effectively.</em> The various ways it can fail are difficult for even experienced developers to understand and avoid. Did your pattern allow for white space? Will your pattern consume trailing newlines? What is the difference between <code>&quot; 1\\n&quot;</code> and <code>&quot;1 \\n&quot;</code> and <code>&quot;1\\n&quot;</code>? The general answer to dealing with <code>scanf</code> is not to deal with <code>scanf</code>!</p>\n<p>Here is <a href=\"http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html\" rel=\"nofollow noreferrer\">a list of ways to avoid <code>scanf</code></a>, which you might want to bookmark</p>\n<h2>Recursion</h2>\n<p>Recursion can be a useful tool, which is why it is taught in even introductory programming courses. <em>However,</em> in C it is a tool that you must use judiciously.</p>\n<p>Recursion implicitly uses the <a href=\"https://en.wikipedia.org/wiki/Call_stack\" rel=\"nofollow noreferrer\">call stack</a> to avoid looping. The cost of doing this is the creation of extra <a href=\"https://en.wikipedia.org/wiki/Call_stack#STACK-FRAME\" rel=\"nofollow noreferrer\">stack frames</a>, which consume memory in the stack region.<sup>[1]</sup></p>\n<p>This is important because the C stack is generally a limited resource. See <a href=\"https://stackoverflow.com/q/21021223/4029014\">this question &amp; answer</a> for more information.</p>\n<p>What this means for you is that a linked list, which is normally an effectively-infinite data structure, will be constrained by the limits of the run-time stack. And, of course, when you reach those limits you will not encounter a recoverable error, but instead will suffer a <em>stack overflow.</em></p>\n<p>Instead of using recursion to input more nodes, use a looping control structure instead:</p>\n<pre><code>nodoNum ** registro; // parameter\n\n// like this:\nfor (;;) {\n nodoNum * nn = create_nn_from_input(stdin);\n *registro = nn;\n registro = &amp;nn-&gt;nn_sig;\n}\n\n// OR like this:\nwhile (true) {\n nodoNum * nn = create_nn_from_input(stdin);\n *registro = nn;\n registro = &amp;nn-&gt;nn_sig;\n}\n\n// OR like this:\nnodoNum * nn = NULL;\ndo {\n nn = create_nn_from_input(stdin);\n\n if (not_null(nn)) {\n *registro = nn;\n registro = &amp;nn-&gt;nn_sig;\n }\n} while (not_null(nn));\n</code></pre>\n<h2>Separation of concerns</h2>\n<p>In the object-oriented world this is sometimes referred to as the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> (or &quot;SRP&quot;).</p>\n<p>In essence, a function should have a single concern in order to clearly convey what it is doing, to avoid errors, and to be reusable.</p>\n<p>Your function has to deal with multiple concerns, which creates confusion and introduces chances for errors to occur.</p>\n<p>Consider reading one single number from the user. You are using <code>scanf</code>, which is not a great idea. In the event of non-numeric input, how do you recover from errors? (You don't.)</p>\n<p>Now consider reading one node from the user. If the user enters zero (0), we will agree that is a valid <a href=\"https://en.wikipedia.org/wiki/Sentinel_value\" rel=\"nofollow noreferrer\">sentinel value</a> for &quot;no node/end of input&quot;, so how would it work? What happens if the user enters a valid first value (non-zero), but then you see end-of-file for the second value?</p>\n<p>Now consider what happens if you are unable to allocate memory for your next node. What happens?</p>\n<p>In every case, the answer to &quot;what happens if ... occurs&quot; is going to be either &quot;You have to restructure your code&quot; or &quot;You have to write more code&quot;.</p>\n<p>When your different concerns are isolated in separate functions, both of those tasks are simple. When your different concerns are mixed together, they interfere with each other. It can be hard to reorganize your code when you have to think about the effects of changes on multiple different things. It can be really hard to add more code when you have to keep mixing in additional concerns.</p>\n<p>I suggest that you identify the various things you are doing and create separate functions to perform each of them.</p>\n<p>You may be alarmed to find that each of those functions will be small, and very simple. <em>That is the objective!</em></p>\n<p>A small, simple function will have few bugs. It will be easily understood. It can be easily re-used. These are all good things. ;-)</p>\n<p>You may also find that &quot;small simple functions&quot; will tend to grow. When you realize that the concern of a function is doing exactly one simple thing, you may start thinking up &quot;edge cases&quot; to handle. Eventually you will have a very robust function that is not quite so small or simple, but which reliably does what it should do in even the most stressful conditions.</p>\n<h2>Handling errors</h2>\n<p>C is famous for its error handling. Not in a good way.</p>\n<p>One of the challenges of being a C developer is knowing how to handle errors. When you start work on an existing project, there will be an existing error-handling mechanism that you will hopefully learn. When you are writing your own code <em>de novo,</em> you have to provide the error handling yourself.</p>\n<p>For a simple command-line program, the easiest way to handle errors is to print some kind of message and then exit the program immediately. As your program becomes larger, you will want to allow the user to retry certain operations, or perform some kind of &quot;graceful shutdown,&quot; or just abort whatever was in process and go back to an earlier state. These are all valid things to do, but C doesn't actually support you in any of them.</p>\n<p>My suggestion would be to write yourself a failure function and a <code>FAIL</code> macro, and call it to handle errors for you:</p>\n<pre><code>noreturn void fail(const char * file, signed long line, const char * mesg, ...);\n#define FAIL(...) fail(__FILE__, __LINE__, __VA_ARGS__)\n</code></pre>\n<p>The idea is that you make a decision about how failure is to be handled. Maybe it's just print-a-message-and-exit. (In fact, for beginner-level code that's always the right answer.) Then you implement that behavior inside <code>fail()</code>. Then you always call <code>FAIL</code> which will call <code>fail</code> on failure.</p>\n<p>If you don't want to print-and-exit, there is one place to change the behavior. (Maybe you want to add logging. Maybe you want to <code>longjmp</code> to <code>main</code> and start over. Whatever, it's your code.)</p>\n<p>Doing this let's you develop coding idioms that make sense for you. If you're going to call <code>malloc</code>, you'll want to check for errors. So...</p>\n<pre><code>if (malloc(size) == NULL) FAIL(&quot;Could not malloc(%u) memory for &lt;reason&gt;&quot;);\n</code></pre>\n<p>In fact, you might find yourself <em>always</em> writing your calls to malloc that way, in which case you can just create a new function for your personal library.</p>\n<p>Obviously the same thing is true for <code>fopen</code>, <code>strdup</code>, etc. If all you do with errors is call <code>FAIL,</code> then write a wrapper function to simplify your code even more. If you do more than call <code>FAIL</code>, then ask yourself if you need to add lines to your <code>fail</code> function to simplify your code even more. ;-)</p>\n<hr />\n<p><sup>[1]</sup> To truly be called <em>recursion,</em> the memory used must be from the Stack region. If the memory does not come from the Stack region, what you are doing is merely <em>sparkling iteration.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:09:58.067", "Id": "530656", "Score": "0", "body": "Great answer, though the pedant in me wants to point out that `if (malloc(size) == NULL)` is a memory leak..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T18:49:05.923", "Id": "530673", "Score": "0", "body": "Thanks so much for the detailed answer and explanations! I created this since the code I was given in class first created a node with malloc inside the main function and only then passed it to the createList() function. I didn't think it was ok since what would happen if the user doesn't input anything at all? The node with the assigned is still there just \"empty\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T13:52:54.353", "Id": "269014", "ParentId": "269000", "Score": "4" } } ]
{ "AcceptedAnswerId": "269014", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T22:56:26.350", "Id": "269000", "Score": "3", "Tags": [ "beginner", "c", "linked-list" ], "Title": "Function to create single linked-list" }
269000
<p>here it is my simple cash register app. It lacks some functionality ( <code>class Payments</code> should have more options like daily statements etc, <code>class TillSettings</code> needs more settings as well) but it does the job. Simple Cash Register and Stock Manager allows to add items to stock and then sell it and register total value of sales (very basic options). There is one bug I haven't fixed yet but that is a matter just of time. My question is do you have any advice for beginner in building 'bigger' apps. I mean that could be extended for multiple options, clerk id, manager privileges, refunds etc but have I started anywhere close to the right way? Any advice and critic will be appreciated. This is only one of the projects for me to learn so having my code seen and commented on by people who know how to do these things is important to me.</p> <p><a href="https://i.stack.imgur.com/W0QSc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W0QSc.png" alt="enter image description here" /></a></p> <pre><code>import tkinter as tk import os, json from typing import Any from tkinter import DoubleVar, StringVar, ttk from tkinter.constants import CENTER, END, NO class Application(tk.Tk): def __init__(self, database: 'StockDatabase', settings: 'TillSettings', payments: 'Payments') -&gt; None: super().__init__() self._db = database self._sett = settings self._pay = payments self.geometry('500x500') self.geometry('+100+100') self.title('Cash Register') self.iconbitmap('icon.ico') self.createButtons() self.createPurchaseList() self.createLabels() def createButtons(self) -&gt; None: addToCart = ttk.Button(self, text='Add to basket', command=self.addToBasket) addToCart.place(x=10, y=10, width=90, height=50) stockManagment = ttk.Button(self, text='Manage Stock', command=self.manageStockWindow) stockManagment.place(x=10, y=430, width=90) exitButton = ttk.Button(self, text='EXIT', command= self.destroy) exitButton.place(x=10, y=460, width=90) paymentButton = ttk.Button(self, text='PAY', command=self.getPayment) paymentButton.place(x=390, y=420, height=70, width=90) def createPurchaseList(self) -&gt; None: columns = ('#1', '#2', '#3', '#4') # set shopping list panel self.shoppingList = ttk.Treeview(self, columns=columns, show='headings', height=27, selectmode='browse') self.shoppingList.place(x=150, y=10, width=330, height=400) self.shoppingList.heading('#1', text='Product') self.shoppingList.heading('#2', text='#') # quantity self.shoppingList.heading('#3', text='#') # price per item self.shoppingList.heading('#4', text='Sum') self.shoppingList.column('#1', anchor=CENTER, stretch=NO, width=157) self.shoppingList.column('#2', anchor=CENTER, stretch=NO, width=50) self.shoppingList.column('#3', anchor=CENTER, stretch=NO, width=50) self.shoppingList.column('#4', anchor=CENTER, stretch=NO, width=70) # set scrollbar for shopping list scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.shoppingList.yview) self.shoppingList.configure(yscrollcommand=scrollbar.set) scrollbar.place(x=481, y=10, height=400) def manageStockWindow(self) -&gt; None: mngStockWin = tk.Toplevel() mngStockWin.geometry('350x600') mngStockWin.geometry('+150+100') mngStockWin.title('Stock Manager') mngStockWin.iconbitmap('icon.ico') def addNewItem() -&gt; None: newItemWin = tk.Toplevel() newItemWin.geometry('300x200') newItemWin.geometry('+200+200') newItemWin.title('New Item Menu') newItemWin.iconbitmap('icon.ico') # set labels nameLabel = ttk.Label(newItemWin, text='Product:') nameLabel.place(x=10, y=10) priceLabel = ttk.Label(newItemWin, text='Price:') priceLabel.place(x=10, y=30) purchaseLabel = ttk.Label(newItemWin, text='Purchase Price:') purchaseLabel.place(x=10, y=50) quantityLabel = ttk.Label(newItemWin, text='Quantity:') quantityLabel.place(x=10, y=70) # set entry points tk.nameVar = StringVar(value='Product') nameEntry = ttk.Entry(newItemWin, textvariable=tk.nameVar, justify='right') nameEntry.place(x=150, y=10) tk.priceVar = DoubleVar(value=0.0) priceEntry = ttk.Entry(newItemWin, textvariable=tk.priceVar, justify='right') priceEntry.place(x=150, y=30) tk.purchaseVar = DoubleVar(value=0.0) purchaseEntry = ttk.Entry(newItemWin, textvariable=tk.purchaseVar, justify='right') purchaseEntry.place(x=150, y=50) tk.quantityVar = DoubleVar(value=0.0) quantityEntry = ttk.Entry(newItemWin, textvariable=tk.quantityVar, justify='right') quantityEntry.place(x=150, y=70) # window buttons cancelButton = ttk.Button(newItemWin, text='CANCEL', command=newItemWin.destroy) cancelButton.place(x=190, y=150, height=30) addButton = ttk.Button(newItemWin, text='ADD ITEM', command=lambda: [StockDatabase.addNewStockItem(self._db, [tk.nameVar.get(), tk.priceVar.get(), tk.purchaseVar.get(), tk.quantityVar.get()]), newItemWin.destroy(), mngStockWin.destroy(), self.manageStockWindow()]) addButton.place(x=30, y=150, height=30) cancelButton = ttk.Button(mngStockWin, text='CANCEL', command=mngStockWin.destroy) cancelButton.place(x=250, y=550, height=30) addButton = ttk.Button(mngStockWin, text='ADD', command=addNewItem) addButton.place(x=10, y=550, height=30) # msw = Manage Stock Window mswColumns = ('#1', '#2', '#3', '#4') stockList = ttk.Treeview(mngStockWin, columns=mswColumns, show='headings', height=27, selectmode='browse') stockList.place(x=10, y=10, width=315, height=500) stockList.heading('#1', text='Product') stockList.heading('#2', text='Price') stockList.heading('#3', text='Purchase Price') stockList.heading('#4', text='Quantity') stockList.column('#1', anchor=CENTER, stretch=NO, width=133) stockList.column('#2', anchor=CENTER, stretch=NO, width=60) stockList.column('#3', anchor=CENTER, stretch=NO, width=60) stockList.column('#4', anchor=CENTER, stretch=NO, width=60) scrollbar = ttk.Scrollbar(mngStockWin, orient=tk.VERTICAL, command=self.shoppingList.yview) stockList.configure(yscrollcommand=scrollbar.set) scrollbar.place(x=325, y=10, height=500) # insert data to stock list for item in StockDatabase.loadData(self._db): stockList.insert('', tk.END, values=item) def deleteItem() -&gt; None: # get choosen item currentItem = stockList.focus() itemInfo = stockList.item(currentItem) itemDetails = itemInfo[&quot;values&quot;] # excepting index error if someone would press delete when stock list is empty try: # corrected for 'for' loop comparison. .focus() .item() returned all values as str correctedType = (itemDetails[0], float(itemDetails[1]), float(itemDetails[2]), float(itemDetails[3])) # delete item newData: list[Any] = [] for item in StockDatabase.loadData(self._db): if item != correctedType: newData.append(item) StockDatabase.createNewStockFile(self._db) for item in newData: StockDatabase.addNewStockItem(self._db, item) # refresh stock list mngStockWin.destroy() self.manageStockWindow() except IndexError: pass # delete button deleteButton = ttk.Button(mngStockWin, text='DELETE', command=deleteItem) deleteButton.place(x=170, y=550, height=30) def amendItemDetails() -&gt; None: amendWin = tk.Toplevel() amendWin.geometry('250x250') amendWin.geometry('+200+200') amendWin.title('Change details') amendWin.iconbitmap('icon.ico') questionLabel = ttk.Label(amendWin, text='What would you like to change?') questionLabel.place(x=10, y=10) itemOptions = ('Sale Price', 'Purchase Price', 'Stock Quantity') choice = StringVar() options = ttk.OptionMenu(amendWin, choice, itemOptions[0], *itemOptions) options.place(x=10, y=47) options.config(width=15) itemNewData = ttk.Label(amendWin, text='New Data:') itemNewData.place(x=10, y=90) newDataEntry = ttk.Entry(amendWin, justify='right') newDataEntry.place(x=10, y= 130) def acceptNewData(detailIndex: int, newDetail: Any) -&gt; None: # get choosen item currentItem = stockList.focus() itemInfo = stockList.item(currentItem) itemDetails = itemInfo[&quot;values&quot;] print(itemDetails) # corrected for 'for' loop comparison. .focus() .item() returned all values as str correctedType = (itemDetails[0], float(itemDetails[1]), float(itemDetails[2]), float(itemDetails[3])) print(correctedType) newData: list[Any] = [] for item in StockDatabase.loadData(self._db): if item != correctedType: print(item) newData.append(item) # append changed item itemDetails[detailIndex] = float(newDetail) # type adjustment as floats were turned into strings itemDetails = (itemDetails[0], float(itemDetails[1]), float(itemDetails[2]), float(itemDetails[3])) newData.append(itemDetails) print(itemDetails) print(correctedType) StockDatabase.createNewStockFile(self._db) # write to database for item in newData: StockDatabase.addNewStockItem(self._db, item) # destroy window after changing details amendWin.destroy() # refresh stock list mngStockWin.destroy() self.manageStockWindow() okButton = ttk.Button(amendWin, text='UPDATE', command=lambda: acceptNewData(itemOptions.index(choice.get()) + 1, newDataEntry.get())) okButton.place(x=60, y=200) cancelButton = ttk.Button(amendWin, text='CANCEL', command=amendWin.destroy) cancelButton.place(x=150, y=200) amendButton = ttk.Button(mngStockWin, text='CHANGE', command=amendItemDetails) amendButton.place(x=90, y=550, height=30) def addToBasket(self) -&gt; None: basketWin = tk.Toplevel() basketWin.geometry('250x200') basketWin.geometry('+200+200') basketWin.title('Add Item to Basket') basketWin.iconbitmap('icon.ico') itemLabel = ttk.Label(basketWin, text='Item:') itemLabel.place(x=10, y=10) quantityLabel = ttk.Label(basketWin, text='Quantity:') quantityLabel.place(x=10, y=70) availableLAbel = ttk.Label(basketWin, text='Available:') availableLAbel.place(x=10, y=110) # load options from available stock def getOptions() -&gt; list[str]: choice: list[str] = [] for item in StockDatabase.loadData(self._db): choice.append(item[0]) if len(choice) == 0: choice = ['Nothing in stock'] return choice tk.choosenItem = StringVar() options = ttk.OptionMenu(basketWin, tk.choosenItem, getOptions()[0], *getOptions()) options.place(x=120, y=10) options.config(width=15) # get maximum quantity of item from stock database def getMaxQuantity(item: str) -&gt; float: for product in StockDatabase.loadData(self._db): if product[0] == item: return float(product[3]) tk.quantityVar = DoubleVar(value=getMaxQuantity(tk.choosenItem.get())) quantityAmountLabel = ttk.Label(basketWin, textvariable=tk.quantityVar, justify='right', background='lightgrey') quantityAmountLabel.place(x=215, y=110) tk.entryVar = DoubleVar() quantityEntry = ttk.Entry(basketWin, textvariable=tk.entryVar, justify='right') quantityEntry.place(x=120, y=70, width=120) cancelButton = ttk.Button(basketWin, text='CANCEL', command=basketWin.destroy) cancelButton.place(x=140, y=150) # insert maximum available stock in quantity label, update everytime different option from option menu is choosen # x, y, z just to pass argument to callback function, as required by tkinter. otherwise= error def updateQuantity(x: Any, y: Any, z: Any) -&gt; None: tk.quantityVar = DoubleVar(value=getMaxQuantity(tk.choosenItem.get())) quantityAmountLabel['textvariable'] = tk.quantityVar tk.choosenItem.trace_add('write', updateQuantity) '''NEED TO WORK ON THIS PART EVERYTHING IS WORKING FINE, BUT WHILE ADDING SAME ITEM MULTIPLE TIMES WHEN IT COMES TO PAYMENT TIME stock_data.json IS NOT UPDATED CORRECTLY. NEED TO FIND THE WAY TO CONSOLIDATE ITEMS IN THE shoppingList''' # create item for the shopping list, calculate sum for product (quantity * price) def addToShoppingList(item: str, quantity: float) -&gt; None: productToAdd: list[Any] = [] productToAdd.append(item) # excepting TypeError if someone will try to add items when stock_data is empty try: # ensure it can't be added more than in the stock if quantity &gt;= getMaxQuantity(tk.choosenItem.get()): productToAdd.append(getMaxQuantity(tk.choosenItem.get())) else: productToAdd.append(quantity) for product in StockDatabase.loadData(self._db): if product[0] == item: productToAdd.append(product[1]) total = productToAdd[1] * productToAdd[2] productToAdd.append(total) self.shoppingList.insert('', tk.END, values=productToAdd) except TypeError: pass addButton = ttk.Button(basketWin, text='ADD', command=lambda: addToShoppingList(tk.choosenItem.get(), tk.entryVar.get())) addButton.place(x=30, y=150) def createLabels(self) -&gt; None: totalLabel = ttk.Label(self, text='TOTAL:') totalLabel.place(x=150, y=420) taxLabel = ttk.Label(self, text='TAX:') taxLabel.place(x=150, y=445) toPayLabel = ttk.Label(self, text='TOTAL TO PAY:') toPayLabel.place(x=150, y=470) def calculateTotal() -&gt; float: total: float = 0.0 for child in self.shoppingList.get_children(): total += float(self.shoppingList.item(child, 'values')[3]) return total def getTaxValue() -&gt; float: for item in TillSettings.loadSettings(self._sett): for key, value in item.items(): if key == 'sales tax': return value return 0.0 # just a basic tax calculation for training purposes def calculateTax(amount: float) -&gt; float: return round((amount / 100) * getTaxValue(), 2) self.totalVar = DoubleVar(value=calculateTotal()) totalValue = ttk.Label(self, textvariable=self.totalVar, background='lightgrey') totalValue.place(x=330, y=420) self.taxVar = DoubleVar(value=calculateTax(self.totalVar.get())) taxValue = ttk.Label(self, textvariable=self.taxVar, background='lightgrey') taxValue.place(x=330, y=445) self.toPayVar = DoubleVar(value=self.taxVar.get() + self.totalVar.get()) toPayValue = ttk.Label(self, textvariable=self.toPayVar, background='lightgrey') toPayValue.place(x=330, y=470) def updateTotals() -&gt; None: self.totalVar = DoubleVar(value=calculateTotal()) self.taxVar = DoubleVar(value=calculateTax(self.totalVar.get())) self.toPayVar = DoubleVar(value=self.taxVar.get() + self.totalVar.get()) totalValue = ttk.Label(self, textvariable=self.totalVar, background='lightgrey') totalValue.place(x=330, y=420) taxValue = ttk.Label(self, textvariable=self.taxVar, background='lightgrey') taxValue.place(x=330, y=445) toPayValue = ttk.Label(self, textvariable=self.toPayVar, background='lightgrey') toPayValue.place(x=330, y=470) self.after(1000, updateTotals) updateTotals() def getPayment(self) -&gt; None: # update total payment Payments.updateTotalPayments(self._pay, self.toPayVar.get()) # update stock values newData: list[Any] = [] updatedData: list[Any] = [] for item in StockDatabase.loadData(self._db): item = list(item) for child in self.shoppingList.get_children(): if self.shoppingList.item(child, 'values')[0] == item[0]: item[3] -= float(self.shoppingList.item(child, 'values')[1]) updatedData.append(list(item)) # get names of bought products compareList: list[str] = [] for item in updatedData: compareList.append(item[0]) print(compareList) print(updatedData) # append new data with not bought products for item in StockDatabase.loadData(self._db): if item[0] not in compareList: newData.append(list(item)) # append new data with bought products with new values for item in updatedData: newData.append(item) print(newData) # write to file procedure StockDatabase.createNewStockFile(self._db) for item in newData: StockDatabase.addNewStockItem(self._db, item) # clear shopping list after successful purchase self.shoppingList.delete(*self.shoppingList.get_children()) class StockDatabase: def __init__(self, dataFile: str) -&gt; None: self._stockFile = dataFile # check for stock data file existence if os.path.isfile(self._stockFile) == True and os.stat(self._stockFile).st_size != 0: pass else: self.createNewStockFile() def createNewStockFile(self) -&gt; None: with open(self._stockFile, 'w') as f: writeData: dict[str, list[Any]] = {&quot;stock&quot;: []} json.dump(writeData, f, indent=4) def addNewStockItem(self, newItem: list[Any]): item = { &quot;item&quot;: newItem[0], &quot;sale price&quot;: newItem[1], &quot;purchase price&quot;: newItem[2], &quot;stock quantity&quot;: newItem[3] } with open(self._stockFile, 'r') as f: data = json.load(f) data[&quot;stock&quot;].append(item) with open(self._stockFile, 'w') as f: json.dump(data, f, indent=4) def loadData(self) -&gt; list[Any]: stockItem = [] with open(self._stockFile, 'r') as f: data = json.load(f) for itemData in data[&quot;stock&quot;]: item: str = itemData[&quot;item&quot;] salePrice: float = itemData[&quot;sale price&quot;] purchasePrice: float = itemData[&quot;purchase price&quot;] stockQuantity: float = itemData[&quot;stock quantity&quot;] stockItem.append((item, salePrice, purchasePrice, stockQuantity)) return stockItem class TillSettings: def __init__(self, dataFile: str) -&gt; None: self._settFile = dataFile # check for settings file existence if os.path.isfile(self._settFile) == True and os.stat(self._settFile).st_size != 0: pass else: self.createNewSettingsFile() def createNewSettingsFile(self) -&gt; None: with open(self._settFile, 'w') as f: writeData = {&quot;settings&quot; : [{ &quot;sales tax&quot;: 0 }] } json.dump(writeData, f, indent=4) def loadSettings(self) -&gt; list[Any]: settings: list[Any] = [] with open(self._settFile, 'r') as f: data = json.load(f) for item in data[&quot;settings&quot;]: settings.append(item) return settings class Payments: def __init__(self, paymentFile: str) -&gt; None: self._paymentFile = paymentFile # check for file existence if os.path.isfile(self._paymentFile) == True and os.stat(self._paymentFile).st_size != 0: pass else: self.createNewPaymentFile() def createNewPaymentFile(self) -&gt; None: with open(self._paymentFile, 'w') as f: writeData = {&quot;Total Payments&quot;: 0} json.dump(writeData, f, indent=4) def updateTotalPayments(self, payment: float): with open(self._paymentFile, 'r') as f: data = json.load(f) data[&quot;Total Payments&quot;] += payment with open(self._paymentFile, 'w') as f: json.dump(data, f, indent=4) if __name__ == '__main__': _stockFIle = f'{os.path.dirname(__file__)}\\stock_data.json' _settFile = f'{os.path.dirname(__file__)}\\settings.json' _paymentFile = f'{os.path.dirname(__file__)}\\payments.json' db = StockDatabase(_stockFIle) sett = TillSettings(_settFile) pay = Payments(_paymentFile) Application(database= db, settings= sett, payments= pay).mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T09:08:11.433", "Id": "530632", "Score": "0", "body": "I can't run the code because `list[Any]` in line 458 causes error, is it because it's written in old python?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T11:02:40.457", "Id": "530646", "Score": "0", "body": "@WalidSiddik `list[Any]` is the newer syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T13:13:22.310", "Id": "530652", "Score": "0", "body": "@hjpotter92. It says `TypeError: 'type' object is not subscriptable` (python 3.8)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T13:42:25.333", "Id": "530653", "Score": "0", "body": "When do you get that error? The only one error I can get atm is when I try to input ```str``` in place where ```float``` should be, but that is easy to fix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T03:44:22.337", "Id": "530686", "Score": "1", "body": "@WalidSiddik https://www.python.org/dev/peps/pep-0585/ it was implemented in 3.9+" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T22:24:16.803", "Id": "530788", "Score": "0", "body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T22:50:55.370", "Id": "530791", "Score": "0", "body": "My bad. Sorry., just wanted to share the updated version without creating another post. Completely didn't think about it." } ]
[ { "body": "<h2>Violation of <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP8</a></h2>\n<p>According to <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP8</a>,</p>\n<ul>\n<li>Imports should be on seperate lines.</li>\n<li>Surround top-level function and class definitions with two blank lines.</li>\n<li>Method definitions inside a class are surrounded by a single blank line.</li>\n<li>Variables and function names should be <code>snake_case</code>.</li>\n</ul>\n<h2>My thoughts</h2>\n<ul>\n<li><p>You should create seperate files for GUI and Data Handling part. Currently your code is around 550 lines which makes it hard to navigate over.</p>\n</li>\n<li><p>I do not know why you have done this <code>tk.priceVar = ...</code>. Better make it <code>self.prive_var</code>.</p>\n</li>\n<li><p>You have justified all the entries to the right. This causes some unwanted behaviour.\n<a href=\"https://i.stack.imgur.com/7qhib.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7qhib.png\" alt=\"\" /></a></p>\n</li>\n</ul>\n<p>Your GUI part is very well done. But I would like some additions -</p>\n<ul>\n<li>Currently one can not remove an item from the basket.</li>\n<li>Your 2nd and 3rd columns are named <code>#</code>. Would be better if renamed.</li>\n</ul>\n<p>Waiting to see the other parts of the project in action. Happy Coding!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:43:10.380", "Id": "530627", "Score": "0", "body": "I was always naming my_functions rather than myFunction but been told that way it looks more \"proper\", will stick to my_function as I prefer it anyway. Yes delete but for shoppingList will be added and some more, just wasn't sure if my approach to build this app right. Need to test adding window again as I didn't have that issue. Splitting the code in to different files would make a lot of sense, will need to do it. Thank you very much for your time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T21:02:29.087", "Id": "530677", "Score": "0", "body": "```Remove``` button is added now, the issue from your screenshot is also fixed. A few more things and I will re-upload the code. Waiting for one of my friends to bring me a scanner and till draw, so may be able to add barcode reading and a function to open the draw when payment is done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T06:58:12.963", "Id": "530748", "Score": "0", "body": "All the best!!!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T04:59:38.460", "Id": "269006", "ParentId": "269002", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T00:32:49.957", "Id": "269002", "Score": "4", "Tags": [ "python", "beginner", "tkinter" ], "Title": "Simple Cash Register -Python" }
269002
<h1>Simple Disjoint Set Implementation</h1> <p>I had not implemented a <code>DisjointSet</code> before and the following is my attempt at implementing a very simple <code>DisjointSet</code> for learning purposes.</p> <p>When <code>union</code>-ing sets, the goal was to implement union-by-size.</p> <h1>Approach</h1> <p>For simplicity, I implement a disjoint set that only dealt with <code>Integer</code> values and not generic values.</p> <p>I used two <code>Map</code>s to keep track of both the sizes of sets and the tree of values within each set.</p> <p>I like to name my <code>Map</code>s <code>{value}By{key}</code> as the naming provides useful information as to the structure of the data. So <code>sizesByRoot</code> represents the root value of each set as the key and size of the elements in each set as the value.</p> <p>When trying to find the root for a specified value, I decided to throw a checked exception - I think this makes it clear to the caller what the expected inputs into the <code>findRoot</code> method should be.</p> <p>When calling <code>findRoot</code> I also make the decision to path compaction - i.e. setting the root for a value to the identified root so that the next lookup does not have to iterate over the tree again.</p> <p>When <code>union</code>-ing two sets together, I look up the sizes of the two sets. Logically, it should be impossible that the sizes for the two sets do not exist. However, calling <code>Map#get</code> can return a <code>null</code> value. I decided to <code>throw</code> a <code>RuntimeError</code> if the value returned by <code>get</code> was <code>null</code> because while it should never occur, if it did occur, a <code>RuntimeError</code> with some context is more useful to the caller than a <code>NullPointerException</code>.</p> <h1>Feedback</h1> <p>First and foremost, correctness.</p> <p>Secondly, design choices and naming. For example, I did not override <code>equals</code> and <code>hashcode</code>. I couldn't think of a practical reason why a caller might want to compare <code>DisjointSet</code>s. I also designed a static constructor vs. initializing the internal data structures within a public constructor.</p> <p>Thirdly, feedback on the tests I wrote and how to make them more readable and if I'm missing any test cases.</p> <h1>Implementation</h1> <pre class="lang-java prettyprint-override"><code>public class DisjointSet { public static class UnableToIdentifyRootForValue extends Exception { } public static DisjointSet create(final Set&lt;Integer&gt; values) { return new DisjointSet( values .stream() .collect( Collectors.toMap( Function.identity(), (v) -&gt; 1 ) ), values .stream() .collect( Collectors.toMap( Function.identity(), Function.identity() ) ) ); } private final Map&lt;Integer, Integer&gt; sizesByRoot; private final Map&lt;Integer, Integer&gt; parentsByChild; private DisjointSet(final Map&lt;Integer, Integer&gt; sizesByRoot, final Map&lt;Integer, Integer&gt; parentsByChild) { this.sizesByRoot = sizesByRoot; this.parentsByChild = parentsByChild; } public void add(final int value) { if (!parentsByChild.containsKey(value)) { parentsByChild.put(value, value); sizesByRoot.put(value, 1); } } public int findRoot(final int value) throws UnableToIdentifyRootForValue { final Integer parent = parentsByChild.get(value); if (null == parent) { throw new UnableToIdentifyRootForValue(); } if (parent.equals(value)) { return value; } final int root = findRoot(parent); parentsByChild.put(value, root); return root; } public void union(final int value1, final int value2) throws UnableToIdentifyRootForValue { final int root1 = findRoot(value1); final int root2 = findRoot(value2); if (root1 != root2) { final Integer root1Size = sizesByRoot.get(root1); if (null == root1Size) { throw new RuntimeException(createUnableToIdentifyRootSizeForValueErrorMessage(root1, value1)); } final Integer root2Size = sizesByRoot.get(root2); if (null == root2Size) { throw new RuntimeException(createUnableToIdentifyRootSizeForValueErrorMessage(root2, value2)); } final int parentRoot; final int childRoot; { if (root1Size &lt; root2Size) { parentRoot = root2; childRoot = root1; } else { parentRoot = root1; childRoot = root2; } } parentsByChild.put(childRoot, parentRoot); sizesByRoot.put(parentRoot, root1Size + root2Size); } } private static String createUnableToIdentifyRootSizeForValueErrorMessage(final int root, final int value) { return &quot;Unable to identify size for root &quot; + root + &quot; and value &quot; + value; } } </code></pre> <h1>Tests</h1> <pre class="lang-java prettyprint-override"><code>public class DisjointSetTest { @Test public void TestCreatingNonEmptySets() { IntStream.rangeClosed(0, 3) .boxed() .forEach( v -&gt; DisjointSet.create( IntStream.rangeClosed(0, v) .boxed() .collect(Collectors.toSet()) ) ); } @Test public void TestUnableToFindRootForValue() { Assert.assertThrows( DisjointSet.UnableToIdentifyRootForValue.class, () -&gt; { final DisjointSet disjointSet = DisjointSet.create( Set.of(1) ); disjointSet.findRoot(-1); } ); } @Test public void TestAddingValue() { final DisjointSet disjointSet = DisjointSet.create(Collections.emptySet()); try { disjointSet.findRoot(1); Assert.fail(); } catch (DisjointSet.UnableToIdentifyRootForValue e) { // expected } IntStream .rangeClosed(1, 10) .boxed() .forEach( v -&gt; { disjointSet.add(1); try { Assert.assertEquals(1, disjointSet.findRoot(1)); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } ); } @Test public void TestAbleToFindRootForValue() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1) ); try { Assert.assertEquals( 1, disjointSet.findRoot(1) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } @Test public void TestRootValueDoesNotChangeAfterMultipleCalls() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1) ); IntStream .rangeClosed(1, 10) .forEach( v -&gt; { try { Assert.assertEquals( 1, disjointSet.findRoot(1) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } ); } @Test public void TestUnionTwoValuesThatDoNotHaveRootsInSetThrowUnableToIdentifyRoot() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1) ); Assert.assertThrows( DisjointSet.UnableToIdentifyRootForValue.class, () -&gt; disjointSet.union(-1, -2) ); } @Test public void TestUnionForFirstValueThatDoesNotHaveARootThrowsUnableToIdentifyRoot() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1) ); Assert.assertThrows( DisjointSet.UnableToIdentifyRootForValue.class, () -&gt; disjointSet.union(-1, 1) ); } @Test public void TestUnionForSecondValueThatDoesNotHaveARootThrowsUnableToIdentifyRoot() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1) ); Assert.assertThrows( DisjointSet.UnableToIdentifyRootForValue.class, () -&gt; disjointSet.union(1, -1) ); } @Test public void TestUnionForSameValues() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1) ); try { disjointSet.union(1, 1); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } @Test public void TestUnionForTwoDifferentRootValues() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1, 2) ); try { disjointSet.union(1, 2); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } try { Assert.assertEquals( 1, disjointSet.findRoot(2) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } try { Assert.assertEquals( 1, disjointSet.findRoot(1) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } @Test public void TestUnionForThreeDifferentRootValues() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1, 2, 3) ); try { disjointSet.union(1, 2); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } IntStream .rangeClosed(1, 2) .boxed() .forEach( v -&gt; { try { Assert.assertEquals( 1, disjointSet.findRoot(v) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } ); try { disjointSet.union(2, 3); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } IntStream .rangeClosed(1, 3) .boxed() .forEach( v -&gt; { try { Assert.assertEquals( 1, disjointSet.findRoot(v) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } ); } @Test public void TestUnionForFourDifferentRootValues() { final DisjointSet disjointSet = DisjointSet.create( Set.of(1, 2, 3, 4) ); try { disjointSet.union(1, 2); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } IntStream .rangeClosed(1, 2) .boxed() .forEach( v -&gt; { try { Assert.assertEquals( 1, disjointSet.findRoot(v) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } ); try { disjointSet.union(4, 3); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } IntStream .rangeClosed(3, 4) .boxed() .forEach( v -&gt; { try { Assert.assertEquals( 4, disjointSet.findRoot(v) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } ); try { disjointSet.union(4, 1); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } IntStream .rangeClosed(1, 4) .boxed() .forEach( v -&gt; { try { Assert.assertEquals( 4, disjointSet.findRoot(v) ); } catch (DisjointSet.UnableToIdentifyRootForValue e) { Assert.fail(); } } ); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T11:15:56.360", "Id": "530647", "Score": "0", "body": "You might be interested in the following post: https://codereview.stackexchange.com/questions/267718/comparing-8-different-disjoint-set-data-structure-variants-in-java" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:04:07.073", "Id": "530655", "Score": "0", "body": "@coderodde I left some thoughts here: https://codereview.stackexchange.com/a/269015/90653" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T06:48:41.093", "Id": "269007", "Score": "0", "Tags": [ "java", "union-find" ], "Title": "Implementation for Simple Disjoint Set" }
269007
<p>Got this problem in a coding interview - Get the max value of a stack in O(1). The stack contains numbers only. Please review my solution.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class Stack { data; maxVal; pop() { return this.data.pop(); } insert(x) { const cm = new CheckMax(); this.data.push(x); this.maxVal = cm.max.call(this); } peek() { return this.data[this.data.length - 1]; } } class CheckMax { max() { let maxVal = this.maxVal; let oldVal; if (this.data.length &gt; 0) { oldVal = this.peek(); if (maxVal == undefined) { maxVal = oldVal; } if (oldVal &gt; maxVal) { maxVal = oldVal; } } return maxVal; } } const stack = new Stack(); stack.data = []; stack.insert(123); stack.insert(22); stack.insert(23); stack.insert(9); stack.insert(73); stack.insert(54); console.log(stack.maxVal);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T11:09:08.397", "Id": "530763", "Score": "0", "body": "The code does not work. If you `push` `[2, 1, 5]` the max is 5. However if you `pop` the 5 the max remains 5 (should be 2)., If you then push a 4 the max is still 5 (should be 4). You need to recalculate the max each time the stack size changes, not just on the `push` what you called `insert` (BTW Stacks don't insert)" } ]
[ { "body": "<p>This solution looks incorrect and doesn't cover the case when the max value is popped.</p>\n<p>For example,</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const stack = new Stack();\nstack.data = [];\nstack.insert(1);\nstack.pop();\nconsole.log(stack.maxVal); // even though stack is empty, this will print 1, right?\n</code></pre>\n<p>I think one naive way to solve this is to store (internally) the max value along with the element value, at time of element insertion.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>class Entry {\n constructor(value, maxValue) {\n this.value = value;\n this.maxValue = maxValue;\n }\n}\n// insert 1\n[new Entry(1, 1)]\n// insert 2\n[new Entry(1, 1), new Entry(2, 2)]\n// insert 1 - notice how the latest Entry has a value property of 1 but a maxValue property of 2 since the largest property seen so far is 2\n[new Entry(1, 1), new Entry(2, 2), new Entry(1, 2)]\n// pop - look at last Entry's max value to see max value (2)\n[new Entry(1, 1), new Entry(2, 2)]\n// pop - look at last Entry's max value to see max value (1)\n[new Entry(1, 1)]\n// pop - empty, so max value is undefined / null\n[]\n</code></pre>\n<p>One way to implement this would be something like this</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>class Stack {\n constructor() {\n this.entries = [];\n }\n\n get maxValue() {\n // this value can be stored in an instance variable and updated on pop/push if access to value will occur frequently\n if (0 &lt; this.entries.length) {\n return this.entries[this.entries.length - 1].maxValue;\n }\n return null;\n }\n\n pop() {\n return this.entries.pop();\n }\n\n push(value) {\n this.entries.push(\n new Entry(\n value,\n Math.max(\n value,\n this.maxValue\n )\n )\n );\n }\n}\n</code></pre>\n<p>Another thing to watch out for - in every call to <code>insert</code> you are instantiating a new <code>CheckMax</code> instance which seems wasteful. <code>CheckMax</code> doesn't really contain any state and the <code>this</code> is referring to an instance of a <code>Stack</code>. I think it's more natural to add the logic in <code>CheckMax</code> on <code>Stack</code> itself.</p>\n<p>Finally, the setting of the <code>data</code> property on a <code>Stack</code> instance seems like an internal implementation detail that the caller should not be worried about. I don't think the caller should have to initialize the <code>data</code> property on a <code>Stack</code> instance in order for it to work correctly. Whatever data structure the stack uses under the hood to keep track of elements should not be the concern of the caller of the stack.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T16:08:36.363", "Id": "269017", "ParentId": "269013", "Score": "5" } }, { "body": "<p>The <a href=\"https://codereview.stackexchange.com/a/269017/120114\">answer by Jae Bradley</a> already mentions great points - the code should handle the case where elements are removed, and it is strange that the method in the <code>CheckMax</code> class is separate from the <code>Stack</code> class.</p>\n<h2>Formatting</h2>\n<p>If I saw this code in an interview one of the first things I would look at is the formatting - e.g. indentation, spacing. The indentation looks fairly consistent - i.e. two spaces, though the properties <code>data</code> and <code>maxVal</code> are indented with six spaces.</p>\n<h2>uninitialized <code>data</code> property</h2>\n<p>It seems strange that the <code>data</code> field is not initialized to an array when declared, and the sample usage assigns it before calling the <code>insert</code> method. If the class was used and the <code>data</code> property wasn't assigned then the following error would occur:</p>\n<blockquote>\n<p>VM35:12 Uncaught TypeError: Cannot read property 'push' of undefined</p>\n</blockquote>\n<h2>comparison operators</h2>\n<p>In the <code>CheckMax::max()</code> method there is a loose comparison operator used:</p>\n<blockquote>\n<pre><code> if (maxVal == undefined) {\n</code></pre>\n</blockquote>\n<p>A good habit and recommendation of many style guides is to use strict equality operators (i.e. <code>===</code>, <code>!==</code>) whenever possible (like is used in the snippet above). The problem with loose comparisons is that it has <a href=\"https://stackoverflow.com/q/359494\">so many weird rules</a> one would need to memorize in order to be confident in its proper usage.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T21:59:22.557", "Id": "269023", "ParentId": "269013", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T13:23:38.687", "Id": "269013", "Score": "3", "Tags": [ "javascript", "interview-questions", "ecmascript-6", "stack" ], "Title": "Check for max value in stack" }
269013
<p><strong>Problem definition : Array partition problem</strong></p> <p>Given an array of positive integers, divide it into three disjoint subsets having equal sum. These disjoint sets cover the complete array.</p> <p><strong>Example</strong> Input: [7, 6, 1, 7] Output: [[7], [6, 1], [7]]</p> <p>Input: [7, 6, 2, 7] Output: Not possible to partition in three parts</p> <p>Input: [[1, 1, 1, 1, 3, 2 ] Output:[[1, 1, 1], [1, 2], [3]]</p> <p><strong>Solution</strong> Brute force solution of examining all possible subsets in iterative approach.</p> <pre><code># Gets all possible subsets of input_array which doesn't include element from skip_indices def get_subsets(input_array, skip_indices=[]): def get_incremental_subsets(index, subsets): new_subsets = [] new_subsets.append([index]) for count in range(len(subsets)): current_subset = subsets[count].copy() current_subset.append(index) if len(current_subset) == 1: new_subsets.append([current_subset]) else: new_subsets.append(current_subset) return subsets + new_subsets subsets = [] for count in range(len(input_array)): if count not in skip_indices: subsets = get_incremental_subsets(count, subsets) return subsets # Sum of a subset def get_subset_sum(input_array, subset_indices): subset_sum = 0 for subset_index in subset_indices: subset_sum = subset_sum + input_array[subset_index] return subset_sum # Find partition input_array in two subsets such that each subset have sum equal to sum_value. # Subset exclude elements present in skip_indices def partition_two(input_array, skip_indices, sum_value): input_array_sum = sum(input_array) for index in skip_indices: input_array_sum = input_array_sum - input_array[index] if input_array_sum != 2*sum_value: return None subsets = get_subsets(input_array, skip_indices) for index in range(len(subsets)): if get_subset_sum(input_array, subsets[index]) == sum_value: return subsets[index] return None def partition_three(input_array): # Check if input_array sum is actually multiple of 3 input_array_sum = sum(input_array) if input_array_sum%3 != 0: return None target_sum = input_array_sum/3 #Iterate over all subsets for subset in get_subsets(input_array): # Skip subsets where sum is not equal to target_sum if get_subset_sum(input_array, subset) != target_sum: continue # If subset with target_sum is found, try finding two subsets with target_sum in remaining array subset_1 = partition_two(input_array, subset, target_sum) if subset_1 != None: return [subset,\ subset_1,\ list(set([index for index in range(len(input_array))]) - set(subset) - set(subset_1))] return None print(partition_three([1, 1, 1 ])) # Possible. Subset indices are [[0], [1], [2]] print(partition_three([1, 1, 1, 3, 2, 1 ])) # Possible. Subset indices are [[0, 1, 2], [3], [4, 5]] print(partition_three([1, 1, 1, 1, 3, 2 ])) # Possible. Subset indices are [[0, 1, 2], [4], [3, 5]] print(partition_three([1, 5 ])) # Not possible print(partition_three([])) # Not possible print(partition_three([7, 3, 2, 1, 5, 4, 8 ])) # Possible. Subset indices are [[0, 1], [3, 4, 5], [2, 6] print(partition_three([1, 3, 6, 2, 7, 1, 2, 8 ])) # Possible. Subset indices are [[0, 1, 2], [3, 4, 5], [6, 7]] print(partition_three([7, 6, 1, 7 ])) #Possible. Subset indices are [[0], [1, 2], [3]] print(partition_three([7, 6, 2, 7 ])) # Not possible print(partition_three([17, 17, 17, 34, 34, 34, 59, 59, 59])) # Possible. Subset indices are [[0, 3, 6], [1, 4, 7], [8, 2, 5]] print(partition_three([20, 23, 25, 30, 49, 45, 27, 30, 30, 40, 22, 19])) # Possible. Subset indices are [[0, 2, 3, 5], [1, 6, 7, 9], [8, 10, 11, 4]] </code></pre> <p><strong>Review ask</strong></p> <ol> <li>Functional correctness</li> <li>Algorithm improvements</li> <li>Python usage</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T21:18:11.210", "Id": "530679", "Score": "0", "body": "Your problem description has output of list values. Your solution outputs list indices. Why?" } ]
[ { "body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> has a several conventions all Python programmers should follow. You deviate from the guidelines in a few minor areas.</p>\n<ul>\n<li>Binary operators should be surrounded by a space. You have <code>2*sum_value</code>, <code>input_array_sum%3</code> and <code>input_array_sum/3</code>, which should be written <code>2 * sum_value</code>, <code>input_array_sum % 3</code> and <code>input_array_sum / 3</code></li>\n<li>You have a long statement continued over 3 lines using backslashes. The backslashes are completely unnecessary, since the backslashes are contained inside brackets (<code>[...]</code>). The backslashes can be simply removed.</li>\n<li>Spaces should not proceed <code>]</code>. Many of your test cases have a space before the closing <code>]</code>, such as <code>[1, 1, 1 ]</code>. The final space should be removed (<code>[1, 1, 1]</code>)</li>\n</ul>\n<h1>Speed improvements</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def get_subset_sum(input_array, subset_indices):\n subset_sum = 0\n for subset_index in subset_indices:\n subset_sum = subset_sum + input_array[subset_index]\n return subset_sum\n</code></pre>\n<p>This code creates a <code>subset_sum</code> variable, assigns an integer to it, retrieves the value of the variable, adds another number to it (creating a new number object), and reassigns that to the variable, and repeats.</p>\n<p>A minor improvement would be to use the <code>+=</code> operator.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_subset_sum(input_array, subset_indices):\n subset_sum = 0\n for subset_index in subset_indices:\n subset_sum += input_array[subset_index]\n return subset_sum\n</code></pre>\n<p>but it would be much better to let the Python interpreter keep track of the intermediate results itself, without having to keep reassigning it to a variable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_subset_sum(input_array, subset_indices):\n return sum(input_array[subset_index] for subset_index in subset_indices)\n</code></pre>\n<h1>Fast reject</h1>\n<p>You immediately return <code>None</code> if the sum of the input array is not a multiple of 3. There are other checks you can make:</p>\n<ul>\n<li>If the array length is less that 3, you could immediately stop, since one or more partitions would be empty.</li>\n<li>If any element is larger that <code>target_sum</code> no solution is possible.</li>\n</ul>\n<p><code>[1, 5]</code> fails both the above conditions, but you run the entire algorithm on the input anyway futilely searching for a solution. With 2 elements, the failure is fairly fast, but with 99 ones, and one 99, you start exhaustively looking for subsets that total 66, of which there are many, but one subset will always have to include the 99, which means no solution is possible.</p>\n<h1>Algorithmic improvement</h1>\n<p>Your example cases contain many duplicate values. By searching all subset of indices, there are 24 different ways of selecting 4 ones from a list containing 4 ones, but the order does not matter when you end up summing these. If instead you maintained a count of all values (ie, using <code>collections.Counter</code>) you could avoid generating equivalent subsets which have already been examined, by selecting subsets containing 0 to n of those repeated values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T21:58:50.260", "Id": "269022", "ParentId": "269020", "Score": "3" } } ]
{ "AcceptedAnswerId": "269022", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T20:00:48.957", "Id": "269020", "Score": "2", "Tags": [ "python", "python-3.x", "algorithm", "array", "dynamic-programming" ], "Title": "Divide array into three disjoint sets with equal sum" }
269020
<p>The goal is to have a function that can sort a series of all object types that implement the comparable interface. I'm not trying to improve the performance of the sort. I'm only trying to optimize my use of generics.</p> <p>I currently use <code>T extends whatever</code> and <code>T[]</code>, however I was also considering to use <code>T extends whatever</code> and <code>ArrayList&lt;T&gt;</code>. Is one more preferable over the other or are both approaches just trash? If you have other remarks please tell me I'm here to learn :)</p> <pre><code> public static void main( String[] args ) { String[] stringList = {&quot;hello&quot;, &quot;this&quot;, &quot;is&quot;, &quot;a&quot;, &quot;test&quot;, &quot;ab&quot;, &quot;aaa&quot;,&quot;aba&quot;}; Quicksort.sort(stringList, 0, stringList.length - 1); System.out.println( Arrays.toString(stringList)); } </code></pre> <pre><code>public class Quicksort{ private static &lt;T extends Comparable&lt;T&gt;&gt; int partitioning(T[] arr, int start, int end) { T pivot = arr[end]; int balancePoint = start; // everything that's smaller to the left of this, the rest to the right for (int i = start; i &lt; end; i++) { if(arr[i].compareTo(pivot)&lt;=0) { Arrayswap.genericArraySwap(arr, i, balancePoint); balancePoint++; } } Arrayswap.genericArraySwap(arr, end, balancePoint); return balancePoint; } public static &lt;T extends Comparable&lt;T&gt;&gt; void sort(T[]a, int i, int j) { if (i&gt;=j) { return; } int pivot = partitioning(a, i, j); sort(a, i, pivot-1); sort(a, pivot+1, j); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:31:19.300", "Id": "530989", "Score": "0", "body": "Er, there is a space too many after `main(` and before the closing `)` - not consistent ;)" } ]
[ { "body": "<p>Welcome to Code Review, the use of <code>&lt;T extends Comparable&lt;T&gt;&gt;</code> and <code>T[]</code> looks fine to me and personally I would not change it. The only one thing I am not agree is about the indexes you use to order one array like below :</p>\n<pre><code>Quicksort.sort(stringList, 0, stringList.length - 1);\n</code></pre>\n<p>In the java sorting methods from the std library the range to be sorted extends from the starting index, inclusive, to the end index, exclusive, so for me your method should be rewritten in the way that ordering an array <code>arr</code> of length <em>n</em> should be obtained by <code>Quicksort.sort(arr, 0, n)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T11:53:13.733", "Id": "530702", "Score": "0", "body": "Hi Thanks for your feedback. Making the last parameter inclusive is indeed more consistent. Thanks again for your time :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T12:20:55.263", "Id": "530705", "Score": "0", "body": "@DevShot You are welcome and again good job :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T10:33:41.980", "Id": "269033", "ParentId": "269024", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T22:19:01.907", "Id": "269024", "Score": "3", "Tags": [ "java", "sorting", "generics", "quick-sort" ], "Title": "Quicksort using generics in java" }
269024
<p>The program is supposed to be set as the default browser in Windows and allows me to select which browser profile I want to use when I open a link from another program. I have quite some experience in PHP, Java, C, C++, Pascal, but this is my first venture into Rust. Before I continue adding features I'd like to know how good my understanding of the language is and what could be solved better than what I found.</p> <pre><code>#![windows_subsystem = &quot;windows&quot;] use nwg::Button; use nwg::WindowFlags; use std::process::Command; use serde::Deserialize; use std::env; use std::fs; use std::rc::Rc; use std::sync::Arc; #[derive(Debug, Deserialize)] #[serde(rename_all = &quot;camelCase&quot;)] struct Settings { browsers: Vec&lt;Browser&gt; } #[derive(Debug, Default, Deserialize)] #[serde(rename_all = &quot;camelCase&quot;)] struct Browser { name: String, command_line: String, arguments: Vec&lt;String&gt;, icon: String, } fn run_browser(browser: &amp;Browser, url: String) { let mut arguments: Vec&lt;String&gt; = Vec::new(); for argument in &amp;browser.arguments { arguments.push(argument.clone()); } arguments.push(url); let _process = match Command::new(&amp;browser.command_line) .args(arguments) .spawn() { Ok(process) =&gt; process, Err(err) =&gt; panic!(&quot;Running process error: {}&quot;, err), }; nwg::stop_thread_dispatch(); std::process::exit(0); } fn main() { nwg::init().expect(&quot;Failed to init Native Windows GUI&quot;); nwg::Font::set_global_family(&quot;Segoe UI&quot;).expect(&quot;Failed to set default font&quot;); let mut window = Default::default(); let mut url_edit = Default::default(); let layout = Default::default(); let appdata = env::var(&quot;APPDATA&quot;).unwrap(); let settings_filepath = format!(&quot;{}/CrossRoad/settings.json&quot;, appdata); let settings_file = fs::read_to_string(settings_filepath).expect(&quot;Unable to read settings.json&quot;); let parsed_settings: Settings = serde_json::from_str(&amp;settings_file).expect(&quot;Error reading settings.json&quot;); let settings = Arc::new(parsed_settings); let mut buttons: Vec&lt;Button&gt; = Vec::new(); let args: Vec&lt;String&gt; = env::args().collect(); let mut url=&quot;&quot;; if args.len() &gt; 1 { url = &amp;args[1]; } nwg::Window::builder() .center(true) .size((600, 250)) .flags(WindowFlags::WINDOW | WindowFlags::POPUP) .title(&quot;CrossRoad&quot;) .build(&amp;mut window) .unwrap(); nwg::TextInput::builder() .text(url) .focus(true) .parent(&amp;window) .build(&amp;mut url_edit) .unwrap(); let mut buttons_layout = nwg::GridLayout::builder() .parent(&amp;window) .spacing(1) .child_item(nwg::GridLayoutItem::new(&amp;url_edit, 0, 0, settings.browsers.len() as u32, 1)); let mut button_count = 0; for browser in &amp;settings.browsers { let mut button = Default::default(); nwg::Button::builder() .text(&amp;browser.name) .parent(&amp;window) .build(&amp;mut button) .unwrap(); buttons_layout = buttons_layout.child_item(nwg::GridLayoutItem::new(&amp;button, button_count, 1, 1, 1)); button_count += 1; buttons.push(button); }; buttons_layout.build(&amp;layout) .unwrap(); let window = Rc::new(window); window.set_visible(true); let events_window = window.clone(); let handler = nwg::full_bind_event_handler(&amp;window.handle, move |evt, _evt_data, handle| { use nwg::Event as E; match evt { E::OnWindowClose =&gt; if &amp;handle == &amp;events_window as &amp;nwg::Window { nwg::stop_thread_dispatch(); }, E::OnButtonClick =&gt; for button in &amp;buttons { if &amp;handle == &amp;button.handle { for browser in &amp;settings.browsers { if &amp;browser.name == &amp;button.text() { run_browser(&amp;browser, url_edit.text()); } } } }, _ =&gt; {} } }); nwg::dispatch_thread_events(); nwg::unbind_event_handler(&amp;handler); } </code></pre> <p>I'm aware that there already are some programs that do that, but most of them are very outdated and limited, as they only allow to predefine URL lists that are used to decide which browser to use for which URL. I only found a single program that allows an interactive selection and that was bloated up to 50MB, which indicates that it was written using a framework like Electron. I prefer optimized programs that are written for the intended platform. I wanted to dive into Rust for some time now and decided to use this as an opportunity to learn it.</p> <p><a href="https://github.com/schneidr/CrossRoad" rel="nofollow noreferrer">Here is the complete project on GitHub</a>.</p> <p>What feels &quot;dirty&quot; to me:</p> <ul> <li>building the <code>arguments</code> array in the function <code>run_browser</code>. It seems superfluous to create a new vector of strings and iterate over an existing vector of strings and add each string one by one, but I was unable to find a way to just use, clone or cast the existing vector.</li> <li>finding the correct browser after a button click by comparing the button text. I'd rather store a reference to the button in the Browser object, but I couldn't find how to ignore this during the serialization/deserialization.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T05:35:12.120", "Id": "269026", "Score": "1", "Tags": [ "beginner", "rust" ], "Title": "Interactive browser launcher in Rust using Native Windows GUI" }
269026
<p>Recently, I was studying flask and my friend sent me a bit.ly link. Then the idea of a bit.ly clone struck my mind.</p> <p>This project uses</p> <ul> <li>Python - 3.10.0</li> <li>flask - version 2.0.2</li> <li>Bootstrap CSS. (I am very bad at CSS)</li> <li>sqlite3</li> </ul> <p>I would appreciate you thoughts and improvements on my implementation.</p> <p>File directory structure -</p> <pre><code>Bit.ly Clone - |- templates - | - index.html |- app.py |- database.db |- schema.sql </code></pre> <h2>index.html</h2> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;title&gt;Url Shortener&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Url Shortener&lt;/h1&gt; &lt;form method=&quot;post&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;URL&quot;&gt;URL&lt;/label&gt; &lt;input name=&quot;org_url&quot; class=&quot;form-control&quot; id=&quot;URL&quot;&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;short_url&quot;&gt;Short URL&lt;/label&gt; &lt;input name=&quot;short_url&quot; class=&quot;form-control&quot; id=&quot;short_url&quot;&gt; &lt;/div&gt; &lt;br&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Create&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>schema.sql</h2> <pre><code>DROP TABLE IF EXISTS URL_Table; CREATE TABLE URL_Table ( org_url TEXT NOT NULL, short_url TEXT NOT NULL); </code></pre> <h2>database.db</h2> <h2>app.py</h2> <pre><code>from flask import Flask, render_template, request, redirect from werkzeug.exceptions import abort import sqlite3 app = Flask(__name__) database = 'database.db' def init_db(): conn = sqlite3.connect(database) cursor = conn.cursor() with open('schema.sql', 'r') as file: cursor.executescript(file.read()) conn.commit() conn.close() def get_db_conn(): return sqlite3.connect(database) def get_record(short_url): conn = get_db_conn() cursor = conn.cursor() record = cursor.execute('SELECT * FROM URL_Table WHERE short_url = ?', (short_url,)).fetchone() conn.close() return record def create_record(org_url, short_url): conn = get_db_conn() cursor = conn.cursor() cursor.execute('INSERT INTO URL_Table VALUES(?, ?)', (org_url, short_url)) conn.commit() conn.close() @app.route('/') def index(): init_db() return redirect('/create') @app.route('/create', methods=('GET', 'POST')) def create(): if request.method == 'POST': create_record(request.form['org_url'], request.form['short_url']) return render_template('index.html') @app.route('/&lt;string:url&gt;') def get_url(url): record = get_record(url) if record is None: return abort(404) return redirect(record[0]) app.run(debug=True) </code></pre> <p>Thanks!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T07:53:01.470", "Id": "269030", "Score": "1", "Tags": [ "python", "sqlite", "flask" ], "Title": "bit.ly Clone in Python powered by Flask" }
269030
<blockquote> <p><strong>Input</strong><br /> The first line of input contains a string s: the word misspelled by your partner. Assume that your partner did not add or remove any letters; they only replaced letters with incorrect ones. The next line contains a single positive integer n indicating the number of possible valid words that your partner could have meant to write. Each of the next n lines contains each of these words. There is guaranteed to be at least one word of the same length as the misspelled word.</p> <p><strong>Output</strong><br /> Output a single word w: the word in the dictionary of possible words closest to the misspelled word. &quot;Closeness&quot; is defined as the minimum number of different characters. If there is a tie, choose the word that comes first in the given dictionary of words.</p> </blockquote> <pre><code>Example: input deat 6 fate feet beat meat deer dean output beat </code></pre> <blockquote> </blockquote> <pre><code>s = input() n = int(input()) count_list = [] word_list = [] final = [] count = 0 for i in range(n): N = input() for j in range(len(N)): if s[j] == N[j]: count += 1 count_list.append(count) word_list.append(N) count = 0 max_c = count_list[0] for i in range(len(count_list)): if count_list[i] &gt; max_c: max_c = count_list[i] indices = [index for index, val in enumerate(count_list) if val == max_c] for i in range(len(indices)): final.append(word_list[indices[i]]) print(final[0]) </code></pre> <p>This is what I managed to write. This code passed 3 test cases but failed the 4th. I tried to do final.sort() to put them in alphabetical order, but it fails on the 2nd test case (I can only see the 1st test case which is included in this post). What can I do to fix this? The code only allows words with the same number of characters as the control string, which might be causing the wrong test case since one of the test cases might have more or less characters than the control string? Can someone help?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T13:59:56.697", "Id": "530713", "Score": "0", "body": "Related: [Calculate Levenshtein distance between two strings in Python](https://codereview.stackexchange.com/questions/217065/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T12:12:12.450", "Id": "530764", "Score": "0", "body": "Please add a link to the programming challenge." } ]
[ { "body": "<h1>Code Review</h1>\n<p>Your code doesn't pass all of the test cases, so by some definitions, it is not ready for a code review. However, it is close enough to working and has several code-habits that should be corrected, that I'll give you a Code Review anyway.</p>\n<h2>Variable names</h2>\n<p>Both <code>count_list</code> and <code>word_list</code> are nice, descriptive variable names. <code>final</code> is ok, but not very descriptive (final what?). However, variable names like <code>s</code>, <code>n</code>, <code>N</code> are terrible, especially in global scope. The fact the <code>n</code> is a count, and <code>N</code> is a string is outright confusing.</p>\n<p><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8: The Style Guide for Python Code</a> recommends all variable names should be in <code>snake_case</code>. Uppercase letters are used only in <code>NAMED_CONSTANTS</code> and <code>ClassNames</code>.</p>\n<h2>Variable Types</h2>\n<p><code>count_list</code> and <code>word_list</code> are parallel data structures. <code>count_list[j]</code> is the count of matching letters in <code>word_list[j]</code>.</p>\n<p>The would be better expressed as a dictionary. Ie) <code>match_length = {}</code> and <code>match_length[word] = count</code>. As of Python 3.6 (December 2016), dictionaries are ordered by insertion order, so determining which word came before other words is still possible.</p>\n<h2>Throw-away variables</h2>\n<p>In the first loop, <code>for i in range(n):</code>, the variable <code>i</code> is never used. PEP-8 recommends using <code>_</code> for these kind of variables. Ie) <code>for _ in range(n):</code></p>\n<h2>Initialize before use</h2>\n<p>You have:</p>\n<pre class=\"lang-py prettyprint-override\"><code>count = 0\n\nfor i in range(n):\n ...\n \n for j in range(len(N)):\n if s[j] == N[j]:\n count += 1 \n ...\n count = 0\n</code></pre>\n<p>The variable <code>count</code> is set to zero in two different statements. The first initialization is before the outer loop, so it looks like it might be counting items found in the outer loop, but it is not; it is counting in the inner loop. This should be reorganized:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\nfor i in range(n):\n ...\n count = 0\n \n for j in range(len(N)):\n if s[j] == N[j]:\n count += 1 \n ...\n</code></pre>\n<p>Now you only have one location where <code>count</code> is reset to zero. The code should be easier to understand.</p>\n<h2>Loop over values, not indices</h2>\n<p>The inner loop iterates over the indices of <code>N</code>, assigning successive values to <code>j</code>, but the contents of the loop only ever uses <code>j</code> as an index: <code>s[j]</code> and <code>N[j]</code>. Python is optimized for iterating over the values in containers.</p>\n<pre class=\"lang-py prettyprint-override\"><code>\n count = 0\n for s_letter, candidate_word_letter in zip(s, N):\n if s_letter == candidate_word_letter:\n count += 1\n</code></pre>\n<h2>Built in functions</h2>\n<pre class=\"lang-py prettyprint-override\"><code>max_c = count_list[0]\nfor i in range(len(count_list)):\n if count_list[i] &gt; max_c:\n max_c = count_list[i]\n</code></pre>\n<p>This is reinventing the wheel. It is such a common operation, Python has a built-in function for doing it.</p>\n<pre class=\"lang-py prettyprint-override\"><code>max_c = max(count_list)\n</code></pre>\n<h1>Incorrect Output</h1>\n<blockquote>\n<p>This code passed 3 test cases but failed the 4th</p>\n</blockquote>\n<p>Relook at your problem description. Print it out. Using a pen, cross off all the conditions that you test for. At the end, you should see something which you haven't tested. Adding a check for that will solve your problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T12:14:14.133", "Id": "530765", "Score": "1", "body": "I'm going to leave the question open because this is a good answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T18:40:36.877", "Id": "269043", "ParentId": "269031", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T10:00:30.540", "Id": "269031", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Find the closest match to a string" }
269031
<p>I've created a simple Snakes and Ladders game. The goal is improving my knowledge about OOP.There are some basic rules.</p> <ol> <li>I need to be able to move my token.</li> <li>The token starts in the square 1.</li> <li>If the token is on square 1 and is moved by 3 then the token is on square 4.</li> <li>A player can win the game.</li> <li>The first who reaches the square 100 is the winner.</li> <li>You can't over-square the board. If you do it your position will remain the same. (97 + 4 = 97)</li> <li>The moves are based on a roll dice between 1 and 6.</li> <li>The player rolls the dice, then moves the token.</li> </ol> <p>Keeping all this in mind as I did.</p> <h1>Class CBoard.cs</h1> <pre><code>using System; using System.Collections.Generic; namespace Snakes_and_ladders { class CBoard { private int[] board; List&lt;CPlayer&gt; players = new List&lt;CPlayer&gt;(); public int[] Board { get =&gt; board; } public CBoard() { // A 100-cell board is created by default. board = new int[100]; Array.Clear(board, 0, board.Length); } // Function to create Ladders and Snakes.Se changes the value // of the array in the index [i-1] being i the key of the // dictionary.the value that is saved in that index corresponds // to the value of the board where the player moves in case of // falling into said Index. // // Ex: Key =&gt; 2, Value =&gt; 10 implies that there is a ladder that // goes from cell 1 to cell 9 of the board. private void createSnakesOrLadders(Dictionary&lt;int, int&gt; dataDict) { foreach (KeyValuePair&lt;int, int&gt; data in dataDict) { board[data.Key - 1] = data.Value - 1; } } // Default constructor overload // Creates an A x L board by adding ladders and snakes. public CBoard(int altura, int largo, Dictionary&lt;int, int&gt; ladders = null, Dictionary&lt;int, int&gt; snakes = null) { // At a minimum, a 2x2 board is necessary. if (altura &lt; 2 || largo &lt; 2) throw new Exception(&quot;The height and length need to be at least greater than 1.&quot;); // Initial size of the number of ladders and snakes on the board. int ladderSize = 0; int snakesSize = 0; // If the board is not null, we save the actual number of ladders and snakes. if (!(ladders is null)) ladderSize = ladders.Count; if (!(snakes is null)) snakesSize = snakes.Count; // We create the board, with values set to 0. board = new int[altura * largo]; Array.Clear(board, 0, board.Length); // If the total size of the number of ladders and snakes is less than half the board // ladders and snakes are created on the board. If not, the exception is thrown. if ((ladderSize * 2) + (snakesSize * 2) / 2 &lt; board.Length) { if (!(ladders is null)) createSnakesOrLadders(ladders); if (!(snakes is null)) createSnakesOrLadders(snakes); } else { throw new Exception(&quot;The total sum of Snakes and Ladders cannot exceed 50% of the board.&quot;); } } } } </code></pre> <h1>Class CPlayer.cs</h1> <pre><code>using System; using System.Threading; namespace Snakes_and_ladders { class CPlayer { int[] board; private int position = 0; private string nickName = null; private int diceResult = 0; private bool winner = false; public int Position { get =&gt; position + 1; } public int DiceResult { get =&gt; diceResult; } public string NickName { get =&gt; nickName; } public bool Winner { get =&gt; winner; } public CPlayer(string nickName, CBoard board) { this.nickName = nickName; this.board = board.Board; } public void Roll() { // Wait 30 milliseconds to change the random seed. Random rnd = new Random(); Thread.Sleep(30); diceResult = rnd.Next(1, 7); } public void Move() { // Move the player N dice cells. if (position + diceResult &lt; board.Length) if (board[position + diceResult] == 0) position = position + diceResult; else position = board[diceResult + position]; if (position == board.Length - 1) winner = true; } } } </code></pre> <h1>Program.cs</h1> <pre><code>using System; using System.Collections.Generic; namespace Snakes_and_ladders { class Program { static void Main(string[] args) { // Ladders Dictionary&lt;int, int&gt; ladderDicctionary = new Dictionary&lt;int, int&gt;() { {2, 38}, {7, 14}, {8, 31}, {16, 26}, {21, 42}, {28, 84}, {36, 44}, {51, 67}, {71, 91}, {78, 98}, {87, 94} }; // Snakes Dictionary&lt;int, int&gt; snakesDicctionary = new Dictionary&lt;int, int&gt;() { {15, 5}, {48, 10}, {45, 24}, {61, 18}, {63, 59}, {73, 52}, {88, 67}, {91, 87}, {94, 74}, {98, 79} }; CBoard customBoard = new CBoard(10, 10, ladderDicctionary, snakesDicctionary); // Board by default. CBoard board = new CBoard(); List&lt;CPlayer&gt; players = new List&lt;CPlayer&gt;(); int n_players = 0; do { Console.Write(&quot;Enter the number of players: &quot;); n_players = Convert.ToInt32(Console.ReadLine()); if(n_players &lt;= 1) Console.WriteLine(&quot;The total of players need to be 2 or more.&quot;); } while (n_players &lt;= 1); for(int i=1; i &lt; n_players + 1; i++) { Console.Write(&quot;Enter the name for the player {0}: &quot;, i); string nickName = Console.ReadLine(); players.Add(new CPlayer(nickName, customBoard)); } string pressed = &quot;&quot;; int count = 0; do { if (count &gt;= n_players) count = 0; CPlayer currentPlayer = players[count]; Console.WriteLine(&quot;It's the player {0}'s turn&quot;, currentPlayer.NickName); Console.WriteLine(&quot;Press R to Roll the die or A to abort the game.&quot;); pressed = Console.ReadLine(); if(pressed.Equals(&quot;R&quot;, StringComparison.CurrentCultureIgnoreCase)) { Console.WriteLine(&quot;--------------------------------&quot;); currentPlayer.Roll(); Console.WriteLine(&quot;Dice's result: {0} &quot;, currentPlayer.DiceResult); int previousPosition = currentPlayer.Position; currentPlayer.Move(); Console.WriteLine(&quot;You moved from cell [{0}] ====&gt; to cell [{1}]&quot;, previousPosition, currentPlayer.Position); if (currentPlayer.Winner) { Console.WriteLine(&quot;Player {0} won the game.&quot;, currentPlayer.NickName); break; } Console.WriteLine(&quot;--------------------------------&quot;); count++; } } while (!pressed.Equals(&quot;A&quot;, StringComparison.CurrentCultureIgnoreCase)); Console.ReadLine(); } } } </code></pre> <p>Based on the code, I'd like to know what I could improve, what mistakes I did, what advice you'd give me, in a nutshell: How could I improve the code and be better at OOP. Thanks!</p>
[]
[ { "body": "<ul>\n<li><p>When an array is created, it is nulled automatically. <code>Array.Clear(board, 0, board.Length);</code> is obsolete.</p>\n</li>\n<li><p>Rolling the dice: You are waiting a few milliseconds before creating the <code>Random</code> object to get different seeds. Better: Create it as a static field. The effect is that only one <code>Random</code> object will be created (and seeded once), no matter how many players you create.</p>\n<pre><code>class CPlayer\n{\n private static readonly Random rnd = new Random();\n\n public void Roll()\n {\n diceResult = rnd.Next(1, 7);\n }\n ...\n}\n</code></pre>\n</li>\n<li><p>We can also mark <code>board</code> as <code>readonly</code> since it is set only in the constructors. Note: <code>readonly</code> refers to the reference stored in <code>board</code>, not the contents of the board.</p>\n</li>\n<li><p>You are using dictionaries for the definition of snakes and ladders; however, you are never doing a dictionary lookup. Dictionaries are fast when looking up a value by key either through the indexer or the method <code>TryGetValue</code>. Inserting into a dictionary involves some overhead. Better use a list or an array.</p>\n<p>E.g., you could create an array of <code>KeyValuePair</code> or <code>ValueTuple</code>:<br />\n<code>(int from, int to)[] ladders = { (2, 38), (7, 14),… };</code></p>\n</li>\n<li><p>You are testing whether ladders and snakes are <code>null</code> twice. Do it once. You can still throw an exception after having added ladders and snakes to the board. This does not hurt. In C# 9.0 you can use the test <code>is not null</code>:</p>\n<pre><code>if (ladders is not null) {\n ladderSize = ladders.Count;\n createSnakesOrLadders(ladders);\n}\n// TODO: Do the same for the snakes.\n</code></pre>\n</li>\n<li><p>The calculation of the total number of snakes and ladders is wrong. It must be:</p>\n<pre><code>if (ladderSize + snakesSize &gt; board.Length / 2) {\n throw new Exception(&quot;The total sum of Snakes and Ladders cannot exceed 50% of the board.&quot;);\n}\n</code></pre>\n</li>\n<li><p>In class <code>CPlayer</code> you are initializing <code>position</code>, <code>nickName</code>, <code>diceResult</code> and <code>winner</code> to their default values. Other than local variables, class fields are automatically initialized to their default values. You can do it if you think that it better reflects you intention, but it is not necessary.</p>\n</li>\n<li><p>The <a href=\"https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md\" rel=\"nofollow noreferrer\">usual naming conventions for C#</a> is to not prepend a <code>C</code> for class names. Often developers prepend field names with an underscore to better distinguish them from local variables.</p>\n</li>\n<li><p>Optional: You could simplify moving the token if instead of initializing the board with 0s, you initialized it with the indexes:<br />\n<code>for (int i = 0; i &lt; board.Length; i++) { board[i] = i; }</code><br />\nThen, no matter whether there is a snake or ladder or not:<br />\n<code>position = board[diceResult + position];</code></p>\n</li>\n<li><p>Another simplification would be to replace <code>null</code> initial snakes and ladders arrays by empty ones. This eliminates some checks and the need for storing the sizes in variables as you can then directly use the array lengths.</p>\n<pre><code>public CBoard(int altura, int largo,\n (int from, int to)[] ladders = null, (int from, int to)[] snakes = null)\n{\n ladders = ladders ?? Array.Empty&lt;(int, int)&gt;();\n snakes = snakes ?? Array.Empty&lt;(int, int)&gt;();\n ...\n</code></pre>\n</li>\n<li><p>Instead of testing <code>i &lt; n_players + 1</code>, you can test <code>i &lt;= n_players</code>.</p>\n</li>\n<li><p>You can use modulo arithmetic to make the player index turn around:<br />\n<code>count = (count + 1) % n_players;</code></p>\n</li>\n<li><p>You can use string interpolation:<br />\n<code>Console.WriteLine($&quot;Player {currentPlayer.NickName} won the game.&quot;);</code><br />\nis easier to read than<br />\n<code>Console.WriteLine(&quot;Player {0} won the game.&quot;, currentPlayer.NickName);</code></p>\n</li>\n<li><p>You can use auto properties in some cases. They automatically create an invisible backing field.</p>\n<pre><code>private readonly string nickName;\npublic string NickName { get =&gt; nickName; }\n</code></pre>\n<p>Can be replaced by</p>\n<pre><code>public string NickName { get; }\n</code></pre>\n<p>Note that a getter-only property can be set in the constructor.</p>\n</li>\n<li><p>By using</p>\n<pre><code>// pressed is declared as char\npressed = Char.ToUpper(Console.ReadKey().KeyChar);\nConsole.WriteLine();\n</code></pre>\n<p>instead of</p>\n<pre><code>pressed = Console.ReadLine();\n</code></pre>\n<p>The user does not need to press <kbd>Enter</kbd> after entering R or A and you eliminate the need to do a complex comparison involving <code>StringComparison.CurrentCultureIgnoreCase</code>.</p>\n</li>\n</ul>\n<p>I suggested some changes using C# techniques that you might not be familiar with. You can just ignore them and keep your approach, if you prefer.</p>\n<p>Here is a possible solution</p>\n<pre><code>class Board\n{\n public int[] GameBoard { get; }\n\n public Board()\n {\n GameBoard = CreateBoard(100);\n }\n\n public Board(int altura, int largo,\n (int, int)[] ladders = null, (int, int)[] snakes = null)\n {\n if (altura &lt; 2 || largo &lt; 2) {\n throw new Exception(&quot;The height and length need to be at least greater than 1.&quot;);\n }\n\n // Ensure non-null arrays.\n ladders = ladders ?? Array.Empty&lt;(int, int)&gt;();\n snakes = snakes ?? Array.Empty&lt;(int, int)&gt;();\n\n GameBoard = CreateBoard(altura * largo);\n if (ladders.Length + snakes.Length &gt; GameBoard.Length / 2) {\n throw new Exception(&quot;The total sum of Snakes and Ladders cannot exceed 50% of the board.&quot;);\n }\n\n CreateSnakesOrLadders(ladders);\n CreateSnakesOrLadders(snakes);\n }\n\n private int[] CreateBoard(int size)\n {\n int[] board = new int[size];\n for (int i = 0; i &lt; size; i++) {\n board[i] = i;\n }\n return board;\n }\n\n private void CreateSnakesOrLadders((int, int)[] jumps)\n {\n foreach (var (from, to) in jumps) {\n GameBoard[from - 1] = to - 1;\n }\n }\n}\n</code></pre>\n<pre><code>class Player\n{\n private static readonly Random _rnd = new Random();\n private readonly int[] _board;\n\n private int _position;\n public int Position =&gt; _position + 1;\n\n public int DiceResult { get; private set; }\n public string NickName { get; }\n public bool Winner { get; private set; }\n\n public Player(string nickName, Board board)\n {\n NickName = nickName;\n _board = board.GameBoard;\n }\n\n public void Roll()\n {\n DiceResult = _rnd.Next(1, 7);\n }\n\n public void Move()\n {\n if (_position + DiceResult &lt; _board.Length) {\n _position = _board[DiceResult + _position];\n if (_position == _board.Length - 1) {\n Winner = true;\n }\n }\n }\n}\n</code></pre>\n<pre><code>class Program\n{\n public static void Main_()\n {\n (int, int)[] ladders = {\n (2, 38), (7, 14), (8, 31), (16, 26), (21, 42),\n (28, 84), (36, 44), (51, 67), (71, 91), (78, 98), (87, 94)\n };\n\n (int, int)[] snakes = {\n (15, 5), (48, 10), (45, 24), (61, 18), (63, 59),\n (73, 52), (88, 67), (91, 87), (94, 74), (98, 79)\n };\n\n var board = new Board(10, 10, ladders, snakes);\n var players = new List&lt;Player&gt;();\n\n int numPlayers;\n do {\n Console.Write(&quot;Enter the number of players: &quot;);\n numPlayers = Convert.ToInt32(Console.ReadLine());\n\n if (numPlayers &lt;= 1) {\n Console.WriteLine(&quot;The total of players need to be 2 or more.&quot;);\n }\n } while (numPlayers &lt;= 1);\n\n for (int i = 1; i &lt;= numPlayers; i++) {\n Console.Write($&quot;Enter the name for the player {i}: &quot;);\n string nickName = Console.ReadLine();\n\n players.Add(new Player(nickName, board));\n }\n\n char pressed;\n int count = 0;\n do {\n Player currentPlayer = players[count];\n Console.WriteLine($&quot;It's the player {currentPlayer.NickName}'s turn&quot;);\n Console.WriteLine(&quot;Press R to Roll the dice or A to abort the game.&quot;);\n pressed = Char.ToUpper(Console.ReadKey().KeyChar);\n Console.WriteLine();\n\n if (pressed == 'R') {\n Console.WriteLine(&quot;--------------------------------&quot;);\n\n currentPlayer.Roll();\n Console.WriteLine($&quot;Dice's result: {currentPlayer.DiceResult} &quot;);\n\n int previousPosition = currentPlayer.Position;\n currentPlayer.Move();\n Console.WriteLine($&quot;{currentPlayer.NickName} moved from cell [{previousPosition}] ====&gt; to cell [{currentPlayer.Position}]&quot;);\n\n if (currentPlayer.Winner) {\n Console.WriteLine($&quot;Player {currentPlayer.NickName} won the game.&quot;);\n break;\n }\n\n Console.WriteLine(&quot;--------------------------------&quot;);\n count = (count + 1) % numPlayers;\n }\n } while (pressed != 'A');\n }\n}\n</code></pre>\n<hr />\n<p><strong>Q &amp; A</strong></p>\n<blockquote>\n<p>Also, just to be sure, what would be the appropriate scenarios where you would use auto properties?</p>\n</blockquote>\n<p>Auto properties were introduced in C# 3.0 and were improved in later versions. They aim to make your life easier. Use them when ever you can, i.e., when there is no logic other than getting or setting the backing field. In <code>Position</code> we cannot use it because we are returning <code>_position + 1</code>.</p>\n<hr />\n<blockquote>\n<p>instead of var in the foreach statement, what'd be its type? I tried with (int,int)[] but it didn't work. Happened the same with (int, int)</p>\n</blockquote>\n<p>Tuples can be deconstructed, i.e., their components can be extracted into variables. The foreach loop does it with <code>var (from, to) in jumps</code>. This could also be written as <code>(int from, int to) in jumps</code>. This declares two new <code>int</code> variables <code>from</code> and <code>to</code> and assigns them the tuple elements.</p>\n<p>Alternatively, we could keep the tuple as is and write <code>var jump in jumps</code> or explicitly <code>(int, int) jump in jumps</code> and then access its components through the loop variable <code>jump</code> with <code>jump.Item1</code> and <code>jump.Item2</code>. We can also give custom names to the tuple items: <code>(int from, int to) jump in jumps</code> and then access them with <code>jump.from</code> and <code>jump.to</code>.</p>\n<p>Note that we are looping through an array <code>(int, int)[] jumps</code>, i.e., an array consisting of elements of the tuple type <code>(int, int)</code>. Therefore, the loop variable must be a <code>(int, int)</code>.</p>\n<p>As you can see, we have a lot of options here: deconstruct vs. keeping the tuple, implicit versus explicit type declarations, using standard vs. custom tuple item names.</p>\n<hr />\n<blockquote>\n<p>public int Position =&gt; _position + 1; this line is acting like a getter? It means that I can omit the get statement in that way?</p>\n</blockquote>\n<p>This is quite a new addition to the language and is called “expression bodied members”. This is only a simplified syntax variant having no special meaning. It can be used whenever a method or a getter consists of a single return statement or when a void method, a setter or a constructor contains a single expression (where an assignment is an expression). Examples:</p>\n<p><code>string GetGreeting() { return “Hello”; }</code> same as <code>string GetGreeting() =&gt; “Hello”;</code>.</p>\n<p><code>string Greeting { get { return “Hello”; } }</code> same as <code>string Greeting =&gt; “Hello”;</code>.</p>\n<p><code>string Greeting { get { return g; } set { g = value; } }</code> same as<br />\n<code>string Greeting { get =&gt; g; set =&gt; g = value; }</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T18:13:31.930", "Id": "530724", "Score": "0", "body": "Thanks a lot for your reply @Olivier Jacot-Descombes, I feel that I've learnt a LOT from this. Thanks for such a good answer! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T18:25:25.773", "Id": "530725", "Score": "0", "body": "Also, just to be sure, what would be the appropriate scenarios where you would use auto properties?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T00:58:16.370", "Id": "530739", "Score": "0", "body": "And my last two questions, 1. instead of `var` in the foreach statement, what'd be its type? I tried with `(int,int)[]` but it didn't work. Happened the same with `(int, int)`. 2. `public int Position => _position + 1;` this line is acting like a getter? It means that I can omite the `get` statement in that way? Thanks in advance, as I've said I've learnt a lot from this." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T15:29:13.850", "Id": "269039", "ParentId": "269035", "Score": "6" } }, { "body": "<p>It would have been much more fun to play if you had some sort of visualization of what's happening on the board.</p>\n<p>I have come up with this quick and dirty method, but I'm sure you can do much better!</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public void PrintBoard(List&lt;CPlayer&gt; players)\n{\n Console.Write(&quot; &quot;);\n for (int col = 0; col &lt; 10; col++)\n Console.Write(col.ToString(&quot;D1&quot;) + &quot; &quot;);\n Console.WriteLine(&quot;&quot;);\n for (int row = 9; row &gt;= 0; row--)\n {\n Console.Write((row * 10).ToString(&quot;D2&quot;) + &quot; | &quot;);\n for (int col = 0; col &lt; 10; col++)\n {\n int index = col + row * 10;\n char c = ' ';\n foreach (var player in players)\n {\n if (player.Position - 1 == index)\n c = player.NickName[0];\n }\n Console.Write(board[index].ToString(&quot;D2&quot;) + &quot;[&quot; + c + &quot;]&quot;);\n }\n Console.WriteLine();\n }\n}\n</code></pre>\n<p>After another 5 minutes of playing, I realized that it might be better to play against someone else. I asked my wife to join but she was not interested.</p>\n<p>Perhaps you should consider the option of playing against the computer if the number of players is 1.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T18:05:53.827", "Id": "534030", "Score": "1", "body": "Also I was referring to this post in the other one! :) I found funny that you asked your wife to play this awful code haha, thanks for your reply, I also found interesting to implement an option to play against the machine. Have a good day and sorry for the late response." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T17:33:58.570", "Id": "269204", "ParentId": "269035", "Score": "1" } } ]
{ "AcceptedAnswerId": "269039", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T12:46:00.130", "Id": "269035", "Score": "3", "Tags": [ "c#", "object-oriented" ], "Title": "Snakes and Ladders OOP" }
269035
<p>I have created a simple server that host html that has css. Please make sure if ur testing then change the paths relative to ur system in listhell.c in respond_main(..) function.</p> <p>The html file has to be named as html9.html and css has to be named as style9.css should be path to ../project directory/css directory. this is the code along with makefile</p> <p>This is main function file server.c</p> <pre><code> #include &quot;headers/accept.h&quot; int main() { pthread_t thread_css; pthread_t thread_html; pthread_t thread_get; int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = {0}; char *hello = &quot;Hello from server&quot;; if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { printf(&quot;socket failed\n&quot;); exit(EXIT_FAILURE); } printf(&quot;server_fd = %d\n&quot;,server_fd); if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &amp;opt, sizeof(opt))) { printf(&quot;setsockopt\n&quot;); exit(EXIT_FAILURE); } int state = 1; if(setsockopt(server_fd, IPPROTO_TCP, TCP_CORK, &amp;state, sizeof(state))) { printf(&quot;TCP CORK\n&quot;); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&amp;address, sizeof(address))&lt;0) { printf(&quot;bind failed\n&quot;); exit(EXIT_FAILURE); } if (listen(server_fd, 3) &lt; 0) { printf(&quot;listen\n&quot;); exit(EXIT_FAILURE); } accept1(server_fd,address,addrlen); return 0; } </code></pre> <p>this is the file that contains linux socket <code>accept</code> function call accept.c</p> <pre><code> #include &quot;headers/accept.h&quot; #define BUFFER 1024+1 int check_if_t(char *buffer,int valread,int *f) { int i=0; while(i&lt;BUFFER) { printf(&quot;%c&quot;,*(buffer+i)); if(*(buffer+i)=='\r') { *f=1; printf(&quot;***************************************************************************\n&quot;); return i; } i++; } return i; } void* handle_request(void *arg) { //printf(&quot;\n&quot;); struct connection *con_obj=malloc(sizeof(struct connection)); if(con_obj!=NULL) { //con_obj-&gt;server_fd=(int*)arg; con_obj=(struct connection *)arg; //printf(&quot;new_socket get thread : %d\n&quot;,*(con_obj-&gt;new_socket)); char *str_array=NULL; str_array=malloc(BUFFER+1); str_array[0]='\0'; char buffer[BUFFER] = {0}; int x=0; int check_tp=0; int j=0; while(x&lt;BUFFER) { int valread=read(*(con_obj-&gt;new_socket),&amp;buffer[x],BUFFER);; // printf(&quot;Socket Buffer read valread = %d \n %.*s&quot;,(valread-1),(valread-1),buffer); int f=0; check_tp=check_if_t(buffer,(BUFFER),&amp;f); //printf(&quot;check_tp = %d\n&quot;,check_tp); if(f==1) { strncpy(&amp;str_array[j],&amp;buffer[j],check_tp); j=j+check_tp; str_array[j]='\0'; //printf(&quot;---&gt;\n&quot;); //printf(&quot;j = %d\n&quot;,j); //printf(&quot;%.*s\n&quot;,j,str_array); break; } if(str_array!=NULL) strncpy(&amp;str_array[j],&amp;buffer[j],check_tp); j=j+check_tp; x=x+check_tp; } x=0; if(str_array!=NULL) { if(strlen(str_array)&gt;0) { //printf(&quot;printing first line = %s | length = %zu j = %d\n &quot;,str_array,strlen(str_array),j); pthread_t thread_process; con_obj-&gt;request_line=malloc(sizeof(char)*j); if(con_obj-&gt;request_line==NULL) { while(1) { printf(&quot;handle_request -- heap problem at line 80: con_obj-&gt;request_line=malloc(sizeof(char)*j); \n&quot;); } } if(j&gt;=BUFFER) { free(con_obj-&gt;request_line); printf(&quot;check line 89 handle_request\n&quot;); //exit(0); j=BUFFER-1; con_obj-&gt;request_line[j]='\0'; close(*(con_obj-&gt;new_socket)); free(con_obj); return (void*)0; } memcpy((con_obj-&gt;request_line),str_array,sizeof(char)*j); con_obj-&gt;request_line_size=j; pthread_create(&amp;thread_process, NULL, process, (void *)con_obj); } else{ //printf(&quot;str_array length not found = %zu\n&quot;,strlen(str_array)); } free(str_array); // } } else { printf(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n&quot;); printf(&quot;No space for malloc on heap\n&quot;); } return (void*)0; } void accept1(int server_fd,struct sockaddr_in address,int addrlen) { while(1) { int new_socket; if ((new_socket = accept(server_fd, (struct sockaddr *)&amp;address, (socklen_t*)&amp;addrlen))&lt;0) { perror(&quot;accept&quot;); exit(EXIT_FAILURE); } //printf(&quot;new_socket just created = %d\n&quot;,new_socket); pthread_t thread_get; struct connection *con_obj=malloc(sizeof(struct connection)); if(con_obj!=NULL) { con_obj-&gt;new_socket=&amp;new_socket; con_obj-&gt;address=address; //printf(&quot;%d hello\n&quot;,*(con_obj-&gt;new_socket)); pthread_create(&amp;thread_get, NULL, handle_request, (void *)con_obj); } else { printf(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n&quot;); printf(&quot;No space for malloc on heap\n&quot;); } int state = 0; if(setsockopt(server_fd, IPPROTO_TCP, TCP_CORK, &amp;state, sizeof(state))) { printf(&quot;TCP CORK\n&quot;); } state = 1; if(setsockopt(server_fd, IPPROTO_TCP, TCP_CORK, &amp;state, sizeof(state))) { printf(&quot;TCP CORK\n&quot;); } //printf(&quot;After Thread creation\n&quot;); } } </code></pre> <p>this is process.c</p> <pre><code> #include &lt;stdio.h&gt; #include &quot;headers/accept.h&quot; //fetch null terminated string values // void get_dirs_file(char *path, char **dirs,char **file) // { // printf(&quot;getting directories and file for path = %s \n&quot;,path); // // } int handle_process(struct connection *con_obj,char **path,char **request_type) { int i=0; request_type[0]='\0'; int method=0; while(i&lt;(con_obj-&gt;request_line_size)) { //printf(&quot;%c&quot;,(con_obj-&gt;request_line[i])); if(strncmp(&amp;(con_obj-&gt;request_line[i]),&quot;GET&quot;,3)==0) { method=3; *request_type=malloc(sizeof(char)*4); strncpy(*request_type,&quot;GET&quot;,sizeof(char)*4); char *temp=con_obj-&gt;request_line+4; if(strncmp(temp,&quot;/ &quot;,2)==0) { *path=malloc(sizeof(char)*strlen(&quot;html9.html&quot;)); strncpy(*path,&quot;html9.html&quot;,strlen(&quot;html9.html&quot;)+1); break; } if(strncmp(temp,&quot;/add?&quot;,sizeof(char)*5)==0) { int j=0; while(j&lt;strlen(temp)) { if(temp[j]==' ') { break; } j++; } *path =malloc(sizeof(char)*j+1); strncpy(*path,temp,sizeof(char)*j); (*(path+j))='\0'; //tm((&amp;path)); //printf(&quot;hello line now -------&gt; %s\n&quot;,*path); break; } if(strncmp(temp,&quot;/css/&quot;,sizeof(char)*5)==0) { int j=0; while(j&lt;strlen(temp)) { if(temp[j]==' ') { break; } j++; } *path=malloc(sizeof(char)*j+1); strncpy(*path,temp,sizeof(char)*j); (*(path+j))='\0'; //printf(&quot;hello line now -------&gt; %s\n&quot;,*path); } //return strlen(&quot;GET&quot;); } i++; } printf(&quot;hello line now -------&gt; path = %s request_type = %s\n&quot;,*path,*request_type); if(method==0) return 0; return strlen(*request_type); } void *process(void *p) { //printf(&quot;hello in process thread\n&quot;); int r=0; struct connection *con_obj=malloc(sizeof(struct connection)); if (con_obj != NULL) { printf(&quot;\n\n&quot;); printf(&quot;------------------------------------------------------------------------------------\n&quot;); con_obj=(struct connection *)p; printf(&quot;In process thread | new_socket = %d\n&quot;,*(con_obj-&gt;new_socket)); printf(&quot;j = %d | request_line = %s\n&quot;,(con_obj-&gt;request_line_size),(con_obj-&gt;request_line)); char *path=NULL; char*request_type=NULL; //path will be allocated and get null ['\0'] terminated in handle_process printf(&quot;before handle_process\n&quot;); int request_type_size=handle_process(con_obj,&amp;path,&amp;request_type); if(request_type_size==0) { //different request_type close(*(con_obj-&gt;new_socket)); if(path!=NULL) free(path); if(request_type!=NULL) free(request_type); free(con_obj); return (void*)0; } printf(&quot;after handle_process\n&quot; ); if(path!=NULL) { printf(&quot;in handle_process Path Len = %zu Request Path = '%s'\n&quot;,strlen(path),path); } if(request_type!=NULL) { printf(&quot;in handle_process Type Len = %zu Request Type = '%s'\n&quot;,strlen(request_type),request_type); } if(path!=NULL &amp;&amp; request_type!=NULL) { if(strncmp(request_type,&quot;GET&quot;,request_type_size)==0) { printf(&quot;inside GET in process func\n&quot;); char *dirs; char *file; file=malloc(sizeof(char)*strlen(path)); // get_dirs_file: returns '/ ' for TYPE_MAIN | 'style9.css' for TYPE_CSS | 'title=&amp;price=' for TYPE_QUERY r= get_dirs_file(&amp;path[0],file);//get null terminated string values printf(&quot;\n\npath to follow -- = 'path = %s' 'file = %s'\n\n&quot;,path,file); if(r == TYPE_MAIN) { respond_main(con_obj,RESPONSE_MAIN_HTML); } else if(r== TYPE_CSS) { respond_main(con_obj,RESPONSE_MAIN_CSS); } else if(r=TYPE_QUERY) { respond_main(con_obj,RESPONSE_MIAN_QUERY); } free(file); } } close(*(con_obj-&gt;new_socket)); free(con_obj); printf(&quot;------------------------------------------------------------------------------------\n&quot;); } else { printf(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n&quot;); printf(&quot;No space for malloc on heap\n&quot;); } return (void *)0; } </code></pre> <p>this is file.c</p> <pre><code> #include &lt;fcntl.h&gt; #include &lt;errno.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &quot;headers/accept.h&quot; #include &lt;sys/types.h&gt; #include &lt;stdlib.h&gt; #include &lt;errno.h&gt; #include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; #include &lt;time.h&gt; int get_file_type(char *path,char *file) { int i=0; printf(&quot;%zu \n&quot;,strlen(path)); while(i&lt;strlen(path)) { if(path[i]=='?') { //query string int j=0; strcpy(file,&amp;path[i+1]); file[strlen(path)]='\0'; return TYPE_QUERY; } if(strncmp(&amp;path[i],&quot;html9.html&quot;,strlen(path))==0) { strcpy(file,&quot;/ &quot;); return TYPE_MAIN; } if(strncmp(&amp;path[i],&quot;.css&quot;,4)==0) { int j=strlen(path); while(j&gt;0) { if(path[j]=='/') { strcpy(&amp;file[0],&amp;path[j]); break; } j--; } // file[j]='\0'; return TYPE_CSS; } i++; } return 0; } /*&lt;-whether found return 1; else 0;*/ int getfile_data(char *path,char *file) { int ret=get_file_type(path,file); printf(&quot;request found !!! %s\n&quot;,file); if(ret==TYPE_MAIN) { printf(&quot;responding with main page\n&quot; ); return TYPE_MAIN; } else if(ret ==TYPE_CSS) { printf(&quot;responding with css\n&quot;); return TYPE_CSS; } else if(ret ==TYPE_QUERY) { printf(&quot;finally saving data and redirecting user to main with message\n&quot; ); return TYPE_QUERY; } else{ return 0; } //strncpy(**file,&quot;fwd&quot;,4); } int get_dirs_file( char *path,char *file) { printf(&quot;in get_dirs_file&quot;); int ret=getfile_data(path,file); return ret; } </code></pre> <p>this is listhell.c</p> <pre><code> //for fullfilling user requests #include &lt;stdio.h&gt; #include &quot;headers/accept.h&quot; int respond_main(struct connection *con_obj,int response_type) { char *html_header = &quot;HTTP/1.1 200 Okay\r\nContent-Type: text/html; charset=ISO-8859-4 \r\n\r\n&quot;; char *css_header = &quot;HTTP/1.1 200 Okay\r\nContent-Type: text/css\r\n\r\n&quot;; char *data_saved_message=&quot;HTTP/1.1 200 Okay\r\nContent-Type: text/html; charset=ISO-8859-4 \r\n\r\n&lt;html&gt;&lt;body&gt;add posted. will appear in 24 hours on listhell &lt;a href=\&quot;http://listhell.com/\&quot;&gt;go to main page&lt;/a&gt;&lt;/body&gt;&lt;/html&gt;&quot;; if(response_type==RESPONSE_MAIN_HTML) { struct stat sb_html; send(*(con_obj-&gt;new_socket) , html_header , strlen(html_header) , 0 ); sleep(10); int fd_in_html=open(&quot;/home/user/Desktop/lh/html9.html&quot;,O_RDONLY); const char* filename_html=&quot;/home/user/Desktop/lh/html9.html&quot;; if(fd_in_html!=-1) { if (stat(filename_html, &amp;sb_html) == -1) { printf(&quot;stat error %d\n&quot;,errno); } int x3=sendfile(*(con_obj-&gt;new_socket),fd_in_html,0,sb_html.st_size); close(fd_in_html); return HTTP_OK_200; } } else if(response_type==RESPONSE_MAIN_CSS) { struct stat sb_css; int fd_in_css=open(&quot;/home/user/Desktop/lh/css/style9.css&quot;,O_RDONLY); if(fd_in_css!=-1) { const char* filename_css=&quot;/home/user/Desktop/lh/css/style9.css&quot;; if (stat(filename_css, &amp;sb_css) == -1) { printf(&quot;stat error %d\n&quot;,errno); exit(EXIT_FAILURE); } sendfile(*(con_obj-&gt;new_socket),fd_in_css,0,sb_css.st_size); close(fd_in_css); return HTTP_OK_200; } } else if(response_type==RESPONSE_MIAN_QUERY) { // send(*(con_obj-&gt;new_socket) , data_saved_message , strlen(data_saved_message) , 0 ); //send(*(con_obj-&gt;new_socket) , data_saved_message , 200 , 0 ); //send(*(con_obj-&gt;new_socket) , data_saved_message , 200 , 0 ); //data_saved_message printf(&quot;data saved\n&quot;); return HTTP_OK_200; } return 0; } </code></pre> <p>This is sendfile.c</p> <pre><code> #include &lt;stdio.h&gt; #include &quot;headers/accept.h&quot; ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count) { off_t orig; if (offset != NULL) { /* Save current file offset and set offset to value in '*offset' */ orig = lseek(in_fd, 0, SEEK_CUR); if (orig == -1) return -1; if (lseek(in_fd, *offset, SEEK_SET) == -1) return -1; } size_t totSent = 0; while (count &gt; 0) { size_t toRead = min(BUF_SIZE, count); char buf[BUF_SIZE]; ssize_t numRead = read(in_fd, buf, toRead); if (numRead == -1) return -1; if (numRead == 0) break; /* EOF */ ssize_t numSent = write(out_fd, buf, numRead); if (numSent == -1) return -1; if (numSent == 0) /* Should never happen */ printf(&quot;fatal: should never happen&quot;); //fatal(&quot;sendfile: write() transferred 0 bytes&quot;); count -= numSent; totSent += numSent; } if (offset != NULL) { /* Return updated file offset in '*offset', and reset the file offset to the value it had when we were called. */ *offset = lseek(in_fd, 0, SEEK_CUR); if (*offset == -1) return -1; if (lseek(in_fd, orig, SEEK_SET) == -1) return -1; } return totSent; } </code></pre> <p>accept.h</p> <pre><code> #ifndef SERVER #define SERVER #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;sys/socket.h&gt; #include &lt;stdlib.h&gt; #include &lt;netinet/in.h&gt; #include &lt;string.h&gt; #include &lt;pthread.h&gt; #include &lt;malloc.h&gt; #include &lt;errno.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; #include &lt;netinet/tcp.h&gt; #include &lt;time.h&gt; #define PORT 80 void accept1(int server_fd,struct sockaddr_in address,int addrlen); struct connection { int *new_socket; int type; struct sockaddr_in address; char *request_line; int request_line_size; int server_fd; }; struct lh { int adid; char title[250]; float price; char city[75]; char state[125]; char country[125]; }; void *handle_request(void *arg); void *process(void *p); int handle_process(struct connection *con_obj,char **path,char **request_type); int get_dirs_file( char *path,char *file); int respond_main(struct connection *con_obj,int response_type); ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count); //request type #define TYPE_MAIN 2 #define TYPE_CSS 3 #define TYPE_QUERY 4 //reply type #define RESPONSE_MAIN_HTML 2 #define RESPONSE_MAIN_CSS 3 #define RESPONSE_MIAN_QUERY 4 // #define BUF_SIZE 20000 #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2 //HTTP RESPONSE #define HTTP_OK_200 200 #endif </code></pre> <p>makefile</p> <pre><code> HEADERS = headers/ lh: accept.o server.o process.o file.o listhell.o cc -g -pthread -o lh accept.o server.o process.o file.o listhell.o listhell.o: $(HEADERS)accept.h listhell.c cc -g -c -pthread listhell.c process.o : $(HEADERS)accept.h process.c cc -g -c -pthread process.c file.o : $(HEADERS)accept.h file.c cc -g -c -pthread file.c server.o : $(HEADERS)accept.h server.c cc -g -c -pthread server.c accept.o : $(HEADERS)accept.h accept.c cc -g -c -pthread accept.c clean : rm lh accept.o server.o process.o file.o listhell.o </code></pre>
[]
[ { "body": "<p>In this part:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct connection *con_obj=malloc(sizeof(struct connection));\nif(con_obj!=NULL)\n</code></pre>\n<p>You have checked if malloc succeeded, but then you print a warning and continue on. Consider using <code>assert</code> to test:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct connection *con_obj=malloc(sizeof(struct connection));\nassert(con_obj != NULL);\n</code></pre>\n<p>Why are you sleeping for 10 seconds?</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>sleep(10);\n</code></pre>\n<p>Here you are allocating one byte less than you need, and do not check if <code>malloc</code> was successfull:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>*path=malloc(sizeof(char)*strlen(&quot;html9.html&quot;));\nstrncpy(*path,&quot;html9.html&quot;,strlen(&quot;html9.html&quot;)+1);\n</code></pre>\n<p>Corrected code;</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>size_t length = strlen(&quot;html9.html&quot;) + 1;\n*path = (char*)malloc(sizeof(char) * length);\nassert(*path);\nstrncpy(*path, &quot;html9.html&quot;, length);\n</code></pre>\n<p>There is still a lot to go through, but I have to go and mow the lawn =)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T07:30:43.963", "Id": "530892", "Score": "0", "body": "did I accept your answer some time ago" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T12:22:07.193", "Id": "530917", "Score": "0", "body": "@user786, nope and i think G Sliepen's answer is much better =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T09:49:58.597", "Id": "531322", "Score": "0", "body": "thanks for answering." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T17:15:59.547", "Id": "269041", "ParentId": "269036", "Score": "1" } }, { "body": "<h1>Print errors to <code>stderr</code></h1>\n<p>Error messages should be sent to <code>stderr</code>. This is especially important if regular messages are sent to <code>stdout</code> and the standard output is redirected to a file or a pipe. On Linux, I recommend you use the <a href=\"https://linux.die.net/man/3/err\" rel=\"nofollow noreferrer\"><code>err()</code></a> function to report errors, like so:</p>\n<pre><code>if ((server_fd = socket(...)) == -1)\n err(EXIT_FAILURE, &quot;failed to open socket&quot;);\n</code></pre>\n<p>You can also print warnings using <a href=\"https://linux.die.net/man/3/warn\" rel=\"nofollow noreferrer\"><code>warn()</code></a>.</p>\n<h1>Incorrect checks of return values</h1>\n<p>If <a href=\"https://man7.org/linux/man-pages/man2/socket.2.html#RETURN_VALUE\" rel=\"nofollow noreferrer\"><code>socket()</code></a> fails, it will return -1, not 0. In fact, 0 is a valid file descriptor. Note that most POSIX functions return -1 on error if they return an <code>int</code>, and <code>NULL</code> if they return a pointer.</p>\n<h1>Consider supporting IPv6</h1>\n<p>Your program only supports IPv4 at the moment. I strongly recommend you also make it work for IPv6. It is not that hard. On Linux, you can get away with creating an <a href=\"https://man7.org/linux/man-pages/man7/ipv6.7.html\" rel=\"nofollow noreferrer\">IPv6 socket</a> and ensuring the <code>IPV6_V6ONLY</code> socket option is set to zero. The socket will then accept both IPv4 and IPv6 connections.</p>\n<h1><code>accept1()</code> only needs to know the file descriptor</h1>\n<p>There is no need to pass <code>address</code> to <code>accept1()</code>. You can just declare a local <code>struct sockaddr</code> variable inside <code>accept1()</code>.</p>\n<h1>Remove unused variables</h1>\n<p>You declared several variables at the top of <code>main()</code> that are never used in that function. Your compiler should be warning you about unused variables (and if not, be sure to enable warnings). Just remove them.</p>\n<h1>Useless use of <code>TCP_CORK</code> on the listening socket</h1>\n<p>The listening socket does not receive or transmit any data, so <code>TCP_CORK</code> is not doing anything there. Instead, you should set <code>TCP_CORK</code> on the file descriptor you got from <code>accept()</code>.</p>\n<h1>Remove unnecessary variables from <code>struct connection</code></h1>\n<p>There are a lot of variables in <code>struct connection</code> that are never used or should not be in there. The only thing <code>handle_request()</code> needs is the file descriptor of the socket it is handling. Since <code>handle_request()</code> only handles a single request and then immediately exits, there is no need for it to create yet another thread to call <code>process()</code>, it could just call <code>process()</code> directly. And if it calls it directly, it can pass any number of variables as regular function arguments, no need to store it in <code>con_obj</code>.</p>\n<p>Variables not used at all are <code>address</code> and <code>server_fd</code>.</p>\n<h1>Thread management</h1>\n<p>You create threads with <code>pthread_create()</code>, but you never clean them up. Threads should either be joined using <a href=\"https://man7.org/linux/man-pages/man3/pthread_join.3.html\" rel=\"nofollow noreferrer\"><code>pthread_join()</code></a> or detached using\n<a href=\"https://man7.org/linux/man-pages/man3/pthread_detach.3.html\" rel=\"nofollow noreferrer\"><code>pthread_detach()</code></a>. If you don't do either the resources used by the threads will not be cleaned up, and at some point you won't be able to create new threads anymore.</p>\n<p>Also think about what happens if someone opens thousands of connections to your server per second. This will spawn thousands of threads that all want to use the CPU. This can create lots of issues. I recommend implementing some way to limit how many threads can run at the same time. The best way is to implement a <a href=\"https://en.wikipedia.org/wiki/Thread_pool\" rel=\"nofollow noreferrer\">thread pool</a> and limit the number of threads to roughly the number of CPU cores of your machine. You can have the main thread call <code>accept()</code> in a loop and add <code>struct connection</code> object to a task queue that the workers will pick up, or alternatively have the workers call <code>accept()</code> themselves (but see <a href=\"https://stackoverflow.com/questions/17630416/calling-accept-from-multiple-threads\">this StackOverflow question</a>).</p>\n<h1>Use array notation where appropriate</h1>\n<p>I see you write <code>*(buffer+i)</code> in serveral places, but you should just use array notation instead: <code>buffer[i]</code>.</p>\n<h1>Memory leak</h1>\n<p>In <code>handle_requests()</code>, you call <code>malloc()</code> at the start, but you never actually use that memory, because you overwrite <code>con_obj</code> with <code>arg</code> right afterwards. Just remove that call to <code>malloc()</code>.</p>\n<h1>Reading lines from a socket</h1>\n<p>You correctly read from the socket in a loop, however the string copying code you wrote is rather buggy; in particular if there was no <code>\\r</code> in the first <code>read()</code>, you call <code>read()</code> again but now you can write past the end of <code>buffer</code>. The copying between <code>buffer</code> and <code>str_array</code> seems unnecessary as well. Instead of doing all this low-level stuff, consider using <a href=\"https://linux.die.net/man/3/fdopen\" rel=\"nofollow noreferrer\"><code>fdopen()</code></a> to create a <code>FILE</code> handle from a file descriptor, and then you can use <a href=\"https://linux.die.net/man/3/getdelim\" rel=\"nofollow noreferrer\"><code>getdelim()</code></a> to read a whole line at once, and not have to worry about allocating memory for buffers at all.</p>\n<h1>Consider using a HTTP server library</h1>\n<p>As you have probably realized, writing a HTTP server, even a simple one, is quite a lot of work. There are many libraries that can help you write a HTTP server without having to reimplement the socket I/O and request parsing yourself, like <a href=\"https://www.gnu.org/software/libmicrohttpd/\" rel=\"nofollow noreferrer\">libmicrohttpd</a> or <a href=\"https://github.com/cesanta/mongoose\" rel=\"nofollow noreferrer\">Mongoose</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T07:30:24.997", "Id": "530891", "Score": "0", "body": "did I accept ur answer some time ago?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T13:56:24.017", "Id": "530924", "Score": "0", "body": "What about resource leaks. Can u please check that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T10:14:04.773", "Id": "531325", "Score": "0", "body": "is Mongoose a C++ library or C library? Is there any documentation for it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T10:30:27.663", "Id": "531331", "Score": "0", "body": "@user786 Yes and yes. Just read the README.md that is shown when you follow the link." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T10:36:11.077", "Id": "269064", "ParentId": "269036", "Score": "2" } } ]
{ "AcceptedAnswerId": "269064", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T14:43:56.247", "Id": "269036", "Score": "1", "Tags": [ "c", "linux", "http", "socket", "server" ], "Title": "Simple server to host simple website page with css" }
269036
<p>I have a solution to the following question which seems straightforward enough. However, I feel as if I am missing something.</p> <p>The question: Objective: You have given a character ‘A’ which is already printed. You are allowed to perform only 2 operations –</p> <p>Copy All – This operation will copy all the printed characters. Paste – This operation will paste all the characters which are already copied. Given a number N, write an algorithm to print character ‘A’ exactly N times with minimum no of operations (either copy all or paste) Example</p> <p>Character – A<br /> N = 6</p> <p>Option 1: Copy All – this will copy ‘A’<br /> Paste – output “AA”<br /> Paste – output “AAA”<br /> Paste – output “AAAA”<br /> Paste – output “AAAAA”<br /> Paste – output “AAAAAA”<br /> Total operations – 6</p> <p>Option 2:<br /> Copy All – this will copy ‘A’<br /> Paste – output “AA”<br /> Paste – output “AAA”<br /> Copy All<br /> Paste – output “AAAAAA”<br /> Total operations – 5</p> <p>Since with option 2, the task is done in 5 operations. Minimum operations – 5</p> <p>My code:</p> <pre class="lang-py prettyprint-override"><code># Prime factors, this is just a brute force method, I am aware of better ways, however it is not my concern for this solution. def prime_factors(number): i = 2 factors = [] while i * i &lt;= number: if number % i: i += 1 else: number //= i factors.append(i) if number &gt; 1: factors.append(number) return factors # Helper function to copy the the current character string into the resultant final string def copy_characters(character_array, character_to_be_copied, number_of_times, operation_count): for i in range(number_of_times): character_array += character_to_be_copied operation_count += 1 return character_array, operation_count # Main function containing logic def copy_paste(character_to_be_copied = &quot;A&quot;, number_of_times_to_be_pasted = 0): character_array = &quot;&quot; operation_count = 0 # Just some validation if number_of_times_to_be_pasted &lt;= 0: return &quot;Invalid Number of Times to Be Pasted&quot; if character_to_be_copied == &quot;&quot;: return character_array # The first copy operation character_array += character_to_be_copied operation_count += 1 # Finding prime factors factors = prime_factors(number_of_times_to_be_pasted) # This code will cycle through the prime factors to perform the copy paste operations while factors != []: character_array, operation_count = copy_characters(character_array, character_to_be_copied, max(factors) - 1, operation_count) character_to_be_copied = character_array factors.remove(max(factors)) if factors != [] : operation_count += 1 #finally return the results print(character_array, operation_count) # Note: I am aware that fewer operations would be needed if we consider prime factors as further divisible # ie., for a large prime number this solution would make as many operations as the prime. However, a solution # that accounts for it would need to allow for memory of past states, which I do not think this question # is asking for. Please do correct me if I am wrong. Just trying to improve my programming ability. def main(): copy_paste(&quot;A&quot;, 7) if __name__ == '__main__': main() </code></pre> <p>Any feedback would be appreciated. Apologies if the format for the question is wrong, starting out in programming and need to get used to the rules for this site</p>
[]
[ { "body": "<ul>\n<li><p>The approach is correct. It may be optimized a bit.</p>\n<ul>\n<li><p>Use the fact that <span class=\"math-container\">\\$N(p^n) = n(p - 1)\\$</span>. Do not collect identical primes in the list, but just count them.</p>\n</li>\n<li><p>Calling <code>max(factors)</code> is a waste of time, for two reasons.</p>\n<p>First, the list of prime factors is naturally sorted. The way you build it, smaller factors are discovered, and added to the list, before the larger ones. Use <code>factors[-1]</code>.</p>\n<p>Second, the order in which you process factors really doesn't matter. This is a bit harder to see; try to prove it.</p>\n</li>\n<li><p>Combining the bullets above we can see that the list of factors is not needed at all. Process primes as you discover them.</p>\n</li>\n</ul>\n</li>\n<li><p>The problem doesn't ask for the final string. It only asks the number of operations. It means that you don't need to maintain the <code>character_array</code>. You are only interested in its length, a simple integer. Performing the quite expensive concatenations is another waste of cycles.</p>\n</li>\n<li><p>Do not hardcode the second argument to <code>copy_paste</code>. Pass it as a command line parameter, and use <code>sys.argv</code>.</p>\n</li>\n<li><p>Side note. If a decomposition of large primes (hence the history of copies) is allowed, the problem becomes <a href=\"https://en.wikipedia.org/wiki/Addition_chain\" rel=\"noreferrer\">much more complicated</a>.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T22:01:29.980", "Id": "530728", "Score": "0", "body": "Thanks a lot, this was very helpful. I can see the improvements now. Now that I think about it, the order does not indeed matter, and there was no need to process the primes separtely. I will rework the solution with these points in mind. Also, the addition chain wiki was very insightful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T19:53:44.433", "Id": "269045", "ParentId": "269038", "Score": "5" } } ]
{ "AcceptedAnswerId": "269045", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T15:18:45.767", "Id": "269038", "Score": "4", "Tags": [ "python", "strings" ], "Title": "String Manipulation: Given two operations on a character 'A', Copy and Paste, find the minimum number of operations to produce a string of length 'N'" }
269038
<p>Find all subarrays from a given array in the least possible time complexity.</p> <p><strong>Requirement:</strong><br /> calculate the square of (sum of even-indexed elements) - (the sum of odd-indexed elements) of al the subarrays.</p> <p><strong>Explanation of above code:</strong><br /> I am iterating the array, and inserting all elements of the subarray in the innerList. Then, summing up all the even-indexed and odd-indexed elements separately. Subtracting the even and odd sum, and calculating its square.</p> <p><strong>What I am looking for:</strong><br /> Optimization for the code.</p> <p><strong>My Solution:</strong></p> <pre><code>public static void subarr2(int[] arr) { int N = arr.length; int set_size = (int) Math.pow(2, N); List&lt;List&lt;Integer&gt;&gt; list = new ArrayList&lt;&gt;(); List&lt;Integer&gt; innerList = null; int evnSum = 0, oddSum = 0, finalSum = 0; Set&lt;Integer&gt; sums = new TreeSet&lt;&gt;(Comparator.reverseOrder()); for (int i = 1; i &lt; set_size; i++) { innerList = new ArrayList&lt;&gt;(); for (int j = 0; j &lt; N - 1; j++) { int temp = (int) (1 &lt;&lt; j); if ((i &amp; temp) &gt; 0) { innerList.add(arr[j]); } } innerList.add(arr[N - 1]); if (innerList.size() &gt; 1) { list.add(innerList); evnSum = oddSum = 0; for (int m = 0; m &lt; innerList.size(); m++) { if (m % 2 == 0) evnSum += innerList.get(m); else oddSum += innerList.get(m); } System.out.println(&quot;evnsum=&quot; + evnSum + &quot; subarr=&quot; + innerList); finalSum = Math.subtractExact(evnSum, oddSum); sums.add((int) Math.pow(finalSum, 2)); } } System.out.println(&quot;Output=&quot; + sums.stream().findFirst().get()); } </code></pre> <p>I want to know, if this code can be further optimized? or made more full proof to cover any corner-case scenarios?</p> <p>Some of the test cases failed saying &quot;Time limit exceeded &gt; 4s&quot;.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T21:06:57.903", "Id": "530727", "Score": "0", "body": "Welcome to Stack Review, I understand how you find the subarrays of one array like the title of your question, but I don't understand the part about sum of even and odd elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T05:10:10.977", "Id": "530745", "Score": "0", "body": "I have updated the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T06:39:32.493", "Id": "530747", "Score": "1", "body": "This doesn't help. Is that an explanation of the code or the correction to the task?\nIf you have the task to find subarrays - you can throw out that even/odd sum part, the code will be much more efficient.\nIf you have the task of \"iterating the array, and inserting all elements of the subarray in the innerList. Then, summing up all the even-indexed and odd-indexed elements separately. Subtracting the even and odd sum, and calculating its square\" - then you're doing exactly what is said, no optimization possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T07:35:37.097", "Id": "530749", "Score": "1", "body": "Have added required clarifications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T07:58:49.627", "Id": "530750", "Score": "4", "body": "It is helpful and customary to put the introduction first: [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) If this is a 3rd party programming challenge, please hyperlink and [tag](https://codereview.stackexchange.com/tags) accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:16:10.797", "Id": "533394", "Score": "0", "body": "The problem statement urgently needs improvement, starting with *square (evenSum - oddSum)* vs. *(square evenSum) - oddSum*. The code prints something entirely different, and using an element stream of an ordered set to find a maximum is far out." } ]
[ { "body": "<h3>Naming</h3>\n<p>Using consistent variable naming with full words usually is considered a good habit. Well, in a small part of the code like this using <code>evnSum</code> instead of <code>evenSum</code> can be justified by length of <code>oddSum</code>; but <code>subarr2</code>, <code>set_size</code> and <code>oddSum</code> shouldn't be used together. If you want to keep names, spell them as <code>subArr2</code> (I hope you have subArr1 somewhere to justify it) and <code>setSize</code>. <code>m</code> is not a good name for a variable, too.</p>\n<h3>Overflowing</h3>\n<p><code>finalSum = Math.subtractExact(evnSum, oddSum);</code> is not the only place where it can occur. If you care about overflowing - use other functions like <code>Math.addExact</code> all over.</p>\n<h3>Algorithm</h3>\n<p>You have <span class=\"math-container\">\\$O(n*2^n)\\$</span> complexity (if you don't care about memory management), and I'm afraid this is the best you can do with this task.</p>\n<h3>Small optimizations</h3>\n<p>But still, you can do fewer operations in every loop. It doesn't look like you're using variable <code>list</code> anywhere - you're just copying data into it. So you can get rid of it with all data copy operations.</p>\n<p>Next, what with <code>innerList</code>? First, you're filling it with data. Next, you're looping over it. You can combine two loops into one and cast <code>innerList</code> out:</p>\n<pre><code>evnSum = oddSum = m = 0;\nfor (int j = 0; j &lt; N - 1; j++, m++) {\n int temp = (int) (1 &lt;&lt; j);\n if ((i &amp; temp) &gt; 0) {\n if(m%2==0)\n evnSum += arr[j];\n else\n oddSum += arr[j]\n }\n}\n</code></pre>\n<p>But, of course, you'll be unable to output evnSum before the whole innerList this way. If you need it - make <code>innerList</code> the simple array of size N and output just the part you're working on, up to <code>m</code>. You'll avoid memory allocation/deallocation this way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:19:23.620", "Id": "533403", "Score": "1", "body": "You increment `j` and `m` (declare in same place as `j`!) in lockstep - they will stay the same. I think the intention was to have `m` represent the *index in the current subarray*: just increment it \"in the `if`\". Just use *one* `sum`, conditionally adding to and subtracting from it. Or try to find a \"branch free\" variant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T15:44:58.287", "Id": "533430", "Score": "0", "body": "I was trying to transform Adil's code keeping it close to the original." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T15:56:50.610", "Id": "533432", "Score": "0", "body": "(`trying to [keep the code] close to the original` fair enough; but as is, `m` is *not* the index in the sub-array/\"conceptual inner List\".)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:06:18.203", "Id": "269091", "ParentId": "269044", "Score": "1" } }, { "body": "<p><code>int set_size = (int) Math.pow(2, N);</code> is bound to result in zero for <code>arr</code> longer than <code>Integer.size</code>. (You use <code>1 &lt;&lt; j</code> later on: why switch?)</p>\n<p><code>inserting all elements of the subarray in the innerList</code><br />\nis in dire need of explanation: &quot;the subarray&quot; is specified by (bits set in) <code>i</code>.</p>\n<p>You posted an <a href=\"https://xyproblem.info\" rel=\"nofollow noreferrer\">XY-problem</a>:<br />\nThe &quot;real&quot; problem seems to be to print the maximum square of the difference between the totals of even- and odd-indexed elements among all subarrays of a given array - smells <em>dynamic programming</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:27:52.680", "Id": "270192", "ParentId": "269044", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T19:35:34.160", "Id": "269044", "Score": "0", "Tags": [ "java", "performance", "algorithm", "array" ], "Title": "Calculate square of (sum of even-indexed) - (sum of odd-indexed) subarrays from an array" }
269044
<p>this is my first real website I created after learning about web development. It's amazing to me that anyone would spare their free time to code review strangers' code. So thank you in advance. I'd like a general feedback and especially on the caching I implemented. The full Code (with ejs templates and media etc) is on <a href="https://github.com/Paulemeister/WebBlog" rel="nofollow noreferrer">Github</a>. I wrote this half a year ago and just added some more comments so, just ignore the stupid stuff :D. Here's the server code:</p> <pre class="lang-javascript prettyprint-override"><code>const ejs = require(&quot;ejs&quot;); // not needed const marked = require(&quot;marked&quot;); const path = require(&quot;path&quot;); const fs = require(&quot;fs&quot;); const db = require(&quot;./mariadb.js&quot;); const config = require(&quot;./config.js&quot;); const express = require('express'); const app = express(); // used to be BodyParser.url... now deprecated app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use(express.static('public')) app.set(&quot;view engine&quot;,&quot;ejs&quot;); app.set('view cache', false); app.set('views', path.join(__dirname, '/sites')); app.use(&quot;*&quot;,(req, res, next) =&gt; { console.log(&quot;-----------------------------&quot;); console.log(&quot;Request:&quot;); console.log(&quot;\tMethod: &quot; +req.method); console.log(&quot;\tOriginal URL:&quot;+req.originalUrl); console.log(&quot;\tBase URL:&quot;+req.baseUrl); console.log(&quot;-----------------------------&quot;); next(); }); app.use((error,req, res, next) =&gt; { console.log(error.message) res.status(error.code || 500); res.send(&quot;404 - File Not Found :(&quot;); }); app.get(&quot;/&quot;, (req,res) =&gt; { if (fs.existsSync(&quot;cache/index.html&quot;)){ fs.readFileSync(&quot;cache/index.html&quot;,(err,data) =&gt; { if (!err){ res.send(data.toString()); return; } }) } res.render(&quot;index&quot;,{&quot;cache&quot;: true}, (err,html) =&gt; { if (err){ throw err;} res.send(html) fs.mkdirSync(&quot;cache&quot;,{recursive: true}); fs.writeFileSync(&quot;cache/index.html&quot;,html,(err) =&gt; { if (err){ console.log(err.message) } }) }); }) app.get(&quot;/blog/:article&quot;, (req,res) =&gt; { // serve cached page if possible if (fs.existsSync(&quot;cache&quot;+req.baseUrl+req.path+&quot;.html&quot;)){ fs.readFileSync(&quot;cache&quot;+req.baseUrl+req.path+&quot;.html&quot;,(err,data) =&gt; { if (!err){ res.send(data.toString()); return; } }) } // check db for wanted entry db.pool.query(&quot;select * from BlogEntries where url=(?);&quot;,[req.params.article],(err,rows,meta) =&gt; { if (err ){ //|(rows.length != 2) console.log(err.message | &quot;Weird Amount of Entries from DB&quot; ) ; } console.log(rows[0].heading); // render blogEntry template with queried data res.render(&quot;blogEntry&quot;,{heading: rows[0].heading, bloghtml: marked(rows[0].content)}, (err,html) =&gt; { if (err){ console.log(err.message); res.end() return } // send rendered page res.send(html) // save rendered page to cache fs.mkdirSync(path.dirname(&quot;cache&quot;+req.baseUrl+req.path),{recursive: true}); fs.writeFileSync(&quot;cache&quot;+req.baseUrl+req.path+&quot;.html&quot;,html,(err) =&gt; { if (err){ console.log(err.message) } }) }); }); }) app.get(&quot;/blog&quot;, (req,res) =&gt; { // would serve cached blogoverview, but as it's dependent on the amount on the blogentries it changes too much to be usefull // also: how to find if changed? // deleting cached on render of blog page not viable /* if (fs.existsSync(&quot;cache/blog.html&quot;)){ fs.readFileSync(&quot;cache/blog.html&quot;,(err,data) =&gt; { if (!err){ res.send(data.toString()); return; } }) } */ db.pool.query(&quot;select url,heading,substring(content,1,200) as description from BlogEntries;&quot;,(err,rows,meta) =&gt; { if (err ){ console.log(err.message ) ; } blogEntries = rows; for (let i=0; i&lt; rows.length;i++){ blogEntries[i].description = marked(rows[i].description) } console.log(rows[0].heading); res.render(&quot;blog&quot;,{blogEntries: blogEntries}, (err,html) =&gt; { if (err){ console.log(err.message); res.end() return } res.send(html) // would save blog overwiev to cache /* fs.mkdirSync(path.dirname(&quot;cache&quot;+req.baseUrl+req.path),{recursive: true}); fs.writeFileSync(&quot;cache&quot;+req.baseUrl+req.path+&quot;.html&quot;,html,(err) =&gt; { if (err){ console.log(err.message) } })*/ }); }); }) app.get(&quot;/*&quot;, (req,res) =&gt; { if (fs.existsSync(&quot;cache&quot;+req.baseUrl+req.path+&quot;.html&quot;)){ fs.readFileSync(&quot;cache&quot;+req.baseUrl+req.path+&quot;.html&quot;,(err,data) =&gt; { if (!err){ res.send(data.toString()); return; } console.log(err.message) }) } res.render((req.baseUrl+req.path).substr(1),{&quot;cache&quot;: true}, (err,html) =&gt; { if (err){ throw err;} res.send(html) fs.mkdirSync(path.dirname(&quot;cache&quot;+req.baseUrl+req.path),{recursive: true}); fs.writeFileSync(&quot;cache&quot;+req.baseUrl+req.path+&quot;.html&quot;,html,(err) =&gt; { if (err){ console.log(err.message) } }) }); }) // put data from /new form into db app.post(&quot;/*&quot;, (req,res) =&gt;{ let url = req.body.heading.replace(/[;/?:@&amp;=+$, ]/g ,&quot;-&quot;) db.pool.query(&quot;insert into BlogEntries (heading,url,content) values ((?),(?),(?));&quot;,[req.body.heading,url,req.body.content]); res.status(301).redirect(&quot;/new&quot;) }) // no idea what this does app.use((error,req, res, next) =&gt; { console.log(error.message) res.status(error.code || 500); res.send(&quot;404 - File Not Found :(&quot;); }); // starting the server app.listen(8080, () =&gt; console.log(&quot;Started Server on Port &quot;+config.port)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T09:52:46.650", "Id": "530754", "Score": "0", "body": "Welcome to Code Review@SE. Time allowing, (re?)visit [How to get the best value out of Code Review](https://codereview.meta.stackexchange.com/q/2436)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T21:17:43.823", "Id": "269047", "Score": "2", "Tags": [ "html", "css", "node.js", "express.js", "markdown" ], "Title": "Simple Markdown Blog" }
269047
<p>I've seen <a href="https://codereview.stackexchange.com/questions/257344/using-asyncio-and-aiohttp-in-classes">Using asyncio and aiohttp in classes</a> but could not really figure out how to apply this to my own code.</p> <p>The main idea of this code is to inherit from this RESTClient class whenever I build a new API Client. I'll probably improve on this code later to add functions to run multiple requests asynchronously.</p> <p>While creating this bit of code, I ran into a few problems with the asyncio loop that, to be honest, I know very little about. This might not be the most pythonistic way, please provide your feedback.</p> <p>I've posted this code to validate with the Python community if the way I'm handling the ClientSession in this example is <em>the right way</em>.</p> <pre class="lang-py prettyprint-override"><code>import asyncio import aiohttp import json from dataclasses import dataclass @dataclass class Config: verify_ssl: bool = True tcp_connections: int = 5 class RestClient: def __init__(self, config: Config = None) -&gt; None: if not config: self.config = Config() else: assert isinstance(config, Config) self.config = config try: loop = asyncio.new_event_loop() loop.run(self._create_session()) except: loop = asyncio.get_event_loop() loop.run_until_complete(self._create_session()) def __del__(self): try: loop = asyncio.new_event_loop() loop.run_until_complete(self._close_session()) except: loop = asyncio.get_event_loop() loop.run_until_complete(self._close_session()) async def _create_session(self): self.con = aiohttp.TCPConnector(ssl=self.config.verify_ssl) self.session = aiohttp.ClientSession(connector=self.con) async def _close_session(self): await self.session.close() await self.con.close() def request( self, method: str, url: str, query_param: dict = None, headers: dict = None, body: json = None, ): &quot;&quot;&quot;Performs an Async HTTP request. Args: method (str): request method ('GET', 'POST', 'PUT', 'DELETE'). url (str): request url. query_param (dict or None): url query parameters. header (dict or None): request headers. body (json or None): request body in case of method POST or PUT. &quot;&quot;&quot; loop = asyncio.get_event_loop() return loop.run_until_complete( self.async_request( method=method, url=url, query_param=query_param, headers=headers, body=body, ) ) async def async_request( self, method: str, url: str, query_param: dict = None, headers: dict = None, body: json = None, ): &quot;&quot;&quot;Performs an Async HTTP request. Args: method (str): request method ('GET', 'POST', 'PUT', 'DELETE'). url (str): request url. query_param (dict or None): url query parameters. header (dict or None): request headers. body (json or None): request body in case of method POST or PUT. &quot;&quot;&quot; assert isinstance(method, str) assert isinstance(url, str) method = method.upper() assert method in (&quot;GET&quot;,) # TODO: Add (&quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;) headers = headers or {} try: if method == &quot;GET&quot;: async with self.session.get( url, params=query_param, headers=headers ) as response: return await response.text() except: raise if __name__ == &quot;__main__&quot;: client = RestClient() print(client.request(method=&quot;GET&quot;, url=&quot;https://httpbin.org/get&quot;)) </code></pre>
[]
[ { "body": "<blockquote>\n<p>While creating this bit of code, I ran into a few problems with the asyncio loop that, to be honest, I know very little about.</p>\n</blockquote>\n<p>You are using <code>asyncio</code> very inappropriately.\nYou need to pick one either <code>RestClient</code> is synchronous or asynchronous.\nSince you're using asynchronous libraries you have to make the class asynchronous.\nTherefore most methods <em>have</em> to be <code>async</code> methods, and you cannot call <code>asyncio.run</code> at all in the class.</p>\n<p>Additionally your class should be an <a href=\"https://docs.python.org/3/reference/datamodel.html#asynchronous-context-managers\" rel=\"nofollow noreferrer\">asynchronous context manager</a> by changing <code>_create_session</code> to <code>__aenter__</code> and <code>_close_session</code> to <code>__aexit__</code>.</p>\n<p>This makes your code significantly simpler:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import asyncio\nimport aiohttp\nimport json\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Config:\n verify_ssl: bool = True\n tcp_connections: int = 5\n\n\nclass RestClient:\n def __init__(self, config: Config = None) -&gt; None:\n self.config = Config() if config is none else config\n assert isinstance(self.config, Config)\n\n async def __enter__(self):\n self.con = aiohttp.TCPConnector(ssl=self.config.verify_ssl)\n self.session = aiohttp.ClientSession(connector=self.con)\n\n async def __exit__(self, *args):\n await self.session.close()\n await self.con.close()\n\n async def request(\n self,\n method: str,\n url: str,\n query_param: dict = None,\n headers: dict = None,\n body: json = None,\n ):\n &quot;&quot;&quot;Performs an Async HTTP request.\n\n Args:\n method (str): request method ('GET', 'POST', 'PUT', ).\n url (str): request url.\n query_param (dict or None): url query parameters.\n header (dict or None): request headers.\n body (json or None): request body in case of method POST or PUT.\n &quot;&quot;&quot;\n assert isinstance(method, str)\n assert isinstance(url, str)\n\n method = method.upper()\n assert method in (&quot;GET&quot;,) # TODO: Add (&quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;)\n\n headers = headers or {}\n\n try:\n if method == &quot;GET&quot;:\n async with self.session.get(\n url, params=query_param, headers=headers\n ) as response:\n return await response.text()\n except:\n raise\n\n\nasync def main():\n async with RestClient() as client:\n print(await client.request(method=&quot;GET&quot;, url=&quot;https://httpbin.org/get&quot;))\n\n\nif __name__ == &quot;__main__&quot;:\n asyncio.run(main())\n</code></pre>\n<p>You can make a synchronous -&gt; asynchronous class to build on-top of <code>RestClient</code> but it's generally not a good idea.\nIf you don't want to have all your code be asynchronous then you shouldn't use async.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T11:29:12.337", "Id": "530910", "Score": "0", "body": "I see how my use of the asyncio was inappropriate. I've copied you code but am getting an error when I run it `AttributeError: __aexit__`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:04:41.327", "Id": "530930", "Score": "0", "body": "@NielsPerfors Sorry yes, I'm so used to writing synchronous context managers that muscle memory won over what I intended to write! I'm happy you figured out how to get the code working on your own." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T16:46:30.007", "Id": "269075", "ParentId": "269049", "Score": "1" } }, { "body": "<p>I've updated the code according to the feedback from @Peilonrayz (thanks!)</p>\n<p><strong>rest.py</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>import asyncio\nimport aiohttp\nimport json\n\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Config:\n verify_ssl: bool = True\n tcp_connections: int = 5\n\n\nclass RestClient:\n &quot;&quot;&quot;A generic HTTP Rest client.&quot;&quot;&quot;\n\n def __init__(self, config: Config = None) -&gt; None:\n self.config = Config() if config is None else config\n assert isinstance(self.config, Config)\n\n async def __aenter__(self):\n self._con = aiohttp.TCPConnector(\n verify_ssl=self.config.verify_ssl, limit=self.config.tcp_connections\n )\n self._session = aiohttp.ClientSession(connector=self._con)\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n await self._session.close()\n await self._con.close()\n\n async def request(\n self,\n method: str,\n url: str,\n query_param: dict = None,\n headers: dict = None,\n body: json = None,\n ):\n &quot;&quot;&quot;Performs an Async HTTP request.\n\n Args:\n method (str): request method ('GET', 'POST', 'PUT', ).\n url (str): request url.\n query_param (dict or None): url query parameters.\n header (dict or None): request headers.\n body (json or None): request body in case of method POST or PUT.\n &quot;&quot;&quot;\n assert isinstance(method, str)\n assert isinstance(url, str)\n\n method = method.upper()\n assert method in (&quot;GET&quot;,) # TODO: Add (&quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;)\n\n headers = headers or {}\n\n try:\n if method == &quot;GET&quot;:\n async with self._session.get(\n url, params=query_param, headers=headers\n ) as response:\n return await response.text()\n except:\n raise\n # TODO: Handle exceptions explicitly\n\n\nasync def main():\n async with RestClient() as client:\n print(await client.request(method=&quot;GET&quot;, url=&quot;https://httpbin.org/get&quot;))\n\n\nif __name__ == &quot;__main__&quot;:\n loop = asyncio.get_event_loop() #asyncio.run(main()) throws an error on windows.\n loop.run_until_complete(main())\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T16:28:40.223", "Id": "530945", "Score": "2", "body": "Rather than adding an answer, you can create a follow up question with a link to this question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:01:51.633", "Id": "269136", "ParentId": "269049", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T22:23:54.183", "Id": "269049", "Score": "0", "Tags": [ "python", "api", "rest", "asyncio" ], "Title": "Python RESTClient Class with asyncio and aiohttp" }
269049
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/268829/231235">Calculate distances between two multi-dimensional arrays in Matlab</a>. Given a set S<sub>X</sub></p> <p><span class="math-container">$$ S_{X} = \{ { X_{1}, X_{2}, X_{3}, \dots, X_{n} } \} $$</span></p> <p>where n is the count of elements in set S<sub>X</sub> (the cardinality of set S<sub>X</sub>)</p> <p>There are <span class="math-container">$${{ n }\choose{2}}$$</span> element-wise distances in set S<sub>X</sub>.</p> <p>The mean and variance of these element-wise distances can be calculated with <code>AverageIntraEuclideanDistancesPar</code> and <code>VarIntraEuclideanDistancesPar</code> functions.</p> <p><strong>Example</strong></p> <pre><code>%% Preparing data DataCount = 10; sizex = 8; sizey = 8; sizez = 8; Collection = ones(sizex, sizey, sizez, DataCount); for i = 1:DataCount Collection(:, :, :, i) = ones(sizex, sizey, sizez) .* i; end %% Function testing AIED = AverageIntraEuclideanDistancesPar(Collection) VIED = VarIntraEuclideanDistancesPar(Collection) </code></pre> <p>The output result of example above:</p> <pre><code>AIED = 82.9672 VIED = 4.0328e+03 </code></pre> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>AverageIntraEuclideanDistancesPar</code> function</p> <pre><code>function [output] = AverageIntraEuclideanDistancesPar(X1) D = 0; for i = 1:size(X1, 4) element1 = X1(:, :, :, i); parfor j = i:size(X1, 4) element2 = X1(:, :, :, j); D = D + EuclideanDistance(element1, element2); end end k = 2; NormalizationFactor = (1 / nchoosek(size(X1, 4), k)); output = NormalizationFactor * D; end </code></pre> </li> <li><p><code>VarIntraEuclideanDistancesPar</code> function</p> <pre><code>function [output] = VarIntraEuclideanDistancesPar(X1) Avg = AverageIntraEuclideanDistancesPar(X1); D = 0; for i = 1:size(X1, 4) element1 = X1(:, :, :, i); for j = i:size(X1, 4) element2 = X1(:, :, :, j); D = D + (EuclideanDistance(element1, element2) - Avg)^2; end end k = 2; NormalizationFactor = ( 1 / nchoosek(size(X1, 4), k)); output = NormalizationFactor * D; end </code></pre> </li> <li><p><code>EuclideanDistance</code> function</p> <pre><code>function [output] = EuclideanDistance(X1, X2) %EUCLIDEANDISTANCE Calculate Euclidean distance between two inputs if ~isequal(size(X1), size(X2)) error('Sizes of inputs are not equal!') end output = sqrt(SquaredEuclideanDistance(X1, X2)); end </code></pre> </li> </ul> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/268829/231235">Calculate distances between two multi-dimensional arrays in Matlab</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am trying to implement <code>AverageIntraEuclideanDistancesPar</code> and <code>VarIntraEuclideanDistancesPar</code> functions in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>My only comment here is that</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>AIED = AverageIntraEuclideanDistancesPar(Collection)\nVIED = VarIntraEuclideanDistancesPar(Collection)\n</code></pre>\n<p>computes the average twice, since <code>VarIntraEuclideanDistancesPar</code> also calls <code>AverageIntraEuclideanDistancesPar</code>. I would suggest writing a function that returns both the average and the variance.</p>\n<p>That said, your way of computing variance is precise, but expensive because it computes the distances twice, first to determine the mean, and then again to determine the variance. I suggest you read <a href=\"https://en.m.wikipedia.org/wiki/Algorithms_for_calculating_variance\" rel=\"nofollow noreferrer\">this Wikipedia article on computing variance</a>. Depending on the properties of the input, either the naive algorithm or Welford’s could be used.</p>\n<p>Three more details:</p>\n<ul>\n<li><code>VarIntraEuclideanDistancesPar</code> had “par” in the name, but doesn’t actually do its computation in parallel.</li>\n<li><code>parfor</code> should ideally be the outer loop, not the inner one. Starting up a parallel computation had overhead, you want to limit this overhead as much as possible.</li>\n<li>Reshaping the arrays to be 2D would make your indexing operations simpler and easier to read. Reshaping is an essentially free operation.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T15:02:44.853", "Id": "269067", "ParentId": "269052", "Score": "1" } } ]
{ "AcceptedAnswerId": "269067", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T00:00:47.377", "Id": "269052", "Score": "1", "Tags": [ "array", "multithreading", "matlab" ], "Title": "Mean and variance of element-wise distances in a set of multi-dimensional arrays in Matlab" }
269052
<p>I wrote the following Bash scripts to make pull-mode backups with <a href="https://restic.net/" rel="nofollow noreferrer">restic</a>, a backup solution written in Golang, similar to Borg Backup. The main use case for this script is pulling backups into a central backup server that you trust, especially if you don't want to create a shell account or sftp user for every machine you backup, while still using a tool like restic on your own infrastructure.</p> <p>This script is mostly just a wrapper for restic to talk to <a href="https://github.com/restic/rest-server" rel="nofollow noreferrer">rest-server</a> over SSH, using port forwarding. Rest-server allows for enforcing append-only mode, so clients shouldn't be able to delete their past backups.</p> <p>The main developer of restic is interested in, or at least considering, making restic support pull-mode without rest-server. If that is released at some point, then it would probably make more sense to use restic directly, rather than this script.</p> <p>A coworker with more BASH experience than me reviewed the codebase, and I merged in most of those patches, with some changes.</p> <p>My main concern regarding this code is security, and was wondering if there are any ways I could improve it. One weakness is that restic's encryption password has to be stored somewhere, and so I store it in plain text on the backup server, with the expectation that the backups are encrypted by a LUKS partition and a password.</p> <p>restic also uses its encryption password to verify backups, so I don't know if that complicates the security of this script. More details about my design choices are in the readme of the <a href="https://github.com/leaf-node/kaya" rel="nofollow noreferrer">source code repository</a>.</p> <p>I'm interested in hearing your thoughts. Thanks! : )</p> <p><code>kaya</code>:</p> <pre class="lang-bsh prettyprint-override"><code>#! /bin/bash # This file is part of Kaya. # # Kaya is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Kaya is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Kaya. If not, see &lt;https://www.gnu.org/licenses/&gt;. # # Copyright 2021 Andrew Engelbrecht # if ! test &quot;$BASH_VERSION&quot;; then echo &quot;error: shell is not bash&quot; &gt;&amp;2; exit 1; fi shopt -s inherit_errexit 2&gt;/dev/null ||: # ignore fail in bash &lt; 4.4 set -eE -o pipefail trap 'echo &quot;$0:$LINENO:error: \&quot;$BASH_COMMAND\&quot; exit status: $?, PIPESTATUS: ${PIPESTATUS[*]}&quot; &gt;&amp;2' ERR # first stable version of API between kaya and kaya-client kaya_protocol_version=1 kaya-usage() { cat &lt;&lt; EOF &gt;&amp;2 kaya usage: kaya [-c CONFIG_PATH] [-u REMOTE_USER] HOST_TO_BACKUP backup -- RESTIC_ARGS REMOTE_USER Default is root CONFIG_PATH Default is /etc/kaya.conf HOST_TO_BACKUP For example www1.example.com RESTIC_ARGS See possible args by running &quot;restic backup --help&quot; EOF exit &quot;$1&quot; } set-defaults() { global_conf=&quot;/etc/kaya.conf&quot; remote_user=&quot;root&quot; } get-params() { local -a positional local key while (( $# )); do key=&quot;$1&quot; case $key in -c|--conf) global_conf=&quot;$2&quot; shift 2 ;; -u|--user) remote_user=&quot;$2&quot; shift 2 ;; --) shift backup_options=(&quot;$@&quot;) break ;; -*) echo &quot;kaya: error: unrecognized argument: $key&quot; &gt;&amp;2 kaya-usage 1 ;; *) positional+=(&quot;$key&quot;) shift ;; esac done set -- &quot;${positional[@]}&quot; hostname=&quot;$1&quot; action=&quot;$2&quot; if [[ -z $hostname ]]; then echo &quot;kaya: error: missing hostname argument&quot; &gt;&amp;2 kaya-usage 1 fi case $action in backup) # currently the only option is to backup ;; *) echo &quot;kaya: error: invalid action argument: $action&quot; &gt;&amp;2 kaya-usage 1 ;; esac } ## create restic backup repo, store the new password in plaintext create-backup-dir() { echo &quot;kaya: Creating backup directory...&quot; mkdir -p &quot;${backup_dir}&quot;; chmod 700 &quot;${backup_dir}&quot; touch &quot;${password_file}&quot;; chmod 600 &quot;${password_file}&quot;; pwgen 30 1 &gt; &quot;${password_file}&quot;; chmod 400 &quot;${password_file}&quot; RESTIC_PASSWORD=&quot;$(cat &quot;${password_file}&quot;)&quot; restic -r &quot;${backup_dir}&quot; init &gt; /dev/null } # check / create the hashed password in .htpasswd update-htpasswd-file() { if [[ ! -e $htpasswd_file ]] ; then touch &quot;${htpasswd_file}&quot; fi chmod 600 &quot;${htpasswd_file}&quot; # check to see if the password is already there and correct # otherwise, update it if ! grep -q &quot;^${hostname}&quot; &quot;${htpasswd_file}&quot; || ! htpasswd -i -v &quot;${htpasswd_file}&quot; &quot;${hostname}&quot; &lt; &quot;${password_file}&quot; &amp;&gt; /dev/null ; then flock -w 10 &quot;${htpasswd_file}.flock&quot; -c &quot;htpasswd -i -B '${htpasswd_file}' '${hostname}'&quot; &lt; &quot;${password_file}&quot; \ |&amp; { grep -E -v &quot;(Adding|Updating) password for user&quot; &gt;&amp;2 ||:; } echo &quot;kaya: Waiting for rest-server to reload .htpasswd... (mostly for new backups)&quot; sleep 32 fi } start-backup() { echo &quot;kaya: Starting backup of ${hostname}&quot; echo local password password=&quot;$(head -n1 &quot;${password_file}&quot;)&quot; # make the backup over a forwarded port cat &lt;&lt; EOF | ssh -R &quot;${remote_port}:localhost:${local_port}&quot; &quot;${remote_user}@${hostname}&quot; kaya-client \ &quot;${remote_port@Q}&quot; &quot;${hostname@Q}&quot; &quot;${backup_options[@]@Q}&quot; ${kaya_protocol_version} ${password} EOF } main() { local program local missing_prog missing_prog=false for program in flock pwgen; do if ! type -p $program &amp;&gt;/dev/null; then echo &quot;kaya: error: install $program (package $program on debian based systems)&quot; &gt;&amp;2 fi done if ! type -p htpasswd &amp;&gt;/dev/null; then echo &quot;kaya: error: install htpasswd (package apache2-utils on debian based systems)&quot; &gt;&amp;2 fi if $missing_prog; then exit 1 fi set-defaults get-params &quot;$@&quot; # shellcheck source=/etc/kaya.conf source &quot;${global_conf}&quot; if [[ -z $local_port ]]; then local_port=8000 fi backup_dir=&quot;${backuproot}/${hostname}&quot; password_file=&quot;${backup_dir}/repo-password-keep&quot; htpasswd_file=&quot;${backuproot}/.htpasswd&quot; if [[ ! -d $backup_dir ]]; then create-backup-dir fi if [[ ! -e $password_file ]]; then echo &quot;kaya: error: the repo password file is missing:&quot; &gt;&amp;2 echo &quot;${password_file}&quot; &gt;&amp;2 exit 1 fi update-htpasswd-file if [[ $action == backup ]]; then start-backup fi } main &quot;$@&quot; </code></pre> <p><code>kaya-client</code>:</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash # This file is part of Kaya. # # Kaya is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Kaya is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Kaya. If not, see &lt;https://www.gnu.org/licenses/&gt;. # # Copyright 2021 Andrew Engelbrecht # if ! test &quot;$BASH_VERSION&quot;; then echo &quot;error: shell is not bash&quot; &gt;&amp;2; exit 1; fi shopt -s inherit_errexit 2&gt;/dev/null ||: # ignore fail in bash &lt; 4.4 set -eE -o pipefail trap 'echo &quot;$0:$LINENO:error: \&quot;$BASH_COMMAND\&quot; exit status: $?, PIPESTATUS: ${PIPESTATUS[*]}&quot; &gt;&amp;2' ERR read -r kaya_protocol_version if [[ $kaya_protocol_version != 1 ]] ; then echo &quot;kaya-client: error: mismatched protocol version with kaya&quot; &gt;&amp;2 echo &quot;kaya-client: error: kaya protocol version: ${kaya_protocol_version} kaya-client protocol version: 1&quot; &gt;&amp;2 exit 1 fi read -r password port=&quot;$1&quot; hostname=&quot;$2&quot; shift 2 username=&quot;${hostname}&quot; backupdir=&quot;${hostname}&quot; export RESTIC_REPOSITORY=&quot;rest:http://${username}:${password}@localhost:${port}/${backupdir}/&quot; export RESTIC_PASSWORD=&quot;${password}&quot; cmd=( restic backup &quot;$@&quot;) ret=0 &quot;${cmd[@]}&quot; || ret=$? if (( ret )); then echo &quot;kaya-client: command exit code $ret: ${cmd[*]}&quot; &gt;&amp;2 exit $ret fi </code></pre> <p><code>kaya.conf</code>:</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash # # Config file for Kaya, a restic backup wrapper # # This will be sourced by bash backuproot=/srv/backups/kaya # set if using non-default port as in 'rest-server --listen :PORT' # local_port=8000 remote_port=8777 # some aribtrary port <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T01:36:07.353", "Id": "269055", "Score": "3", "Tags": [ "bash", "security", "encryption" ], "Title": "Bash script for pull-mode backups via restic's rest-server" }
269055
<p>I am making a UI library for the fun of it, and decided to use move semantics instead of pointers with new/delete.</p> <p>Everything is working, but I am not satisfied.</p> <p>Given this code:</p> <pre><code>void ControlGroup::AddControl(Control&amp;&amp; control) noexcept { if(control.tabstop) control.taborder = GetMaxTabOrder() + 1; control.SetParent(*parent_control); HWND hwnd = control.hwnd; control_map.emplace(control.hwnd, std::move(control)); Control* c = &amp;control_map.at(hwnd); tab_map.emplace(c-&gt;taborder, c); } </code></pre> <p>I would like advice for a better technique to add Control* c inside tab_map.</p> <p>Before going further - Are move semantics really worth the trouble?</p> <p>The complete related code follows:</p> <p><strong>Control.hpp</strong></p> <pre><code>#pragma once #include &quot;../class_macro.hpp&quot; #include &quot;Window.hpp&quot; #include &lt;cassert&gt; class ControlGroup; struct UserControlCreateInfo { SIZE client_size{}; int control_id{}; Window::Layout layout{}; POINT position{}; int taborder{}; bool tabstop{true}; LPCTSTR text{}; SIZE window_size{}; }; class Control : public Window { ControlGroup* control_group; friend ControlGroup; protected: int control_id; int taborder; bool tabstop; public: ENABLE_MOVE_CONSTRUCTOR(Control) struct ControlCreateInfo { LPCTSTR class_name{}; SIZE client_size{}; int control_id{}; DWORD ex_style{}; HWND hwnd_parent{}; Layout layout{}; POINT position{}; DWORD style{}; int taborder{}; bool tabstop{true}; LPCTSTR text{}; SIZE window_size{}; }; Control(const ControlCreateInfo&amp; cci) noexcept; protected: Control(const UserControlCreateInfo&amp; cci, LPCTSTR class_name, DWORD style = {}, DWORD ex_style = {}) noexcept; public: virtual ~Control() noexcept; virtual void SetFocus() noexcept; void AddChild(Control&amp;&amp; control) noexcept; virtual bool BeforeKeyDown(HWND hwnd, WPARAM wparam) noexcept override; private: void SetParent(const Window&amp; parent_window) noexcept; }; </code></pre> <p><strong>Control.cpp</strong></p> <pre><code>#include &quot;Control.hpp&quot; #include &quot;ControlGroup.hpp&quot; Control::Control(Control&amp;&amp; other) noexcept : Window{std::move(other)}, control_group{other.control_group}, control_id{other.control_id}, taborder{other.taborder}, tabstop{other.tabstop} { other.control_group = nullptr; } Control::Control(const ControlCreateInfo&amp; cci) noexcept : Window{{ .class_name = cci.class_name, .client_size = cci.client_size, .ex_style = cci.ex_style, .hwnd_parent = cci.hwnd_parent, .layout = cci.layout, .position = cci.position, .style = cci.style, .text = cci.text, .window_size = cci.window_size, }}, control_group{new ControlGroup(this)}, control_id{cci.control_id}, taborder{cci.taborder}, tabstop{cci.tabstop} {} Control::Control(const UserControlCreateInfo&amp; cci, LPCTSTR class_name, DWORD style, DWORD ex_style) noexcept : Window{{ .class_name = class_name, .client_size = cci.client_size, .ex_style = ex_style, .layout = cci.layout, .position = cci.position, .style = style, .text = cci.text, .window_size = cci.window_size, }}, control_group{new ControlGroup(this)}, control_id{cci.control_id}, taborder{cci.taborder}, tabstop{cci.tabstop} {} Control::~Control() noexcept { if(control_group) { delete control_group; control_group = nullptr; } } void Control::SetFocus() noexcept { ::SetFocus(hwnd); } void Control::AddChild(Control&amp;&amp; control) noexcept { control_group-&gt;AddControl(std::move(control)); } bool Control::BeforeKeyDown(HWND hwnd, WPARAM wparam) noexcept { switch(wparam) { case VK_TAB: { bool cycle_up = GetAsyncKeyState(VK_SHIFT); control_group-&gt;CycleTab(cycle_up); return true; } case VK_ESCAPE: Destroy(); return true; } return Window::BeforeKeyDown(hwnd, wparam); } void Control::SetParent(const Window&amp; parent_window) noexcept { SetWindowLongPtr(hwnd, GWL_STYLE, style | WS_CHILD); ::SetParent(hwnd, parent_window.GetHandle()); SetWindowPos(hwnd, 0, 0, 0, window_size.cx, window_size.cy, SWP_NOZORDER | SWP_NOMOVE); Show(); } </code></pre> <p><strong>ControlGroup.hpp</strong></p> <pre><code>#pragma once #include &quot;Control.hpp&quot; #include &lt;map&gt; class ControlGroup { const Control* parent_control; std::map&lt;HWND, Control&gt; control_map; std::multimap&lt;int, Control*&gt; tab_map; public: DISABLE_COPY_AND_MOVE(ControlGroup) ControlGroup(const Control* parent_control) noexcept; ~ControlGroup() noexcept; void AddControl(Control&amp;&amp; control) noexcept; void CycleTab(bool cycle_up) noexcept; private: int GetMaxTabOrder() const noexcept; Control* FindControlByHandle(HWND control) noexcept; Control* FindNextControlInTabOrder(Control* control, bool cycle_up) noexcept; void SetFocusToControl(Control* control) noexcept; void SetFocusToFirstControl() noexcept; }; </code></pre> <p><strong>ControlGroup.cpp</strong></p> <pre><code>#include &quot;ControlGroup.hpp&quot; ControlGroup::ControlGroup(const Control* parent_control) noexcept : parent_control{parent_control} {} ControlGroup::~ControlGroup() noexcept { parent_control = nullptr; } void ControlGroup::AddControl(Control&amp;&amp; control) noexcept { if(control.tabstop) control.taborder = GetMaxTabOrder() + 1; control.SetParent(*parent_control); HWND hwnd = control.hwnd; control_map.emplace(control.hwnd, std::move(control)); Control* c = &amp;control_map.at(hwnd); tab_map.emplace(c-&gt;taborder, c); } void ControlGroup::CycleTab(bool cycle_up) noexcept { HWND focus = GetFocus(); if(!focus) { SetFocusToFirstControl(); return; } auto control = FindControlByHandle(focus); if(!control) { SetFocusToFirstControl(); return; } control = FindNextControlInTabOrder(control, cycle_up); if(control) control-&gt;SetFocus(); } int ControlGroup::GetMaxTabOrder() const noexcept { auto it = tab_map.crbegin(); if(it != tab_map.crend()) return it-&gt;first; return 0; } Control* ControlGroup::FindControlByHandle(HWND control) noexcept { auto it = control_map.find(control); if(it == control_map.end()) return nullptr; return &amp;it-&gt;second; } Control* ControlGroup::FindNextControlInTabOrder(Control* control, bool cycle_up) noexcept { if(tab_map.size() == 1) return control; auto current = tab_map.find(control-&gt;taborder); if(current == tab_map.end()) return nullptr; if(cycle_up) { if(current == tab_map.begin()) return tab_map.rbegin()-&gt;second; return std::prev(current)-&gt;second; } auto next = std::next(current); if(next == tab_map.end()) return tab_map.begin()-&gt;second; return next-&gt;second; } void ControlGroup::SetFocusToControl(Control* control) noexcept { control-&gt;SetFocus(); } void ControlGroup::SetFocusToFirstControl() noexcept { const auto it = tab_map.cbegin(); if(it != tab_map.cend()) SetFocusToControl(it-&gt;second); } </code></pre> <p><strong>Window.hpp</strong></p> <pre><code>#pragma once #define WIN32_LEAN_AND_MEAN #include &lt;Windows.h&gt; #include &quot;../class_macro.hpp&quot; #include &quot;../tstring.hpp&quot; class Window { protected: HWND hwnd; SIZE window_size; DWORD style; bool active; public: DISABLE_COPY(Window) ENABLE_MOVE_CONSTRUCTOR(Window) static const DWORD DEFAULT_STYLE; enum class Layout { Custom, CenterParent, FillParent }; struct WindowCreateInfo { LPCTSTR class_name{}; SIZE client_size{}; DWORD ex_style{}; HMENU hwnd_menu{}; HWND hwnd_parent{}; Layout layout{}; POINT position{}; DWORD style{}; LPCTSTR text{}; SIZE window_size{}; }; Window(const WindowCreateInfo&amp; wci) noexcept; virtual ~Window() noexcept; virtual void Show() noexcept; virtual void Hide() noexcept; virtual bool MessageUpdate() noexcept; virtual bool MessageLoop() noexcept; virtual void Destroy() noexcept; virtual bool OnMouseClick(WPARAM wparam, int x, int y) noexcept; virtual bool BeforeKeyDown(HWND hwnd, WPARAM wparam) noexcept; virtual bool OnKeyDown(WPARAM wparam) noexcept; [[nodiscard]] bool IsDestroyed() const noexcept { return !active; } [[nodiscard]] virtual HWND GetHandle() const noexcept { return hwnd; } [[nodiscard]] virtual SIZE GetWindowSize() const noexcept; [[nodiscard]] virtual SIZE GetClientSize() const noexcept; [[nodiscard]] virtual tstring GetText() const noexcept; protected: virtual LRESULT WndProc(UINT msg, WPARAM wparam, LPARAM lparam) noexcept; private: static LRESULT CALLBACK WndProcStatic(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) noexcept; void PrepareWndClass(HINSTANCE hinstance, LPCTSTR class_name) const noexcept; void ProcessMessage(const MSG&amp; msg) noexcept; }; inline SIZE RectToSize(const RECT&amp; rect) noexcept; </code></pre> <p><strong>Window.cpp</strong></p> <pre><code>#include &quot;Window.hpp&quot; #include &lt;cassert&gt; constexpr LONG DEFAULT_WIDTH = 384; constexpr SIZE GetDefaultSize(const int size) { return {size, LONG(size / (16 / 9.0))}; } static LPCTSTR DEFAULT_CLASS_NAME = TEXT(&quot;ShigotoShoujinWndClass&quot;); const DWORD Window::DEFAULT_STYLE = WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX; static SIZE GetParentSize(HWND hwnd_parent) noexcept; static SIZE AdjustWindowSize(SIZE client_size, DWORD style, DWORD ex_style) noexcept; static POINT CenterWindow(SIZE parent_size, SIZE window_size) noexcept; Window::Window(Window&amp;&amp; other) noexcept : hwnd{other.hwnd}, window_size{other.window_size}, style{other.style}, active{other.active} { other.hwnd = {}; other.active = false; } Window::Window(const WindowCreateInfo&amp; wci) noexcept { HINSTANCE hinstance = GetModuleHandle(NULL); POINT position = wci.position; LPCTSTR class_name = wci.class_name ? wci.class_name : DEFAULT_CLASS_NAME; style = wci.style; window_size = wci.window_size; bool is_child = wci.style &amp; WS_CHILD; assert((is_child &amp;&amp; wci.hwnd_parent) || (!is_child &amp;&amp; !wci.hwnd_parent)); if(!style &amp;&amp; !wci.class_name) style = DEFAULT_STYLE; if(wci.hwnd_parent != HWND_DESKTOP) style |= WS_CHILD; PrepareWndClass(hinstance, class_name); switch(wci.layout) { case Layout::Custom: case Layout::CenterParent: if(wci.client_size.cx &amp;&amp; wci.client_size.cy) window_size = AdjustWindowSize(wci.client_size, style, wci.ex_style); else if(!window_size.cx || !window_size.cy) window_size = GetDefaultSize(DEFAULT_WIDTH); if(wci.layout == Layout::CenterParent) position = CenterWindow(GetParentSize(wci.hwnd_parent), window_size); break; case Layout::FillParent: if(!wci.style &amp;&amp; wci.hwnd_parent == HWND_DESKTOP) style = WS_POPUP; position = {}; window_size = GetParentSize(wci.hwnd_parent); } hwnd = CreateWindowEx(wci.ex_style, class_name, wci.text, style, position.x, position.y, window_size.cx, window_size.cy, wci.hwnd_parent, wci.hwnd_menu, hinstance, NULL); assert(hwnd); active = true; SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)(this)); } Window::~Window() noexcept { Destroy(); } void Window::Show() noexcept { assert(active); ShowWindow(hwnd, SW_SHOW); } void Window::Hide() noexcept { assert(active); ShowWindow(hwnd, SW_HIDE); } bool Window::MessageUpdate() noexcept { assert(active); MSG msg; while(active &amp;&amp; PeekMessage(&amp;msg, hwnd, 0, 0, PM_REMOVE)) ProcessMessage(msg); return active; } bool Window::MessageLoop() noexcept { assert(active); MSG msg; while(active &amp;&amp; GetMessage(&amp;msg, hwnd, 0, 0)) ProcessMessage(msg); return active; } void Window::Destroy() noexcept { if(hwnd &amp;&amp; active) { active = false; DestroyWindow(hwnd); hwnd = 0; } } bool Window::OnMouseClick(WPARAM wparam, int x, int y) noexcept { return false; } bool Window::BeforeKeyDown(HWND hwnd, WPARAM wparam) noexcept { return false; } bool Window::OnKeyDown(WPARAM wparam) noexcept { return false; } SIZE Window::GetWindowSize() const noexcept { assert(active); RECT rect; GetWindowRect(hwnd, &amp;rect); return RectToSize(rect); } SIZE Window::GetClientSize() const noexcept { assert(active); RECT rect; GetClientRect(hwnd, &amp;rect); return RectToSize(rect); } tstring Window::GetText() const noexcept { assert(active); size_t max_count = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0); TCHAR* buffer = new TCHAR[max_count + 1]; SendMessage(hwnd, WM_GETTEXT, max_count + 1, (LPARAM)buffer); tstring text(buffer); delete[] buffer; return text; } LRESULT Window::WndProc(UINT msg, WPARAM wparam, LPARAM lparam) noexcept { switch(msg) { case WM_LBUTTONDOWN: if(OnMouseClick(wparam, LOWORD(lparam), HIWORD(lparam))) return 0; break; case WM_KEYDOWN: if(OnKeyDown(wparam)) return 0; break; case WM_DESTROY: Destroy(); return 0; } return DefWindowProc(hwnd, msg, wparam, lparam); } LRESULT CALLBACK Window::WndProcStatic(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) noexcept { Window* self; if(msg != WM_NCCREATE &amp;&amp; (self = (Window*)(GetWindowLongPtr(hwnd, GWLP_USERDATA)))) return self-&gt;WndProc(msg, wparam, lparam); return DefWindowProc(hwnd, msg, wparam, lparam); } void Window::PrepareWndClass(HINSTANCE hinstance, LPCTSTR class_name) const noexcept { WNDCLASSEX wc; if(!GetClassInfoEx(hinstance, class_name, &amp;wc)) { wc.cbSize = sizeof(wc); wc.style = CS_OWNDC; wc.lpfnWndProc = Window::WndProcStatic; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); wc.lpszMenuName = NULL; wc.lpszClassName = class_name; wc.hIconSm = NULL; RegisterClassEx(&amp;wc); } } void Window::ProcessMessage(const MSG&amp; msg) noexcept { TranslateMessage(&amp;msg); if(msg.message == WM_KEYDOWN) if(BeforeKeyDown(msg.hwnd, msg.wParam)) return; DispatchMessage(&amp;msg); } inline SIZE RectToSize(const RECT&amp; rect) noexcept { return {rect.right - rect.left, rect.bottom - rect.top}; } static SIZE GetParentSize(HWND hwnd_parent) noexcept { if(hwnd_parent != HWND_DESKTOP) { RECT rect; GetClientRect(hwnd_parent, &amp;rect); return RectToSize(rect); } else return {GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)}; } static SIZE AdjustWindowSize(SIZE client_size, DWORD style, DWORD ex_style) noexcept { RECT rect{0, 0, client_size.cx, client_size.cy}; AdjustWindowRectEx(&amp;rect, style, 0, ex_style); return RectToSize(rect); } static POINT CenterWindow(SIZE parent_size, SIZE window_size) noexcept { return { (parent_size.cx - window_size.cx) &gt;&gt; 1, (parent_size.cy - window_size.cy) &gt;&gt; 1}; } </code></pre> <p>Also available in this <a href="https://github.com/ShigotoShoujin/shigoto.shoujin/" rel="nofollow noreferrer">repo</a>, but everything needed is shown above.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T23:59:52.097", "Id": "530996", "Score": "0", "body": "Also added Window.hpp / Window.cpp in the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T04:56:47.860", "Id": "530999", "Score": "0", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/269056/5) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[ { "body": "<h2>WndProc setup</h2>\n<p>It's been a while since I've done Windows API stuff, so my memory's kinda fuzzy, but I think there's an issue with how the window procedure is set up in the <code>Window</code> class:</p>\n<p><code>CreateWindowEx</code> only returns after various calls have already been made to the window procedure. Until it returns, <code>hwnd</code> isn't set properly, and <code>this</code> isn't passed to the userdata with <code>SetWindowLongPtr</code>. So in the meantime we might pass a null <code>hwnd</code> to <code>DefWindowProc</code>, and we won't call our own <code>WndProc</code> function until later than we should.</p>\n<p>I think the correct way to solve the issue is to pass <code>this</code> as the <code>lParam</code> in <code>CreateWindowEx</code>. We can retrieve it in the window proc for the <code>WM_NCCREATE</code> message, and use it in <code>SetWindowLongPtr</code>. At the same time, we set the <code>hwnd</code> member to the correct value.</p>\n<p>See <a href=\"https://devblogs.microsoft.com/oldnewthing/20191014-00/?p=102992\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://devblogs.microsoft.com/oldnewthing/20140203-00/?p=1893\" rel=\"nofollow noreferrer\">here</a> for more details and the &quot;correct&quot; way to do things.</p>\n<hr />\n<h2>Simplify settings structs</h2>\n<p>There's a lot of shared data between <code>WindowCreateInfo</code>, <code>ControlCreateInfo</code> and <code>UserControlCreateInfo</code>. Perhaps we can split these variables into groups to avoid duplication?</p>\n<p><code>ControlCreateInfo</code> adds <code>control_id</code>, <code>taborder</code> and <code>tabstop</code> and removes <code>hwnd_menu</code>. <code>UserControlCreateInfo</code> removes <code>hwnd_parent</code>, <code>class_name</code>, <code>style</code> and <code>ex_style</code>, but they're passed to the constructor as separate parameters anyway.</p>\n<p>So perhaps we could use <code>WindowCreateInfo</code> throughout the codebase, and add a second parameter for <code>Control</code>s:</p>\n<pre><code>struct ControlCreateInfo {\n int control_id{};\n int taborder{};\n bool tabstop{true};\n};\n\n...\n\nControl(WindowCreateInfo const&amp; wci, ControlCreateInfo const&amp; cci) { ... }\n</code></pre>\n<p>I'm not sure we need a separate protected constructor for <code>Control</code>.</p>\n<hr />\n<h2>Use plain C++ instead of macros</h2>\n<p>I admit that I used to use similar macros for move and copy when it was first introduced, but quickly decided that was more trouble than just typing the declarations.</p>\n<p>For example, I spent a while thinking there was a bug with how the <code>control_group</code> was handled, because I assumed that <code>ENABLE_MOVE_CONSTRUCTOR</code> would <code>= default</code> the move constructor. Unexpectedly, it's actually just a declaration, and we have the full definition in the .cpp file.</p>\n<p>I think it's much clearer to write out the full declaration in the class though: <code>Control(Control&amp;&amp; other) noexcept;</code> so people like me don't get confused. It's about the same amount of typing anyway.</p>\n<hr />\n<h2>Avoid manual memory management</h2>\n<p>We should use <code>std::unique_ptr&lt;ControlGroup&gt;</code> so that we don't have to manually delete it, and we can also use the <code>= default</code> move constructor.</p>\n<hr />\n<h2><code>Control</code> and <code>ControlGroup</code></h2>\n<p>The <code>ControlGroup</code> stores <code>Controls</code> by value in the <code>control_map</code>, and <code>Control*</code>s in the <code>tab_map</code>. This is safe, because the <code>ControlGroup</code> can ensure that we don't add or remove a <code>Control</code> without changing the <code>tab_map</code>.</p>\n<p>However, that's not the case for the <code>parent_control</code>. Moving the owning <code>Control</code> will change its location in memory, but the <code>ControlGroup</code>'s <code>parent_control</code> pointer won't be updated.</p>\n<p>It might be reasonable to decide that a <code>Control</code> &quot;Is A&quot; <code>ControlGroup</code> (every <code>Control</code> allocates its own after all), and merge the two classes together. I think it's safe to allow <code>ControlGroup</code> to be moved, since moving a <code>std::map</code> won't invalidate pointers.</p>\n<p>We can keep the functionality separate by having <code>Control</code> inherit <code>ControlGroup</code>:</p>\n<pre><code>class Control;\n\nclass ControlGroup\n{\nprotected:\n ControlGroup();\n\n Control* GetOwner();\n};\n\n// note: function must be defined in the .cpp file so we have complete knowledge of Control\nControl* ControlGroup::GetParent() { return static_cast&lt;Control*&gt;(this); }\n\nclass Control : public ControlGroup, public Window { ... };\n</code></pre>\n<p>Since our <code>*this</code> pointer is always up-to-date, we can get the <code>Control</code>, even if it (and the <code>ControlGroup</code>) is moved.</p>\n<p>As a side-note, we should be able to implement move-assignment for the <code>Control</code> class as well as move-construction.</p>\n<hr />\n<h2>Control insertion</h2>\n<pre><code>HWND hwnd = control.hwnd;\ncontrol_map.emplace(control.hwnd, std::move(control));\n\nControl* c = &amp;control_map.at(hwnd);\ntab_map.emplace(c-&gt;taborder, c);\n</code></pre>\n<p>From the linked repo, it looks like you've already found that <code>emplace</code> returns an iterator. :)</p>\n<p>It's probably worth an <code>assert</code>ion or some other check to ensure that adding the control succeeded. (And maybe we should do the insertion before any of the other operations here).</p>\n<hr />\n<h2>Move semantics and pointers</h2>\n<p>I think the main issue with using move-semantics here is (as seen above), keeping references (or pointers), up to date. The <code>ControlGroup</code> class can ensure that it only uses pointers while a <code>Control</code> exists safely on it's <code>control_map</code>. Any outside use of <code>Control</code> pointers is likely to be unsafe, so we have to use <code>hwnd</code>s (or some other id) everywhere else.</p>\n<p>If you're happy with this restriction then that's fine. If not, then storing Controls in <code>unique_ptr</code>s might be easier. You still have a single point of ownership, but pointers are valid for the entire lifetime of the <code>Control</code> instance.</p>\n<hr />\n<h2>Move assignment</h2>\n<p>[In response to comments:] The copy and swap idiom is a good way to implement the move-assignment operator. It looks like this for a class <code>T</code>:</p>\n<pre><code>T&amp; T::operator=(T&amp;&amp; other)\n{\n T temp (std::move(other)); // use the move constructor to copy from other\n\n using std::swap;\n swap(m_var_1, temp.m_var_1); // swap each member variable between this and temp\n swap(m_var_2, temp.m_var_2);\n\n return *this;\n}\n</code></pre>\n<p>We could provide a <code>void swap(T&amp; other)</code> member function on our class to encapsulate all the swapping if we have many variables, and just call <code>swap(temp)</code>.</p>\n<p>If we wanted to, we could unify it with the copy constructor by providing a single <code>operator=</code> like so.</p>\n<pre><code>T&amp; T::operator=(T other)\n{\n swap(temp); // use the swap member function we defined\n return *this;\n}\n</code></pre>\n<p>This is safe for self-assignment, so we don't need to check for it. (Although we could check for self-assignment and avoid the swapping, note that self-assignment is very rare. By doing the check we make the &quot;normal&quot; (non-self-assignment) case slower! So we just don't check).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:19:14.573", "Id": "531091", "Score": "0", "body": "Thank you very much for this very detailed and informative answer. Receiving feedback is a great way to give weight to particular a design choice while there are so many ways of achieving the same 'visual' result.\n\nI did not realize that WndProc would be called more then once with WM_NCCREATE before CreateWindowsEx returns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:19:17.743", "Id": "531092", "Score": "0", "body": "On the duplicate structs, they were an attempts to avoid having structs based on other structs, which makes the c++20 named initializer less beautiful, having to use extra {} for each base class. But indeed no need to inherit if we just pass WindowCreateInfo along with ControlCreateInfo." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:19:26.627", "Id": "531093", "Score": "0", "body": "Agreed on macro, they obfuscate the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:21:20.177", "Id": "531094", "Score": "0", "body": "Also agreed on Control being A ControlGroup. This should resolve the issue with the existance of \"friend ControlGroup;\" in Control.hpp. Having to use \"friend\" seems like a bad smell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:22:18.013", "Id": "531095", "Score": "0", "body": "The parent_control not being updated might just be the answer to the bug that I was having yesterday while implementing ColorControl, a color picker." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:24:08.057", "Id": "531096", "Score": "0", "body": "Indeed for map::emplace, I've found the solution meanwhile : )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:28:30.230", "Id": "531097", "Score": "0", "body": "When you say that the default move constructor could be used if std::unique_ptr is used to manage ControlGroup*, doesn't the default move ctor only copy values and does not clear them? And this would be ok because the moved unique_ptr would just be internally flagged as not containing ptr anymore? More reading needs to be done. Being able to use the default move ctor / assign would be very nice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:30:19.317", "Id": "531099", "Score": "0", "body": "In a move assigment operator we have to also check for self reference and destroy *this before proceeding, would it be fine to manually call our own destructor with this::~ClassName();, meaning that the destructor could be called twice but not on the same internal values? Or should a \"Destroy\" function be made, and called from both the destructor and the move assignment? Many thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T07:37:58.427", "Id": "531109", "Score": "0", "body": "@ShigotoShoujin Yep. Moving from a std::unique_ptr is guaranteed to leave the `unique_ptr` empty (it effectively calls `release()` on it): https://en.cppreference.com/w/cpp/memory/unique_ptr/operator%3D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T07:48:50.697", "Id": "531110", "Score": "0", "body": "@ShigotoShoujin You shouldn't manually call the destructor in the move assignment operator. Having a \"Destroy\" function would work. Even better would be to use the \"copy and swap\" idiom. That method uses the destructor to do cleanup, and ensures safety, even for self-assignment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T02:09:33.400", "Id": "531175", "Score": "0", "body": "On \"Avoid manual memory management\", in this particular case the default move cannot be used, because at that point ControlGroup is declared but not defined, which lead to error \"can't delete an incomplete type\". Other than that, it is now an unique_ptr in the feature/color_control branch :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T04:41:42.183", "Id": "531312", "Score": "0", "body": "The std::map will need to store pointers to Control instead of values, otherwise it does not handle inheritance and objects derived from Control will not be stored correctly.\n\nThis defeat the whole purpose of going with value type." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T10:01:16.493", "Id": "269177", "ParentId": "269056", "Score": "1" } } ]
{ "AcceptedAnswerId": "269177", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T05:11:24.403", "Id": "269056", "Score": "1", "Tags": [ "c++", "c++11", "winapi" ], "Title": "Win32 UI with tabs and buttons" }
269056
<p>I find myself frequently needing to create a new directory and changing to it enough to want to combine the two commands, so I figured it was a good opportunity to practice scripting with bash.</p> <p>The command I use to create and change to a directory is <code>mkdir -p directory_name &amp;&amp; cd directory_name</code>, and that's the command that the <code>mkkdir</code> function wraps, essentially. The only additional stuff that I would say is really consequential is the check to make sure that the name of the directory does not begin with a hyphen.</p> <p>Also, the script explicitly checks to make sure the directory does not already exist. This is not something that <code>mkdir</code> does, and when I'm using this command combination, I'm usually trying to specifically create a new directory. I've accidentally modified files that I did not mean to because I <code>mkdir -p &amp;&amp; cd</code>'d into a directory that already existed.</p> <pre class="lang-bsh prettyprint-override"><code># mkkdir version 1.4.0 # # Create a new directory and move into it in the same # command. # # If the specified directory already exists, the command # will fail, as the assumption is that the directory is # meant to be new. # function mkkdir() { # We begin by checking for the command-line argument # passed in by the user. It must be exactly one, since # we can only create and change into one directory, and # all of the valid program options result in short- # circuiting program execution. # if [[ $# -ne 1 ]] then # Since the number of command-line arguments was # not exactly one, notify the user of their error # and return with an error status code. echo 'Usage: mkkdir &lt;DirectoryPath&gt;' &gt;&amp;2 &amp;&amp; return 1 fi # Check whether the user requested the version number # of the program or the help menu. case $1 in -h | --help) echo 'Usage: mkkdir &lt;DirectoryPath&gt;' echo 'Create new directory and cd to it' echo '' echo ' -h, --help display this help and exit' echo ' --version output version information and exit' echo 'This is free software: you are free to change and redistribute it.' echo 'There is NO WARRANTY, to the extent permitted by law.' return 0 ;; --version) echo 'mkkdir version 1.4.0' return 0 ;; # Check for invalid options. This function will thus # not be able to create directories that begin with a # hyphen, but that's so uncommon so as to be totally # fine. # # Usually an argument that begins with a hyphen # detected here will almost always be a mispelled # command-line option. -* | --*) echo &quot;Invalid option detected: $1&quot; return 1 ;; esac # Passing in an empty string to the function will not # trigger any errors so far, since an argument was # technically passed in. Still, this edge case is # obviously not a valid use case, and we must therefore # validate the input string. if [ -z &quot;$1&quot; ] then # The input string is a zero-length string, so we # simply let the user know and exit with an error # status. echo 'The empty string is an invalid directory path.' &gt;&amp;2 &amp;&amp; return 1 fi # Check whether the specified directory exists. If it # does, return with an error status. if [[ -d &quot;$1&quot; ]] then # The directory exists so simply let the user know # and exit with an error status. echo &quot;The specified directory already exists: $1&quot; &gt;&amp;2 &amp;&amp; return 1 fi # Finally, create the directory and change the current # working directory to it using the cd command. mkdir -p &quot;$1&quot; &amp;&amp; cd &quot;$1&quot; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Good</h1>\n<ul>\n<li>consistent indentation</li>\n<li>good error checking</li>\n<li>nice comments</li>\n<li>great quoting of variable substitutions</li>\n<li>yay for putting it all in a function</li>\n<li>good use of <code>case</code> statement for processing options. (Typically this would be in a loop, but since you only allow for one argument above this it makes sense that there is no loop here.)</li>\n</ul>\n<h1>ShellCheck suggests</h1>\n<p>One of my favorite tools, <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">Shellcheck.net</a>, suggests:</p>\n<ul>\n<li>Put in a <a href=\"https://en.wikipedia.org/wiki/Shebang_(Unix)\" rel=\"nofollow noreferrer\">shebang</a> line. This is a good habit to have. It would let shellcheck know which shell-specific checks it could apply. And it indicates to users which shell you expect this code to be aimed for.</li>\n<li>Your <code>-*</code> pattern is more general than your <code>--*</code> pattern, so you don't need both.</li>\n<li><code>cd</code> might fail so you should consider including a <code>|| something</code>, which might print an error message or try something different. :) Since the <code>cd</code> is the last thing and it will print a reasonable error message I wouldn't worry about catching this error. Most of my scripts don't check for <code>cd</code> errors and the <code>cd</code> is never the last thing in the file. For critical code I have <a href=\"https://stackoverflow.com/a/821419/2002471\">the <code>set -e</code> flag on</a> for the whole script so any errors cause the script to exit without having to write error checking code for every file I/O operation.</li>\n</ul>\n<h1>My suggestions</h1>\n<ul>\n<li>All of your <code>return</code>s return a 1. This makes it impossible for automation built on top of this to determine which error occurred without parsing the output. Having a unique return code for each error type is a good habit to keep up so code that wasn't intended for automation is ready for automation.</li>\n<li>I like that you've used <code>[[</code> for conditionals for the most part, but you have one where you fell back on <code>[</code>. Using <code>[[</code> is a best practice and I've never found a reason not to use it.</li>\n<li>You have a number of <code>echo &amp;&amp; return</code> lines. (A) The <code>echo</code> is unlikely to fail. (B) Even if the <code>echo</code> fails you probably still want to return. (C) It is clearer that you are returning if the <code>return</code> isn't buried at the end of the <code>echo</code>.</li>\n<li>It would be easier to follow if the innards of your <code>case</code>...<code>esac</code> were indented another level.</li>\n<li>I would tend to put the <code>then</code>s up next to the if with a <code>; next</code> sort of thing.</li>\n<li>It would be nice to mention in the docs that this file should be <code>source</code>d and then the command will be available.</li>\n</ul>\n<h1>Conclusion</h1>\n<p>Overall, this is an excellent implementation for a challenge that has been around for decades. The code is very approachable and maintainable. The improvements suggested are mostly cosmetic. There are no apparent bugs. Keep up the great work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T06:43:46.090", "Id": "530803", "Score": "0", "body": "Each and every one of these suggestions was something that I either completely missed or just plain had no idea about. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:37:59.600", "Id": "530814", "Score": "0", "body": "Many different error returns can be a maintenance nightmare. Look to the core utils for good examples; the only commands that have multiple failure codes tend to be the ones (such as `timeout`) that invoke other commands as their main function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T15:23:58.537", "Id": "269071", "ParentId": "269057", "Score": "4" } }, { "body": "<p>The only thing here that's not standard shell is <code>[[</code>. That's easily replaced with <code>[</code>, which would give a more portable function: usable with any POSIX shell, not just Bash.</p>\n<blockquote>\n<pre><code>if [ -z &quot;$1&quot; ]\n</code></pre>\n</blockquote>\n<p>We could have included this test as part of the <code>case</code>.</p>\n<blockquote>\n<pre><code>mkdir -p &quot;$1&quot;\n</code></pre>\n</blockquote>\n<p>Always using <code>-p</code> might not be desirable. If I mis-type one of the directory components, I might be surprised to find a whole new directory created. Consider instead accepting more options, and passing them on to <code>mkdir</code>. That would save us having to do the <code>-d</code> test ourselves, and allow a user to use this command even when the directory might already exist, rather than having to perform <code>test -d</code> to decide whether to use this function or just <code>cd</code> (which completely negates its usefulness!).</p>\n<p>While we're looking at more options, also consider allowing <code>--</code> to signal end of options.</p>\n<blockquote>\n<pre><code>echo '…' &gt;&amp;2 &amp;&amp; return 1\n</code></pre>\n</blockquote>\n<p>I think these <code>return</code>s should be unconditional. There's no good reason to continue just because the error reporting failed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:51:46.777", "Id": "269088", "ParentId": "269057", "Score": "4" } } ]
{ "AcceptedAnswerId": "269071", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T07:27:08.860", "Id": "269057", "Score": "2", "Tags": [ "bash" ], "Title": "Bash function to create a directory and change to it in a single command" }
269057
<p>I want to create ENUM which maps different statuses:</p> <pre><code>public enum BusinessCustomersStatus { A(&quot;active&quot;), O(&quot;onboarding&quot;), NV(&quot;not_verified&quot;), private String status; BusinessCustomersStatus(String status) { this.status = status; } public String getStatus() { return status; } public static BusinessCustomersStatus getStatusByText(String statusText) { BusinessCustomersStatus response = null; for (BusinessCustomersStatus status : values()) { if (status.getStatus().equalsIgnoreCase(statusText)) { response = status; break; } } if(response == null) { throw new UnsupportedOperationException(String.format(&quot;Unknown status: '%s'&quot;, statusText)); } return response; } } </code></pre> <p>I want to improve the Java method <code>getStatusByText</code>. The code is working but I want to improve the logic for throwing exception.</p>
[]
[ { "body": "<p>About the for in your <code>getStatusByText</code> method :</p>\n<pre><code>BusinessCustomersStatus response = null;\nfor (BusinessCustomersStatus status : values()) {\n if (status.getStatus().equalsIgnoreCase(statusText)) {\n response = status;\n break;\n }\n}\nif(response == null) {\n throw new UnsupportedOperationException(String.format(&quot;Unknown status: '%s'&quot;, statusText));\n}\nreturn response;\n</code></pre>\n<p>You can return directly the <code>status</code> as your response instead of breaking the <em>for</em> loop and after return the response. This implies the rewritting of your method like below :</p>\n<pre><code>public static BusinessCustomersStatus getStatusByText(String statusText) {\n for (BusinessCustomersStatus status : values()) {\n if (status.getStatus().equalsIgnoreCase(statusText)) {\n return status;\n }\n }\n\n throw new UnsupportedOperationException(String.format(&quot;Unknown status: '%s'&quot;, statusText));\n\n}\n</code></pre>\n<p>The final part of your method changes too ending directly with the exception in case no value in your <em>for</em> loop satisfies your condition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T09:23:48.047", "Id": "269059", "ParentId": "269058", "Score": "11" } }, { "body": "<p>Few suggestions:</p>\n<ul>\n<li><strong>Naming</strong>: <code>A</code>, <code>O</code>, and <code>NV</code> are not clear names. Would be better to use their extended names: <code>ACTIVE</code>, <code>ONBOARDING</code>, and <code>NOT_VERIFIED</code>.</li>\n<li><strong>Missing semicolon</strong>: <code>NV(&quot;not_verified&quot;),</code> should be <code>NV(&quot;not_verified&quot;);</code>.</li>\n<li><code>return</code> instead of <code>break</code> as @dariosicily suggested.</li>\n</ul>\n<p>Alternative using <strong>Streams</strong>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static BusinessCustomersStatus getStatusByText(String text) {\n return Stream.of(BusinessCustomersStatus.values())\n .filter(bcs -&gt; bcs.getStatus().equalsIgnoreCase(text))\n .findAny()\n .orElseThrow(() -&gt; new UnsupportedOperationException(String.format(&quot;Unknown status: '%s'&quot;, text)));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:58:54.813", "Id": "530991", "Score": "0", "body": "Personally I prefer adding the semicolon on the line after the last entry, it makes the git history cleaner" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:59:44.937", "Id": "530992", "Score": "0", "body": "`UnsupportedOperationException` is unnecessary, `IllegalArgumentException` is clearer. For other points, see tucuxi's answer, which I think has the best approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T23:01:06.677", "Id": "530993", "Score": "0", "body": "If the edge-case of an invalid text is something that can actually happen and needs to be handled properly, then I would use an `Optional<BusinessCustomersStatus>` instead." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T09:36:37.210", "Id": "269061", "ParentId": "269058", "Score": "17" } }, { "body": "<p>The previous answers by dariosicily and marc cover most of the ground. But I have a few other comments.</p>\n<ul>\n<li>If you go for more meaningful names for your enum values, you\nprobably don't need a &quot;status&quot; field - you can simply map the name to\nlower case.</li>\n<li>I'm not sure UnsupportedOperationException is the best choice here, and can see no good reason not to create your own Exception for the purpose.</li>\n<li>If your list of enum values grows significantly bigger, I'd suggest maintaining a Map of the values rather than doing a sequential search. My example below does this, just to illustrate how I'd do that, though for three values it's probably overkill.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>package codeReview;\n\nimport java.util.Arrays;\n\nimport java.util.HashMap;\n\nimport java.util.Map;\n\nimport codeReview.Penzov.BusinessCustomersStatus.NoSuchStatusException;\n\npublic class Penzov {\n\n public enum BusinessCustomersStatus {\n ACTIVE, //\n ONBOARDING, //\n NOT_VERIFIED;\n\n static Map &lt;String,BusinessCustomersStatus&gt; statusLookup = new HashMap&lt;&gt;();\n static {\n for (BusinessCustomersStatus status: values()) {\n statusLookup.put(status.getStatus(), status);\n }\n }\n\n public String getStatus() {\n return name().toLowerCase();\n }\n\n public static BusinessCustomersStatus getStatusByText(String statusText) throws NoSuchStatusException {\n BusinessCustomersStatus status = statusLookup.get(statusText.toLowerCase());\n if (status != null) {\n return status;\n }\n\n // Didn't find a match\n throw new NoSuchStatusException(String.format(&quot;Unknown status: '%s'&quot;, statusText));\n }\n\n public static class NoSuchStatusException extends Exception {\n\n private static final long serialVersionUID = -2003653625428537073L;\n\n public NoSuchStatusException(String message) {\n super(message);\n }\n }\n }\n\n public static void main(String[] args) {\n for (String testString: Arrays.asList(&quot;active&quot;, &quot;ONBOARDING&quot;, &quot;NoT_VERified&quot;, &quot;dubious&quot;)) {\n try {\n System.out.format(&quot;testString = '%s', status found = '%s'%n&quot;, testString, BusinessCustomersStatus.getStatusByText(testString));\n } catch (NoSuchStatusException e) {\n System.out.format(&quot;testString = '%s', exception thrown = '%s'%n&quot;, testString, String.valueOf(e));\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:08:18.680", "Id": "530817", "Score": "1", "body": "Thanks to Marc for the edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T15:45:52.547", "Id": "530839", "Score": "2", "body": "I usually use `IllegalArgumentException` in this context since someone was trying to parse a string to the enum (but the argument to that parsing was illegal)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T08:15:44.050", "Id": "530896", "Score": "0", "body": "Note that having seen tucuxi's post, I'd use his approach." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T08:18:03.580", "Id": "269089", "ParentId": "269058", "Score": "4" } }, { "body": "<p>Your code can be simpler if you take advantage of <code>valueOf()</code> (see <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Enum.html#valueOf(java.lang.Class,java.lang.String)\" rel=\"noreferrer\">javadoc</a>):</p>\n<pre><code>public static BusinessCustomersStatus getStatusByText(String text) {\n return Enum.valueOf(\n BusinessCustomersStatus.class, \n text.toUpperCase());\n}\n</code></pre>\n<p>Note that this throws an <code>IllegalArgumentException</code> if the text does not correspond to a <code>BusinessCustomersStatus</code> value - which actually looks better to me than an <code>UnsupportedOperationException</code>, which is <a href=\"https://stackoverflow.com/a/32847052/15472\">better used</a> when the operation you are attempting (string-to-enum-value) is optional and, in this specific class, not implemented for any argument at all -- and not just &quot;unsupported&quot; for the argument you have just entered.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T08:53:03.857", "Id": "530899", "Score": "0", "body": "Probably the best approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T15:49:02.607", "Id": "269102", "ParentId": "269058", "Score": "5" } } ]
{ "AcceptedAnswerId": "269061", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T08:08:05.247", "Id": "269058", "Score": "8", "Tags": [ "java" ], "Title": "Throw exception if value is not found" }
269058
<p>I recently came across the <code>OneOf&lt;T0,...,Tn&gt;</code> package from <a href="https://github.com/mcintyre321/OneOf" rel="nofollow noreferrer">mcintyre321</a> via a video by <a href="https://www.youtube.com/watch?v=r7QUivYMS3Q" rel="nofollow noreferrer">Nick Chapsas</a>, which presents the idea of holding exception types to be returned in the same object as would hold a successful result; e.g.</p> <pre><code>public OneOf&lt;User, InvalidEmail, EmailAlreadyExists&gt; CreateUser { /* ... */ } </code></pre> <p>This made me consider; aside from the expected return type (<code>User</code>), all other types are to cater for exceptions.<br /> Also the caller of the class library (not API) who may only be interested in receiving a valid user or having an exception thrown, now needs to implement that logic for themselves, converting the OneOf approach to their own needs.</p> <p>I considered the below class; as a way to also allow an expected result class or an Exception to be returned (not thrown).</p> <pre class="lang-cs prettyprint-override"><code>public class ResultOrException&lt;T&gt; { private T _result; public bool IsException {get {return Exception != null;}} public Exception Exception {get;private set;} public ResultOrException(): this(new InvalidOperationException($&quot;A {nameof( ResultOrException&lt;T&gt; )} class has been accessed before it is assigned to.&quot;)){} public ResultOrException(T result) { _result = result; } public ResultOrException(Exception exception) { Exception = exception ?? throw new ArgumentNullException(nameof(exception)); } public static implicit operator T(ResultOrException&lt;T&gt; value) { if (value.IsException) { throw value.Exception; } return value._result; } public static implicit operator ResultOrException&lt;T&gt;(T result) { return new ResultOrException&lt;T&gt;(result); } } </code></pre> <p>This includes implicit conversion to the expected result type; so if the client's expecting a value of type <code>User</code> they don't need to do any heavy lifting to get that; they just rely on implicit conversion. If the returned value was an exception, the exception gets thrown during the conversion so the information in that exception is then accessible to the caller.</p> <p>However if the caller wants to handle the different exception cases differently (e.g. to return the exception to their API's caller), they can implement their own logic to handle that, without having to catch the thrown exception as they may if working with a more traditional class library.</p> <p>Here's a simple example of the above class being used in practice:</p> <pre class="lang-cs prettyprint-override"><code>void Main() { var userManager = new UserManager(); var found = false; var result = new ResultOrException&lt;User&gt;(); while (!found) { Console.WriteLine(&quot;Please enter your username&quot;); var id = Console.ReadLine(); result = userManager.GetById(id); found = !result.IsException; if (!found) { Console.WriteLine(&quot;{0}. Please try again.&quot;, result.Exception?.Message); } } User loggedInAs = result; Console.WriteLine($&quot;You've successfully logged in as '{loggedInAs.Name}'&quot;); User nonExistant = userManager.GetById(&quot;simon.borg@example.com&quot;); Console.WriteLine(&quot;We'll never get here; as the above line throws an exception&quot;); } public class UserManager { IDictionary&lt;string, User&gt; db; public UserManager() { var users = new []{ new User(&quot;anne.droid@example.com&quot;, &quot;Anne&quot;), new User(&quot;rob.ott@example.com&quot;, &quot;Robert&quot;) }; db = new Dictionary&lt;string, User&gt;(); foreach (var user in users) { db.Add(user.Id, user); } } public ResultOrException&lt;User&gt; GetById (string id) { if (db.ContainsKey(id)) { return db[id]; } return new ResultOrException&lt;User&gt;(new UserNotFoundException(id)); } } public class User { public string Id {get; private set;} public string Name {get; private set;} public User (string id, string name) { Id = id; Name = name; } } public class NotFoundException: Exception { public NotFoundException(string message): base(message){} } public class UserNotFoundException: NotFoundException { public UserNotFoundException(string userId): base($&quot;No user with id '{userId}' was not found&quot;){} } </code></pre> <p>One issue with this approach is that the stack trace shows the error coming from the implicit conversion, rather than from where it's thrown; but I feel like in this context that shouldn't be an issue; as we'd only use this approach for functional exceptions. I.e. I wouldn't propose catching any exception and bundling them into the returned ResultOrException result; only assigning those exceptions which we'd expect a user to handle as part of the normal flow of business logic.</p> <p>I'd be interested in others' thoughts on this approach.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:44:01.977", "Id": "530819", "Score": "4", "body": "If StackTrace matters for you, then I would suggest to take a look at the [`ExceptionDispatchInfo`](https://codereview.stackexchange.com/questions/256732/rethrowing-unhandled-exceptions-later-in-the-catching-method/256755#256755)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:47:58.810", "Id": "530820", "Score": "1", "body": "Thanks @PeterCsala; I wasn't aware of that class; definitely useful in some scenarios. For this use case I believe the exception's stack trace probably isn't needed; since the thrown exceptions are due to specific business logic scenarios; but that's a great tool to have in my toolkit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:48:06.657", "Id": "530821", "Score": "1", "body": "I think you might misunderstand the intent of the OneOf library. Instead of defining exceptions for not exceptional (rather normal) cases (like user not found) you define different state/result objects. With this you make them as explicit as possible to the caller that they should prepare for that case as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:52:42.917", "Id": "530822", "Score": "0", "body": "In this context I don't see the whole point of your `ResultOrException`. You, as the caller, always have to use try-catch block because you don't know what to expect. Or maybe I absolutely misunderstood your intent. If you are interested about the intentional use of OneOf then I would suggest to read [my other post about best practices](https://softwareengineering.stackexchange.com/questions/421825/patterns-for-returning-messages-results-from-business-logic-to-ui/421834#421834)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:57:51.670", "Id": "530823", "Score": "0", "body": "Thanks. I got that knowing what exceptions could be returned was helpful; but wanted something slightly different; i.e. a way to cleanly return exceptions without throwing them; so that I could implement cleaner logic in any API methods. My thinking was to have a mapping between a common set of \"application exceptions\" and the relevant HTTP statuses to wrap those responses as expected. However, I wanted any thrown exceptions to be caught and returned as 503s / logged as errors for investigation by IT, rather than for the user to figure out..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T10:01:39.580", "Id": "530824", "Score": "1", "body": "This mapping is usually implemented in an [exception handler middleware](https://jasonwatmore.com/post/2020/10/02/aspnet-core-31-global-error-handler-tutorial). Which means your controller's actions can throw exceptions as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T10:02:30.470", "Id": "530825", "Score": "1", "body": "My reason for throwing an exception from the implicit conversion was for scenarios where the caller hadn't checked for IsException. Typically I'm thinking if my same class library is used elsewhere, where the client expects the class to throw exceptions or return objects of the requested type; i.e. so this more traditional flow is also supported by the same class library, without the client having to implement `If (result.IsException) {throw result.Exception;} DoSomething(result.Result);` everywhere. I've demoed both use cases in the sample code; one checking the exception, the other throwing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T10:12:03.863", "Id": "530826", "Score": "1", "body": "Exactly. It's up to your API caller whether or not checks the existence of an exception. It might happen that (s)he forgets to perform that check. With OneOf's `Switch` you will get compile time error if you forgot to handle any of the cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T09:14:53.103", "Id": "530901", "Score": "0", "body": "You did a monad Either." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T09:30:11.927", "Id": "269060", "Score": "1", "Tags": [ "c#", "error-handling", "exception" ], "Title": "Class to wrap result or exception, similar to the OneOf approach" }
269060
<p>Created a new typedef and functions supporting it, making it user-friendly [specifically programmer-friendly].</p> <h4>What does the code do?</h4> <ul> <li>It makes users [programmers] easy to deal with strings as most functions are there.</li> <li>Additionally, we can append, obtain substrings, replace string very very easily</li> <li>Also there is no specific limit to the string itself but most functions limit the str to GLOBAL_MAX_CHAR_LIMIT which is defined in mystring.h</li> </ul> <p>Note: This code may contain bugs but I have fixed tons of them which I encountered. Also sstrreplace() is limited to have 7 chars in replacing strings -&gt; I dont know why but if the length is greater than 7 wierd things happen &lt;- I am in progress of finding its solution.</p> <p>Also got to know that gets() is not safe so I used fgets() and removed '\n' in strinput()! All suggestions, feedbacks and bug-encounters are welcome!</p> <h4>Note: This code has been updated and has fixed bugs. updated version can be found <a href="https://codereview.stackexchange.com/questions/269720/user-friendly-string-struct-and-utility-function-upated-version">here</a></h4> <p>The header file: mystring.h</p> <pre class="lang-c prettyprint-override"><code>#ifndef STRING_H_DEFINED #define STRING_H_DEFINED #define GLOBAL_MAX_CHAR_LIMIT 200 //dont need to include stdbool.h! #define true 1 #define false 0 typedef int bool; typedef struct{ char * _str; }sstring; typedef struct{ char _str[GLOBAL_MAX_CHAR_LIMIT]; }substr; //functions declarations sstring cstr2sstr(char _cstr[GLOBAL_MAX_CHAR_LIMIT]); char sgetchar(sstring _str,int _pos); substr strinput(); substr ssetchar(sstring _str,int _pos,char _ch); substr sstrappend(sstring _str,char * _append); substr ssubstr(sstring _str,int pos1,int len); char * sstrval(sstring _str); int cstrlen(const char * _str); int sstrlen(sstring _str); int sstrfind(int init,sstring _strvar,const char * _find); sstring sstrreplace(sstring _str,char * _find,char * _repl); #endif </code></pre> <p>mystring.c &lt;&lt; to be included and compiled at once</p> <pre><code>#include &quot;mystring.h&quot; #include&lt;string.h&gt; #include&lt;stdio.h&gt; char * sstrval(sstring _str){ return _str._str; } int cstrlen(const char * _str){ int i=0; while(1&gt;0){ if(_str[i]=='\0'){ return i; } i++; } } int sstrlen(sstring _str){ return cstrlen(sstrval(_str)); } substr sstrappend(sstring _str,char * _append){ int _len = sstrlen(_str),_len2=cstrlen(_append); char temp[_len+_len2]; for(int i=0;i&lt;_len+_len2;i++){ temp[i] = _str._str[i]; if(i&gt;=_len){ temp[i] = _append[i-_len]; } } substr ret; for(int i=0;i&lt;cstrlen(temp);i++){ ret._str[i] = temp[i]; } ret._str[_len+_len2] = '\0'; return ret; } int sstrfind(int init,sstring _strvar,const char * _find){ const char * _str; _str = _strvar._str; int _len1 = cstrlen(_str); int _len2 = cstrlen(_find); int matching = 0; //some wierd conditions check [user, are u fooling the function ?] if(_len2&gt;_len1||init&lt;0||init&gt;_len1-1||_len2==0){ return -1; } //the main finder for(int i=init;i&lt;_len1+1;i++){ if(_str[i]==_find[0]){ for(int z=0;z&lt;_len2+1;z++){ if(matching==_len2){ return i; } else if(_str[i+z]==_find[z]){ matching+=1; } else{ matching=0; break; } } } } return -1; } substr ssubstr(sstring _str,int pos1,int len){ substr self; if(pos1&lt;0||len&lt;1||sstrlen(_str)&lt;1||pos1+len&gt;sstrlen(_str)){ return self; } char a[GLOBAL_MAX_CHAR_LIMIT]; for(int i=0;i&lt;GLOBAL_MAX_CHAR_LIMIT;i++){ a[i] = '\0'; } if(pos1==0){ for(int i=0;i&lt;len;i++){ a[i] = _str._str[i]; } } for(int i=pos1;i&lt;pos1+len;i++){ a[i-pos1] = _str._str[i]; } substr b; for(int i=0;i&lt;GLOBAL_MAX_CHAR_LIMIT;i++){ b._str[i] = '\0'; } for(int i=0;i&lt;=GLOBAL_MAX_CHAR_LIMIT;i++){ if(i&gt;GLOBAL_MAX_CHAR_LIMIT){ return self; } b._str[i] = a[i]; } return b; } substr ssetchar(sstring _str,int _pos,char _ch){ substr tmp; //nullify the string buffer for(int i=0;i&lt;GLOBAL_MAX_CHAR_LIMIT;i++){ tmp._str[i]='\0'; } if(_pos&lt;0){ return tmp; } //copy the string buffer and set the char of _pos as _ch for(int i=0;i&lt;sstrlen(_str);i++){ tmp._str[i]=_str._str[i]; if(i==_pos){ tmp._str[i]=_ch; } } return tmp; } char sgetchar(sstring _str,int _pos){ char _ret; _ret = '\0'; if(_pos&lt;0){ return _ret; } _ret = _str._str[_pos]; return _ret; } substr strinput(){ substr temp; fgets(temp._str,GLOBAL_MAX_CHAR_LIMIT,stdin); temp._str[cstrlen(temp._str)-1] = '\0'; return temp; } sstring sstrreplace(sstring _str,char * _find,char * _repl){ //duplicate of _str sstring _dup = _str; //temp str's sstring _tmp,_tmp2; substr self,tmp; int _lens = strlen(_str._str); int _lenf = strlen(_find); int _lenr = strlen(_repl); //current limit - idk why but if _lenr &gt; 7 WIERD THINGS HAPPEN so return original string if(_lenr&gt;7){ return _dup; } int temp=0,nottoappend=0; char tmpstr[GLOBAL_MAX_CHAR_LIMIT]; temp=sstrfind(0,_str,_find); if(temp==-1){ return _dup; } int tmpint=0,num=1; while(1&gt;0){ temp = sstrfind(0,_dup,_find); if(temp==-1){ //incase of char buffering printf(&quot;%c\b \b&quot;,_dup._str[sstrlen(_dup)-1]); return _dup; }else{ if(temp==sstrlen(_dup)-1){ _dup._str = ssubstr(_dup,0,sstrlen(_dup)-1)._str; _dup._str = sstrappend(_dup,_repl)._str; //incase of char buffering printf(&quot;%c\b \b&quot;,_dup._str[0]); return _dup; } if(_lenr==0){ _tmp._str = ssubstr(_dup,0,temp)._str; _tmp2._str = ssubstr(_dup,temp+_lenf,sstrlen(_dup)-temp-_lenf)._str; _dup._str = sstrappend(_tmp,_tmp2._str)._str; }else{ _tmp._str = ssubstr(_dup,0,temp)._str; _tmp2._str = ssubstr(_dup,temp+_lenf,sstrlen(_dup)-temp-_lenf)._str; _dup._str = sstrappend(_tmp,_repl)._str; _dup._str = sstrappend(_dup,_tmp2._str)._str; } } } } sstring cstr2sstr(char _cstr[GLOBAL_MAX_CHAR_LIMIT]){ sstring _ret; _ret._str = &quot;&quot;; for(int i=0;i&lt;cstrlen(_cstr);i++){ _ret._str = sstrappend(_ret,&quot; &quot;)._str; } for(int i=0;i&lt;cstrlen(_cstr);i++){ _ret._str = ssetchar(_ret,i,_cstr[i])._str; //incase of char buffering printf(&quot;%c\b%c\b \b&quot;,_cstr[i],_ret._str[i]); } return _ret; } </code></pre> <p>exampleusage.c</p> <pre class="lang-c prettyprint-override"><code>#include&lt;stdio.h&gt; #include &quot;mystring.h&quot; int main(){ int len1,find; sstring var1,var2,var3; char chr; printf(&quot;Enter your name: &quot;); //strinput! var1._str = strinput()._str; //length of string len1 = sstrlen(var1); printf(&quot;\nYour name's Length is: %d&quot;,len1); //replacing all spaces with underscores var2._str = sstrreplace(var1,&quot; &quot;,&quot;_&quot;)._str; printf(&quot;\nYour url might look like : '%s'&quot;,var2); //with no spaces var2._str = sstrreplace(var1,&quot; &quot;,&quot;&quot;)._str; printf(&quot;\nConJusted Name: %s&quot;,var2); //appending &quot; is a good person full of honesty and great behaviour!&quot; var2._str = sstrappend(var1,&quot; is a good person full of honesty and great behaviour!&quot;)._str; printf(&quot;\nGood about you: %s&quot;,var2); //finding space! find = sstrfind(0,var1,&quot; &quot;); printf(&quot;\nFirst space in your name is in %d charachter&quot;,find); //substrings! find = sstrfind(0,var1,&quot; &quot;); var2._str = ssubstr(var1,0,find)._str; printf(&quot;\nYour first name: %s&quot;,var2); var2._str = ssubstr(var1,find+1,len1-find-1)._str; printf(&quot;\nYour last name: %s&quot;,var2); //setting chars! //set first char to 'F' var2._str = ssetchar(var1,0,'F')._str; printf(&quot;\nYour name with first char as 'F': %s&quot;,var2); //getting chars! //get last char of name! chr = sgetchar(var1,sstrlen(var1)-1); printf(&quot;\nYour name's last char is '%c'&quot;,chr); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T07:13:19.297", "Id": "532230", "Score": "0", "body": "This code has been updated with bugfixes and suggestions! thanks all for reviewing this code. [updated code](https://codereview.stackexchange.com/questions/269720/user-friendly-string-struct-and-utility-function-upated-version)" } ]
[ { "body": "<h1>Don't reimplement <code>bool</code></h1>\n<p>Just <code>#include &lt;stdbool.h&gt;</code>. The problem with reimplementing it is that it will now conflict with the definitions from <code>&lt;stdbool.h&gt;</code>, so someone using both <code>&lt;stdbool.h&gt;</code> and your string library will have a problem.</p>\n<p>Even worse, you are not using <code>bool</code>, <code>true</code> or <code>false</code> anywhere in your own code, so it was useless to define them to begin with.</p>\n<h1>Don't reimplement standard library functions</h1>\n<p>Why implement <code>cstrlen()</code> when you can just use the standard library's <a href=\"https://en.cppreference.com/w/c/string/byte/strlen\" rel=\"noreferrer\"><code>strlen()</code></a>? In fact, you call <code>strlen()</code> yourself inside <code>sstrreplace()</code>. Related to this:</p>\n<h1>The result of <code>strlen()</code> is a <code>size_t</code></h1>\n<p>An <code>int</code> might not be large enough to represent the size of all strings on your platform. The proper type to store the length of a string is <a href=\"https://en.cppreference.com/w/c/types/size_t\" rel=\"noreferrer\"><code>size_t</code></a>.</p>\n<h1>Buffer overflows</h1>\n<p>In <code>sstrappend()</code> the concatenation of two strings can be longer than <code>GLOBAL_MAX_CHAR_LIMIT</code>. You don't check against that limit when copying <code>temp</code> into <code>ret._str</code>. This means your program has a buffer overflow that might be <a href=\"https://en.wikipedia.org/wiki/Buffer_overflow#Exploitation\" rel=\"noreferrer\">exploitable</a>.</p>\n<p>Note that just ensuring you never write more than <code>GLOBAL_MAX_CHAR_LIMIT</code> characters into <code>ret._str</code> might fix the buffer overflow, but still is problematic. Consider you might want to create a full pathname by concatenating a directory name and a filename, and the result is longer than can be stored. If you return a truncated filename, the program might open the wrong file, which might itself be a security issue.</p>\n<h1>Incorrect copying of <code>sstring</code>s</h1>\n<p>In <code>sstrreplace()</code>, I see:</p>\n<pre><code>sstring _dup = _str;\n</code></pre>\n<p>This will not actually create a copy of the string itself, it will only create a copy of the pointer to the string, because afterwards the following is true: <code>_dup._str == _str._str</code>.</p>\n<h1>Inconsistent use of underscores</h1>\n<p>Some variables are prefixed with an underscore, some are not. I don't see any pattern to it. Also, some uses of leading underscores are <a href=\"https://stackoverflow.com/questions/25090635/use-and-in-c-programs\">reserved</a> in C, I recommend you don't use them as prefixes at all.</p>\n<h1>Work with the standard library instead of against it</h1>\n<p>The standard string functions in C leave a lot to be desired, so creating a library to add functionality like search-and-replace is great. But I recommend you just make it work with regular C strings, and have it return regular C strings. There are several ways in which you can do that:</p>\n<ul>\n<li>Have your function allocate memory for the result, and return a pointer to that memory after storing the result in it.</li>\n<li>Have the caller specify a pointer to and the size of a buffer where your function can write the results to.</li>\n</ul>\n<p>Also, just use standard library functions inside your own functions when appropriate. For example, I would rewrite <code>sstrappend()</code> like so:</p>\n<pre><code>char *sstrappend(const char *str1, const char *str2) {\n size_t len1 = strlen(str1);\n size_t len2 = strlen(str2);\n\n char *result = malloc(len1 + len2 + 1);\n if (!result) {\n /* Could not allocate memory, let the caller deal with it. */\n return NULL;\n }\n\n memcpy(result, str1, len1);\n memcpy(result + len1, str2, len2);\n result[len1 + len2] = '\\0';\n\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T13:45:17.637", "Id": "530768", "Score": "0", "body": "Your suggestion is truly great ! i use underscores for avoiding the confusion between global variable , temp variable or local variable used inside a function. You are right there are reserved keywords like __MINGW.. etc etc but i think that using custom names might not affect this. Yeah you are right about the buffer overflow and incorrect copying which has caused bugs [ i mentioned that making length of replacing string cause weird things to happen ]! but as u have said to use malloc, the user needs to use free(), else memory leak could happen, to avoid this i used my functions to do so!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T14:53:05.830", "Id": "530773", "Score": "0", "body": "But with your way you can only return fixed size buffers, that are either almost always bigger than necessary, or they are not big enough. I think that is more trouble than it is worth, and I personally would rather use C++ then, as this issue is nicely solved by [`std::string`](https://en.cppreference.com/w/cpp/string/basic_string#Example)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T15:01:36.647", "Id": "530774", "Score": "0", "body": "it wont! yeah i also would like to use c++, but wanna build it in c!. you can check the length of returned var using strlen() <- a default function!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T15:05:05.467", "Id": "530775", "Score": "0", "body": "if u see the function code line by line you would be surprised to see that i perform operations on char arrays[] and return char arrays[] stored in type substr, But in the code i get them assigned to sstring._str which is a pointer . see mystring.h\nThis is a conversion between char[] to char * without returning its address, so the length is not fixed. however, using char arrays[] need a fixed length which is the GLOBAL_MAX_CHAR_LIMIT contains" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T15:09:24.120", "Id": "530776", "Score": "0", "body": "I recommend that you try setting `GLOBAL_MAX_CHAR_LIMIT` to something low like 10, and then try to run your example program again, if possible using [Valgrind](https://en.wikipedia.org/wiki/Valgrind) to ensure writes out of bounds are caught as soon as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T15:10:48.300", "Id": "530777", "Score": "0", "body": "Also i fixed almost all of the issues you found. not used malloc() because i dont want the user to use free() after each function call. also have made a function cstr2sstr which would generally take any length of char arrays[] and convert them into sstrings!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T02:20:04.057", "Id": "530794", "Score": "0", "body": "i want to ask one question to you. as i am very new to stack overflow -> yes i am new :) and i updated my code to improve and made bug fixes. so for the review of the _updated_ code, should i create a new post or edit this post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:02:11.523", "Id": "530809", "Score": "0", "body": "Great! You should create a new post. You can then edit this post to add a link to the new post, but don't change anything else in this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T14:19:05.217", "Id": "530835", "Score": "0", "body": "@Pear *“there are reserved keywords like __MINGW.. etc etc but i think that using custom names might not affect this.”* — It is not that there exist some “reserved keywords”, but rather that the standard reserves identifiers that begin with an underscore and an uppercase letter or two underscores. It is illegal to use `__str` or `_Str` as a variable name. Because of that, most programmers prefer not to use any starting underscores at all. See https://en.cppreference.com/w/c/language/identifier" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T14:26:23.357", "Id": "530836", "Score": "0", "body": "@CrisLuengo That's incorrect. Not all identifiers starting with an underscore are reserved, and even if you do use them it is not illegal, rather it has undefined behavior. In fact, Pear's code is using leading underscores correctly. I would still *advise* not to use any leading underscores just to avoid having to navigate the tricky rules surrounding them." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T13:28:33.293", "Id": "269066", "ParentId": "269062", "Score": "8" } }, { "body": "<p>This declaration is a problem:</p>\n<blockquote>\n<pre><code> substr strinput();\n</code></pre>\n</blockquote>\n<p>Firstly, we should always specify what arguments a function takes (i.e. make it a <em>prototype</em>). In this case, it appears it should take no arguments, so write <code>(void)</code> as the argument list.</p>\n<p>Secondly, we've given it a name that's not ours to assign. Every identifier beginning with the three letters <code>str</code> is <em>reserved</em> for standard library use, so this is at risk of causing problems for programs that also include <code>&lt;string.h&gt;</code> (which is rather likely).</p>\n<hr />\n<p>Also on the subject of naming, many variables are declared beginning with <code>_</code>. Those are also reserved identifiers - keep clear of those, too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:19:56.660", "Id": "269087", "ParentId": "269062", "Score": "0" } } ]
{ "AcceptedAnswerId": "269066", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T09:55:31.777", "Id": "269062", "Score": "2", "Tags": [ "c", "strings" ], "Title": "User-friendly string struct and utility functions" }
269062
<p>So I implemented a program that takes an input file, two command strings and an output file to mimick the behaviour of running :</p> <p><code>&lt;input cmd1 -option | cmd2 -option &gt; output</code></p> <p>that's called like this :</p> <p><code>./pipe input &quot;cmd1 -opt&quot; &quot;cmd2 -opt&quot; output</code></p> <p>and I did without using the <code>wait</code> system call since while there are open file descriptors on the pipe I opened, the exec'd commands will wait for one another. that is the pipe takes care of coordination IIUC.</p> <p>But I feel like I am doing it wrong since it seems that people I using <code>wait()</code> out of convention. Is it reasonnable to think it is not necessary in my case since I only need the return value of the second command and the pipe ensures communication or am I missing something ? What else am I doing wrong in terms of code structure or style ?</p> <p>Here is my code :</p> <pre class="lang-c prettyprint-override"><code>#include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; #include &quot;pipex.h&quot; static const char g_cmd_not_found[] = { &quot;command not found: &quot; }; static const char g_empty_string[] = { &quot;The name of the input or output file cannot be an empty string\n&quot; }; static int open_or_die(char *filename, int flags, mode_t mode) { int fd; fd = open(filename, flags, mode); if (fd == -1) { if (*filename == '\0') write(STDERR_FILENO, g_empty_string, sizeof(g_empty_string)); else { write(STDERR_FILENO, &quot;pipex: &quot;, sizeof(&quot;pipex: &quot;)); perror(filename); } exit(EXIT_FAILURE); } return (fd); } static void pipe_or_die(int *pipe_fds) { int r; r = pipe(pipe_fds); if (r == -1) { write(STDERR_FILENO, &quot;pipex: &quot;, sizeof(&quot;pipex: &quot;)); perror(&quot;pipe&quot;); exit(EXIT_FAILURE); } } static void file_is_ok_or_die(char **cmdv, char **pathvar_entries) { if (access(cmdv[0], X_OK) == -1) { write(STDERR_FILENO, &quot;pipex: &quot;, sizeof(&quot;pipex: &quot;)); if (cmdv[0][0] != '/') { write(STDERR_FILENO, g_cmd_not_found, sizeof(g_cmd_not_found)); ft_puts_stderr(cmdv[0]); } else perror(cmdv[0]); free_null_terminated_array_of_arrays(cmdv); free_null_terminated_array_of_arrays(pathvar_entries); if (errno == ENOENT) exit(127); else if (errno == EACCES) exit(126); else exit(EXIT_FAILURE); } } void execute_pipeline(char *cmd_str, int read_from, int write_to, char **env) { char **pathvar_entries; char **cmdv; redirect_fd_to_fd(0, read_from); redirect_fd_to_fd(1, write_to); pathvar_entries = ft_split(get_path_var(env), ':'); cmdv = ft_split(cmd_str, ' '); if (!pathvar_entries || !cmdv) { write(STDERR_FILENO, &quot;pipex: &quot;, sizeof(&quot;pipex: &quot;)); perror(&quot;malloc&quot;); free_null_terminated_array_of_arrays(cmdv); free_null_terminated_array_of_arrays(pathvar_entries); exit(EXIT_FAILURE); } cmdv[0] = get_command_path(cmdv, get_pwd_var(env), pathvar_entries); file_is_ok_or_die(cmdv, pathvar_entries); execve(cmdv[0], cmdv, env); free_null_terminated_array_of_arrays(cmdv); free_null_terminated_array_of_arrays(pathvar_entries); } int main(int ac, char **av, char **envp) { int pipefd[2]; int child_pid; int infile_fd; int outfile_fd; if (ac != 5) print_usage_exit(); pipe_or_die(pipefd); child_pid = fork(); if (child_pid == -1) perror(&quot;fork&quot;); else if (child_pid == 0) { infile_fd = open_or_die(av[1], O_RDONLY, 0000); close(pipefd[0]); execute_pipeline(av[2], infile_fd, pipefd[1], envp); } else { outfile_fd = open_or_die(av[ac - 1], O_WRONLY | O_CREAT | O_TRUNC, 0666); close(pipefd[1]); execute_pipeline(av[3], pipefd[0], outfile_fd, envp); } return (EXIT_SUCCESS); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:54:03.383", "Id": "530815", "Score": "0", "body": "What's `\"pipex.h\"`? It seems to be essential for this program, but I don't know what I need to install to compile this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T15:53:31.717", "Id": "530840", "Score": "0", "body": "@TobySpeight It's just a global header. I haven't put all the functions I am using because it would be too big and some of them are not relevant to what mattered fr me to show you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T19:13:45.097", "Id": "530858", "Score": "0", "body": "You might like to post it for its own review - I'm wondering what's in `redirect_fd_to_fd()` that plain old `dup2()` doesn't do, for instance. And I'd like to know whether `ft_split()` is any better than passing the command string to `sh -c`, for a much simpler `exec()` setup." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:03:32.597", "Id": "530929", "Score": "0", "body": "@TobySpeight Thanks for the tip. This is an exercise and I am only allowed to use `execve`. Program usage is like `./pipex infile \"cmd1 -op1 -op2\" \"cm2 -op1 -op2\" outfile` which is why I have to use a split, to split the command string. `redirect_fd_to_fd` doesn't to much than `dup2` but for calling `close` before dup2." } ]
[ { "body": "<h1>Error handling</h1>\n<p>The way you handle error is quite unusual. Why use <code>write()</code> instead of <code>fprintf(stderr, ...)</code>? Why have some error messages stored in a variable like <code>g_empty_string</code>, but other errors messages are passes as literals, like <code>&quot;pipex: &quot;</code>? Why try to <code>open()</code> first and only if it fails check if <code>filename</code> is empty?</p>\n<p>On Linux, I recommend you use <a href=\"https://linux.die.net/man/3/err\" rel=\"noreferrer\"><code>err()</code></a> to report errors and exit with an error code in one go. For example:</p>\n<pre><code>static int open_or_die(const char *filename, int flags, mode_t mode)\n{\n if (!filename[0])\n err(EXIT_FAILURE, &quot;Empty filename&quot;);\n\n int fd = open(filename, flags, mode);\n\n if (fd == -1)\n err(EXIT_FAILURE, &quot;Error trying to open '%s'&quot;, filename);\n\n return fd;\n}\n</code></pre>\n<h1>Don't use <code>access()</code> to check if you can <code>execve()</code></h1>\n<p>Instead of first checking with <code>access()</code> if a file is executable before calling <code>execve()</code>, just call <code>execve()</code> unconditionally, and then just check the return value of <code>execve()</code>. Otherwise, you will have a <a href=\"https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use\" rel=\"noreferrer\">TOCTTOU bug</a>.</p>\n<pre><code>if (execve(cmdv[0], cmdv, env) == -1)\n err(EXIT_FAILURE, &quot;Could not execute '%s'&quot;, cmdv[0]);\n</code></pre>\n<p>Note that if <code>execve()</code> succeeds, it will never return, so there's no need to free anything afterwards.</p>\n<h1>Why you should <code>wait()</code></h1>\n<p>If you don't call <code>wait()</code>, your program will terminate when the second command terminates. However, consider that the first command might still be doing something. It will then continue in the background, but you won't have control over it anymore. Suppose you want to call <code>./pipe</code> twice, and the second call depends on results from the first call, then you would really want to ensure both processes of the first call have finished.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T12:52:45.653", "Id": "530766", "Score": "0", "body": "I would perhaps suggest that the OP use `pthreads` or `openMP` to create threads and join them instead of waiting and hoping that the work is done?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T13:31:36.163", "Id": "530767", "Score": "3", "body": "@upkajdt Unfortunately `execve()` replaces the whole process, not just one thread. Also see [this StackOverflow question](https://stackoverflow.com/questions/40296502/calling-execv-after-creating-a-thread)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T13:47:10.403", "Id": "530769", "Score": "0", "body": "@G.Sliepen You say \"It will then continue in the background, but you won't have control over it anymore.\" Indeed \n\nI can see that `./pipex /dev/stdin cat ls outfile` does not wait for input indeed but I am not sure why it is the case. Why can't the zombie `cat` read from stdin even though the main process is over ? It should still run right ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T14:46:16.007", "Id": "530772", "Score": "0", "body": "@cassepipe `cat` will still run but then the question is: what happens with `/dev/stdin` after `ls` exits? If I try to run that command in a shell, then after it finishes, the `cat` process is still running, but as soon as I press any key it exits with the error: `cat: -: Input/output error`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T16:18:12.970", "Id": "530780", "Score": "0", "body": "@G.Sliepen Not sure I understand but to answer your question I have no idea as to what happens to `/dev/stdin` after `ls` exits. I'd say nothing since I `open`ed the input file in the child process. When I run `</dev/stdin cat | ls` in a terminal it prints the ls output and then waits for input. I can enter one line, press `Return` and then I get back to the shell prompt, no error message." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T17:29:05.350", "Id": "530781", "Score": "0", "body": "@cassepipe Yes but the shell properly `wait()`s for the `cat` process to finish. What happens then is that `cat` reads the line from `stdin`, tries to write it to `stdout`, and then gets an `EPIPE` error because the `ls` process already terminated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T20:26:36.403", "Id": "530783", "Score": "0", "body": "@G.Sliepen Sorry to insist so much and thanks for your time but I want to get it. I understand the shell behaviour but what I don't understand is my program's behaviour and why it is not the same, Even though the parent returns with `ls`, the child, shouldn't the child be able to coninue its life that is, ask for input and then get its `EPIPE` just as the shell does without a `wait` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T21:25:01.703", "Id": "530785", "Score": "0", "body": "@cassepipe No, in your shell example, the shell waits for `cat` to finish and keeps its `stdin` redirected to the `cat` process. In your case, your program terminates early and then the shell that started your program wants its `stdin` back. I'm not sure though why it doesn't immediately get an `EPIPE` from `stdin`, but only when you try to type something in the shell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T16:40:47.150", "Id": "530845", "Score": "0", "body": "@G.Sliepen You say that \"the shell wants its `stdin` back\" but I quite don't understand that. The shell must have a file descriptor to `stdin` just as my orphan process does. There's nothing preventing my orphan `cat` to read from stdin as well the shell is there ?\nFrom what you've told me my guess is the following : When my program terminates, the shell prints the prompt to stdout and then both the orphan cat and the shell are reading from stdin. So cat also reads from stdin, gets an EPIPE and quietly becomes a zombie without anybody noticing. Does that make sense ?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T11:42:37.207", "Id": "269065", "ParentId": "269063", "Score": "7" } } ]
{ "AcceptedAnswerId": "269065", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T10:15:29.883", "Id": "269063", "Score": "4", "Tags": [ "c", "linux" ], "Title": "Implementing a pipe-like program without wait?" }
269063
<p>I'm trying to learn OOP with PHP (I know it's hard because It's not an OOP language). I'm rewriting my procedural code to OOP.<br>Please provide any feedback on my code, naming and file/folder structure.</p> <p>Structure:<br></p> <pre><code>\classes Procurement.php ProcurementDetails.php \services DatabaseService.php ProcurementService.php ProcurementsService.php \public Index.php \routes Procurements.php </code></pre> <p>classes\Procurement.php</p> <pre><code>&lt;?php class Procurement { public int $id; public null | array | string $group; public null | string $object_name; public null | string $procurement_type; public null | string | object $responsible_user; public null | string $announcement_time; public null | string $status; public null | string | object $creator; public function __construct() { if ($this-&gt;responsible_user) $this-&gt;responsible_user=json_decode($this-&gt;responsible_user); if ($this-&gt;group) $this-&gt;group=json_decode($this-&gt;group); if ($this-&gt;creator) $this-&gt;creator=json_decode($this-&gt;creator); } private function __set($name, $value) {} }; </code></pre> <p>classes\ProcurementDetails.php</p> <pre><code>&lt;?php require_once __DIR__ . '/Procurement.php'; class ProcurementDetails extends Procurement { public null | string $description; public null | int $sum; public null | string $procurement_method; public null | string | array $contact_person; public function __construct() { if ($this-&gt;contact_person) $this-&gt;contact_person=json_decode($this-&gt;contact_person); parent::__construct(); } } </code></pre> <p>services\DatabaseService.php</p> <pre><code>&lt;?php interface IDatabaseService { /** * * * @return PDO */ public function GetPDO(); } class DatabaseService implements IDatabaseService { /** * PDO object * * @var PDO */ private $DB; private $host = ''; private $dbname = ''; private $user = ''; private $pass = ''; /** * Creates the connection * * @return void */ public function __construct () { $this-&gt;DB = new PDO(&quot;mysql:host={$this-&gt;host};dbname={$this-&gt;dbname};charset=utf8mb4&quot;,$this-&gt;user,$this-&gt;pass); $this-&gt;DB-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this-&gt;DB-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $this-&gt;DB-&gt;setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false); } public function getPDO() { return $this-&gt;DB; } /** * __destruct * * @return void */ public function __destruct () { $this-&gt;DB=null; } } </code></pre> <p>services\ProcurementsService.php</p> <pre><code>&lt;?php require_once __DIR__ . '/../classes/Procurement.php'; require_once __DIR__ . '/ProcurementService.php'; interface IProcurementsService { /** * Returns all procurements from database * Procurement[] * * @return Procurement[] */ public function GetAllProcurements(); /** * GetById * * @param int $id * @return IProcurementService */ public function GetById(int $id); } class ProcurementsService implements IProcurementsService { private PDO $_db; /** * __construct * * @param PDO $db * @return void */ public function __construct(PDO $db) { $this-&gt;_db = $db; } /** * GetById * * @param int $x * @return IProcurementService */ public function GetById(int $id): IProcurementService { return new ProcurementService($id, $this-&gt;_db); } /** * Returns all procurements from database * Procurement[] * * @return Procurement[] */ public function GetAllProcurements(): iterable { $stmt=$this-&gt;_db-&gt;query(&quot;SELECT ....&quot;); return $stmt-&gt;fetchAll(PDO::FETCH_CLASS, 'Procurement'); } } </code></pre> <p>classes\ProcurementService.php</p> <pre><code>&lt;?php require_once __DIR__ . '/../classes/ProcurementDetails.php'; interface IProcurementService { /** * Returns more info about the procurement * * @param int $id * @return ProcurementDetails */ public function GetDetails(); public function GetFiles(); //Not implemented public function GetComments(); //Not implemented } class ProcurementService implements IProcurementService { private int $id; private PDO $_db; public function __construct(int $id, PDO $db) { $this-&gt;id = $id; $this-&gt;_db = $db; } /** * Returns more info about the procurement * * @param int $id * @return ProcurementDetails */ public function GetDetails(): ProcurementDetails { $stmt = $this-&gt;_db-&gt;prepare(&quot;SELECT with details....&quot;); $stmt-&gt;execute([$this-&gt;id]); return $stmt-&gt;fetchObject('ProcurementDetails'); } } </code></pre> <p>routes\Procurements.php</p> <pre><code>&lt;?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; require_once __DIR__ . '/../services/DatabaseService.php'; require_once __DIR__ . '/../services/ProcurementsService.php'; $app-&gt;get('Procurements', function(Request $request, Response $response) { $DB=new DatabaseService(); $ProcurementsService = new ProcurementsService($DB-&gt;getPDO()); $response-&gt;getBody()-&gt;write(json_encode($ProcurementsService-&gt;GetById(100)-&gt;GetDetails())); return $response-&gt;withHeader('content-type','application/json')-&gt;withStatus(200); }); </code></pre> <p>I felt like I got off track with OOP, so I don't have much code. BTW! I am using PHPSLIM.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T22:30:58.477", "Id": "530789", "Score": "4", "body": "If you down vote a question please leave a comment explaining why you down voted the question. I don't see anything here that suggests there should be a down vote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T05:05:16.400", "Id": "530798", "Score": "0", "body": "Just one quick note. The \"classes\" directory would better be called \"entities\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T05:46:42.213", "Id": "530801", "Score": "0", "body": "Thanks @pacmaninbw , was about to delete the post because of the downvote... slepic Ok, that makes more sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T06:59:21.817", "Id": "530805", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:00:37.530", "Id": "530806", "Score": "0", "body": "I didn't downvote, but I could understand how someone would downvote simply due to the title not following our guidelines. Moreover, the question's body also doesn't explain what the code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:00:56.893", "Id": "530808", "Score": "0", "body": "Code Review requires sufficient context for reviewers to understand how that code is used. Generic best practices are outside the scope of this site. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
[ { "body": "<p>Firstly, PHP is 100% an 'OOP' language. It provides you with all the necessary functionality to conform to all of the <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OOP principles</a>.</p>\n<p>Secondly, you should definitely familiarise yourself with the <a href=\"https://www.php-fig.org/psr/\" rel=\"nofollow noreferrer\">PHP Standards Recommendations (PSR)</a> as they will guide you in keeping everything inline with the standard conventions that PHP developers <strong>should</strong> follow when using the language.</p>\n<p>Ok, with those nitpicking points out of the way, let's have a quick look at your code.</p>\n<h2>Utilisation of Interfaces</h2>\n<p>It's good to see you have the foresight to use interfaces, but your utilisation of them is a little off. One of the benefits of using interfaces is to ensure anything that implements it, conforms to the contract it has defined. This allows us to write a piece of code and swap out the implementation of the interface with something else, knowing full well that we won't need to change any of the utilising code.</p>\n<p><strong>Example:</strong></p>\n<p>We declare an interface for connecting to our database. As we may decide to implement different types of database connections, we need to selectively identify functions that will be needed for all database implementations. <em>Note: I've kept it simple to ensure you grasp the concept, as opposed to what It's actually doing...</em></p>\n<pre><code>&lt;?php\n\nnamespace App\\EXAMPLE;\n\ninterface DatabaseInterface\n{\n public function connect();\n\n public function disconnect();\n\n //Any other functions\n}\n</code></pre>\n<p>This interface allows us to create different types of database connections and ensures the code we write to connect to the database, will remain untouched when swapping it out.</p>\n<p>Here's what an implementation may look like utilising PDO.</p>\n<pre><code>&lt;?php\n\nnamespace App\\EXAMPLE;\n\nclass PDODatabase implements DatabaseInterface\n{\n public function __construct(/* Any relevant params */)\n {\n }\n\n public function connect()\n {\n //Connect using PDO\n }\n\n public function disconnect()\n {\n //Disconnect\n }\n}\n</code></pre>\n<p>Now in the area where we connect to the database, we can use the interface to define the type and then use any of the interface functions.</p>\n<pre><code>&lt;?php\n\nnamespace App\\EXAMPLE;\n\nclass DatabaseService\n{\n private DatabaseInterface $database;\n \n public function __construct(DatabaseInterface $database)\n {\n $this-&gt;database = $database;\n }\n\n public function setup()\n {\n //Any setup that needs to be done\n $this-&gt;database-&gt;connect();\n }\n}\n</code></pre>\n<p>When we define the type as an interface, it allows us to swap out the implementation with another. For example, say we wanted to change our PDODatabase to a MySQLi connection. We could easily write a <code>MYSQLiDatabase.php</code> class which implements the <code>DatabaseInterface.php</code> and pass that into our <code>DatabaseService.php</code> constructor. And because any class that is passed into the construct <strong>must</strong> conform to the interface, we know that there will be a connect and a disconnect function. This means we don't need to touch anything in the <code>DatabaseService.php</code> class because we have written code that requires an interface instead of a concrete implementation.</p>\n<h2>Avoid Ambiguity</h2>\n<p>I see that you're declaring your class variables with union types, which is PHP 8 and above, but just because you can doesn't mean you should.</p>\n<pre><code>public null | array | string $group;\npublic null | string $object_name;\npublic null | string $procurement_type;\npublic null | string | object $responsible_user;\n</code></pre>\n<p>Imagine coming back to this code in 6-12 months time. Trying to debug this would be a nightmare because PHP is very forgiving when it comes to types. I would personally recommend to only one type with the allowance of null if it is required.</p>\n<pre><code>public ?string $group;\n</code></pre>\n<p>The same can be said for functions that return something. PHP developers are renowned for returning many different types (mixed) from functions. My personal opinion on this is that it should be avoided because it just over complicates everything later down the track.</p>\n<p>If you want to further your knowledge on building extendable code, I would highly recommend researching the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID Principles</a>. There are a lot of great resources out there to help you along the way. Start off small and get a good understanding of everything before getting too adventurous and biting off more than you can chew.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T06:29:51.043", "Id": "530802", "Score": "0", "body": "Thank you so much for the detailed answer! I tried to recreate the databaseservice, but what would I pass to the ProcurementService? Previously I passed the PDO object (connection)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:02:35.777", "Id": "530810", "Score": "0", "body": "That’s where you pass an interface as opposed to a concrete implementation. Code to interfaces, not concrete classes. PDO is a concrete implementation. This means that if you ever need to swap it out for something else, you’ll need to rewrite your ProcurementService class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:21:36.653", "Id": "530812", "Score": "0", "body": "So in the ProcurementService class I cannot access PDO directly? So I should create a query function in the DatabaseService class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:26:43.860", "Id": "530813", "Score": "1", "body": "Yeh why not give that a go. If you are using this to actually create something though, I’d suggest using some kind of framework instead because it’s much cleaner and you can focus on the actual program instead of designing your own core functionality. Designing your own framework is biting off more than you can chew in my opinion. You will learn very quickly why the structure and adhering to SOLID principles is important. If you use someone else’s framework, all the complex/advanced stuff has been thought of and implemented already. If you’re doing this to learn then go for it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T12:38:28.633", "Id": "530828", "Score": "1", "body": "There are old versions of PHP that I would not try to write OOP in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T19:43:01.707", "Id": "530860", "Score": "0", "body": "@pacmaninbw yeh you’re totally right. Didn’t want to go through the evolution of PHP lol" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T05:50:19.283", "Id": "269085", "ParentId": "269072", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T15:56:00.563", "Id": "269072", "Score": "4", "Tags": [ "php", "object-oriented" ], "Title": "PHP object oriented programming" }
269072
<p>I am supposed to write code for an assignment. The goal is to make 2 threads (which are objects of a class that implements runnable) take turns printing the alphabet. One of them prints upper case while the other one prints lower case. (they print only a single letter each turn, not the whole alphabet, just for clarification)</p> <p>I feel like my code is pretty self-explainatory but if I am wrong here and you have questions please ask them! I appreciate any help I can get for sure!</p> <p>The Code:</p> <pre><code>public class ABCPrinter implements Runnable { // --- Attributes --- private boolean bool_isUpperCase; public static boolean bool_Switch = true; // --- Constructor --- public ABCPrinter (boolean init_isUpperCase) { this.bool_isUpperCase = init_isUpperCase; } @Override public synchronized void run() { // custom run method for (char char_Counter = 'a'; char_Counter &lt;= 'z'; char_Counter++) { // count through the alphabet if (bool_isUpperCase){ // decide whether to print upper or lower case if(bool_Switch) { System.out.println(Character.toUpperCase(char_Counter)); System.out.println(&quot;\n----------------------&quot;); System.out.println(&quot;Message has been sent.&quot;); System.out.println(&quot;-----------------------&quot;); try { Thread.sleep(1000); } catch(Exception e) { System.out.println(&quot;\nInterrupted.&quot;); } bool_Switch = false; System.out.println(&quot;\n--------------------&quot;); System.out.println(&quot;Switch has been set to false.&quot;); System.out.println(&quot;-----------------------&quot;); try { Thread.sleep(1000); notifyAll(); System.out.println(&quot;\n--------------------&quot;); System.out.println(&quot;All threads have been notified.&quot;); System.out.println(&quot;-----------------------&quot;); Thread.sleep(1000); System.out.println(&quot;\n--------------------&quot;); System.out.println(&quot;Thread 1 is entering waiting state.&quot;); System.out.println(&quot;-----------------------&quot;); wait(); } catch (Exception e) { System.out.println(&quot;Process Interrupted.&quot;); } } else { try { System.out.println(&quot;Thread 1 is waiting.&quot;); wait(); } catch (Exception e) { System.out.println(&quot;Process Interrupted.&quot;); } } } else { if(!bool_Switch) { System.out.println(Character.toUpperCase(char_Counter)); System.out.println(&quot;\n----------------------&quot;); System.out.println(&quot;Message has been sent.&quot;); System.out.println(&quot;-----------------------&quot;); try { Thread.sleep(1000); } catch(Exception e) { System.out.println(&quot;\nInterrupted.&quot;); } bool_Switch = true; System.out.println(&quot;\n--------------------&quot;); System.out.println(&quot;Switch has been set to true.&quot;); System.out.println(&quot;-----------------------&quot;); try { Thread.sleep(1000); notifyAll(); System.out.println(&quot;\n--------------------&quot;); System.out.println(&quot;All threads have been notified.&quot;); System.out.println(&quot;-----------------------&quot;); Thread.sleep(1000); wait(); System.out.println(&quot;\n--------------------&quot;); System.out.println(&quot;Thread 2 is entering waiting state.&quot;); System.out.println(&quot;-----------------------&quot;); } catch (Exception e) { System.out.println(&quot;Process Interrupted.&quot;); } } else { try { System.out.println(&quot;Thread 2 is waiting.&quot;); wait(); } catch (Exception e) { System.out.println(&quot;Process Interrupted.&quot;); } } } } } } </code></pre> <p>The main where I execute everything:</p> <pre><code>public class Main2 { public boolean bool_switch; public static void main(String[] args){ ABCPrinter p1 = new ABCPrinter(true); ABCPrinter p2 = new ABCPrinter(false); Thread thr_UpperCase = new Thread(p1); Thread thr_LowerCase = new Thread(p2); thr_UpperCase.start(); thr_LowerCase.start(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T16:47:02.093", "Id": "530951", "Score": "0", "body": "Just a suggestion. Please try to follow the java standard naming conventions when using java to solve a problem. Use camel case when naming any variable. Dont use underscores." } ]
[ { "body": "<p>Welcome to code review! :)</p>\n<p>Here are a few tips to improve your code:</p>\n<ul>\n<li><p>Empty lines have a meaning. Do not just spam emtpy lines every where, as that makes the code harder to read. By removing most of the empty lines, I have reduced you code's number of lines to almost have. Empty lines are usually used to separate pieces of code with different concerns.</p>\n</li>\n<li><p>DRY (Don't Repeat Yourself).</p>\n<ol>\n<li><p>Your code is filled with the same structure of try-sleep-catch-print. Then, if your actually want to make the thread sleep (which for learning purposes you can do, but usually you wouldn't), then extract that logic into a method.</p>\n</li>\n<li><p>The logic for thread 1 and thread 2 are exactly the same, changing a few strings. Again, extract the logic to a common method.</p>\n</li>\n</ol>\n</li>\n<li><p>Use consistent casing. In Java, <a href=\"https://techterms.com/definition/camelcase\" rel=\"nofollow noreferrer\">camelCase</a> is usually used to name variables.</p>\n</li>\n<li><p>Using a static variable for thread communication is not thread-safe. At the very least, you could use an <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/concurrent/atomic/AtomicBoolean.html\" rel=\"nofollow noreferrer\">AtomicBoolean</a>.</p>\n</li>\n<li><p>I would separate the thread communication logic from the actual letter printing.</p>\n</li>\n</ul>\n<p>Putting all this together, here is a refactor using queues to synchronise the threads:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class LetterPrinter {\n\n private final char end;\n private char currentLetter;\n\n public LetterPrinter(char start, char end) {\n if (start &gt; end) {\n throw new IllegalArgumentException(&quot;Start letter cannot be larger than end letter&quot;);\n }\n this.currentLetter = start;\n this.end = end;\n }\n\n public boolean hasNext() {\n return currentLetter &lt;= end;\n }\n\n public void printNext() {\n System.out.println(currentLetter);\n currentLetter++;\n }\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.concurrent.BlockingQueue;\n\npublic abstract class LetterRunnable implements Runnable {\n protected final BlockingQueue&lt;Integer&gt; queue;\n protected final LetterPrinter letterPrinter;\n\n public LetterRunnable(BlockingQueue&lt;Integer&gt; queue, LetterPrinter letterPrinter) {\n this.queue = queue;\n this.letterPrinter = letterPrinter;\n }\n\n @Override\n public final void run() {\n while (letterPrinter.hasNext()) {\n try {\n printNextLetter();\n } catch (InterruptedException e) {\n return;\n }\n }\n }\n\n protected abstract void printNextLetter() throws InterruptedException;\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.concurrent.BlockingQueue;\n\npublic class UpperCaseRunnable extends LetterRunnable {\n\n public UpperCaseRunnable(BlockingQueue&lt;Integer&gt; queue) {\n super(queue, new LetterPrinter('A', 'Z'));\n }\n\n @Override\n protected void printNextLetter() throws InterruptedException {\n letterPrinter.printNext();\n queue.put(0); // notify\n queue.put(0); // wait\n }\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.concurrent.BlockingQueue;\n\npublic class LowerCaseRunnable extends LetterRunnable {\n\n public LowerCaseRunnable(BlockingQueue&lt;Integer&gt; queue) {\n super(queue, new LetterPrinter('a', 'z'));\n }\n\n @Override\n protected void printNextLetter() throws InterruptedException {\n queue.take(); // wait\n letterPrinter.printNext();\n queue.take(); // notify\n }\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\n\npublic class Main {\n public static void main(String[] args) throws InterruptedException {\n\n BlockingQueue&lt;Integer&gt; queue = new ArrayBlockingQueue&lt;&gt;(1);\n\n UpperCaseRunnable upperCaseRunnable = new UpperCaseRunnable(queue);\n LowerCaseRunnable lowerCaseRunnable = new LowerCaseRunnable(queue);\n\n Thread threadUpperCase = new Thread(upperCaseRunnable);\n Thread threadLowerCase = new Thread(lowerCaseRunnable);\n\n threadUpperCase.start();\n threadLowerCase.start();\n\n threadUpperCase.join();\n threadLowerCase.join();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T22:34:34.197", "Id": "530790", "Score": "1", "body": "The answer was very good until you provided an alternate solution. Don't do someones home work for them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T08:54:04.330", "Id": "530816", "Score": "0", "body": "Thanks for your answer!\nI am only a second-year so I gotta say that your answer is quite intimidating haha. I have never seen half of the code you used. I will research it and try to understand it though. \nI hope you don't mind if I come back at you with any questions. Because I predict there will be some." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T20:27:51.963", "Id": "269079", "ParentId": "269073", "Score": "3" } }, { "body": "<p>My word! People seem to go for complexity here, don't they? (and verbosity).</p>\n<p>This problem should be simple enough. I won't write any code, as it's someone else's homework, but here's my thinking.</p>\n<p>You need two threads. Each needs to know two things:</p>\n<ol>\n<li>Am I outputting upper or lower case?</li>\n<li>What is the other thread?</li>\n</ol>\n<p>The main loop of each is this</p>\n<ul>\n<li>wait()</li>\n<li>when notified, output the next letter in the appropriate case</li>\n<li>notify the other thread</li>\n<li>If we haven't run out of letters, return to the initial wait()</li>\n<li>When we have run out, end the thread by leaving the run() method</li>\n</ul>\n<p>The main method simply needs to create these threads, start() one of them and join() to both.</p>\n<p>This is somewhat crude, and I have a strong suspicion that there's a potential timing window in the case where a freshly woken thread attempts to wake the other before the other reaches the wait(). This could be dealt with by adding an &quot;allowed to proceed&quot; boolean to each Runnable, which is checked and cleared by the thread itself, but set (in a synchronized block) by the other thread before notifying it.</p>\n<p>I can't see value in using a queue for synchronization. Perhaps I missed Miguel's point somehow. If you wanted to use java.util.concurrency functionality, probably something like a Phaser would be a reasonable choice, but basic wait/notify seems sufficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T12:44:40.573", "Id": "530829", "Score": "0", "body": "Hi Mark! I did not know about Pashers, so it would probably have been a better option. I just did not want one thread start the other to avoid having that direct dependency. Instead, I just wanted the caller (main) to be the one knowing the dependy, and the threads just need to know they have to syncronise with some other thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T09:26:30.343", "Id": "530902", "Score": "0", "body": "Hi Miguel. If I needed to expand this beyond two threads, provided there was a strict sequencing, I'd probably have a shared circular list of threads, with the same sort of wait/notify mechanism, so each thread simply passed control to the next in the list." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:06:19.830", "Id": "269092", "ParentId": "269073", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T16:07:21.540", "Id": "269073", "Score": "4", "Tags": [ "java", "multithreading", "concurrency" ], "Title": "2 Threads taking turns printing the alphabet" }
269073
<p>I play a lot of old-school western CRPGs, and most of them (if not all) require the player to generate an avatar at the start of a new game, including naming the character (with names that will never be pronounced).</p> <p>I want my character to have the most unique and beautiful name, with as few namesakes as possible and make her have absolutely meaningless name, so that she can define the meaning of her name herself, without being overshadowed by the meaning of the name in any way.</p> <p>Naturally the name has to be random, though of course <code>random.sample(ascii_lowercase, 7)</code> isn't a valid solution, the result must be pronounceable.</p> <p>I always have huge trouble making up the names, I can't make up anything devoid of meaning by myself, because humans are fundamentally incapable of choosing randomly, choice is a conscious act therefore the outcome is inherently deterministic. Therefore the use of computers is required.</p> <p>Thankfully most these games have built-in random name generator's, for those without RNG I use online RNG. The results of the RNGs most of the time sadly seemed way too common, they seemed to be just choosing two random strings from two predefined lists instead of actually generating them...</p> <p>I always spent dozens of minutes hitting the generate button hundreds of times just trying to find the right name, and I am very not impressed...</p> <p>So I am inspired to write a program to actually generate pronounceable gibberish...</p> <p>I have chosen the Markov chain process, though maybe I will throw in Markov Chain Monte Carlo, Neural Network, Minimax and whatnot along the way just for the best result. I am still learning though I understand their basics.</p> <p>In simple terms, Markov Chain involves choosing an initial state randomly from a list of states with weights, then choose a state that can come after the first state with weights, and repeat...</p> <p>Anyway this is the script that analyzes the corpus to generate the statistical data necessary for the generation and store the data...</p> <p>It is supposed to take an inputted corpus and output the data in a database, but for now it is non-interactive and uses the default corpus, and doesn't output to a database... But it is working properly, although performance isn't very impressive.</p> <p>I have pulled 105230 words from GCIDE and I have done quite a lot analyses.</p> <p>I have identified valid chunks (common letter groups that can appear in a syllable rather than must be in two separate syllables) between lengths 1 and 3 (inclusive), the chunks are generated using another script and that script is not for review, the chunks are required by this script.</p> <p>I have counted the lengths of the words (how many words are n letters long, n must be an integer greater than 3 and the count must be greater than or equal to 50).</p> <p>I have counted the starting letters of the words.</p> <p>I have counted how many times letter b is the second letter if letter a is the first letter.</p> <p>I have counted how many times letter b follows letter a in all positions.</p> <p>I have counted the starting chunks of the words (using <code>re</code>, the pattern is constructed in such a way so that the longer parts come before shorter parts).</p> <p>I have counted how many times chunk b is the second chunk if chunk a is first.</p> <p>I have counted how many times chunk b follows chunk a in all positions.</p> <p>And I have counted the occurrences of states; in this usage, state means a sequence of three groups (letter or chunk) immediately following each other, I have counted letter and chunk states occurring at first, second and any positions (6 groups of data).</p> <p>And I did more than just the above. I filtered the data using a number of conditions, each producing more than one set of new data.</p> <p>The conditions include:</p> <ul> <li><p>alternate: letter condition, in this condition a vowel can only be adjacent to a consonant and vice versa, y is a semi-vowel and can be adjacent to any letter except itself.</p> </li> <li><p>singlecon: letter condition, a vowel and y can be adjacent to any letter, but consonant letters can't be adjacent to each other.</p> </li> <li><p>safe: chunk condition, similar to above, chunks consisting only of consonant letters can't be adjacent to each other.</p> </li> </ul> <p>I used the above to create 9 new sets of data.</p> <p>I intend to make my program support 4 modes, including each of the above conditions plus no condition.</p> <p>The intended execution flow is: choose randomly with weights from the dataset that contains the first parts valid for the condition, then the second part, then any part, using the states as basis for scoring... (sorry it is really hard for me to explain this process in English, but I can write the code).</p> <p>I did also sort nested dict and eliminate infrequent entries and a few other things...</p> <p>Here is the code:</p> <pre class="lang-py prettyprint-override"><code>import json import re import time from ast import literal_eval from collections import Counter, defaultdict from pathlib import Path start = time.time() DIRECTORY = Path(__file__).parent INCLUDIR = DIRECTORY / 'include' DATADIR = DIRECTORY / 'data' DATADIR.mkdir(exist_ok=True) def read_list(path): return path.read_text().splitlines() def read_dict(path): return json.loads(path.read_text()) def export(var, path): (DATADIR / path).write_text(json.dumps(var, indent=4)) def represent(dic): ls = [' ' * 4 + repr(k) + ': ' + repr(v) for k, v in sorted(dic.items())] return '{\n' + ',\n'.join(ls) + '\n}' CONSONANT = '[b-df-hj-np-tv-xz]' CORPUS = read_list(INCLUDIR / 'gcide_dict.txt') CHUNKS = read_list(INCLUDIR / 'chunks.txt') IS_CONSONANT = read_dict(INCLUDIR / 'is_consonant.json') IS_VOWEL = read_dict(INCLUDIR / 'is_vowel.json') CONSONANT_CHUNKS = {k: bool(re.match('^'+CONSONANT+'+$', k)) for k in sorted(CHUNKS)} UNITS = re.compile('(' + '|'.join(i[::-1] for i in sorted(CHUNKS, key=lambda x: -len(x))) + ')') CONSONANTS = [i for i in sorted(CHUNKS) if re.match('^'+CONSONANT+'+$', i)] STARTING_CONSONANTS = Counter([m.group() for w in CORPUS if (m := re.match('^'+CONSONANT+'+', w))]) STARTING_CONSONANTS = {k: v for k, v in sorted(STARTING_CONSONANTS.items()) if v &gt;= 20} export(STARTING_CONSONANTS, 'starting_consonants.json') export(CONSONANT_CHUNKS, 'consonant_chunks.json') (DATADIR / 'consonants.txt').write_text('\n'.join(CONSONANTS)) def alternate(x, y): return IS_VOWEL[x] != IS_VOWEL[y] def singlecon(x, y): return IS_CONSONANT[x] + IS_CONSONANT[y] &lt; 2 def safe(x, y): return CONSONANT_CHUNKS[x] + CONSONANT_CHUNKS[y] &lt; 2 alternate_triplets = { (0, 0.5, 0), (0, 0.5, 1), (0, 1, 0), (0, 1, 0.5), (0.5, 0, 0.5), (0.5, 0, 1), (0.5, 1, 0), (0.5, 1, 0.5), (1, 0, 0.5), (1, 0, 1), (1, 0.5, 0), (1, 0.5, 1) } singlecon_triplets = {(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0), (1, 0, 1)} def alternate_triplet(tri): return tuple(IS_VOWEL[i] for i in tri) in alternate_triplets def singlecon_triplet(tri): return tuple(IS_CONSONANT[i] for i in tri) in singlecon_triplets def safe_triplet(tri): return tuple(CONSONANT_CHUNKS[i] for i in tri) in singlecon_triplets def regularize(dic, lim): last = False while True: want_loop = False for k, v in list(dic.items()): if isinstance(v, dict): regularize(v, lim) if isinstance(v, int): if v &lt; lim: length = len(k) if length == 1 and last: dic.pop(k) if length &gt; 1: want_loop = True dic.setdefault(k[:-1], 0) dic[k[:-1]] += v dic.pop(k) if last: break if not want_loop: last = True for k, v in list(dic.items()): if not v: dic.pop(k) def sort_dict(dic): d = dict() for k, v in sorted(dic.items()): if isinstance(v, dict): d[k] = dict(sorted(v.items(), key=lambda x: (-x[1], x[0]))) else: d[k] = v return d chunk_first = Counter() letter_first = Counter() chunk_triplet_first = Counter() chunk_triplet_second = Counter() chunk_triplet_sequence = Counter() chunk_triplet_terminal = Counter() letter_triplet_first = Counter() letter_triplet_second = Counter() letter_triplet_sequence = Counter() letter_triplet_terminal = Counter() chunk_second = defaultdict(Counter) chunk_sequence = defaultdict(Counter) letter_second = defaultdict(Counter) letter_sequence = defaultdict(Counter) chunk_terminal = defaultdict(Counter) letter_terminal = defaultdict(Counter) word_length = Counter() for word in CORPUS: letter_first[word[0]] += 1 len1 = len(word) word_length[len1] += 1 parts = [i[::-1] for i in UNITS.findall(word[::-1])][::-1] chunk_first[parts[0]] += 1 len2 = len(parts) if len1 &gt;= 2: a, b = word[:2] letter_second[a][b] += 1 a, b = word[-2:] letter_terminal[a][b] += 1 for a, b in zip(word, word[1:]): letter_sequence[a][b] += 1 if len1 &gt;= 3: key = word[:3] letter_triplet_first[key] += 1 key = word[-3:] letter_triplet_terminal[key] += 1 if len1 &gt;= 4: key = word[1:4] letter_triplet_second[key] += 1 for key in [word[i:i+3] for i in range(len1-2)]: letter_triplet_sequence[key] += 1 if len2 &gt;= 2: a, b = parts[:2] chunk_second[a][b] += 1 a, b = parts[-2:] chunk_terminal[a][b] += 1 for a, b in zip(parts, parts[1:]): chunk_sequence[a][b] += 1 if len2 &gt;= 3: key = tuple(parts[:3]) chunk_triplet_first[key] += 1 key = tuple(parts[-3:]) chunk_triplet_terminal[key] += 1 if len2 &gt;= 4: key = tuple(parts[1:4]) chunk_triplet_second[key] += 1 for key in [parts[i:i+3] for i in range(len2-2)]: key = tuple(key) chunk_triplet_sequence[key] += 1 for i in (chunk_first, chunk_second, chunk_sequence): regularize(i, 10) for k1, v1 in chunk_terminal.items(): for k2, v2 in list(v1.items()): if v2 &lt; 10: chunk_terminal[k1].pop(k2) chunk_terminal = {k: v for k, v in chunk_terminal.items() if v} for i in (letter_second, letter_sequence, letter_terminal): regularize(i, 20) chunk_second = {k: chunk_second[k] for k in sorted(set(chunk_first) &amp; set(chunk_second))} chunk_first = {k: sum(chunk_second[k].values()) for k in chunk_first if k in chunk_second} assert not set(j for i in chunk_second.values() for j in i.keys()) - set(chunk_sequence) assert not set(j for i in chunk_second.values() for j in i.keys()) - \ set(j for i in chunk_sequence.values() for j in i.keys()) assert not set(chunk_first) ^ set(chunk_second) assert not set(chunk_second) - set(chunk_sequence) terminal = set(j for i in chunk_sequence.values() for j in i.keys()) - set(chunk_sequence) terminal = sorted(terminal) (DATADIR / 'terminal.txt').write_text('\n'.join(terminal)) word_length = {k: v for k, v in sorted( word_length.items()) if k &gt; 3 and v &gt;= 50} (DATADIR / 'word_length.repr').write_text(represent(word_length)) def sort_and_export(var, file): var = sort_dict(var) export(var, file) batch1 = [ (chunk_first, 'chunk_first.json'), (chunk_second, 'chunk_second.json'), (chunk_sequence, 'chunk_sequence.json'), (chunk_terminal, 'chunk_terminal.json'), (letter_first, 'letter_first.json'), (letter_second, 'letter_second.json'), (letter_sequence, 'letter_sequence.json'), (letter_terminal, 'letter_terminal.json') ] for a, b in batch1: sort_and_export(a, b) def filter_sort_export(var, file, lim): var = {k: v for k, v in var.items() if v &gt;= lim} var = sort_dict(var) if file.endswith('.json'): export(var, file) elif file.endswith('.repr'): (DATADIR / file).write_text(represent(var)) batch2 = [ (chunk_triplet_first, 'chunk_triplet_first.repr', 10), (chunk_triplet_second, 'chunk_triplet_second.repr', 10), (chunk_triplet_sequence, 'chunk_triplet_sequence.repr', 10), (chunk_triplet_terminal, 'chunk_triplet_terminal.repr', 10), (letter_triplet_first, 'letter_triplet_first.json', 20), (letter_triplet_second, 'letter_triplet_second.json', 20), (letter_triplet_sequence, 'letter_triplet_sequence.json', 20), (letter_triplet_terminal, 'letter_triplet_terminal.json', 20), ] for a, b, c in batch2: filter_sort_export(a, b, c) def postprocess(infile, outfile, condition, lim): var = read_dict(DATADIR / infile) result = defaultdict(dict) for k1, v1 in var.items(): for k2, v2 in v1.items(): if condition(k1, k2): result[k1][k2] = v2 regularize(result, lim) result = sort_dict(result) export(result, outfile) batch3 = [ ('letter_second.json', 'alternate_second.json', alternate, 20), ('letter_sequence.json', 'alternate_sequence.json', alternate, 20), ('letter_terminal.json', 'alternate_terminal.json', alternate, 20), ('letter_second.json', 'singlecon_second.json', singlecon, 20), ('letter_sequence.json', 'singlecon_sequence.json', singlecon, 20), ('letter_terminal.json', 'singlecon_terminal.json', singlecon, 20), ('chunk_second.json', 'safe_chunk_second.json', safe, 10), ('chunk_sequence.json', 'safe_chunk_sequence.json', safe, 10), ('chunk_terminal.json', 'safe_chunk_terminal.json', safe, 10) ] for a, b, c, d in batch3: postprocess(a, b, c, d) def postprocess_triplet(infile, condition, outfile): var = read_dict(DATADIR / infile) var = {k: v for k, v in var.items() if condition(k)} export(var, outfile) batch4 = [ ('letter_triplet_first.json', alternate_triplet, 'alternate_triplet_first.json'), ('letter_triplet_first.json', singlecon_triplet, 'singlecon_triplet_first.json'), ('letter_triplet_second.json', alternate_triplet, 'alternate_triplet_second.json'), ('letter_triplet_second.json', singlecon_triplet, 'singlecon_triplet_second.json'), ('letter_triplet_sequence.json', alternate_triplet, 'alternate_triplet_sequence.json'), ('letter_triplet_sequence.json', singlecon_triplet, 'singlecon_triplet_sequence.json'), ('letter_triplet_terminal.json', alternate_triplet, 'alternate_triplet_terminal.json'), ('letter_triplet_terminal.json', singlecon_triplet, 'singlecon_triplet_terminal.json') ] for a, b, c in batch4: postprocess_triplet(a, b, c) def postprocess_chunk_triplet(infile): var = literal_eval((DATADIR / infile).read_text()) var = {k: v for k, v in var.items() if safe_triplet(k)} (DATADIR / ('safe_' + infile)).write_text(represent(var)) for i in ['chunk_triplet_first.repr', 'chunk_triplet_second.repr', 'chunk_triplet_sequence.repr', 'chunk_triplet_terminal.repr']: postprocess_chunk_triplet(i) end = time.time() print(end-start) </code></pre> <p>I have packed all the necessary files and the outputs and uploaded to <a href="https://drive.google.com/file/d/1PhHDIOUge8qEHPLNVCJfelD2LLM7Ndbf/view?usp=sharing" rel="nofollow noreferrer">Google Drive</a>.</p> <p>I want to know how the performance can be improved. Currently it takes around 8 seconds to complete, and I want it to come down to around 3 seconds.</p> <p>I want to to how to eliminate code duplication and repetition. Due to the nature of the script a lot of things are repeated, but I have done my best to reuse the functions, but I think more things can be enclosed in functions and reused.</p> <p>I want to know whether my coding style and code format can be improved.</p> <p>Lastly and most importantly, I want to know how I should store all these data; my data are mostly nested dicts but they are in fact <code>dict</code>s of <code>Counter</code>s (though I used <code>defaultdict</code> for convenience), and the dictionary keys in my data can be <code>int</code>s and <code>tuple</code>s, and I would like to store the data while keeping their data types, HUMAN READABLY (I need to read the output), so <code>pickle</code> and <code>dill</code> and the like are out of the question.</p> <p>I mostly use <code>json</code> as you can see. I am OK with <code>Counter</code> becoming <code>dict</code> (thus losing advantage of being a <code>Counter</code>), <code>int</code> becoming <code>str</code> is absolutely not OK and there is no way to store <code>tuple</code> keys in json files, so I have written my own serialization function based on <code>repr</code>, because I don't know how to do <code>repr</code> with indentation yet, and the data is de-serialized using <code>ast.literal_eval</code>...</p> <p>I want my data be stored more structurally and organized, retaining its datatypes and humanreadableness; what are my options? I don't like CSV and it doesn't keep data types, I have used MySQL and datatypes are changed on retrieval, I don't know about sqlite3...</p> <p>What tools can store these data in a more organized way while retaining the identity and readability?</p> <hr /> <h2>Update</h2> <p>I have managed to update thirteen variables in a gigantic nested <code>for</code> loop, and now the code takes around 3.5 seconds to complete, and I have renamed the output files so that files of the same mode are sorted next to each other, I have also reorganized the folder structure of the module, I still don't know how to store all these data more structurally though...</p> <hr /> <h2>Update1</h2> <p>I have re-implemented the pattern matching algorithm using this:</p> <pre class="lang-py prettyprint-override"><code># sort parts by length with longer parts coming first to ensure longer parts are matched first parts = sorted(CHUNKS, key=lambda x: -len(x))) # reverse the individual parts parts = [i[::-1] for i in parts] # compile regex pattern UNITS = re.compile('(' + '|'.join(parts) + ')') # reverse the word, find reversed parts and reverse each part back, and reverse the order of parts [i[::-1] for i in UNITS.findall(word[::-1])][::-1] </code></pre> <p>This significantly improves the accuracy of the algorithm.</p> <p>I have also expanded the definition of the chunks, and counted last letter, last chunk, last letter states and last chunk states and variants.</p> <p><a href="https://drive.google.com/file/d/1tDYrpgmXNEkszMZ_vXusqeBHD0wXq2W9/view?usp=sharing" rel="nofollow noreferrer">Google Drive link updated</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T04:45:25.157", "Id": "530797", "Score": "0", "body": "I've just chosen the path of least resistance and use a single character for the names, like 'I', 'Z' etc. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T22:31:07.757", "Id": "530875", "Score": "0", "body": "The first problem I see is that you've probably written two pages to explain your code, yet your code itself contains NO comments or documentation. If you think it needs explanation, add the explanation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T23:11:50.300", "Id": "530878", "Score": "0", "body": "The second problem I see is that you are still working on this code, based on the two updates since you posted it yesterday. Stop, please. If you post code, we can review it. If you post a series of thoughts, updates, and patches, it no longer fits the format of the site (and, no one will want to review it either--at some point you'll be told to delete the question and re-post the latest version). Don't worry about having done it so far, since I'm sure you didn't know--just letting you know it makes it very hard to review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T16:28:10.667", "Id": "269074", "Score": "3", "Tags": [ "python", "python-3.x", "parsing", "statistics", "markov-chain" ], "Title": "Python program that analyzes a corpus for randomword generation" }
269074
<p>I have solved <a href="https://www.codechef.com/problems/REDALERT" rel="nofollow noreferrer">this problem from the CodeChef platform</a> using the Python prorgamming language</p> <p>Here is the code:</p> <pre><code>test_cases = int(input()) for _ in range(test_cases): n, d, h = [int(x) for x in input().split()] rain_amounts = [int(y) for y in input().split()] red_alert = False water_level = 0 for rain_amount in rain_amounts: if rain_amount &gt; 0: water_level += rain_amount if rain_amount == 0: if water_level &lt; d: water_level = 0 else: water_level -= d if water_level &gt; h: red_alert = True if red_alert: print(&quot;YES&quot;) else: print(&quot;NO&quot;) </code></pre> <p>My solution received an ACCEPTED judgement and I would like feedback on my implementation, coding style, and everything in between.</p> <p>Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T22:15:24.667", "Id": "530787", "Score": "3", "body": "Please make the question self contained. E.g include the information from the link =)" } ]
[ { "body": "<p>I like your code =) What it does is clear, and your variable names and spacing is correct. There is not much of an algorithm to speak of here, so instead I will focus on structure.</p>\n<p>It is always a good idea to separate inputs from actions. This can be done using a if_main guard, and clear functions. Something like this passes the first test case</p>\n<pre><code>def is_red_alert(precipitation, drainage, waterlogging):\n\n water_level = 0\n\n for rain_today in precipitation:\n if rain_today &gt; 0:\n water_level += rain_today\n if rain_today == 0:\n if rain_today &lt; drainage:\n water_level = 0\n else:\n water_level -= drainage\n return water_level &gt; waterlogging\n\n\nif __name__ == &quot;__main__&quot;:\n test_cases = int(input())\n\n for _ in range(test_cases):\n _, drainage, waterlogging = [int(x) for x in input().split()]\n precipitation = [int(y) for y in input().split()]\n\n if is_red_alert(precipitation, drainage, waterlogging):\n print(&quot;YES&quot;)\n else:\n print(&quot;NO&quot;)\n</code></pre>\n<p>Otherwise the code is the same. I will change the name of a few of the variables throughout as naming is hard.. =) We can tidy up the logic a bit using <code>min</code> and <code>max</code>. Something like this</p>\n<pre><code>for day in precipitation:\n accumulation += max(0, day)\n if day == 0:\n accumulation -= min(drainage, accumulation)\n elif accumulation &gt; limit:\n return True\nreturn accumulation &gt; limit\n</code></pre>\n<p>Firstly we do not have to check if the precipitation of the current day is negative. We can just use <code>max(0, today)</code> [Yes, this <em>is</em> slower].\nInstead of setting the water level (or in my case the accumulation of water) we can just subtract the smallest number between <code>drainage</code> and <code>accumulation</code>. I will let you go through to check out what happens when <code>drainage &lt; accumulation</code>, and <code>drainage &gt; accumulation</code>. Similarly we only need to check if we are above the limit if the rain today is greater than zero. Otherwise there is no change.</p>\n<p>We can also add some descriptive typing hints to further explain what is going on in the code</p>\n<h2>Code</h2>\n<pre><code>from typing import Annotated\n\nPrecipitation = Annotated[\n list[int],\n &quot;The amount water released from clouds in the form of rain, snow, or hail over n days&quot;,\n]\nDrainage = Annotated[\n int,\n &quot;The amount of water removed on a dry day&quot;,\n]\nWaterMax = Annotated[\n int,\n &quot;The total amount of water before triggering an warning&quot;,\n]\n\n\ndef is_red_alert(\n precipitation: Precipitation, drainage: Drainage, limit: WaterMax\n) -&gt; bool:\n &quot;Returns True if the citys water level becomes larger than a given limit&quot;\n\n accumulation = 0\n\n for day in precipitation:\n accumulation += max(0, day)\n if day == 0:\n accumulation -= min(drainage, accumulation)\n elif accumulation &gt; limit:\n return True\n return accumulation &gt; limit\n\n\nif __name__ == &quot;__main__&quot;:\n test_cases = int(input())\n\n for _ in range(test_cases):\n _, drainage, water_limit = list(map(int, input().split()))\n precipitation = list(map(int, input().split()))\n\n if is_red_alert(precipitation, drainage, water_limit):\n print(&quot;YES&quot;)\n else:\n print(&quot;NO&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T02:43:59.440", "Id": "530795", "Score": "0", "body": "Thanks for such a comprehensive and thoughtful review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T23:51:52.057", "Id": "269080", "ParentId": "269078", "Score": "1" } } ]
{ "AcceptedAnswerId": "269080", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T20:11:20.537", "Id": "269078", "Score": "2", "Tags": [ "python", "programming-challenge" ], "Title": "CodeChef - Red Alert" }
269078
<p>How can I shorten my code for this? There are 6 variable sets of numbers, someone picks a number between 1-63, if their number is in a set, you add the first number of the list to the magic number variable. If it is not, you don't add anything, and move to the next set. I have used multiple while loops, but want a more effective way to do this.</p> <pre><code>number_set1 = [2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31, 34, 35, 38, 39, 42, 43, 46, 47, 50, 51, 54, 55, 58, 59, 62, 63] number_set2 = [8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 56, 57, 58, 59, 60, 61, 62, 63] number_set3 = [4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31, 36, 37, 38, 39, 44, 45, 46, 47, 52, 53, 54, 55, 60, 61, 62, 63] number_set4 = [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] number_set5 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63] number_set6 = [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] answer = '' magic_number = 0 index = 0 print('I can read your mind... think of a number between 1 to 63 (inclusive)') print('Don\'t tell me... just be sure to keep it in your mind... I\'ll work it out') print('by having you answer a few, simple questions.... :)') answer = input('Would you like to play? [Yes|No] :') if answer != &quot;Yes&quot; and answer != &quot;No&quot;: print(&quot;\nPlease enter either 'Yes' or 'No'.&quot;) while answer == 'Yes' and index == 0: question = input('Is your number in deck 1? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set1[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 1: question = input('Is your number in deck 2? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set2[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 1 or index == 2: question = input('Is your number in deck 3? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set3[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 2 or index == 3: question = input('Is your number in deck 4? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set4[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 3 or index == 4: question = input('Is your number in deck 5? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set5[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 4 or index == 5: question = input('Is your number in deck 6? [Yes|No]: ') if question == 'Yes': magic_number = magic_number + number_set6[0] index = index + 1 if question == 'No': index = index + 1 # Display the secret number to the screen and amaze your friends! ; ) print('The number you are thinking about is.....', magic_number) </code></pre>
[]
[ { "body": "<p>Welcome to Code Review! Congratulations on having a working game/project :)</p>\n<p>I have a few pointers to help you minimizing the code length, and probably make it easily extensible. Some of these might be considered personal quirks; so YMMV.</p>\n<h2>The deck</h2>\n<p>You're asking the user if their number; at a given state of the run; in any of the given decks. However, for a new player; you never really show the decks ever.</p>\n<p>Is the user supposed to remember <strong>the entire deck</strong>? Perhaps showing the deck before asking if the number is in the same would be better, unless you're using printed cards to act as the deck.</p>\n<h2>Functions</h2>\n<p>Use functions for doing something that you see being repeated. In your case, one of the examples is asking user for <code>Yes/No</code>. Let a function ask for user input, and return <code>True</code>/<code>False</code> for y/n values, and the while loop can live inside this little function.</p>\n<h2>User experience</h2>\n<p>Asking user to input <code>Yes</code>/<code>No</code> seems counter intuitive in the sense that you want them to input these exactly as shown. In general, a lot of cli programs accept <code>y</code>/<code>Y</code>/<code>Yes</code>/<code>yes</code> and variations thereof to be the same. You can have a validation with a small if-clause for acceptable values like so:</p>\n<pre><code>if choice not in {&quot;Yes&quot;, &quot;No&quot;}:\n print(&quot;Please enter Yes/No&quot;)\n</code></pre>\n<h2>if-main clause</h2>\n<p>Put the core logic of your run inside the famous <code>if __name__ == &quot;__main__&quot;</code> block. I will not go into details on the benefits, and just leave a link to <a href=\"https://stackoverflow.com/q/419163/1190388\">this excellent Stack Overflow discussion</a> about the same.</p>\n<h2>Mathematics</h2>\n<p>The game works using the concept of boolean algebra. Each set of numbers is actually only setting one of the bits in the binary representation. You can leverage this fact to generate the table dynamically (or to a custom upper limit) and let another function just set the bit value at correct position in the binary representation be set to <span class=\"math-container\">\\$ 1 \\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T04:32:33.890", "Id": "269082", "ParentId": "269081", "Score": "5" } }, { "body": "<p>First, let's observe that your code is just a series of the same repeating pattern:</p>\n<pre><code>while answer == 'Yes' and index == 0:\n question = input('Is your number in deck 1? [Yes|No] :')\n if question == 'Yes':\n magic_number = magic_number + number_set1[0]\n index = index + 1\n if question == 'No':\n index = index + 1\n</code></pre>\n<p>You check for <code>answer == 'Yes'</code>, which is really a check back against the very first question, &quot;would you like to play?&quot; So you can remove that part of the code by simply indenting all your repeated paragraphs under a single <code>if</code> statement:</p>\n<pre><code>if answer == 'Yes':\n while index == 0:\n question = input('Is your number in deck 1? [Yes|No] :')\n if question == 'Yes':\n magic_number = magic_number + number_set1[0]\n index = index + 1\n if question == 'No':\n index = index + 1\n\n ... next while ...\n</code></pre>\n<p>Next, let us observe that your repeated paragraphs really do follow the same pattern. There is a question, a yes-branch, a no-branch, and you add the first member of the number list if the answer is yes.</p>\n<p>That's a perfect candidate for a loop, but what should we loop on? Obviously, the only thing that changes: the <code>number_set</code>!</p>\n<pre><code>for numset in (number_set1, number_set2, number_set3, ... ):\n while index == 0: # FIXME: this is wrong!\n ...\n magic_number += numset[0]\n ...\n\n \n</code></pre>\n<p>Unfortunately, there's that pesky <code>index</code> variable, which wants to increase from 0 by one each time we pass through a number set. You could use the <code>enumerate()</code> built-in function for this, like:</p>\n<pre><code>for nsi, numset in enumerate((number_set1, number_set2, ...)):\n while index == nsi:\n ... as before ...\n</code></pre>\n<p>Alternatively, you could eliminate the <code>index</code> variable and use the <code>break</code> keyword when you were ready to stop a loop:</p>\n<pre><code>while True: # Runs forever, since True is always true\n question = ...\n if question in ('Yes', 'No'):\n if question == 'Yes':\n magic_number += number_set1[0]\n break # stop the while loop\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T04:34:25.507", "Id": "269084", "ParentId": "269081", "Score": "2" } }, { "body": "<p>Consider this an extension to @hjpotter's answer, with some more details. I agree with the basic points. First, congrats on getting something working! And, the main problem I see is the user experience--the game itself looks like it works great. Let's focus on repetition in this review.</p>\n<h2>Functions and retry logic</h2>\n<p>Add a function to get the answer. I'm changing the variable name from <code>question</code> to <code>answer</code>, since, that's what's in the variable--<code>Yes</code> and <code>No</code> are answers. You named it this because you already had an <code>answer</code> variable in use--in the future use <code>answer2</code> or something like that if you really need a new name.</p>\n<pre><code>def ask_question(question):\n answer = input(question)\n while answer not in [&quot;Yes&quot;, &quot;No&quot;]:\n answer = input('Please input [Yes|No] only: ')\n return answer\n</code></pre>\n<p>As hjpotter suggests, this would be a great place to print the deck for the user, who probably won't know the answer otherwise.</p>\n<p>By separating out the retry logic into the function, we've simplified what each deck loop looks like a lot:</p>\n<pre><code>answer = ask_question('Is your number in deck 1? [Yes|No] :')\nif answer == 'Yes':\n magic_number = magic_number + number_set1[0]\nindex += 1\n</code></pre>\n<p>In fact, we no longer care about <code>index</code> at all--it was only being used for retry logic, so we can drop that line.</p>\n<h2>Looping</h2>\n<p>Next, we'll move th the rest of the program. Currently the main logic looks like this:</p>\n<pre><code>answer = ask_question('Is your number in deck 1? [Yes|No] :')\nif answer == 'Yes':\n magic_number = magic_number + number_set1[0]\n\nanswer = ask_question('Is your number in deck 2? [Yes|No] :')\nif answer == 'Yes':\n magic_number = magic_number + number_set2[0]\n\nanswer = ask_question('Is your number in deck 3? [Yes|No] :')\nif answer == 'Yes':\n magic_number = magic_number + number_set3[0]\n\nanswer = ask_question('Is your number in deck 4? [Yes|No] :')\nif answer == 'Yes':\n magic_number = magic_number + number_set4[0]\n\nanswer = ask_question('Is your number in deck 5? [Yes|No] :')\nif answer == 'Yes':\n magic_number = magic_number + number_set5[0]\n\nanswer = ask_question('Is your number in deck 6? [Yes|No] :')\nif answer == 'Yes':\n magic_number = magic_number + number_set6[0]\n</code></pre>\n<p>That's a lot better already. But let's simplify even more using a loop:</p>\n<pre><code>number_sets = {1: number_set1, 2: number_set2, 3: number_set3, 4: number_set4, 5: number_set5, 6: number_set6}\n\nfor deck_number, number_set in number_sets.items():\n answer = ask_question('Is your number in deck {}? [Yes|No] :'.format(deck_number))\n if answer == 'Yes':\n magic_number = magic_number + number_set[0]\n</code></pre>\n<h2>Putting it together</h2>\n<p>The final program might look something like this</p>\n<pre><code>import sys\n\nnumber_set1 = [2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31, 34, 35, 38, 39, 42, 43, 46, 47, 50, 51, 54, 55, 58, 59, 62, 63]\nnumber_set2 = [8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 56, 57, 58, 59, 60, 61, 62, 63]\nnumber_set3 = [4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31, 36, 37, 38, 39, 44, 45, 46, 47, 52, 53, 54, 55, 60, 61, 62, 63]\nnumber_set4 = [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63]\nnumber_set5 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63]\nnumber_set6 = [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63]\nnumber_sets = {1: number_set1, 2: number_set2, 3: number_set3, 4: number_set4, 5: number_set5, 6: number_set6}\n\ndef ask_question(question):\n answer = input(question)\n while answer not in [&quot;Yes&quot;, &quot;No&quot;]:\n answer = input('Please input [Yes|No] only: ')\n return answer\n\nif __name__ == '__main__':\n answer = input('Would you like to play? [Yes|No] :')\n if answer == &quot;No&quot;:\n sys.exit(0)\n\n print('I can read your mind... think of a number between 1 to 63 (inclusive)')\n print('Don\\'t tell me... just be sure to keep it in your mind... I\\'ll work it out')\n print('by having you answer a few, simple questions.... :)')\n\n magic_number = 0\n for deck_number, number_set in number_sets.items():\n answer = ask_question('Is your number in deck {}? [Yes|No] :'.format(deck_number))\n if answer == 'Yes':\n magic_number = magic_number + number_set[0]\n\n # Display the secret number to the screen and amaze your friends! ; )\n print('The number you are thinking about is.....', magic_number)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T06:09:59.453", "Id": "530884", "Score": "2", "body": "the `ask_question` should just return `True`/`False` imo, so that you don't have to later check against valid string values (suppose all variations of y/Y/yes/YES...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T22:20:33.293", "Id": "531224", "Score": "0", "body": "I agree. I thought it would make the rewrite harder to read for the original author--on balance though this was a mistake." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T23:03:08.740", "Id": "269116", "ParentId": "269081", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T02:27:32.520", "Id": "269081", "Score": "7", "Tags": [ "python" ], "Title": "Magic number game in Python" }
269081
<p>I implemented a console version of a news ticker and I will be glad for a code review. It takes a text from the user and displays it for a given period. How may I get it better?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;thread&gt; #include &lt;chrono&gt; #include &lt;string&gt; int main() { using namespace std::chrono_literals; std::string slide; std::cout &lt;&lt; &quot;please enter a message for the slide: &quot;; std::getline(std::cin, slide); slide.insert(slide.begin(), 5, ' '); std::system(&quot;clear -x&quot;); for(int i = 0; i &lt; 10'000; ++i) { std::rotate(slide.begin(), slide.begin() + 1, slide.end()); std::cout &lt;&lt; slide + '\r' &lt;&lt; std::flush; std::this_thread::sleep_for(1000ms); } std::system(&quot;clear -x&quot;); } </code></pre>
[]
[ { "body": "<p>Generally good. A couple of weaknesses:</p>\n<ul>\n<li>We probably want to exit if <code>std::getline()</code> returns a failed stream. We might want to do the same for an empty input. Personally, I'd probably prefer to accept the message as command arguments, rather than reading standard input.</li>\n<li>On platforms without <code>clear</code> or where <code>clear</code> doesn't accept <code>-x</code>, we'll likely get an annoying error message on the standard error channel. We probably want to do something about that.</li>\n<li>What's special about 5 spaces at the start of string? Should that be a named constant somewhere?</li>\n<li><code>std::rotate()</code> moves every element of the string. It might be better to leave the string unmodified, but to print two substrings from it (current to end, followed by beginning to current).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T07:06:13.250", "Id": "269086", "ParentId": "269083", "Score": "2" } } ]
{ "AcceptedAnswerId": "269086", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T04:33:56.023", "Id": "269083", "Score": "2", "Tags": [ "c++", "console", "stl" ], "Title": "Implementing a News Ticker" }
269083
<p>While on SO someone posted this question and I gave it a quick try. My solution passed all the testcases.</p> <p>Link to the problem: <a href="https://codeforces.com/contest/798/problem/A" rel="nofollow noreferrer">Problem: (A) Mike and palindrome</a></p> <p><strong>Question:</strong></p> <blockquote> <p>Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.</p> <p>A palindrome is a string that reads the same backward as forward, for example strings &quot;z&quot;, &quot;aaa&quot;, &quot;aba&quot;, &quot;abccba&quot; are palindromes, but strings &quot;codeforces&quot;, &quot;reality&quot;, &quot;ab&quot; are not.</p> <p><strong>Input</strong></p> <blockquote> <p>The first and single line contains string s (1 ≤ |s| ≤ 15).</p> </blockquote> <p><strong>Output</strong></p> <blockquote> <p>Print &quot;YES&quot; (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or &quot;NO&quot; (without quotes) otherwise.</p> </blockquote> <p><strong>Examples</strong></p> <p><strong>input</strong>: abccaa <strong>output</strong>: YES</p> <p><strong>input</strong>: abbcca <strong>output</strong>: NO</p> <p><strong>input</strong>: abcda <strong>output</strong>: YES</p> </blockquote> <h3>CODE</h3> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt; #include &lt;iostream&gt; int main(){ std::string str; std::cin &gt;&gt; str; int i{0}, j{str.length() - 1}, cnt{0}; // Check from both the ends if characters are equal. while(i &lt; j){ if (str[i]!= str[j]) ++cnt; ++i; --j; } // If there's one mismatch. if ( cnt == 1 ) std::cout &lt;&lt; &quot;YES&quot;; // Odd length string with 0 mismatches e.g: abcba, can change middle char. else if ( cnt == 0 &amp;&amp; str.length()&amp;1 ) std::cout &lt;&lt; &quot;YES&quot;; else std::cout &lt;&lt; &quot;NO&quot;; } </code></pre>
[]
[ { "body": "<p>Formatting: Don't be so stingy with the indentation, give your code some room to breathe!</p>\n<p>Validating input: You should check if <code>std::cin</code> was successful.</p>\n<p>It is always good if you can split out complexities into functions. Your <code>main</code> function does it all, read input, calc result, and write the output. I would suggest you created a separate function to determine if the string is a palindrome:</p>\n<pre><code>bool isPalindromeWithOneChange(const std::string&amp; str) {\n // ...\n // ...\n return cnt == 1 || (cnt == 0 &amp;&amp; length % 2);\n}\n</code></pre>\n<p>And change <code>main</code> to the following:</p>\n<pre><code>int main() {\n std::string str;\n std::cin &gt;&gt; str;\n if (std::cin.fail() || std::cin.bad()) {\n std::cerr &lt;&lt; &quot;Input failure&quot;;\n return 1;\n }\n if (isPalindromeWithOneChange(str))\n std::cout &lt;&lt; &quot;YES&quot;;\n else\n std::cout &lt;&lt; &quot;NO&quot;;\n}\n</code></pre>\n<p>Note that the underlying data type for array indexes and length is <code>size_t</code>.</p>\n<p>This is just personal preferences, but I find the following easier to read with the decleration on seperate lines:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>const std::size_t length = str.length();\nstd::size_t i = 0;\nstd::size_t j = length - 1;\nstd::size_t cnt = 0;\n</code></pre>\n<p>With the decleration of <code>length</code> you can replace this line:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>else if ( cnt == 0 &amp;&amp; str.length()&amp;1 ) std::cout &lt;&lt; &quot;YES&quot;;\n</code></pre>\n<p>With the following</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>else if ( cnt == 0 &amp;&amp; length % 2) std::cout &lt;&lt; &quot;YES&quot;;\n</code></pre>\n<p>You can break out of the <code>while</code> loop as soon as <code>cnt</code> is larger than one.</p>\n<hr>\nFinal nitpicking / brain farts\n<p>Whether you use <code>length &amp; 1</code> or <code>length % 2</code> is entirely up to you but one thing you lose with <code>&amp; 1</code> is the intention. You should write what you want your code to do and rely on the compiler to handle it correctly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T15:27:30.177", "Id": "530837", "Score": "0", "body": "Any decent compiler will generate exactly the same code for `& 1` and `% 2` if optimizations are turned on, at least if it can see that `length` is an unsigned number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T16:24:51.000", "Id": "530842", "Score": "0", "body": "@upkajdt Thank you for the review. `length&1` is a force of habit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T16:26:05.783", "Id": "530843", "Score": "1", "body": "@upkajdt *Do you know why the formatting does not work correctly in the last paragraph?* Apparently, If you put a newline after `<br>` it should work" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T16:47:29.303", "Id": "530846", "Score": "0", "body": "@Ch3steR, thanks, that fixed it. I would suggest you have a look at https://codegolf.stackexchange.com/ if you like these sorts of challenges." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T16:50:08.307", "Id": "530847", "Score": "0", "body": "BTW: Nearly always, prefer `std::string_view` over `std::string const&` for parameter-type. The exception is if you might need zero-termination, or called code expects that exact type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T18:03:53.297", "Id": "530854", "Score": "0", "body": "@Deduplicator, you are correct. My head is still stuck in 2016 :-)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T12:18:03.140", "Id": "269095", "ParentId": "269090", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T09:04:51.623", "Id": "269090", "Score": "0", "Tags": [ "c++", "programming-challenge" ], "Title": "Codeforces - problem: (A) Mike and palindrome" }
269090
<p>I was trying to implement my own version of <code>matplotlib</code>'s <code>hist</code> function and I came up with this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import numba as nb from numba import prange import time N = 10_000_000 normal = np.random.standard_normal(N) @nb.jit(parallel=True) def histogram(a, bins = 1000, density=False): min_data = np.min(a) max_data = np.max(a) dx = (max_data - min_data)/bins D = np.zeros([bins,2]) for i in prange(bins): dr = i*dx + min_data x1 = a[a&gt;dr] x2 = x1[x1&lt;(dr+dx)] D[i] = [dr, len(x2)] D = D.T x , y = D if density == True: inte = sum((x[1]-x[0])*y) y /= inte plt.bar(x, y, width=dx) return D def main(): start_time = time.clock() histogram(normal, bins=1000, density=True) #plt.hist(normal, bins=1000, density=True) print(&quot;Execution time:&quot;, time.clock() - start_time, &quot;seconds&quot;) plt.tight_layout() plt.show() if __name__ == '__main__': main() </code></pre> <p>This outputs the desired result, but with the execution time of <code>24.3555</code> seconds. However, when I use the original <code>hist</code> (just comment my function and uncomment <code>plt.hist</code>) it does the job in just <code>0.6283</code> seconds, which is ridiculously fast. My question is, what am I doing wrong? And how does <code>hist</code> achieve this performance?</p> <p>P.S: Using this bit of a code, you can see the the result of <code>hist</code> function and my implementation:</p> <pre><code>fig, axs = plt.subplots(1,2) axs[0].hist(normal, bins=100, density=True) axs[1] = histogram(normal, bins=100, density=True) plt.tight_layout() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/nCT7k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nCT7k.png" alt="enter image description here" /></a></p> <p>Where the left one is <code>hist</code>s output and the one on right is my implementation; which both are exactly the same.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T17:59:08.793", "Id": "530853", "Score": "1", "body": "Can you show screenshots of your histogram?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T18:47:35.493", "Id": "530855", "Score": "0", "body": "@Reinderien I just did." } ]
[ { "body": "<p>You are slicing your original dataset 1000 times, making 2000 comparisons with borders for each of the values in it.\nIt is much faster to calculate the proper bin for each value using simple math:</p>\n<pre><code>bin = (value - min_data) / dx\nD[bin][1] += 1\n</code></pre>\n<p>And you can use original circle to set all В[bin][0]\nThe only problem, that at max_data, bin would be equal bins (not bins-1 as expected), you can add additional if or just add additional bin D = np.zeros([bins+1,2]) and then add from bins to bins-1 and drop the bin=bins.</p>\n<p>UPD: So here is my full code (on the base of original code with some refactoring)</p>\n<pre><code>def histogram(a, bins = 1000, density=False):\n min_data = np.min(a)\n max_data = np.max(a)\n\n dx = (max_data - min_data) / bins\n x = np.zeros(bins)\n y = np.zeros(bins+1)\n \n for i in range(bins):\n x[i] = i*dx + min_data\n\n for v in a:\n bin = int((v - min_data) / dx)\n y[bin] += 1\n \n y[bins-2] += y[bins-1]\n y = y[:bins]\n \n if density == True:\n inte = sum((x[1]-x[0])*y)\n y /= inte\n\n plt.bar(x, y, width=dx)\n return np.column_stack((x, y))\n</code></pre>\n<p>It gave me 15 seconds in comparision with 60 seconds of original code. What else can we do? The most intense calculations are in this circle</p>\n<pre><code> for v in a:\n bin = int((v - min_data) / dx)\n y[bin] += 1\n</code></pre>\n<p>And they are made pure python which is really slow (C++ is almost 10 times faster, and it is used to optimise inner calculation in numpy). So we'd better make these calculations with numpy (just change previous 3 lines to that 3 lines).</p>\n<pre><code> a_to_bins = ((a - min_data) / dx).astype(int)\n for bin in a_to_bins:\n y[bin] += 1\n</code></pre>\n<p>That gave me the final time about 7 seconds.</p>\n<p>UPD 2: What is the slowest part now? As we know python intensive calculations are slow. Let's check it:</p>\n<pre><code>def histogram(a, bins = 1000, density=False):\n start_time = time.perf_counter()\n min_data = np.min(a)\n max_data = np.max(a)\n dx = (max_data - min_data) / bins\n print(time.perf_counter() - start_time, 'to calc min/max')\n \n x = np.zeros(bins)\n y = np.zeros(bins+1)\n print(time.perf_counter() - start_time, 'to create x, y')\n \n for i in range(bins):\n x[i] = i*dx + min_data\n print(time.perf_counter() - start_time, 'to calc bin borders')\n\n a_to_bins = ((a - min_data) / dx).astype(int)\n print(time.perf_counter() - start_time, 'to calc bins')\n for bin in a_to_bins:\n y[bin] += 1\n print(time.perf_counter() - start_time, 'to fill bins')\n \n y[bins-2] += y[bins-1]\n y = y[:bins]\n \n if density == True:\n inte = sum((x[1]-x[0])*y)\n y /= inte\n\n print(time.perf_counter() - start_time, 'before draw')\n plt.bar(x, y, width=dx)\n print(time.perf_counter() - start_time, 'after draw')\n return np.column_stack((x, y))\n</code></pre>\n<p>Gives me:</p>\n<pre><code>0.010483399993972853 to calc min/max\n0.011489700002130121 to create x, y\n0.012588899990078062 to calc bin borders\n0.09252060001017526 to calc bins\n7.7265202999988105 to fill bins\n7.727168200013693 before draw\n8.440735899988795 after draw\n</code></pre>\n<p>So almost all the time was consumed by python circle to add 1 to the bin (pay attention that previous calculation with numpy made all bin calculation for less than 0.1 seconds). So if we rewrite that code in C++ we would probably get 10x faster result which is pretty close to the original .hist timing.</p>\n<p>By the way, if I use <code>@nb.jit(parallel=True)</code> than time goes down to</p>\n<pre><code>0.014584699994884431 to calc min/max\n0.014821599994320422 to create x, y\n0.3439053999900352 to calc bin borders\n0.5012229999992996 to calc bins\n0.8304882999800611 to fill bins\n0.8317092999932356 before draw\n1.5190471999812871 after draw\n</code></pre>\n<p>While original <code>.hist</code> on my PC takes 0.8466330000082962 (I don't know if it uses parallel computation or not).</p>\n<p>In total: pure python calculations are terribly slow, transfering them into C++ makes huge impact on speed. That is why you'd better use numpy calculations (which uses C++ under the hood) instead of python circles. It can give the speed up around 10x or even more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T18:48:56.817", "Id": "530856", "Score": "0", "body": "I'm not exactly sure how your solution works. Can you make a reproducible example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T16:18:44.657", "Id": "530942", "Score": "1", "body": "Updated the post with the full code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:33:35.753", "Id": "530973", "Score": "0", "body": "This is very good, but still has some significant difference with the original hist function's 0.6283 seconds. So, the question becomes: what is happening inside the hist function that makes it that fast?(!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:11:02.460", "Id": "531036", "Score": "0", "body": "UPD 2: Now I can accept your answer. Thanks." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T14:13:54.343", "Id": "269100", "ParentId": "269093", "Score": "1" } } ]
{ "AcceptedAnswerId": "269100", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T10:10:34.533", "Id": "269093", "Score": "2", "Tags": [ "python", "python-3.x", "numpy", "matplotlib", "numba" ], "Title": "Implementing histogram in python" }
269093
<p>I want to be able to create a hierarchy of classes and efficiently lookup them by common class attribute value. So far I've come up with this solution:</p> <pre><code>class IndexedAttr: def __init__(self): self.cls = None self.name = None def find_cls(self, value): cls_by_value = self.cls.__cache__[self.name] return cls_by_value.get(value) class IndexedAttrMixin: __cache__= {} def __init_subclass__(cls, **kwargs): cache = cls.__cache__ for name, attr in cls.__dict__.items(): if isinstance(attr, IndexedAttr): if name in cache: raise ValueError(f'Attribute {name} is already in the index') attr.cls = cls attr.name = name cache[name] = {} elif name in cache: cache[name][attr] = cls </code></pre> <p>Usage example:</p> <pre><code>class AuthBase(IndexedAttrMixin): auth_type = IndexedAttr() def __call__(self, session): raise NotImplementedError class BasicAuth(AuthBase): auth_type = 'basic' def __init__(self, login: str, password: str): self.login = login self.password = password def __call__(self, session): print('Authorized using basic auth') class NtlmAuth(AuthBase): auth_type = 'ntlm' def __init__(self, local_password: str): self.local_password = local_password def __call__(self, session): print('Authorized using NTLM') auth_cls = AuthBase.auth_type.find_cls('ntlm') auth_cls('password123')(None) </code></pre> <p>My questions are:</p> <ol> <li>Are there more elegant/efficient solutions? For example, for now you'd have to import two objects, i.e. may this be implemented with only one class or maybe decorator?</li> <li>Is <em>indexing</em> a correct term for this functionality?</li> <li>How can I add support for type hinting? For now, I can't write <code>auth_type: str = IndexedAttr()</code>, because it'd cause a warning at this line: <code>auth_cls = AuthBase.auth_type.find_cls('ntlm')</code></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T12:52:24.880", "Id": "530830", "Score": "3", "body": "Please explain what the code is used for, that will help us write better reviews." } ]
[ { "body": "<p>It looks like you are trying to implement a &quot;dynamic new&quot;: create an object of a class using a string to choose the class object to create. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>auths = { 'basic': BasicAuth, 'ntlm': NtlmAuth }\ncls = auths['ntlm']\ncls('password123')(None)\n</code></pre>\n<p>... except you are trying to hide &amp; automate the creation of the <code>auths</code> dictionary using <code>__init_subclass__</code>.</p>\n<h1>Init Subclass</h1>\n<p>You are using <code>__init_subclass__</code> wrong.</p>\n<p>First, the <code>**kwargs</code> parameter passed into <code>__init_class__</code> is supposed to be passed on to the parent's <code>__init_subclass__</code> method:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def __init_subclass__(cls, ..., **kwargs):\n ...\n super().__init_subclass__(**kwargs)\n ...\n</code></pre>\n<p>Second, you are increasing the work of the author of every authentication subclass. Each author has to remember to add this extra <code>auth_type</code> class member to their class definition.</p>\n<p>What you should be doing is passing the <code>auth_type</code> into the <code>__init_subclass__</code> method.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class AuthBase:\n def __init_subclass__(cls, *, auth_type: str, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.auth_type = auth_type\n</code></pre>\n<p>If you try to run the code now, you'll get:</p>\n<pre class=\"lang-none prettyprint-override\"><code> class BasicAuth(AuthBase):\nTypeError: AuthBase.__init_subclass__() missing 1 required keyword-only argument: 'auth_type'\n</code></pre>\n<p>Note, this is generated when Python is trying to define the class. Your code doesn't try to create a <code>BasicAuth</code> object, so this error is telling the class author there is a problem even before someone tries to use the class.</p>\n<p>To fix the issue, we need to pass the <code>auth_type</code> into the subclass creation:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class BasicAuth(AuthBase, auth_type='basic'):\n def __init__(self, login: str, password: str):\n self.login = login\n self.password = password\n\n def __call__(self, session) -&gt; None:\n print(&quot;Authorize using basic auth&quot;)\n</code></pre>\n<p>Notice the class attribute <code>auth_type</code> is no longer present. Instead, we're passing <code>auth_type</code> as a keyword parameter to the <code>AuthBase.__init_subclass__</code> through the class definition syntax.</p>\n<p>Make a similar change to <code>NtlmAuth</code>.</p>\n<h1>Dynamic New</h1>\n<p>Since I've ripped out <code>auth_type = IndexedAttr()</code> from <code>AuthBase</code>, the class selection logic <code>auth_cls = AuthBase.auth_type.find_cls('ntlm')</code> will no longer work. Let's fix that.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class AuthBase:\n _auth_types: dict[str, 'AuthBase'] = {}\n \n def __init_subclass__(cls, *, auth_type: str, **kwargs):\n super().__init_subclass__(**kwargs)\n if auth_type in cls._auth_types:\n raise ValueError(f&quot;Auth-type {auth_type} already exists&quot;)\n cls._auth_types[auth_type] = cls\n</code></pre>\n<p>Now <code>AuthBase</code> has an <code>_auth_types</code> mapping from names to classes. I've omitted <code>cls.auth_type = auth_type</code>, since it isn't being used, but you can add it back in if needed to go from class back to the auth-type name.</p>\n<p>Now we just want to lookup the desired subclass in the <code>AuthBase</code> dictionary based on the desired <code>auth_type</code> key, so let's add a <code>@classmethod</code> to <code>AuthBase</code> to do a <code>__getitem__</code> on that key. Starting with Python 3.7, there is support for a <a href=\"https://docs.python.org/3/reference/datamodel.html?highlight=__class_getitem__#object.__class_getitem__\" rel=\"nofollow noreferrer\"><code>__class_getitem__</code></a> method.</p>\n<pre class=\"lang-py prettyprint-override\"><code> def __class_getitem__(cls, auth_type: str) -&gt; 'AuthBase':\n return cls._auth_types[auth_type]\n</code></pre>\n<p>Now <code>AuthBase['basic']</code> returns the <code>BasicAuth</code> class, and <code>AuthBase['ntlm']</code> returns the <code>NtlmAuth</code> class. Moreover, the typehint system knows that <code>AuthBase[]</code> requires a <code>str</code> key, and returns a <code>AuthBase</code> value, as desired.</p>\n<h1>Resulting Code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>class AuthBase:\n _auth_types: dict[str, 'AuthBase'] = {}\n \n def __init_subclass__(cls, *, auth_type: str, **kwargs):\n super().__init_subclass__(**kwargs)\n if auth_type in cls._auth_types:\n raise ValueError(f&quot;Auth-type {auth_type} already exists&quot;)\n cls._auth_types[auth_type] = cls\n\n def __class_getitem__(cls, auth_type: str) -&gt; 'AuthBase':\n return cls._auth_types[auth_type]\n\nclass BasicAuth(AuthBase, auth_type='basic'):\n ...\n\nclass NtlmAuth(AuthBase, auth_type='ntlm'):\n def __init__(self, local_password: str):\n self.local_password = local_password\n\n def __call__(self, session) -&gt; None:\n print(&quot;Authorize using NTLM&quot;)\n\n\nauth_cls = AuthBase['ntlm']\nauth_cls('password123')(None)\n</code></pre>\n<h1>Options</h1>\n<p>It isn't necessary to use the <code>*, </code> in <code>def __init_subclass__(cls, *, auth_type: str, **kwargs)</code>. You could instead write <code>def __init_subclass__(cls, auth_type: str, **kwargs)</code>, which would give you the flexibility to omit the <code>auth_type=</code> keyword in subclass declarations: <code>class BasicAuth(AuthBase, 'basic')</code> and <code>class NtlmAuth(AuthBase, 'ntlm')</code>.</p>\n<h1>Corrections</h1>\n<p>The above code works, but doesn't type-check in mypy (or apparently PyCharm).</p>\n<h2><code>__init_subclass__</code></h2>\n<p>While <a href=\"https://www.python.org/dev/peps/pep-0487/\" rel=\"nofollow noreferrer\">PEP 487</a> suggests <code>super().__init_subclass__(**kwargs)</code> to chain subclass initialization, that predated type-checking.</p>\n<blockquote>\n<p>The base class object contains an empty <code>__init_subclass__</code> method which serves as an endpoint for cooperative multiple inheritance. Note that this method has no keyword arguments, meaning that all methods which are more specialized have to process all keyword arguments.</p>\n</blockquote>\n<p>Since type-checking now verifies the parameters being passed, the subclasses apparently cannot rely on dynamically splatting of <code>**kwargs</code>. For instance, in a class hierarchy B -&gt; D, the class D must be updated if a new parameter is added to B. Type-safety comes with a higher maintenance cost.</p>\n<p>Corrected method:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def __init_subclass__(cls, *, auth_type: str):\n super().__init_subclass__()\n if auth_type in cls._auth_types:\n raise ValueError(f&quot;Auth-type {auth_type} already exists&quot;)\n cls._auth_types[auth_type] = cls\n</code></pre>\n<h2><code>Type['AuthBase']</code></h2>\n<p>My bad. The dictionary contains the <code>Type[AuthBase]</code>, not objects of type <code>AuthBase</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Type\n\nclass AuthBase:\n _auth_types: dict[str, Type['AuthBase']] = {}\n \n ...\n\n def __class_getitem__(cls, auth_type: str) -&gt; Type['AuthBase']:\n return cls._auth_types[auth_type]\n</code></pre>\n<h2><code>__class_getitem__</code></h2>\n<p>The method <code>__class_getitem__</code> is <a href=\"https://www.python.org/dev/peps/pep-0560/#specification\" rel=\"nofollow noreferrer\">reserved by PEP 560 for typing</a>. Otherwise it would have been a clever hack.</p>\n<h2>Update Code</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Type\n\nclass AuthBase:\n _auth_types: dict[str, Type['AuthBase']] = {}\n \n def __init_subclass__(cls, *, auth_type: str):\n super().__init_subclass__()\n if auth_type in cls._auth_types:\n raise ValueError(f&quot;Auth-type {auth_type} already exists&quot;)\n cls._auth_types[auth_type] = cls\n\n @classmethod\n def get_class(cls, auth_type: str) -&gt; Type['AuthBase']:\n return cls._auth_types[auth_type]\n\n def __init__(self, *args, **kwargs):\n raise NotImplementedError() \n\n def __call__(self, session) -&gt; None:\n raise NotImplementedError()\n\n\nclass BasicAuth(AuthBase, auth_type='basic'):\n ...\n\nclass NtlmAuth(AuthBase, auth_type='ntlm'):\n def __init__(self, local_password: str):\n self.local_password = local_password\n\n def __call__(self, session) -&gt; None:\n print(&quot;Authorize using NTLM&quot;)\n\n\nauth_cls = AuthBase.get_class('ntlm')\nauth_cls('password123')(None)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T18:27:21.423", "Id": "531161", "Score": "0", "body": "PyCharm gives the following warning:\n`Signature of method 'AuthBase.__init_subclass__()' does not match signature of the base method in class 'object'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T19:23:22.667", "Id": "531164", "Score": "0", "body": "See update at bottom of post. Sorry about that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T18:45:41.583", "Id": "269155", "ParentId": "269096", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T12:19:31.767", "Id": "269096", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Indexing base class attribute overrides: cls -> value" }
269096
<p>I've gone through the docs in a fair bit of detail and understand that a setState function can be passed a function if the previous state is needed.</p> <p>Here I am trying to, based on the state of a variable, set the state of another variable. This seems logically correct to me, but just feel weird. Looking for someone to sanity check it.</p> <pre><code>export default function Comp(props) { const [command, setCommand] = useState(&quot;&quot;); const [items, setItems] = useState(allowedTags); useEffect(() =&gt; { setCommand((prevCommand) =&gt; { if (command !== prevCommand) { const items = syncFunc(allowedTags, command); setItems(items); } return command }); }); } </code></pre> <p>I also understand that this effect will run after every render. But will the effect cause itself to be scheduled to run again since it is updating state?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T14:10:40.353", "Id": "530833", "Score": "0", "body": "Did you test it? Does it produce the expected result?" } ]
[ { "body": "<p>Use effect requires a second parameter, the list of dependencies for the effect.</p>\n<p>This effect declares that you want to re-compute the items state when command is updated.</p>\n<pre><code>useEffect(() =&gt; {\n const items = syncFunc(allowedTags, command);\n setItems(items);\n }, [command]);\n</code></pre>\n<p>All the code you have to check if the dependency had updated is actually the sole purpose of the <code>useEffect</code> function. Simply give it some dependencies and it will check every render if those dependencies have been updated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T17:43:48.427", "Id": "269103", "ParentId": "269098", "Score": "1" } } ]
{ "AcceptedAnswerId": "269103", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T12:51:01.060", "Id": "269098", "Score": "0", "Tags": [ "react.js" ], "Title": "Setting a state variable in an effect based on comparing the value of another state variable" }
269098
<p>This week I dived into the issue of speeding up my program by either threading or multiprocessing. I did not understand well the difference between the two, but that became quite clear when I got the results. Below program is processing 12 text data files that has a Pandas DataFrame as output.</p> <p>It compares the execution times for a simple sequential method; a multiprocessing pool method; a multiprocessing process method; and threading. My computer has 8 cpu's.</p> <p>What is obvious is that threading in this case has no benefit over simple sequential processing (it took both just over 1000 s [17 minutes]), but multiprocessing pool and multiprocessing process does give an almost equivalent speed up of 3.4 times running the process in about 303 s [5 minutes].</p> <pre><code>''' program to run extended QC parsing module using various options: sequential, multiprocessing, threading ''' import multiprocessing as mp import threading import queue from pathlib import Path from vp_extended_qc import ExtendedQc from Utils.plogger import Logger, timed from pprint import pprint # Logging setup logformat = '%(asctime)s:%(levelname)s:%(message)s' Logger.set_logger(Path('./logs/vp_extended_qc.log'), logformat, 'INFO') logger = Logger.getlogger() def log_message(message): print(message) logger.info(message) extended_qc_files = [ Path('./data_files/211006 - check VAPS/20210920/210920_VIB01.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB02.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB03.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB04.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB05.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB07.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB08.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB09.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB10.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB11.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB12.txt'), Path('./data_files/211006 - check VAPS/20210920/210920_VIB13.txt'), ] @timed(logger, print_log=True) def extended_qc_pool(file_name): log_message(f'run extended qc for: {file_name}') ext_qc = ExtendedQc(file_name) ext_qc.read_extended_qc() return ext_qc.avg_peak_df @timed(logger, print_log=True) def extended_qc_thread_or_process(file_name, results_queue): log_message(f'run extended qc for: {file_name}') ext_qc = ExtendedQc(file_name) ext_qc.read_extended_qc() results_queue.put(ext_qc.avg_peak_df) @timed(logger, print_log=True) def run_sequential(): results = [] log_message('start sequential ...') results_queue = queue.Queue() for filename in extended_qc_files: results.append(extended_qc_pool(filename)) pprint(results) @timed(logger, print_log=True) def run_pool(): results = [] log_message('start pool ...') cpus = mp.cpu_count() log_message(f'cpu\'s: {cpus}') with mp.Pool(cpus - 1) as pool: results.append(pool.map(extended_qc_pool, extended_qc_files)) pprint(results) @timed(logger, print_log=True) def run_processes(): log_message('start processes ...') processes = [] results_queue = mp.Queue() results = [] for filename in extended_qc_files: processes.append( mp.Process( target=extended_qc_thread_or_process, args=(filename, results_queue,), ) ) processes[-1].start() log_message('all processes have started ...') for _ in range(len(extended_qc_files)): results.append(results_queue.get()) log_message(f'get results for vibrator: {results[-1].iloc[0][&quot;vibrator&quot;]}') log_message('all processes have completed ...') pprint(results) @timed(logger, print_log=True) def run_threading(): results = [] log_message('start threading ...') threads = [] results_queue = queue.Queue() results = [] for filename in extended_qc_files: threads.append( threading.Thread( target=extended_qc_thread_or_process, args=(filename, results_queue) ) ) threads[-1].start() log_message('all threats have started ...') _ = [t.join() for t in threads] log_message('all threats have completed ...') while not results_queue.empty(): results.append(results_queue.get()) pprint(results) if __name__ == '__main__': log_message(f'=================== timed comparisons =================== ') run_sequential() run_pool() run_processes() run_threading() log_message(f'======================= completed ======================= ') </code></pre> <p>log results:</p> <pre><code>2021-10-18 17:10:00,607:INFO:=================== timed comparisons =================== 2021-10-18 17:10:00,608:INFO:start sequential ... 2021-10-18 17:10:00,608:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB01.txt 2021-10-18 17:12:17,395:INFO:==&gt; extended_qc_pool ran in 136.787 s 2021-10-18 17:12:17,398:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB02.txt 2021-10-18 17:13:40,244:INFO:==&gt; extended_qc_pool ran in 82.849 s 2021-10-18 17:13:40,245:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB03.txt 2021-10-18 17:13:52,424:INFO:==&gt; extended_qc_pool ran in 12.179 s 2021-10-18 17:13:52,426:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB04.txt 2021-10-18 17:15:53,204:INFO:==&gt; extended_qc_pool ran in 120.78 s 2021-10-18 17:15:53,206:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB05.txt 2021-10-18 17:17:29,051:INFO:==&gt; extended_qc_pool ran in 95.844 s 2021-10-18 17:17:29,056:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB07.txt 2021-10-18 17:19:35,376:INFO:==&gt; extended_qc_pool ran in 126.325 s 2021-10-18 17:19:35,380:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB08.txt 2021-10-18 17:21:18,993:INFO:==&gt; extended_qc_pool ran in 103.615 s 2021-10-18 17:21:18,995:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB09.txt 2021-10-18 17:21:20,982:INFO:==&gt; extended_qc_pool ran in 1.989 s 2021-10-18 17:21:20,988:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB10.txt 2021-10-18 17:23:04,654:INFO:==&gt; extended_qc_pool ran in 103.669 s 2021-10-18 17:23:04,658:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB11.txt 2021-10-18 17:24:49,316:INFO:==&gt; extended_qc_pool ran in 104.66 s 2021-10-18 17:24:49,317:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB12.txt 2021-10-18 17:26:14,879:INFO:==&gt; extended_qc_pool ran in 85.563 s 2021-10-18 17:26:14,881:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB13.txt 2021-10-18 17:27:18,781:INFO:==&gt; extended_qc_pool ran in 63.902 s 2021-10-18 17:27:19,127:INFO:==&gt; run_sequential ran in 1038.52 s 2021-10-18 17:27:19,130:INFO:start pool ... 2021-10-18 17:27:19,130:INFO:cpu: 8 2021-10-18 17:27:21,550:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB01.txt 2021-10-18 17:27:21,581:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB02.txt 2021-10-18 17:27:21,680:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB03.txt 2021-10-18 17:27:21,758:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB04.txt 2021-10-18 17:27:21,810:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB05.txt 2021-10-18 17:27:21,959:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB07.txt 2021-10-18 17:27:22,086:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB08.txt 2021-10-18 17:27:41,817:INFO:==&gt; extended_qc_pool ran in 20.137 s 2021-10-18 17:27:41,819:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB09.txt 2021-10-18 17:27:45,590:INFO:==&gt; extended_qc_pool ran in 3.772 s 2021-10-18 17:27:45,608:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB10.txt 2021-10-18 17:29:54,069:INFO:==&gt; extended_qc_pool ran in 152.49 s 2021-10-18 17:29:54,075:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB11.txt 2021-10-18 17:29:55,724:INFO:==&gt; extended_qc_pool ran in 153.915 s 2021-10-18 17:29:55,737:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB12.txt 2021-10-18 17:30:27,502:INFO:==&gt; extended_qc_pool ran in 185.744 s 2021-10-18 17:30:27,515:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB13.txt 2021-10-18 17:30:36,060:INFO:==&gt; extended_qc_pool ran in 194.512 s 2021-10-18 17:30:43,957:INFO:==&gt; extended_qc_pool ran in 201.891 s 2021-10-18 17:30:44,781:INFO:==&gt; extended_qc_pool ran in 202.824 s 2021-10-18 17:31:00,955:INFO:==&gt; extended_qc_pool ran in 195.362 s 2021-10-18 17:32:10,120:INFO:==&gt; extended_qc_pool ran in 136.045 s 2021-10-18 17:32:23,161:INFO:==&gt; extended_qc_pool ran in 115.646 s 2021-10-18 17:32:23,415:INFO:==&gt; extended_qc_pool ran in 147.678 s 2021-10-18 17:32:24,020:INFO:==&gt; run_pool ran in 304.891 s 2021-10-18 17:32:24,027:INFO:start processes ... 2021-10-18 17:32:24,094:INFO:all processes have started ... 2021-10-18 17:32:27,595:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB05.txt 2021-10-18 17:32:27,628:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB02.txt 2021-10-18 17:32:27,656:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB08.txt 2021-10-18 17:32:27,708:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB04.txt 2021-10-18 17:32:27,748:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB07.txt 2021-10-18 17:32:27,771:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB10.txt 2021-10-18 17:32:27,771:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB11.txt 2021-10-18 17:32:27,799:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB01.txt 2021-10-18 17:32:28,184:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB09.txt 2021-10-18 17:32:28,393:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB12.txt 2021-10-18 17:32:28,742:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB13.txt 2021-10-18 17:32:30,041:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB03.txt 2021-10-18 17:32:36,264:INFO:==&gt; extended_qc_thread_or_process ran in 8.096 s 2021-10-18 17:32:36,389:INFO:get results for vibrator: 9 2021-10-18 17:33:09,257:INFO:==&gt; extended_qc_thread_or_process ran in 39.309 s 2021-10-18 17:33:09,371:INFO:get results for vibrator: 3 2021-10-18 17:36:08,966:INFO:==&gt; extended_qc_thread_or_process ran in 221.374 s 2021-10-18 17:36:09,068:INFO:get results for vibrator: 5 2021-10-18 17:36:19,484:INFO:==&gt; extended_qc_thread_or_process ran in 231.862 s 2021-10-18 17:36:19,517:INFO:get results for vibrator: 2 2021-10-18 17:36:44,191:INFO:==&gt; extended_qc_thread_or_process ran in 256.498 s 2021-10-18 17:36:44,223:INFO:get results for vibrator: 4 2021-10-18 17:37:05,644:INFO:==&gt; extended_qc_thread_or_process ran in 276.977 s 2021-10-18 17:37:05,652:INFO:get results for vibrator: 13 2021-10-18 17:37:11,263:INFO:==&gt; extended_qc_thread_or_process ran in 283.51 s 2021-10-18 17:37:11,337:INFO:get results for vibrator: 10 2021-10-18 17:37:13,987:INFO:==&gt; extended_qc_thread_or_process ran in 286.245 s 2021-10-18 17:37:14,005:INFO:get results for vibrator: 7 2021-10-18 17:37:14,263:INFO:==&gt; extended_qc_thread_or_process ran in 286.469 s 2021-10-18 17:37:14,293:INFO:get results for vibrator: 1 2021-10-18 17:37:17,111:INFO:==&gt; extended_qc_thread_or_process ran in 289.455 s 2021-10-18 17:37:17,118:INFO:get results for vibrator: 8 2021-10-18 17:37:18,881:INFO:==&gt; extended_qc_thread_or_process ran in 291.122 s 2021-10-18 17:37:18,884:INFO:get results for vibrator: 11 2021-10-18 17:37:26,190:INFO:==&gt; extended_qc_thread_or_process ran in 297.854 s 2021-10-18 17:37:26,192:INFO:get results for vibrator: 12 2021-10-18 17:37:26,196:INFO:all processes have completed ... 2021-10-18 17:37:26,582:INFO:==&gt; run_processes ran in 302.558 s 2021-10-18 17:37:26,583:INFO:start threading ... 2021-10-18 17:37:26,584:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB01.txt 2021-10-18 17:37:26,587:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB02.txt 2021-10-18 17:37:26,589:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB03.txt 2021-10-18 17:37:26,595:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB04.txt 2021-10-18 17:37:26,604:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB05.txt 2021-10-18 17:37:26,609:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB07.txt 2021-10-18 17:37:26,620:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB08.txt 2021-10-18 17:37:26,632:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB09.txt 2021-10-18 17:37:26,644:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB10.txt 2021-10-18 17:37:26,654:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB12.txt 2021-10-18 17:37:26,661:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB13.txt 2021-10-18 17:37:26,664:INFO:run extended qc for: data_files\211006 - check VAPS\20210920\210920_VIB11.txt 2021-10-18 17:37:26,671:INFO:all threats have started ... 2021-10-18 17:37:50,140:INFO:==&gt; extended_qc_thread_or_process ran in 23.528 s 2021-10-18 17:39:20,498:INFO:==&gt; extended_qc_thread_or_process ran in 113.911 s 2021-10-18 17:50:11,285:INFO:==&gt; extended_qc_thread_or_process ran in 764.7 s 2021-10-18 17:51:30,443:INFO:==&gt; extended_qc_thread_or_process ran in 843.846 s 2021-10-18 17:52:23,355:INFO:==&gt; extended_qc_thread_or_process ran in 896.772 s 2021-10-18 17:53:12,968:INFO:==&gt; extended_qc_thread_or_process ran in 946.374 s 2021-10-18 17:53:46,476:INFO:==&gt; extended_qc_thread_or_process ran in 979.855 s 2021-10-18 17:53:50,388:INFO:==&gt; extended_qc_thread_or_process ran in 983.78 s 2021-10-18 17:53:55,209:INFO:==&gt; extended_qc_thread_or_process ran in 988.57 s 2021-10-18 17:54:01,452:INFO:==&gt; extended_qc_thread_or_process ran in 994.826 s 2021-10-18 17:54:03,221:INFO:==&gt; extended_qc_thread_or_process ran in 996.617 s 2021-10-18 17:54:09,694:INFO:==&gt; extended_qc_thread_or_process ran in 1003.066 s 2021-10-18 17:54:09,697:INFO:all threats have completed ... 2021-10-18 17:54:10,039:INFO:==&gt; run_threading ran in 1003.457 s 2021-10-18 17:54:10,041:INFO:======================= completed ======================= </code></pre> <p>As the documents say <code>threading</code> seems only useful if the process is I/O bound and multiprocessing works if you have more than 1 cpu.</p>
[]
[ { "body": "<p>Overall this looks like throwaway code meant to give you a quick answer. It's not worth trying to improve since you will never re-use or maintain it.</p>\n<p>If you did want to improve it, the issue I'd tackle is that the code is too long and repetitive.</p>\n<h2>Reduce Repetition</h2>\n<ul>\n<li>The definition of extended_qc_files is long. Say &quot;run once for each file in this folder&quot; instead of this is all the files in the given folder.</li>\n<li><code>extended_qc_pool</code> and <code>extended_qc_thread_or_process</code> are almost identical, factor out the part in common. Since <code>run_sequential</code> uses a queue, you could pass in the queue for both.</li>\n<li><code>run_*</code> have a lot of repetition across methods, mostly around setting up results and logging. Remove it. You could\n<ul>\n<li>Pull this out into a wrapping loop (loop over each run function and have this outside the function)</li>\n<li>Make a custom decorator, and have the function take <code>results</code> as a parameter</li>\n<li>Make a context handler, and have the function take <code>results</code> or the context handler as a parameter</li>\n</ul>\n</li>\n<li>Stop copy-pasting, which leads to errors and repetition. <code>run_threading</code> defines <code>results</code> twice and copy-pasted the spelling error <code>threats</code>. If you want a short program, typing everything by hand is one viable method. Factor things out instead of copy-pasting them.</li>\n</ul>\n<h2>Logging</h2>\n<p>Replace <code>log_message</code> by having the logger itself print to stderr/stdout in a different format.</p>\n<p>Right now your logging is scattered through all the functions. I think that's fine since this is a quick test. For bigger projects I'd recommend instead <em>returning</em> timing information, and having <code>main</code> print the results. This also would let you group together summary statistics at the end.</p>\n<h2>Other</h2>\n<ul>\n<li><strong>Fuzzy conclusions and understanding of the data.</strong> What did you learn? You (implicitly) conclude your process is CPU-bound and not IO bound. Why? You shouldn't conclude it because of this test--that's indirect and possibly circular reasoning. Learn tools like <code>top</code> and <code>iotop</code> on Linux/Mac, or similar built-in programs on Widows, to test this theory directly. Is the CPU or disk maxed out during a run? Mention the size of the files and where they're stored--this can let you theoretically calculate how long reading the files will take--if it's 30 seconds, and the real process runs 17 minutes, it's probably not IO-bound. Replace <code>ExtendedQc</code> by something that reads the files and exits. How long does that take with each method? If it's still 17 minutes, it was IO bound after all.</li>\n<li>Missing information. You did not include all code. <code>Utils.plogger</code>, <code>Utils.timed</code>, <code>ExtendedQc</code>, etc are all relevant to this review. What does <code>ext_qc.read_extended_qc()</code> do? You call this and ignore the return value.</li>\n<li>Re-usability. Your functions are all some version of calling <code>extended_qc_pool</code>. Pass this in instead of hardcoding it in each of the four methods. This would actually make your code re-usable when you want to test how to speed something up later.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T03:15:15.020", "Id": "530880", "Score": "0", "body": "Thank you for the extensive reply. This was indeed some throwaway code to experiment with threading and multiprocessing. I agree with the refactoring of the function `extended_qc`, which I have done by adding a key word argument for when a queue is necessary. The functions `run_pool`, `run_processes`, `run_threading` are a handy reference on how to boilerplate this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T22:23:27.030", "Id": "269115", "ParentId": "269099", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T14:06:54.760", "Id": "269099", "Score": "0", "Tags": [ "python", "multithreading", "multiprocessing" ], "Title": "Showcase difference multiprocessing and threading in Python" }
269099
<p>Please verify jump searching algorithm that I have written and let me know if any bugs are present. I have tested it from my end, but still would like to get it verified for any missing corner scenarios.</p> <pre><code>class JumpSearch { public static void main(String[] args) { int[] input = new int[] { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 , 670 }; int target = 13; int output=-1; int step = (int) Math.floor(Math.sqrt(input.length)); int lastIndex = input.length-1; int index=step; //directly jump to end of first block. System.out.println(&quot;step : &quot; + step); System.out.println(&quot;start index : &quot; + index); System.out.println(&quot;lastIndex : &quot; + lastIndex); boolean jumpBlocks = true , endOfInput=false;; while(jumpBlocks) { if(target &lt;= input[index]) { int previousIndex = (index-step); System.out.println(&quot;previous index : &quot; + previousIndex); for(int a=index ; a &gt;= previousIndex ; a--) { if(input[a] == target) { output=a; break; } } break; } else { if(endOfInput) { jumpBlocks = false; } else { index += step; if(index &gt;= lastIndex) { endOfInput=true; index = lastIndex; } } } } System.out.println(&quot;output : &quot; + output); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T17:07:58.967", "Id": "530848", "Score": "1", "body": "Welcome back to Stack Review, please confirm if your code is referring to [Jump_search](https://en.wikipedia.org/wiki/Jump_search) and include yours tests." } ]
[ { "body": "<p>The sheer amount of breaks, and boolean controls, is an immediate red flag. It is a natural consequence of a decision to stuff everything into a single loop. Try to decompose the problem into a smaller chunks instead.</p>\n<p>First, the <code>for</code> loop implements an important algorithm, on its own rights. Namely, <strong>linear search</strong>. Don't be shy, and factor it out into the function. At the very least, this would let you unit test it.</p>\n<p>Next, notice that the <code>if</code> clause of <code>target &lt;= input[index]</code> condition is executed at most once. Therefore, it doesn't belong to the <code>while</code> loop. The purpose of that loop is to find the block which potentially contains the target. This observation allows a simple decomposition, along the lines of</p>\n<pre><code> int blockStart = findContainingBlock(input, target, step);\n if (blockStart == input.length) {\n return -1;\n }\n int blockEnd = min(blockStart + step, input.length);\n int index = linearSearch(blockStart, blockEnd, target);\n return index;\n</code></pre>\n<hr />\n<p>A side note about the linear search. The <code>for</code> loop is broken when the <code>target == input[a]</code>. You may as well break it when <code>target &gt; input[a]</code>: there is no point to search any further. It means that</p>\n<pre><code> for (int a=index ; a &gt;= previousIndex &amp;&amp; target &lt;= input[a]; a--)\n</code></pre>\n<p>expresses the goals more clearly.</p>\n<p>Besides clarity, notice that every block, except the very first one, has a natural sentinel: we are guaranteed that the last value of the previous block is less than the target. It means that the <code>for</code> loop doesn't need to test for <code>a &gt;= previousIndex</code> at all:</p>\n<pre><code> for (int a=index ; target &lt;= input[a]; a--)\n</code></pre>\n<p>works, and has twice as few comparisons.</p>\n<p>Dealing with the first block is also easy: before even looking for a suitable block, test whether the target could be there at all.</p>\n<pre><code> if (target &lt; input[0]) {\n return -1; // target is definitely not there.\n }\n</code></pre>\n<p>Now the first block is not special.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T17:57:26.843", "Id": "269104", "ParentId": "269101", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T14:25:51.997", "Id": "269101", "Score": "2", "Tags": [ "java", "algorithm", "search" ], "Title": "Please verify Jump searching algorithm" }
269101
<p>I am trying to implement a <em><strong>Left shift/ Right Shift on arrays</strong></em>.</p> <p>I was able to accomplish this using double loops. Can the efficiency be improved?</p> <p>This is the working code for LeftShift/RightShift which is using 2 nested loops.</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; struct Array { int A[10]; int size; int length; }; void Display(struct Array arr) { printf(&quot;\nElements are : \n&quot;); for(int i = 0;i&lt;arr.length;i++) printf(&quot;%d &quot;, arr.A[i]); } // Left Shift------------------------------------------------------------------------------- void LeftShift1(struct Array *arr, int n) //n is the number of shifts { for(int i=0; i&lt;n; i++) { //int temp = arr-&gt;A[0]; for(int j=0; j&lt;arr-&gt;length-1; j++) { arr-&gt;A[j] = arr-&gt;A[j+1]; } arr-&gt;A[arr-&gt;length-1] = 0; } } //Right Shift------------------------------------------------------------------------------- void RightShift(struct Array *arr, int n) //n is the number of shifts { for(int i = 0; i&lt;n; i++) { for(int j=arr-&gt;length-1; j&gt;0; j--) { arr-&gt;A[j] = arr-&gt;A[j-1]; } arr-&gt;A[0] = 0; } } int main() { struct Array arr={{1,2,3,4,5},10,5}; LeftShift1(&amp;arr, 2); //RightShift(&amp;arr, 1); Display(arr); return 0; } </code></pre> <p><em><strong>I'm trying something like this which uses 2 iterators to solve this problem!</strong></em></p> <p><em><strong>This is also working!</strong></em></p> <pre><code>void LeftShift2(struct Array *arr, int n) { if (n &gt; arr-&gt;length) { n = arr-&gt;length; } for(int k=0; k&lt;n; k++) { int i,j; for(i=0, j=0; j&lt;arr-&gt;length-1; i++, j++) { arr-&gt;A[j] = arr-&gt;A[j+1]; } arr-&gt;A[arr-&gt;length-1] = 0; } } </code></pre> <p><strong>But can this be solved without loops? OR with a single loop?</strong></p> <p><em><strong>Can this be made more efficient?</strong></em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T19:18:32.027", "Id": "530859", "Score": "5", "body": "This looks like a use-case for `std::rotate`: https://en.cppreference.com/w/cpp/algorithm/rotate" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T20:01:24.207", "Id": "530862", "Score": "0", "body": "@user673679 I will try to implement it. I was trying not to use inbuilt functions for now, but this helped me! Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T20:02:20.567", "Id": "530864", "Score": "1", "body": "Is this a C or a C++ question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T20:10:49.987", "Id": "530866", "Score": "0", "body": "@G.Sliepen Both C/C++ will work. If you can add any suggestions/tricks, it will be appreciated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T06:46:11.993", "Id": "530887", "Score": "2", "body": "`<iostream>` is a C++ header, so obviously not C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T09:36:36.687", "Id": "530904", "Score": "1", "body": "\"*...which uses 2 iterators...*\" The word to use here is \"index\". When you start working with C++, \"iterator\" has a very specific meaning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T05:28:47.390", "Id": "531000", "Score": "0", "body": "@TobySpeight `<stdio.c>` is a C header (C++ one is `<cstdio>`), so obviously not C++ -_-" } ]
[ { "body": "<p>You can use <code>memmove()</code> function to move overlapping areas of memory and <code>memset()</code> to clear the moved items.</p>\n<p>LeftShift can be implemented like:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;string.h&gt;\n\nvoid LeftShift(struct Array *arr, int n) //n is the number of shifts\n{\n memmove(&amp;arr-&gt;A[0], &amp;arr-&gt;A[n], (arr-&gt;size-n)*sizeof(arr-&gt;A[0]));\n memset(&amp;arr-&gt;A[arr-&gt;size-n], 0, n * sizeof(arr-&gt;A[0]));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T19:18:35.073", "Id": "269106", "ParentId": "269105", "Score": "9" } }, { "body": "<p>Why do you have the following line if you are not using <code>temp</code>?</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int temp = arr-&gt;A[0];\n</code></pre>\n<p>You do not need the nested loops. You are currently shifting the elements one position at a time when you can move them <code>n</code> positions.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void LeftShift1(struct Array* arr, unsigned int n) {\n for (unsigned int i = 0; i &lt; arr-&gt;length; i++) {\n if (i + n &lt; arr-&gt;length)\n arr-&gt;A[i] = arr-&gt;A[i + n];\n else\n arr-&gt;A[i] = 0;\n }\n}\n</code></pre>\n<p>Or use <code>memmove</code> / <code>memset</code> as suggested by @Carlo</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T20:12:26.133", "Id": "530867", "Score": "0", "body": "That line was copied from the array rotation part. My bad!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T04:48:32.173", "Id": "530881", "Score": "1", "body": "Doing it with a single loop like this is possible, but for efficiency you need the compiler to [unswitch the loop](https://en.wikipedia.org/wiki/Loop_unswitching), aka make two loops. Writing it in the source with two loops is about neutral in terms of complexity for future readers of the code. And if performance is relevant at all, it won't make them worry about whether the compiler (or which compilers) can optimize it easily into memmove and memset like they will with separate loops." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T17:17:17.153", "Id": "531205", "Score": "2", "body": "@PeterCordes, you are correct, as always =). I had some fun playing around with [this](https://godbolt.org/z/G183o8Gca)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T20:09:58.953", "Id": "269108", "ParentId": "269105", "Score": "8" } }, { "body": "<blockquote>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n</code></pre>\n</blockquote>\n<p>If this is C, don't attempt to include <code>&lt;iostream&gt;</code>. If it's C++, use the C++ headers (<code>&lt;cstdlib&gt;</code> etc), and prefer <code>&lt;iostream&gt;</code> to <code>&lt;stdio.h&gt;</code>. There's almost never any need for an <em>implementation</em> file to be bilingual C and C++ (sometimes it's useful for a <em>header</em>).</p>\n<hr />\n<blockquote>\n<pre><code>struct Array\n{\n int A[10];\n int size;\n int length;\n};\n</code></pre>\n</blockquote>\n<p>This is a strange way to define an array. Does it ever make sense for <code>size</code> to have a different value to <code>int(sizeof A)</code>? Why are we using a signed integer anyway?</p>\n<p>In C, we'd normally use a <em>flexible array member</em> for the elements:</p>\n<pre><code>struct Array\n{\n size_t capacity;\n size_t length;\n int elements[];\n};\n</code></pre>\n<p>In C++, a <code>std::vector&lt;int&gt;</code> provides exactly this functionality.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T07:46:44.437", "Id": "530894", "Score": "0", "body": "I was using size for testing dynamic array earlier. `size` was being used for allocating the size of the array in heap using something like this : `arr.A=(int *)malloc(arr.size*sizeof(int));`. On the other hand, can we not intermix legal C code with C++ code? C++ is backward compatible with C right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T08:43:18.870", "Id": "530897", "Score": "0", "body": "No, you can't change an array to a pointer like that; you would need `int *A` rather than `int A[]`. (And there's no need to cast the result of `malloc()` in C). Yes, you _could_ write C++ that's also valid C - but why would you want to do that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T09:02:42.927", "Id": "530900", "Score": "0", "body": "Yes, it was `int *A` before! Thanks for this insight, it helped a lot!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T06:58:54.017", "Id": "269123", "ParentId": "269105", "Score": "2" } }, { "body": "<p>The code doesn't check if <code>n</code> is within the expected boundaries of the array. Unintentional overwriting of memory is such an infamous concern in C/C++, even in toy code I would add the range check to build good habits, or at the very least document in a comment that the caller is assumed to be trusted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T07:00:37.400", "Id": "269124", "ParentId": "269105", "Score": "2" } }, { "body": "<p>The fastest way is to use <code>memmove()</code> and <code>memset()</code>, because as library routines they should be optimal. But if you can't do that for whatever reason, your best speed-up is from moving to using pointers. Looping over arrays with indexing is <em>never</em> optimal speed-wise (although it has obvious advantages for code readability). And since you're shifting by a known number of steps, you can build that in too.</p>\n<pre><code>/** Right-shift array data in place, one element at a time.\n@param arr Array data structure\n@param n Number of shifts\n@note n should be less than length of array.\n*/\nvoid RightShift(struct Array *arr, int n) /* n is the number of shifts */\n{\n int* fromPtr;\n int* toPtr;\n int* endPtr;\n \n if (n == 0)\n {\n /* No shift required */\n return;\n }\n \n /* Limit shift */\n if (n &gt; arr-&gt;length)\n {\n n = arr-&gt;length;\n }\n \n /* Shift data up, starting at the end and working \n backwards so that we don't overwrite data to shift.\n Note that the end is one element *before* the start,\n because we're working backwards.\n */\n toPtr = arr-&gt;A + (arr-&gt;length - 1);\n fromPtr = toPtr - n;\n endPtr = arr-&gt;A - 1;\n while (fromPtr != endPtr)\n {\n *toPtr = *fromPtr;\n toPtr --;\n fromPtr --;\n }\n \n /* Clear remaining data */\n fromPtr = arr-&gt;A + (n - 1);\n while (fromPtr != endPtr)\n {\n *fromPtr = 0;\n fromPtr --;\n } \n}\n</code></pre>\n<p>This should handle your right-shift. (Note that I have only written this, not run it. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T12:10:33.253", "Id": "530915", "Score": "1", "body": "I like your idea of using pointers but there are two errors: ` toPtr = arr->A + (&arr->length - 1);` should be ` toPtr = arr->A + (arr->length - 1);` and there is a `;` dangling after the `while` statement that results in an infinite loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T12:13:18.700", "Id": "530916", "Score": "2", "body": "Most modern compilers should also be able to optimize basic loops into `memmove` / `memcpy`. I am not the expert on this but I think your approach may confuse the compiler and cause more harm than good =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T10:31:02.723", "Id": "531022", "Score": "0", "body": "@upkajdt The perils of writing code without having time to compile and run it! Thanks! :) I agree that memmove/memcpy would be better, but I'm not aware that modern compilers are smart enough to turn regular array indexing into something better, because that's about guessing the coder's intent rather than what they've written. Either way, pointers are going to be faster than array operations though AFAIK. Although perhaps I'm not up on the latest optimisation techniques." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T11:22:51.497", "Id": "531025", "Score": "0", "body": "Cool, as I said, I'm not the expert, but I decided to do some benchmarking [see here](https://codereview.stackexchange.com/questions/269140/benchmarking-data-copying) and you may find the results interesting. I would also like to know what sort of times you get if you have access to gcc and a linux box." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:07:08.110", "Id": "531035", "Score": "0", "body": "Interestingly if you look at the [following](https://tio.run/##vU7LDcIwDL17CnNr47JAqx5gEYSSCCJVaYUNSKDOHpwUChPwTn4/@dlp2trhGE8p3cbgUDzLrgpRDDqWBsvFF9sgi2tbDg9/ELTjNUoNT0BFifjosM9BpMXtinc/h8FjlfVNn0N1kZdihtEvWjSa6FZRNaIvVe9DZ5gB1qH7Pw8lek/9nZPSCw), `testA` and `testB` have about the same results with MSVC and Intel compiler, but the inline incrementation seems to confuse gcc." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T10:00:27.633", "Id": "269125", "ParentId": "269105", "Score": "0" } }, { "body": "<p>You know, C and C++ are different languages. You used both tags, and your code is confused as to which it wants to be. It appears to use C syntax, library calls, and ways of doing things; but it includes a C++ header. It doesn't seem to use that header though. Maybe this is the current state of the file after you have done some experimentation and different versions?</p>\n<p>Generally, you want to consider doing this array shifting with element types other than a plain <code>int</code>. In fact, it may be a complex type like a <code>string</code> and you should not be doing raw <code>memcpy</code> stuff on it as some suggested. In your code, you're setting the shifted-out elements to <code>0</code> which is OK for an integer and related types, but won't work in general (say, <code>string</code>).</p>\n<p>Note that there exists <a href=\"https://en.cppreference.com/w/cpp/algorithm/rotate\" rel=\"nofollow noreferrer\"><code>std::rotate</code></a> which doesn't stick zeros on the shifted-from end but copies the shifted-off elements there instead.</p>\n<p>As of C++20, there is a standard <a href=\"https://en.cppreference.com/w/cpp/algorithm/shift\" rel=\"nofollow noreferrer\"><code>std::shift_left</code> and <code>shift_right</code></a> ready to use.</p>\n<pre><code>int arr[] = {1,2,3,4,5};\nusing std::ranges::begin;\nusing std::ranges::end;\nstd::shift_left (begin(arr),end(arr),2);\nDisplay(arr);\n</code></pre>\n<p>I'm not sure what your <code>struct Arr</code> is all about; if it's an array with a maximum and current size, you are not making use of that. In C++, just use <code>vector</code>. But with a real flexible container, do you really want to &quot;shift&quot;, putting 0/empty/blank element on the other end, or did you really want to just delete elements from one end? The whole point of flexible containers is you don't have placeholders ready to be assigned to, but only store those elements actually present. So maybe instead of <code>shift_right</code> you really want to <code>vector::erase</code> <em>n</em> elements starting at the beginning, and <code>shift_left</code> is just a <code>resize</code> to make smaller.</p>\n<p>If you are doing a lot of adding and removing elements from <strong>both ends</strong> then there is a container specifically designed for that called <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>deque</code></a>. Its name means &quot;double ended queue&quot; but it's pronounced like &quot;<em>deck</em>&quot;.</p>\n<h2>summary</h2>\n<ul>\n<li>what do you <em>really</em> want to do?</li>\n<li>know what's in the library.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:47:53.207", "Id": "269141", "ParentId": "269105", "Score": "9" } } ]
{ "AcceptedAnswerId": "269108", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T18:34:51.460", "Id": "269105", "Score": "6", "Tags": [ "c++", "c", "array", "iterator", "pointers" ], "Title": "Left Shift/ Right Shift an array in C" }
269105
<p>For reasons, I want to implement a predicated version of <code>std::for_each</code>. I know that, in C++20, this is made somewhat redundant or less useful, as we can use <code>std::ranges:views::filter</code>; and that a more robust implementation than the one I present below might use conditional iterators (like Boost has), but - suppose I want to limit the amount of code and just get what I need, which is this templated function.</p> <p>So, here it is:</p> <pre><code>template&lt; typename InputIterator, typename Predicate, typename UnaryFunction &gt; constexpr UnaryFunction for_each_if( InputIterator first, InputIterator last, Predicate p, UnaryFunction f ) { std::for_each(first, last, [&amp;](auto&amp;&amp; x) { using x_type = decltype(x); if (p(std::forward&lt;x_type&gt;(x))) { f(std::forward&lt;x_type&gt;(x)); } } ); return f; } </code></pre> <p>You can <a href="https://godbolt.org/z/fWKjMcasb" rel="nofollow noreferrer">try it out on GodBolt</a>. I also have an alternative version without using <code>std::for_each</code>:</p> <pre><code>template&lt; typename InputIterator, typename Predicate, typename UnaryFunction &gt; constexpr UnaryFunction for_each_if( InputIterator first, InputIterator last, Predicate p, UnaryFunction f ) { for (; first != last; ++first) { auto&amp;&amp; x { *first }; using x_type = decltype(x); if (p(std::forward&lt;x_type&gt;(x))) { f(std::forward&lt;x_type&gt;(x)); } } return f; } </code></pre> <p>Some specific questions:</p> <ul> <li>Which version is preferable? The latter has less dependencies, but the former has no raw loops...</li> <li>Is the <code>auto&amp;&amp;</code> and the forwarding overkill?</li> <li>Should I bother with a <code>noexcept()</code> clause? libc++ and libstdc++ don't seem to.</li> <li>Should I make some static assertions to give nicer error messages? Especially in the second versions?</li> </ul> <p>of course, any criticism/ideas/notes are welcome.</p>
[]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Which version is preferable? The latter has less dependencies, but the former has no raw loops...</p>\n</blockquote>\n<p>If having less dependencies matters, then go for the raw loops. If not, then I don't think it matters much; the lambda in the first version makes it just as verbose as the second version, and they should be functionally identical.</p>\n<blockquote>\n<p>Is the <code>auto&amp;&amp;</code> and the forwarding overkill?</p>\n</blockquote>\n<p>Yes. You normally use <code>std::forward</code> if you are forwarding a function parameter to another function. However, here we just have an iterator that we dereference. That should normally return a plain reference, so forwarding is not going to do anything useful here.</p>\n<blockquote>\n<p>Should I bother with a <code>noexcept()</code> clause? libc++ and libstdc++ don't seem to.</p>\n</blockquote>\n<p>You could but then you'd have to specify an expression that is true only if both predicates and the iterator operations are <code>noexcept</code> themselves. That's a lot of work. Consider that this is a template, so the compiler will be able to inline it completely, and deduce whether any of it will throw itself.</p>\n<blockquote>\n<p>Should I make some static assertions to give nicer error messages? Especially in the second versions?</p>\n</blockquote>\n<p>Yes, you could do that to make incorrect use a bit easier to debug. Even better would be to use C++20 concepts to ensure the types are all correct. It would even help in the first version, since if the error occurs inside the lambda, the error message of the compiler would probably be hard to understand as well.</p>\n<h1>Consider creating an <code>apply_if()</code> instead</h1>\n<p>It looks straightforward and fine to me, apart from the unnecessary use of <code>std::forward</code>. However, a different approach would be to create a template function that just returns the lambda you have in the first version. You could call it <code>apply_if()</code>:</p>\n<pre><code>template&lt;typename Predicate, typename UnaryFunction&gt;\nauto apply_if(Predicate p, UnaryFunction f) {\n return [p, f](auto&amp; x) {\n if (p(x)) {\n f(x);\n };\n };\n}\n</code></pre>\n<p>This way, you can compose predication with other algorithms. For example, you could then write:</p>\n<pre><code>std::for_each(first, last, apply_if(p, f));\n</code></pre>\n<p>Of course, the above <code>apply_if()</code> itself is not very generic and should probably be improved to handle arbitrary arguments and forward arguments in case it is used outside of another algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T21:58:35.950", "Id": "530872", "Score": "0", "body": "About the forwarding - don't I need std::forward for forwarding the kind-of-reference and the constness?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T22:07:54.523", "Id": "530873", "Score": "0", "body": "Constness is handled correctly by `auto&` itself. As for the kind-of-reference: think about what the kind-of-reference a dereferenced iterator is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T22:15:06.540", "Id": "530874", "Score": "0", "body": "\"think about what the kind-of-reference a dereferenced iterator is\" <- How sure can I really be that it's an lvalue reference? Is that officially required?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T07:32:10.327", "Id": "530893", "Score": "1", "body": "Your `apply_if()` doesn't work for `for_each_if()`, because `for_each()` has a stateful `f()` and returns it. You'd need an `apply_if()` which also has this behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T08:49:15.890", "Id": "530898", "Score": "0", "body": "+1: I was about to suggest the functional approach to compose the predicate and operator, and found I'd been beaten to it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:12:02.497", "Id": "530952", "Score": "0", "body": "@einpoklum True. Then it should be a `class` that stores the predicate and function, has an `operator()`, and some member functions to get back the predicate and function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T21:24:32.857", "Id": "530977", "Score": "0", "body": "@G.Sliepen: Yes, but then - do we really want to expose such a thing for general use? It's rather ugly. Of course, `for_each` itself has some of this ugliness built in to its semantics; I rather dislike how it involves this sort of stateful accumulation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:14:08.090", "Id": "531003", "Score": "0", "body": "@einpoklum Well if you want `for_each_if` to act like `for_each` as much as possible, you'd have to implement this ugliness as well. Alternatively, consider having `for_each_if` and/'or `apply_if` take the predicate and function by reference." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T21:50:15.597", "Id": "269114", "ParentId": "269112", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T21:11:06.020", "Id": "269112", "Score": "3", "Tags": [ "c++", "template", "generics", "stl" ], "Title": "A predicated version of std::for_each" }
269112
<p>I had to implement a function for getting the Levenshtein distance of two strings for a problem. It linked to the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Wikipedia Article</a> for Levenshtein distance and mentioned I can use the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix" rel="nofollow noreferrer">dynamic programming</a> solution. Following is my implementation.</p> <pre><code>def levenshtein_distance(s, t): m, n = len(s) + 1, len(t) + 1 d = [[0] * n for _ in range(m)] for i in range(1, m): d[i][0] = i for j in range(1, n): d[0][j] = j for j in range(1, n): for i in range(1, m): substitution_cost = 0 if s[i - 1] == t[j - 1] else 1 d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + substitution_cost) return d[m - 1][n - 1] </code></pre> <p>This function did work and my code passed the test case but I'm not sure if this is the most optimum solution.</p> <p>Any pointers or suggestions will be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T12:48:42.947", "Id": "530920", "Score": "2", "body": "You don't actually need such a big array (`d`) because you're only ever accessing two consecutive rows at a time. Hence a `2 x m` array is sufficient, while accessing the two rows in an alternating fashion (à la `j % 2`). However, sometimes you're interested not just in the smallest distance but also what is the actual \"path\" through the array (as in: which operations do you have to apply to transform `s` into `t`), in which case you *do* need the full array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T12:57:25.190", "Id": "530921", "Score": "1", "body": "Correction, you don't even need the full array then - you could simply store the best \"path\" that lead to `d[i][j%2]` in a separate data structure -- which, however, would then take up the same size as storing the full `d` as you're currently doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:51:13.990", "Id": "530990", "Score": "1", "body": "I personally would find it easier to read without the blank lines between the for loops. But PEP8 leaves that up to the author's judgment, using blank lines to separate logical sections is apparently fine. I'd be interested to hear a more experienced opinion on blank lines in short functions." } ]
[ { "body": "<h2>Documentation</h2>\n<p>Add a docstring for <code>levenshtein_distance</code> which explains what Levenshtein distance is. Explain the algorithm (or give a link to some existing explanation) if easy. I count about 5 sections in the algorithm--put a comment above each to explain what it's doing. Not all code needs a lot of comments, but algorithms do.</p>\n<h2>Variable names</h2>\n<p>Your names here are: <code>d</code>, <code>s</code>, <code>t</code>, <code>i</code>, <code>j</code>, <code>m</code>, and <code>substitution_cost</code>. One of these is not like the others. Make all of them have descriptive names like <code>substitution_cost</code>.</p>\n<h2>Tests</h2>\n<p>You're worried your algorithm is not correct. So add some explicit tests and test cases.</p>\n<h2>Optimality</h2>\n<p>Time how long your function takes on various lengths of string. Measure the runtime experimentally to make sure it's what you expect.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T23:25:50.887", "Id": "269118", "ParentId": "269117", "Score": "13" } }, { "body": "<p>Just in case you might be interested in a memoized version. (Maybe somewhat cleaner, but slower by a constant factor.)</p>\n<pre><code>#!/usr/bin/env python3\n\nfrom functools import cache\n\n\ndef levenshtein_distance(s, t):\n '''\n &gt;&gt;&gt; levenshtein_distance(&quot;snowy&quot;, &quot;sunny&quot;)\n 3\n '''\n\n @cache\n def d(i, j):\n return (\n i if j == 0 else\n j if i == 0 else\n d(i - 1, j - 1) if s[i - 1] == t[j - 1] else\n min(\n d(i - 1, j) + 1,\n d(i, j - 1) + 1,\n d(i - 1, j - 1) + 1\n )\n )\n\n return d(len(s), len(t))\n\nif __name__ == &quot;__main__&quot;:\n import doctest\n doctest.testmod()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:15:48.817", "Id": "530985", "Score": "1", "body": "Why are you including `#!/usr/bin/env python3` this is not neccecary for Python 3. Why are you using `lru_cache`? From Python 3.9 the standard is `@cache` https://docs.python.org/3/library/functools.html. Not super happy with your formating either, this is what black gives: https://pastebin.com/EShFq31D. Assert should only be used for testing, not production code. It would be clearer using https://docs.python.org/3/library/doctest.html." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:39:28.237", "Id": "531061", "Score": "0", "body": "Good points, thanks. For this purpose I don't like the way black formats the if .. else construct. Should use doctest, no doubt, but didn't know it. Mainly just wanted to show how a memoized version can avoid the explicit array management." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:10:16.533", "Id": "269167", "ParentId": "269117", "Score": "0" } }, { "body": "<p>Kill two birds with one stone, documented examples and testing, by using <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctests</a>:</p>\n<pre><code>def levenshtein_distance(s, t):\n &quot;&quot;&quot;Return the Levenshtein edit distance between t and s.\n \n &gt;&gt;&gt; levenshtein_distance('kitten', 'sitting')\n 3\n &gt;&gt;&gt; levenshtein_distance('flaw', 'lawn')\n 2\n &quot;&quot;&quot;\n</code></pre>\n<p>Test the that your code produces these expected results with</p>\n<pre><code>python -mdoctest levenshtein.py\n</code></pre>\n<p>Take the chance to write a good docstring too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T02:47:20.740", "Id": "530998", "Score": "1", "body": "Do note that doctests aren't a substitute for tests nor a substitute for documentation: they serve a number of adjacent purposes, but primarily they supplement (and verify the correctness of) documentation. Ideally, every bug you encounter gets a test once fixed (or potentially prior to fixing in TDD), but you don't want that in your documentation!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:45:49.593", "Id": "269168", "ParentId": "269117", "Score": "1" } } ]
{ "AcceptedAnswerId": "269118", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T23:13:44.007", "Id": "269117", "Score": "7", "Tags": [ "python-3.x" ], "Title": "Levenshtein distance using dynamic programming in Python 3" }
269117
<p>I want to create an <em>In Memory Cache</em> in .Net. The primary usage for this cache would be to store addresses... I want to keep around 1000 addresses in memory and once the cache is full, remove the <em>Least Recently Used</em> address from the cache.</p> <p>Microsoft provide 2 versions of <code>MemoryCache</code>, one is implemented in <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache?view=dotnet-plat-ext-5.0" rel="nofollow noreferrer">System.Runtime.Caching</a> and the other is implemented in <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.memory.memorycache?view=dotnet-plat-ext-5.0" rel="nofollow noreferrer">Microsoft.Extensions.Caching.Memory</a>.</p> <p>The second implementation seems to be more flexible, you can define <strong>Sliding Expiration</strong> (which updates expiration time every time an entry is used) and it also allows to set a size limit for the entries in cache. For example I can set the cache size to 1000 entries... however the problem is that once the cache is full (reached 1000 entries), it does not remove the <em>Least Recently Used</em> entry... instead it ignores additional inserts until some of the existing elements are expired.</p> <p>So I ended up writing my own <strong>Most Recently Used Cache</strong>:</p> <p><strong>MruCache.cs</strong></p> <pre><code>// Most Recently Used Cache public class MruCache&lt;T&gt; { private readonly object _lock; private readonly int _size; private Dictionary&lt;string, MruCacheEntry&lt;T&gt;&gt; _enteries; public MruCache(int size = 1024) { _lock = new object(); _size = size; _enteries = new Dictionary&lt;string, MruCacheEntry&lt;T&gt;&gt;(); } private bool IsFull { get { return _enteries.Count &gt;= _size; } } private int OnePercent { get { int number = _size / 100; return number &lt; 1 ? 1 : number; } } public bool TryGetValue(string key, out T value) { if (_enteries.TryGetValue(key, out MruCacheEntry&lt;T&gt; entry)) { value = _enteries[key].Value; return true; } else { value = default(T); return false; } } public void AddOrUpdate(string key, T value) { lock (_lock) { if (_enteries.ContainsKey(key)) { _enteries[key].Update(value); } else { MakeRoomIfFull(); _enteries.Add(key, new MruCacheEntry&lt;T&gt;(value)); } } } private void MakeRoomIfFull() { if (IsFull) { // get 1% of entries which were Least Recently Used var keysToRemove = _enteries.OrderBy(e =&gt; e.Value.LastUsageTime).Select(e =&gt; e.Key).Take(OnePercent); foreach (var k in keysToRemove) { _enteries.Remove(k); } } } } </code></pre> <p><strong>MruCacheEntry.cs</strong></p> <pre><code>// Most Recently Used Cache Entry public class MruCacheEntry&lt;T&gt; { private T _value; public MruCacheEntry(T value) { Value = value; } public T Value { get { Touch(); return _value; } set { Touch(); _value = value; } } public DateTime LastUsageTime { get; set; } public void Update(T value) { Value = value; } private void Touch() { LastUsageTime = DateTime.Now; } } </code></pre> <p><strong>UnitTests</strong></p> <pre><code>[TestMethod] public void Test_cache_size_4() { var _mruCache = new MruCache&lt;string&gt;(4); _mruCache.AddOrUpdate(&quot;item1&quot;, &quot;1&quot;); _mruCache.AddOrUpdate(&quot;item2&quot;, &quot;2&quot;); _mruCache.AddOrUpdate(&quot;item3&quot;, &quot;3&quot;); _mruCache.AddOrUpdate(&quot;item1&quot;, &quot;new1&quot;); _mruCache.AddOrUpdate(&quot;item4&quot;, &quot;4&quot;); _mruCache.AddOrUpdate(&quot;item5&quot;, &quot;5&quot;); _mruCache.TryGetValue(&quot;item1&quot;, out string valueOfItem1); _mruCache.TryGetValue(&quot;item2&quot;, out string valueOfItem2); _mruCache.TryGetValue(&quot;item3&quot;, out string valueOfItem3); _mruCache.TryGetValue(&quot;noSuchKey&quot;, out string valueOfNoSuchKey); valueOfItem1.Should().Be(&quot;new1&quot;); valueOfItem2.Should().Be(null); valueOfItem3.Should().Be(&quot;3&quot;); valueOfNoSuchKey.Should().Be(null); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T06:53:38.970", "Id": "530888", "Score": "0", "body": "is it possible to use timestamp key instead of `string` ? I'm thinking if you were using a timestamp key, then you can just compare the last usage time and the timestamp (which is the time created). also, why `DateTime.Now` ? are you planning to cache address for more than one day ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T10:08:52.037", "Id": "530906", "Score": "0", "body": "@iSR5: I am using this cache to store frequently used addresses.... the `Key` is normalized StreetAddress (by normalized I mean lowercase and alphanumric, removing evening else)... this way I know if an address is already added to cache or not. At the same time uppercase, lower case, commas and dashes won't make any difference is the address `key`. I want to keep the frequently used addressed in the cache for much more than a day... for example the city of Auckland (which has Lat/Long) remains in the cache for months as it is frequently used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T13:22:07.337", "Id": "530922", "Score": "0", "body": "In that case, you could save some efforts by initiating a case-insensitive `Dictionary`, which would reduce some efforts `_enteries = new Dictionary<string, MruCacheEntry<T>>(StringComparer.InvariantCultureIgnoreCase);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T16:31:23.550", "Id": "530947", "Score": "0", "body": "This code isn't thread-safe. Is it intended to use in multithreaded environment? How about `ConcurrentDictionary` instead of `lock`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:30:17.453", "Id": "530960", "Score": "0", "body": "Wouldn't it be easier to just make a new add Set Extension method to the Microsoft.Extensions.Caching.Memory.MemoryCache that would create a CacheEntry with a PostEvictionCallbacks and if the post evict is called with EvictionReason.Capacity then to do a Spin.Wait and retry?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:29:34.487", "Id": "530971", "Score": "0", "body": "@aepot: thanks for your suggestion, yes the cache is meant to be thread safe, though by adding a `lock` on write operation it has become thread safe? Good suggestion about `ConcurrentDictionary`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:33:23.120", "Id": "530972", "Score": "0", "body": "@CharlesNRice: initially I tried extending MemoryCache (the one provided in *Microsoft.Extensions.Caching.Memory*) but it requires a lot of work, for example there is no built-in method to [get all cache entries](https://github.com/dotnet/runtime/issues/36026) so I decided that it would be easier to write my own code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:13:25.607", "Id": "530984", "Score": "0", "body": "`though by adding a lock on write` actually not. Because reading may occur while writing. Multiple reads - OK, single write - OK, multiple reads while single write is processing - NOT OK. Learn something about `ReaderWriterLockSlim` in case you want to keep `Dictionary`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:22:08.327", "Id": "530988", "Score": "0", "body": "I have rolled back Rev 7 → 4. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<h3>The Least Recently Used cache replacement policy</h3>\n<blockquote>\n<p>I want to keep around 1000 addresses in memory and once the cache is full, remove the Least Recently Used address from the cache.</p>\n</blockquote>\n<p>Based on your description of what you're trying to do, this is called a Least Recently Used cache, not Most Recently Used... See also <a href=\"https://en.wikipedia.org/wiki/Cache_replacement_policies#Most_recently_used_(MRU)\" rel=\"nofollow noreferrer\">wikipedia</a>.</p>\n<h3>Removing the least recently used items efficiently</h3>\n<p>Disclaimer: I don't know much C#.\nThis looks inefficient:</p>\n<blockquote>\n<pre><code>var keysToRemove = _enteries\n .OrderBy(e =&gt; e.Value.LastUsageTime)\n .Select(e =&gt; e.Key)\n .Take(OnePercent);\n</code></pre>\n</blockquote>\n<p>To remove the <code>k</code> smallest items from an unordered set of <code>n</code> items,\nan efficient way I know is <a href=\"https://en.wikipedia.org/wiki/Quickselect\" rel=\"nofollow noreferrer\">quickselect</a>. It's efficient because quickselect doesn't sort all the elements. It uses clever partitioning to find the <code>k</code> smallest, without any precise ordering. It basically comes up with &quot;these bunch of values are all definitely smaller than the rest&quot;. It's a <span class=\"math-container\">\\$k \\log(n)\\$</span> operation.</p>\n<p>I suspect the code above does a regular sort of the full set of items, a <span class=\"math-container\">\\$n \\log(n)\\$</span> operation. This is performed every time some items need to be evicted.</p>\n<p>Although using quickselect would be an improvement,\nthere's a far better data structure for your purpose: linked hashtable.\nThe idea is to use a combination of two data structures to keep the cache entries, keep track of their ordering and manage eviction efficiently:</p>\n<ul>\n<li>a doubly-linked list:\n<ul>\n<li>when a cache entry is added, append at the end</li>\n<li>when a cache entry is updated, remove from the list and append at the end</li>\n<li>when the list is long, delete entries from the front</li>\n</ul>\n</li>\n<li>a dictionary of keys to linked list nodes:\n<ul>\n<li>used for quick lookup of cache entries, with direct access to list nodes</li>\n</ul>\n</li>\n</ul>\n<p>Note that the doubly-linked list is never traversed; nodes are accessed directly. Timestamps are not needed, the position of nodes in the list already express their ordering.</p>\n<h3>Avoid repeated computations</h3>\n<p><code>OnePercent</code> computes the same value on every call, because <code>_size</code> cannot change after construction. You could compute the one percent once at construction.</p>\n<h3>Make chained calls easier to read</h3>\n<p>Instead of this:</p>\n<blockquote>\n<pre><code>var keysToRemove = _enteries.OrderBy(e =&gt; e.Value.LastUsageTime).Select(e =&gt; e.Key).Take(OnePercent);\n</code></pre>\n</blockquote>\n<p>I find it a lot easier to read if you break the line after each step:</p>\n<pre><code>var keysToRemove = _enteries\n .OrderBy(e =&gt; e.Value.LastUsageTime)\n .Select(e =&gt; e.Key)\n .Take(OnePercent);\n</code></pre>\n<p>This is in the same spirit of the general good rule of having one statement per line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:40:58.143", "Id": "530974", "Score": "1", "body": "Thanks a lot. I was not aware of the Cache Replacement Policies that you linked... I called it `Most Recently Used` as I thought it would be the most descriptive name... I spent a lot of time thinking maybe `Least Recently Used` would be a better name... but your Wikipedia link made it all clear." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:38:14.777", "Id": "269157", "ParentId": "269120", "Score": "1" } } ]
{ "AcceptedAnswerId": "269157", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T00:57:18.350", "Id": "269120", "Score": "2", "Tags": [ "c#", "cache" ], "Title": "Implementing a Most Recently Used Cache" }
269120
<p>There are six Binary Tree DFS traversals (preorder, inorder, postorder, and their reverse counterparts). Their implementations can be very similar <sup>1</sup>, so I factored out the core logic into a class <code>Traverser</code> (found in the first code block below). As an example, say you want the &quot;inorder&quot; traversal of a tree whose root is <code>root</code>; you can get it like this: <code>inorder = Traverser(TraversalOrder.INORDER, root)</code>. Now you can iterate over <code>inorder</code> using a for loop (<code>for node in inorder: print(node.val</code>) or you can call <code>iter</code> on it (<code>inorder_iter = iter(inorder); first = next(inorder_iter)</code>. By the way, <code>TraversalOrder.INORDER</code> is nothing more than an alias for <code>'LNR'</code> as these three letters are enough to denote inorder traversal (<strong>L</strong>eft subtree, then <strong>N</strong>ode, then <strong>R</strong>ight subtree). Similarly, the other 5 DFS traversals are denoted by the other 5 permutations of <code>'LNR'</code>. There are more examples and &quot;tests&quot; (found in the second code block below).</p> <p>In general, any suggestions or considerations are welcome, but in particular, I want thoughts on code organization and the API:</p> <ul> <li>Should I nest the <code>TraversalOrder(StrEnum)</code> class within the <code>Traverser</code> class?</li> <li>Are the class/function signatures sensible? Are they surprising or unexpected? Perhaps, the class should return an object that can perform a specific traversal on any tree, rather than on a specific tree as it does now.</li> <li>Also, I have an implementation for level order BFS traversals (found in the third code block below) and would appreciate suggestions on how to incorporate the BFS traversals into the <code>Traverser</code> class?</li> <li>Another thing that can improve is <code>TraversalOrder.reverse</code> which is just a series of <code>if</code> statements. A bimap defined at the class level would be useful here, but it's not possible to define any non-member attributes in the body of an <code>Enum</code> class<sup>2</sup>.</li> </ul> <h2><code>class Traverser</code> and <code>class TraversalOrder(StrEnum)</code>:</h2> <pre><code>from enum import auto, Enum class Traverser: '''Implements the six Binary Tree DFS traversals.''' D = {'L': lambda trav_iter, node: trav_iter(node.left), 'N': lambda trav_iter, node: (node,), 'R': lambda trav_iter, node: trav_iter(node.right)} def __init__(self, order, root): if order in {TraversalOrder.LEVELORDER_LR, TraversalOrder.LEVELORDER_RL}: raise NotImplementedError self.order = order self.root = root def __iter__(self): a, b, c = map(self.D.__getitem__, self.order) def trav_iter(node): if not node: return yield from a(trav_iter, node) yield from b(trav_iter, node) yield from c(trav_iter, node) return trav_iter(self.root) # https://docs.python.org/3/library/enum.html#others class StrEnum(str, Enum): pass class TraversalOrder(StrEnum): '''The six DFS traversals and two BFS traversals for Binary Trees''' PREORDER = 'NLR' INORDER = 'LNR' POSTORDER = 'LRN' REVERSE_PREORDER = 'RLN' REVERSE_INORDER = 'RNL' REVERSE_POSTORDER = 'NRL' LEVELORDER_LR = auto() LEVELORDER_RL = auto() @classmethod def reverse(cls, order): # TODO: Use match/case statements instead of if statements it's when it's supported (Python 3.10). if order == cls.PREORDER: return cls.REVERSE_PREORDER if order == cls.INORDER: return cls.REVERSE_INORDER if order == cls.POSTORDER: return cls.REVERSE_POSTORDER if order == cls.REVERSE_PREORDER: return cls.PREORDER if order == cls.REVERSE_INORDER: return cls.INORDER if order == cls.REVERSE_POSTORDER: return cls.POSTORDER if order == cls.LEVELORDER_LR: return cls.LEVELORDER_RL if order == cls.LEVELORDER_RL: return cls.LEVELORDER_LR class TreeNode: def __init__(self, val=None, left=None, right=None): self.val = val self.left = left self.right = right </code></pre> <hr /> <h2><code>Traverser</code> examples and &quot;tests&quot;:</h2> <pre><code># Example binary tree (this one's a BST, but any binary tree will do): # # https://bit.ly/3aQpqLo # # 7 # / \ # 5 12 # /\ / \ # 3 6 9 15 # /\ /\ / \ # 1 4 8 10 13 17 node1 = TreeNode(1) node4 = TreeNode(4) node3 = TreeNode(3, node1, node4) node6 = TreeNode(6) node5 = TreeNode(5, node3, node6) node8 = TreeNode(8) node10 = TreeNode(10) node9 = TreeNode(9, node8, node10) node13 = TreeNode(13) node17 = TreeNode(17) node15 = TreeNode(15, node13, node17) node12 = TreeNode(12, node9, node15) root = node7 = TreeNode(7, node5, node12) # &quot;Tests&quot;: inorder = Traverser(TraversalOrder.INORDER, root) inorder_str = '' for node in inorder: inorder_str += f'{node.val}, ' assert inorder_str == '1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, ' print('Inorder traveral using `inorder`: passed') inorder_str = '' for node in inorder: inorder_str += f'{node.val}, ' assert inorder_str == '1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, ' print('Inorder traveral using `inorder` again: passed') inorder_iter = iter(inorder) fst = next(inorder_iter) assert fst.val == 1 partial_inorder_str = '' for node in inorder_iter: partial_inorder_str += f'{node.val}, ' assert partial_inorder_str == '3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, ' print('Inorder traversal using the iterator: passed') exhausted_inorder_str = '' for node in inorder_iter: exhausted_inorder_str += f'{node.val}, ' assert not exhausted_inorder_str print('Inorder iterator exhausted: passed') preorder_str = '' for node in Traverser('NLR', root): # 'NLR' denotes preorder traversal preorder_str += f'{node.val}, ' assert preorder_str == '7, 5, 3, 1, 4, 6, 12, 9, 8, 10, 15, 13, 17, ' print('Preorder traversal: passed') </code></pre> <hr /> <h1><code>def levelorder_iter</code> and &quot;tests&quot;:</h1> <p>(assume that <code>root</code> still refers to the binary tree defined above)</p> <pre><code>from operator import attrgetter def levelorder_iter(root, left_to_right=True): a, b = attrgetter('left'), attrgetter('right') if not left_to_right: a, b = b, a nodes0 = [root] nodes1 = [] while nodes0: for node0 in nodes0: yield node0 for node1 in (a(node0), b(node0)): if node1: nodes1.append(node1) nodes0, nodes1 = nodes1, nodes0 nodes1.clear() # &quot;Tests&quot; levelorder_lr = levelorder_iter(root) # generator, iterator, gets exhausted after the for loop levelorder_lr_str = '' for node in levelorder_lr: levelorder_lr_str += f'{node.val}, ' assert levelorder_lr_str == '7, 5, 12, 3, 6, 9, 15, 1, 4, 8, 10, 13, 17, ' print('Levelorder left to right traversal: passed') levelorder_rl = levelorder_iter(root, left_to_right=False) # generator, iterator, gets exhausted after the for loop levelorder_rl_str = '' for node in levelorder_rl: levelorder_rl_str += f'{node.val}, ' assert levelorder_rl_str == '7, 12, 5, 15, 9, 6, 3, 17, 13, 10, 8, 4, 1, ' print('Levelorder right to left traversal: passed') </code></pre> <hr /> <p><sup>1</sup> <em>Implementations of all 6 DFS traversals and 2 BFS traversals for Binary Trees:</em></p> <pre><code>+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------+ | DFS/BFS | DFS Traversals | BFS Traversals | +============+==========================+=========================================+=========================================+===========================================+==================================================+=================================================+==================================================+====================================================+ | | | | | | reverse | reverse | reverse | level | | order | generic | preorder | inorder | postorder | preorder | inorder | postorder | order | | +--------------------------+-----------------------------------------+-----------------------------------------+-------------------------------------------+--------------------------------------------------+-------------------------------------------------+--------------------------------------------------+--------------------------+-------------------------+ | | ABC | NLR | LNR | LRN | RLN | RNL | NRL | left to right | right to left | +------------+--------------------------+-----------------------------------------+-----------------------------------------+-------------------------------------------+--------------------------------------------------+-------------------------------------------------+--------------------------------------------------+--------------------------+-------------------------+ | generator, | def generic_iter*(node): | def preoder_iter(node): | def inorder_iter(node): | def postorder_iter(node): | def reverse_preoder_iter(node): | def reverse_inoder_iter(node): | def reverse_postoder_iter(node): | from operator import attrgetter | | iterator | if not node: | if not node: | if not node: | if not node: | if not node: | if not node: | if not node: | | | | return | return | return | return | return | return | return | def levelorder_iter(root, left_to_right=True): | | | yield from A | yield node | yield from inorder_iter(node.left) | yield from postorder_iter(node.left) | yield from reverse_preorder_iter(node.right) | yield from reverse_inorder_iter(node.right) | yield node | a, b = attrgetter('left'), attrgetter('right') | | | yield from B | yield from preoder_iter(node.left) | yield node | yield from postorder_iter(node.right) | yield from reverse_preorder_iter(node.left) | yield node | yield from reverse_postoder_iter(node.right) | if not left_to_right: | | | yield from C | yield from preoder_iter(node.right) | yield from inorder_iter(node.right) | yield node | yield node | yield from reverse_inorder_iter(node.left) | yield from reverse_postoder_iter(node.left) | a, b = b, a | +------------+ +-----------------------------------------+-----------------------------------------+-------------------------------------------+--------------------------------------------------+-------------------------------------------------+--------------------------------------------------+ nodes0 = [root] | | list v1 | *just for | def preorder_list(node): | def inorder_list(node): | def postorder_list(node): | def reverse_preorder_list(node): | def reverse_inorder_list(node): | def reverse_postorder_list(node): | nodes1 = [] | | | illustration, | return list(preoder_iter) | return list(inoder_iter) | return list(postorder_iter(node)) | return list(reverse_preorder_iter(node)) | return list(reverse_inorder_iter(node)) | return list(reverse_postorder_iter(node)) | while nodes0: | +------------+ see post for +-----------------------------------------+-----------------------------------------+-------------------------------------------+--------------------------------------------------+-------------------------------------------------+--------------------------------------------------+ for node0 in nodes0: | | list v2 | actual impl | def preorder_list(node): | def inorder_list(node): | def postorder_list(ndoe): | def reverse_preorder_list(node): | def reverse_inorder_list(node): | def reverse_postorder_list(node): | yield node0 | | | | def pre(node): | def in_(node): | def post(node): | def rev_pre(node): | def rev_in(node): | def rev_post(node): | for node1 in (a(node0), b(node0)): | | | | if not node: | if not node: | if not node: | if not node: | if not node: | if not node: | if node1: | | | | return | return | return | return | return | return | nodes1.append(node1) | | | | preorder.append(node) | in_(node.left) | post(node.left) | rev_pre(node.right) | rev_in(node.right) | reverse_postorder.append(node) | nodes0, nodes1 = nodes1, nodes0 | | | | pre(node.left) | inorder.append(node) | post(node.right) | rev_pre(node.left) | reverse_inorder.append(node) | rev_post(node.right) | nodes1.clear() | | | | pre(node.right) | in_(node.right) | postorder.append(node) | reverse_preorder.append(node) | rev_in(node.left) | rev_post(node.left) | | | | | | | | | | | | | | | preorder = [] | inorder = [] | postorder = [] | reverse_preorder = [] | reverse_inorder = [] | reverse_postorder = [] | | | | | pre(node) | in_(node) | post(node) | rev_pre(node) | rev_in(node) | rev_post(node) | | | | | return preorder | return inorder | return postorder | return reverse_preorder | return reverse_inorder | return reverse_postorder | | +------------+--------------------------+-----------------------------------------+-----------------------------------------+-------------------------------------------+--------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ </code></pre> <p><em>text table made using tablesgenerator.com/text_tables</em></p> <p><sup>2</sup> <a href="https://docs.python.org/3/library/enum.html?highlight=enum#allowed-members-and-attributes-of-enumerations" rel="nofollow noreferrer">https://docs.python.org/3/library/enum.html?highlight=enum#allowed-members-and-attributes-of-enumerations</a></p> <blockquote> <p>The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (<strong>str</strong>(), <strong>add</strong>(), etc.), descriptors (methods are also descriptors), and variable names listed in <em>ignore</em>.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T03:47:37.030", "Id": "269121", "Score": "0", "Tags": [ "iterator", "breadth-first-search", "depth-first-search", "generator", "binary-tree" ], "Title": "Binary Tree DFS and BFS traversalsclass [python3]" }
269121
<p>I have put together a small node application with <strong>Express.js</strong> and <strong><a href="https://jsonplaceholder.typicode.com" rel="nofollow noreferrer">jsonplaceholder</a></strong>.</p> <p>On the homepage, it displays posts by all users. You can also filter posts by one user (author).</p> <p>In <code>app.js</code> I have:</p> <pre><code>var createError = require('http-errors'); var express = require('express'); var axios = require('axios'); var path = require('path'); var cookieParser = require('cookie-parser'); var expressLayouts = require('express-ejs-layouts'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var app = express(); global.base_url = 'https://jsonplaceholder.typicode.com'; global.title = 'Express Magazine'; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(expressLayouts); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/users', usersRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; </code></pre> <p>In <code>routes\index.js</code>:</p> <pre><code>const express = require('express'); const indexController = require('../controllers/index'); const router = express.Router(); // Get Posts router.get('/', indexController.getHomepageData); // Get Posts By User router.get('/users/:uid/posts/', indexController.getPostsByUser); // Redirect from bad routes router.get('/users/', function(req, res) { res.redirect('/'); }); router.get('/users/:uid/', function(req, res) { res.redirect('/'); }); module.exports = router; </code></pre> <p>In the routes file I have:</p> <pre><code>const express = require('express'); const indexController = require('../controllers/index'); const router = express.Router(); // Get Posts router.get('/', indexController.getHomepageData); // Get Posts By User router.get('/users/:uid/posts/', indexController.getPostsByUser); // Redirect from bad routes router.get('/users/', function(req, res) { res.redirect('/'); }); router.get('/users/:uid/', function(req, res) { res.redirect('/'); }); module.exports = router; </code></pre> <p>The <code>indexController</code> controler has the folwing code:</p> <pre><code>var axios = require('axios'); var helpers = require('../utils/helpers'); /* GET home page data */ exports.getHomepageData = async (req, res, next) =&gt; { try { let [userData, postData] = await Promise.all([ axios.get(`${base_url}/users`), axios.get(`${base_url}/posts`) ]); const users = userData.data; const posts = postData.data; res.render('index', { layout: 'layout', pageTitle: 'All posts', users: users, currentUser: null, posts: posts, }); } catch (error) { res.status(500).json(error); } }; /* GET posts by user */ exports.getPostsByUser = async (req, res, next) =&gt; { try { let uid = req.params.uid; let [userData, currentUserData, postData] = await Promise.all([ axios.get(`${base_url}/users`), axios.get(`${base_url}/users/${uid}`), axios.get(`${base_url}/posts?userId=${uid}`) ]); const users = userData.data; const currentUser = currentUserData.data; const posts = postData.data; res.render('index', { layout: 'layout', users: users, posts: posts, currentUser: currentUser, pageTitle: `Posts by ${currentUser.name}`, }); } catch (error) { res.status(500).json(error); } }; </code></pre> <p>In the index.ejs view I use the above finctions. Sample:</p> <pre><code>&lt;% if (posts) {%&gt; &lt;div class=&quot;row post-grid&quot;&gt; &lt;% posts.forEach(function(post) { %&gt; &lt;div class=&quot;col-sm-6 post&quot;&gt; &lt;div class=&quot;post-container&quot;&gt; &lt;h2 class=&quot;display-4 post-title&quot;&gt;&lt;%= post.title.toTitleCase() %&gt;&lt;/h2&gt; &lt;div class=&quot;short-desc&quot;&gt; &lt;%= post.body.capitalizeSentence() %&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;% }); %&gt; &lt;/div&gt; &lt;% } %&gt; </code></pre> <p>The application works, but I am certain there is room for improvement.</p> <h4>Questions</h4> <ol> <li>Is the code DRY enough?</li> <li>Is it missing anything <em>essential</em>?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T21:49:47.113", "Id": "530980", "Score": "0", "body": "Could you please [edit] to include the contents of `routes/users.js`? and is `helpers` actually used by the code in `indexController`? If so, what for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T07:55:07.200", "Id": "531016", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I have added the required code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T08:06:02.133", "Id": "531017", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ In fact, you can see the entire repo **[here](https://github.com/Ajax30/express-posts)**, if you want." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T05:04:14.653", "Id": "269122", "Score": "1", "Tags": [ "javascript", "express.js" ], "Title": "Express.js and jsonplaceholder application" }
269122
<p>I'd like to have a review on my C-style array wrapper. I based this on std::array implementation. I hope you can leave some feedback!</p> <h2>array.ixx</h2> <pre><code>module; #include &lt;cstddef&gt; #include &lt;stdexcept&gt; #include &lt;utility&gt; #include &lt;type_traits&gt; #include &lt;compare&gt; export module array; export namespace stl { template&lt;class T, std::size_t N&gt; struct array { using value_type = T; using size_type = std::size_t; using reference = value_type&amp;; using const_reference = const value_type&amp;; using pointer = value_type*; using const_pointer = const value_type*; using iterator = value_type*; using const_iterator = const value_type*; T _items[N ? N : 1]; constexpr reference at(size_type pos); constexpr const_reference at(size_type pos) const; constexpr reference operator[](size_type pos); constexpr const_reference operator[](size_type pos) const; constexpr reference front(); constexpr const_reference front() const; constexpr reference back(); constexpr const_reference back() const; constexpr pointer data() noexcept; constexpr const_pointer data() const noexcept; constexpr iterator begin() noexcept; constexpr iterator end() noexcept; constexpr const_iterator begin() const noexcept; constexpr const_iterator end() const noexcept; [[nodiscard]] constexpr bool empty() const noexcept; constexpr size_type size() const noexcept; constexpr size_type max_size() const noexcept; constexpr void fill(value_type value); constexpr void swap(array&amp; other) noexcept(std::is_nothrow_swappable_v&lt;T&gt;); }; template&lt;std::size_t I, class T, std::size_t N&gt; constexpr T&amp; get(array&lt;T, N&gt;&amp; a) noexcept; template&lt;std::size_t I, class T, std::size_t N&gt; constexpr const T&amp; get(const array&lt;T, N&gt;&amp; a) noexcept; template&lt;std::size_t I, class T, std::size_t N&gt; constexpr T&amp;&amp; get(array&lt;T, N&gt;&amp;&amp; a) noexcept; template&lt;std::size_t I, class T, std::size_t N&gt; constexpr const T&amp;&amp; get(const array&lt;T, N&gt;&amp;&amp; a) noexcept; template&lt;class T, std::size_t N&gt; constexpr bool operator==(const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); template&lt;class T, std::size_t N&gt; constexpr auto operator&lt;=&gt;(const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); } template&lt;class T, std::size_t N&gt; constexpr T&amp; stl::array&lt;T, N&gt;::at(size_type pos) { /** * @brief: Returns a reference to the element at specified location pos, with bounds checking. * If pos is not within the range of the container, an exception of type std::out_of_range is thrown. * * @param: pos - position of the element to return. * * @return: Reference to the requested element. * * @excep: std::out_of_range if !(pos &lt; size()). * * @complex: O(1). */ return !(pos &lt; N) ? throw std::out_of_range(&quot;Out of range&quot;) : _items[pos]; } template&lt;class T, std::size_t N&gt; constexpr const T&amp; stl::array&lt;T, N&gt;::at(size_type pos) const { /** * @brief: Returns a reference to the element at specified location pos, with bounds checking. * If pos is not within the range of the container, an exception of type std::out_of_range is thrown. * * @param: pos - position of the element to return. * * @return: Reference to the requested element. * * @excep: std::out_of_range if !(pos &lt; size()). * * @complex: O(1). */ return !(pos &lt; size()) ? throw std::out_of_range(&quot;Out of range&quot;) : _items[pos]; } template&lt;class T, std::size_t N&gt; constexpr T&amp; stl::array&lt;T, N&gt;::operator[](size_type pos) { /** * @brief: Returns a reference to the element at specified location pos. No bounds checking is performed. * * @param: pos - position of the element to return. * * @return: Reference to the requested element. * * @excep: None; * * @complex: O(1). */ return _items[pos]; } template&lt;class T, std::size_t N&gt; constexpr const T&amp; stl::array&lt;T, N&gt;::operator[](size_type pos) const { /** * @brief: Returns a reference to the element at specified location pos. No bounds checking is performed. * * @param: pos - position of the element to return. * * @return: Reference to the requested element. * * @excep: None; * * @complex: O(1). */ return _items[pos]; } template&lt;class T, std::size_t N&gt; constexpr T&amp; stl::array&lt;T, N&gt;::front() { /** * @brief: Returns a reference to the first element in the container. * Calling front on an empty container is undefined. * * @param: None. * * @return: Reference to the first element. * * @excep: None; * * @complex: O(1). */ return *_items; } template&lt;class T, std::size_t N&gt; constexpr const T&amp; stl::array&lt;T, N&gt;::front() const { /** * @brief: Returns a reference to the first element in the container. * Calling front on an empty container is undefined. * * @param: None. * * @return: Reference to the first element. * * @excep: None; * * @complex: O(1). */ return *_items; } template&lt;class T, std::size_t N&gt; constexpr T&amp; stl::array&lt;T, N&gt;::back() { /** * @brief: Returns a reference to the last element in the container. * Calling back on an empty container causes undefined behavior. * * @param: None. * * @return: Reference to the last element. * * @excep: None; * * @complex: O(1). */ return *(_items + N); } template&lt;class T, std::size_t N&gt; constexpr const T&amp; stl::array&lt;T, N&gt;::back() const { /** * @brief: Returns a reference to the last element in the container. * Calling back on an empty container causes undefined behavior. * * @param: None. * * @return: Reference to the last element. * * @excep: None; * * @complex: O(1). */ return *(_items + N); } template&lt;class T, std::size_t N&gt; constexpr T* stl::array&lt;T, N&gt;::data() noexcept { /** * @brief: Returns pointer to the underlying array serving as element storage. * * @param: None. * * @return: Pointer to the underlying element storage. For non-empty containers, * the returned pointer compares equal to the address of the first element. * * @excep: None; * * @complex: O(1). */ return _items; } template&lt;class T, std::size_t N&gt; constexpr const T* stl::array&lt;T, N&gt;::data() const noexcept { /** * @brief: Returns pointer to the underlying array serving as element storage. * * @param: None. * * @return: Pointer to the underlying element storage. For non-empty containers, * the returned pointer compares equal to the address of the first element. * * @excep: None; * * @complex: O(1). */ return _items; } template&lt;class T, std::size_t N&gt; constexpr T* stl::array&lt;T, N&gt;::begin() noexcept { /** * @brief: Returns an iterator to the first element of the array. * If the array is empty, the returned iterator will be equal to end(). * * @param: None. * * @return: Iterator to the first element. * * @excep: None; * * @complex: O(1). */ return _items; } template&lt;class T, std::size_t N&gt; constexpr T* stl::array&lt;T, N&gt;::end() noexcept { /** * @brief: Returns an iterator to the element following the last element of the array. * This element acts as a placeholder; attempting to access it results in undefined behavior. * * @param: None. * * @return: Iterator to the element following the last element. * * @excep: None; * * @complex: O(1). */ return _items + N; } template&lt;class T, std::size_t N&gt; constexpr const T* stl::array&lt;T, N&gt;::begin() const noexcept { /** * @brief: Returns an iterator to the first element of the array. * If the array is empty, the returned iterator will be equal to end(). * * @param: None. * * @return: Iterator to the first element. * * @excep: None; * * @complex: O(1). */ return _items; } template&lt;class T, std::size_t N&gt; constexpr const T* stl::array&lt;T, N&gt;::end() const noexcept { /** * @brief: Returns an iterator to the element following the last element of the array. * This element acts as a placeholder; attempting to access it results in undefined behavior. * * @param: None. * * @return: Iterator to the element following the last element. * * @excep: None; * * @complex: O(1). */ return _items + N; } template&lt;class T, std::size_t N&gt; constexpr bool stl::array&lt;T, N&gt;::empty() const noexcept { /** * @brief: Checks if the container has no elements, i.e. whether begin() == end(). * * @param: None. * * @return: true if the container is empty, false otherwise. * * @excep: None; * * @complex: O(1). */ return begin() == end(); } template&lt;class T, std::size_t N&gt; constexpr std::size_t stl::array&lt;T, N&gt;::size() const noexcept { /** * @brief: Returns the number of elements in the container. * * @param: None. * * @return: The number of elements in the container. * * @excep: None; * * @complex: O(1). */ return N; } template&lt;class T, std::size_t N&gt; constexpr std::size_t stl::array&lt;T, N&gt;::max_size() const noexcept { /** * @brief: Returns the maximum number of elements the container is able to * hold due to system or library implementation limitations. * * @param: None. * * @return: Maximum number of elements. * * @excep: None; * * @complex: O(1). */ return N; } template&lt;class T, std::size_t N&gt; constexpr void stl::array&lt;T, N&gt;::fill(value_type value) { /** * @brief: Assigns the given value value to all elements in the container. * * @param: value - the value to assign to the elements * * @return: None. * * @excep: None; * * @complex: O(n). */ for (auto&amp; i : _items) { i = value; } } template&lt;class T, std::size_t N&gt; constexpr void stl::array&lt;T, N&gt;::swap(array&amp; other) noexcept(std::is_nothrow_swappable_v&lt;T&gt;) { /** * @brief: Exchanges the contents of the container with those of other. * * @param: other - container to exchange the contents with * * @return: None. * * @excep: None; * * @complex: O(n). */ for (std::size_t i = 0; i &lt; size(); i++) { std::swap(_items[i], other[i]); } } template&lt;std::size_t I, class T, std::size_t N&gt; constexpr T&amp; stl::get(array&lt;T, N&gt;&amp; a) noexcept { /** * @brief: Extracts the Ith element element from the array. * I must be an integer value in range [0, N). * * @param: array - whose contents to extract * * @return: A reference to the Ith element of a. * * @excep: None; * * @complex: O(1). */ static_assert(I &lt; a.size()); return a[I]; } template&lt;std::size_t I, class T, std::size_t N&gt; constexpr T&amp;&amp; stl::get(array&lt;T, N&gt;&amp;&amp; a) noexcept { /** * @brief: Extracts the Ith element element from the array. * I must be an integer value in range [0, N). * * @param: array - whose contents to extract * * @return: A reference to the Ith element of a. * * @excep: None; * * @complex: O(1). */ static_assert(I &lt; a.size()); return a[I]; } template&lt;std::size_t I, class T, std::size_t N&gt; constexpr const T&amp; stl::get(const array&lt;T, N&gt;&amp; a) noexcept { /** * @brief: Extracts the Ith element element from the array. * I must be an integer value in range [0, N). * * @param: array - whose contents to extract * * @return: A reference to the Ith element of a. * * @excep: None; * * @complex: O(1). */ static_assert(I &lt; a.size()); return a[I]; } template&lt;std::size_t I, class T, std::size_t N&gt; constexpr const T&amp;&amp; stl::get(const array&lt;T, N&gt;&amp;&amp; a) noexcept { /** * @brief: Extracts the Ith element element from the array. * I must be an integer value in range [0, N). * * @param: array - whose contents to extract * * @return: A reference to the Ith element of a. * * @excep: None; * * @complex: O(1). */ static_assert(I &lt; a.size()); return a[I]; } template&lt;class T, std::size_t N&gt; constexpr bool stl::operator==(const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { /** * @brief: Checks if the contents of lhs and rhs are equal, that is, they have the same number of elements * and each element in lhs compares equal with the element in rhs at the same position. * * @param: lhs, rhs - arrays whose contents to compare. * * @return: true if the contents of the arrays are equal, false otherwise. * * @excep: None; * * @complex: O(n). */ std::equal(lhs.begin(), lhs.end(), rhs.begin()); } template&lt;class T, std::size_t N&gt; constexpr auto stl::operator&lt;=&gt;(const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { /** * @brief: The comparison is performed as if by calling std::lexicographical_compare_three_way on two arrays * with a function object performing synthesized three-way comparison * * @param: lhs, rhs - arrays whose contents to compare. * * @return: lhs.size() &lt;=&gt; rhs.size(). * * @excep: None; * * @complex: O(1). */ return lhs.size() &lt;=&gt; rhs.size(); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:16:57.357", "Id": "530933", "Score": "0", "body": "It's nice to see _someone_ using modules!" } ]
[ { "body": "<pre><code>template&lt;class T, std::size_t N&gt;\nconstexpr const T&amp; stl::array&lt;T, N&gt;::back() const\n{\n return *(_items + N);\n}\n</code></pre>\n<p><strong>bug:</strong> Shouldn't this be accessing element <code>(N - 1)</code>?</p>\n<p>(Same issue with the non-const version).</p>\n<hr />\n<p>Otherwise everything looks pretty good. It's just nitpicking below:</p>\n<hr />\n<pre><code> T _items[N ? N : 1];\n</code></pre>\n<p>I think this works (allows zero-sized array with no compiler error, still ensures that <code>begin() == end()</code> because we use <code>N</code> to calculate them). But some comments to explain it would be nice.</p>\n<hr />\n<pre><code>template&lt;class T, std::size_t N&gt;\nconstexpr T&amp; stl::array&lt;T, N&gt;::at(size_type pos)\n{\n return !(pos &lt; N) ? throw std::out_of_range(&quot;Out of range&quot;) : _items[pos];\n}\n</code></pre>\n<p>Just style, but I think it's a bit clearer to put the <code>throw</code> outside of the <code>return</code> statement (we don't return anything if we throw).</p>\n<pre><code>template&lt;class T, std::size_t N&gt;\nconstexpr T&amp; stl::array&lt;T, N&gt;::at(size_type pos)\n{\n if (!(pos &lt; N)) \n throw std::out_of_range(&quot;Out of range&quot;);\n \n return _items[pos];\n}\n</code></pre>\n<hr />\n<pre><code>template&lt;class T, std::size_t N&gt;\nconstexpr void stl::array&lt;T, N&gt;::swap(array&amp; other) noexcept(std::is_nothrow_swappable_v&lt;T&gt;)\n{\n for (std::size_t i = 0; i &lt; size(); i++)\n {\n std::swap(_items[i], other[i]);\n }\n}\n</code></pre>\n<p>Could use the <code>size_type</code> typedef for the loop index.</p>\n<p>There is an array version of <code>std::swap</code> which calls <code>std::swap_ranges</code> internally, so I think we can just do: <code>std::swap(_items, other._items)</code>.</p>\n<hr />\n<p>Don't forget to implement reverse iterators!</p>\n<hr />\n<p>If you want to go for completeness, there's also <code>make_array</code>, <code>to_array</code>, <code>tuple_size</code>, <code>tuple_element</code> and the deduction guide. <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\">See cppreference</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T11:45:58.700", "Id": "530913", "Score": "0", "body": "What do you mean by \"deudction guide\"? Anyway, thank you for the review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T11:54:46.090", "Id": "530914", "Score": "2", "body": "The deduction guide lets users write something like: `std::array a{ 1, 2, 3, 4};` without directly specifying the type or size: https://en.cppreference.com/w/cpp/container/array/deduction_guides" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:19:04.830", "Id": "530934", "Score": "0", "body": "re `throw` inside the `return`: it could be legacy from an implementation that was written right after `constexpr` functions were added, when that was how you had to do it. Like, 10 years ago." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T16:50:04.693", "Id": "531065", "Score": "1", "body": "`!(pos < N)` should *really* be written `pos >= N` for integral types. Complexity is bad. `T _items[N ? N : 1];` does not work for types which aren't trivially (or at least cheaply without side-effects) default-constructible for `N == 0`. `std::array<T, 0> x;` and `std::array<T, 0> x {};` must always be valid, side-effect free and dirt cheap." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T11:20:22.980", "Id": "269128", "ParentId": "269126", "Score": "4" } } ]
{ "AcceptedAnswerId": "269128", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T10:34:48.593", "Id": "269126", "Score": "5", "Tags": [ "c++", "array", "c++20" ], "Title": "C++20 std::array implementation" }
269126
<p>I have 3 different lists which I get in 3 separate API calls.</p> <ol> <li><code>persons</code> 2. <code>cars</code> 3. <code>categories</code></li> </ol> <p>What I need to do is:</p> <ol> <li>Get <code>persons</code> -&gt; then pull cars ids from the <code>persons</code> list</li> <li>Gel <code>cars</code> based on the cares ids I got on #1 -&gt; then pull categories ids from the <code>cars</code> list</li> <li>Get <code>categories</code> based on categories ids I got on #2 -&gt; then get all <code>categories</code> names and <code>cars</code> names.</li> </ol> <p>Desired output:</p> <pre><code>tags=[{&quot;categoryName&quot;:&quot;&quot;, &quot;carName&quot;:&quot;&quot;},{&quot;categoryName&quot;:&quot;&quot;, &quot;carName&quot;:&quot;&quot;}...] </code></pre> <p>This is what I did, I don't find it much readable, would appreciate any refactor/alternative</p> <pre><code>let persons= [ {carId: '020e49c9-3c31-4abf-b83c-d2ebdc026300'}, {carId: '0fb208e4-dec7-44d1-aea4-e15712455146'}, {carId: '00a10008-09c3-4bab-81de-34c1eae3e0ca'}, {carId: '00a10008-09c3-4bab-81de-34c1eae3e0ca'}, {carId: '14d7456c-6a94-467f-a1a0-bcb15c9120ef'} ] persons= new Map( persons.map(p =&gt; [p.carId, p]) ) categories= new Map( categories.data.map(c =&gt; [c.id, c.name]) ) const carsPerCategory = cars.data .filter(({id}) =&gt; persons.get(id)) .map(({name, categoryId}) =&gt; ({ description: name, category: categories.get(categoryId) })) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:45:43.850", "Id": "530964", "Score": "1", "body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:07:05.573", "Id": "530966", "Score": "0", "body": "@pacmaninbw Ok, will know for next tine, thanks for your comment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:18:12.480", "Id": "530968", "Score": "1", "body": "In this case I left the edit because the person that answered should have just commented and let you improve the post." } ]
[ { "body": "<h1>Inconsistent Requirements</h1>\n<p>You state the following</p>\n<blockquote>\n<p>What I need to do is:\nGet persons -&gt; then pull cars ids from the persons list\nGel cars based on the cares ids I got on #1 -&gt; then pull categories ids from the cars list\nGet categories based on categories ids I got on #2 -&gt; then get all categories names.</p>\n</blockquote>\n<p>And then show some example output (which looks like it's malformed)</p>\n<blockquote>\n<p>tags=[\n{\n&quot;categoriesName&quot;:&quot;&quot;,\n&quot;carsName&quot;:&quot;&quot;\n}</p>\n</blockquote>\n<p>Which seems to have a different form than the final step in the &quot;What I need to do is&quot; description.</p>\n<p>This inconsistency and malformed example output makes it slightly hard to review - but if we assume that the example output is what is desired, the following implementation may be useful</p>\n<h2>Possible Implementation</h2>\n<pre class=\"lang-javascript prettyprint-override\"><code>const carIds = new Set([Object.entries(persons).map(([key, value]) =&gt; value)]);\n\ncategoryNamesByCategoryId = new Map(categories.data.map(c =&gt; [c.id, c.name]));\n\nconst carsPerCategory = cars.data\n .filter(({ id }) =&gt; carIds.has(id))\n .map(({ name, categoryId }) =&gt; ({\n carName: name,\n categoryName: categoryNamesByCategoryId.get(categoryId)\n })\n );\n</code></pre>\n<h2>Naming</h2>\n<p>I like to name my mappings something like <code>{values}By{key}</code>. So in this case, the <code>categories</code> <code>Map</code> would be <code>categoryNamesByCategoryId</code>. I think this is expresses the nature of the data structure more-so than the name <code>categories</code> would imply a list / array / set of categories (to me, at the very least).</p>\n<p><code>carsPerCategory</code> also seems misnamed - it looks like an array of objects which have two properties - a <code>description</code> property and a <code>category</code> property. Something like <code>carNameAndCategory</code> or <code>cars</code> might be better, but honestly, I think a <code>Map</code> data structure might be more natural here where you have the car name as the key and the category as the value.</p>\n<p>Also note that the <code>description</code> property seems improperly named as it's really the car <em>name</em>, at least based on what I can infer from the property destructuring, and that the <code>category</code> property doesn't refer to a <code>Category</code> object or multiple <code>Category</code> properties but the category name. I think for readers, it would be clearer if <code>category</code> was renamed to <code>categoryName</code>.</p>\n<h2>Data Structures</h2>\n<p>I don't think you need a <code>persons</code> <code>Map</code> - you're only using the <code>persons</code> <code>Map</code> to filter data, so basically using the <code>carId</code> keys as a <code>Set</code> to filter against. I think it's more natural to simply produce that <code>Set</code> vs. allocating a <code>Map</code> where the <code>value</code> is not necessary.</p>\n<p>One additional thing - it was never clear if an additional filter was needed for categories, to guarantee that every car had a non-<code>undefined</code> <code>categoryName</code> associated with it.</p>\n<h2>Variable Reassignment</h2>\n<p>I think the <code>let persons</code> variable declaration to then re-assign <code>persons</code> shortly after is not desirable.</p>\n<p>First of all, <code>persons</code> was initially an array of objects, then was assigned to a <code>Map</code>. These are pretty different data structures and would seem odd that the same variable could represent both data structures on a philosophical level.</p>\n<p>Secondly, I believe you could generate the <code>Map</code> in a single statement like</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const personsById = new Map(\n ...[\n //data\n ].map(person =&gt; [person.carId, person])\n)\n</code></pre>\n<p>The upside is that you can declare <code>personsById</code> as a <code>const</code> and avoid using a <code>let</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:51:05.467", "Id": "530965", "Score": "2", "body": "If the question is unclear, please leave a comment instead of an answer. If you answer and the question is improved, there will be answer invalidation while the answer was premature." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:02:20.263", "Id": "269147", "ParentId": "269127", "Score": "-1" } } ]
{ "AcceptedAnswerId": "269147", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T10:42:40.667", "Id": "269127", "Score": "0", "Tags": [ "javascript" ], "Title": "Get data from a chain of lists" }
269127
<p>I'm learning C++, and would like some guidance. I'm pretty sure I'm doing something wrong.</p> <p>This algorithm runs in O(n) time and uses O(n) external space. Could I make a more efficient algorithm for doing this, time and memory-wise? Also, could I multi-thread this?</p> <p>Here is my code. Ignore my coding style, I like making it minimal:</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; std::ostream&amp;operator&lt;&lt;(std::ostream&amp;ost,const std::vector&lt;int&gt;&amp;input){ for(auto const&amp;inp:input){ ost&lt;&lt;inp&lt;&lt;&quot; &quot;; } return ost; } int main(){ std::vector&lt;int&gt;nums={1,2,3,4,5,6,7,8,9}; std::vector&lt;int&gt;evens; std::vector&lt;int&gt;odds; for(int ctr=0;ctr&lt;nums.size();ctr++){ if(nums[ctr]%2){ odds.push_back(nums[ctr]); }else{ evens.push_back(nums[ctr]); } } std::cout&lt;&lt;evens; std::cout&lt;&lt;odds; std::cout&lt;&lt;&quot;\n&quot;; } </code></pre>
[]
[ { "body": "<pre><code>std::ostream&amp;operator&lt;&lt;(std::ostream&amp;ost,const std::vector&lt;int&gt;&amp;input){\n</code></pre>\n<p>It's not just style.</p>\n<p>Peopledontwritelikethisbecauseitsreally reallyhardtoreadthisiswhatyourcodelookslikedontdoit.</p>\n<p>...</p>\n<p>Please use a reasonable amount of whitespace. Being able to read the code easily is a huge step towards understanding it:</p>\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; ost, const std::vector&lt;int&gt;&amp; input) {\n</code></pre>\n<hr />\n<pre><code>for(int ctr=0;ctr&lt;nums.size();ctr++)\n</code></pre>\n<p><code>int</code> isn't the correct type for indexing a vector. It should be <code>std::size_t</code> or <code>std::vector&lt;int&gt;::size_type</code> if we want to be picky.</p>\n<p>But we could just use a range-based for loop here too:</p>\n<pre><code>for (int n : nums) { ... }\n</code></pre>\n<hr />\n<p>Otherwise it looks pretty reasonable.</p>\n<p>We could use <a href=\"https://en.cppreference.com/w/cpp/algorithm/partition_copy\" rel=\"nofollow noreferrer\"><code>std::partition_copy</code> from the <code>&lt;algorithm&gt;</code> header</a> to implement this if we wanted to:</p>\n<pre><code> std::partition_copy(\n nums.begin(), nums.end(), \n std::back_inserter(odds), std::back_inserter(evens),\n [] (int n) { return n % 2; });\n</code></pre>\n<p>(And we could pass an execution policy to it for easy parallelization if we really wanted to - which seems overkill for splitting a vector of 9 numbers).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T16:44:07.270", "Id": "269145", "ParentId": "269138", "Score": "3" } }, { "body": "<pre><code> for(int ctr=0;ctr&lt;nums.size();ctr++){\n if(nums[ctr]%2){\n odds.push_back(nums[ctr]);\n }else{\n evens.push_back(nums[ctr]);\n }\n }\n</code></pre>\n<p>Well, you are repeating <code>nums[ctr]</code> three different places. Using the proper looping construct takes care of this automatically:</p>\n<pre><code>for (const auto x : nums) {\n</code></pre>\n<p>Now you already have the value in a simple named variable <code>x</code> and don't need to use the index at all.</p>\n<p>Normally you don't want to repeat the same code in the if/else branches with only a small change to which variable is being used or something like that. Here, what you are doing is very simple so it's not as much as an issue, but you can still be clearer by saying</p>\n<ul>\n<li>the odd/even chooses the target collection</li>\n<li>it always does something with the target collection</li>\n</ul>\n<p>This could be written</p>\n<pre><code> const bool is_even = x%2;\n (is_even?evens:odds).push_back(x);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T18:19:05.727", "Id": "269154", "ParentId": "269138", "Score": "2" } } ]
{ "AcceptedAnswerId": "269145", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:28:04.240", "Id": "269138", "Score": "0", "Tags": [ "c++", "object-oriented", "complexity", "bitwise", "vectors" ], "Title": "Separating odd numbers and even numbers into two vectors in C++" }
269138
<p>At heart, this program is just the basic <a href="https://en.wikipedia.org/wiki/Fizz_buzz" rel="nofollow noreferrer">&quot;FizzBuzz&quot; program</a>. However, the program was pushed further, by making it a client-server via Unix Socket:</p> <ol> <li>Server run, and listening on a socket.</li> <li>Client run with an argument, a file containing a JSON one query or more. The client opens the file and takes the queries.</li> <li>A typical JSON query would look like this: <em>{&quot;id&quot;:&quot;first attempt&quot;,&quot;from&quot;:0,&quot;to&quot;:15,&quot;fizz&quot;:&quot;Mango&quot;,&quot;buzz&quot;:&quot;Avocado&quot;}\n</em> and is sent through the unix socket file to the server.</li> <li>The server receives the JSON message perform the FizzBuzz, and send an answer back to client (also JSON form). <em>{&quot;first attempt&quot;:[&quot;MangoAvocado&quot;,1,2,&quot;Mango&quot;,4,&quot;Avocado&quot;,&quot;Mango&quot;,7,8,&quot;Mango&quot;,&quot;Avocado&quot;,11,&quot;Mango&quot;,13,14,&quot;MangoAvocado&quot;]}</em></li> <li>Client receives the JSON message and printout the JSON elements:</li> </ol> <p>Here is the <code>server.go</code>:</p> <pre><code>package main import ( &quot;log&quot; &quot;net&quot; &quot;os&quot; &quot;os/signal&quot; &quot;syscall&quot; &quot;encoding/json&quot; ) //thanks to https://mholt.github.io/json-to-go/ type input struct { ID string `json:&quot;id&quot;` From int `json:&quot;from&quot;` To int `json:&quot;to&quot;` Fizz string `json:&quot;fizz&quot;` Buzz string `json:&quot;buzz&quot;` } type output struct { Output []interface{} `json:&quot;output&quot;` } func nice(inputBytes []byte)[]byte{ var in input json.Unmarshal(inputBytes, &amp;in) out := output{ Output: []interface{}{}, } for i := in.From; i &lt;= in.To; i++ { if i % 3 == 0 { if i % 5 == 0{ out.Output = append(out.Output, in.Fizz + in.Buzz) }else{ out.Output = append(out.Output, in.Fizz) } }else if i % 5 == 0{ out.Output = append(out.Output, in.Buzz) }else{ out.Output = append(out.Output, i) } } d, _ := json.Marshal(out.Output) d = append([]byte(&quot;\&quot;:&quot;), d...) d = append([]byte(in.ID), d...) d = append([]byte(&quot;{\&quot;&quot;), d...) d = append(d, &quot;}&quot;...) return d } func echoServer(c net.Conn) { for { buf := make([]byte, 512) nr, err := c.Read(buf) if err != nil { return } data := buf[0:nr] println(&quot;Server got:&quot;, string(data)) data = nice(data) _, err = c.Write(data) if err != nil { log.Fatal(&quot;Writing client error: &quot;, err) } } } func main() { log.Println(&quot;Starting echo server&quot;) ln, err := net.Listen(&quot;unix&quot;, &quot;/tmp/go.sock&quot;) if err != nil { log.Fatal(&quot;Listen error: &quot;, err) } sigc := make(chan os.Signal, 1) signal.Notify(sigc, os.Interrupt, syscall.SIGTERM) go func(ln net.Listener, c chan os.Signal) { sig := &lt;-c log.Printf(&quot;Caught signal %s: shutting down.&quot;, sig) ln.Close() os.Exit(0) }(ln, sigc) for { fd, err := ln.Accept() if err != nil { log.Fatal(&quot;Accept error: &quot;, err) } go echoServer(fd) } } </code></pre> <p>and the <code>client.go</code>:</p> <pre><code>package main import ( &quot;fmt&quot; &quot;os&quot; &quot;bufio&quot; &quot;io&quot; &quot;log&quot; &quot;net&quot; &quot;time&quot; ) func reader(r io.Reader) { buf := make([]byte, 1024) for { n, err := r.Read(buf[:]) if err != nil { return } println(&quot;Client got:&quot;, string(buf[0:n])) } } func main() { if len(os.Args) &lt;= 1 { fmt.Println(&quot;No args given. (expecting a filename)&quot;) return } if len(os.Args) &gt; 2 { fmt.Println(&quot;Too many args (only expecting one)&quot;) return } var file, err = os.OpenFile(os.Args[1], os.O_RDONLY, 0644) if (err != nil){ log.Fatal(err) //problem opening filename return } defer file.Close() scanner := bufio.NewScanner(file) msg := &quot;&quot; c, err := net.Dial(&quot;unix&quot;, &quot;/tmp/go.sock&quot;) if err != nil { log.Fatal(&quot;Dial error&quot;, err) } defer c.Close() go reader(c) for scanner.Scan(){ msg = scanner.Text() _, err = c.Write([]byte(msg)) if err != nil { log.Fatal(&quot;Write error:&quot;, err) //break return } println(&quot;Client sent:&quot;, msg) time.Sleep(1e9) // this gives time for } if err:=scanner.Err(); err != nil{ log.Fatal(err) } } </code></pre> <p>Say, we have this file named <code>input</code>:</p> <pre><code>{&quot;id&quot;:&quot;first entry&quot;,&quot;from&quot;:0,&quot;to&quot;:15,&quot;fizz&quot;:&quot;Orca&quot;,&quot;buzz&quot;:&quot;Seal&quot;} {&quot;id&quot;:&quot;second entry&quot;,&quot;from&quot;:-3,&quot;to&quot;:8,&quot;fizz&quot;:&quot;Mango&quot;,&quot;buzz&quot;:&quot;Avocado&quot;} {&quot;id&quot;:&quot;third one&quot;,&quot;from&quot;:1001,&quot;to&quot;:1025,&quot;fizz&quot;:&quot;Coke&quot;,&quot;buzz&quot;:&quot;Pepsi&quot;} </code></pre> <p>Running <code>go run server.go</code> and <code>go run client.go input</code> will give these:</p> <blockquote> <p>Client sent: {&quot;id&quot;:&quot;first entry&quot;,&quot;from&quot;:0,&quot;to&quot;:15,&quot;fizz&quot;:&quot;Orca&quot;,&quot;buzz&quot;:&quot;Seal&quot;}</p> </blockquote> <blockquote> <p>Client got: {&quot;first entry&quot;:[&quot;OrcaSeal&quot;,1,2,&quot;Orca&quot;,4,&quot;Seal&quot;,&quot;Orca&quot;,7,8,&quot;Orca&quot;,&quot;Seal&quot;,11,&quot;Orca&quot;,13,14,&quot;OrcaSeal&quot;]}</p> </blockquote> <blockquote> <p>Client sent: {&quot;id&quot;:&quot;second entry&quot;,&quot;from&quot;:-3,&quot;to&quot;:8,&quot;fizz&quot;:&quot;Mango&quot;,&quot;buzz&quot;:&quot;Avocado&quot;}</p> </blockquote> <blockquote> <p>Client got: {&quot;second entry&quot;:[&quot;Mango&quot;,-2,-1,&quot;MangoAvocado&quot;,1,2,&quot;Mango&quot;,4,&quot;Avocado&quot;,&quot;Mango&quot;,7,8]}</p> </blockquote> <blockquote> <p>Client sent: {&quot;id&quot;:&quot;third one&quot;,&quot;from&quot;:1001,&quot;to&quot;:1025,&quot;fizz&quot;:&quot;Coke&quot;,&quot;buzz&quot;:&quot;Pepsi&quot;}</p> </blockquote> <blockquote> <p>Client got: {&quot;third one&quot;:[1001,&quot;Coke&quot;,1003,1004,&quot;CokePepsi&quot;,1006,1007,&quot;Coke&quot;,1009,&quot;Pepsi&quot;,&quot;Coke&quot;,1012,1013,&quot;Coke&quot;,&quot;Pepsi&quot;,1016,&quot;Coke&quot;,1018,1019,&quot;CokePepsi&quot;,1021,1022,&quot;Coke&quot;,1024,&quot;Pepsi&quot;]}</p> </blockquote> <p>This program works as expected but I am somehow not satisfied since I am new to both JSON and Go. How can I improve the code?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:34:23.120", "Id": "269139", "Score": "2", "Tags": [ "json", "go", "socket", "fizzbuzz", "ipc" ], "Title": "FizzBuzz JSON via Unix socket (Go)" }
269139
<p>I got inspired by a recent question to do some benchmarking on the different methods to copy data and this is what I have come up with:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;chrono&gt; #include &lt;vector&gt; #include &lt;cstring&gt; class TimedTest { public: TimedTest(const std::string&amp; name) : name{ name }, time{ 0 }, total{ 0 }, testCount{ 0 } { } void run(int* dst, int* src, std::size_t count) { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); test(dst, src, count); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); time = (double)std::chrono::duration_cast&lt;std::chrono::milliseconds&gt; (end - begin).count(); total += time; testCount += 1.0; } virtual void test(int* dst, int* src, std::size_t count) = 0; double average() { return total / testCount; } public: std::string name; double time; double total; double testCount; }; class TimedTestMemCpy : public TimedTest { using TimedTest::TimedTest; virtual void test(int* dst, int* src, std::size_t count) override { memcpy(dst, src, sizeof(int) * count); } }; class TimedTestStdCopy : public TimedTest { using TimedTest::TimedTest; virtual void test(int* dst, int* src, std::size_t count) override { std::copy(src, src + count, dst); } }; class TimedTestSimpleLoop : public TimedTest { using TimedTest::TimedTest; virtual void test(int* dst, int* src, std::size_t count) override { for (size_t i = 0; i &lt; count; i++) dst[i] = src[i]; } }; class TimedTestPointerCopy : public TimedTest { using TimedTest::TimedTest; virtual void test(int* dst, int* src, std::size_t count) override { int* end = dst + count; while (dst != end) *dst++ = *src++; } }; class TimedTestOMPCopy : public TimedTest { using TimedTest::TimedTest; virtual void test(int* dst, int* src, std::size_t count) override { #pragma omp parallel for for (int i = 0; i &lt; (int)count; i++) dst[i] = src[i]; } }; int main() { constexpr std::size_t length = 200'000'000; int* src = new int[length]; for (int i = 0; i &lt; length; i++) src[i] = i; int* dst = new int[length]; std::vector&lt;TimedTest*&gt; tests; tests.push_back(new TimedTestMemCpy(&quot;memcpy&quot;)); tests.push_back(new TimedTestStdCopy(&quot;std::copy&quot;)); tests.push_back(new TimedTestSimpleLoop(&quot;simpleLoop&quot;)); tests.push_back(new TimedTestPointerCopy(&quot;pointerCopy&quot;)); tests.push_back(new TimedTestOMPCopy(&quot;OMPCopy&quot;)); std::cout &lt;&lt; std::setw(5) &lt;&lt; &quot;Test#&quot;; for (auto test : tests) std::cout &lt;&lt; std::setw(12) &lt;&lt; test-&gt;name &lt;&lt; std::setw(9) &lt;&lt; &quot;Avg&quot;; std::cout &lt;&lt; &quot;\n&quot;; for (int i = 0; i &lt; 100; i++) { std::cout &lt;&lt; std::setw(5) &lt;&lt; i; for (auto test : tests) { test-&gt;run(dst, src, length); std::cout &lt;&lt; std::setw(12) &lt;&lt; test-&gt;time &lt;&lt; std::setw(9) &lt;&lt; test-&gt;average(); } std::cout &lt;&lt; &quot;\n&quot;; } for (auto test : tests) delete test; delete[] src; delete[] dst; } </code></pre> <p>I would appreciate any comments on the results or suggestions on improving the benchmarking / general code.</p>
[]
[ { "body": "<h2>avoid manual memory management</h2>\n<pre><code>int* src = new int[length];\nfor (int i = 0; i &lt; length; i++)\n src[i] = i;\nint* dst = new int[length];\n</code></pre>\n<p>We could use two <code>std::vector&lt;int&gt;</code>s for this and avoid the manual memory management. Pointers to the underlying storage can be obtained using the <code>.data()</code> member function.</p>\n<pre><code>std::vector&lt;TimedTest*&gt; tests;\n</code></pre>\n<p>Similarly we should use <code>std::vector&lt;std::unique_ptr&lt;TimedTest&gt;&gt;</code> here so we don't have to manually <code>delete</code> them.</p>\n<hr />\n<h2>add a virtual destructor</h2>\n<p>We're deleting classes through a base-class pointer (<code>TimedTest*</code>), so we <em>must</em> have a <code>virtual</code> destructor to ensure proper cleanup.</p>\n<hr />\n<h2>use std::iota</h2>\n<pre><code>for (int i = 0; i &lt; length; i++)\n src[i] = i;\n</code></pre>\n<p>We could use <code>std::iota</code> in the <code>&lt;numeric&gt;</code> header for this.</p>\n<hr />\n<h2>preserve timing accuracy</h2>\n<pre><code>(double)std::chrono::duration_cast&lt;std::chrono::milliseconds&gt; (end - begin).count();\n</code></pre>\n<p><code>std::chrono::milliseconds</code> is an integer type. So doing this loses a <strong>lot</strong> of accuracy.</p>\n<p>We should accumulate time in a <code>std::chrono::steady_clock::duration</code> (which is likely nanoseconds) member, and then do the conversion to milliseconds (or whatever) once after all the test runs are complete.</p>\n<p>If we want to output a floating point result at the end, we need to use something like: <code>std::chrono::duration_cast&lt;std::chrono::milliseconds&lt;double&gt;&gt;(...).count()</code> on the final time.</p>\n<hr />\n<h2>simplify</h2>\n<pre><code>class TimedTest;\n</code></pre>\n<p>This class (and it's children) isn't really necessary. The timing members don't need to exist before the test is run, and are not used again after output. They should be local variables in the test-running loop.</p>\n<p>Using a <code>virtual</code> function for every <code>test</code> call may also add overhead to the functions being tested. We could instead write a template function to run the tests a set number of times and return timings. Perhaps something like:</p>\n<pre><code>template&lt;class F&gt;\nstd::chrono::steady_clock::duration run_test(std::size_t num_runs, F test_func)\n{\n auto begin = std::chrono::steady_clock::now();\n \n for (auto i = std::size_t { 0 }; i != num_runs; ++i)\n test_func();\n \n auto end = std::chrono::steady_clock::now();\n \n return (end - begin);\n}\n</code></pre>\n<p>That could be called with a lambda like so: <code>run_test(100, [&amp;] () { test_memcpy(src.data(), dst.data(), length); })</code> which should be easy to optimize for the compiler.</p>\n<hr />\n<h2>misc. other things:</h2>\n<ul>\n<li><p>In C++ we should technically use <code>std::memcpy</code>, not just <code>memcpy</code> (because that's where the <code>&lt;cstring&gt;</code> header declares it and the other might not exist).</p>\n</li>\n<li><p>It might affect the timings to share source and destination memory between the different tests. Each one should perhaps do its own allocation and cleanup (outside the timed section of code).</p>\n</li>\n<li><p>If we don't want to roll our own, we could use <a href=\"https://github.com/google/benchmark\" rel=\"noreferrer\">Google Bench</a> for making these kinds of measurements, which has an online platform <a href=\"https://www.quick-bench.com/\" rel=\"noreferrer\">here</a>.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T00:28:16.297", "Id": "531087", "Score": "1", "body": "`int* dst = new int[length];` is different from `std::vector<int> dst(length)` in that it won't have touched the memory pages to zero them. So if you *wanted* to time the page faults on first access to the new memory, you need to use `new`, or some allocator tricks to get `std::vector` to keep its hands off the memory instead of constructing each element. Especially if you do a new alloc for each test! See [Why is iterating though \\`std::vector\\` faster than iterating though \\`std::array\\`?](https://stackoverflow.com/q/57125253) on SO for a microbenchmark that fell into that trap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T00:33:06.840", "Id": "531088", "Score": "1", "body": "*It might affect the timings to share source and destination memory between the different tests.* - Yes, in a good way, if you want to time the case where memory is pre-faulted, TLB is hot, and (depending on copy size) data is hot in some level of cache. Copying to untouched memory could amplify the benefit of OpenMP doing page faults in parallel on multiple cores, especially on a desktop CPU where a single core can nearly saturate DRAM bandwidth. (Unlike on a big Xeon where single-core BW is actually lower, but aggregate is higher with 6 or 8 memory controller channels.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T07:29:01.773", "Id": "531106", "Score": "0", "body": "@PeterCordes Good points. I guess `std::unique_ptr<int[]>` would be the thing to use for `dst` then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T07:34:26.800", "Id": "531108", "Score": "1", "body": "Well, *if* you want to test fresh-allocation write performance, i.e. page faults moreso than than memory bandwidth, then yeah maybe." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:59:03.700", "Id": "269150", "ParentId": "269140", "Score": "8" } }, { "body": "<p>I think your approach is overcomplicated. You don't need to create/free objects and maintain a collection of objects. You just have the various different implementations that have the same signature. So give each implementation a different function name, and write:</p>\n<pre><code>test (&quot;memcpy&quot;, &amp;TestMemCpy);\ntest (&quot;simple loop&quot;, &amp;TestSimpleLoop);\n // etc.\n</code></pre>\n<p>This makes the other issues, like using a naked <code>new</code> and having to explicitly code a <code>delete</code> loop, just go away.</p>\n<p>Likewise, your <code>src</code> and <code>dst</code> memory does not need to be allocated on the heap. It could just be global variables declared as arrays.</p>\n<p>I'm worried that the benchmark won't be timing things to the necessary precision to notice anything useful. At the very least, just doing the test once may have an unknown error or jitter in the typical timing that you won't know about. Normal benchmarking frameworks will run the thing many times. You're running through all the tests 100 times, rather than running <em>each</em> test 100 times before moving on to the next. The latter is better because of code cache issues.</p>\n<h1>about memory copying in particular</h1>\n<p>As the conversation in the comments points out, benchmarking memory copying in particular has its own issues unrelated to the benchmarking framework.</p>\n<p>Look at <a href=\"https://godbolt.org/z/6v5n9jons\" rel=\"nofollow noreferrer\">your functions under Compiler Explorer</a>, with optimizations turned on.\nYou can comment out the <code>push_back</code> lines and un-comment one at a time, to clearly see generated code for each option.</p>\n<p>The compiler generates pretty much the same code for <em>all</em> of those! Memory copying is something it watches out for, and once the compiler understands what you <em>meant</em>, it throws away what you wrote and puts in optimal code for that result. &quot;Optimal&quot; is based on various flags you can use to control it, including target architecture.</p>\n<p>With compilers like this, you should focus on <em>clearly expressing your intent</em> rather than imagining that the assembly language is a rough line-by-line translation of what you wrote.</p>\n<p>This means using <code>memcpy</code> or <code>std::copy</code>. Since these are standard, the compiler can have built-in advanced understanding of what they do. In real code, you work with typed objects not raw bytes, so always use <code>std::copy</code>. Note that <code>std::copy</code> and related functions can also be given an <a href=\"https://en.cppreference.com/w/cpp/algorithm#Execution_policies\" rel=\"nofollow noreferrer\">Execution Policy</a> argument, so it can parallelized as with your last example.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T00:36:37.293", "Id": "531089", "Score": "0", "body": "*The latter is better because of code cache issues.* - That's assuming you want to test the case where the copy loop itself is already hot in I-cache, and branch-predictors are trained for that copy size. I think in most real code, it's more normal to do one large copy between a bunch of other work. So depending what you want to measure, it might or might not be more realistic to alternate between tests. OTOH this is pretty synthetic anyway, and hopefully (with `-O2` or `-O3`) most of them just compile to a call to the same libc memcpy function anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T14:20:31.050", "Id": "531142", "Score": "0", "body": "Right; the real fastest code will copy (on x86-64 chips) 128 bits at a time. It may take pains to align the reads even if that mis-aligns the writes. Future architectures may benefit from copying 256 or 512 bits at a time, and recompiling with a newer compiler will take care of that without touching my source code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T20:42:01.390", "Id": "531167", "Score": "0", "body": "You're talking about DRAM bandwidth? Current CPUs benefit from 256-bit vectors when data is hot in L2 cache, or maybe even L3 cache. Maybe even a small benefit on DRAM bandwidth from the same number of in-flight loads/stores looking twice as far ahead for triggering HW prefetch from the next physical page. Note that if the compiler doesn't inline memcpy, then you don't even need to recompile. glibc dispatches to `__memmove_avx_erms` when resolving memcpy at dynamic link time on CPUs that have those features, so you already benefit from CPU features for large or variable-size copies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T22:21:46.753", "Id": "531170", "Score": "0", "body": "@PeterCordes I've observed gcc generate 128-bit copying when the `-march` specified a processor that had AVX-512. The answer I found was that it wasn't any faster but adding another word size to deal with the alignment and total copy size logic increased code size and added cycles. I'm sure CPU generations keep on getting better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T22:24:37.020", "Id": "531171", "Score": "0", "body": "Ok yes, if you're talking about inlining memcpy for small copies, then the decision is up to gcc rather than glibc, and yes is fixed at compile time. Yes, sometimes GCC's inline expansion of memcpy / memset and sometimes other string functions works differently auto-vectorization's `-mprefer-vector-width=256` default on most recent CPUs. I think that sounds familiar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T16:53:52.473", "Id": "531204", "Score": "0", "body": "@JDługosz, thanks for the link, it is very interesting to see how the compiler optimizes things!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:59:14.420", "Id": "269151", "ParentId": "269140", "Score": "6" } }, { "body": "<h1>Avoid <code>new</code> and <code>delete</code></h1>\n<p>There is often no need to use <code>new</code> and <code>delete</code> manually in C++, containers do their own memory management, and in almost all other cases <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> can be used. In your program, <code>src</code> and <code>dst</code> can be made <code>std::vector</code>s:</p>\n<pre><code>std::vector&lt;int&gt; src(length);\nstd::vector&lt;int&gt; dst(length);\n</code></pre>\n<p>For the vector of test cases, you can use <code>std::unique_ptr</code> like so:</p>\n<pre><code>std::vector&lt;std::unique_ptr&lt;TimedTest&gt;&gt; tests;\ntests.push_back(std::make_unique&lt;TimedTestMemcpy&gt;(&quot;memcpy&quot;));\n...\n</code></pre>\n<h1>Use composition instead of inheritance</h1>\n<p>The problem with your approach of using inheritance is that you have to make a new <code>class</code> for every test case. And the only thing they all add is a single function. Instead of inheriting, you could make <code>TimedTest</code> a non-virtual class, and have it store the function as a member variable of type <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a>:</p>\n<pre><code>class TimedTest\n{\n // A type alias to avoid repeating the full type\n using Function = std::function&lt;void(int*, int*, std::size_t)&gt;;\n\npublic:\n TimedTest(const std::string&amp; name, Function test)\n : name{name}, test{test}\n {\n }\n...\nprivate:\n std::string name;\n Function test;\n}\n</code></pre>\n<p>Note that your <code>run()</code> function doesn't have to be changed at all! And since the class is now no longer virtual, you don't need to store pointers to it in the vector <code>tests</code>, and can instead write:</p>\n<pre><code>static void test_memcpy(int* src, int* dst, std::size_t count) {\n memcpy(dst, src, sizeof(*dst) * count);\n}\n\n...\n\nstd::vector&lt;TimedTest&gt; tests = {\n {&quot;memcpy&quot;, test_memcpy},\n ...\n};\n</code></pre>\n<h1>Avoid using classes at all</h1>\n<p>Even better, as <a href=\"/a/269150\">user673679</a> and <a href=\"/a/269151\">JDługosz</a> mentioned, there is no need to have a <code>class TimedTest</code>, you can just write a function that takes another function as an argument and runs that in a loop. The only difference with your code would then be that you interleave running each test once, and accumulate results, and at the end calculate all the averages.</p>\n<h1>Use <code>auto</code> and <code>using</code> to avoid writing long type names</h1>\n<p>Instead of writing out full type names like in this line of code:</p>\n<pre><code>std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n</code></pre>\n<p>I recommend you use <code>using</code> to create a type alias for the clock type you want to use, and <code>auto</code> to avoid having to specify types at all where appropriate. The above then becomes:</p>\n<pre><code>using clock = std::chrono::steady_clock;\nauto start = clock::now();\n...\nauto stop = clock::now();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:59:17.440", "Id": "269152", "ParentId": "269140", "Score": "12" } }, { "body": "<p>When running your code (after changing from millisecond to native resolution on the timing) I get the following:</p>\n<pre><code>clang++ -O3\n\nTest# memcpy Avg std::copy Avg simpleLoop Avg pointerCopy Avg OMPCopy Avg\n 0 626.327 626 40.8343 40 59.0428 59 58.9443 58 58.962 58\n 1 41.0973 333.5 39.1295 39.5 59.3185 59 59.0245 58.5 59.0766 59\n...\n 99 41.1162 41.17 39.8022 39.46 57.1298 57.08 57.4694 57.16 57.1774 57.26\n</code></pre>\n<p>notice anything odd? The first test ran is 15 times slower than the next test... this is because that test is the first test to touch the newly allocated memory. This has to do with how the OS (win10 in this case) allocates memory. It will just give you a memory range in virtual memory when you allocate. The first time you touch that memory the OS will generate a page fault, and perform physical memory allocation for that memory. This takes a hot minute and you see this in the test.</p>\n<p>There are two ways you can solve this:</p>\n<h4>Specific solution</h4>\n<p>We know this is caused by page allocation. In the loop where you prime the source vector, also write something to the destination vector to make sure it's paged in.</p>\n<h4>Generic solution</h4>\n<p>There are other causes that my result in the first, last or a random run being notably faster or slower than the rest. In statistics these would be called outliers. A good benchmarking suite will remove the <code>n</code> slowest and <code>k</code> fastest runs from the stats for each function under test. This removes the effects from hot/cold cache lines at start, page faults etc.</p>\n<h2><a href=\"https://www.youtube.com/watch?v=OWwOJlOI1nU\" rel=\"nofollow noreferrer\">Danger Will Robinson!</a></h2>\n<p>All the inputs to your program are deterministic and the output is never used. A C++ compiler (and C for the matter) is allowed under the <a href=\"https://stackoverflow.com/a/15718279\">as-if rule</a> to completely elide everything in this program (including the memory allocations!) except printing the output table if it can determine that the output didn't change by the elide.</p>\n<p>In this case you could argue that the times would be vastly different if the compiler did that, but under that argument the compiler would be prevented from doing ANY optimizations at all as soon as you did anything time related and that doesn't hold, and in fact I've seen clang do this. I had a benchmark test where it removed my entire code under test (memory allocations and all!) and replaced it with returning a constant instead of my code.</p>\n<p>In your case, I'd make both the destination and source pointers point to <code>volatile int</code>. This forces the compiler to perform the copies, but I'm not sure if this also\nforbids some forms of optimizations like (SIMD vectorization).</p>\n<p>TL;DR: It's hard to create a good benchmark, use a library.</p>\n<h2>Performance</h2>\n<p>I'm surprised to see that <code>pointerCopy</code> and <code>simpleLoop</code> are slower than <code>memcpy</code> typically compilers will detect simple copy loops and replace them with calls to <code>memcpy</code>. But then I remembered that little detail about pointer aliasing... and the C <a href=\"https://en.wikipedia.org/wiki/Restrict\" rel=\"nofollow noreferrer\">restrict</a> keyword that tells the compiler: &quot;Look, these pointers don't alias, ok?&quot;. It's technically nonstandard but all C++ compilers that matter support some form of <code>restrict</code> for C++. I used <code>__restrict__</code> for the pointer arguments in the <code>test</code> functions and this is what I got:</p>\n<pre><code>clang++ -O3\n\nTest# memcpy Avg std::copy Avg simpleLoop Avg pointerCopy Avg OMPCopy Avg\n 0 41.0359 41 39.2272 39 39.1399 39 56.4088 56 39.4728 39`\n...\n 99 40.8882 41.38 40.5645 39.7 39.9101 39.59 56.9585 57.48 39.4448 39.6\n</code></pre>\n<p>Notice how everything except <code>memcpy</code> and <code>std::copy</code> got faster? This is possible because the compiler can now generate much more efficient code when it knows that the source and destination memory doesn't overlap (alias). I'm not completely sure but I believe that the library functions do not have overloads with <code>restrict</code> (in fact I do not believe that's even possible) so they internally determine if the source and destination alias by some math, and if they don't, they run a fast non-alias copy. But if they do alias they run another code path that is slower.</p>\n<p>I think this additional math and branching is the slight edge that <code>simpleLoop</code> has over <code>std::copy</code> (not sure why <code>memcpy</code> is a full 1.5 ms slower than <code>std::copy</code>). I believe that the <code>pointerCopy</code> is slower because of the way you increment. I've seen this happen before where the post increment is slower than the pre increment and you could probably make this as fast as <code>simpleLoop</code> but I don't think it's worth the effort.</p>\n<p>At the end of the day, this reinforces the old mantra: Write clear code, and give the compiler as much information as possible and let it do it's job.</p>\n<p>For fun I also ran with</p>\n<pre><code>g++ -O3\n\nTest# memcpy Avg std::copy Avg simpleLoop Avg pointerCopy Avg OMPCopy Avg\n 0 41.2107 41 39.4616 39 39.2258 39 39.1013 39 39.4802 39\n...\n 99 40.8445 41.01 39.2478 39.43 39.1988 39.32 39.1874 39.27 39.1505 39.25\n</code></pre>\n<p>which interestingly generates better code for <code>pointerCopy</code>. I also ran with:</p>\n<pre><code>clang++ -O3 -march=native\n\nTest# memcpy Avg std::copy Avg simpleLoop Avg pointerCopy Avg OMPCopy Avg\n 0 41.0537 41 39.3157 39 39.2856 39 56.9359 56 39.5525 39\n...\n 99 40.8602 41 39.1795 39.34 39.1104 39.31 56.5426 56.8 39.738 39.29\n</code></pre>\n<p>where <code>-march=native</code> made slight improvements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T18:06:39.040", "Id": "531284", "Score": "0", "body": "Thanks for the insightful observations!regarding the pointer copy, I have noticed that with gcc - O3 testB is much faster than testA [TIO](https://tio.run/##vY5BDoMgEEX3c4rpTkUvIHHRXqRpgFoSAwlMNanh6qWA1qQX6Kzmz/8/80Q3ChHjbLVEUp7OlTbUoPTUYtm8Ey16kn3v9UtdCYV9GqrRzso5LRWsgGlKVhmJQ24g22Ici7k89KSwysZpyKm6nPM06RNjqdUklzEOAeCAufwRZv1B2oH4cdzpvrJQbzJAiPEt7tNt9LFbPg). With msvc and the intel compiler it does not look like it makes a difference." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T12:17:03.993", "Id": "269293", "ParentId": "269140", "Score": "3" } } ]
{ "AcceptedAnswerId": "269152", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T15:42:24.917", "Id": "269140", "Score": "7", "Tags": [ "c++", "performance" ], "Title": "Benchmarking data copying" }
269140
<p>I'm writing a function which iterate through a list of objects and should return: true if all the items have the attributes (cp and type). false if all the items haven't the attributes (cp and type). throw an error if one of the attribute is missed in the object.</p> <pre><code>const checkList = (list) =&gt; { if (list &amp;&amp; !list.length) return false console.time('setCheckList') const dict = { withCpCount: 0, withoutCpCount: 0, total: 0 } for (elem of list) { const {cp, type} = elem if((!cp &amp;&amp; type) || (cp &amp;&amp; !type)) { throw new Error('The cp/type is not exclusive') } if (cp &amp;&amp; type &amp;&amp; dict.withCpCount === dict.total) { dict.withCpCount += 1 } if (!cp &amp;&amp; !type &amp;&amp; dict.total === dict.withoutCpCount){ dict.withoutCpCount += 1 } dict.total += 1 if ((dict.withCpCount &gt; 0 &amp;&amp; dict.total !== dict.withCpCount) || (dict.withoutCappingCount &gt; 0 &amp;&amp; dict.total !== dict.withoutCpCount)) { throw new Error('All items should have the same shape') } } if (dict.withoutCpCount) return false console.timeEnd('checkList') return true; } </code></pre> <p>The function works well but I'm trying to generate some data using this function:</p> <pre><code>const generateList = (n) =&gt; { return Array.from({length: n}, (x, i) =&gt; ({ lat: Number((Math.random() * 100).toFixed(5)), lon: Number((Math.random() * 100).toFixed(5)), rad: Number((Math.random() * 100).toFixed(5)), cp: parseInt(Math.random() * 10000 + 1), type: 'imp' })) } </code></pre> <p>Then I tested with huge value like 10Exp7 and 10Exp8 but I got a heap out of memory, and I wonder if I should increase the memory using <code>export NODE_OPTIONS=--max-old-space-size=8192</code> or the function should be moree optimized. I got this issue when I increase the number:</p> <pre><code>&lt;--- Last few GCs ---&gt; ca[12998:0x102d88000] 50019 ms: Mark-sweep 2047.7 (2050.4) -&gt; 2046.7 (2050.4) MB, 741.7 / 0.0 ms (+ 8.2 ms in 17 steps since start of marking, biggest step 6.0 ms, walltime since start of marking 810 ms) (average mu = 0.165, current mu = 0.074) allocati[12998:0x102d88000] 51104 ms: Mark-sweep 2048.0 (2050.7) -&gt; 2047.0 (2050.7) MB, 1011.9 / 0.0 ms (+ 12.6 ms in 17 steps since start of marking, biggest step 6.5 ms, walltime since start of marking 1085 ms) (average mu = 0.108, current mu = 0.056) alloc &lt;--- JS stacktrace ---&gt; ==== JS stack trace ========================================= 0: ExitFrame [pc: 0x100a0d8d9] Security context: 0x3506d33008d1 &lt;JSObject&gt; 1: /* anonymous */ [0x3506baaf7d59] [/Users/xxx/projects/utils/index.js:~59] [pc=0x3231b97054d9](this=0x3506d787fe99 &lt;JSGlobal Object&gt;,0x350675d804b1 &lt;undefined&gt;,21011726) 2: from [0x3506d331a659](this=0x3506d331a4b1 &lt;JSFunction Array (sfi = 0x350622812af9)&gt;,0x3506baaf7d91 &lt;Object map = 0x350650b89949&gt;,0x3506baaf7d59 &lt;JSFunction (sfi = 0x3506618d4... FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory 1: 0x101204d65 node::Abort() (.cold.1) [/usr/local/bin/node] 2: 0x1000a5fd9 node::Abort() [/usr/local/bin/node] 3: 0x1000a613f node::OnFatalError(char const*, char const*) [/usr/local/bin/node] 4: 0x1001f0127 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node] xxxx@MacBook-Pro utils % node index.js **************** Generate list ***************** &lt;--- Last few GCs ---&gt; [13738:0x102d88000] 33405 ms: Scavenge 2715.1 (2733.7) -&gt; 2699.1 (2733.7) MB, 1.7 / 0.0 ms (average mu = 0.988, current mu = 0.988) allocation failure [13738:0x102d88000] 33503 ms: Scavenge 2719.2 (2738.0) -&gt; 2703.2 (2738.0) MB, 1.7 / 0.0 ms (average mu = 0.988, current mu = 0.988) allocation failure [13738:0x102d88000] 33599 ms: Scavenge 2723.3 (2742.0) -&gt; 2707.4 (2742.0) MB, 1.7 / 0.0 ms (average mu = 0.988, current mu = 0.988) allocation failure &lt;--- JS stacktrace ---&gt; ==== JS stack trace ========================================= 0: ExitFrame [pc: 0x100a0d8d9] Security context: 0x1362a92408d1 &lt;JSObject&gt; 1: from [0x1362a925a659](this=0x1362a925a4b1 &lt;JSFunction Array (sfi = 0x1362567d2af9)&gt;,0x1362a37045d9 &lt;Object map = 0x13628ca099e9&gt;,0x1362a37045a1 &lt;JSFunction (sfi = 0x13621754b531)&gt;) 2: generateList [0x1362a3704619] [/Users/xxx/projects/utils/index.js:59] [bytecode=0x13621754b5f1 offset=30](this=0x136275d3f759 &lt;JSGlobal Object&gt;,1000000000) 3:... FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory 1: 0x101204d65 node::Abort() (.cold.1) [/usr/local/bin/node] 2: 0x1000a5fd9 node::Abort() [/usr/local/bin/node] 3: 0x1000a613f node::OnFatalError(char const*, char const*) [/usr/local/bin/node] 4: 0x1001f0127 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node] 5: 0x1001f00c7 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node] 6: 0x100388e85 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/usr/local/bin/node] 7: 0x10058df7f v8::internal::HashTable&lt;v8::internal::NumberDictionary, v8::internal::NumberDictionaryShape&gt;::EnsureCapacity(v8::internal::Isolate*, v8::internal::Handle&lt;v8::internal::NumberDictionary&gt;, int, v8::internal::AllocationType) [/usr/local/bin/node] 8: 0x10058eef2 v8::internal::Dictionary&lt;v8::internal::NumberDictionary, v8::internal::NumberDictionaryShape&gt;::Add(v8::internal::Isolate*, v8::internal::Handle&lt;v8::internal::NumberDictionary&gt;, unsigned int, v8::internal::Handle&lt;v8::internal::Object&gt;, v8::internal::PropertyDetails, int*) [/usr/local/bin/node] 9: 0x1004f6112 v8::internal::(anonymous namespace)::DictionaryElementsAccessor::AddImpl(v8::internal::Handle&lt;v8::internal::JSObject&gt;, unsigned int, v8::internal::Handle&lt;v8::internal::Object&gt;, v8::internal::PropertyAttributes, unsigned int) [/usr/local/bin/node] 10: 0x10055db56 v8::internal::JSObject::AddDataElement(v8::internal::Handle&lt;v8::internal::JSObject&gt;, unsigned int, v8::internal::Handle&lt;v8::internal::Object&gt;, v8::internal::PropertyAttributes) [/usr/local/bin/node] 11: 0x10059e71b v8::internal::Object::AddDataProperty(v8::internal::LookupIterator*, v8::internal::Handle&lt;v8::internal::Object&gt;, v8::internal::PropertyAttributes, v8::Maybe&lt;v8::internal::ShouldThrow&gt;, v8::internal::StoreOrigin) [/usr/local/bin/node] 12: 0x100551a08 v8::internal::JSObject::DefineOwnPropertyIgnoreAttributes(v8::internal::LookupIterator*, v8::internal::Handle&lt;v8::internal::Object&gt;, v8::internal::PropertyAttributes, v8::Maybe&lt;v8::internal::ShouldThrow&gt;, v8::internal::JSObject::AccessorInfoHandling) [/usr/local/bin/node] 13: 0x10054e074 v8::internal::JSObject::CreateDataProperty(v8::internal::LookupIterator*, v8::internal::Handle&lt;v8::internal::Object&gt;, v8::Maybe&lt;v8::internal::ShouldThrow&gt;) [/usr/local/bin/node] 14: 0x1006ccd10 v8::internal::Runtime_CreateDataProperty(int, unsigned long*, v8::internal::Isolate*) [/usr/local/bin/node] 15: 0x100a0d8d9 Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/usr/local/bin/node] zsh: abort node index.js </code></pre> <p>It's just a question related to performance when iterating on a list with huge number of items.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:43:33.743", "Id": "530954", "Score": "0", "body": "What is poiDict? I can't see it declared in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:10:08.763", "Id": "530958", "Score": "0", "body": "\"It's just a question related to performance when iterating on a list with huge number of items.\"\n\n@Slim based on the stack trace are you ever actually iterating over the huge array? From what I'm reading in the stack trace, the OOM error is occurring when trying to create the Array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T08:41:01.480", "Id": "531018", "Score": "0", "body": "@Balastrong my bad sorry it means dict, I updated it." } ]
[ { "body": "<p>As @JaeBradley says, the out-of-memory error doesn't seem to have anything to do with the function you want to to have reviewed, so I'll just do a regular review, but I've added some words about this at the end.</p>\n<h1>Code style</h1>\n<p>Personally I'm not a big fan of using the lambda notation to define top-level functions. Using the <code>function</code> keyword makes the purpose of the code (to define a function) clearer to me.</p>\n<p>I'm also not a big fan of leaving out the semicolons. This requires you to memorize the rules of automatic semicolon insertion in order to avoid formatting the code in a way, that accidentally a semicolon is inserted where you don't want one. I find it easier, just to use semicolons.</p>\n<p>Generally it's considered a bad style to leave out the braces for single statement blocks (<code>if (list &amp;&amp; !list.length) return false</code>).</p>\n<p>You have a few inconsistencies in the spacing, e.g. sometimes missing a space after a keyword (<code>if(</code>) or between <code>)</code> and <code>{</code>.</p>\n<p>Generally you may want to look into using a linter, maybe one that automatically inserts the semicolons for you.</p>\n<h1>Programming style</h1>\n<p>The condition <code>if (list &amp;&amp; !list.length)</code> looks strange to me and is a potential bug. That condition explicitly allows an <code>undefined</code>/<code>null</code> list to continue only to generate a reference error when the <code>for</code> loop is reached.</p>\n<p>Either your contract disallows passing in <code>undefined</code> or <code>null</code> in the first place, then in that case you can just as well leave out <code>list &amp;&amp;</code>, because it doesn't matter when the reference error is thrown. Or the condition should be <code>!list || !list.length</code>.</p>\n<p>You are missing a <code>let</code> to declare <code>elem</code> in <code>for (elem of list) {</code> making <code>elem</code> a global variable. Make sure you are using strict mode and then you'll get an error in those cases.</p>\n<p>The use of a (badly named) object (<code>dict</code>) instead of just three local variables (<code>let withCpCount = 0;</code> etc.) is strange and makes the code less readable.</p>\n<p>The two <code>if</code> statements</p>\n<pre><code>if (cp &amp;&amp; type &amp;&amp; dict.withCpCount === dict.total) {\n dict.withCpCount += 1\n} \nif (!cp &amp;&amp; !type &amp;&amp; dict.total === dict.withoutCpCount){\n dict.withoutCpCount += 1\n}\n</code></pre>\n<p>could be combined with an <code>else</code> and in that case the part <code>!cp &amp;&amp; !type &amp;&amp;</code> can be left out, because that will always be true at that point:</p>\n<pre><code>if (cp &amp;&amp; type &amp;&amp; dict.withCpCount === dict.total) {\n dict.withCpCount += 1\n} else if (dict.total === dict.withoutCpCount){\n dict.withoutCpCount += 1\n}\n</code></pre>\n<p>You should be careful using JavaScript's truthy/falsy logic to validate <code>cp</code> and <code>type</code>. In my experience real life data rarely conforms to those conditions. You should at the very least extract that logic into two separate functions and then you only have one place to change:</p>\n<pre><code>function checkCp(cp) {\n return !!cp; // Or replace with an explicit check for zero, for example\n}\n\nfunction checkType(type) {\n return !!type; \n}\n</code></pre>\n<p>Finally the use of exceptions as a &quot;return value&quot; is not optimal, unless those cases never (or very seldom) occur. If it's a common occurrence you may want to look into alternatives.</p>\n<h1>Logic</h1>\n<p>The function is a bit over-engineered. There is no real need to count the items that validate. You can just look at the state of the first item and make sure the other items match that state. For example:</p>\n<pre><code>function checkItem(item) {\n const cpState = checkCp(item.cp);\n const typeState = checkType(item.type);\n if (cpState !== typeState) {\n throw new Error('The cp/type is not exclusive');\n }\n return cpState;\n}\n\nfunction checkList(list) {\n if (!list || !list.length) { return false; }\n const firstState = checkItem(list[0]);\n // This unnecessarily checks the first item again, however it is much\n // more work skipping the first item, than just repeating the check,\n // especially if the list is millions of items long anyway.\n if (!list.every(item =&gt; firstItem === checkItem(item))) {\n throw new Error('All items should have the same shape');\n }\n return firstState;\n}\n</code></pre>\n<h1>Memory problems</h1>\n<p>As suggested at the start, the memory problems have nothing to do with this function, but with the choice to keep all items in memory at once. If your real life scenario will be to actually work with that many items, then you'll need to find different solution. This depends on where the data is coming from. I would assume that it's a database. In that case you should consider either move this logic to the database itself, or implement a solution that reads the items lazily one by one from the database (usually using a &quot;database cursor&quot;).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T11:47:56.497", "Id": "269181", "ParentId": "269143", "Score": "2" } } ]
{ "AcceptedAnswerId": "269181", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T16:01:25.227", "Id": "269143", "Score": "2", "Tags": [ "javascript", "performance", "node.js", "memory-optimization" ], "Title": "iterating a big list of objects throws a memory issue" }
269143
<p>I want to learn about performance impact of different calculations and influences/optimizations like compiler flags, use of SSE, AVX etc.</p> <p>I'm going to code some small subroutines which will take place in almost every arithmetic operation in a special program, thus good code, portability and performance do! matter.</p> <p>Insofar the questions:</p> <ul> <li>is the code below meaningful?</li> <li>should it be improved?</li> <li>or is 'better' already in the field and i just overlooked it?</li> <li>is similar possible in 'C'?</li> </ul> <p>I'm new here and <strong>not</strong> a coder, 'script kiddie' at best, the program is 'picked together' at SO and cppreference, thus 'bear with me' and I beg your pardon for any stupidity or errors.</p> <p>I have asked the question with a prior version at SO, some tips from there are implemented.</p> <pre><code>// compile with e.g. // g++ -O1 timing_operations_2.c -o timing_operations_2 -lm // impressive differenes with // g++ -O9 timing_operations_2.c -o timing_operations_2 -lm // but think that's reg. supressing code with no further use // not necessary? // #include &lt;algorithm&gt; // #include &lt;ctime&gt; #include &lt;iostream&gt; // reg. cout, #include &lt;iomanip&gt; // reg. put_time, setpreision, #include &lt;chrono&gt; // reg. chrono, #include &lt;thread&gt; // reg. thread, #include &lt;math.h&gt; // reg. pow( x, y ), using namespace std; using namespace std::literals; // enables the usage of 24h, 1ms, 1s instead of // e.g. std::chrono::hours(24), accordingly void slow_motion() { std::cout &lt;&lt; &quot;Hello waiter\n&quot; &lt;&lt; std::flush; auto start = std::chrono::high_resolution_clock::now(); std::cout &lt;&lt; &quot;Hi! in one second I'll die! :-( &quot; &lt;&lt; endl; std::this_thread::sleep_for(1000ms); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration&lt;double, std::milli&gt; elapsed = end-start; std::cout &lt;&lt; &quot;urrrrggghhhh! took: &quot; &lt;&lt; elapsed.count() &lt;&lt; &quot; ms\n&quot;; } int main() { int amount = 100000; // size of testfield int i = 0; // counter double x1 = 0; // working value std::cout &lt;&lt; std::setprecision(16) &lt;&lt; std::fixed; const std::chrono::time_point&lt;std::chrono::system_clock&gt; now = std::chrono::system_clock::now(); const std::time_t t_c = std::chrono::system_clock::to_time_t(now - 24h); std::cout &lt;&lt; &quot;24 hours ago, the time was &quot; &lt;&lt; std::put_time(std::localtime(&amp;t_c), &quot;%F %T.\n&quot;) &lt;&lt; std::flush; const std::chrono::time_point&lt;std::chrono::steady_clock&gt; start = std::chrono::steady_clock::now(); slow_motion(); const auto end = std::chrono::steady_clock::now(); std::cout &lt;&lt; &quot;Slow calculations took &quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end - start).count() &lt;&lt; &quot;µs ≈ &quot; &lt;&lt; (end - start) / 1ms &lt;&lt; &quot;ms ≈ &quot; // almost equivalent form of the above, but &lt;&lt; (end - start) / 1s &lt;&lt; &quot;s.\n&quot;; // using milliseconds and seconds accordingly // preparing testvalues for timing, double testme[amount]; for( i = 0; i &lt; amount; ++i ) { testme[i] = rand() / pow( 2, 16 ); } // timing ' x / 2 ', auto start_1 = std::chrono::high_resolution_clock::now(); for( i = 0; i &lt; amount; ++i ) { x1 = testme[i] / 2; // cout &lt;&lt; &quot;' x / 2: &quot; &lt;&lt; x1 &lt;&lt; &quot;\n&quot;; } auto end_1 = std::chrono::high_resolution_clock::now(); std::chrono::duration&lt;double, std::milli&gt; elapsed = end_1-start_1; std::cout &lt;&lt; &quot;calculating &quot; &lt;&lt; amount &lt;&lt; &quot; times ' = x / 2 ' took &quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end_1 - start_1).count() &lt;&lt; &quot;µs ≈ &quot; &lt;&lt; (end_1 - start_1) / 1ms &lt;&lt; &quot;ms ≈ &quot; // almost equivalent form of the above, but &lt;&lt; (end_1 - start_1) / 1s &lt;&lt; &quot;s.\n&quot;; // using milliseconds and seconds accordingly // timing ' x / 2 ', a second time aginst caching influences, start_1 = std::chrono::high_resolution_clock::now(); for( i = 0; i &lt; amount; ++i ) { x1 = testme[i] / 2; // cout &lt;&lt; &quot;' x / 2: &quot; &lt;&lt; x1 &lt;&lt; &quot;\n&quot;; } end_1 = std::chrono::high_resolution_clock::now(); elapsed = end_1-start_1; std::cout &lt;&lt; &quot;calculating &quot; &lt;&lt; amount &lt;&lt; &quot; times ' = x / 2 ' took &quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end_1 - start_1).count() &lt;&lt; &quot;µs ≈ &quot; &lt;&lt; (end_1 - start_1) / 1ms &lt;&lt; &quot;ms ≈ &quot; // almost equivalent form of the above, but &lt;&lt; (end_1 - start_1) / 1s &lt;&lt; &quot;s.\n&quot;; // using milliseconds and seconds accordingly // timing ' x / 3 ', start_1 = std::chrono::high_resolution_clock::now(); for( i = 0; i &lt; amount; ++i ) { x1 = testme[i] / 3; // cout &lt;&lt; &quot;' x / 3: &quot; &lt;&lt; x1 &lt;&lt; &quot;\n&quot;; } end_1 = std::chrono::high_resolution_clock::now(); elapsed = end_1-start_1; std::cout &lt;&lt; &quot;calculating &quot; &lt;&lt; amount &lt;&lt; &quot; times ' = x / 3 ' took &quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end_1 - start_1).count() &lt;&lt; &quot;µs ≈ &quot; &lt;&lt; (end_1 - start_1) / 1ms &lt;&lt; &quot;ms ≈ &quot; // almost equivalent form of the above, but &lt;&lt; (end_1 - start_1) / 1s &lt;&lt; &quot;s.\n&quot;; // using milliseconds and seconds accordingly // timing ' (int)x ', start_1 = std::chrono::high_resolution_clock::now(); for( i = 0; i &lt; amount; ++i ) { x1 = (int)testme[i]; // cout &lt;&lt; &quot;' (int)x ': &quot; &lt;&lt; x1 &lt;&lt; &quot;\n&quot;; } end_1 = std::chrono::high_resolution_clock::now(); elapsed = end_1-start_1; std::cout &lt;&lt; &quot;calculating &quot; &lt;&lt; amount &lt;&lt; &quot; times ' = (int)x ' took &quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end_1 - start_1).count() &lt;&lt; &quot;µs ≈ &quot; &lt;&lt; (end_1 - start_1) / 1ms &lt;&lt; &quot;ms ≈ &quot; // almost equivalent form of the above, but &lt;&lt; (end_1 - start_1) / 1s &lt;&lt; &quot;s.\n&quot;; // using milliseconds and seconds accordingly // timing ' pow( 10, x ) ', start_1 = std::chrono::high_resolution_clock::now(); for( i = 0; i &lt; amount; ++i ) { x1 = pow( 10, testme[i] ); // cout &lt;&lt; &quot;' (int)x ': &quot; &lt;&lt; x1 &lt;&lt; &quot;\n&quot;; } end_1 = std::chrono::high_resolution_clock::now(); elapsed = end_1-start_1; std::cout &lt;&lt; &quot;calculating &quot; &lt;&lt; amount &lt;&lt; &quot; times ' = pow( 10, x ) ' took &quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end_1 - start_1).count() &lt;&lt; &quot;µs ≈ &quot; &lt;&lt; (end_1 - start_1) / 1ms &lt;&lt; &quot;ms ≈ &quot; // almost equivalent form of the above, but &lt;&lt; (end_1 - start_1) / 1s &lt;&lt; &quot;s.\n&quot;; // using milliseconds and seconds accordingly return ( 0 ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:29:48.797", "Id": "530953", "Score": "0", "body": "I don't see any mutexes or `std::atomic` types in your code, so I wouldn't call the things you want to measure \"atomic\", just \"small bits of code\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T18:59:01.957", "Id": "530957", "Score": "0", "body": "@G. Sliepen: 'atomic' - didn't know that it's a reserved word, sorry | 'tag' - I tagged the issue 'C' because it includes the question how to perform such in (pure) 'C'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:17:55.457", "Id": "530986", "Score": "0", "body": "Welcome to Code Review! I have rolled back Rev 6 → 4. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"nofollow noreferrer\">SF.7</a>.)</p>\n<hr />\n<p>I'm afraid the high-resolution-clock might not work right as it's not a <em>monotonic</em> clock. Which clock is best for this purpose depends on the platform, I'm afraid. And, I don't think any clock will be good enough for the kind of micro-benchmarks you describe. You're mentioning <em>microseconds</em> in the code, but &quot;some small subroutines which will take place in almost every arithmetic operation&quot; sounds like you need to be using <em>nanoseconds</em>. I would use the CPU-specific cycle counter register to benchmark something like individual arithmetic operations.</p>\n<p>If you're going to make a loop to do a primitive operation millions or billions of times, you might get deceptive or even bizarre results, as it will not reflect the mix of instructions as seen in the real code. The CPU may pipeline the loop with multiple operations in-flight simultaneously, but in real code the operation of interest is mixed with other code. You can get a completely wrong answer as it relates to the real code, because of differences in pipelining, simultaneous instructions in-flight vs latency of dependant results, and caching.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T18:46:51.813", "Id": "530955", "Score": "0", "body": "hello @JDługosz, thanks for your hints. 'namespace' - implemented | 'monotonic clock' - I'm open for proposals | 'micro-benchmarks' - i'm aware that this is no exact science on modern systems, just want to get an 'idea' | 'nanoseconds' i had in my first try? - https://stackoverflow.com/questions/69631678/which-operations-are-costly-for-the-cpu-review-a-program-rewrite-for-c - | 'loop different to code mix' - I'm aware of, but while I can't be perfect I have to accept compromises | where is the 'speedometer' program doing such analysis without requiring every coder to re-invent the wheel?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:20:28.870", "Id": "530969", "Score": "0", "body": "I use `clock_gettime(CLOCK_MONOTONIC, &ts);` _or_ `getrusage(RUSAGE_THREAD, &rr);` depending on whether I want to measure system call times. I've done simple microbenchmarks by using the `rdtsc` instruction via an intrinsic. That is the cycle timer on x86." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T18:04:47.833", "Id": "269153", "ParentId": "269148", "Score": "1" } }, { "body": "<p>There's a lot of repetition here - consider refactoring the timing code so you don't need to write so much to add timing (perhaps pass a lambda to suitable timing function).</p>\n<p>This kind of code:</p>\n<blockquote>\n<pre><code>for( i = 0; i &lt; amount; ++i )\n{\n x1 = testme[i] / 2;\n}\n</code></pre>\n</blockquote>\n<p>will be optimised away completely by any decent compiler, since the results are never used (the assignment is a <em>dead write</em>). So you're likely not measuring what you think you are (unless you build without optimisation, which will be just as misleading).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T21:52:46.920", "Id": "530981", "Score": "0", "body": "hello @Toby Speight, thank you. 'repetition' - I'm not! a 'pro' | 'lambda' - don't know about | 'dead code' - issue: how to get it 'live', with as less as possible impact on the timings. I don't need 'absolute' timings as I mostly will compare two different algos, '(void)x1;' which elsewhere helped against compiler warnings 'unused' didn't help. | 'optimizations' - funnily 'pow..' isn't optimized away except with -Ofast ??? and 'jitters' between -O5 and -O8? | 'clock_monotonic' - like this: https://people.cs.rutgers.edu/~pxk/416/notes/c-tutorials/gettime.html ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:56:56.223", "Id": "531007", "Score": "0", "body": "For your code not to be optimised away to nothing, it's important to actually _use_ the result - perhaps `x1 += testme[i] / 2;`, combined with some other use of `x1` outside the loop (printing, perhaps)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T08:52:27.190", "Id": "531019", "Score": "0", "body": "thank you @Toby Speight, would the compiler be dumb enough not! to see that it would be sufficient to calculate only the last element of the array? as the prior results results would be overwritten by the next calculation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T11:26:14.313", "Id": "531026", "Score": "0", "body": "That is why I suggested `+=`, to ensure that all the values get used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T12:33:25.387", "Id": "531030", "Score": "0", "body": "thank you @Toby Speight, overlooked that detail ... have to be aware that the timing will have 2 operations in the loop ('+' and '/') and need to use small values in testme, otherwise x1 will overflow ... improving ..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:52:04.753", "Id": "269160", "ParentId": "269148", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T17:20:38.293", "Id": "269148", "Score": "1", "Tags": [ "c++", "performance" ], "Title": "Little program to measure costly operations" }
269148
<p>This is for leetcode problem: <a href="https://leetcode.com/problems/majority-element" rel="nofollow noreferrer">https://leetcode.com/problems/majority-element</a></p> <p>There is something wrong with the way I create solutions, and not sure how to stop doing it. Basically the problem is I always create a count variable. Here is it called greatest_count. For the if statement, I create a conditional, which I think is fine, but I feel like I don't need the additional greatest_count variable here but not sure a better way to write it. I always seem to think I need to count it and check it against the previous counts. Do I need this? How can I write this without needing the count variable? or without using the greatest unique? Any ways to optimize this would be great to know.</p> <p>Problem area:</p> <pre><code>if unique_count &gt; greatest_count: greatest_count = unique_count greatest_unique = i </code></pre> <p>Here is the full code:</p> <pre><code>class Solution: def majorityElement(self, nums): unique_nums = set(nums) greatest_unique = 0 greatest_count = 0 for i in unique_nums: unique_count = nums.count(i) if unique_count &gt; greatest_count: greatest_count = unique_count greatest_unique = i return greatest_unique </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:36:08.813", "Id": "530961", "Score": "4", "body": "Thank you for providing the link, however, links can break. Please include the text of the programming challenge in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:42:24.457", "Id": "530963", "Score": "2", "body": "It's not clear from question, but I'm assuming the code is passing all tests?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:08:04.480", "Id": "531002", "Score": "0", "body": "Check out [Moore's algorithm](https://en.wikipedia.org/wiki/Boyer–Moore_majority_vote_algorithm)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T09:57:42.980", "Id": "531637", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<h2>Your code, simplified:</h2>\n<p>Here's an alternative that uses fewer variables. It involves tuple comparisons in <code>max(num_cnt_max, num_cnt)</code>:</p>\n<pre><code>CNT, NUM = 0, 1\nclass Solution:\n def majorityElement(self, nums):\n unique_nums = set(nums)\n num_cnt_max = (0, 0)\n \n for num in unique_nums:\n num_cnt = (nums.count(num), num)\n num_cnt_max = max(num_cnt_max, num_cnt)\n return num_cnt_max[CNT]\n</code></pre>\n<hr />\n<h2>Use <code>Counter</code> instead of <code>set</code> and <code>list.count</code>:</h2>\n<p>Another suggestion is to use <a href=\"https://docs.python.org/3/library/collections.html?highlight=counter#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> instead of the combination of <code>set</code> and <code>list.count</code> your solution uses. In case you're not familiar with <code>Counter</code>, here's an example of its usage:</p>\n<pre><code>from collections import Counter\n\nnums = [1, 6, 3, 9, 3, 4, 3, 1]\nnums_counter = Counter(nums)\nprint(nums) # Counter({3: 3, 1: 2, 6: 1, 9: 1, 4: 1})\n</code></pre>\n<p>The relationship between <code>nums</code> and <code>nums_counter</code> is that <code>nums_counter[num] == nums.count(num)</code>. Creating a <code>Counter</code> (<code>Counter(nums)</code>) and then accessing it (<code>nums_counter[num]</code>) repeatedly is probably faster than repeatedly calling <code>nums.count(num)</code>.</p>\n<h2>Use information given in the problem statement:</h2>\n<p>Another suggestion is to use the information that the majority element appears more than <code>N / 2</code> times. In a list of <code>N</code> elements how many different elements can have a count of more than <code>N / 2</code>? Using that information would let you break out of the foo loop earlier and you'd know which element is the majority just by looking at its count, so you would not have to maintain the intermediate <code>num_cnt_max</code> variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:13:14.443", "Id": "530983", "Score": "2", "body": "You should make note of the [`Counter.most_common([n])`](https://docs.python.org/3/library/collections.html?highlight=counter#collections.Counter.most_common) method, which reduces the code to one statement `return Counter(nums).most_common(1)[0]`. But what you really should do is provide a **review** of the OP's code, since alternate-solution-only answers are not valid answers on this site." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:47:04.363", "Id": "269159", "ParentId": "269156", "Score": "0" } } ]
{ "AcceptedAnswerId": "269159", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:33:33.160", "Id": "269156", "Score": "-2", "Tags": [ "python", "programming-challenge" ], "Title": "leetcode 169 optimzations reducing complexity" }
269156
<p>I'm trying to write a program whose input is an array of integers, and its size. This code has to delete each element which is smaller than the element to the left. We want to find number of times that we can process the array this way, until we can no longer delete any more elements.</p> <p>The contents of the array after we return are unimportant - only the return value is of interest.</p> <p>For example: given the array <code>{10, 9, 7, 8, 6, 5, 3, 4, 2, 1}</code>, the function should return <code>2</code>, because [10,9,7,8,6,5,3,4,2,1] → [10,8,4] → [10].</p> <pre class="lang-cpp prettyprint-override"><code>int numberOfTimes(int array[] , int n) { int count = 0; int flag = 0; int sizeCounter = 0; while (true){ for (int i = 0; i &lt; n-1; ++i) { if (array[i]&lt;= array[i+1]){ sizeCounter++; array[sizeCounter] = array[i+1]; } else{ flag = 1; } } if (flag == 0) return count; count++; flag = 0; n = (sizeCounter+1); sizeCounter = 0; } } </code></pre> <p>My code works but I want it to be faster.</p> <p>Do you have any idea to make this code faster, or another way that is faster than this?</p>
[]
[ { "body": "<p>Cannot tell about how to make your solution run faster, but I have some suggestions for the cosmetic issues in your code:</p>\n<p><strong><code>size_t</code> for counting stuff</strong></p>\n<p>Instead of using <code>int</code> values for counting, it is more customary to use <code>size_t</code> instead.</p>\n<p><strong>Reducing scope</strong></p>\n<pre><code>int numberOfTimes(int array[], int n) {\n int count = 0;\n int flag = 0;\n int sizeCounter = 0;\n while (true) {\n ...\n</code></pre>\n<p>Above, you could move both <code>flag</code> and <code>sizeCounter</code> inside the <code>while</code> loop:</p>\n<pre><code>while (true) {\n int sizeCounter = 0;\n int flag = 0;\n ...\n\n</code></pre>\n<p><strong>Use <code>bool</code> for <code>flag</code></strong></p>\n<p>C++ provides the <code>bool</code> data type; it accepts only two values: <code>true</code> and <code>false</code>. Use it.</p>\n<p><strong>Summa summarum</strong></p>\n<p>All in all, I had the following rewrite:</p>\n<pre><code>// Modifies array!\nsize_t numberOfTimes2(int array[], size_t n) {\n size_t count = 0;\n\n while (true) {\n size_t sizeCounter = 0;\n bool flag = false;\n\n for (size_t i = 0; i &lt; n - 1; ++i) {\n if (array[i] &lt;= array[i + 1]) {\n array[++sizeCounter] = array[i + 1];\n }\n else {\n flag = true;\n }\n }\n\n if (!flag) {\n return count;\n }\n\n count++;\n n = sizeCounter + 1;\n }\n}\n</code></pre>\n<p>(See <a href=\"https://gist.github.com/coderodde/6c327b731fd830e829c142b3ec2ae268\" rel=\"nofollow noreferrer\">this gist</a> for demo.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:37:18.383", "Id": "269186", "ParentId": "269158", "Score": "1" } }, { "body": "<p>In addition to the issues <code>coderodde</code> pointed out,</p>\n<ul>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i13-do-not-pass-an-array-as-a-single-pointer\" rel=\"nofollow noreferrer\">⧺I.13</a> Do not pass an array as a single pointer (includes pointer and count parameters in the discussion)</p>\n</li>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r14-avoid--parameters-prefer-span\" rel=\"nofollow noreferrer\">⧺R.14</a> Avoid <code>[]</code> parameters, prefer <code>span</code></p>\n</li>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f24-use-a-spant-or-a-span_pt-to-designate-a-half-open-sequence\" rel=\"nofollow noreferrer\">⧺F.24</a> Use a <code>span&lt;T&gt;</code> or a <code>span_p&lt;T&gt;</code> to designate a half-open sequence</p>\n</li>\n</ul>\n<p>Real reusable code would allow any kind of sequential container of values to be passed in. The caller will most likely have a <code>vector</code>, not a plain C array! If you look at <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">anything in the standard library</a>, you'll see that algorithms take a pair of iterators or a <em>range</em> to work on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:54:45.597", "Id": "269189", "ParentId": "269158", "Score": "1" } }, { "body": "<p>It would be good to include some tests with the code, so that we can confirm it returns the correct results.</p>\n<p>It's very hard to read, because it is written like a C program, and fails to take advantage of the rich standard library provided with C++. We've reimplemented <code>std::remove_if()</code>, but we could just use that algorithm directly, for much simpler code. Look how a more idiomatic C++ function looks, and see that it doesn't need to do any actual arithmetic other than the comparison:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;climits&gt;\n#include &lt;utility&gt;\n#include &lt;span&gt;\n\nstd::size_t count_peak_iterations(std::span&lt;int&gt; array)\n{\n auto a = array.rbegin();\n auto z = array.rend();\n\n auto one_pass = [a, &amp;z](){\n auto prev = INT_MAX;\n auto new_z = std::remove_if(a, z,[&amp;prev](int n){ return n &gt; std::exchange(prev,n); });\n return new_z != std::exchange(z, new_z);\n };\n\n std::size_t count = 0;\n while (one_pass()) {\n ++count;\n }\n return count;\n}\n</code></pre>\n<p>(If the use of <code>std::exchange()</code> looks a little tricky to follow, it just saves us having to introduce new short-term variables to store return values.)</p>\n<hr />\n<p>Given that we don't care about the results in the array, we can avoid rewriting it, if we think a little about what happens during the process. I find it helps to visualise this graphically by looking at values as the <em>y</em> values on a chart like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>5| ·\n4| ·\n3| ·\n2| ·\n1|·\n |------\n</code></pre>\n<p>We can write in the iteration at which each element is deleted. For the simplest case, all of the elements are already in ascending order, and there are no deletions at all (function returns 0):</p>\n<pre class=\"lang-none prettyprint-override\"><code> ·\n ·\n ·\n ·\n ·\n</code></pre>\n<p>When the array is in descending order, all elements except the first will be deleted in the first pass:</p>\n<pre class=\"lang-none prettyprint-override\"><code> ·\n 1\n 1\n 1\n 1\n</code></pre>\n<p>For several runs of descending elements, we see that they will all be\ndealt with in the first pass, and the &quot;lead&quot; element of the run may be deleted in a subsequent pass:</p>\n<pre class=\"lang-none prettyprint-override\"><code> · ·\n 1 1\n 1 1\n 1 1\n 1 1\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code> ·\n 1 2\n 1 1\n 1 1\n 1 1\n</code></pre>\n<p>When we have runs of increasing/equal values that are lower than some previous peak, we only delete the first of the run in each pass, so the counts increase quickly:</p>\n<pre class=\"lang-none prettyprint-override\"><code> ·\n ·\n · 5 4\n · 4 3\n · 3 2\n · 2 1\n · 1\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code> · ·\n 1234 12\n</code></pre>\n<p>If we stare at these graphs for a while, we see that it's possible to compute the number of iterations by examining each element in turn, just once:</p>\n<ul>\n<li>We'll want to track the highest value previously seen; any value greater or equal to this will remain in the output.</li>\n<li>We need to count how many values we've seen in the current non-descending run less than the peak.</li>\n<li>Then we simply return the longest of those runs that we've seen (so we'll need a variable to track the maximum).</li>\n</ul>\n<p>An implementation of that looks like this, and passes the tests that correspond to what I've drawn above:</p>\n<pre><code>#include &lt;climits&gt;\n#include &lt;span&gt;\n\nstd::size_t count_peak_iterations(std::span&lt;const int&gt; array)\n{\n int peak = INT_MIN;\n int prev = INT_MIN;\n std::size_t max_iter = 0;\n std::size_t current_iter = 0;\n\n for (auto const value: array) {\n if (value &lt; prev) {\n current_iter = 1;\n } else if (value &lt; peak) {\n ++current_iter;\n } else {\n peak = value;\n }\n if (current_iter &gt; max_iter) {\n max_iter = current_iter;\n }\n prev = value;\n }\n\n return max_iter;\n}\n</code></pre>\n<p>This version scales much better than the original (it's O(<em>n</em>) rather than O(<em>m</em> ✕ <em>n</em>), where <em>n</em> is the input size and <em>m</em> is the result value).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:44:07.683", "Id": "269251", "ParentId": "269158", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:43:15.260", "Id": "269158", "Score": "1", "Tags": [ "c++", "performance", "algorithm", "array" ], "Title": "Count how many iterations of deletion until array is ordered" }
269158
<p>I was working on <a href="https://leetcode.com/problems/first-unique-character-in-a-string/" rel="nofollow noreferrer">First Unique Character in a String</a></p> <h2>Question</h2> <p>Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.</p> <p>Example 1:</p> <pre><code>Input: s = &quot;leetcode&quot; Output: 0 </code></pre> <p>Example 2:</p> <pre><code>Input: s = &quot;loveleetcode&quot; Output: 2 </code></pre> <p>Example 3:</p> <pre><code>Input: s = &quot;aabb&quot; Output: -1 </code></pre> <h2>My Solution</h2> <pre><code>var firstUniqChar = function(s) { let myMap = new Map() for(let i = 0; i &lt; s.length; i++){ const val = myMap.get(s[i]) if(!val){ myMap.set(s[i], [i, 1]) } else { myMap.set(s[i], [i, val+1]) } } for(let entry of myMap){ if(entry[1][1] == 1){ return entry[1][0] } } return -1 }; </code></pre> <p>As per my understanding the above code has time complexity <code>O(N)</code> and space complexity <code>O(1)</code>. However, i get pretty bad runtimes using the above solution (tried a lot of times to check if it's issue on leetcode server end). Is there any particular part of my code that is causing this? How can i optimize this further?</p>
[]
[ { "body": "<p>When I execute your solution, I get a result that says that the submission is faster than ~5% of submissions and uses less memory than ~5% of submissions.</p>\n<p>The following solution ran faster than ~94% of submissions and used less memory than ~92% of submissions.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var firstUniqChar = function(s) {\n const characterCounts = new Array(26).fill(0);\n for (let index = 0; index &lt; s.length; index += 1) {\n characterCounts[s.charCodeAt(index) - 97] += 1;\n }\n\n for (let index = 0; index &lt; s.length; index += 1) {\n if (1 === characterCounts[s.charCodeAt(index) - 97]) {\n return index;\n }\n }\n\n return -1;\n}\n</code></pre>\n<p>I don't know the internal implementation of the <code>Map</code> object, so it's hard to get a sense for the instructions that are executed when a <code>Map</code> is created or when <code>get</code> or <code>set</code> are called on a <code>Map</code>, but interestingly enough, if I simply create a <code>new Map</code> at the beginning of my solution (see the following code block), the result is faster than ~38% of solutions. So the creation of a new <code>Map</code> object has a large execution cost.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var firstUniqChar = function(s) {\n new Map();\n const characterCounts = new Array(26).fill(0);\n for (let index = 0; index &lt; s.length; index += 1) {\n characterCounts[s.charCodeAt(index) - 97] += 1;\n }\n\n for (let index = 0; index &lt; s.length; index += 1) {\n if (1 === characterCounts[s.charCodeAt(index) - 97]) {\n return index;\n }\n }\n\n return -1;\n}\n</code></pre>\n<p>If we want to avoid using a <code>Map</code> we could use an array to keep track of character counts. The problem states that &quot;s consists of only lowercase English letters.&quot;. This means we only really need to keep counts for <code>26</code> different values.</p>\n<p>To map a lowercase English letter to an array index, we can use the ASCII character code for each letter. The ASCII character code for lowercase English letters are between <code>97</code> (<code>a</code>) and <code>122</code> (<code>z</code>) inclusive. If we subtract <code>97</code> from these ASCII character codes, we have the values <code>0</code> to <code>25</code>. We can use these values as the indexes of our <code>26</code> element array.</p>\n<p>So if we iterate over each character in the input string, we can identify the ASCII character code for each character, subtract <code>97</code> to get the relevant index in our array, and increment the count at that index. This should give us the counts for all letters in the input string.</p>\n<p>If we iterate over the characters in the input string again, we can check the array of character counts for each character. Return the index for the first character that has a count of <code>1</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:48:55.323", "Id": "269169", "ParentId": "269161", "Score": "2" } }, { "body": "<h3>Make the logic more obviously correct</h3>\n<p>This piece of code made me doubt if the logic is correct:</p>\n<blockquote>\n<pre><code>for(let entry of myMap){\n if(entry[1][1] == 1){\n return entry[1][0]\n }\n}\n</code></pre>\n</blockquote>\n<p>My first doubt was the iteration order of <code>Map</code> entries. In most languages that I know, the iteration order of map data structures is undefined. I had to lookup in the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">docs</a> to see that indeed <code>Map</code> in JavaScript <em>remembers the original insertion order of the keys</em>. So far so good.</p>\n<p>My second doubt was, ok so for the program to work correctly, the entries in <code>myMap</code> would have to be inserted in the correct order. And they are, but I had to read and understand how <code>myMap</code> is populated to be convinced.</p>\n<p>My natural approach to find the first character would be to iterate over the input string:</p>\n<pre><code>for (let i = 0; i &lt; s.length; i++) {\n const [ index, count ] = myMap.get(s[i]);\n if (count === 1) {\n return index;\n }\n}\n</code></pre>\n<p>Written like this, I don't have any doubts about the iteration order of maps, or how <code>myMap</code> was populated. It's evident that I'm iterating over letters in the correct order, so as long as <code>myMap</code> contains what I think it does, this code looks correct.</p>\n<p>Written like this, I realize one more thing. I don't need the index in the map entry anymore, since I already have it, in the <code>i</code> variable. So I go ahead and change <code>myMap</code> to contain only the counts of characters. At this point, I also rename some variables to names as they feel natural:</p>\n<pre><code>const counts = new Map();\n\nfor (let index = 0; index &lt; s.length; index++) {\n const letter = s[index];\n \n if (!counts.has(letter)) {\n counts.set(letter, 1);\n } else {\n counts.set(letter, counts.get(letter) + 1);\n }\n}\n\nfor (let index = 0; index &lt; s.length; index++) {\n const count = counts.get(s[index]);\n if (count === 1) {\n return index;\n }\n}\n</code></pre>\n<p>This turns out to be much faster than the previous version. The significant change is that the values in the map are simple integers instead of arrays.</p>\n<h3>Checking if a map contains a key correctly</h3>\n<p>Looking at this kind of code out of context, I would suspect a possible bug.\nThis is not the correct way to check if a map does not contain a key.</p>\n<blockquote>\n<pre><code>const val = myMap.get(s[i])\nif(!val){\n</code></pre>\n</blockquote>\n<p>Because, if the map could contain <em>falsy</em> values, such as <code>false</code>, or <code>0</code>, or <code>''</code>, or <code>null</code>, or <code>undefined</code> (... I hope I didn't miss anything!), then the condition would pass, and most probably that would not be intended.</p>\n<p>The correct way:</p>\n<blockquote>\n<pre><code>if (!myMap.has(s[i])) {\n</code></pre>\n</blockquote>\n<p>The current code works fine because all the keys are guaranteed to be letters of the English alphabet, and none of them are falsy. As a matter of principle, it's good to build the habit of using the correct idiom when working with maps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T18:50:49.683", "Id": "269207", "ParentId": "269161", "Score": "1" } }, { "body": "<h3>Your code is actually <em>buggy</em>, though <em>correctly</em>.</h3>\n<ul>\n<li><em>Buggy</em> here means the code is not what you want.</li>\n<li><em>Correctly</em> here means it passes all testcases.</li>\n</ul>\n<pre class=\"lang-javascript prettyprint-override\"><code>const val = myMap.get(s[i]);\nif (!val) {\n myMap.set(s[i], [i, 1]);\n} else {\n myMap.set(s[i], [i, val + 1]);\n}\n</code></pre>\n<p>What is the value saved in the <code>myMap</code>? <em>Maybe</em> you originally meant:</p>\n<blockquote>\n<p>The value in map is a tuple, while first value is the index of last occurrence, and the second value is the count of occurrence.</p>\n</blockquote>\n<p>But is this true?</p>\n<p>You may have some test by your self:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var firstUniqChar = function (s) {\n let myMap = new Map()\n for (let i = 0; i &lt; s.length; i++){\n const val = myMap.get(s[i]);\n if (!val) {\n myMap.set(s[i], [i, 1])\n } else {\n myMap.set(s[i], [i, val + 1])\n }\n }\n return myMap;\n}\nconsole.log(firstUniqChar('aaaab').get('a'));\n</code></pre>\n<p>You will get <code>[ 3, &quot;2,1,0,1111&quot; ]</code> on the console.</p>\n<p>Yes, your program still calculated the correct result. But maybe the string <code>&quot;2,1,0,1111&quot;</code> is not what you want anyway.</p>\n<p>Consider a large input, you are trying to build some (maybe much larger) strings in the Map. And the JavaScript runtime have to handle these large strings (allocate memory, type convert, write memory, garbage collection...). That would cost too much times.</p>\n<p>I haven't tested your code on LCOJ. Maybe you can fix this bug (is this a bug?) and see if it have a better performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T09:24:04.700", "Id": "269451", "ParentId": "269161", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T20:27:40.607", "Id": "269161", "Score": "2", "Tags": [ "javascript", "performance", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "Leetcode First Unique Character in a String code optimisation" }
269161
<p>would love a review for this hook.</p> <p>The context:</p> <ul> <li>I have a &quot;date slider&quot;, which has &quot;today&quot;, and previous days</li> <li>It's possible that a user leaves the app, and when he re-opens it from foreground, it's the next day</li> <li>In a scenario like this, I'd like to reset the state.</li> </ul> <p>So, to do this, I wrote up the following:</p> <pre class="lang-javascript prettyprint-override"><code>function useForegroundListener(f) { const appState = useRef(AppState.currentState); const lastOpenedDate = useRef(subHours(new Date(), 3)); useEffect(() =&gt; { const sub = AppState.addEventListener(&quot;change&quot;, (nextAppState) =&gt; { if ( appState.current.match(/inactive|background/) &amp;&amp; nextAppState === &quot;active&quot; ) { f(lastOpenedDate.current); lastOpenedDate.current = new Date(); } appState.current = nextAppState; }); return () =&gt; sub?.remove(); }, [f]); } function useForegroundingResettingState(hoursForReset, f) { const [state, setState] = useState(f()); const foregroundFn = useCallback( (lastOpenedDate) =&gt; { const openedDate = new Date(); const numHoursPassed = differenceInHours(openedDate, lastOpenedDate); if (numHoursPassed &gt;= hoursForReset) { console.log( &quot;Reset state, too much time has passed since foreground!&quot;, numHoursPassed, hoursForReset ); setState(f()); } else { console.log( &quot;Ignoring foreground, not enought time has passed&quot;, numHoursPassed, hoursForReset ); } }, [hoursForReset, f] ); useForegroundListener(foregroundFn); return [state, setState]; } </code></pre> <p>I can then do something like this:</p> <pre><code>const [date, setDate] = useForegroundingResettingState(3, () =&gt; new Date()); </code></pre> <p>Now, I can use <code>date</code> <code>setDate</code> as normal, but if the user comes back from the foreground after 3 hours, this will <code>reset</code></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T21:20:42.577", "Id": "269164", "Score": "0", "Tags": [ "react.js", "react-native" ], "Title": "React Native useForegroundResettingState hook" }
269164
<p>This is my implementation of the Pig Latin recommended exercise in The Rust Programming Language book. Any pointers on making this code more idiomatic or run more optimal?</p> <pre class="lang-rust prettyprint-override"><code>fn pig_latin() { let s = String::from(&quot;Some abobus string 32 text привет абоба 123&quot;); let mut new_s = s.clone(); let consonant = Vec::from([ 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ' ]); // Согласные for word in s.split_whitespace() { let chars = word.chars(); if let Some(ch) = chars.peekable().peek() { if ch.is_alphabetic() { if consonant.contains(ch.to_lowercase().peekable().peek().map_or(ch, |v| v )) { new_s = new_s.replace(word, &amp;format!(&quot;{}-{}ay&quot;, &amp;word[ch.len_utf8()..word.len()], ch)); } else { new_s = new_s.replace(word, &amp;format!(&quot;{}-hay&quot;, &amp;word[0..word.len()])); } } } } println!(&quot;Old: '{}' \nNew: '{}'&quot;, s, new_s); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T16:42:23.600", "Id": "532573", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<pre><code>let consonant = Vec::from([\n 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r',\n 's', 't', 'v', 'w', 'x', 'y', 'z', 'б', 'в', 'г', 'д', 'ж', 'з', 'й',\n 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ'\n]);\n</code></pre>\n<p>An alternative would be:</p>\n<pre><code>fn is_consonant(character: char) -&gt; bool {\n matches!(character, 'b' | 'c' | ...)\n}\n</code></pre>\n<p>My theory would be that Rust probably generated somewhat better code against a pattern match as compared to searching a vector.</p>\n<pre><code> let chars = word.chars();\n if let Some(ch) = chars.peekable().peek() {\n</code></pre>\n<p>There doesn't seem to be any reason to use peekable here. Just use <code>word.chars.next()</code>.</p>\n<pre><code> if consonant.contains(ch.to_lowercase().peekable().peek().map_or(ch, |v| v )) {\n</code></pre>\n<p>You don't need peekable here either. I would also probably not use <code>map_or</code> but instead <code>unwrap</code>. My theory would be that <code>to_lowercase</code> is never going to return an empty string, so <code>next</code> or <code>peek</code> should always return something. If it doesn't, I don't think falling back to <code>ch</code> makes sense.</p>\n<pre><code> new_s = new_s.replace(word, &amp;format!(&quot;{}-{}ay&quot;, &amp;word[ch.len_utf8()..word.len()], ch));\n</code></pre>\n<p>This is wrong. You replace the whole string, but its very possible that the word appears other places in the string and will give you odd results.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T10:07:31.670", "Id": "269760", "ParentId": "269165", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T21:29:12.813", "Id": "269165", "Score": "2", "Tags": [ "strings", "rust", "pig-latin" ], "Title": "The Rust Programming Language Pig Latin" }
269165
<p>I consistently have code where I need to pull individual chunks of substrings out of a larger string; while I won't get into details, it's easy to replicate in a proof of concept:</p> <pre><code>var data = &quot;alja5nerjvnalskjnbaeviunreklvnaslidhfvbaelkjnrfvliasndve&quot;; var open = data.Substring(0, 4); var inputLength = int.Parse(data.Substring(4, 1)); var input = data.Substring(5, inputLength); data = data.Substring(5 + inputLength); ... </code></pre> <p>Now, let's ignore the ellipsis for now and focus on the magic numbers and having to keep track of indices. I'm not a fan of that, I'm sure others aren't either, so a way to make this easier to understand is to remove what we just retrieved from <code>input</code>, each time we retrieve it:</p> <pre><code>var data = ...; // Get the open variable, then remove it from the data. const int openLength = 4; var open = input.Substring(0, openLength); data = data.Remove(0, openLength); // Get the input length variable, then remove it from the data. const int expectedInputLength = 1; // Bad naming, I know. var inputLength = int.Parse(data.Substring(0, expectedInputLength)); data = data.Remove(0, expectedInputLength); // Get the input variable, then remove it from the data. var input = data.Substring(0, inputLength); data = data.Remove(0, inputLength); </code></pre> <p>Unfortunately, this way gets quite verbose and leaves developers leaning towards the original snippet, which is fine, it's just harder to manage (in my opinion). However, I've decided to create an extension method for strings that handles this use case in a more efficient way:</p> <pre><code>public static string Substring(this string input, int startingIndex, int length, ref string removeFrom) { var substring = input.Substring(startingIndex, length); removeFrom = removeFrom.Remove(startingIndex, length); return substring; } </code></pre> <p>The usage changes the previously verbose code back to the original snippet's form, with less guess work:</p> <pre><code>var data = ...; var open = data.Substring(0, 4, removeFrom: ref data); var inputLength = int.Parse(data.Substring(0, 1), removeFrom: ref data)); var input = data.Substring(0, inputLength, removeFrom: ref data); </code></pre> <h5>Working Example</h5> <p>I've created a working example that you can test on <a href="https://dotnetfiddle.net/acSP6P" rel="nofollow noreferrer">.NET Fiddle</a>; the complete code for it is:</p> <pre><code>using System; public static class ExtensionMethods { public static string Substring(this string input, int startingIndex, int length, ref string removeFrom) { var substring = input.Substring(startingIndex, length); removeFrom = removeFrom.Remove(startingIndex, length); return substring; } } public class Program { public static void Main() { var data = &quot;alja5nerjvnalskjnbaeviunreklvnaslidhfvbaelkjnrfvliasndve&quot;; Console.WriteLine(data); var open = data.Substring(0, 4, removeFrom: ref data); var inputLength = int.Parse(data.Substring(0, 1, removeFrom: ref data)); var input = data.Substring(0, inputLength, removeFrom: ref data); Console.WriteLine(open); Console.WriteLine(inputLength); Console.WriteLine(input); Console.WriteLine(data); } } </code></pre> <p>The expected output of which is:</p> <blockquote> <p>alja5nerjvnalskjnbaeviunreklvnaslidhfvbaelkjnrfvliasndve<br> alja<br> 5<br> nerjv<br> nalskjnbaeviunreklvnaslidhfvbaelkjnrfvliasndve</p> </blockquote> <h5>Notes</h5> <p>I have no interest in discussing the following:</p> <ul> <li>The use of <code>Parse</code> over <code>TryParse</code>. <ul> <li>I don't care if the proof of concept blows up, I use <code>TryParse</code> where necessary.</li> </ul> </li> <li>The use of magic numbers in the second and final examples. <ul> <li>I will actually have constants to represent things such as <code>openLength</code> and <code>expectedInputLength</code>.</li> </ul> </li> <li>The lack of validation for <code>removeFrom</code> in the extension method. <ul> <li>I want this to blow up if the implementation doesn't check the value prior.</li> </ul> </li> <li>Stylistic issues such as: <ul> <li>Brace placement.</li> <li>Indentation.</li> </ul> </li> </ul> <hr /> <p>I'd like the community's review of this extension method. My biggest concern in particular is the name of the method not clearly articulating what's going on, even with the named variable in the implementation (which would be a standards thing).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:18:01.187", "Id": "531004", "Score": "1", "body": "IMHO this `data.Substring(..., ref data)` looks really weird. I do understand the intent but passing the same parameter twice seems odd. Are you interested about alternative solution for this particular problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:31:14.207", "Id": "531005", "Score": "1", "body": "It is also error-prone since the caller can pass different strings for `input` and `removeFrom` parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T12:11:32.560", "Id": "531029", "Score": "1", "body": "I think Span + Slice completely covers your task." } ]
[ { "body": "<p>Overloading a built-in string method with an extension method is not a good idea IMO, especially something as well known as <code>Substring</code>.</p>\n<p>I'd also avoid mutating arguments, it's a recipe for confusing code. You do have the <code>ref</code> clue here but it's a practice best avoided. It's easier to reason about code that takes an input and returns an output than code that takes an input, changes it and also returns an output.</p>\n<p>The simple answer to your question is to create a static helper:</p>\n<pre><code>public static (string substring, string remaining) Cut(string input, int start, int length)\n{\n var substring = input.Substring(start, length);\n var remaining = input.Remove(start, length);\n return (substring, remaining);\n}\n</code></pre>\n<p>You can keep the <code>ref</code> if that's your thing:</p>\n<pre><code>public static string Cut(ref string input, int startingIndex, int length) \n{\n var substring = input.Substring(startingIndex, length);\n input = input.Remove(startingIndex, length);\n return substring;\n}\n</code></pre>\n<p>I think the better answer would be to create a class to hold the parsing logic. Consuming it could look like this:</p>\n<pre><code>var data = ...\nvar parsed = MyParser.Parse(data);\nConsole.WriteLine(parsed.Open);\nConsole.WriteLine(parsed.OtherStuff);\n</code></pre>\n<p>It means your <code>MyParser</code> can also own all of the magic numbers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T11:41:10.583", "Id": "269180", "ParentId": "269170", "Score": "3" } }, { "body": "<h2>Reusability vs readability</h2>\n<p>You've definitely tried to improved the code and abstract it. You've made some strides in promoting reusability.</p>\n<p>However, you haven't tackled the bigger issue of readability and complicated code (e.g. index juggling), which make both the old and new examples cumbersome to handle. Additionally, the signature of your fixes is similarly complicated, therefore compounding the issue of complexity.</p>\n<p>The main issue here is <code>ref data</code>. Having to pass the same <code>data</code> reference twice really detracts from your solution. Sadly, you can't alter a string by reference by doing <code>myString.MyMethod()</code>. I understand why you therefore started using <code>ref data</code> as this does allow you to alter by reference, but this is a case where you should've looked for alternatives, instead of persisting with your initial idea. It's all about finding the path of least resistance, and your solution met more resistance than it could have.</p>\n<p>Secondly, it's actually inefficient to always create new strings. Strings are immutable, and each new string (= unique sequence of characters) you create takes up more and more memory. The garbage collector tries to catch up but you can create significant memory issues if your logic very quickly generates many new strings.</p>\n<p>I want to redesign the approach from the ground up, as this will help in understanding how to alleviate the complexities and making sure that the abstractions we implement actually make the end user's life simpler.</p>\n<p>I suggest you compare your approach with my suggested approach, both from the perspective of the developer who created them and the developer who will use them. Which is cleaner? Which do you think a newcomer will understand better? Why? How you could have changed one approach to be more like the other?</p>\n<hr />\n<h2>Basic solution</h2>\n<p>What you're really trying to do, when all it said and done, it to <strong>take</strong> a certain amount of characters from a string, in a way that it also removes them from the original. That is the outset, and we should design our solution to best fit with this goal.</p>\n<p>As I mentioned before, it's actually inefficient to always create new strings. It's better to keep working with the same string, and just have a secretly tracked index which automatically skips the first <code>X</code> characters of the string (i.e. the characters you've already handled).</p>\n<p>Because you are trying to track state (i.e. the secret index), an OOP solution will help you encapsulate your state and use it while at the same time hiding it from the consumer.<br />\nA second way you could've come to the realization that OOP is useful here is that you can't alter a string by reference by doing <code>myString.MyMethod()</code>, but if you wrap that string in an object, you <em>can</em> alter that object by reference by doing <code>myObjectContainingMyString.MyMethod()</code>.</p>\n<p>To the consumer, this alternate approach will handle exactly the same. It's as if the handled characters no longer exist. But internally, you simply skip over the characters. They're still there, they're just not used anymore.</p>\n<p>I'm going to call this a <code>StringQueue</code>, because it basically makes your data behave like a queue of substrings.</p>\n<p>First, the initial state. We create a queue, with a given data string. The secret index is 0 since we have not processed any characters yet.</p>\n<pre><code>public class StringQueue\n{\n private readonly string original;\n private int index;\n\n public StringQueue(string data)\n {\n this.original = data;\n this.index = 0;\n }\n}\n</code></pre>\n<p>Now we want to have a public method that allows you to take the next <code>X</code> characters. The secret index then also increases by <code>X</code>.</p>\n<pre><code>public string Next(int count)\n{\n var chars = original.Substring(index, count);\n index += count;\n \n return chars;\n}\n</code></pre>\n<p>However, I want to suggest a readability improvement here. LINQ adds a lot of nice and readable features to C#, allowing you to cut down on the syntactic complexity and keeps things readable.<br />\nAs a <code>string</code> is inherently treated as if it's a <code>char[]</code>, this means you can rther easily rewrite the above method to be nicer to read:</p>\n<pre><code>public string Next(int count)\n{\n var chars = original.Skip(index).Take(count);\n index += count;\n \n return new string(chars.ToArray());\n}\n</code></pre>\n<p>Does it matter much? Well, for this small method, maybe it doesn't. Maybe the (arguably negligible in most cases) performance difference matters more to you. That is certainly a possibility.</p>\n<p>I find the LINQ approach to be more intuitively understandable. I don't use <code>Substring</code> much and I sometimes forget whether the second parameter denotes a length or an ending index. But <code>Skip</code> and <code>Take</code> are clear and unambiguous.</p>\n<p>Even if you don't use it here, LINQ is a good trick to keep in your repertoire because when the code gets to be more complex, the readability enhancement can do a lot to help keep things sane and readable.</p>\n<p>Basic usage of <code>StringQueue</code> would be (<a href=\"https://dotnetfiddle.net/1fyf1K\" rel=\"nofollow noreferrer\">fiddle</a>)</p>\n<pre><code>var q = new StringQueue(&quot;abcdefghij&quot;);\n\nfor(int i = 0; i &lt; 5; i++)\n{\n Console.WriteLine(q.Next(3));\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>abc\ndef\nghi\nj // 1 character\n // empty string\n</code></pre>\n<p>This has significantly whittled down the complexity of the syntax when using the <code>StringQueue</code>. All you need to do now is specify the source string and tell it how big your chunks should be.</p>\n<hr />\n<h2>Further improvement</h2>\n<p>There's another feature you could add here. I'm unsure if this is needed for your current use case, but it might be nicer to use in certain scenarios where you break a string in many chunks at the same time.</p>\n<p>By implementing method chaining and <code>out</code> parameters, you could create a syntax that allows you to very quickly define your chunks.</p>\n<pre><code>public StringQueue Next(int count, out string result)\n{\n result = Next(count);\n return this;\n}\n</code></pre>\n<p>Note that this relies on the existence of the earlier <code>Next</code> method we discussed.</p>\n<p>This allows for a syntax using <code>out</code> parameters and quick chaining:</p>\n<pre><code>new StringQueue(&quot;abcdefghij&quot;)\n .Next(3, out string first)\n .Next(3, out string second)\n .Next(3, out string third);\n \nConsole.WriteLine(first);\nConsole.WriteLine(second);\nConsole.WriteLine(third);\n</code></pre>\n<p>Output:</p>\n<pre><code>abc\ndef\nghi\n</code></pre>\n<p>I really like this approach. The one niggle here is that it doesn't play nice with converting the substrings to different types, because that would break the chain. But we can add this functionality.</p>\n<p>Note that I'm intentionally not implementing the conversion logic for specific target types in <code>StringQueue</code> itself, as this would violate SRP. It is up to the consumer to decide how they want their substrings to be converted.</p>\n<pre><code>public T Next&lt;T&gt;(int count, Func&lt;string, T&gt; convert)\n{\n return convert(Next(count));\n}\n\npublic StringQueue Next&lt;T&gt;(int count, out T result, Func&lt;string, T&gt; convert)\n{\n result = Next(count, convert);\n return this;\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>// With method chaining\n\nnew StringQueue(&quot;abc123ghij&quot;)\n .Next(3, out string first)\n .Next(3, out int second, s =&gt; Convert.ToInt32(s))\n .Next(3, out string third);\n \nConsole.WriteLine(first);\nConsole.WriteLine(second);\nConsole.WriteLine(third);\n\n// Without method chaining\n\nvar q = new StringQueue(&quot;abc123ghij&quot;);\n \nConsole.WriteLine(q.Next(3));\nConsole.WriteLine(q.Next(3, s =&gt; Convert.ToInt32(s)));\nConsole.WriteLine(q.Next(3));\n</code></pre>\n<hr />\n<p>All code and usage examples can be found in <a href=\"https://dotnetfiddle.net/1fyf1K\" rel=\"nofollow noreferrer\">this fiddle</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:05:22.663", "Id": "531055", "Score": "0", "body": "Oh, now this I love!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T12:43:52.703", "Id": "269183", "ParentId": "269170", "Score": "5" } }, { "body": "<p>Let me share with you yet another solution. ;)</p>\n<p>The basic idea is the following:</p>\n<ul>\n<li>Define slices (upfront) by specifying their length and optional padding</li>\n<li>Iterate through the slices and return chunks after each other</li>\n<li>Use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges\" rel=\"nofollow noreferrer\">Range</a>s instead of the substring method</li>\n</ul>\n<p>So, first let's define the <code>Slice</code>:</p>\n<pre><code>struct Slice\n{\n public byte Length { get; init; }\n public byte? Padding { get; init; }\n}\n</code></pre>\n<ul>\n<li>It could be a <code>class</code> or a <code>record</code> it really does not matter</li>\n</ul>\n<p>Next, let's define the slices upfront:</p>\n<pre><code>var slices = new List&lt;Slice&gt;\n{\n new Slice { Length = 4 },\n new Slice { Length = 1 },\n new Slice { Length = 5 },\n new Slice { Length = 6, Padding = 1 },\n};\n</code></pre>\n<p>Now let's implement the iterable method which returns the chunks:</p>\n<pre><code>public static IEnumerable&lt;string&gt; GetChunks(string input, IEnumerable&lt;Slice&gt; slices)\n{\n byte currentPadding = 0;\n foreach (var slice in slices)\n {\n int startindex = currentPadding + (slice.Padding ?? 0);\n var chunk = new string(input.AsSpan()[(startindex)..(startindex+slice.Length)]);\n currentPadding += slice.Length;\n yield return chunk;\n }\n yield return new string(input.AsSpan()[(currentPadding+1)..]);\n}\n</code></pre>\n<p>Several notes about the above code:</p>\n<ul>\n<li>For the sake of simplicity I've omitted all safe checks</li>\n<li><code>currentPadding</code> captures the start position of the next chunk</li>\n<li>if the next <code>Slice</code> defines a padding then we add that to the <code>currentPadding</code> otherwise we add zero</li>\n<li>We treat the string as an <code>ReadOnlySpan&lt;char&gt;</code> to be able to use range-based indexing</li>\n<li>We construct each and everytime a <code>new string</code> based on the slice</li>\n<li>We increment the <code>currentPadding</code> for the next slice and then we <code>yield return</code> the newly constructed string</li>\n<li>And finally we yield return the rest of the string if there is no more slice defined</li>\n</ul>\n<p>Please note that we can't preserve the result of <code>input.AsSpan()</code> into a method level variable, because <code>IReadOnlySpan</code> can't be used in an iterator block (CS4013).</p>\n<p>Finally, we can simple wire up things:</p>\n<pre><code>var data = &quot;alja5nerjvnalskjnbaeviunreklvnaslidhfvbaelkjnrfvliasndve&quot;;\nforeach (var chunk in GetChunks(data, slices))\n{\n Console.WriteLine(chunk);\n}\n</code></pre>\n<p>The output will be the following:</p>\n<pre class=\"lang-none prettyprint-override\"><code>alja\n5\nnerjv\nalskjn\nbaeviunreklvnaslidhfvbaelkjnrfvliasndve\n</code></pre>\n<hr />\n<p>Known limitation of this solution: The slices are defined upfront. So, you can't define slices based on the read values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:19:43.390", "Id": "269194", "ParentId": "269170", "Score": "3" } }, { "body": "<p>Here are a couple of observations.</p>\n<p>There's a fine balance between elegant code, fast code, and maintainable code.</p>\n<p>Although your code may be clean and elegant, even fast, it may not be easy to understand what it actually does at first glance. (i.e. not easily maintainable) That <code>ref removeFrom</code> may be legal and perfectly legitimate as far as the compiler cares, but it takes a minute to wrap one's head around what's happening there.</p>\n<p>Also, as others have mentioned, overloading a base method is only sometimes ok, for example if one is making some developer oriented framework / extension. However, be sure to respect the basic intention of the original method. In this case, you are not only performing a substring, but really altering the string that was provided by extracting specific pieces based on some internal logic. IMO, that would warrant a <em>brand new method name</em> that tells the next developer down the line who inherits your code exactly what happens, and what is expected to pop out of the method.</p>\n<p>Then you will be free to remove the ref and simply return the modified / desired portion of the string as a return value, instead of altering the original string.</p>\n<p>I do like the idea of making some sort of &quot;extract&quot; extension from string as a quick and common way to get some logical portion of the string. I'm surprised there's not a built in way after all these years!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T00:04:59.133", "Id": "269212", "ParentId": "269170", "Score": "3" } }, { "body": "<p>I also like Flater's idea of <code>StringQueue</code> :-)</p>\n<p>Here are some additional ideas that you can play with.</p>\n<p><code>Microsoft.Extensions.Primitives</code> has a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.primitives.stringsegment?view=dotnet-plat-ext-5.0\" rel=\"nofollow noreferrer\">StringSegment</a> class.</p>\n<p>Consider changing the <code>Next</code> function to the following:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public StringSegment Next(int count)\n{\n var segment = new StringSegment(data, index, count);\n index += count;\n return segment;\n}\n</code></pre>\n<p>For some applications, it's more optimal to work with the underlying <code>char</code> array than the <code>string</code> itself.</p>\n<p>Consider creating something like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class StringArray\n{\n public StringArray(String text)\n {\n data = text.ToCharArray();\n }\n\n public ArraySegment&lt;char&gt; Next(int count)\n {\n var segment = new ArraySegment&lt;char&gt;(data, index, count);\n index += count;\n return segment;\n }\n\n private int index;\n private char[] data;\n}\n</code></pre>\n<p>And creating functions like the following:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>int SegmentToNumber(ArraySegment&lt;char&gt; segment)\n{\n int value = 0;\n foreach (char c in segment)\n {\n value *= 10;\n value += c - '0';\n }\n return value;\n}\n</code></pre>\n<p><b>Will any of this make a difference?</b></p>\n<p>I was not really sure myself but decided to do a little testing:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.Extensions.Primitives;\n\npublic class Program\n{\n const int numberLength = 5;\n\n public static int TestStringSimple(List&lt;string&gt; list)\n {\n int total = 0;\n foreach(var line in list)\n {\n int count = line.Length / numberLength;\n for (int i=0; i&lt;count; i++)\n {\n total += int.Parse(line.Substring(i * numberLength, numberLength));\n }\n }\n return total;\n }\n\n public static int TestStringSegment(List&lt;string&gt; list)\n {\n int total = 0;\n foreach (var line in list)\n {\n int count = line.Length / numberLength;\n for (int i = 0; i &lt; count; i++)\n {\n var segment = new StringSegment(line, i * numberLength, numberLength);\n total += int.Parse(segment);\n }\n }\n return total;\n }\n\n public static int TestArraySegment(List&lt;string&gt; list)\n {\n int total = 0;\n foreach (var line in list)\n {\n char[] data = line.ToCharArray();\n int count = line.Length / numberLength;\n for (int i = 0; i &lt; count; i++)\n {\n var segment = new ArraySegment&lt;char&gt;(data, i * numberLength, numberLength);\n int value = 0;\n foreach (char c in segment)\n {\n value *= 10;\n value += c - '0';\n }\n total += value;\n }\n }\n return total;\n }\n\n public static string GenerateRandomNumberString(Random random, int length)\n {\n const string chars = &quot;0123456789&quot;;\n return new string(Enumerable.Repeat(chars, length)\n .Select(s =&gt; s[random.Next(s.Length)]).ToArray());\n }\n\n public static void Main()\n {\n var rand = new Random();\n\n int count = 1000000;\n var list = new List&lt;string&gt;();\n for (int i = 0; i &lt; count; i++)\n list.Add(GenerateRandomNumberString(rand, numberLength * 20));\n\n for (int i = 0; i &lt; 20; i++)\n {\n int total = TestStringSimple(list);\n Console.WriteLine(total);\n\n total = TestStringSegment(list);\n Console.WriteLine(total);\n\n total = TestArraySegment(list);\n Console.WriteLine(total);\n }\n }\n}\n</code></pre>\n<p>And here are the results:</p>\n<p><a href=\"https://i.stack.imgur.com/n4sWA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n4sWA.png\" alt=\"enter image description here\" /></a></p>\n<p><code>TestArraySegment</code> has an unfair advantage over the other functions that are using <code>int.Parse</code> since it assumes that all the characters will be digits. If we have more secret knowledge, such as the length of the string, we could create something nasty like the following:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static int TestArrayNumFive(List&lt;string&gt; list)\n{\n int total = 0;\n foreach (var line in list)\n {\n char[] data = line.ToCharArray();\n int count = line.Length / numberLength;\n for (int i = 0; i &lt; count; i++)\n {\n var segment = new ArraySegment&lt;char&gt;(data, i * numberLength, numberLength);\n total += (segment[0] - '0') * 10000 +\n (segment[1] - '0') * 1000 +\n (segment[2] - '0') * 100 +\n (segment[3] - '0') * 10 +\n (segment[4] - '0');\n }\n }\n return total;\n}\n</code></pre>\n<p>That really flies =)\n<a href=\"https://i.stack.imgur.com/uCkU3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uCkU3.png\" alt=\"enter image description here\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T13:48:58.513", "Id": "269253", "ParentId": "269170", "Score": "1" } } ]
{ "AcceptedAnswerId": "269183", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:57:22.493", "Id": "269170", "Score": "2", "Tags": [ "c#", "strings", "extension-methods" ], "Title": "Substring extension method with a method of removal" }
269170
<p>For a particular problem, I need to have a list that:</p> <ol> <li>supports <code>O(1)</code> prepend, and</li> <li>that I can call <a href="https://docs.python.org/3.9/library/bisect.html?highlight=bisect#bisect.bisect_left" rel="nofollow noreferrer"><code>bisect.bisect_left</code></a> on, which means the list must be sorted.</li> </ol> <p>Prepending to a list via <code>list.insert(0, item)</code> is <code>O(N)</code>; however, <code>O(1)</code> prepend can be emulated by maintaining the list in reverse order in which case <code>list.append</code> emulates <code>O(1)</code> <code>prepend</code>. This would work, except that <code>bisect_left</code> only works for sorted input, not reverse sorted input. Other functions, like <code>min</code>, allow for reverse sorted order input (or input of arbitrary ordering) with their <code>key</code> argument; unfortunately, <code>bisect_left</code> does not have a <code>key</code> argument for performance reasons.</p> <p>I have a workaround which I would like reviewed. It's a class that subclasses <code>list</code>. The class stores the list in reverse order so that prepend can be implemented via <code>O(1)</code> <code>append</code>, but overrides <code>__getitem__</code> and other methods so that from the outside (including from <code>bisect_left</code>'s view), it looks like the list is in normal order. This way, the list can be used by <code>bisect_left</code> and other functions that only work on sorted order input, and not on reverse sorted order input. The only indication that I have found so far that the list is in reverse is if you <code>print</code> it:</p> <pre><code>class PrependableList(list): '''List with O(1) &quot;prepend&quot;. (appending is O(N))''' def __init__(self, l): super().__init__(reversed(l)) def __getitem__(self, index): N = len(self) index = N - 1 - index return super().__getitem__(index) def __setitem__(self, index, item): N = len(self) index = N - 1 - index return super().__setitem__(index, item) def __iter__(self): return reversed(self) def prepend(self, item): super().append(item) # Are there any other `list` methods that I should override? from bisect import bisect_left nums = PrependableList([5,10,15,20]) nums.prepend(0) print(nums) # [20, 15, 10, 5, 0] # &lt;- how to make this print `[0, 5, 10, 15, 20]` instead? for i in range(len(nums)): print(nums[i]) # uses __getitem__ # prints: # 0 # 5 # 10 # 15 # 20 for num in nums: # uses __iter__ print(num) # prints: # 0 # 5 # 10 # 15 # 20 # `bisect_left` works! for num in range(0, 55): print(f'{num}: {bisect_left(nums, num)}') # uses __getitem__ # prints: # 0: 0 # 1: 1 # 2: 1 # 3: 1 # 4: 1 # 5: 1 # 6: 2 # 7: 2 # 8: 2 # 9: 2 # 10: 2 # 11: 3 # 12: 3 # 13: 3 # 14: 3 # 15: 3 # 16: 4 # 17: 4 # 18: 4 # 19: 4 # 20: 4 # 21: 5 # 22: 5 # 23: 5 # 24: 5 # 25: 5 # 26: 5 # 27: 5 # 28: 5 # 29: 5 # 30: 5 # 31: 5 # 32: 5 # 33: 5 # 34: 5 # 35: 5 # 36: 5 # 37: 5 # 38: 5 # 39: 5 # 40: 5 # 41: 5 # 42: 5 # 43: 5 # 44: 5 # 45: 5 # 46: 5 # 47: 5 # 48: 5 # 49: 5 # 50: 5 # 51: 5 # 52: 5 # 53: 5 # 54: 5 </code></pre> <p>Should just use a <code>deque</code>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T07:40:08.483", "Id": "531011", "Score": "2", "body": "What python version do you use? From the bisect docs : \"Changed in version 3.10: Added the key parameter.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T10:10:40.970", "Id": "531021", "Score": "0", "body": "@kubatucka I'm using 3.8. That's good news, though." } ]
[ { "body": "<blockquote>\n<p>Should just use a <code>deque</code>?</p>\n</blockquote>\n<p>No. Unless you're ok with <code>bisect_left</code> taking O(n log n) instead of O(log n).</p>\n<p>Your class doesn't support negative indexes, like lists normally do. Not saying you should add that (up to you, doesn't sound like you need it), but you can take advantage of lists supporting it to simplify your methods:</p>\n<pre><code> def __getitem__(self, index):\n return super().__getitem__(~index)\n \n def __setitem__(self, index, item):\n return super().__setitem__(~index, item)\n</code></pre>\n<p>Benchmark of <code>bisect_left</code> searching the middle value of a list, deque or PrependableList of a million elements:</p>\n<pre><code> 0.41 μs bisect_left(lst, middle)\n751.68 μs bisect_left(deq, middle)\n 5.77 μs bisect_left(ppl, middle)\n</code></pre>\n<p>Benchmark code (<a href=\"https://tio.run/##fVFBasMwELzrFXsJkoJJnARCKeSYWw@9l2KSaJ0KZFmV5NJe@rK@oV9yV5aTGALVQbAzo9ndkfuKb63dPDjf97VvG4i6QR1BN671cawYCxg7BzvgnLNBdmqNwVPUrQ0XrcL3DjN71IHIC5GrymBNTidzCAGePTq06nA0@KRDFIYu@ciAjsIaqkpbHatKBDR1AWak0gmdQy/k4irx@IE@oBJGyonBGaOO2Fw9tFX4OfHxtJG3E7vbg@@sZczSxqsS5nPYskYrZZAAC8slrJkJkYo0t/AHe0ZhqT1FQOAQhCCBZM4ZAu62TVSKku2JfRlm4pOUkqCA3FHy4p6nDv/y1HbKvzJWtx4qCgHysJsxiQRjgve3ZNJe@d8FFjD8fAG2a47od6uyLOVV6by2UfDZdrGu4fcnAIcZiAhzWOFGFoBZmmWy7/8A\" rel=\"nofollow noreferrer\" title=\"Python 3.8 (pre-release) – Try It Online\">Try it online!</a>):</p>\n<pre><code>from timeit import timeit\n\nsetup = '''\nfrom collections import deque\nfrom bisect import bisect_left\n\nclass PrependableList(list):\n def __init__(self, l):\n super().__init__(reversed(l))\n def __getitem__(self, index):\n return super().__getitem__(~index)\n\nn = 10 ** 6\nmiddle = n // 2\nlst = list(range(n))\ndeq = deque(lst)\nppl = PrependableList(lst)\n'''\n\nE = [\n 'bisect_left(lst, middle)',\n 'bisect_left(deq, middle)',\n 'bisect_left(ppl, middle)',\n]\n\nfor _ in range(3):\n for e in E:\n t = timeit(e, setup, number=1000)\n print('%6.2f μs ' % (t * 1e3), e)\n print()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:10:58.227", "Id": "531056", "Score": "0", "body": "Thanks! `~x == -x - 1`, so I see how `~index` works perfectly for reverse indexing. It's a cool trick! Thanks for the benchmark! Why does `bisect_left` take `O(n log n)` on `deque`? Is it because `deque` is implemented as a (doubly) linked list, therefore `deque.__getitem__` is `O(n)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T20:16:52.247", "Id": "531081", "Score": "1", "body": "@joseville Yes, O(n) for that, and it gets called log n times." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T10:48:26.573", "Id": "269179", "ParentId": "269171", "Score": "2" } }, { "body": "<blockquote>\n<p>Should I just use a <code>deque</code>?</p>\n</blockquote>\n<p>Maybe, it depends on what exactly you're trying to do, but probably not - as dont talk just code pointed out, <code>deque</code> does not offer efficient access to elements near the middle, which is very much not great for binary search. Which is unfortunate, since this approach does come with a very real risk of missing pieces of functionality, especially if the base <code>list</code> class gets updated in future</p>\n<p>Though the <code>help</code> built-in function can help avoid that by providing a list of known methods of a class</p>\n<blockquote>\n<p><code># Are there any other list methods that I should override?</code></p>\n</blockquote>\n<p>Well, there are several non-overridden methods which behave in unexpected ways</p>\n<ul>\n<li>While <code>__getitem__</code> and <code>__setitem__</code> do the right thing, <code>__delitem__</code> deletes the wrong element</li>\n<li>As does <code>pop</code>, <code>insert</code> and <code>index</code> get indexes wrong</li>\n<li>Likewise, <code>append</code> and <code>extend</code> don't append elements but prepend them instead</li>\n<li><code>__reversed__</code> returns the same result as <code>__iter__</code>, which is probably not a good idea</li>\n<li><code>sort</code> effectively sorts in reverse order</li>\n<li><code>__add__</code> places the lists in the wrong order - <code>[1,2] + [3,4] == [1,2,3,4]</code>, but <code>PrependableList([1,2]) + PrependableList([3,4]) == PrependableList([3,4,1,2])</code>. <code>__iadd__</code> has the same problem</li>\n<li>You yourself noted that the list doesn't get printed in the expected manner - that's because <code>__repr__</code> isn't overridden</li>\n</ul>\n<p>And finally, the current implementations of <code>__getitem__</code> and <code>__setitem__</code> don't support slices - <code>PrependableList([1,2,3,4,5])[1:3]</code> raises a <code>TypeError</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:44:35.943", "Id": "531033", "Score": "2", "body": "A deque turns the binary search from O(log n) into O(n log n). I don't think that's a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:05:17.553", "Id": "531034", "Score": "1", "body": "@don'ttalkjustcode That's a good point which I completely overlooked, thanks for pointing it out" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:27:39.733", "Id": "531058", "Score": "0", "body": "@SaraJ thanks, `help(list)` helps! I think I have two options: 1) override the methods mentioned, so that they do the right thing; or 2) Make the `PrependableList` class \"private\", so that it can only be used within the file/module it is defined in and I have total control over how it's used. #2 is viable because I only plan to use `PrependableList` within a single module. A StackOverflow post says that naming a class with a singe leading underscore will prevent it from being imported in a `from <module> import *` statement, so that seems like a sensible solution (although it has caveats)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:30:56.580", "Id": "531059", "Score": "0", "body": "With option #2 of my previous comment, would it also make sense to nest `PrependableList` within the sole class that uses it? Or fine to keep them as seperate classes of the same file/module?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:01:30.127", "Id": "269184", "ParentId": "269171", "Score": "1" } } ]
{ "AcceptedAnswerId": "269179", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T00:01:01.093", "Id": "269171", "Score": "0", "Tags": [ "python", "binary-search" ], "Title": "Python list subclass with O(1) prepend / How to get bisect to work with reverse sorted list" }
269171
<p>This is a follow-up on my first question, <a href="https://codereview.stackexchange.com/questions/269148/little-program-to-measure-costly-operations">Little program to measure costly operations</a>, thanks for all answers and comments, esp. @JDługosz. I made a second attempt adapting a teaching program I found on the web.</p> <p>It already helps me to 'get a handle' on things normally hidden, e.g. i can see the effort for 'POW' compared to divide and e.g the influence of compiler optimizations (besides they mostly result from optimizing away 'dead' calculations).</p> <p>And as on repeated execution the results vary, rather in 'jumps' (up to ~1 : 2,5) than smoothly - there are conditions / circumstances which trigger bad or good performance which I can start to investigate (CPU throttling, memory alignment, caching, thread priority, a weak core or whatever). Although I'm not getting any clue about what is happening in detail, I get a clue that something is different. And I can check the influences of things I change. :-) :-) :-)</p> <p>Any suggestions for further improvements welcome, and the questions:</p> <ul> <li>Are better tools available? which?</li> <li>How to port to C?</li> <li>How to get the compiler doing its optimizations but not omitting the calculations to be timed?</li> </ul> <pre class="lang-cpp prettyprint-override"><code>/* gettime - get time via clock_gettime N.B.: OS X does not support clock_gettime Paul Krzyzanowski many thanks for the template, i hope i din't rape it too much, newbie-02 */ #include &lt;stdio.h&gt; /* for printf */ #include &lt;stdint.h&gt; /* for uint64 definition */ #include &lt;stdlib.h&gt; /* for exit() definition */ #include &lt;time.h&gt; /* for clock_gettime */ #include &lt;thread&gt; // reg. thread, #include &lt;math.h&gt; // reg. pow( x, y ), #include &lt;iostream&gt; // reg. cout, #define BILLION 1000000000L using namespace std::literals; // enables the usage of 24h, 1ms, 1s instead of // e.g. std::chrono::hours(24), accordingly int localpid(void) { static int a[9] = { 0 }; return a[0]; } int main(int argc, char **argv) { int i = 0; // counter, int amount = 1000000; // size of testfield, double testme[amount]; // array with test values, struct timespec start, end, start_1, end_1; // special high precision time values, double x1; // working value, uint64_t diff, diff_1; // 'big numbers' for high nanosecond values, // preparing testvalues for timing, for( i = 0; i &lt; amount; ++i ) { testme[i] = rand() / pow( 2, 16 ); } // timing ' x / 2 ', /* measure monotonic time */ clock_gettime(CLOCK_MONOTONIC, &amp;start); /* mark start time */ /* measure 'CPU_TIME' */ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &amp;start_1); /* mark start time */ for( i = 0; i &lt; amount; ++i ) { x1 = testme[i] / 2; // std::cout &lt;&lt; &quot;' x / 2: &quot; &lt;&lt; x1 &lt;&lt; &quot;\n&quot;; // uncomment to see that real values are processed, careful with high 'amounts', } // std::this_thread::sleep_for(1000ms); // uncomment to see different 'busy' and 'total' timings, clock_gettime(CLOCK_MONOTONIC, &amp;end); /* mark the end time */ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &amp;end_1); /* mark the end time */ diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; diff_1 = BILLION * (end_1.tv_sec - start_1.tv_sec) + end_1.tv_nsec - start_1.tv_nsec; std::cout &lt;&lt; &quot;calculating &quot; &lt;&lt; amount &lt;&lt; &quot; times ' = x / 2 ' took &quot; &lt;&lt; diff &lt;&lt; &quot; nanoseconds &quot; &lt;&lt; &quot; from which the CPU 'used' &quot; &lt;&lt; diff_1 &lt;&lt; &quot; nanoseconds \n&quot;; // timing ' pow( 10, x ) ', /* measure monotonic time */ clock_gettime(CLOCK_MONOTONIC, &amp;start); /* mark start time */ /* measure 'CPU_TIME' */ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &amp;start_1); /* mark start time */ for( i = 0; i &lt; amount; ++i ) { x1 = pow( 10, testme[i] ); // std::cout &lt;&lt; &quot;' x1 = pow( 10, testme[i] )' : &quot; &lt;&lt; x1 &lt;&lt; &quot;\n&quot;; // uncomment to see that real values are processed, careful with high 'amounts', } // std::this_thread::sleep_for(1000ms); // uncomment to see different 'busy' and 'total' timings, clock_gettime(CLOCK_MONOTONIC, &amp;end); /* mark the end time */ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &amp;end_1); /* mark the end time */ diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; diff_1 = BILLION * (end_1.tv_sec - start_1.tv_sec) + end_1.tv_nsec - start_1.tv_nsec; std::cout &lt;&lt; &quot;calculating &quot; &lt;&lt; amount &lt;&lt; &quot; times ' x1 = pow( 10, testme[i] ) ' took &quot; &lt;&lt; diff &lt;&lt; &quot; nanoseconds &quot; &lt;&lt; &quot; from which the CPU 'used' &quot; &lt;&lt; diff_1 &lt;&lt; &quot; nanoseconds \n&quot;; exit(0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:58:06.647", "Id": "531008", "Score": "1", "body": "Asking how to port this to C is a separate topic which would probably better be left out from this particular question, and arguably not asked on this site." } ]
[ { "body": "<p>You are including several C headers that have C comments on the lines, and then several C++ headers. Don't use C headers. Sometimes, don't use the C library stuff in C++ (e.g. <code>printf</code>; you are also using <code>cout</code>! and this is a small piece of code! Is it just pasted up from fragments of C and C++ of different ages?)</p>\n<p>See <a href=\"https://en.cppreference.com/w/cpp/header#C_compatibility_headers\" rel=\"nofollow noreferrer\">Cppreference on <em>C compatibility headers</em></a>: (emphasis mine)</p>\n<blockquote>\n<p>For some of the C standard library headers of the form <code>xxx.h</code>, the C++ standard library both includes an identically-named header and another header of the form <code>cxxx</code> (all meaningful <code>cxxx</code> headers are listed above). <strong>The intended use of headers of form <code>xxx.h</code> is for interoperability only.</strong><br />\n⋮<br />\n<code>xxx.h</code> headers are deprecated in C++98 and undeprecated in C++23. These headers are discouraged for pure C++ code, but not subject to future removal.</p>\n</blockquote>\n<p>So,<br />\n<code>#include &lt;stdint.h&gt; /* for uint64 definition */</code><br />\nis clearly pasted in from a C (not C++) program. You should instead write<br />\n<code>#include &lt;cstdint&gt; // for uint64_t</code><br />\nthough the use of this header is so targeted that the comment is unnecessary. I like these comments on grab-bag library headers that have tons of unrelated things in them.</p>\n<p>So, before sending code out for review, review it <em>yourself</em>. Proof reading the whole file, preferably after a break, look for things that are not used, comments that don't match the code, extra spaces, leftover commented-out lines, inconsistent indentation, etc.</p>\n<p>I appreciate (via comments on this thread) that you're not experienced enough to see the difference between different old languages/dialects/idioms, but in general that's something else to look for.</p>\n<p>It's like pasting in a passage from <a href=\"https://en.wikipedia.org/wiki/William_Shakespeare\" rel=\"nofollow noreferrer\">Shakespeare</a> and another from <a href=\"https://en.wikipedia.org/wiki/John_Grisham\" rel=\"nofollow noreferrer\">Grisham</a>.</p>\n<hr />\n<p><code>#define BILLION 1000000000L</code></p>\n<h1>NO.</h1>\n<p>Just don't use <code>#define</code>.</p>\n<p><code>constexpr auto Billion = 1'000'000'000;</code></p>\n<p>Though you probably don't even need this, since the chrono library includes SI prefix rational number stuff and directly knows about <a href=\"https://en.cppreference.com/w/cpp/chrono/duration#Helper_types\" rel=\"nofollow noreferrer\">nanoseconds</a>.</p>\n<p>You may be interested in my article <a href=\"https://www.codeproject.com/Tips/5249485/The-Most-Essential-Cplusplus-Advice\" rel=\"nofollow noreferrer\"><em>The Most Essential C++ Advice</em></a> which covers this, and has pointers to other useful resources.</p>\n<hr />\n<p><code>int localpid(void)</code></p>\n<p>Strustrup calls that &quot;an abomination&quot;. Empty parameter lists in C++ are <code>()</code>. <code>(void)</code> is for C and has no business being in a C++ implementation file.</p>\n<hr />\n<p><code>struct timespec start, end, start_1, end_1;</code></p>\n<p>In C++ you don't need to use <code>struct</code> in front of struct names. This is an indication that it was copy/pasted from C code.</p>\n<p>You generally don't declare multiple variables in one declaration either, and note that these primitive C structures are not initialized. I don't see them used in the next few lines either. <strong>Don't declare variables all huddled together at the top</strong>; C doesn't even require that anymore! Declare variables where you are ready to give it a value.</p>\n<p>You don't need to end <code>main</code> with a call to <code>exit</code>. Just return from it like any other function. You note that you are including a library header just to get <code>exit</code> to use, but you don't need to call it.</p>\n<p>For <code>main</code>, you can omit the <code>return</code> completely and it returns 0. If you don't have anything useful to say, just leave it out.</p>\n<hr />\n<pre><code>int localpid(void) \n{\n static int a[9] = { 0 };\n return a[0];\n}\n</code></pre>\n<p>What is this supposed to accomplish? How's it any different from just:</p>\n<p><code>int localpid() { return 0; }</code></p>\n<p>since the static value is never modified, and you don't use the other 8 values you made room for?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T17:42:34.360", "Id": "531072", "Score": "1", "body": "thank you @JDługosz, looks like a good review. 'fragments ... ages?' - yes, as i didn't find something 'ready' I picked together snippets. see name in 'top_comment', where I can't even distinguish C and C++ I'm surprised myself to have managed something executable ;-) | comments - I like the '//' style better as it's easier to use for temporary code disabling, | 'define' - it's from a 'teaching' program | 'localpid' - as well, but i don't see it in use there | 'struct', 'variables', 'return' - will care for | 'declarations' in other projects I got bombarded! with warnings about the order," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T13:48:18.763", "Id": "531140", "Score": "0", "body": "@user1018684 You might like to read my [Most Essential C++ Advise](https://www.codeproject.com/Tips/5249485/The-Most-Essential-Cplusplus-Advice) article. I'll edit the Answer in light of your remarks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:19:57.173", "Id": "531190", "Score": "0", "body": "thank you @JDługosz, 'reading' - did, sure about this: 'T foo (T x, T,y)' | 'declarations' - it didn't make it through to compilers, people or code i'd meet shortly | 'initializing' - YES | 'unsigned(f)' - 'long double(f)' -> error | are we really missing an 'upgrading' conversion e.g. 'float -> long double' keeping the 'corresponding decimal value' with the 'decimal precision' of the 'lower precise' representation rather than it's FP-conversion artifacts? :-( | rest - as of now above my scope ... | 'Grisham' - it was a quite quick! way for me to start and achieve sth i couldn't find 'ready'." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:23:22.297", "Id": "269195", "ParentId": "269173", "Score": "2" } }, { "body": "<p>Using <code>gettimeofday</code> may give you more <i>precision</i> than <code>clock</code> but is not likely to be any more <b>accurate</b>. When doing benchmarks, we are not so much concerned with how long a function takes in nanoseconds, but more with how long <code>functionA</code> takes compared to <code>functionB</code>.</p>\n<p>Consider the following plain vanilla C code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;math.h&gt;\n#include &lt;time.h&gt;\n\nint main()\n{\n // working value, \n double x1 = 0; \n\n // prepare some test data\n int amount = 100000;\n double testme[amount];\n for (int i = 0; i &lt; amount; ++i)\n testme[i] = (double)rand();\n\n int repeapts = 1000;\n clock_t start;\n clock_t end;\n\n // first test\n start = clock();\n for (int r = 0; r &lt; repeapts; r++)\n {\n for (int i = 0; i &lt; amount; ++i)\n {\n x1 += testme[i] / 2;\n }\n }\n end = clock();\n printf(&quot;calculating %d times * %d repeats ' = x / 2 ' took %ld ticks.\\n&quot;, amount, repeapts, end - start);\n\n // second test\n start = clock();\n for (int r = 0; r &lt; repeapts; r++)\n {\n for (int i = 1; i &lt; amount; ++i)\n {\n x1 += pow(10, testme[i]);\n }\n }\n end = clock();\n printf(&quot;calculating %d times * %d repeats ' x1 = pow( 10, testme[i] )' took %ld ticks.\\n&quot;, amount, repeapts, end - start);\n\n\n printf(&quot;x1 = %f\\n&quot;, x1);\n}\n</code></pre>\n<p>You do not need to be concerned about how long a <code>tick</code> is, only that</p>\n<pre><code>x1 += testme[i] / 2\n</code></pre>\n<p>is roughly 20 times faster than</p>\n<pre><code>x1 += pow(10, testme[i]);\n</code></pre>\n<p>Also take note of the last line:</p>\n<pre><code>printf(&quot;x1 = %f\\n&quot;, x1);\n</code></pre>\n<p>If we don't actually do anything with <code>x1</code> most compilers are smart enough to skip over the loops and you won't measure any ticks at all!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T22:02:55.053", "Id": "531084", "Score": "0", "body": "thanks to @upkajdt! works out of the box, readable, and impressive insights: \n~ g++ -O0 timing.c -o timing -lm\n~./timing\ncalculating 100000 times * 1000 repeats ' = x / 2 ' took 278604 ticks.\nx1 = 24993406.681235\ncalculating 100000 times * 1000 repeats ' x1 = pow( 10, testme[i] )' took 2160413 ticks.\nx1 = 390778681.759619\n~ g++ -Ofast -march=native timing.c -o timing -lm\n./timing\ncalculating 100000 times * 1000 repeats ' = x / 2 ' took 31046 ticks.\nx1 = 24993406.681235\ncalculating 100000 times * 1000 repeats ' x1 = pow( 10, testme[i] )' took 38313 ticks.\nx1 = 390778681.759360" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T22:34:12.763", "Id": "531085", "Score": "0", "body": "@user1018684, Cool! Just be VERY careful about how you interpret the results. `x1 = testme[i] / 2` might seem faster than `x1 = testme[i] + 2` purely because of timing jitters when 90% of the time is actually spent accessing the array and have nothing to do with the calculation =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:35:31.377", "Id": "531193", "Score": "0", "body": "'Just be VERY careful about how you interpret ...' - YES SIR! - of course i'll do, it's just meant to have sth giving me some ... known inexact ... answers. E.g. if an optimization gives identical result to -O0 after 1000*100000 iterations it's likely not 'inexact', if timings vary in 'grains' at repeated calls there likely are conditions influencing it, if '__builtin_powi( x, y)' is faster than but identical results to 'POW(...)' it could be used ..., if -Ofast -march=native' is impressive fast but with small devias it's worth investigating, much better now 'than blind in the fog' :-) :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T18:56:30.180", "Id": "269208", "ParentId": "269173", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:28:51.743", "Id": "269173", "Score": "0", "Tags": [ "c++", "performance" ], "Title": "Little program to measure the 'cost' of CPU-operations" }
269173
<blockquote> <p>As firestore don't support in operation for more than 10 items. So I decided to write a code to handle multiple (OR) query and merge them afterwards.</p> </blockquote> <p>Suppose I want to show posts of the user you follow (that can be more than 10) . <a href="https://stackoverflow.com/questions/69494502/multiple-where-clause-in-firestore-on-map-in-android?noredirect=1#comment122854983_69494502">See my question here for details</a></p> <p>I want to display recent post of the user's someone follows.</p> <p>Code for paging..</p> <pre><code>fun pagingQuery(followers: List&lt;String&gt;) { val queryTask = arrayListOf&lt;Task&lt;QuerySnapshot&gt;&gt;() followers.forEachIndexed { index, user -&gt; var query = fs.collection(&quot;pagingCollection&quot;).limit(5) .whereEqualTo(&quot;createdBy.$user&quot;, true) if (lastDocumentMap.isNotEmpty()) { val documentSnapShot = lastDocumentMap[followers[index]] if (documentSnapShot?.exists() == true) { query = query.startAfter(documentSnapShot) queryTask.add(query.get()) } } else if(firstTimeCall) { queryTask.add(query.get()) } } Tasks.whenAllSuccess&lt;QuerySnapshot&gt;(queryTask).addOnSuccessListener { val allPosts = arrayListOf&lt;PostBO&gt;() lastDocumentMap = hashMapOf() firstTimeCall = false it.forEachIndexed { index, snapshot -&gt; if (snapshot.documents.isNotEmpty()) { val lastDoc = snapshot.documents[snapshot.size() - 1] lastDocumentMap[followers[index]] = lastDoc val posts = snapshot.toObjects(PostBO::class.java) posts.forEach { post -&gt; allPosts.add(post) } } else{ lastDocumentMap.remove(followers[index]) } } if(lastDocumentMap.isNotEmpty()){ //It means no more data available. overAllPost.addAll(allPosts) adapter.notifyDataSetChanged() pagingQuery(followers) } } } </code></pre> <p>And I am calling it like</p> <pre><code>for(i in 1..20){ mFollowers.add(&quot;USER_$i&quot;) } pagingQuery(mFollowers) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:33:07.607", "Id": "269174", "Score": "0", "Tags": [ "android", "kotlin", "firebase" ], "Title": "Firestore Paging implementation for multiple OR query Android" }
269174
<p>the last couple of weeks i have been working on my own WordPress plugin. I am trying to do a class based codebase.</p> <p>My plugin works correctly, but i don't really know if this is the correct way to develop. I would like to learn the best practices.</p> <p>To demonstrate, here is my base plugin file:</p> <pre><code> &lt;?php /** * Blub Hamerhaai plugin * * This is the main blub plugin for all sites * * @link {github link} * @since 0.0.2 * @package Blub Hamerhaai * * @wordpress-plugin * Plugin Name: {plugin name} * Plugin URI: {github link} * Description: This is the main blub plugin for all sites * Version: 0.0.4 * Author: Blub * Author URI: {link} * License: Copyright Blub media, all rights reserved * License URI: {link} * Text Domain: blub-hamerhaai * Domain Path: /languages * * Created by: Me */ namespace Blub; require 'includes/includes.php'; define(__NAMESPACE__ . '\PLUGINROOT', __FILE__); define(__NAMESPACE__ . '\PLUGINDIR', __DIR__); if (!class_exists('Hamerhaai')) { class Hamerhaai { public function __construct() { register_activation_hook(__FILE__, [$this, 'activation']); register_deactivation_hook(__FILE__, [$this, 'deactivation']); add_action('init', [$this, 'init']); } public function activation() { BlubRole::add(); PluginUpdate::add(); } public function deactivation() { BlubRole::remove(); PluginUpdate::remove(); } public function init() { //Preventing removals in other pages global $pagenow; load_textdomain('blub-hamerhaai', PLUGINDIR . '/languages/blub-hamerhaai-nl_NL.mo'); //Things to do for all users new OptionsPage(); new BlubColors(); new CustomLoginPage(); $widget = new DashboardWidget(); // Things to do for blub user if (BlubRole::isBlubUser()) { new AdminText(); new RemoveMenuItems(); new GutenbergEdits(); //Only for dashboard if ($pagenow === 'index.php') { $widget-&gt;forceShow(); $widget-&gt;removeDefault(); } new LoadFrontendStyle(); } } } } new Hamerhaai(); </code></pre> <p>The main thing i am insecure about is instantiating all the classes on the plugin init function. I don't think this is the best practice. All the classes are based on a specific functionality.</p> <p>Can someone explain me if this is the way to go? Or how to improve?</p> <p>Thanks in advance.</p>
[]
[ { "body": "<p><strong>1. The constructor is not a good place for actions &amp; filters.</strong></p>\n<p>See <a href=\"https://wordpress.stackexchange.com/questions/164121/testing-hooks-callback/164138#164138\">this very detailed answer from WP.SE</a> or <a href=\"https://tommcfarlin.com/wordpress-plugin-constructors-hooks/\" rel=\"nofollow noreferrer\">this blog post</a> for some reasoning. As far as I understand, it makes testing much more difficult and in a oop-way doesn't make sense, as it doesn't directly relate to the object's state.</p>\n<p><strong>2. Do you really need that state?</strong></p>\n<p>Right now, your <code>Hamerhaai</code> doesn't actually use state. In this case I usually define the methods as static, which makes enqueue/dequeue much simpler because you don't need the original object.</p>\n<pre><code>register_activation_hook(__FILE__, [$this, 'activation']);\n\n// ...\npublic function activation()\n{\n BlubRole::add();\n PluginUpdate::add();\n}\n</code></pre>\n<p>would become</p>\n<pre><code>register_activation_hook(__FILE__, [__CLASS__, 'activation']);\n\n// ...\npublic static function activation()\n{\n BlubRole::add();\n PluginUpdate::add();\n}\n</code></pre>\n<p>(using <code>__CLASS__</code> simplifies it a lot so you don't need to watch out for namespaces, see <a href=\"https://www.php.net/manual/en/language.constants.predefined.php#71064\" rel=\"nofollow noreferrer\">PHP Doc</a>)</p>\n<p><strong>3. Don't go half the way.</strong></p>\n<p>You're doing modern PHP code. So why <code>require 'includes/includes.php';</code>? Use <a href=\"https://code.tutsplus.com/tutorials/how-to-autoload-classes-with-composer-in-php--cms-35649\" rel=\"nofollow noreferrer\">composer's autoloading</a> feature and avoid manual <code>include</code> / <code>require</code> statements. In my plugins, all code lives somewhere in a class. And the class is easily autoloaded via composer.</p>\n<p>You're in a namespace, so <code>if (!class_exists('Hamerhaai')) { </code> doesn't actually do what you think it does. Instead you should either check for <code>if (!class_exists('Blub\\Hamerhaai')) {</code> or as you're already using <code>__NAMESPACE__</code> something like</p>\n<pre><code>if (!class_exists(__NAMESPACE__ . '\\Hamerhaai')) {\n</code></pre>\n<p><strong>4. Only load code that is actually required</strong></p>\n<pre><code> //Things to do for all users\n new OptionsPage();\n new BlubColors();\n new CustomLoginPage();\n $widget = new DashboardWidget();\n</code></pre>\n<p>this code lives in your <code>init()</code> method. So it is called on every request. Most likely you want to check if the user is logged in, has a specific role, etc. before actually calling it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T09:43:47.390", "Id": "532876", "Score": "0", "body": "Thanks for the feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T09:58:12.840", "Id": "269500", "ParentId": "269175", "Score": "1" } } ]
{ "AcceptedAnswerId": "269500", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T08:06:43.790", "Id": "269175", "Score": "1", "Tags": [ "php", "wordpress" ], "Title": "Instantiating classes in WordPress plugin" }
269175
<p>I have been working on an online <strong><a href="https://github.com/Ajax30/Bravecms/" rel="nofollow noreferrer">newspaper/blogging application</a></strong> with <em>CodeIgniter 3.1.8</em> and Twitter Bootstrap 4.</p> <p>The latest feature added is <em>lazy loading</em> of posts.</p> <p>From the <strong>Static_model</strong> (<code>application\models\Static_model.php</code>), which is responsible with the general settings, I can set <code>$data['is_ajax_loading']</code> to <code>true</code> and enable loading posts via AJAX.</p> <p>In the Posts controller, I have:</p> <pre><code>class Posts extends CI_Controller { public function __construct() { parent::__construct(); } private function _initPagination($path, $totalRows, $query_string_segment = 'page') { // load and configure pagination $this-&gt;load-&gt;library('pagination'); $config['base_url'] = base_url($path); $config['query_string_segment'] = $query_string_segment; $config['enable_query_strings'] = TRUE; $config['reuse_query_string'] = TRUE; $config['total_rows'] = $totalRows; $config['per_page'] = 12; if ($this-&gt;Static_model-&gt;get_static_data()['has_pager']) { $config['display_pages'] = FALSE; $config['first_link'] = FALSE; $config['last_link'] = FALSE; $config['prev_tag_open'] = '&lt;li class=&quot;prev&quot;&gt;'; $config['prev_tag_close'] = '&lt;/li&gt;'; $config['next_tag_open'] = '&lt;li class=&quot;next&quot;&gt;'; $config['next_tag_close'] = '&lt;/li&gt;'; } if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] &lt; 1) { $_GET[$config['query_string_segment']] = 1; } $this-&gt;pagination-&gt;initialize($config); $limit = $config['per_page']; $offset = ($this-&gt;input-&gt;get($config['query_string_segment']) - 1) * $limit; return array( 'limit' =&gt; $limit, 'offset' =&gt; $offset ); } public function index() { //call initialization method $config = $this-&gt;_initPagination(&quot;/&quot;, $this-&gt;Posts_model-&gt;get_num_rows()); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['base_url'] = base_url(&quot;/&quot;); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); $data['search_errors'] = validation_errors(); $data['posts'] = $this-&gt;Posts_model-&gt;get_posts($config['limit'], $config['offset']); $data['max_page'] = ceil($this-&gt;Posts_model-&gt;get_num_rows() / 12); $this-&gt;twig-&gt;addGlobal('pagination', $this-&gt;pagination-&gt;create_links()); // Featured posts if ($data['is_featured']) { $data['featured'] = $this-&gt;Posts_model-&gt;featured_posts(); $this-&gt;twig-&gt;addGlobal('featuredPosts', &quot;themes/{$data['theme_directory']}/partials/hero.twig&quot;); } $this-&gt;twig-&gt;display(&quot;themes/{$data['theme_directory']}/layout&quot;, $data); } public function search() { // Force validation since the form's method is GET $this-&gt;form_validation-&gt;set_data($this-&gt;input-&gt;get()); $this-&gt;form_validation-&gt;set_rules('search', 'search term', 'required|trim|min_length[3]', array( 'min_length' =&gt; 'The search term must be at least 3 characters long.' )); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class = &quot;error search-error&quot;&gt;', '&lt;/p&gt;'); // If search fails if ($this-&gt;form_validation-&gt;run() === FALSE) { $data['search_errors'] = validation_errors(); return $this-&gt;index(); } else { $expression = $this-&gt;input-&gt;get('search'); $posts_count = $this-&gt;Posts_model-&gt;search_count($expression); $query_string_segment = 'page'; $config = $this-&gt;_initPagination(&quot;/posts/search&quot;, $posts_count, $query_string_segment); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['base_url'] = base_url(&quot;/&quot;); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); //use limit and offset returned by _initPaginator method $data['posts'] = $this-&gt;Posts_model-&gt;search($expression, $config['limit'], $config['offset']); $data['expression'] = $expression; $data['posts_count'] = $posts_count; $data['max_page'] = ceil($posts_count / 12); $this-&gt;twig-&gt;addGlobal('pagination', $this-&gt;pagination-&gt;create_links()); $this-&gt;twig-&gt;display(&quot;themes/{$data['theme_directory']}/layout&quot;, $data); } } public function byauthor($authorid) { //load and configure pagination $this-&gt;load-&gt;library('pagination'); $config['base_url'] = base_url('/posts/byauthor/' . $authorid); $config['query_string_segment'] = 'page'; $config['total_rows'] = $this-&gt;Posts_model-&gt;posts_by_author_count($authorid); $config['per_page'] = 12; if ($this-&gt;Static_model-&gt;get_static_data()['has_pager']) { $config['display_pages'] = FALSE; $config['first_link'] = FALSE; $config['last_link'] = FALSE; $config['prev_tag_open'] = '&lt;li class=&quot;prev&quot;&gt;'; $config['prev_tag_close'] = '&lt;/li&gt;'; $config['next_tag_open'] = '&lt;li class=&quot;next&quot;&gt;'; $config['next_tag_close'] = '&lt;/li&gt;'; } if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] &lt; 1) { $_GET[$config['query_string_segment']] = 1; } $limit = $config['per_page']; $offset = ($this-&gt;input-&gt;get($config['query_string_segment']) - 1) * $limit; $this-&gt;pagination-&gt;initialize($config); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['base_url'] = base_url(&quot;/&quot;); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); $data['posts'] = $this-&gt;Posts_model-&gt;get_posts_by_author($authorid, $limit, $offset); $data['posts_count'] = $this-&gt;Posts_model-&gt;posts_by_author_count($authorid); $data['posts_author'] = $this-&gt;Posts_model-&gt;posts_author($authorid); $data['max_page'] = ceil($data['posts_count'] / $limit); $data['tagline'] = &quot;Posts by &quot; . $data['posts_author']-&gt;first_name . &quot; &quot; . $data['posts_author']-&gt;last_name; $this-&gt;twig-&gt;addGlobal('pagination', $this-&gt;pagination-&gt;create_links()); $this-&gt;twig-&gt;display(&quot;themes/{$data['theme_directory']}/layout&quot;, $data); } public function post($slug) { $data = $this-&gt;Static_model-&gt;get_static_data(); $data['base_url'] = base_url(&quot;/&quot;); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); $data['authors'] = $this-&gt;Usermodel-&gt;getAuthors(); $data['posts'] = $this-&gt;Posts_model-&gt;sidebar_posts($limit = 5, $offset = 0); $data['post'] = $this-&gt;Posts_model-&gt;get_post($slug); $data['next_post'] = $this-&gt;Posts_model-&gt;get_next_post($slug); $data['prev_post'] = $this-&gt;Posts_model-&gt;get_prev_post($slug); $data['author_image'] = isset($data['post']-&gt;avatar) &amp;&amp; $data['post']-&gt;avatar !== '' ? $data['post']-&gt;avatar : 'default-avatar.png'; if ($data['categories']) { foreach ($data['categories'] as &amp;$category) { $category-&gt;posts_count = $this-&gt;Posts_model-&gt;count_posts_in_category($category-&gt;id); } } if (!empty($data['post'])) { // Overwrite the default tagline with the post title $data['tagline'] = $data['post']-&gt;title; // Get post comments $post_id = $data['post']-&gt;id; $data['comments'] = $this-&gt;Comments_model-&gt;get_comments($post_id); $this-&gt;twig-&gt;addGlobal('singlePost', &quot;themes/{$data['theme_directory']}/templates/singlepost.twig&quot;); } else { $data['tagline'] = &quot;Page not found&quot;; $this-&gt;twig-&gt;addGlobal('notFound', &quot;themes/{$data['theme_directory']}/templates/404.twig&quot;); } $this-&gt;twig-&gt;display(&quot;themes/{$data['theme_directory']}/layout&quot;, $data); } } </code></pre> <p>The script that does the loading:</p> <pre><code>(function($) { var currentPage = 2, maxPage = $('#postsContainer').data('max-page'), posts = null, pageUrl = $(location).attr('href'), pageBaseUrl = pageUrl.split('?')[0], searchStr = pageUrl.split('?')[1]; $('.pagination').hide(); $(window).scroll(function() { var toBottom = $(window).scrollTop() &gt;= $(document).height() - $(window).height() - 25; if (toBottom &amp;&amp; currentPage &lt;= maxPage) { loadMore(); } }); function loadMore() { $.ajax({ url: `${pageBaseUrl}?${typeof searchStr === 'string' ? searchStr : ''}&amp;page=${currentPage}`, type: 'GET', beforeSend: function() { if (typeof posts != 'undefined') { $('.loader').show(); } } }) .done(function(data) { $('.loader').hide(); posts = $(data).find('#postsContainer').html(); if (typeof posts != 'undefined') { $('#postsContainer').append(posts); currentPage = currentPage + 1; if (currentPage &gt; maxPage) { $('#postsContainer').append('&lt;p class=&quot;text-center text-muted&quot;&gt;No more posts to load&lt;/p&gt;'); } } }); } })(jQuery); </code></pre> <p>In the <code>posts-lists.twig</code> view:</p> <pre><code>{% if posts %} {% if is_ajax_loading %} &lt;div id=&quot;postsContainer&quot; data-max-page=&quot;{{max_page}}&quot;&gt; {% endif %} {% for post in posts %} &lt;div class=&quot;post-preview&quot;&gt; &lt;a href=&quot;{{base_url}}{{post.slug}}&quot;&gt; &lt;h2 class=&quot;post-title&quot;&gt;{{post.title}}&lt;/h2&gt; &lt;h3 class=&quot;post-subtitle&quot;&gt;{{post.description}}&lt;/h3&gt; &lt;/a&gt; &lt;p class=&quot;post-meta&quot;&gt; Posted {% if category_name is null %}in &lt;a href=&quot;{{base_url}}categories/posts/{{post.cat_id}}&quot; title=&quot;All posts in {{post.post_category}}&quot;&gt;{{post.post_category}}&lt;/a&gt;,{% endif %} on {{post.created_at | date(&quot;M d, Y&quot;)}} &lt;/p&gt; &lt;/div&gt; &lt;hr class=&quot;posts-separator&quot;&gt; {% endfor %} {% if is_ajax_loading %} &lt;/div&gt; {% endif %} {% else %} {% if posts_author is not defined and expression is not defined %} &lt;p class=&quot;mt-0 text-muted text-center&quot;&gt;There are no posts {% if category_name is defined %} in this category {% endif %} yet.&lt;/p&gt; {% endif %} {% endif %} {% if is_ajax_loading %} &lt;div class=&quot;loader&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt; {% endif %} </code></pre> <p>My main concerns are security and code redundancy.</p> <h4>Questions:</h4> <ol> <li>Is the code DRY enough?</li> <li>Are there any security risks?</li> <li>Improvement opportunities?</li> </ol>
[]
[ { "body": "<h3>I will briefly mention a few things I see in you're snippets.</h3>\n<ol>\n<li>\n<blockquote>\n<p>Is the code DRY enough?</p>\n</blockquote>\n</li>\n</ol>\n<p>Given this line of code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>pageUrl = $(location).attr('href'),\n pageBaseUrl = pageUrl.split('?')[0],\n searchStr = pageUrl.split('?')[1];\n</code></pre>\n<p>You would be better served using the <a href=\"https://www.php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\">parse_url</a> function</p>\n<pre class=\"lang-php prettyprint-override\"><code>parse_url(string $url, int $component = -1): mixed \n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$url = 'http://www.example.com/news?q=string&amp;f=true&amp;id=1233&amp;sort=true';\n\n$values = parse_url($url);\n\n$host = explode('.',$values['host']);\n\necho $host[1];\n\n</code></pre>\n<p>SO <a href=\"https://stackoverflow.com/a/5257289/997457\">source</a></p>\n<p>as far as the templating language twig, that would be out of my familiarity.</p>\n<h2>I would also like focus on your second question because I feel it is the most important.</h2>\n<h4>Are there any security risks?</h4>\n<p>There are multiple Cross-site Scripting (XSS) vulnerabilities inherently in your code because it's in the code igniter code base. Here is a list of known vulnerabilities 'CVE' with <a href=\"https://www.cvedetails.com/vulnerability-list/vendor_id-6918/Codeigniter.html\" rel=\"nofollow noreferrer\">Code Igniter</a> itself.</p>\n<h4>Definition: Cross-site Scripting</h4>\n<blockquote>\n<p>Un-sanitized input from data from a remote resource flows into append, where it is used to dynamically construct the HTML page on client side. This may result in a DOM Based Cross-Site Scripting attack (DOMXSS).</p>\n</blockquote>\n<p>The good news and hopefully an answer to your 3rd question is that yes! there are solutions.</p>\n<p>My first step would be to use built in code analysis tools freely available from GitHub where your repository lives.</p>\n<p><a href=\"https://codeql.github.com/docs/codeql-overview/about-codeql/\" rel=\"nofollow noreferrer\">CodeQL</a> is the analysis engine built by GitHub to automate security checks, for developers and by security researchers to perform variant analysis.</p>\n<p>I will only mention that one by name because you posted your github link, but there are several.</p>\n<ul>\n<li>snyk</li>\n<li>sonarqube</li>\n<li>veracode</li>\n<li>blackduck</li>\n<li>Nessus (The US Govt choice before FEDRAMP)</li>\n</ul>\n<ol>\n<li>sanitize your inputs.</li>\n<li>Always be aware of your dependencies and the skeletons they have in their closets.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T22:37:05.590", "Id": "531225", "Score": "0", "body": "I don't see any mention of the status or fix date for those insecurities at https://www.cvedetails.com/vulnerability-list/vendor_id-6918/Codeigniter.html Is it just a list of all historical vulnerabilities and makes no attempt to show that issues that have been eliminated? Are all of those vulnerabilities current?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T13:44:16.983", "Id": "531259", "Score": "0", "body": "Thanks for your valuable contribution. I am very interested in improving the **Posts controller** too. I think it is not DRY enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T12:52:54.627", "Id": "531576", "Score": "0", "body": "“_You would be better served using the [parse_url](https://www.php.net/manual/en/function.parse-url.php) function_” Is the suggestion for the OP to use that PHP function to pass data to the JS code for use instead of splitting `pageUrl`?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T13:03:32.433", "Id": "269252", "ParentId": "269178", "Score": "2" } }, { "body": "<blockquote>\n<h3><em>1. Is the code DRY enough?</em></h3>\n</blockquote>\n<p>It could be less repetitive. The following lines appear in both <code>_initPagination()</code> and <code>byauthor()</code></p>\n<blockquote>\n<pre><code>if ($this-&gt;Static_model-&gt;get_static_data()['has_pager']) {\n $config['display_pages'] = FALSE;\n $config['first_link'] = FALSE;\n $config['last_link'] = FALSE;\n $config['prev_tag_open'] = '&lt;li class=&quot;prev&quot;&gt;';\n $config['prev_tag_close'] = '&lt;/li&gt;';\n $config['next_tag_open'] = '&lt;li class=&quot;next&quot;&gt;';\n $config['next_tag_close'] = '&lt;/li&gt;';\n}\nif (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] &lt; 1) {\n $_GET[$config['query_string_segment']] = 1;\n}\n</code></pre>\n</blockquote>\n<p>Those could be abstracted into a separate method that can be called in both places.</p>\n<p>Similarly the following lines appear in four places - in methods <code>index</code>, <code>byauthor()</code>, <code>search()</code>, <code>post()</code>:</p>\n<blockquote>\n<pre><code>$data = $this-&gt;Static_model-&gt;get_static_data();\n$data['base_url'] = base_url(&quot;/&quot;);\n$data['pages'] = $this-&gt;Pages_model-&gt;get_pages();\n$data['categories'] = $this-&gt;Categories_model-&gt;get_categories();\n</code></pre>\n</blockquote>\n<hr />\n<blockquote>\n<h3><em>2. Are there any security risks?</em></h3>\n</blockquote>\n<p>You stated <a href=\"https://codereview.stackexchange.com/questions/253064/a-contact-form-with-codeigniter-and-twig#comment499301_253218\">last year that you attempted to follow advice about CSRF protection and XSS filtering</a> but the AJAX forms won't work. Were you able to resolve that? perhaps It didn't work because the AJAX forms weren't submitting the CSRF tokens. The token could be included with the AJAX data, or else the URIs could be excluded from CSRF protection (see the end of the <a href=\"https://www.codeigniter.com/userguide3/libraries/security.html?highlight=csrf#cross-site-request-forgery-csrf\" rel=\"nofollow noreferrer\">CSRF protection in the documentation</a>).</p>\n<hr />\n<blockquote>\n<h3><em>3. Improvement opportunities?</em></h3>\n</blockquote>\n<p>As I mentioned two years ago in <a href=\"https://codereview.stackexchange.com/a/221876/120114\">my review of your <code>Posts</code> controller</a> the <code>Posts</code> controller (still) has a constructor that merely calls the parent controller. Unless there is a good reason (e.g. provide/override specific parameters) there is not really a point in defining the overriden constructor and it can be eliminated.</p>\n<p>Perhaps the constructor is overridden because <a href=\"https://codeigniter.com/userguide3/general/controllers.html#class-constructors\" rel=\"nofollow noreferrer\">the documentation</a> mentions them:</p>\n<blockquote>\n<p>Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can’t return a value, but they can do some default work.</p>\n</blockquote>\n<p>However in the Posts constructor no default values are set and no default process is run when the class is instantiated, so the override can be removed.</p>\n<hr />\n<p>In the <code>_initPagination()</code> method the single-use variables - i.e. <code>$limit</code> and <code>$offset</code> - can be eliminated:</p>\n<pre><code>return [\n 'limit' =&gt; $config['per_page'],\n 'offset' =&gt; ($this-&gt;input-&gt;get($config['query_string_segment']) - 1) * $limit\n];\n</code></pre>\n<p>Note the <a href=\"https://www.php.net/manual/ro/migration54.new-features.php\" rel=\"nofollow noreferrer\">shorter array syntax</a> is used, presuming PHP 5.4+ is used - hopefully it is 7.3 or newer <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">for the sake of support</a>.</p>\n<hr />\n<p>In the Javascript code:</p>\n<blockquote>\n<pre><code>pageBaseUrl = pageUrl.split('?')[0],\nsearchStr = pageUrl.split('?')[1];\n</code></pre>\n</blockquote>\n<p>The string is being split twice, which isn’t as bad as splitting it many times but it could be done with a single split- e.g.</p>\n<pre><code>const [pageBaseUrl, searchStr] = pageUrl.split('?');\n</code></pre>\n<p>Or instead of parsing it manually, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL\" rel=\"nofollow noreferrer\">URL</a> interface could be used - including modifying the query string with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\">URLSearchParams</a> <code>get</code> method on the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams\" rel=\"nofollow noreferrer\"><code>URL.searchParams</code></a> property and the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/href\" rel=\"nofollow noreferrer\"><code>href</code> property</a> (or the ``toString()`](<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/toString\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/URL/toString</a>) method).</p>\n<p>As I mentioned <a href=\"https://codereview.stackexchange.com/a/261601/120114\">in this review</a> the AJAX method (i.e. <code>type</code> parameter) can be eliminated by using a shorthand method - i.e. <a href=\"https://api.jquery.com/jQuery.get/\" rel=\"nofollow noreferrer\"><code>$.get()</code></a>.</p>\n<p>And the incrementing of the page number can be simplified from:</p>\n<blockquote>\n<pre><code>currentPage = currentPage + 1;\n</code></pre>\n</blockquote>\n<p>To</p>\n<pre><code>currentPage++;\n</code></pre>\n<p>In fact it can be changed to a prefix increment in the conditional:</p>\n<pre><code> if (++currentPage &gt; maxPage) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T12:34:11.883", "Id": "531647", "Score": "0", "body": "https://codeigniter.com/userguide3/general/controllers.html#:~:text=If%20you%20intend%20to%20use,line%20of%20code%20in%20it%3A&text=The%20reason%20this%20line%20is,need%20to%20manually%20call%20it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T05:55:19.977", "Id": "269409", "ParentId": "269178", "Score": "1" } } ]
{ "AcceptedAnswerId": "269409", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T10:04:58.777", "Id": "269178", "Score": "3", "Tags": [ "php", "jquery", "ecmascript-6", "ajax", "codeigniter" ], "Title": "PHP blogging application with AJAX loading" }
269178
<p><strong>Problem description</strong></p> <p>As the title indicates, I want to be able to write to and read from a binary file safely, in the sense that I want to have full control of everything that might go wrong. Since I am somewhat unfamiliar with all the flags of the <code>ofstream</code> class and not sure how to use them, I wrote the following code as an exercise.</p> <p><strong>Code</strong></p> <pre><code>#include &lt;filesystem&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string_view&gt; using DType = int; using namespace std; namespace fs = filesystem; int main(int argc, char* argv[]) { /* Command line arguments */ if (argc == 1) { cout &lt;&lt; &quot;Usage: &lt;executable&gt; -f &lt;filename&gt;&quot; &lt;&lt; endl; exit(-1); } string_view filename {&quot;&quot;s}; for (int i=1; i&lt;argc; i++) { if ((argv[i] == &quot;-f&quot;s) &amp;&amp; (argv[++i] != nullptr)){ filename = argv[i]; } else { cout &lt;&lt; &quot;Provide a filename with -f &lt;filename&gt;.&quot; &lt;&lt; endl; exit(-1); } } /* Create file if it does not exist */ fs::path wdir = fs::current_path(); fs::path filepath = wdir/filename; fstream outfile; if (!fs::exists(filepath)) { auto touch = ofstream{filepath}; cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; created.&quot; &lt;&lt; endl; } else { cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; exists and cannot be created.&quot; &lt;&lt; endl; string yesOrNo = {&quot;&quot;s}; bool isFalse = 1; do { cout &lt;&lt; &quot;Do you wish to delete the file? Type yes/no and return.&quot; &lt;&lt; endl; cin &gt;&gt; yesOrNo; for_each(yesOrNo.begin(), yesOrNo.end(), [](char&amp; c){c = tolower(c);}); if (yesOrNo == &quot;yes&quot;s) { fs::remove(filepath); cout &lt;&lt; &quot;Old file &quot; &lt;&lt; filepath &lt;&lt; &quot; removed.&quot; &lt;&lt; endl; auto touch = ofstream{filepath}; cout &lt;&lt; &quot;New file &quot; &lt;&lt; filepath &lt;&lt; &quot; created.&quot; &lt;&lt; endl; isFalse = 0; } else if (yesOrNo == &quot;no&quot;s) { cout &lt;&lt; &quot;Program exiting.&quot; &lt;&lt; endl; exit(-1); } }while (isFalse); } /* Open file and write to it */ DType bufToWrite[10] = {0,1,2,3,4,5,6,7,8,9}; outfile.open(filepath, ios::in | ios::out | ios::binary); if (!outfile) { throw invalid_argument{&quot;Cannot open file: &quot;s + filepath.string()}; } outfile.write(reinterpret_cast&lt;char*&gt;(&amp;bufToWrite), sizeof(bufToWrite)); if(outfile.good()) { cout &lt;&lt; &quot;Writing to file &quot; &lt;&lt; filepath &lt;&lt; &quot; succeeded.&quot; &lt;&lt; endl; outfile.close(); } else { cout &lt;&lt; &quot;Writing to file &quot; &lt;&lt; filepath &lt;&lt; &quot; failed.&quot; &lt;&lt; endl; exit(-1); } /* Read the created file and store its content */ size_t bufSize = sizeof(bufToWrite)/sizeof(DType); DType toRestore[bufSize] = {}; ifstream infile(filepath, ios::binary); if(infile){ infile.read(reinterpret_cast&lt;char*&gt;(&amp;toRestore), sizeof(toRestore)); if(infile.good()) { cout &lt;&lt; &quot;Reading from file &quot; &lt;&lt; filepath &lt;&lt; &quot; succeeded.&quot; &lt;&lt; endl; infile.close(); } else { cout &lt;&lt; &quot;Reading from file &quot; &lt;&lt; filepath &lt;&lt; &quot; failed.&quot; &lt;&lt; endl; exit(-1); } } else{ cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; does not exist.&quot; &lt;&lt; endl; exit(-1); } /* Final print out */ cout &lt;&lt; &quot;Printing contents of &quot; &lt;&lt; filepath &lt;&lt; &quot; file:\n&quot;; for (DType elem : toRestore) cout &lt;&lt; elem &lt;&lt; &quot;\t&quot;; cout &lt;&lt; &quot;\nProgram terminated sucessfully. &quot; &lt;&lt; endl; return 0; } </code></pre> <p>What are the pitfalls that one should avoid and how to do so? For example when should I use <code>good()</code> and avoid the sticky bits? For example here <a href="https://stackoverflow.com/questions/28342660/error-handling-in-stdofstream-while-writing-data">https://stackoverflow.com/questions/28342660/error-handling-in-stdofstream-while-writing-data</a> it says that</p> <blockquote> <p>In principle, if there is a write error, badbit should be set. The error will only be set when the stream actually tries to write, however, so because of buffering, it may be set on a later write than when the error occurs, or even after close. And the bit is “sticky”, so once set, it will stay set.</p> </blockquote> <p>I understand my question is general, but If you can mention all the spots that can go wrong and how one should properly deal with them in C++17, I would be grateful. General notes concerning style etc. are most welcome.</p>
[]
[ { "body": "<h2><code>using namespace std;</code></h2>\n<p>Don't do <code>using namespace std;</code>. It can <a href=\"https://stackoverflow.com/a/1453605/673679\">lead to name collisions and other issues</a>.</p>\n<p>Typing out the full names (e.g. <code>std::cout</code>) avoids such issues, and is also clearer for readers.</p>\n<p><code>using namespace std::literals;</code> is reasonable inside a <code>.cpp</code> file, or a function.</p>\n<hr />\n<h2>string_view literals</h2>\n<pre><code>std::string_view filename{&quot;&quot;s};\n</code></pre>\n<p><code>s</code> is the <code>std::string</code> string literal, so this is unsafe (it creates a string view into a temporary string). We should use the <code>std::string_view</code> literal, <code>sv</code>, or simply leave the variable as a default initialized (empty) string-view.</p>\n<pre><code>argv[i] == &quot;-f&quot;s\n</code></pre>\n<p>Again, we should use &quot;sv&quot; - we don't need to actually construct a <code>std::string</code>, a <code>std::string_view</code> of a string literal (effectively a raw character array) is fine.</p>\n<hr />\n<h2>use functions</h2>\n<p>The <code>main</code> function is very long, and could be easily split into smaller parts that each do one specific task. This is important because it limits the scope of local variables and makes dependencies much more obvious.</p>\n<p>Basically where each of your comments are:</p>\n<pre><code>/* Command line arguments */\n/* Create file if it does not exist */\n/* Open file and write to it */\n...\n</code></pre>\n<p>These could be calls to functions with names like <code>read_command_line_args</code>.</p>\n<hr />\n<h2>simplifying file usage / user interation</h2>\n<pre><code>if (!fs::exists(filepath))\n{\n auto touch = std::ofstream{filepath};\n std::cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; created.&quot; &lt;&lt; std::endl;\n}\nelse\n{\n std::cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; exists and cannot be created.&quot; &lt;&lt; std::endl;\n std::string yesOrNo = {&quot;&quot;s};\n bool isFalse = 1;\n do\n {\n std::cout &lt;&lt; &quot;Do you wish to delete the file? Type yes/no and return.&quot; &lt;&lt; std::endl;\n std::cin &gt;&gt; yesOrNo;\n for_each(yesOrNo.begin(), yesOrNo.end(), [](char &amp;c) { c = (char)tolower(c); });\n if (yesOrNo == &quot;yes&quot;s)\n {\n fs::remove(filepath);\n std::cout &lt;&lt; &quot;Old file &quot; &lt;&lt; filepath &lt;&lt; &quot; removed.&quot; &lt;&lt; std::endl;\n auto touch = std::ofstream{filepath};\n std::cout &lt;&lt; &quot;New file &quot; &lt;&lt; filepath &lt;&lt; &quot; created.&quot; &lt;&lt; std::endl;\n isFalse = 0;\n }\n else if (yesOrNo == &quot;no&quot;s)\n {\n std::cout &lt;&lt; &quot;Program exiting.&quot; &lt;&lt; std::endl;\n std::exit(-1);\n }\n } while (isFalse);\n}\n</code></pre>\n<p>I don't think any of this is necessary. It makes the program more complicated for both the programmer and the user. We already made the user specify a command line argument, so the extra interaction isn't needed.</p>\n<p>We should either:</p>\n<ul>\n<li>require that the user specify a file that doesn't exist.</li>\n<li>assume that they know what they're doing and overwrite the specified file (i.e. use <code>std::ios::trunc</code> when opening the file for writing).</li>\n</ul>\n<p>Note that we don't need to &quot;touch&quot; a file to create it. We can just open it and start writing.</p>\n<hr />\n<h2>writing binary data</h2>\n<pre><code>outfile.write(reinterpret_cast&lt;char *&gt;(&amp;bufToWrite), sizeof(bufToWrite));\n</code></pre>\n<p>This is simple enough that it works when writing a file on a particular machine, and reading that file on the same machine. However, the binary file written isn't portable between computers because of several issues:</p>\n<ul>\n<li><p>Size of types - <code>int</code> is not a fixed size type - for example it could be 32 or 16 bits on different machines.</p>\n</li>\n<li><p>Numeric representation - different machines may represent signed numbers differently in memory.</p>\n</li>\n<li><p>Alignment - <a href=\"https://codesynthesis.com/%7Eboris/blog/2009/04/06/cxx-data-alignment-portability/\" rel=\"noreferrer\">different machines lay out combinations of simple types differently in memory</a>. This shouldn't affect an array of integers, but more complex types (e.g. an array of structs containing member variables of various different types) may have their parts located in differing locations in memory, and have padding in between the members.</p>\n</li>\n<li><p>Endianness - different machines may store bit representations of numbers in different directions.</p>\n</li>\n</ul>\n<p>Each of these issues needs to be solved before we can portably read a binary file written on a different machine. This can be done by:</p>\n<ul>\n<li><p>Write only <a href=\"https://en.cppreference.com/w/cpp/types/integer\" rel=\"noreferrer\">fixed size types</a> (e.g. <code>std::uint32_t</code> etc. from the <code>&lt;cstdint&gt;</code> header).</p>\n</li>\n<li><p>Cast fixed-size signed numbers to the same-sized unsigned type before writing.</p>\n</li>\n<li><p>Don't write aggregate types in bulk - write elements individually (unless you're certain you can get away with doing otherwise).</p>\n</li>\n<li><p>Convert types to a known endianness when writing. Each machine can then convert back to its own <a href=\"https://en.cppreference.com/w/cpp/types/endian\" rel=\"noreferrer\">system endianness</a> when reading the file.</p>\n</li>\n</ul>\n<hr />\n<h2>closing files after writing</h2>\n<pre><code>if (outfile.good())\n{\n std::cout &lt;&lt; &quot;Writing to file &quot; &lt;&lt; filepath &lt;&lt; &quot; succeeded.&quot; &lt;&lt; std::endl;\n outfile.close();\n}\n</code></pre>\n<p>Note that closing a file can also fail, so we should check for failure afterwards (files are buffered, so writing to disk might not happen until we close the file).</p>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:26:29.840", "Id": "531039", "Score": "2", "body": "Should I use good() after closing a file then? How can I make sure that the error, whatever might that be, will be identified at the moment of occurrence and not at a later time due to the intermediate buffer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:20:16.147", "Id": "531057", "Score": "3", "body": "@AngelosFr Yep. close() sets the failbit if something goes wrong, so you can use good() (see: https://en.cppreference.com/w/cpp/io/basic_ofstream/close ). write() errors set the badbit (and if the badbit is already set, the failbit). You can check after every write or once at the end, it's up to you. Note that you can also set the exceptions flags to get an exception if anything goes wrong: https://en.cppreference.com/w/cpp/io/basic_ios/exceptions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T02:24:29.823", "Id": "531100", "Score": "4", "body": "This is a good answer, but there is a *lot* of important stuff missing from it. Some of it is low level problems (use of `std::exit()`, throwing exceptions with no `catch`, etc.), and some of it is high-level design issues (the filesystem race conditions, all the bugs (command line parsing, yes/no logic) etc.)… but most notably, the questions asked were never really addressed (like when to use `good()` (never), when to use the sticky bits (a non-sequitur), etc.). I guess the questioner was satisfied with the answer, though, so… ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T07:21:46.570", "Id": "531104", "Score": "2", "body": "@indi I'm always happy to read your answers, so I'd love to see your take on things. I'm curious about what you mean by never using `good()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T10:11:43.790", "Id": "531114", "Score": "3", "body": "Oh, I didn’t mean that `good()` is *wrong*. It’s just that it’s pretty much never necessary. It’s almost always simpler to use the `bool` conversion to check the stream state after any operations. Like, the output here, with checking, is basically a one-liner: `if (output.write(...).flush()) /* write *probably* succeeded (not accounting for OS/hardware/other buffering) */`. And the input is basically: `if (infile.read(...)) /* read succeeded (though there might be other stuff in file) */`. Wrap those in scopes (or better, functions) to auto-close, and that’s all you need." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T07:02:11.343", "Id": "531177", "Score": "0", "body": "General question: Would you (if you were to write this) use iostreams at all, or rather the C standard library, or potentially immediate POSIX low-level I/O?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T09:56:48.217", "Id": "531185", "Score": "0", "body": "@Peter-ReinstateMonica I think it depends entirely on your needs. After you decide on your file format, and make the binary data portable, then it's just bytes - you can read / write it however you want. C++ iostreams work ok with `.read()` and `.write()`. I've written a minimal binary-file wrapper class around `FILE*` that uses `fread()` and `fwrite()`, so I might use that. Or you could use memory mapped files, or some other platform dependent method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T14:41:33.900", "Id": "531266", "Score": "0", "body": "@Peter-ReinstateMonica I’d use IOstreams unless there were a compelling reason not to, like if I needed to absolutely-certainly confirm writes succeeded (because that requires platform-specific stuff). Wanting unbuffered output is not a compelling reason, because you can do that with IOstreams." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T07:37:52.937", "Id": "531313", "Score": "0", "body": "@indi Thank you for your comments. It is true that from the answers that I got in the beginning I thought that my question was not conveyed properly. Even though I got more than enough feedback in general, the main take away regarding my original question is the following: after each operation that might produce an error, check the state of the buffer with ```if(file)```. However, I would be most interested in your answer, if you have time to spend on that of course." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T22:07:26.280", "Id": "531439", "Score": "1", "body": "@AngelosFr Sure, I could do one that’s focused specifically on IOstreams and error handling, because I think everything else is pretty well covered by the existing reviews. It’ll probably take a few days though; I usually don’t have time to write reviews except on the weekend." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:58:27.287", "Id": "269190", "ParentId": "269182", "Score": "11" } }, { "body": "<p>Also,</p>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n<p>Don't explicitly compare against <code>nullptr</code>. Use the truth value of the pointer (or smart pointer!): <code>if (argv[++i])</code>. In this case, modifying the index as part of the long expression that refers to it several times is confusing. I get the idea that this is boilerplate code anyway, so use a proper library instead of pasting it.</p>\n<hr />\n<pre><code>size_t bufSize = sizeof(bufToWrite)/sizeof(DType);\nDType toRestore[bufSize] = {};\n</code></pre>\n<p>First of all, that second line is not actually legal in C++. <code>gcc</code> accepts C-style VLA's as an extension <em>with no warning</em>, but incorporating this into the C++ standard was <strong>rejected</strong> for good reason.</p>\n<p>Don't use <code>sizeof</code> on an array. It is fragile and can easily accidently give you the size of a pointer instead. Here you just want the number of elements in the array: that's <code>std::size(bufToWrite)</code>.</p>\n<p>But really, you just want to duplicate the type of <code>bufToWrite</code> in both its array size and element type. So just write &quot;I want another variable the same as that one&quot; directly:</p>\n<p><code>decltype(bufToWrite) toRestore;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:23:53.523", "Id": "531037", "Score": "2", "body": "Which library can I use for example to handle the first part of the code with the command line arguments? Is there anything in the standard library?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:28:45.253", "Id": "531040", "Score": "3", "body": "@AngelosFr I use [Clara](https://github.com/catchorg/Clara/releases/tag/v1.1.5), and it's also part of `Catch2` which I use for writing unit tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T07:02:33.823", "Id": "531178", "Score": "1", "body": "General question: Would you (if you were to write this) use iostreams at all, or rather the C standard library, or potentially immediate POSIX low-level I/O?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T16:17:33.027", "Id": "531201", "Score": "1", "body": "@Peter-ReinstateMonica Good question! In the distant past, writing for 16-bit DOS, I used low-level OS wrappers (meant to look like the POSIX functions). On later machines, the benefits of the library's I/O buffering showed up. I think I'd look into the standard library's implementation and performance: does iostream add another wrapper around stdio, or do they both use a common back-end? I'd prefer the iostream because the `fstream` has a destructor and it knows about `filepath` rather than C-style strings. If performance became a bottleneck, I'd look into it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T16:21:24.623", "Id": "531202", "Score": "0", "body": "@Peter-ReinstateMonica What I really like is to know that the entire record to be parsed is in a contiguous memory buffer, so it can just advance the pointer rather than having to issue a `read` call at each little part. Loading the whole file into memory and then parsing that; or designing the data so the records have length prefix, I'd make the unpacking code take the memory block and not care about files at all. Then it's easy to change the layer that opens and reads (or receives from the network, or locates a resource, or...)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:07:36.383", "Id": "269191", "ParentId": "269182", "Score": "8" } }, { "body": "<ol>\n<li><p>Style:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>This is generally seen as poor practice because it imports all symbols from the std namespace in the main namespace, somewhat defeating the namespace isolation and highly increasing the risk of name collision. Explicitely importing only the used symbols is generally seen as better practice, even if it requires more typing:</p>\n<pre><code>using namespace std::string_literals;\nnamespace fs = std::filesystem;\nusing std::cout\n...\n</code></pre>\n<hr />\n<pre><code>if ((argv[i] == &quot;-f&quot;s)\n</code></pre>\n<p>Nothing is wrong here: <code>&quot;-f&quot;s</code> is indeed a <code>std::string</code> so the compiler should select the string equality operator. But it could unsettle older reviewers which were used to the C language. Said differently, if everybody in your team is using that idiom, just keep on, if you are working on an opensource project, or expect older reviewers, you should add a comment.</p>\n<hr />\n<p>You sometimes test <code>if (stream)</code> and sometimes <code>if (steam.good())</code>. It is not an error but is useless because when used in boolean context, a stream is converted to true iif it is in good state. The idiomatic way is to consistently test <code>if (stream)</code>. If you want to reset a bad read condition you have to clear it with <code>stream.clear()</code></p>\n<hr />\n<p>You consistently use <code>endl</code> to write a newline on stdout. In fact using <code>endl</code> both adds the newline <strong>and</strong> flushes the output stream. It is probably not a problem here but it can prevent best performances when writing to a real file.</p>\n</li>\n<li><p>IO testing</p>\n<p>The loop asking whether an existing file should be removed fails to test all possible bad conditions:</p>\n<pre><code> do {\n cout &lt;&lt; &quot;Do you wish to delete the file? Type yes/no and return.&quot; &lt;&lt; endl;\n cin &gt;&gt; yesOrNo; // what on read error?\n ...\n }while (isFalse);\n</code></pre>\n<p>If <code>cin</code> finds an error (whatever the reason) you will enter an endless loop because <code>yesOrNo</code> will not be updated and will never get a yes or no value</p>\n</li>\n<li><p>File system handling</p>\n<p>If the file already exists, you remove it and try do create it again. Write access to a file and permission to remove and create it are different permissions (for example in a plain Unix-like filesystem, write access to a file is the <code>w</code> permission on the file, removing and creating it requires <code>w</code> permission on the directory). If you know that it cannot be a problem in your use case, just move on, but you must be aware of it.</p>\n<p>When writing to the file, you use <code>ios::in | ios::out</code>, while you never read from that stream.</p>\n</li>\n<li><p>Variable Length Array in C++</p>\n<p>You use</p>\n<pre><code> size_t bufSize = sizeof(bufToWrite)/sizeof(DType);\n DType toRestore[bufSize] = {};\n</code></pre>\n<p>unless you declare <code>bufsize</code> to be <code>constexpr</code> it is a normal variable and not a constant, so <code>toRestore</code> is a VLA. Both gcc and clang do allow VLA as documented extensions, but the standard does not, and there are good reasons for that. Just declare <code>busSize</code> to be <code>constexpr</code></p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:33:15.790", "Id": "531042", "Score": "3", "body": "re \"nothing wrong here\" for `(argv[i] == \"-f\"s)`: it's legal and does what is expected, but it's inefficient to construct a string just to do the comparison. It should be written `\"-f\"sv`, as in other places where the temporary string is actually wrong. I actually advocate using sv literals for comparing against zstrings, as a replacement for `strcmp`. There's so much more for \"older reviews\" to be unsettled about and I'm not pandering to them!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:36:17.987", "Id": "531043", "Score": "2", "body": "@JDługosz: I was trying to bring my help and recieved yours :-) Thank you, even old dinosaurs like to learn..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:37:53.907", "Id": "531044", "Score": "2", "body": "So is the if(file) the one line to deal with everything? Either to check file existence or a bad state after an IO operation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:42:27.417", "Id": "531045", "Score": "2", "body": "@SergeBallesta thanks. I keep meaning to write a Code Project article on this, but never finish it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:43:26.613", "Id": "531047", "Score": "3", "body": "@AngelosFr read https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool It is defined as \"_Returns true if the stream has no errors and **is ready for I/O operations**._\" sounds like exactly what you need to check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:49:35.507", "Id": "531050", "Score": "0", "body": "@SergeBallesta re Dinosaur: My first C++-related publication was in 1989, so don't knock \"older reviewers\" or disparage dinosaurs!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T18:49:50.327", "Id": "531075", "Score": "1", "body": "Perhaps `\"-f\"sv.compare(argv[i]) == 0` could be used, I'm sure older reviewers won't mistake that for a pointer comparison. With C++20, `std::ranges::equals(argv[1], \"-f\")` could be an option. It's all very ugly though. If only there was a `main()` variant that gave you a `std::vector<std::string_view> args`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T20:44:21.750", "Id": "531082", "Score": "0", "body": "@G.Sliepen: My intend is definitely not to ask for C idioms (even if I had grown with `strcmp`...). I was just warning that this idiom may not be common to every reviewer and that a comment about C++ std::string literal (or string view literal) could help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T07:02:53.170", "Id": "531179", "Score": "0", "body": "General question: Would you (if you were to write this) use iostreams at all, or rather the C standard library, or potentially immediate POSIX low-level I/O? (Yes, I'm conducting a poll ;-) )." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:28:42.863", "Id": "269196", "ParentId": "269182", "Score": "7" } }, { "body": "<p>The other answers give good information as to what you're doing is wrong and specifically how to correct your issues, but they miss the larger picture:</p>\n<p><strong>Don't write binary data to files in C++</strong></p>\n<p>As @user673679 pointed out there are many possible portability issues with writing raw binary in C++ like endianness, memory layout, etc. Instead of trying to mitigate those issues like they suggested though, the correct thing to do in 99% of cases for robust, industry standard, code is to use a standardized network transcriber like <a href=\"https://developers.google.com/protocol-buffers/docs/cpptutorial\" rel=\"nofollow noreferrer\">Protobuf</a>.</p>\n<p>Google Protocol buffers, also known as Protobuf, is an industry standard language agnostic way of of writing rich data to binary. It will likely be a hair slower than direct bit writing so in maybe 1% of cases the way they suggested is necessary, but this will cover every possible edge case for transcription and most importantly be quite readable and portable.</p>\n<p>The main downside is having to maintain an external dependency which is much worse for C++ than basically any other language, but I think it's very much worth it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T16:44:37.167", "Id": "531148", "Score": "2", "body": "Protobuf turns a data structure into binary data. Then you have to write that binary data to a file..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T06:56:07.977", "Id": "531176", "Score": "1", "body": "@BenVoigt Well, with a bit of benevolence one would read the bold sentence as \"**Dont't write native typed data directly as binary**\", or something like that. Obviously, all data is binary at the end of the day ;-)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:40:32.997", "Id": "269213", "ParentId": "269182", "Score": "2" } }, { "body": "<p>Sorry it took so long—this is a <em>very</em> busy time of year for me (and it’s getting worse)—but as promised, here is an error-handling-focused review. This review is laser-focused <em>just</em> on the error-handling in the original code; other reviews do a fine job of covering other angles. The main focus is going to be error-handling with IOstreams, but I’ll brush on some general error-handling issues as well.</p>\n<p>So here we go.</p>\n\n<h1>General error-handling issues</h1>\n<p>I wish I could give you better news, but error-handling in C++ is a goddamn mess. Even just within the standard library, there are <em>at least</em> a half-dozen different error-handling paradigms in use:</p>\n<ul>\n<li>Return status codes, e.g. <code>printf()</code>.</li>\n<li>Special error values embedded in return. This is different from the previous in that if you are not interested in error handling, you can simple ignore the return value of <code>printf()</code>… but in <em>this</em> case, the return value is actually important—it’s what you want—but special values indicate failue. e.g. <code>malloc()</code> (<code>0</code> indicates failure).</li>\n<li>Status codes as part of returned structures, e.g. <code>from_chars()</code>.</li>\n<li>Global status variables, e.g. <code>errno</code>. This also includes sorta-global status variables, like thread local or function static variables (like <code>strtok()</code>).</li>\n<li>“Out” parameters, either passed by pointer or reference, e.g. the <code>&lt;filesystem&gt;</code> functions that take <code>error_code&amp;</code> args.</li>\n<li>Exceptions, obviously. Numerous examples.</li>\n<li><code>&lt;system_error&gt;</code>, e.g. the <code>&lt;filesystem&gt;</code> functions that <em>don’t</em> take <code>error_code&amp;</code> args.</li>\n<li>… and probably more.</li>\n</ul>\n<p>Error handling is such a raging dumpster fire in C++, that there are <em>numerous</em> new solutions being developed—this is a <em>hot</em> topic of research. The most interesting are perhaps:</p>\n<ul>\n<li><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0709r4.pdf\" rel=\"nofollow noreferrer\">Zero-overhead deterministic exceptions</a>, a.k.a. <code>std::error</code>, a.k.a. “Herbceptions”, by Herb Sutter.</li>\n<li><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html\" rel=\"nofollow noreferrer\"><code>std::expected</code></a>, currently by Vicente Botet and J.F. Bastien.</li>\n<li><a href=\"https://github.com/ned14/outcome\" rel=\"nofollow noreferrer\"><code>outcome</code></a>, by Niall Douglas.</li>\n<li><a href=\"https://github.com/ned14/status-code\" rel=\"nofollow noreferrer\"><code>std::status_code</code> or <code>&lt;system_error2&gt;</code></a>, by Niall Douglas.</li>\n</ul>\n<p>The big hold-up on these things is that there are some really <em>incredible</em> features coming in C++23 and beyond that would be game-changers for implementing these, so they’re on hold until those other features get implemented. As just one example: pattern matching. If we get pattern matching, it would be nice if error-handling integrated well with it.</p>\n<p>And for all that bad news, it gets even worse: IOstreams is the second-worst part of the standard library, when it comes to error-handling. (The dishonour of being the worst part of the standard library, when it comes to error-handling, is undoubtedly <code>&lt;filesystem&gt;</code>.)</p>\n<p>I know that makes IOstreams sound shitty, and I admit I frequently dump on it… <em>very</em> frequently… but the truth is, IOstreams is pretty incredible. I noticed @Peter-ReinstateMonica doing a survey about whether one would use IOstreams for your program’s purpose, or the C stdio library, or platform-specific calls, and it struck me as an amusing question, because there is only one really correct answer: IOstreams. I can’t even fathom why someone would purposefully <em>choose</em> to use stdio when they have other options; stdio is just irreparably broken in so many ways (it’s utterly impossible to use safely in multi-threaded code, for example). And platform-specific calls are… well… platform-specific; by contrast, with IOstreams, the code can theoretically work on <em>any</em> platform, <em>and</em> can transparently work with <em>any</em> kind of I/O: in-memory I/O, file I/O, network I/O, and so on. Unless you were just slapping a quickie program together—in which case, sure, maybe using platform-specific I/O will be simple and efficient—there really is no other sensible choice (well, <em>maybe</em> there are third-party C++ I/O libraries one might consider).</p>\n<p>So IOstreams is not <em>perfect</em>… it’s got <em>piles</em> of problems… but it <em>is</em> very, very good. And it should be your default choice for <em>all</em> I/O in C++.</p>\n<p>Nevertheless, by the standards of high-quality, modern C++, some of what follows is going to be… inelegant. Just keep that in mind.</p>\n<h2>You <em>must</em> catch exceptions</h2>\n<p>Exceptions were added very late in the original C++ standardization process, and at the time were poorly understood… it wasn’t until a couple years later that Dave Abrahams formalized exception safety. People were <em>terrified</em> of exceptions at first, and some still are. There is a <em>lot</em> of misinformation out there about exceptions.</p>\n<p>Because of that, there is a very dangerous hole in the specification of exceptions in C++.</p>\n<p>If exceptions are thrown and caught normally, there are no problems; everything works predictably. (Exceptions are non-deterministic in terms of <em>complexity</em>—that is, how long they’ll take—but are deterministic in terms of <em>behaviour</em>… you don’t necessarily know how long it will take for an exception to be completely handled, but you know for sure <em>exactly</em> what will happen when it does, including everything that happens along the way.)</p>\n<p>The problem is what happens if an exception is thrown <em>but never caught</em>.</p>\n<p>To illustrate the problem (<a href=\"https://wandbox.org/permlink/ETQ1cl9v8DMpqE7b\" rel=\"nofollow noreferrer\">source here</a>):</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include &lt;iostream&gt;\n\nstruct foo\n{\n foo() { std::cout &lt;&lt; &quot;construct\\n&quot;; }\n ~foo() { std::cout &lt;&lt; &quot;destruct\\n&quot;; }\n};\n\nauto main() -&gt; int\n{\n auto f = foo{};\n\n throw 1;\n}\n</code></pre>\n<p>When run, <em>may</em> produce:</p>\n<pre class=\"lang-none prettyprint-override\"><code>construct\n</code></pre>\n<p>See the problem? The <code>foo</code> object is constructed… but never destroyed.</p>\n<p>When an exception is thrown but never caught, <code>std::terminate()</code> is called, and… and this is the important part… <em>the stack is not (necessarily) unwound</em>.</p>\n<p>When the stack is not unwound, destructors are not called. This is bad… this is <em>very</em> bad. Arguably, the single most important feature of C++—the <strong>THING</strong> that separates it from other languages—is its deterministic destructors. I’ve seen it claimed that the most important line of code in C++ is “<code>}</code>”, because that is what triggers destructors. Destructors release and clean up resources, which means that if they’re not run, you will leak those resources, and a lot of clueless people will shrug and say, “so what; if the program is ending anyway, it’s fine to leak resources, because the OS will clean them all up anyway.” That “thinking” is relatively harmless for things like memory, which, yes, if your program ends while still holding memory, the OS will reclaim it… but memory is not the only resource C++ classes manage. Destructors are also used to commit or roll back database transactions, they’re used to send shut down sequences to external hardware, and so much more that is outside of the scope of the OS. If you fail to release these resources, you can lock up external hardware, you can leave online databases in indeterminate state, and who knows what else.</p>\n<p>So failing to run destructors is very, <em>very</em> bad, and you must do <em>everything</em> in your power to ensure that destructors are run, <em>even when your program is crashing</em>.</p>\n<p>(Obviously there are exceptional cases where priorities are different. For example, if your code is control software for a self-driving car, you want it to crash <em><strong>FAST</strong></em>, and restart just as fast. But that is <em>not</em> the general case, obviously.)</p>\n<p>So, whether you explicitly throw exceptions (as you do with <code>throw invalid_argument{&quot;Cannot open file: &quot;s + filepath.string()};</code>) or not (because you must always be exception safe), you should defend against them going uncaught. You can’t do much about exceptions thrown from static objects… but you shouldn’t really be doing anything complicated or dangerous in static objects anyway. But you <em>can</em> do something to prevent exceptions escaping <code>main()</code>. You can do something like this:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>auto main() -&gt; int\n{\n try\n {\n // your whole program goes here\n }\n catch (...)\n {\n }\n}\n</code></pre>\n<p>This is the bare minimum you should do.</p>\n<p>To improve this, you could return <code>EXIT_FAILURE</code> in the <code>catch</code> block. (Note: <em><strong>NOT</strong></em> <code>-1</code>. <code>-1</code> is not portable.)</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include &lt;cstdlib&gt;\n\nauto main() -&gt; int\n{\n try\n {\n // your whole program goes here\n }\n catch (...)\n {\n return EXIT_FAILURE;\n }\n}\n</code></pre>\n<p>Personally, I use what’s called a Lippincott function to print <em>some</em> information about the fact that there was an unhandled exception:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>// in a separate module/translation unit -----------------------\n\n// Note: Once written, this module can be copy-pasted into new\n// projects, and used without modification.\n\nnamespace indi {\n\nauto handle_uncaught_exception() -&gt; int\n{\n try\n {\n throw;\n }\n // you can catch custom exception types if you like\n //catch (indi::exception const&amp; x)\n //{\n //}\n catch (std::exception const&amp; x)\n {\n std::cerr &lt;&lt; &quot;unhandled exception: &quot; &lt;&lt; x.what() &lt;&lt; '\\n';\n\n // technically, writing to std::cerr, and some of this other\n // stuff, might throw... in which case, the exception will\n // escape, and std::terminate() will be called.\n //\n // but by this point, all of the non-static destructors will\n // already have been run, so this situation, while not *great*\n // is not all that serious.\n }\n catch (...)\n {\n std::cerr &lt;&lt; &quot;unhandled exception: &quot;\n &lt;&lt; &quot;&lt;unknown exception type&gt;&quot;\n &lt;&lt; '\\n';\n\n // perhaps:\n //std::cerr &lt;&lt; boost::current_exception_diagnostic_information();\n }\n\n return EXIT_FAILURE;\n}\n\n} // namespace indi\n\n// in the main source file -------------------------------------\n\nauto main() -&gt; int\n{\n try\n {\n // your whole program goes here\n }\n catch (...)\n {\n return indi::handle_uncaught_exception();\n }\n}\n</code></pre>\n<p>You should consider the above boilerplate to be standard code that you have to include for <em><strong>EVERY</strong></em> non-trivial project.</p>\n<h2>Never use <code>std::exit()</code></h2>\n<p>You use <code>std::exit()</code> numerous times in your code, often calling it as <code>exit(-1)</code> to exit immediately with a failure status.</p>\n<p>There are two problems here:</p>\n<ol>\n<li><code>-1</code> is not a portable exit status. There are only 3 portable exit statuses: <code>0</code> and <code>EXIT_SUCCESS</code> to indicate success (<code>EXIT_SUCCESS</code> may equal zero, or it may not), and <code>EXIT_FAILURE</code> to indicate failure. So you <em>should</em> be calling <code>exit(EXIT_FAILURE)</code>. Except…</li>\n<li><code>std::exit()</code> is a C library function. You should never, ever use it in a C++ program.</li>\n</ol>\n<p>What’s the problem with <code>std::exit()</code>? <a href=\"https://wandbox.org/permlink/jekxRpwHae1XT2x3\" rel=\"nofollow noreferrer\">Once again, it’s about destructors</a>:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n\nstruct foo\n{\n foo() { std::cout &lt;&lt; &quot;construct\\n&quot;; }\n ~foo() { std::cout &lt;&lt; &quot;destruct\\n&quot;; }\n};\n\nauto main() -&gt; int\n{\n auto f = foo{};\n\n std::exit(0);\n}\n</code></pre>\n<p>When run, <em>may</em> produce:</p>\n<pre class=\"lang-none prettyprint-override\"><code>construct\n</code></pre>\n<p><code>std::exit()</code> is <em>slightly</em> less dangerous than leaving an exception uncaught… but still very dangerous.</p>\n<p>So, now you have a program that calls <code>std::exit()</code> everywhere. How do you fix it?</p>\n<p>Well, as a transitional step, you could do something like this:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>// in a reusable module/translation unit -----------------------\n\nnamespace indi {\n\nstruct clean_exit_t\n{\n int status = 0;\n};\n\n[[noreturn]] auto clean_exit(int status) -&gt; void\n{\n throw clean_exit_t{status};\n}\n\n[[noreturn]] auto clean_exit() -&gt; void\n{\n clean_exit(0);\n}\n\n[[noreturn]] auto clean_fail() -&gt; void\n{\n clean_exit(EXIT_FAILURE);\n}\n\nauto handle_uncaught_exception() -&gt; int\n{\n try\n {\n throw;\n }\n catch (clean_exit_t x)\n {\n return x.status;\n }\n // ... and so on ...\n catch (...)\n {\n std::cerr &lt;&lt; &quot;unhandled exception:\\n&quot;\n &lt;&lt; boost::current_exception_diagnostic_information();\n }\n\n return EXIT_FAILURE;\n}\n\n} // namespace indi\n</code></pre>\n<p>And everywhere your program does:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (/*whatever*/)\n{\n cout &lt;&lt; &quot;...&quot; &lt;&lt; endl;\n exit(-1);\n}\n</code></pre>\n<p>Instead do:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (/*whatever*/)\n{\n std::cerr &lt;&lt; &quot;...\\n&quot;;\n indi::clean_fail();\n}\n</code></pre>\n<p>But this is just a temporary fix (actually, a bit of a hack, really). The <em>proper</em> solution is to use to purpose-specific exceptions, and to catch them, and report the error properly. For example, this is what just the first bit of your program might look like:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>auto main(int argc, char* argv[]) -&gt; int\n{\n try\n {\n try\n {\n if (argc == 1)\n throw no_filename_argument_provided{};\n\n // ... and so on ...\n }\n catch (no_filename_argument_provided const&amp;)\n {\n std::cerr &lt;&lt; &quot;Usage: &lt;executable&gt; -f &lt;filename&gt;\\n&quot;;\n\n return EXIT_FAILURE;\n }\n }\n catch (...)\n {\n return indi::handle_uncaught_exception();\n }\n}\n</code></pre>\n<p>You may find the nested <code>try</code> blocks ugly, and I don’t disagree. You <em>could</em> integrate the program-specific error handling in the <code>handle_uncaught_exception()</code> function… but then that function is no longer reusable for different programs. You could also try something “clever” like using a function <code>try</code> block for <code>main()</code>. In practice, because I use functions for all the “steps” of a program, I find that <code>main()</code> is so simple, the nested blocks aren’t such a big deal. For example, if I were writing your program, it might look like:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>// Another Lippincott function, this one for program-specific error handling.\nauto handle_error()\n{\n try\n {\n throw;\n }\n catch (no_filename_argument_provided const&amp;)\n {\n std::cerr &lt;&lt; &quot;Usage: &lt;executable&gt; -f &lt;filename&gt;\\n&quot;;\n }\n // and any other error handling you want to do\n\n return EXIT_FAILURE;\n // note: no catch (...)\n}\n\nauto main(int argc, char* argv[]) -&gt; int\n{\n try\n {\n try\n {\n // Read the command line arguments and/or any configuration\n // files.\n //\n // handle_program_options() returns a struct or a map with\n // all the program options.\n auto const options = handle_program_options(argc, argv);\n auto const&amp; filepath = options.filepath; // just for convenience\n\n // Create the sample data, and write it to the file.\n auto const original_data = create_data();\n write_data(filepath, original_data);\n\n // Read the data back from the file.\n auto const data = read_data(filepath);\n\n // Print the data.\n std::cout &lt;&lt; &quot;Printing contents of &quot; &lt;&lt; filepath &lt;&lt; &quot; file:\\n&quot;;\n print_data(data);\n\n std::cout &lt;&lt; &quot;\\nProgram terminated sucessfully. \\n&quot;;\n }\n catch (...)\n {\n return handle_error();\n }\n }\n catch (...)\n {\n return indi::handle_uncaught_exception();\n }\n}\n</code></pre>\n<h2>TOCTOU</h2>\n<p>There is another general error-handling issue throughout your program, but this one is a higher-level, design-level issue.</p>\n<p>Take a look at this bit of your program:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code> if (!fs::exists(filepath)) {\n auto touch = ofstream{filepath};\n cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; created.&quot; &lt;&lt; endl;\n }\n</code></pre>\n<p>Now, suppose that the file path doesn’t actually exist. You call <code>fs::exists(filepath)</code>, it returns <code>false</code>, then it gets negated, and the test passes, and you enter the block.</p>\n<p>STOP! Right at that moment, the OS happens to suspend your process, and give another process some CPU time. This other process happens to create a new file… exactly with the same path you just tested. And then the OS scheduler suspends <em>that</em> process, and returns control to <em>your</em> process.</p>\n<p>What happens now?</p>\n<p></p>\n<p>This is UB. Literally anything could happen.</p>\n<p>But let’s consider some realistic probabilities.</p>\n<ol>\n<li>The other process created the file path and filled it with critical info, and managed to do all that and close the file before it lost its time slice. Now <em>your</em> process, executes <code>auto touch = ofstream{filepath};</code>, thinking it’s creating the file… but instead opens the existing file, and truncates it… destroying that critical info. When the other process or something else goes looking for that critical info… again, who knows… could be a simple crash, could be something catastrophic.\n<ul>\n<li>Bonus confusion: The other process did the same thing you did: created the file, assumed it had rights to it, then closed it… then <em>your</em> process opens it, writes its integers, and closes it… then the <em>other</em> process <em>re</em>-opens it, writes its data, and closes it… then <em>your</em> process tries to read what it assumes are the integers it just wrote and… WTF?</li>\n</ul>\n</li>\n<li>The other process never got around to closing that file before it lost its time slice—or maybe it did, but it had created it with restrictive permissions that your process doesn’t have. Either way, your process tries to open it… fails… but you never check… so it prints “File … created”. Later, you try to re-open it, and get the “cannot open” error. What the―? You can’t open the file you just created?</li>\n</ol>\n<p>This is a general category of bugs known as <a href=\"https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use\" rel=\"nofollow noreferrer\">“time of check/time of use” (TOCTOU) errors</a>. It’s a race condition that pops up whenever you “check-then-do”, and outside forces can invalidate the check in the “then” part. Filesystem I/O is particularly vulnerable to this class of error, because you’re almost always sharing the filesystem with dozens or hundreds of other processes.</p>\n<p>IOstreams is actually designed with TOCTOU in mind (all half-decent I/O libraries are, by necessity). Proper usage patterns for IOstreams are always “do-then-check”… not “check-then-do”. For example, this is bad:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (not in.eof())\n{\n in &gt;&gt; value;\n // use value\n}\nelse\n{\n // no more values\n}\n</code></pre>\n<p>That is “check-then-do”. This is the proper “do-then-check” pattern:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (in &gt;&gt; value)\n{\n // use value\n}\nelse if (in.eof())\n{\n // no more values\n}\n</code></pre>\n<p>So let’s rethink the way you’re creating your output file. You want to create the file <em>if and only if</em> it doesn’t exist, and write to it. If it does exist, you want to give the user the option to overwrite it, and if they say yes, open it for writing <em>even if it does exist</em>, stomping over its contents if any. I’ve formulated it this way so that all the I/O operations are done <em>without</em> checking. The code might <em>hypothetically</em> look like this (preserving all the messages of your existing code):</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>// First try to open exclusively.\nauto out = xxx::ofstream{filepath, xxx::ios_base::binary | xxx::ios_base::exclusive};\nif (not out.error_code)\n{\n std::cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; created.\\n&quot;;\n}\nelse\n{\n // Failed to open for some reason.\n\n // If the reason is that the file exists...\n if (out.error_code == std::make_error_condition(std::errc::file_exists))\n {\n std::cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; exists and cannot be created.\\n&quot;;\n\n if (confirm(&quot;Do you wish to delete the file?&quot;))\n {\n out = xxx::ofstream{filepath, xxx::ios_base::binary};\n if (not out.error_code())\n {\n std::cout &lt;&lt; &quot;Old file &quot; &lt;&lt; filepath &lt;&lt; &quot; removed.\\n&quot;;\n std::cout &lt;&lt; &quot;New file &quot; &lt;&lt; filepath &lt;&lt; &quot; created.\\n&quot;;\n }\n }\n else\n {\n std::cout &lt;&lt; &quot;Program exiting.\\n&quot;;\n xxx::clean_fail();\n }\n }\n}\n\n// Check for any errors.\nif (out.error_code)\n throw std::system_error{out.error_code};\n\n// At this point, we can (try to) write to the file.\n</code></pre>\n<p>(As an aside, <code>invalid_argument</code> is not the correct error to throw when a file fails to open. This is an abuse of what <code>invalid_argument</code> means. There was (presumably) nothing wrong with the file path argument; it was a perfectly cromulent file path (if it wasn’t then the <code>std::filesystem::path</code> constructor should have failed)… it just couldn’t be opened for one reason or another. If there were something wrong with the argument, it would <em>never</em> be right… but if you can pass the same argument at different times, and it might open or might not, then the problem is not the argument, it’s something else.)</p>\n<p>Unfortunately, the above is not possible with <code>std::ofstream</code>. There are two issues here:</p>\n<ol>\n<li>There is no exclusive flag… <em>yet</em>. I’m pretty sure it’s inevitable that it will be added; the committee just hasn’t got around to it. This is a major problem for this pattern.</li>\n<li>There no error code member to suss out the actual cause of the error. This is a less-major problem, because it primarily affects the quality of the error messages. As it stands in IOstreams, you can know whether something failed or not… but if it failed, you can’t find out <em>why</em> it failed.</li>\n</ol>\n<p>For an example of where issue 2 pops up, consider this bit of your code:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code> ifstream infile(filepath, ios::binary);\n if(infile){\n // ...\n }\n else{\n cout &lt;&lt; &quot;File &quot; &lt;&lt; filepath &lt;&lt; &quot; does not exist.&quot; &lt;&lt; endl;\n // ...\n }\n</code></pre>\n<p>You <em>assume</em> the file doesn’t exist… but you have no way of knowing. All you know is you tried to open it, and that failed. Maybe it doesn’t exist. Maybe it does, but you don’t have permission to read it. Maybe it exists, and you have permission, but after you opened it, the stream failed to allocate something.</p>\n<p>This is a general quality issue with standard IOstreams. You can’t give good error messages. You either have to accept that, and only give very literal, though very unhelpful messages (“failed to open file”… but <em>why</em>?!)… or you have to go beyond the standard streams.</p>\n<p>And because of issue 1, you pretty much <em>have</em> to go beyond the standard streams… at least until the committee adds an exclusive flag.</p>\n<p>So, yeah, in practice, for any non-trivial file I/O, you pretty much have to write your own file streams (technically, you have to write your own file <em>buffer</em>, but… yeah). Yes, that massively sucks. But that’s (one of the reasons) why people hate IOstreams. (And why there is work afoot to make a modern replacement.)</p>\n<p>From this point on, I’m going to assume you are not going to try to create the output file exclusively. In other words, no “file exists, replace?” stuff… the user gave a filename, so it’s their responsibility if something gets overwritten. I’m also going to assume you don’t care about quality error messages. If these assumptions are wrong, you will have to be writing your own streams (and/or buffers), which is way beyond the scope here.</p>\n<h1>IOstreams error handling</h1>\n<p>Okay, now we get to the IOstreams specific stuff. When dealing with IOstreams error handling there are a couple things to keep in mind.</p>\n<ul>\n<li><p>IOstreams is <em>archaic</em>. It not only predates the standard, it predates most of C++. It <em>technically</em> doesn’t predate C++ itself (C++ was renamed from “C with classes” about two years before IOstreams), but it predates the very first book (which was the unofficial standard for years), it was probably the very first C++ library written, and it predates just about everything that defines C++: templates, exceptions, and so on. Support for a lot of these things was retroactively grafted on to IOstreams… and it shows.</p>\n</li>\n<li><p>IOstreams is necessarily vague, in order to be portable (though, modern technologies like <code>&lt;system_error&gt;</code> do make it possible to be specific <em>and</em> portable). It doesn’t even assume a filesystem exists (and no, <code>fstream</code> <em>et al</em> do <em>not</em> require that a filesystem exists). This mostly comes up when trying to deal with errors. IOstreams will tell you that an error occurred… but they usually won’t tell you <em>which</em> error occurred.</p>\n</li>\n<li><p>IOstreams, like <em>all</em> half-decent I/O libraries, expects you to use the “do-then-check” pattern… not “check-then-do”. As the saying goes, it is better to ask forgiveness than to ask permission. Your code already does this (other than the stuff I mentioned previously), which is good. But do keep the pattern in mind. If you want something from a stream, just ask for it… don’t ask to ask.</p>\n</li>\n<li><p>IOstreams <em>appears</em> to make exceptions optional. Don’t be fooled. Even if you don’t explicitly enable exceptions in a stream, you can still get exceptions. That means you have to write all your IOstreams code to handle <em>both</em> exceptions <em>and</em> status flags. That gets clunky and frustrating, but it’s what you gotta do.</p>\n</li>\n</ul>\n<h2>There are no “sticky” bits</h2>\n<p>IOstreams generally considers 2½ types of errors that map to bits in the <a href=\"https://en.cppreference.com/w/cpp/io/ios_base/iostate\" rel=\"nofollow noreferrer\"><code>std::ios_base::iostate</code></a> enumeration:</p>\n<ol>\n<li><p><code>failbit</code>: This is for “recoverable” errors… which really just means formatting errors. This is when the stream fails to convert the source data to the type you want (when reading) or fails to convert the data in your type to character data (when writing). The theory is that you could try to read some data as, for example, an <code>int</code>… and then if that fails, you can retry it as a string token. In reality… it’s not quite so simple, and it’s often impossible, or at least absurdly impractical, to recover from formatting errors. (To understand why, imagine the data is “123xyz”… you try to read as <code>int</code>, and successfully parse “123”, then fail… so you try to reparse as a string… but “123” has already been read, so you will only read “xyz”. To properly reparse “123xyz” as a string, you’d need to “putback” everything already read… which means you’d have to keep track of everything already read… which is pretty impractical, generally. I often do parsing using <em>two</em> (-ish) streams: one to read the entire “123xyz” token, and one to parse it. I <em>never</em> parse <code>cin</code> directly: I <code>getline()</code> into a string, and then try to parse that.)</p>\n</li>\n<li><p><code>badbit</code>: This is for “unrecoverable” errors, which generally means the stream itself is bad. Like the drive with the file you’re reading has been unplugged, or you were reading a network stream and the connection dropped, or whatever. This is considered “unrecoverable” because the only way to “fix” these errors is to give up, close the stream, and try to reopen it.</p>\n</li>\n</ol>\n<p>In practice, because retrying reading/writing operations is impractical, there’s usually no reason to distinguish between <code>fail</code> errors and <code>bad</code> errors. The exception is when you’re doing UI-like stuff with <code>std::cin</code>, because you want to distinguish between “user gave me garbage, but I’ll let them try again” (<code>failbit</code>) versus stuff like “the input pipe is broken” (<code>badbit</code>).</p>\n<p>The “third” fail state is <code>eofbit</code>… which is hard to call a distinct thing because it <em>always</em> comes hand-in-hand with <code>failbit</code>. However, it does deserve special attention, because there are some cases where you want to separate <code>eof</code> from <code>fail</code>:</p>\n<ol>\n<li>When you are reading an unknown number of “things”, you will eventually get a failure. If <code>eofbit</code> is set, that means you successfully reached the end of the “things”. Otherwise, you did <em>not</em> reach the end, but there is corrupt data.</li>\n<li>After you have read all the data you expect, and you want to make sure there isn’t any trailing garbage, you can try to read one more character. It <em>should</em> fail, and set <code>eofbit</code>. If it does <em>not</em> fail, or it fails but does not set <code>eofbit</code> (which should never happen), then you know there is trailing garbage.</li>\n</ol>\n<p>The latter case is relevant to your program: after you successfully read the data, you should check to make sure you read <em>all</em> the data:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (auto in = std::ifstream{filepath, std::ios_base::binary}; in)\n{\n auto buffer = std::array&lt;int, 10&gt;{};\n\n // others have explained why this is not correct, but whatever\n if (in.read(reinterpret_cast&lt;char*&gt;(buffer.data()), buffer.size() * CHAR_BIT))\n {\n std::cout &lt;&lt; &quot;Reading from file &quot; &lt;&lt; filepath &lt;&lt; &quot; succeeded.\\n&quot;;\n\n // we read the data... but did we read *all* the data?\n if (in.peek(); not in.eof())\n throw std::runtime_error{&quot;unexpected extra data in file&quot;};\n }\n else\n {\n throw std::runtime_error{&quot;Reading from file &quot; + filepath.string() + &quot; failed.&quot;};\n }\n}\nelse\n{\n throw std::runtime_error{&quot;File &quot; + filepath.string() + &quot; does not exist.&quot;};\n}\n</code></pre>\n<p>So, the title of this section is “there are no ‘sticky’ bits”. Let me clarify. When we talk about the “sticky” bits, we mean the <em><strong>FORMATTING</strong></em> bits… not the <em>status</em> bits. The reason is because formatting flags are <em>usually</em> ephemeral in, like, every other I/O library every written. IOstreams is very weird in that regard. For example, consider C’s stdio library:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>std::printf(&quot;%x&quot;, 42); // print an int formatted in hexadecimal\nstd::printf(&quot;%d&quot;, 42); // print an int (note, hex format is not &quot;sticky&quot;)\n</code></pre>\n<p>But with IOstreams:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>std::cout &lt;&lt; std::hex &lt;&lt; 42; // print an int formatted in hexadecimal\nstd::cout &lt;&lt; 42; // print an int (hex format is &quot;sticky&quot;!)\n</code></pre>\n<p>If you want to be pedantic, the status bits <em>are</em>, technically, “sticky”. But we (usually) never talk about them that way… because what else would they be? Consider what it would be like if the status bits weren’t “sticky”:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (std::cin &gt;&gt; x &gt;&gt; y &gt;&gt; z)\n // successfully read x, y, and, z!\n\n// ... or did we?\n//\n// what if there was an error reading x, but then when reading y, the\n// status bits were reset, and y was read successfully? you'd never know\n// there was an error. x would just have some default value; you'd never\n// know if that was what was actually read for x or not.\n</code></pre>\n<h2>You should (almost) never use <code>.good()</code></h2>\n<p>There are at least two ways to check for IOstream errors, the <code>bool</code> conversion, and <code>.good()</code>. The <em>only</em> difference is that <code>.good()</code> <em>also</em> checks <code>eofbit</code>. In other words:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>// these two expressions are *exactly* equivalent\ns.good()\n(s or s.eof())\n</code></pre>\n<p>So since <code>.good()</code> checks everything the <code>bool</code> conversion does… <em>and more</em>… doesn’t that mean it’s better? Doesn’t that mean it should be the default choice?</p>\n<p>No, but the reason why isn’t technical, it’s social.</p>\n<p>When you write code, you are obviously trying to communicate with the compiler, and get it to generate operations that do what you want. But you are <em>also</em> communicating with your peers. A lot of the time, there are multiple ways you can write your program that all mean the same thing to the compiler… but send very different messages about your intentions to other programmers.</p>\n<p>Now, in IOstreams, EOF <em>always</em> happens with failure. This is a consequence of the TOCTOU-proof design of IOstreams; you don’t get EOF until you actually try to read past the end of the file, at which point the read was obviously a failure. So you (almost) never need to check for <em>both</em> EOF <em>and</em> failure, making <code>.good()</code> redundant. You just need to check for what you actually care about: whether EOF <em>or</em> failure. And the thing you choose to check for reveals your intentions about the code.</p>\n<p>Consider the following code (which is a very stripped down version of your input section):</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (auto s = std::ifstream{path}; s)\n{\n if (s.read(/* ... */)) // or if (s.read(/* ... */; s) // &lt;-- 1\n {\n if (s.peek(); s.eof()) // &lt;-- 2\n // everything was okay!\n }\n}\n</code></pre>\n<p>At point 1, I use the <code>bool</code> conversion, which sends the message to readers that what I really care about is whether the read operation succeeds or not. I am not interested in whether the reason for the failure was that the file was empty or not. I want that data, and all I care about is whether I get it or not.</p>\n<p>At point 2, I ask for <code>.eof()</code>. This sends a very different message. It says that I am only interested in whether I was at the end of the file. If I’m not, I don’t care whether the peek succeeded or failed… either way, I wasn’t at the end of the file, which is what matters to me.</p>\n<p>I <em>could</em> rewrite the code above to use <code>.good()</code> for every test. It wouldn’t change the logic of the program in any way (well, except the last test would need to distinguish between EOF and failure). But if I did that, it would obscure my intentions in the code.</p>\n<p>You could basically replace every <code>bool</code> test of a stream with <code>.good()</code> in your code, or vice versa. It won’t change the <em>behaviour</em> of the code. But if you use <code>.good()</code> everywhere, you are implying to me that you care about EOF everywhere… even though you don’t. You would be miscommunicating your intentions… which is bad, because the whole point of using a high-level language is to communicate your intentions clearly.</p>\n<p>To put it another way, if I saw code where someone had used <code>.good()</code> everywhere, I won’t be thinking “this programmer is being cautious and defensive in their code”. I would be thinking “this programmer doesn’t know what they’re doing (or, at least, they’re not telling <em>me</em> what they actually mean)”.</p>\n<p>So does that mean <code>.good()</code> is completely pointless? Is there <em>never</em> a situation where you should use <code>.good()</code>?</p>\n<p>I can only think of one situation where <code>.good()</code> makes sense.</p>\n<p>Suppose you were doing an I/O operation that involved some very expensive stuff. For example, suppose you were doing an input operation that involved allocating a large buffer. If the stream is not in a good state for reading, you want to avoid that expensive allocation… you want to “fail fast”. In that situation, you could write:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>auto expensive_input_operation(std::istream&amp; in)\n{\n if (in.good())\n {\n // do expensive operation\n }\n else\n {\n // Why set the failbit? Because it is the right thing to do whenever\n // your input/output operation fails.\n //\n // The failbit *might* already be set... but it might not. For\n // example, the stream might actually be bad (badbit). Or someone\n // mucked with the status bits.\n //\n // Either way, all you care about in this function is that your job\n // was to do some input, but you couldn't... so, set the failbit.\n in.setstate(std::ios_base::failbit);\n }\n}\n</code></pre>\n<p>You can’t—or rather, <em>shouldn’t</em>—just use the <code>bool</code> conversion here, because it is conceivable that someone cleared <code>failbit</code> and <code>badbit</code>, but failed to clear <code>eofbit</code>. But even if there were no difference, the use of <code>.good()</code> here sends the message that you really just care if the stream is in a good state. If it’s not, you don’t care <em>why</em> not; you don’t care what <em>kind</em> of bad state it’s it. It’s either good, or you don’t care.</p>\n<p>This is the only situation I can think of where <code>.good()</code> makes sense: when you’ve just been handed a stream from god-knows-where, and you’re about to do some expensive work involving that stream, and you want to skip that expensive work if it’s doomed to be pointless anyway.</p>\n<p>(In practice, when I’ve done really complicated and expensive I/O functions, I’ve usually ended up using the stream buffer, rather than the stream. That means using the stream’s <code>sentry</code>, which makes <code>.good()</code> pointless in that case, too. But that’s getting really deep into the weeds.)</p>\n<h2>Putting it all together</h2>\n<p>So, <a href=\"https://wandbox.org/permlink/WA0gLkyqaTIiipmN\" rel=\"nofollow noreferrer\">here’s a link to an implementation of your program I put together</a>. It’s not <em>exactly</em> like your program, as mentioned in the comments—it doesn’t check for whether the output file exists first. But it’s as close as I could get with pure, standard IOstreams.</p>\n<p>I’m not claiming this is the “right” way to write this code. I just want to illustrate how it’s possible to almost completely remove error-handling from the happy path. (Except for the <code>handle_program_options()</code> function, which is a mess, because it’s just hacked together; it’s not realistic argument-handling code.) Like, when you’re reading the code to find out what it does, you start in <code>main()</code>, say: “Okay, step 1 (after command-line argument handling) is writing data (as implied by the function being named <code>write_data()</code>). How do we do that? Well, as it says in <code>write_data()</code>, if the output file opens, and if the serializing succeeds, then we print a success message.” While the code handles all errors, and prints human-readable messages for them all, all of that happens out-of-the-way from the main logic.</p>\n<p>And if writing the data were more complicated, the actual code wouldn’t get more bogged down with error-handling stuff. For example:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>auto write_data(std::filesystem::path const&amp; path, ...)\n{\n auto out = std::ofstream{path, std::ios_base::binary};\n if (not out)\n throw failed_to_open_output_file{path};\n\n if (not (/* output operation 1 */))\n throw failed_to_do_output_operation_1{};\n\n if (not (/* output operation 2 */))\n throw failed_to_do_output_operation_2{};\n\n // ... and so on ...\n\n if (not out.flush())\n throw failed_to_write_to_output_file{};\n\n // output file is automatically closed\n\n // Note that there is no portable way 100% absolutely guarantee that\n // the data was actually written to disk in a way that there is an\n // uncorrupted file on that disk that can be reopened later, and\n // will contain that exact data.\n //\n // But if the flush operation succeeds... that's *probably* good\n // enough. You don't really need to check that *closing* the file\n // succeeds. In most real-world programs, you usually don't close a\n // file then reopen it in the same program, so in practice, even if\n // a close fails, the file handle/id will not be &quot;stuck&quot; holding the\n // file open.\n}\n</code></pre>\n<p>Input code looks pretty much the same.</p>\n<p>Note that the pattern means always checking for <em>failure</em>… not success. Checking for success looks reasonable if you’re not using exceptions, because it puts the happy code first, and the error code is pushed out of the way in a later <code>else</code> block. But if you always check for success, you’d get:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>auto write_data(std::filesystem::path const&amp; path, ...)\n{\n auto out = std::ofstream{path, std::ios_base::binary};\n if (out)\n {\n if (/* output operation 1 */)\n {\n if (/* output operation 2 */)\n {\n if (/* ... and so on ... */)\n {\n if (out.flush())\n {\n // ...\n }\n else\n {\n throw failed_to_write_to_output_file{};\n }\n }\n else\n {\n // ... more errors ...\n }\n }\n else\n {\n throw failed_to_do_output_operation_2{};\n }\n }\n else\n {\n throw failed_to_do_output_operation_1{};\n }\n }\n else\n {\n throw failed_to_open_output_file{path};\n }\n\n // output file is automatically closed\n}\n</code></pre>\n<p>Which is ugly and unscalable.</p>\n<p>Even if you’re not using exceptions, you should still consider the test-for-failure-and-bail pattern over the test-for-success-with-an-else pattern. It should’t be a problem in C++, because you can (and should) use RAII to clean up intermediate stuff, so the fail blocks would just be <code>return fail_status;</code> rather than <code>throw whatever;</code>. (Of course, you only have to write <code>x; if (not x_succeeded) throw y;</code> if <code>x</code> doesn’t throw on failure itself… which it should. IOstreams is just too ancient to do that.)</p>\n<p>If you don’t care about getting specific error information, this could be even simpler:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>auto write_data(std::filesystem::path const&amp; path, ...)\n{\n auto out = std::ofstream{path, std::ios_base::binary};\n out.exceptions(std::ios_base::failbit | std::ios_base::badbit);\n\n /* output operation 1 */\n\n /* output operation 2 */\n\n // ... and so on ...\n\n out.flush();\n\n // output file is automatically closed\n}\n</code></pre>\n<p>Personally, I like to use the pattern where the file stream is restricted to a block, because it’s just nicer to keep the scope of resources as small as possible:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>if (auto stream = std::ifstream{path}; stream)\n{\n // stream object only exists within this block\n}\n// optional if you want to do something about failure:\n// else\n// {\n// // handle failure to open file\n// }\n\n// file is already closed and stream resources cleaned up by this point\n</code></pre>\n<h1>A small aside that is actually a HUGE rabbit hole</h1>\n<p>There is a big chunk in the middle of your code that looks like this:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code> string yesOrNo = {&quot;&quot;s};\n bool isFalse = 1;\n do {\n cout &lt;&lt; &quot;Do you wish to delete the file? Type yes/no and return.&quot; &lt;&lt; endl;\n cin &gt;&gt; yesOrNo;\n for_each(yesOrNo.begin(), yesOrNo.end(), [](char&amp; c){c = tolower(c);});\n if (yesOrNo == &quot;yes&quot;s) { \n fs::remove(filepath);\n cout &lt;&lt; &quot;Old file &quot; &lt;&lt; filepath &lt;&lt; &quot; removed.&quot; &lt;&lt; endl;\n auto touch = ofstream{filepath};\n cout &lt;&lt; &quot;New file &quot; &lt;&lt; filepath &lt;&lt; &quot; created.&quot; &lt;&lt; endl;\n isFalse = 0;\n }\n else if (yesOrNo == &quot;no&quot;s) {\n cout &lt;&lt; &quot;Program exiting.&quot; &lt;&lt; endl;\n exit(-1);\n } \n }while (isFalse);\n</code></pre>\n<p>Now if this were being refactored, all that yes/no code would be moved into its own function, so this might become something like this:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code> if (confirm(&quot;Do you wish to delete the file?&quot;))\n {\n fs::remove(filepath);\n std::cout &lt;&lt; &quot;Old file &quot; &lt;&lt; filepath &lt;&lt; &quot; removed.\\n&quot;;\n [[maybe_unused]] auto touch = std::ofstream{filepath};\n std::cout &lt;&lt; &quot;New file &quot; &lt;&lt; filepath &lt;&lt; &quot; created.\\n&quot;;\n }\n else\n {\n std::cout &lt;&lt; &quot;Program exiting.\\n&quot;;\n // exit program somehow\n }\n</code></pre>\n<p>That <code>confirm()</code> function seems innocuous. As a first pass, you might write it like this:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>auto confirm(std::ostream&amp; out, std::istream&amp; in, std::string_view const question) -&gt; bool\n{\n auto const is_yes = [](std::string_view s) { /* check for &quot;y&quot; or &quot;yes&quot;, case insensitively */ };\n auto const is_no = [](std::string_view s) { /* check for &quot;n&quot; or &quot;no&quot;, case insensitively */ };\n\n auto input = std::string{}; // moved outside the loop so we can reuse the memory\n while (true)\n {\n out &lt;&lt; question &lt;&lt; &quot; [yes/no]: &quot;;\n\n in &gt;&gt; input;\n\n if (is_yes(input))\n return true;\n else if (is_no(input))\n return false;\n else\n out &lt;&lt; &quot;Sorry, your response was not understood.\\n&quot;;\n }\n}\n\nauto confirm(std::string_view question) -&gt; bool\n{\n return confirm(std::cout, std::cin, question);\n}\n</code></pre>\n<p>This is almost exactly your existing code… the only real additions are that it emits a “sorry, don’t understand” message before re-asking for confirmation, and, of course, <code>std::cin</code> and <code>std::cout</code> aren’t (necessarily) hard-coded, so you can test the function.</p>\n<p>However, this function is buggy, and has no error checking whatsoever. Thing is, <em>fixing</em> it is such a massive undertaking, that requires going so deep into IOstreams quirks, that it would require a whole new answer almost the same size as this current answer… which is already huge. I’m actually seriously considering writing an article on how one might implement this kind of function—that’s how complicated fixing this would be.</p>\n<p>It’s always the “simple” things that are the most devilishly complicated.</p>\n<h1>Summary</h1>\n<p>So it’s kinda hard to summarize all the details of working with IOstreams error handling, but I’ll try.</p>\n<ol>\n<li><p>IOstreams makes exceptions “optional”, but you have to write all your code assuming they’ll fly anyway. That means that when you’ve been handed a stream (as a function parameter, for example), you either have to:</p>\n<p>a. manually enable exceptions in the stream so you know what you’re dealing with</p>\n<p>b. manually disable exceptions in the stream so you know what you’re dealing with… but safely disabling exceptions is tricky (and you’ll have be ready for exceptions regardless); or</p>\n<p>c. write your code in such a way that it handles both stream exceptions and status flags.</p>\n<p>In general, the practical options are either b or c.</p>\n</li>\n<li><p>IOstreams works under the “do-then-check” paradigm; don’t ask permission, just do what you want and then check the status flags to see if it worked. It usually won’t matter if the stream was already bad (unless you’re trying to narrow down <em>which</em> operation failed), so there’s generally no need to check for that in advance.</p>\n</li>\n<li><p>IOstreams recognizes 2½ types of failure:</p>\n<p>a. “Recoverable” failures: <code>failbit</code>. These are generally failures converting to/from character data, so parse/format failures. They’re called “recoverable” failures by the standard, but in practice, they’re usually impractical to recover from.</p>\n<p>b. “Non-recoverable” failures: <code>badbit</code>. This means the stream itself is broken. (For example, the drive you were reading/writing was unplugged.)</p>\n<p>c. End of file (EOF): <code>eofbit</code>. This is not really an <em>error</em>, per se, but it’s packed in with the failure status. It <em>always</em> comes in tandem with <code>failbit</code> (though it is possible to use <code>.setstate()</code> to set <code>eofbit</code> without setting <code>failbit</code>, if you are being nefarious), so it doesn’t really deserve to be considered on its own, except that sometimes you want to distinguish between failure due to corrupt data and failure due to no more data.</p>\n</li>\n<li><p>Avoid <code>.good()</code>, because it is too broad. Use either the stream’s <code>bool</code> conversion to check for failure (and <code>.bad()</code> or <code>.fail()</code> if you are interested in the specific <em>type</em> of failure, though that is very rare), and <code>.eof()</code> to check for EOF.</p>\n</li>\n<li><p>Realize that IOstreams, out of the box, is <em>very</em> limited. One way it is limited is in determining the exact cause of a problem—it will tell you when failure occurs, but it usually won’t tell you why.</p>\n<p>However, while it is limited out of the box, IOstreams is <em>astonishingly</em> flexible and extensible. It’s not <em>easy</em> to extend… but if you’re willing to do the work, it will pay off.</p>\n</li>\n<li><p>A lot of the time, it’s easier to separate input and parsing, particularly when using <code>cin</code> for input, because if parsing fails, <code>cin</code> goes into fail state… which is usually problematic. Instead, especially when dealing with line-oriented input, it usually makes more sense to just read in the whole line from <code>cin</code> into a string, and then parse <em>that</em> (either with <code>istringstream</code> or <code>from_chars()</code> or whatever). If the parsing goes bad, <code>cin</code> is still okay, so re-asking for the information is trivial.</p>\n</li>\n<li><p>If you want to confirm that writing succeeded, you should probably flush and then check. Flushing doesn’t <em>guarantee</em> that the output was successfully written to a file or whatever—that level of guarantee requires very low-level OS support. But it’s close enough.</p>\n<p>If you want to confirm that <em>reading</em> succeeded… well, it either did, or it didn’t. There’s no trick there.</p>\n</li>\n</ol>\n<p>That’s about all I can think of. Happy streaming!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T21:15:31.973", "Id": "533596", "Score": "0", "body": "I appreciate the time you invested and I couldn't accept your answer! Thanks for making my dull train ride interesting. I might have understood less than half of what you wrote, but there is lots of useful information for me to study in your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T20:01:24.743", "Id": "270254", "ParentId": "269182", "Score": "4" } } ]
{ "AcceptedAnswerId": "270254", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T12:32:53.967", "Id": "269182", "Score": "7", "Tags": [ "file", "error-handling", "c++17" ], "Title": "Robust program to write an array of certain data type to a binary file and read back from it (C++17)" }
269182
<p>This is a Python program that finds all possible ways a positive integer <code>num</code> can be expressed a sum of a number of integers between 1 and <code>lim</code> (including both ends).</p> <p>There is no limit on the number of integers, duplicates are allowed, same elements in different order is considered different.</p> <p>The output is a nested dictionary. Each key is a possible integer, each key in the nested dictionary is a possible integer in the series formed by the keys of the parent dictionaries in the previous levels that allows or makes the series sum to <code>num</code>.</p> <p>From any last level keys, through the keys in the parent dictionaries, to the first level parent key, the sum of such a series is always <code>num</code>.</p> <p><em><strong>The Code</strong></em></p> <pre class="lang-py prettyprint-override"><code>def partition_tree(num: int, lim: int) -&gt; dict: &quot;&quot;&quot;take a positive integer `num` and a positive integer `lim`, calculate all possible ways integer `num` can be expressed as, a summation of integers between 1 and `lim`, returns a tree&quot;&quot;&quot; d = dict() if any(not isinstance(i, int) for i in (num, lim)): raise TypeError('The parameters of this function should be `int`s') if any(i &lt;= 0 for i in (num, lim)): raise ValueError('The parameters should be both greater than 0') def worker(num: int, lim: int, dic: dict) -&gt; None: for i in range(1, lim+1): n = num - i if n: dic.setdefault(i, dict()) worker(n, lim, dic[i]) else: dic.update({i: 0}) break worker(num, lim, d) return d </code></pre> <p>Example output:</p> <pre class="lang-py prettyprint-override"><code>def partition_tree(num: int, lim: int) -&gt; dict: &quot;&quot;&quot;take a positive integer `num` and a positive integer `lim`, calculate all possible ways integer `num` can be expressed as, a summation of integers between 1 and `lim`, returns a tree&quot;&quot;&quot; d = dict() if any(not isinstance(i, int) for i in (num, lim)): raise TypeError('The parameters of this function should be `int`s') if any(i &lt;= 0 for i in (num, lim)): raise ValueError('The parameters should be both greater than 0') def worker(num: int, lim: int, dic: dict) -&gt; None: for i in range(1, lim+1): n = num - i if n: dic.setdefault(i, dict()) worker(n, lim, dic[i]) else: dic.update({i: 0}) break worker(num, lim, d) return d import json print(json.dumps(partition_tree(6, 3), indent=4)) </code></pre> <p>Output:</p> <pre><code>{ &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;3&quot;: { &quot;1&quot;: 0 } }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 }, &quot;3&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 } }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;3&quot;: { &quot;1&quot;: 0 } }, &quot;3&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 } } </code></pre> <p>I came up with this in under 2 minutes and made it work in one try. I made this for use in my project to generate pseudowords, more specifically to calculate all possible ways a given word length <code>num</code> can be achieved using chunks of lengths 1 to <code>lim</code>.</p> <p>How is the performance, coding style and memory consumption of my code (try <code>partition_tree(18, 6)</code>, something like this can be in common use)? How can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:35:36.710", "Id": "531060", "Score": "0", "body": "So just want to confirm. The nested dictionaries represent a tree, where each root-to-leaf path has a path sum equal to the target, namely `num`? For completeness, the root can be thought of as having a value of zero; all other nodes have non-zero values; node values don't have to be unique." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:46:06.523", "Id": "531063", "Score": "0", "body": "`worker(num, lim, dic)` populates the input dictionary `dic` with a tree whose root-to-leaf paths each sum to `num` s.t. each node in the tree has a value, `v`, `1 <= v <= lim`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T09:17:35.360", "Id": "531113", "Score": "0", "body": "Btw, do you actually need to have all the different partitions or just the number of possibles partitions?" } ]
[ { "body": "<p>In terms of code structure, here are my suggestions:</p>\n<ol>\n<li><p>Move <code>d = dict()</code> to after the argument checks, so that you only create the dictionary if the inputs are valid.</p>\n</li>\n<li><p>The <code>if</code>/<code>else</code> statements inside the <code>for</code> loop can be removed:</p>\n<pre><code> for i in range(1, lim+1):\n n = num - i\n if n:\n dic.setdefault(i, dict())\n worker(n, lim, dic[i])\n else:\n dic.update({i: 0})\n break\n</code></pre>\n<p>becomes:</p>\n<pre><code> for i in range(1, min(num, lim+1)):\n n = num - i\n dic.setdefault(i, dict())\n worker(n, lim, dic[i])\n if num &lt;= lim:\n dic.update({num: 0})\n</code></pre>\n</li>\n<li><p>Additionally, <code>dic.setdefault(i, dict())</code> has two modes. One for when the input key doesn't exist and one for when it does exists. I believe that within your code you're only ever hitting the latter mode (key doesn't exist), so <code>dic.setdefault(i, dict())</code> can be replaced with <code>dic[i] = dict()</code>.</p>\n</li>\n<li><p>Lastly, <code>dic.update({num: 0})</code> can be replaced with <code>dic[num] = 0</code> which would prevent you from creating the <code>{num: 0}</code> dictionary input to <code>dic.update</code>.</p>\n</li>\n</ol>\n<hr />\n<p>With all those changes, the code becomes:</p>\n<pre><code>def partition_tree(num: int, lim: int) -&gt; dict:\n &quot;&quot;&quot;take a positive integer `num` and a positive integer `lim`,\n calculate all possible ways integer `num` can be expressed as,\n a summation of integers between 1 and `lim`, returns a tree&quot;&quot;&quot;\n if any(not isinstance(i, int) for i in (num, lim)):\n raise TypeError('The parameters of this function should be `int`s')\n if any(i &lt;= 0 for i in (num, lim)):\n raise ValueError('The parameters should be both greater than 0')\n d = dict()\n def worker(num: int, lim: int, dic: dict) -&gt; None:\n for i in range(1, min(num, lim+1)):\n n = num - i\n dic[i] = dict()\n worker(n, lim, dic[i])\n if num &lt;= lim:\n dic[num] = 0\n worker(num, lim, d)\n return d\n</code></pre>\n<p>I ran this code on your input:</p>\n<pre><code>import json\nprint(json.dumps(partition_tree(6, 3), indent=4))\n</code></pre>\n<p>and it produced the same output as your code.</p>\n<hr />\n<p>In terms of code readability, I would suggest renaming <code>d</code> and <code>dic</code> to <code>tree</code> or something that indicates that the dictionaries represent a tree. I would also suggest renaming <code>num</code> to <code>target</code> or <code>target_sum</code> or just <code>sum_</code> -- if take this suggestion, also consider renaming <code>lim</code> to <code>max_num</code> or <code>max_</code>; <code>i</code> to <code>num</code>; and <code>n</code> to <code>new_target</code> or <code>new_target_sum</code> or <code>new_sum_</code> as appropriate. Also consider renaming <code>worker</code> to <code>dfs</code> since that's basically what it is doing and <code>dfs</code> is more descriptive than <code>worker</code>.</p>\n<p>With some of the readability changes, the code looks like this:</p>\n<pre><code>def partition_tree(target_sum: int, max_num: int) -&gt; dict:\n &quot;&quot;&quot;take a positive integer `num` and a positive integer `lim`,\n calculate all possible ways integer `num` can be expressed as,\n a summation of integers between 1 and `lim`, returns a tree&quot;&quot;&quot;\n if any(not isinstance(i, int) for i in (target_sum, max_num)):\n raise TypeError('The parameters of this function should be `int`s')\n if any(i &lt;= 0 for i in (target_sum, max_num)):\n raise ValueError('The parameters should be both greater than 0')\n tree = dict()\n def worker(target_sum: int, max_num: int, tree: dict) -&gt; None:\n for num in range(1, min(target_sum, max_num+1)):\n new_target_sum = target_sum - num\n tree[num] = dict()\n worker(new_target_sum, max_num, tree[num])\n if target_sum &lt;= max_num:\n tree[target_sum] = 0\n worker(target_sum, max_num, tree)\n return tree\n</code></pre>\n<p>This code still produces the same output as your original code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T16:35:02.693", "Id": "531064", "Score": "0", "body": "@@Xeнεi Ξэnвϵς, one more thing I noticed after writing my answer is that the dictionaries consist of sequential keys, starting from `1`. It should make sense as we iterate over `i` from `1` creating items with `i` as the keys. All that to say that it should be possible to use `list`s instead of `dict`s to represent this tree structure and in fact shouldn't be too hard to make the switch. In general, I would think `list` access and memory consumption is better than `dict`'s, so making that switch would probably improve things." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T16:08:17.093", "Id": "269200", "ParentId": "269185", "Score": "3" } }, { "body": "<h2>Recursion Improvements</h2>\n<p>In your problem, you end up calling the same recursive function multiple times. For example for <code>partition_tree(6, 3)</code> calls <code>worker(2, 3, d)</code> many many times albeit with updated dictionaries. This ends up costing you quite a bit of performance. You could avoid recomputing the same combinations by using memoization. Meaning you would save the outputs of your previous calls.</p>\n<p>Python's functools makes it incredibly easy to implement memoization with the <code>@lru_cache</code> decorator:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@lru_cache(maxsize=None)\ndef worker(*args):\n ...\n</code></pre>\n<p>If we're to save calls to the function, we can't be passing around dictionaries or prefixes. It has to be a pure function. And limit doesn't change within the partition tree and therefore it doesn't need to be passed around either. So let's remove those arguments and do the updating ourselves:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from functools import lru_cache\n\ndef partition_tree_lru(num: int, lim: int) -&gt; dict:\n &quot;&quot;&quot;take a positive integer `num` and a positive integer `lim`,\n calculate all possible ways integer `num` can be expressed as,\n a summation of integers between 1 and `lim`, returns a tree&quot;&quot;&quot;\n\n if any(not isinstance(i, int) for i in (num, lim)):\n raise TypeError('The parameters of this function should be `int`s')\n if any(i &lt;= 0 for i in (num, lim)):\n raise ValueError('The parameters should be both greater than 0')\n\n @lru_cache(maxsize=None)\n def worker(num: int) -&gt; dict:\n working_dict = {}\n for i in range(1, lim+1):\n n = num - i\n if n:\n working_dict[i]=worker(n)\n else:\n working_dict[i]=0\n break\n return working_dict\n \n return worker(num)\n</code></pre>\n<p>Improvement:</p>\n<pre><code>function [partition_tree_lru]((50, 50)) finished in 1 ms\nfunction [partition_tree]((20, 10)) finished in 570 ms\n</code></pre>\n<p><strong>Note</strong> : if 'you're going to be calling the <code>partition_tree</code> multiple times for different inputs it would be worth moving the worker function definition to the outer scope so that the cache persists between calls.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T08:40:36.760", "Id": "269218", "ParentId": "269185", "Score": "3" } } ]
{ "AcceptedAnswerId": "269218", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:17:26.833", "Id": "269185", "Score": "3", "Tags": [ "python", "python-3.x", "mathematics" ], "Title": "Python program to find all possible ways an integer num can be expressed as sum of integers between 1 and lim" }
269185
<p>I need to implement in Python the formula in the image. The set B is a set of real numbers <span class="math-container">\$-1 \le t \le 1\$</span>. Also, <span class="math-container">\$\mathbb{F}_2\$</span> is a set with the elements 0 and 1. <span class="math-container">\$y_i\$</span> is the <span class="math-container">\$i\$</span>-th element of <span class="math-container">\$y\$</span>. This formula is part of an iterative part of my program. The number of iterations is about 10K (over x) and n is 32. I tried a pre-computation approach. That is, I precomputed all <span class="math-container">\$f(y)\$</span> and put it in a numpy array, also I computed <span class="math-container">\$-1^{y_i}\$</span> and put it in a numpy array. See code below. But even with that, the computation takes approx 3s for the non-precomputation and n=24. When I tried to n=32 I get some memory issues due to the big arrays. My question is.</p> <p>Can you help me to improve this code in terms of memory and time, please?</p> <p><a href="https://i.stack.imgur.com/Azs2V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Azs2V.png" alt="enter image description here" /></a></p> <pre><code>import time from multiprocessing import Pool import multiprocessing import numpy as np import numexpr as ne import galois def precomputation_part(linear_layer_matrix, dim): y_shift = np.fromfunction(lambda i,j: (i)&gt;&gt;j, ((2**dim), dim), dtype=np.uint32) um=np.ones(((2**dim), dim), dtype=np.uint8); and_list = np.bitwise_and(y_shift,um, dtype=np.uint8) minus1_power_x_t = np.power(-1,and_list, dtype=np.int8) fy_matrix = evaluated_f_bool_matrix(and_list, np.array(linear_layer_matrix,dtype=np.uint8)) boolean_function_0 = fy_matrix[0] return boolean_function_0, minus1_power_x_t def evaluated_f_bool_matrix(and_components, input_matrix): t1 = time.time() mc = and_components.transpose() mal = input_matrix return np.matmul(mal,mc,dtype=np.uint8)%2 def create_ext_component_function(dim, boolean_function, input_lst, minus1_power_x_t): um_minus_minus1_power = ne.evaluate('1-minus1_power_x_t*input_lst') um_minus_minus1_power_prod = um_minus_minus1_power.prod(axis=1) boolean_function_times_prod = np.dot(boolean_function, um_minus_minus1_power_prod) return boolean_function_times_prod*(1/((2**dim)-1))-1 if __name__ == '__main__': dim = 24 f_matrix = [[0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1], [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1], [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0], [1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1], [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1], [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1]] boolean_function_0, minus1_power_x_t = precomputation_part(f_matrix, dim) ########The below two lines are executed several times x = np.array([i+1 for i in range(dim)], dtype=float) print(create_ext_component_function(dim, boolean_function_0, x, minus1_power_x_t)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:25:33.990", "Id": "531038", "Score": "0", "body": "A quick note: using `if __name__ == '__main__'` is great but you should consider putting all the chunk of code in a `main` function and then just call it under the if. (`if __name__ == '__main__': \nmain()`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:42:28.723", "Id": "531046", "Score": "0", "body": "2**24 * 24 is about 402 MB of memory for just one of your matrices. Is this intended? Creating this is, on its own, fairly slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:45:00.433", "Id": "531062", "Score": "2", "body": "I failed to understand the connection between the input matrix and the computed boolean function. Can you elaborate?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T17:45:08.123", "Id": "531073", "Score": "0", "body": "@vnp I'm not sure if you were asking me or the OP. I was referring to `um` which isn't (?) the input matrix; it's part of the precomputation routine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T18:38:45.730", "Id": "531074", "Score": "2", "body": "@Reinderien I was asking OP. It seems that keeping only those \\$y\\$s yielding true values of \\$f(y)\\$ would be beneficial. But as I said, I faild to understand the nature of \\$f\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T01:28:32.710", "Id": "531098", "Score": "0", "body": "What is the F set and the F_2 set and the F_2^n set?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T05:33:40.407", "Id": "531102", "Score": "0", "body": "F_2 set with elements 0 and 1. F_2^n set of vector os length n, where the elements belongs to F_2" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:39:19.563", "Id": "269187", "Score": "3", "Tags": [ "python", "performance", "numpy" ], "Title": "Implementation of a crypto formula in Python" }
269187
<p>I used recursion to generate fractal and got the desired result but I think my code can be better</p> <p>I started using MATLAB a few days ago and since than trying and learning new things.<br> Now this code generates the fractal exactly as I wanted but I feel like it can a little bit neater.<br> Any suggestions are welcome (even off topic but related to how to use MATLAB) as I am a beginner in MATLAB, they will definitely help me in future.</p> <pre><code>hold on x=[0 1 1/2]; %Coordinates of a equilateral triangle fill(x,y,'k'); axis equal axis off abc(list) function abc(listnew) if abs(listnew(1,1)-listnew(1,2))&gt;0.002 listold=listnew; t=size(listold,2)/3; for j=1:t listnew(1,(j-1)*3+1:j*3)=[(listold(1,(j-1)*3+2)+listold(1,(j-1)*3+1))/2 (listold(1,(j-1)*3+3)+listold(1,(j-1)*3+2))/2 (listold(1,(j-1)*3+1)+listold(1,(j-1)*3+3))/2]; listnew(2,(j-1)*3+1:j*3)=[listold(2,(j-1)*3+1) (listold(2,(j-1)*3+3)+listold(2,(j-1)*3+2))/2 (listold(2,(j-1)*3+1)+listold(2,(j-1)*3+3))/2]; end pause(2) tri(listnew); k=size(listnew,2)/3; for m=1:k f=(m-1)*(3^2); l(1,(f+1):(f+3))=[listold(1,(m-1)*3+1) listnew(1,(m-1)*3+1) listnew(1,(m-1)*3+3)]; l(2,(f+1):(f+3))=[listold(2,(m-1)*3+1) listnew(2,(m-1)*3+1) listnew(2,(m-1)*3+3)]; l(1,(f+4):(f+6))=[listnew(1,(m-1)*3+1) listold(1,(m-1)*3+2) listnew(1,(m-1)*3+2)]; l(2,(f+4):(f+6))=[listnew(2,(m-1)*3+1) listold(2,(m-1)*3+2) listnew(2,(m-1)*3+2)]; l(1,(f+7):(f+9))=[listnew(1,(m-1)*3+3) listnew(1,(m-1)*3+2) listold(1,(m-1)*3+3)]; l(2,(f+7):(f+9))=[listnew(2,(m-1)*3+3) listnew(2,(m-1)*3+2) listold(2,(m-1)*3+3)]; end abc(l); end end function tri(list) for i =1:(size(list,2)/3) fill(list(1,(i-1)*3+1:i*3),list(2,(i-1)*3+1:i*3),'w'); end end </code></pre>
[]
[ { "body": "<p>Though MATLAB allows to expand the size of a matrix by assigning to elements outside its bounds, it is always best to <a href=\"https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html\" rel=\"nofollow noreferrer\">preallocate</a> the array to its final size.</p>\n<p>The <code>for m=1:k</code> loop has a lot of repeated code. First, <code>m</code> is always used as <code>m-1</code>. You could instead do <code>for m=0:k-1</code> and simplify the code a bit. Next,</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>l(1,(f+1):(f+3))=[listold(1,(m-1)*3+1) listnew(1,(m-1)*3+1) listnew(1,(m-1)*3+3)];\n</code></pre>\n<p>can be written as</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>l(1,(f+1):(f+3)) = listold(1,(m-1)*3+[1,1,3]);\n</code></pre>\n<p>and you do the same for both elements along the 1 dimension, which can be written as</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>l(:,(f+1):(f+3)) = listold(:,(m-1)*3+[1,1,3]);\n</code></pre>\n<p>All 6 statements in this loop can be summarized as</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>l(:,(f+1):(f+9)) = listold(:,(m-1)*3+[1,1,3,1,2,2,3,2,3]);\n</code></pre>\n<p>It is possible to replace the whole loop, but that just makes the code less readable, I don’t recommend it.</p>\n<p>It is common in MATLAB code to not use spaces, but I think code is more readable with spaces in it. Especially around the <code>=</code> assignment operator. In any case, make sure you use consistent spacing, <code>for i =1:(size(list,2)/3)</code> is rather unsettling to me. ;)</p>\n<p>Likewise, be consistent with indentation. The loop <code>for j=1:t</code> is not indented.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T08:15:45.667", "Id": "532783", "Score": "0", "body": "Thanks. I will take notes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T15:53:09.397", "Id": "269336", "ParentId": "269188", "Score": "1" } } ]
{ "AcceptedAnswerId": "269336", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T13:42:02.337", "Id": "269188", "Score": "2", "Tags": [ "performance", "recursion", "matlab", "fractals" ], "Title": "Recursion to generate fractal" }
269188
<p>So I've decided to practice I will turn all my scripts etc into GUI apps. So my 36 loc guess the number game turned into 136 loc. It's not the best looking, but it does work and on hard it's actually hard to beat computer sometimes. What are your thoughts guys? After finishing it I am not sure if my approach was right. Thank you for any comments and advice. No offence if they will be harsh ;)</p> <p><a href="https://i.stack.imgur.com/LGE4H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGE4H.png" alt="screenshot" /></a></p> <pre><code>import math import tkinter as tk import random from tkinter import Frame, PhotoImage, Radiobutton, StringVar, ttk from typing import Any from math import ceil class Game(tk.Tk): def __init__(self) -&gt; None: super().__init__() self.geometry('400x440+400+300') self.title('Guess The Number') self.iconphoto(True, PhotoImage(file='icon.png')) self.level_var = StringVar(value='medium') self.player_var = StringVar(value='Player') self.number_var = StringVar(value='0') self.player_attempts = 0 self.computer_attempts = 0 self.turn = StringVar(value='0') self.winner = '' self.switch_frame(StartFrame) def switch_frame(self, frameClass: Any) -&gt; None: new_frame: Frame = frameClass(self) self._frame = new_frame self._frame.place(x=0, y=0, width=400, height=440) # function to ensure user input is actually a number nothing else. def is_number(self, valueToCheck: str) -&gt; int: try: return int(valueToCheck) except ValueError: return 0 # difficulty level scope def game_level(self, level: str) -&gt; int: if level == 'low': return 10 elif level == 'medium': return 100 else: return 1000 def new_game(self) -&gt; None: self.player_attempts = 0 self.computer_attempts = 0 self.turn.set('0') self.winner = '' class StartFrame(tk.Frame): def __init__(self, master: Game) -&gt; None: tk.Frame.__init__(self, master) tk.Frame.configure(self, bg='#9aaeb6') main_font = ('Arial', 12, 'bold') secondary_font = ('Arial', 10) main_label = ttk.Label(self, text='Game Settings', anchor='center', background='#eee', font=main_font) main_label.place(x=10, y=10, width=380, height=30) level_label = ttk.Label(self, text='Difficulty Level', anchor='center', background='#eee', font=secondary_font) level_label.place(x=10, y=70, width=380, height=30) level_1 = Radiobutton(self, text='Low', variable=master.level_var, value='low') level_1.place(x=50, y=110, height=30, width=80) level_2 = Radiobutton(self, text='Medium', variable=master.level_var, value='medium') level_2.place(x=160, y=110, height=30, width=80) level_3 = Radiobutton(self, text='Hard', variable=master.level_var, value='hard') level_3.place(x=270, y=110, height=30, width=80) player_label = ttk.Label(self, text='Who will start the game? You or Computer?', anchor='center', background='#eee', font=secondary_font) player_label.place(x=10, y=150, width=380, height=30) player_1 = Radiobutton(self, text='Player', variable=master.player_var, value='Player') player_1.place(x=100, y=190, height=30, width=80) player_2 = Radiobutton(self, text='Computer', variable=master.player_var, value='Computer') player_2.place(x=220, y=190, height=30, width=80) number_label = ttk.Label(self, text='What is your secret number?', anchor='center', background='#eee', font=secondary_font) number_label.place(x=10, y=230, width=380, height=30) number_entry = ttk.Entry(self, textvariable=master.number_var, justify='center') number_entry.place(x=100, y=270, width=200, height=40) play_button = ttk.Button(self, text='PLAY', command=lambda: master.switch_frame(GameFrame)) play_button.place(x=100, y=350, width=200, height=60) class GameFrame(tk.Frame): def __init__(self, master: Game) -&gt; None: tk.Frame.__init__(self, master) tk.Frame.configure(self, bg='#9aaeb6') main_font = ('Arial', 12, 'bold') secondary_font = ('Arial', 10) self.com_out = StringVar(value='Let\'s start.') if master.player_var.get() == 'Computer': master.turn.set('1') self.player_secret_number = master.is_number(master.number_var.get()) game_lvl = master.game_level(master.level_var.get()) self.computer_secret_number = random.randint(0, game_lvl) self.computer_low = 0 self.computer_high = game_lvl # ensure player number can't be higher than choosen difficulty lvl scope if self.player_secret_number &gt; game_lvl: self.player_secret_number = random.randint(0, game_lvl) main_label = ttk.Label(self, text='Game Time', anchor='center', background='#eee', font=main_font) main_label.place(x=10, y=10, width=380, height=30) turn_label = ttk.Label(self, text='Turn:', anchor='center', background='#eee', font=main_font) turn_label.place(x=10, y=60, width=190, height=30) self.turn_display = StringVar(value='1') turn_label_val = ttk.Label(self, textvariable=self.turn_display, anchor='center', background='#eee', font=main_font) turn_label_val.place(x=200, y=60, width=190, height=30) player_label = ttk.Label(self, text='Player', anchor='center', background='#eee', font=main_font) player_label.place(x=50, y=105, width=100, height=30) computer_label = ttk.Label(self, text='Computer', anchor='center', background='#eee', font=main_font) computer_label.place(x=250, y=105, width=100, height=30) command_out = ttk.Label(self, textvariable=self.com_out, anchor='center', font=secondary_font) command_out.place(x=115, y=180, height=40, width=180) self.player_guess = StringVar() player_guess_entry = ttk.Entry(self, textvariable=self.player_guess, justify='center', font=main_font) player_guess_entry.place(x=160, y=250, height=40, width=90) guess_button = ttk.Button(self, text='Guess', command=lambda: self.play(master=master)) guess_button.place(x=160, y=300, height=60, width=90) def play(self, master: Game) -&gt; None: if int(master.turn.get()) % 2 != 0: computer_choice = random.randint(self.computer_low, self.computer_high) if computer_choice == self.player_secret_number: master.winner = 'computer' master.switch_frame(WinnerFrame) else: if computer_choice &gt; self.player_secret_number: self.computer_high = computer_choice else: self.computer_low = computer_choice master.computer_attempts += 1 master.turn.set(str(int((master.turn.get())) + 1)) self.turn_display.set(str(math.ceil(int(master.turn.get()) / 2))) else: try: player_choice = int(self.player_guess.get()) if player_choice == self.computer_secret_number: master.winner = 'player' master.switch_frame(WinnerFrame) else: if player_choice &gt; self.computer_secret_number: self.com_out.set('Number too high.') else: self.com_out.set('Number too low.') except ValueError: pass master.player_attempts += 1 master.turn.set(str(int((master.turn.get())) + 1)) self.player_guess.set('0') self.turn_display.set(str(math.ceil(int(master.turn.get()) / 2))) self.play(master) class WinnerFrame(tk.Frame): def __init__(self, master: Game) -&gt; None: tk.Frame.__init__(self, master) main_font = ('Arial', 12, 'bold') def winner_looser(): if master.winner == 'computer': return 'red' else: return 'green' self.configure(background=winner_looser()) main_label = ttk.Label(self, text='Do you want to play again?', anchor='center', background='#eee', font=main_font) main_label.place(x=10, y=120, width=380, height=30) yes_button = ttk.Button(self, text='YES', command=lambda: [master.switch_frame(StartFrame), master.new_game()]) yes_button.place(x=100, y=180, width=90, height=70) no_button = ttk.Button(self, text='NO', command=master.destroy) no_button.place(x=200, y=180, width=90, height=70) def attempt_result() -&gt; str: if master.winner == 'computer': return f'{master.computer_attempts} moves for Computer to beat you.' else: return f'{master.player_attempts} moves, all you needed to win.' result_label = ttk.Label(self, text=attempt_result(), anchor='center') result_label.place(x=10, y=270, width=380) if __name__ == '__main__': Game().mainloop() </code></pre>
[]
[ { "body": "<ul>\n<li>You're not using <code>math</code>, so delete that import</li>\n<li><code>is_number</code> has nothing to do with the class, so move it to global scope. Also, this can be simplified with <code>str.isnumeric</code> if the function did what it's named to do. However, it <em>doesn't</em> do what it's named to do - it doesn't check whether a string is numeric; it attempts to parse an integer; so a more appropriate name would be <code>try_parse_int</code>. Finally: returning 0 on failure is not a good idea. What if <code>valueToCheck</code> (which should be <code>value_to_check</code>) is itself <code>'0'</code>? How can you distinguish between that and a failure?</li>\n<li>It's unlikely that <code>StartFrame</code> should exist as a class. It has no members, doesn't access the members of its parent, and doesn't override anything. It can just be a function. Better, keep it and others as classes, but don't inherit; instantiate the frame or window as appropriate (&quot;has-a&quot;, not &quot;is-a&quot;).</li>\n<li><code>'Let\\'s start.'</code> would not require an escape if enclosed in double quotes.</li>\n<li><code>GameFrame</code> has poor separation of concerns and bakes in a bunch of game logic when all it should do is display.</li>\n<li>Typo: <code>looser</code> -&gt; <code>loser</code></li>\n<li><code>attempt_result</code> is missing a <code>self</code>, and refers to a <code>master</code> variable that's undefined. The initialization of <code>result_label</code> is done in the static namespace, which is not appropriate.</li>\n<li>Consider representing player state in a class - one for both the user and computer - and differentiating behaviour using polymorphism. This is not the only way to do things, but it's one way.</li>\n<li>You only have <code>StringVar</code>s. Sometimes <code>IntVar</code> or <code>BooleanVar</code> are called for.</li>\n<li>You can simplify your difficulty logic by using <code>10**x</code> where <code>x</code> is a difficulty between 1 and 3.</li>\n<li>Move your main and secondary fonts to global constants for reuse.</li>\n<li>Many of the declarations that you make for <code>tk</code> variables don't actually need to keep references, locally or otherwise.</li>\n<li>If you want your computer to be harder to beat, call into <code>bisect</code>.</li>\n<li>Consider using a spinbox instead of an unconstrained entry box for the guess, so that lower and upper limits are automatically enforced.</li>\n<li>Consider telling the user what their minimum and maximum guess is permitted to be.</li>\n<li>For quality of life, after the user has clicked the <code>Guess</code> button, re-select the guess entry. I haven't shown this below.</li>\n<li>You have a mix of qualified and de-qualified <code>tk</code> imports. Choose one (probably the qualified version with no <code>from</code>).</li>\n<li>Don't repeat your geometric references (the 400 pixels) - instead, you can format the geometry string based on integer members of your view class.</li>\n<li>Give an owner and <code>name=</code> to all of your <code>Var</code> instances.</li>\n<li>Where possible, <a href=\"https://www.theserverside.com/feature/Why-GitHub-renamed-its-master-branch-to-main\" rel=\"nofollow noreferrer\">avoid writing &quot;master&quot;</a>.</li>\n</ul>\n<h2>Suggested</h2>\n<p>I messed around with coroutines a little (see <code>blocked_on_user_coro</code>) - they're a convenient way to &quot;pause&quot; code, for example when waiting for player input. This also relies on function reference hooks to enforce loose coupling.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import tkinter as tk\nimport random\nfrom itertools import count\nfrom tkinter import ttk\nfrom typing import Callable, Optional, ClassVar, Tuple\n\nMAIN_FONT = ('Arial', 12, 'bold')\nSECONDARY_FONT = ('Arial', 10)\n\n\nclass Player:\n NAME: ClassVar[str]\n INTERACTIVE: ClassVar[bool]\n WIN_SUFFIX: ClassVar[str]\n\n def __init__(self, secret: int) -&gt; None:\n self.attempts = 0\n # The secret the player is guessing about, not the secret the other\n # player has chosen\n self.secret = secret\n\n def play(self) -&gt; int:\n self.attempts += 1\n guess = self.guess()\n delta = guess - self.secret\n self.strategise(guess, delta)\n return delta\n\n def guess(self) -&gt; int:\n raise NotImplementedError()\n\n def strategise(self, guess: int, delta: int) -&gt; None:\n pass\n\n @property\n def result(self) -&gt; str:\n return f'{self.attempts}{self.WIN_SUFFIX}'\n\n\nclass User(Player):\n INTERACTIVE = True\n NAME = 'Player'\n WIN_SUFFIX = ' moves, all you needed to win.'\n\n def __init__(self, max_number: int, get_guess: Callable[[], int]):\n super().__init__(secret=random.randrange(max_number))\n self.guess = get_guess\n\n\nclass Computer(Player):\n INTERACTIVE = False\n NAME = 'Computer'\n WIN_SUFFIX = ' moves for Computer to beat you.'\n\n def __init__(self, max_number: int, secret: int) -&gt; None:\n super().__init__(secret)\n self.lower, self.upper = 0, max_number\n\n def guess(self) -&gt; int:\n guess = random.randrange(start=self.lower, stop=self.upper)\n # print(f'{self.NAME}: {self.lower} &lt;= {guess} &lt; {self.upper}')\n return guess\n\n def strategise(self, guess: int, delta: int) -&gt; None:\n if delta &gt; 0: # too high\n self.upper = guess\n elif delta &lt; 0: # too low\n self.lower = guess\n\n\nclass Game:\n def __init__(\n self, max_number: int, user_secret: int, user_goes_first: bool,\n parent: tk.Tk, win_hook: Callable[[Player], None],\n ) -&gt; None:\n self.view = GameView(parent, max_number, self.user_played)\n self.players: Tuple[Player, ...] = (\n User(max_number=max_number, get_guess=self.view.player_guess_var.get),\n Computer(max_number=max_number, secret=user_secret),\n )\n if not user_goes_first:\n self.players = self.players[::-1]\n self.win_hook = win_hook\n self.blocked_on_user = None\n\n def start(self) -&gt; None:\n self.blocked_on_user = self.blocked_on_user_coro()\n self.user_played()\n\n def user_played(self) -&gt; None:\n try:\n next(self.blocked_on_user)\n except StopIteration:\n pass\n\n def blocked_on_user_coro(self):\n for turn_index in count():\n self.view.show_turn(turn_index)\n\n for player in self.players:\n if player.INTERACTIVE:\n yield # wait for a user to play\n if self.do_turn(player):\n return\n\n def do_turn(self, player: Player) -&gt; bool:\n delta = player.play()\n if delta == 0:\n self.win_hook(player)\n return True\n\n if player.INTERACTIVE:\n if delta &lt; 0:\n desc = 'low'\n else:\n desc = 'high'\n self.view.show_command(f'Number too {desc}.')\n return False\n\n\nclass GameProgram:\n def __init__(self):\n self.parent_view = ParentView()\n\n def run(self) -&gt; None:\n def play():\n game = Game(\n max_number=start_view.max_number,\n user_secret=start_view.number_var.get(),\n user_goes_first=start_view.player_goes_first_var.get(),\n parent=self.parent_view.window,\n win_hook=self.win,\n )\n self.parent_view.switch_frame(game.view.frame)\n game.start()\n\n start_view = StartView(self.parent_view.window, play)\n self.parent_view.switch_frame(start_view.frame)\n self.parent_view.window.mainloop()\n\n def win(self, winner: Player) -&gt; None:\n winner_view = WinnerView(\n parent=self.parent_view.window,\n user_won=winner.INTERACTIVE,\n result=winner.result,\n restart_hook=self.run,\n )\n self.parent_view.switch_frame(winner_view.frame)\n\n\nclass ParentView:\n def __init__(self) -&gt; None:\n self.window = tk.Tk()\n self.width = 400\n self.height = 440\n self.window.geometry(f'{self.width}x{self.height}+400+300')\n self.window.title('Guess The Number')\n # self.parent.iconphoto(True, PhotoImage(file='icon.png'))\n\n self.child: Optional[tk.Frame] = None\n\n def switch_frame(self, child: tk.Frame) -&gt; None:\n if self.child is not None:\n self.child.destroy()\n\n child.place(\n x=0, width=self.width,\n y=0, height=self.height,\n )\n self.child = child\n\n\nclass StartView:\n def __init__(self, parent: tk.Tk, done_hook: Callable[[], None]):\n self.frame = tk.Frame(parent, background='#9aaeb6')\n\n self.level_var = tk.IntVar(self.frame, name='level', value=1)\n self.player_goes_first_var = tk.BooleanVar(self.frame, name='player_goes_first', value=True)\n self.number_var = tk.IntVar(self.frame, name='number', value=0)\n\n ttk.Label(\n self.frame, text='Game Settings', anchor='center',\n background='#eee', font=MAIN_FONT,\n ).place(x=10, y=10, width=380, height=30)\n\n ttk.Label(\n self.frame, text='Difficulty Level', anchor='center',\n background='#eee', font=SECONDARY_FONT,\n ).place(x=10, y=70, width=380, height=30)\n tk.Radiobutton(\n self.frame, text='Low', variable=self.level_var, value=1,\n ).place(x=50, y=110, height=30, width=80)\n tk.Radiobutton(\n self.frame, text='Medium', variable=self.level_var, value=2,\n ).place(x=160, y=110, height=30, width=80)\n tk.Radiobutton(\n self.frame, text='Hard', variable=self.level_var, value=3,\n ).place(x=270, y=110, height=30, width=80)\n\n ttk.Label(\n self.frame, text='Who will start the game? You or Computer?',\n anchor='center', background='#eee', font=SECONDARY_FONT,\n ).place(x=10, y=150, width=380, height=30)\n tk.Radiobutton(\n self.frame, text='Player', variable=self.player_goes_first_var, value=True,\n ).place(x=100, y=190, height=30, width=80)\n tk.Radiobutton(\n self.frame, text='Computer', variable=self.player_goes_first_var, value=False,\n ).place(x=220, y=190, height=30, width=80)\n\n ttk.Label(\n self.frame, text='What is your secret number?', anchor='center',\n background='#eee', font=SECONDARY_FONT,\n ).place(x=10, y=230, width=380, height=30)\n\n ttk.Entry(\n self.frame, textvariable=self.number_var, justify='center',\n ).place(x=100, y=270, width=200, height=40)\n\n ttk.Button(\n self.frame, text='PLAY', command=self.play,\n ).place(x=100, y=350, width=200, height=60)\n\n self.done_hook = done_hook\n\n @property\n def max_number(self) -&gt; int:\n return 10**self.level_var.get()\n\n @property\n def is_valid(self) -&gt; bool:\n try:\n return 0 &lt;= self.number_var.get() &lt; self.max_number\n except tk.TclError:\n return False\n\n def play(self) -&gt; None:\n if self.is_valid:\n self.done_hook()\n\n\nclass GameView:\n def __init__(self, parent: tk.Tk, max_number: int, play_hook: Callable[[], None]) -&gt; None:\n self.frame = tk.Frame(parent, background='#9aaeb6')\n\n self.make_label(text='Game Time').place(x=10, y=10, width=380, height=30)\n\n self.turn_var = tk.IntVar(self.frame, name='turn', value=0)\n self.make_label(text='Turn:').place(x=10, y=60, width=190, height=30)\n self.make_label(textvariable=self.turn_var).place(x=200, y=60, width=190, height=30)\n\n self.make_label(text='Player').place(x=50, y=105, width=100, height=30)\n self.make_label(text='Computer').place(x=250, y=105, width=100, height=30)\n\n self.command_var = tk.StringVar(self.frame, name='command', value=&quot;Let's start.&quot;)\n self.make_label(\n textvariable=self.command_var, font=SECONDARY_FONT,\n ).place(x=115, y=180, height=40, width=180)\n\n self.player_guess_var = tk.IntVar(self.frame, name='player_guess')\n ttk.Spinbox(\n self.frame, justify='center', font=MAIN_FONT,\n textvariable=self.player_guess_var, from_=0, to=max_number-1,\n ).place(x=160, y=250, height=40, width=90)\n\n ttk.Button(\n self.frame, text='Guess', command=play_hook,\n ).place(x=160, y=300, height=60, width=90)\n\n def show_command(self, command: str) -&gt; None:\n self.command_var.set(command)\n\n def show_turn(self, index: int) -&gt; None:\n self.turn_var.set(index)\n\n def make_label(self, **kwargs) -&gt; tk.Label:\n label_kwargs = {\n 'master': self.frame,\n 'anchor': 'center',\n 'background': '#eee',\n 'font': MAIN_FONT,\n **kwargs,\n }\n return ttk.Label(**label_kwargs)\n\n\nclass WinnerView:\n def __init__(\n self, parent: tk.Tk, user_won: bool, result: str, restart_hook: Callable[[], None],\n ) -&gt; None:\n background = 'green' if user_won else 'red'\n self.frame = tk.Frame(parent, background=background)\n\n ttk.Label(\n self.frame, text='Do you want to play again?',\n anchor='center', background='#eee', font=MAIN_FONT,\n ).place(x=10, y=120, width=380, height=30)\n\n ttk.Button(self.frame, text='YES', command=restart_hook,).place(x=100, y=180, width=90, height=70)\n ttk.Button(self.frame, text='NO', command=parent.destroy).place(x=200, y=180, width=90, height=70)\n ttk.Label(self.frame, text=result, anchor='center').place(x=10, y=270, width=380)\n\n\nif __name__ == '__main__':\n GameProgram().run()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T19:58:15.420", "Id": "531079", "Score": "1", "body": "Thank you very much for your review. Corrected typo and removed math straight away." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T19:09:37.343", "Id": "269209", "ParentId": "269193", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:18:16.580", "Id": "269193", "Score": "1", "Tags": [ "python", "beginner", "game", "tkinter", "number-guessing-game" ], "Title": "Guess The Number Game with GUI" }
269193
<p>I was struggling to make the RadioButtons widget look presentable. Either the circles were not round, or the frame had a totally wrong shape, or both (see pictures below, and also <a href="https://stackoverflow.com/questions/66510212/how-to-place-widgets-axes-with-equal-aspect-and-requested-size">this question on SO</a>). So I had created a function that draws a reasonably good-looking one. It works (I have tested for the different number of options, font sizes, and canvas sizes), but feels very manual, there are some constants that I cannot make sense of (but it works!) Any comments welcome.</p> <p>How it looks now <a href="https://i.stack.imgur.com/UelOt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UelOt.png" alt="enter image description here" /></a></p> <p>How it looked before</p> <p><a href="https://i.stack.imgur.com/od9Ig.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/od9Ig.png" alt="enter image description here" /></a></p> <p>My code</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons #left, bottom = rax_left, 0 def place_ratiobuttons(options, font_size, left, bottom, bg_color, frame_zorder=-.5, active_option=0): fig = plt.gcf() figure_width_height_ratio = fig.get_size_inches()[0] / fig.get_size_inches()[1] renderer = plt.gcf().canvas.get_renderer() size_ax = len(options) * font_size / 200 * (figure_width_height_ratio if figure_width_height_ratio &lt; 1 else 1) frame_location = [left, bottom , size_ax/figure_width_height_ratio, size_ax] axes_ = plt.axes(frame_location) rb = RadioButtons(axes_, options, active=active_option) all_widgets.append(rb) for circle in rb.circles: # adjust radius here. The default is 0.05 circle.set_radius(0.2/len(options)) inverted_rb_axes = rb.ax.transData.inverted() max_x1 = 0 for label_ in rb.labels: # adjust radius here. The default is 0.05 label_bbox = label_.get_window_extent(renderer=renderer).transformed(inverted_rb_axes) max_x1 = max(max_x1, label_bbox.x1) max_x1 += font_size / 100 max_x1 *= size_ax / figure_width_height_ratio axes_.set_frame_on(False) new_frame = plt.Rectangle(xy=frame_location[:2], width=max_x1, height=size_ax, ec='black', linewidth=plt.rcParams['axes.linewidth'], color=bg_color, zorder=frame_zorder, transform=fig.transFigure, figure=fig) fig.patches += [new_frame] return rb, new_frame font_size = 20 plt.rcParams.update({'font.size': font_size}) rb_options = [''.join(['M'*(k+3)])+str(k) for k in range(20)] all_widgets = [] fig = plt.figure(figsize=(15, 8), dpi=50) rax_left = .05 for c_, bg_color in enumerate(['cyan', 'pink', 'aliceblue']): rb, new_frame = place_ratiobuttons(options=rb_options[:c_*2+3], font_size=font_size, left=rax_left, bottom=0, bg_color=bg_color, frame_zorder=-.5, active_option=0) rax_left += new_frame.get_width() + .05 plt.show() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:44:48.717", "Id": "531048", "Score": "1", "body": "Are you constrained to using Matplotlib for a UI? This doesn't seem very practical. I would stick to using Matplotlib for plots and something else (tkinter, etc.) for UI. Are there constraints preventing this approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:00:58.657", "Id": "531051", "Score": "0", "body": "It has to work in a web-based GUI replit.com, I am not sure if I can use tkinter there, but I will look into this, thanks for the tip!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T15:04:07.010", "Id": "531054", "Score": "0", "body": "@Reinderien I have to have the button and the graph on the same figure, this is definitely a constraint!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T17:31:59.747", "Id": "531071", "Score": "0", "body": "Can you link to the applicable repl.it entry?" } ]
[ { "body": "<ul>\n<li>Use four-space indentation instead of two</li>\n<li>Try not to rely on <code>gcf</code>. Pass around figures explicitly.</li>\n<li>Unpack the return of <code>get_size_inches</code> to a width and a height rather than using indexing.</li>\n<li>Replace your ternary with a call to <code>min</code>.</li>\n<li>Why are you underscore-suffixing some variable names? This does not seem necessary.</li>\n<li>Your <code>for</code>-loop calculating <code>max_x1</code> can be replaced with one call to <code>max</code> using a generator.</li>\n<li>Add type hints.</li>\n<li>Move your global code into functions. One side-effect is that <code>all_widgets</code> will no longer be in the global namespace. You can instead form this from the return of a generator function.</li>\n<li>Rather than creating a list literal and using the <code>+=</code> operator, you can just call <code>.append</code> on <code>patches</code>.</li>\n<li>This:</li>\n</ul>\n<pre><code>''.join(['M'*(k+3)])+str(k) \n</code></pre>\n<p>doesn't work quite the way you think it does. Using the multiplication operator on a string returns a string already, so <code>join</code> is not needed.</p>\n<ul>\n<li>For your background colours, prefer an immutable tuple instead of a list.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Collection, Tuple, Iterable\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.widgets import RadioButtons\n\n\ndef place_ratiobuttons(\n fig: Figure,\n options: Collection[str],\n font_size: int,\n left: float,\n bottom: float,\n bg_color: str,\n frame_zorder: float = -.5,\n active_option: int = 0,\n) -&gt; Tuple[RadioButtons, Rectangle]:\n width, height = fig.get_size_inches()\n figure_width_height_ratio = width / height\n size_ax = len(options) * font_size / 200 * min(1, figure_width_height_ratio)\n frame_location = [left, bottom, size_ax/figure_width_height_ratio, size_ax]\n\n axes = fig.add_axes(rect=frame_location)\n axes.set_frame_on(False)\n rb = RadioButtons(axes, options, active=active_option)\n\n for circle in rb.circles: # adjust radius here. The default is 0.05\n circle.set_radius(0.2/len(options))\n\n inverted_rb_axes = rb.ax.transData.inverted()\n renderer = fig.canvas.get_renderer()\n\n max_x1 = max(\n label\n .get_window_extent(renderer=renderer)\n .transformed(inverted_rb_axes)\n .x1\n for label in rb.labels\n )\n max_x1 = (max_x1 + font_size/100) * size_ax / figure_width_height_ratio\n\n new_frame = plt.Rectangle(\n xy=frame_location[:2],\n width=max_x1,\n height=size_ax, ec='black', linewidth=plt.rcParams['axes.linewidth'],\n color=bg_color, zorder=frame_zorder, transform=fig.transFigure, figure=fig,\n )\n fig.patches.append(new_frame)\n\n return rb, new_frame\n\n\ndef make_buttons(fig: Figure) -&gt; Iterable[RadioButtons]:\n font_size = 20\n plt.rcParams.update({'font.size': font_size})\n\n rb_options = [\n 'M'*(k + 3) + str(k)\n for k in range(20)\n ]\n rax_left = .05\n\n for c_index, bg_color in enumerate(('cyan', 'pink', 'aliceblue')):\n rb, new_frame = place_ratiobuttons(\n fig=fig,\n options=rb_options[:c_index*2 + 3],\n font_size=font_size,\n left=rax_left,\n bottom=0,\n bg_color=bg_color,\n )\n yield rb\n rax_left += new_frame.get_width() + .05\n\n\ndef main() -&gt; None:\n fig = plt.figure(figsize=(15, 8), dpi=50)\n all_widgets = list(make_buttons(fig))\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T18:27:23.340", "Id": "269205", "ParentId": "269197", "Score": "1" } } ]
{ "AcceptedAnswerId": "269205", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T14:32:17.783", "Id": "269197", "Score": "2", "Tags": [ "python", "matplotlib", "widget" ], "Title": "RadioButtons with round circles" }
269197